Is there a way to remember the old DOM or state when navigating between pages with Python and Selenium webdriver?

Question: I have a list of courses on page A, after clicking edit for a course it takes me to page B where I perform certain actions. When clicking save and return it brings me back to page A where I want to click and edit the following item on the list. The problem is I lose the DOM or state (not sure how to reference it) of the previous item on the list, this causes my loop to break without going to the next item and performing the necessary actions.
#iterate backup ul with each year and faculty
lists = ['2018-1','2017-1','2017-2','2016-2','2016-3']
faculties = ['FEA','FMSS','FNAHSW','FST','ODL']
for link_text in lists:
    link = driver.find_element_by_link_text(link_text)
    link.click()
    time.sleep(1)
    for facs in faculties:
        link = driver.find_element_by_link_text(facs)
        link.click()
        #check to see if faculties have courses
        if driver.find_element_by_class_name('dimmed').text != 0:
            #traverse course list
            resultSet = driver.find_element_by_class_name('course-list')
            options = resultSet.find_elements_by_tag_name("li")
            #traverse and click each edit course button
            for option in options:
                time.sleep(3)
                option.find_element_by_class_name('action-edit').click()
                #inside edit page
                #convert to CAPS
                Inputelement = driver.find_element_by_id('id_fullname')
                time.sleep(1)
                String = Inputelement.get_attribute('value')
                time.sleep(1)
                Inputelement.send_keys(Keys.CONTROL + "a")
                Inputelement.send_keys(Keys.DELETE)
                time.sleep(1)
                Inputelement.send_keys(String.upper())
                #save and return
                driver.find_element_by_id('id_saveandreturn').click()

        else:
            print ('List has no courses')
        time.sleep(1)

Comment: couldn't you just store them as strings in a list or something?
Answer: Welcome to SO. I would recommend using the index in each iteration rather trying to access the previously stored elements. If you are referring to the options in Original Post(OP) then change the options list to as below.
# Get the number of options
options = driver.find_elements_by_xpath("//*[@class='course-list']/li")
# iterate through each option
for optionCounter in range(len(options)):
    # get the option here based on index
    option = driver.find_element_by_xpath("(//*[@class='course-list']/li)[" + str(optionCounter) + "]")
    # continue working with option from here


Cocoapods: how to create a pod using the latest Swift version?

Question: I am learning how to create a pod using Cocoapods, so I ran this command:
pod lib create {my_pod_name}

Using iOS platform, Swift language, including a demo application in my library, and not using any testing framework nor view based testing.
However, when opening the project, I'm getting the warning:

Conversion to Swift 4.2 is available

That's what I see in the build settings:

So why is this happening?
Thanks for your help!
Comment: Show your podspec. If you haven't done that already, add the line `s.swift_version = '4.2'` to it (assuming `s` is your spec)
Comment: What's your current cocoapod version? I think the current cocoapod create a Xcode 9 project instead of Xcode 10, so that's why it's using Swift 4.0 by default (see here: https://useyourloaf.com/blog/upgrading-to-swift-4.2/)
Comment: Thanks for your answer, but my question was more like: what is actually deciding when I first create a pod that the default Swift version if 4.0 ?
Answer: If I understood your question correctly, the Swift version is dictated by the Podspec.
In more details, it would look like:
Pod::Spec.new do |spec|
  ...
  spec.swift_version = '4.2'
  ...
end

I assume that if this is left out, that it currently defaults to 4.0.
If you want to go more into detail, check the source:
# @return [String] the Swift version for the target. If the pod author has provided a set of Swift versions
#         supported by their pod then the max Swift version across all of target definitions is chosen, unless
#         a target definition specifies explicit requirements for supported Swift versions. Otherwise the Swift
#         version is derived by the target definitions that integrate this pod as long as they are the same.
#
def swift_version
  @swift_version ||= begin
    if spec_swift_versions.empty?
      target_definitions.map(&:swift_version).compact.uniq.first
    else
      spec_swift_versions.sort.reverse_each.find do |swift_version|
        target_definitions.all? do |td|
          td.supports_swift_version?(swift_version)
        end
      end.to_s
    end
  end
end

Comment: Thank you for your answer.
Yes, I understand that I can select the `swift_version` by specifying it into the `podspec`, but what I want to know is what decides that the default `swift_version` is 4.0 if not specified in the `podspec` ?
Comment: You can check the version implementation in the source: https://github.com/CocoaPods/CocoaPods/blob/master/lib/cocoapods/target/pod_target.rb


phpmyadmin login error 1045, need help fixing

Question: i am currently setting up an old computer as a server and i am at the webserver part, but i currently have a problem where phpmyadmin wont let me login (at least from my main computer on the same network), it throws out error #1045. I currently have no way of testing a login directly from the computer but i need to be able to login from other comptuers on my network.
Anyone know a possible fix ?
Note: ive already tried to reset the mysql account passwords
all the errors
Comment: Does this answer your question? [PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client](https://stackoverflow.com/questions/52364415/php-with-mysql-8-0-error-the-server-requested-authentication-method-unknown-to)
Answer: Which phpMyAdmin, PHP, and MySQL versions are you using? This is most likely a version incompatibility with MySQL and PHP; when using MySQL 8.0 or newer you'll need PHP 7.4 or newer, this error message suggests that your PHP installation is older than that. The best solution is to upgrade your PHP to 7.4 or newer. Which operating system does the server use and how have you installed PHP (using the package manager, manually compiling, using some prebuilt kit, etc)?
You could also see https://docs.phpmyadmin.net/en/latest/faq.html#i-get-an-error-message-about-unknown-authentication-method-caching-sha2-password-when-trying-to-log-in for more details.


Completeness of an FO theory with a single model

Question: Prove or disprove:
If some FO theory $T$ has only one infinite model up to isomorphism (of cardinality $n$) , then T is complete.
Answer: This is false. Consider $L$ with only equality.
Let $T= \{(\exists x)(x=x)\}$. Now, for any infinite $\kappa$ there is exactly one model up to isomorphism. However, this theory is incomplete since $T\not \models$ "There exists at least  2 elements" and $T \not \models \neg$ "There exists at least 2 elements".
Now, if you expand your assumptions and also assume $T$ has no finite models, then yes, your statement holds (this result is known as the Łoś–Vaught test).
Comment: Would someone like to explain their down vote?


Cannot insert data into many-to-many relations in asp.net using LINQ

Question: I am developing a asp.net web api with angularjs project. My project is actually Hybrid Granularity Authentication. There are several tables in my project but there are only three tables that create problem with insertion. Three tables are AspNetRoles, RolePermission and Roles. And their relationship is:

There are three roles in Roles table. Employee, Manager and Admin. When admin changes any Role permission then the old Role permission is removed and a new permission is inserted into AspNetRoles table. However, an error occurs when this operation is executed. The error is:

Violation of PRIMARY KEY constraint 'PK_dbo.AspNetRoles'. Cannot insert duplicate key in object 'dbo.AspNetRoles'. The duplicate key value is (dbc1ae5c-a8a7-4aa9-b62e-0948e6e2856c)

My Code is to remove and update permission
public void SaveUpdateRolePermission(RoleWisePermission rolePermissionList)
    {
        var RoleObject = db.Roles.Where(s => s.Id == rolePermissionList.RoleId).FirstOrDefault();

        if (RoleObject.AspNetRoles.Any())
        {
            foreach (var rolePermission in RoleObject.AspNetRoles.ToList())
            {
                RoleObject.AspNetRoles.Remove(rolePermission);
                db.SaveChanges();
            }
        }

        foreach (AspNetRoles Role in rolePermissionList.PermissionList.Distinct())
        {
            RoleObject.AspNetRoles.Add(Role);
        }

        db.SaveChanges();
        db.Dispose();

    } public class RoleWisePermission
{
    public List<AspNetRoles> PermissionList { get; set; }
    public System.Guid RoleId { get; set; }
}

A problem occurs when db.saveChanges(). Please help me solve this problem.
I already removed all the AspNetRoles related with RoleId. So there is no chance to duplicate ant items. And also remember that the problem is occurred even there is no data in Role Permission table.And i also check the distinct items of rolePermissionList.PermissionList. And if i remove data from Role object for specific Role id and then check that there are any AspNetRoles in Role Permission table that return true. How it possible where there are no data in Role Permission Table. Please help me to solve this problems
Answer: At first glance this looks like it would likely be a case where your roleWisePermissions are not recognized as entities associated with the context. Whenever you are dealing with entities it's important to ensure that all references are set to entities that the context knows about. (Either loaded from that context, or attached to it.)  When a context is given an unknown entity the default behaviour is to attempt to insert it.
RoleObject was loaded from your current instance of the DbContext, however the roleWisePermissionList.AspNetRoles? From your example it isn't clear what the scope of "db" is, and where these entities/objects were populated. The class declaration for RoleWisePermission doesn't look like an entity declaration (No Key declaration, non-virtual collection) unless you are using an EntityTypeConfiguration for it.
With Many-to-Many relationships you generally want to load both applicable collections from the context, set up the replationships, and save. Often the approach I use is to select the entities in one go, then use those references in the association.
I.e.
var apsNetRoleIds = roleWisePermission.PermissionsList.Select(x=>x.PermisionId).ToList();
var aspNetRoles = db.AspNetRoles.Where(x=> aspNetRoleIds.Contains(x=> x.PermissionId);

RoleObject.AspNetRoles.AddRange(aspNetRoles); // Assuming List<>, otherwise, iterate and add.


Remove terms from taxonomy vocabulary for node type

Question: I have two node types that share a taxonomy vocabulary. I'll call them type1 and type2. type2 uses two terms from the vocabulary that type1 does not. Both type1 and type2 have views that allow filtering by the taxonomy terms. I need to have the two terms that type2 uses not show in the view for type1. Any ideas?
[EDIT]
The terms are in a dropdown menu.
Answer: I found an option in the settings for the Views filter called "Limit list to selected items" I checked that and selected all the ones I wanted to show up in the list of terms by the operator settings. That made the ones I didn't want not show up.
Comment: Can you be more specific? Where is this filter?
Comment: It was filter for a view. A taxonomy term filter to be precise. I went to the edit page of the view, clicked on the filter in the filter pane.


Leading asymptotic behaviour about irregular singular point

Question: I am trying to find the leading asymptotic behaviours, using the method of dominant balance, about the irregular singular point $x=0$ for the equation $$x^4\frac{d^2y}{dx^2}+\frac{1}{4}y=0.$$
First let $y=e^{S(x)}, y'= S'e^{S(x)}, y''=[(S')^2+S'']e^{S(x)}$. Our equation then looks like $$x^4[(S')^2+S'']e^{S(x)}+\frac{1}{4}e^{S(x)}=0$$ which implies that $$x^4[(S')^2+S'']=-\frac{1}{4}.$$
We then make the assumption that $S'' << (S')^2$, allowing us to then say $$x^4(S')^2 \sim -\frac{1}{4}.$$
This then implies that $$S' \sim \pm \frac{i}{2x^2} \implies S \sim \mp \frac{i}{2x}.$$
We can see that $S'' \sim \mp \frac{i}{x^3}$ and $(S')^2=-\frac{1}{4x^4}$ which show our assumption to be true as $x \to 0$.
Now we assume that $$S(x) = \frac{i}{2x} + C(x), $$ where $C(x) = o(x^{-1})$.
Sub this into $$ S'' + (S')^2 + \frac{1}{4x^4} = 0 $$ to find $$ \frac{i}{x^3} + C'' -\frac{1}{4x^4}+\frac{i}{x^2}C'+(C')^2
+\frac{1}{4x^4} = 0. $$
After cancelling out and removing small terms we are left with $$ \frac{i}{x^3} + \frac{i}{x^2}C' \sim 0. $$
This then implies that $C \sim -\ln(x)$.
We then have that $$ S(x) = \frac{i}{2x} - \ln(x) + D(x),$$ where $D(x) = o(\ln(x)).$
Sub this into $$ S'' + (S')^2 + \frac{1}{4x^4} = 0 $$ to find $$ \frac{2}{x^2}+\frac{2i}{x^3}-\frac{2D'}{x}-\frac{1}{4x^4}+(D')^2-\frac{iD'}{x^2}+\frac{1}{4x^4}=0.$$
Again we cancel and remove very small terms to find $$\frac{2}{x^2}+\frac{2i}{x^3}-\frac{2D'}{x} \sim 0.$$
This then implies that $D' \sim \frac{1}{x} + \frac{i}{2x}.$
Hence, $D \sim \ln(x) + \frac{i}{2}\ln(x).$
Since this does not tend to $0$ as $x \to 0$ I figured I must continue with the process but the next stage gave me some very questionable results and I realised I didn't really understand what I was looking for or trying to achieve.
Any feedback on current work or clarifications on what I am supposed to be doing would be greatly appreciated.
Answer: You're doing the right thing, but remember that you're interested in the behaviour of $y(x)$ rather than $S(x)$: using your approximation, you should get that
$$
 y(x) = e^{S(x)} = e^{\frac{i}{2x} + \text{ln}(x)} = x\,e^{\frac{i}{2x}},
$$
for which $\lim_{x \to 0} y(x) = 0$. To check your approximations, it might be useful to know that the solutions to the original ODE are given by
$$
 y(x) = x\,e^{\pm \frac{i}{2x}}.
$$
Comment: Thank you for the response, is it not neccessary to include constants in the final solution ?
Comment: Well, yes, that follows from general ODE theory: given two linearly independent solutions to your second order ODE (which are given in the last line of my answer), the general solution can be written as a linear combination of those two independent solutions -- that's where the constants come in.
Answer: First, I think $C \sim \log(x)$ not $-\log(x)$, because in the equation above, we have
$$ \frac{i}{x^3} + C'' -\frac{1}{4x^4} \color{red}{\text{ minus }}  \frac{i}{x^2}C'+(C')^2
+\frac{1}{4x^4} = 0 $$
instead of plus.
Next, let us get the equation for $D$ and as you said. The equation is
$$\big(\color{blue}{S''} + C'' + \color{orange}{D''}\big) + \big(\color{red}{S'^2} + C'^2 +\color{orange}{D'^2} + \color{blue}{2S'C'} + 2 S' D' + \color{orange}{2 C' D'} \big)+ \color{red}{\frac{1}{4x^4}} = 0$$
where $S = \frac{i}{2x}$, $C = \log(x)$.

The $\color{red}{\text{ color red terms }}$ will cancel out because this is how we solved $S$, i.e.
$$S'^2 + \frac{1}{4x^2} \sim 0 \Longrightarrow S \sim \pm\frac{i}{2x}$$
and we can easily check
$$S'^2 + \frac{1}{4x^2} = 0 \Longleftarrow S = \pm\frac{i}{2x}.$$
The $\color{blue}{\text{ color blue terms }}$ will cancel out because this is how we solved for $C$.
The $\color{orange}{\text{ color orange terms }}$ are small compared to the rest of the terms.

Finally, we get
$$C'' + C'^2 + 2S'D' \sim 0$$
We get
$$D' \sim 0.$$
Hope my calculations are correct...
Furthermore, if as you calcuated $C = -\log(x)$, then you should get
$$D \sim -2ix.$$


Como remover arquivo incluindo com include de acordo com condições

Question: Dei uma pesquisada básica e não encontrei nada. Imagino que deva ser algo simples, e que eu possa estar "procurando errado"...
Então por exemplo:
<?php
    if ($var1 != "qualquercoisa") {
        include "arquivo1.php";
    }
    elseif ($var2 == "outracoisa") {
        include "arquivo2.php";
        **remove** "arquivo1.php";
    }
?>

Existe um comando que faça isso, ou tenho que fazer de outro jeito, tipo com switch?
Comment: Não seria melhor criar uma função que retorna um array com todos includes e depois apenas invocar eles?
Comment: Oi Gustavo, eu respondi, mas gostaria de saber o objetivo disto, por que assim posso talvez lhe sugerir uma alternativa para fazer algo semelhante :)
Comment: @rray Ótima estratégia +1 vale uma resposta
Comment: @GuilhermeNascimento as variáveis recebem as informações de um formulário, e dependendo da escolha de um select por exemplo, eu incluo um arquivo com um bloco de texto (vai formar um texto completo juntando estes blocos)... Deu pra entender? Então às vezes eu tenho que trocar estes blocos, porque uma escolha posterior (num select em outra página) inclui outro arquivo ao invés daquele que seria incluido se a escolha anterior não afetasse a posterior...
Comment: @rray e como eu faria isso? Pode dar um exemplo?
Answer: O processo do PHP não é algo "assincrono", o arquivo incluído é executado como se fosse parte do arquivo que o está incluindo.
Supondo que você tem a.php:
<?php
echo 1;

E b.php:
<?php
include 'a.php';
echo 2;

Para o interpretador do PHP, vai ser o "mesmo" que:
<?php
echo 1;
echo 2;

Isto é semelhante ao C/C++ aonde o arquivo incluído é compilado "junto" com o arquivo que inclui.
Não tem como "remover" o arquivo incluído, note também que include e require não são funções.
Outra coisa (não estou certo disto), softwares opcache para PHP geram versões já processadas do PHP, neste caso o arquivo incluído é processado junto do que inclui, como se fosse apenas um arquivo (eu acho).
Altenativa
Conforme o @rray sugeriu, você pode chamar os includes após as ifs, utilizando uma array por exemplo, seria algo como:
<?php
$includes = array();

if (condicao1) {
   $includes[] = 'file1.php';

   if (condicao2) {//condição dois
       $includes[] = 'file2.php';
   } else {
       $includes[] = 'file3.php';
   }
} else {
   $includes[] = 'file4.php';

   if (condicao2) {//Aqui repete a condição dois
       $includes[] = 'file2.php';
   }
}

foreach($key as $includes) {
   include $key;
}

Se condicao1 e condicao2 forem true ele vai incluir os arquivos file1.php e file2.php
Se condicao1 for true e condicao2 for false ele vai incluir os arquivos file1.php e file3.php
Se condicao1 for false e condicao2 for true ele vai incluir os arquivos file4.php e file2.php
Se condicao1 for false e condicao2 for false ele vai incluir apenas o arquivo file4.php
Comment: Legal! Tudo ficou mais claro! :-) Valeu! +1
Answer: Não existe forma de remover um ficheiro já incluído.

O código é interpretado no lado do servidor pelo módulo PHP, que também gera a página web a ser visualizada no lado do cliente.

Isto quer dizer que a cada vez que o utilizador dá um refresh na página ou abre a página esta envia um requisito ao servidor e o servidor interpreta o código no lado do servidor (server-side).
O que eu quero dizer com isto é que não existiria necessidade de remover a include visto que quando é feito um novo requisito é feito tudo do inicio, logo, se tivermos uma condição:
if($var == true)
{
    include "file1.php";
} else {
    include "file2.php";
}

No primeiro pedido se a variável $var for igual a true o ficheiro file1.php será incluído, mas se for feito outro pedido e a variável $var for falsa o ficheiro file2.php será incluido e o ficheiro file1.php não existira, isto porque, como eu disse, quando é feito um requisito ele começa de novo.

Fiz um pequeno código para exemplificar isso, testa por ti mesmo.
TestB.php
<?php
echo "Hello from A";

TestA.php
<?php
echo "Hello from A";

Test.php
<?php

$var = $_GET['n'];

switch($var)
{
    case 1:
    {
        include "testA.php";
        break;
    }
    case 2:
    {
        include "testB.php";
        break;
    }
}

Verificarás que ao mudar o valor de n no link (test.php?n=1 ou test.php?n=2) o ficheiro anterior existente não estará incluído.
Comment: Boa resposta, valeu! Gostei da ideia com o switch. Vou estudar melhor aqui as opções que surgiram. +1
Answer: Como dito nas outras respostas não é possível remover um arquivo já incluido.
Sugiro algo flexivel como dada uma entrada uma função ela retornará um (gabarito) array com todos arquivos que devem ser incluidos, após isso é feito um foreach.
function gabarito($entradas){
   $arquivos = array('config.php', 'segurancao.php');

   if($entrada['perfil'] == 'admin'){
      $arquivos[] = 'perfil/admin.php';
   }elseif($entrada['perfil'] == 'anon'){
     $arquivos[] = '/perfil.anon.php';
     unset($arquivos[0]); //remove as configurações do usuario como temas
   }

   return $arquivos;
}

$arquivos = gabarito($entradas);
foreach($arquivos as $item){
   include $item;
}

echo '
';
print_r(get_included_files());

Pode ver os arquivos incluidos com a função get_included_files(), também pode ser interessante definir uma constante com o prefixo de algumas pastas.
Comment: Dependendo da complexidade vc pode criar configurações/perfils e gravar/recuperar do banco de dados e tratar com a sessão. Exemplo perfil 1, carrega o `config` e o `admin`, perfil 2 carrega, `somente_leitura` e `interface_basica`. @gustavox
Comment: Então, eu ainda não estou usando sessões, mas gostei da solução com foreach... a ideia da outra resposta com switch também parece boa... vou estudar aqui melhor, acho que terei que rever a lógica que estava pensando (só com `ifs`). Valeu pela resposta, acho que em breve (quando implantar o controle de usuários) será ainda mais útil que agora! +1
Comment: Legal, é bem isso mesmo que vou ter que fazer em breve. Por enquanto estou usando apenas em localhost, desenvolvendo ainda, mas em breve terei que me aprofundar em sessões, já até arrumei uns livros, porque sei que esta parte será um dos maiores (banco de dados, sessões etc) desafios do meu projeto... valeu mesmo!
Comment: +1 pela ótima ideia (rray é o estrategista dos códigos o/ )


If $E/F$ is finite divisible, then it is separable.

Question: I want build a separable extension $E/F$. Suppose that $E/F$ is a finite divisible field extension. I want to prove that $E/F$ is separable in this method:
we know that if $Char(F)=0$, then $E/F$ is separable. So suppose that we are in case $Char(F)=p>0$ for a prime $p$ and $F$ is indivisible. We know that $F^*=N_{E/F}(E^*)\times C_m$ for $1\neq m|[E:F]=n$ and From ${F^*}^n\subseteq N_{E/F}(E^*)$, every element of $C_m$ is a root of $x^n-1$. So if I can say $p\nmid m$, I can prove that ${F^*}^p=F^*$, and from it I can prove that $F$ is perfect and so $E/F$ is separable.
So my question is why $p\nmid m$?
Comment: I have heard of divisible (abelian) groups and modules, but somebody pray tell me what is a divisible field extension? Are you referring to divisibility of the multiplicative group?
Comment: A divisible group?
Comment: Yes, we say a group $G$ is radicable if for every $a\in G$ and every $n\in \mathbb{N}$, there exists $b\in G$ such that $b^n=a$. A ring $R$ is called radicable if its unit group is radicable. We say divisible when the group is abelian. A field $F$ is divisible when its multiplicative group is divisible.
Comment: Then "divisibility" is not a property of extensions, but of the individual fields. Did you mean for both $E$ and $F$ to be "divisible" or just $E$?
Comment: $F$ can be both of them, indivisible or divisible.
Answer: As $C_m$ is a cyclic group of order $m$, so we have $m$th root of unity in $F$ like $a$. If $p=Char(F)|m$, then there exists natural number $r$ such that $rp=m$ we have :
$0=a^m-1=(a^r)^p-1=a^r-1$, so the order of $a$ can not be $m$ and it is contradiction. Therefore $p\nmid m$.


Error with datapicker in internet explorer

Question: I have this code in the header:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

and after this script more below

And in my HTML I use this sentence:
<input id="datePicker" name="datePicker" type="date" size="36" onkeypress="return postOnReturn(event)">

In chrome I can see the datapicker but in Internet Explorer i only see a empty field. And error message that it said "JQUEry isn't defined" in Console
Do you know what happen?
THX!
Answer: I try to refer your steps to produce the issue on my side with IE. I find that your code is working fine on my side without any error. Here is my testing result.
Code:

<!doctype html>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

<input id="datePicker" name="datePicker" type="date" size="36" onkeypress="return postOnReturn(event)">

Output:

So we can say that this example code does not have any issue and it is working fine in IE. It is possible that some other line of code have the issue and causing this error. You can try to check the code again.
If you are using any older version of IE than I suggest you to move to IE 11. It can also help you to solve your issue. I had also test the code with various document mode and it works without any error.
You can try to make a test with my code and check whether it is running correctly or not.
Let us know about your testing results.
Comment: I have to do a datepicker for IE 8 or more. Do you know anything?
Comment: @CMorillo, I am not available with IE 8 but I try to change the document mode in IE 11 and made a test with IE 8, 9, 10 and IE 11. In all document mode your code works fine. Besides that IE 8 is outdated and currently not supported by Microsoft. If possible than I suggest you to move to IE 11.
Answer: Use this way
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

<input id="datePicker" name="datePicker" type="text" size="36" onkeypress="return postOnReturn(event)">

https://jsfiddle.net/s2yku8q7/3/
Comment: internet explorer version? I have the check on 11 version working fine.


Full organisation certificiate, no domain name - Possible?

Question: Our organisation is planning to add HTTPS to our sites. Because our server has only one IP (which means we can only use one certificate) we need a certificate that is valid for all sites in our organisation which have various domain names. The certificate should therefore not contain a domain name.
Are they technically possible, do CA's sign those, and how do browsers handle them?
Answer: You can't get an X.509 cert that doesn't have at least one subject principle name (the domain) specified. No useful CA is going to let you have a certificate without one that can be tied to a domain that you can demonstrate that you own. They can be wildcarded at the level that you "own" it so site1.domain.com, site2.domain.com etc are fine but site1.domain2.com wont be.
The alternative is to use Subject Alternate Names or SAN [capable] certs, these can contain a range of additional names (of various types) provided your cert provider is prepared to add them that is. For your use case they can be FQDNs for specific sites within a domain (site1.domain.com, site2.domain.com etc), FQDNs for other domains (site1.domain2.com, site1.domain.net). They can be used to add additional types of identifier depending on what you want to do, including ip-addresses however I don't know how widely supported these additional capabilities actually are. The number of SAN identifiers you can include also varies by certificate provider, Verisign allows for 19, while Digicert will support up to 150 for example.
From the OpenSSL documentation:

The subject alternative name extension
  allows various literal values to be
  included in the configuration file.
  These include email (an email address)
  URI a uniform resource indicator, DNS
  (a DNS domain name), RID (a registered
  ID: OBJECT IDENTIFIER), IP (an IP
  address), dirName (a distinguished
  name) and otherName.
The email option include a special
  'copy' value. This will automatically
  include and email addresses contained
  in the certificate subject name in the
  extension.
The IP address used in the IP options
  can be in either IPv4 or IPv6 format.
  ...
  subjectAltName=email:copy,email:firstname.lastname@example.com,URI:http://my.url.here/
  subjectAltName=IP:192.168.7.1
  subjectAltName=IP:13::17
  subjectAltName=email:email@example.com,RID:22.214.171.124
  subjectAltName=otherName:184.108.40.206;UTF8:some
  other identifier
Answer: Yes - they're called wildcard SSL certificates but they only count for a single domain (*.domain.com.)
Newer certificates can also contain SANs (subject alternate names) within the certificate which I believe allows you to cross the domain name boundary (i.e. one certificate for www.domain.com and www.domain2.com.)
Comment: I know about wildcard certificates but they're not enough. I mean entirely different domains, e.g. example.com and freebeer.org
I'll look into SANs
Comment: Why the downvote?  I did point out about the cross-domain names, and I believe this is the main reason why SANs were devised.
Comment: FYI: Not my downvote :)
Answer: No. SSL Certificates are bound by their Common Names (CN), and CN is tied to a Domain Name, not an IP address.
Unfortunately there's no choice except to ask for a bunch of IPs. Most ISPs will give you a additional block of 4 (2 usable) for no additional cost on a business plan.
Comment: To my surprise, I found out we already have about 8 IPs
Comment: Well, that should cover you for 6 domains at least! (1st and last are usually unusable)
Answer: Contrary to popular belief it is now possible to have many SSL sites with different names on the same IP address, but it requires that both the server and the client applications support SNI (see http://en.wikipedia.org/wiki/Server_Name_Indication for info).
Lack of support in some clients (most notably IE6, and IE7/8 if run on Windows XP) is the main reason not to use SNI, but if this would not affect your userbase significantly it may be worth considering. Firefox has supported SNI since version 2, and IE7 & IE8 support it under Vista/2003/2008/7 (see the Wikipedia article linked above for more client support detail).
Another problem if your servers are Windows based and serving HTTP(S) via IIS is the lack of support in IIS - but you could get around this by installing lighttp or nginx as a reverse proxy to the real http(s) daemon (IIS).
You will still need a separate certificate for each FQDN, or at least a wildcard certificate for each group of names, of course - but it does reduce the number of IP addresses you need allocated which will be a GoodThing(tm) if these are a scarce (or otherwise expensive) resource where your server is located.


JavaScript for Drupal Edit Overlay

Question: I have written some JavaScript that I want to only run on the Edit page.  We are using Drupal 7.8 and in our setup the edit page opens as an overlay.  How do I get this javascript to run when the edit overlay page opens up and only then?
Thanks!
Jon
Comment: I asked if you meant "Node edit page" when you said "Edit page" in your question. You can have Edit pages for taxonomy terms, vocabularies, content types, various entities, users, configurations... which is it? Do you just want to run a javascript file on the node edit page? Please clarify. Thank you.
Comment: "Node" Edit Page?
Comment: Hmm, maybe.  I could probably do it by adding a custom node edit tpl.php file.  But I really just want to add a javascript file that will listen to an event and trigger with that event.  What file name will be the node edit tpl.php file and will I need one for each content type?
Comment: @Beebee is right, we need to know what are you trying to edit. And what overlay? One from core? Asking to be sure.
Comment: Oh.  Sorry.  Yes, the node edit page from core.  I have not made any changes to the edit pages so far because they have all worked fine for our needs so far.
Answer: Regardless of whether the page opens in an overlay or not, the following should work. Suppose you have a node type called "Basic Page", and the machine name of the content type is "page". The node edit forms take the form of: MACHINENAME_node_form. So for "page" content type our form id is: page_node_form. The hook we're using is hook_form_FORM_ID_alter. The following code placed in a custom module should attach the JS file (replace instances of word hook with the module name, and /path/to/file.js with the path to the javascript file relative to the custom module directory):
function hook_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  // Attach a JS file
  $form['#attached']['js'][] = drupal_get_path('module', 'hook') . '/path/to/file.js';
}

For reference: Form API #attached

JavaScript for Drupal Edit Overlay


getRequestURI for servlet or jsp?

Question: I'm making a filter for my login form in my JEE project. I want to make sure you need to configure your session before you can access any pages past the login form. So, so far I have written this
public class AuthenticationFilter implements Filter {

 @Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)arg0;
if(request.getRequestURI().startsWith("/"))
}

In my request.getRequestURI statement, should I write the servlets or the jsp pages that the user can only access after passing the login form?
Comment: You shouldn't do that.
Answer:     @Override
    public void doFilter ( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException
    {
            doFilter( (HttpServletRequest) request, (HttpServletResponse) response, chain );
    }

    private void doFilter ( final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain ) throws IOException, ServletException
    {
        if ( isAuthorized( request ) )
        {
            chain.doFilter( request, response );
        }
        else
        {
            response.sendRedirect("/login.html");
        }
    }

    boolean isAuthorized ( final HttpServletRequest request ) throws
    {
        if ( request.getParameter("password").equals("swordfish") )
            request.getSession().setAttribute("authorized","true");

        return request.getSession().getAttribute("authorized") != null;
    }

This is sort of a "toy" implementation and doesn't follow many best practices, but it's easy to understand, I hope.

getRequestURI for servlet or jsp?


Minimum and Maximum .

Question: In a book it has been written that
"Taking the minimum and maximum of each term we see that on $[0,1]$ the function, $y=x^3-7x^2+1$" , is bounded below by c$=0-7+1=-6$ and above by d$=1+0+1=2$.
I am not understanding how they calculate the c and d ?
Comment: Are u allowed to use derivatives?
Answer: They simply splitted calculation of $\min x^3-7x^2+1$ into $\min x^3$, $\min -7x^2$, $\min 1$.
As $x \in [0,1]$:

$\min x^3=0$ (because $x^3>0$ for $x>0$ and $0^3=0$)
$\min -7x^2=-7$, because it is a monotically decreasing function on $[0,1]$ with minimum at $x=1$, which is easy to see, as any $0\leq x<1$, $-7x^2>-7$
$\min 1=1$, as it is a constant function

Of course thic minimum is not actually achievable (as it requires $x$ to be both 0 and 1), but it gives the lower bound of the whole equation. Similarly with the upper bound.
Comment: Could you please explain what will be the lower bound when the function is $\sqrt(1-x^2)$ ?
Comment: $\sqrt{1-x^2}$ on $[0,1]$ is a monoticaly decreasing function, which achieves minimum in $x=1$. If you take $x=1$, then $\sqrt{1-x^2}=0$, but as $\sqrt{a}\geq 0, \forall a \in \mathbb{R}$, you know that $\min \sqrt{1-x^2} = 0$, for $x \in [0,1]$. You should check out **wolfram alpha** for such simple function analysis: http://www.wolframalpha.com/input/?i=sqrt%281-x%5E2%29
Answer: The key here is:

Taking the minimum and maximum of each term ...

Here, the terms of the given function are $x^3$, $-7x^2$ and $1$.
The minimum of the term $x^3$ in the interval $[0,1]$ is $0$ and max is $1$.
Similarly for other terms as well.
Answer: You're gone while I asked you the comment. If you are allowed to use the derivatives, then you could get the answers better. Our function is $f(x)=x^3-7x^2+1$ and you know that it is differentiable at least $2$ times. So we have $$f'(x)=3x^2-14x$$ Since $f'(x)$ is a polynomial so the critical points can be achieved by setting $f'=0$. This gives us $$x=0,~~x=14/3$$ We have  then: $$x_1=0,~~f''(0)=-14\longrightarrow f(0)=+1 ~~\text{relative max}\\ x_2=14/3,~~f''(14/3)=+14\longrightarrow f(14/3)\approx-49 ~~\text{relative min}$$ But you are given an interval $[0,1]$. Considering that $x_2\notin I$ so we compute $f(1)$ and then probe the finial results:
 $$f(0)=0,~~f(1)=-5$$ So on $I$: $$-5\le f(x)\le +1$$
Comment: $+1 \ddot\smile$

Minimum and Maximum .


Multiple user avatars

Question: I'm looking at putting together a Drupal 7 installation for a community website. One of the features of the website will actually be in specific user profiles, which will double as "About" pages in a catalogue of team members. Anyway, the site is currently designed in such a way that a user has a detailed photo on their page. I'm looking at one of two different options, and would like some input as to how best to carry out this task.

After a user uploads a profile picture (with the ImageStyle profile_picture) , have the system create a duplicate photo for the forum avatar based on what was just uploaded, only resize and crop the photo to be 200x200 pixels, and have the duplicate be named under the image style forum_avatar.
Provide an additional upload form for avatars in the user configuration settings with Drupal 7.

Obviously, the first one would take a little bit of doing, but I'm really curious: what would be the best way to carry out one of these two processes?
Answer: Assuming that you want to use the same avatar image, just in different sizes, you do not have to duplicate anything.
Being able to display the same image with different styles is the whole point of having different image styles. "Styled" images are created on demand, according to the request. This already works out of the box for normal image files (For example, you can chose a different image style for teaser and default view modes).
The user avatar image can be displayed with different image styles too, the only problem right now is that you can't select the image style when using theme_user_picture(). There is however already a patch for that. And if you're using Views, it should already be possible to choose the image style for the user picture.
Comment: Hey, great! I'll give those things a try. I think I'll try doing it with Views first. I'm still trying to get the hang of Views, so I'm going to have to read up on some of the documentation to try it out.
Comment: So, I'm still confused...how do I apply the patch?
Comment: http://drupal.org/patch/apply has some information about applying patches. You should however only apply patches to test them in most cases, and not to use them on production sites, because you will always have to re-apply those patches until they are commited. As an alternative, you write a custom function similar to http://api.drupal.org/api/drupal/modules--user--user.module/function/template_preprocess_user_picture/7, that calls theme_image() directly with the desired image style.

Multiple user avatars


Error while using Group By in LinQ

Question: i am relatively new to Linq and am trying to group by my Linq query but am getting the error that does not contain Field value.
Below is my linq query. Can anyone please help me on this.
var name = dt1.AsEnumerable()
    .Where(p => (int)p["Age"] >= 29)
    .GroupBy(p =>p.Field<string>("Role"))
    .Select(p => new{ID = p.Field<int>("ID"),Name =p.Field<string>("Name"),Role = p.Field<string>("Role"),Age = p.Field<int("Age")});

Comment: What is the purpose of groupbby here?
Comment: please add more information to have [a complete and verifiable example](http://stackoverflow.com/help/mcve)
Answer: Correct code:
var name = dt1.AsEnumerable()
                  .Where(p => p.Field<int>("Age") >= 29)
                  .GroupBy(p =>p.Field<string>("Role"))
                  .Select(q => q.Select(p => new{ID = p.Field<int>("ID"),Name =p.Field<string>("Name"),Role = p.Field<string>("Role"),Age = p.Field<int>("Age")}));

Explanation:

GroupBy will create IEnumerable<IGrouping<string,DataRow>> in this case
When you do Select, you get IGrouping, on which you need to do further Select to get the exact element DataRow used for creation of result Anonymous Type as in this case
Comment: Thanks for the explanation. It solution worked fine.
Answer: Refer LINQ Case statement with COUNT and GROUP for selecting fields in group by. both Lambda exp and c# linq is available.
Comment: Please add this as a comment, there's no value add from your end

Error while using Group By in LinQ


How do I create a supplier of a class with limitations regarding constructor arguments?

Question: I have a class called Human (accepts name(string) and height(int) in the constructor) and need too create a supplier of this class that will create an object but I want the object's name to let's say be between 5-10 characters, and the height should be between 110-250. Is it possible to do so in Java?
Comment: What is the specific problem you're facing here?
Comment: I don't know how to create limits for arguments in Supplier's definition.
Comment: What do you want to happen if it's wrong?
Comment: @DM Then the object shouldn't be created, could return a null perhaps.
Comment: Pretty sure a constructor can't return a null.  Does it have to be a constructor?  Or would a factory method work for you?
Comment: @DM I need a supplier similar to this one:
Supplier i  = ()-> {return new Person()};
but in the brackets there should be the constraints that I mentioned higher. Can't figure out how to make this work.
Comment: You need to describe what do you want in more concise way, do you need random Human instances generation with different parameters?
Answer: here is one approach, rejecting invalid arguments
public class Human {

    private final String name;
    private final int height;

    public Human(String name, int height) {
        validateName(name);
        validateHeight(height);
        this.height = height;
        this.name = name;
    }

    private void validateName(String name) {
        if(name==null || name.length()<5 || name.length()>10)
            throw new IllegalArgumentException("Name should be between 5-10 chars long but  "+name);
    }

    private void validateHeight(int height) {
        if(height<110 || height>250)
            throw new IllegalArgumentException("Height should be between 110-250 but "+height);
    }
}

Note that this is a RuntimeException, variations include throwing a checked exception instead and let the client code have a workaround.  Or, perhaps have a static factory method and return a InvalidHuman object if not valid.
UPDATE
Ok, I think you want something like this
public class HumanProvider {

    private static final Random r = new Random();

    private static String vowels = "aeiou";
    private static String cons = "bcdfghjklmnpqrstvwxyz";

    private static String[] patterns = "cvc vc cv cvvc vcc".split(" ");

    private HumanProvider() {
    } // don't instantiate

    public static Human createRandom() {

        String name;
        do {
            name = getRandomString();
        } while (name.length() < 5 || name.length() > 10);

        int height = r.nextInt(251 - 110) + 110;

        return new Human(name, height);
    }

    private static String getRandomString() {
        int numSyllabels = r.nextInt(5) + 1;
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < numSyllabels; i++) {
            String pattern = patterns[r.nextInt(patterns.length)];
            for (char c : pattern.toCharArray()) {
                name.append(randomChar((c == 'c') ? cons : vowels));
            }
        }
        return name.toString();
    }

    private static char randomChar(String list) {
        return list.charAt(r.nextInt(list.length()));
    }
}

Comment: Let's say I have a similar Human class to yours but without validateName and validateHeight. I want sth like this:
Supplier i  = ()-> {return new Person()};
Comment: You could always just put that logic in the constructor instead of in those methods, but why?
Comment: That's because I want the Supplier class to generate Human objects with randomized attributes but within the constraints that were mentioned.
Comment: Then, you should constrain the random value generator instead.
Comment: @karakfa Yeah, I just stumbled upon the Random() class so the height is quite easy. What about the string argument, is there some kind of regex generator in Java?
Comment: added a pattern driven primitive random String generator, you can fine tune the patterns and change char frequencies by adding extra instances of high frequency letters.
Answer: A constructor can't directly return null, but you could use something called a factory method.  A factory method would look something like this:
public static Human createHuman(String name, int height)
{
    if (height < 110 || height > 250)
        return null;
    if (name == null || name.length() < 5 || name.length() > 10)
        return null;
    else
        return new Human(name, height);
}

private Human (String name, int height)  // note that this is private
{
    this.name = name;
    this.height = height;
}

You could call it like this:
Human.createHuman("Steve", 117);

(Or in your case, perhaps like this:)
Supplier<Human> i = ()-> {return Human.createHuman(someName, someHeight)};


Random vector, finding CDF

Question: We have random vector $(X,Y)$ with distribution
$$
f(x,y) =
\begin{cases}
2,  & \text{(x,y) $\in (0,1)^2,y>x$} \\
0, & \text{otherwise}
\end{cases}
$$
Let $Z=\frac{Y}{X}$. Find $F_Z$.
My approach:
$F_Z(t)=P(\frac{Y}{X}<t)=\int_0^1\int_u^{tu}{f_{X,Y}(u,v)dvdu}=\int^1_02(tu-u)du=2*\frac{1}{2}u^2(t-1)]^1_0=t-1.$ Which is wrong. Could you help me with it?
Answer: $Z>1$ so you need $F_Z(t)$ only for $t>1$.
You need $ tu<1$ in your inside integral, so the outside integral is from $0$ to $\frac 1   t$ if the inside one is from $u$ to $tu$. There is also an integral w.r.t. $u$ from $\frac 1  t $ to $1$ and in this, the inside integral would be from $u$ to $1$.
$F_Z(t)=\int_{(1/t)}^{1}\int_u^{1} f_{X,Y}(u,v)dvdu +\int_{0}^{1/t}\int_u^{tu} f_{X,Y}(u,v)dvdu$.
Answer: Writing everything in terms of indicators, one gets
\begin{align}
F_Z(t)&=2\int_{\mathbb R}\int_{\mathbb R}\mathbf{1}_{0<x<y<1}\mathbf{1}_{y/x\leq  t}dxdy\\&=2\int_{\mathbb R}\int_{\mathbb R}\mathbf{1}_{0<x<1} \mathbf{1}_{0<y<1} \mathbf{1}_{ x<y}\mathbf{1}_{y\leq  tx}dxdy\\
&=2\int_{\mathbb R}\int_{\mathbb R}\mathbf{1}_{0<x<1}   \mathbf{1}_{x<y\leq  tx}\mathbf{1}_{y<1}dxdy\\
&=2\int_{\mathbb R}\int_{\mathbb R}\mathbf{1}_{0<x<1}   \mathbf{1}_{x<y\leq  \min\{tx,1\}} dxdy.
\end{align}
Note that for $t\lt 1$ and $x>0$, $\mathbf{1}_{x<y\leq  \min\{tx,1\}}\leq\mathbf{1}_{x<y\leq   tx,1}=0$ (which is logical, since $Z=Y/X\geqslant 1$). For $t\geq 1$, integrating first over $y$, we get
$$
F_Z(t)=2\int_{\mathbb{R}}\mathbf{1}_{0<x<1} (\min\{tx,1\}-x)dx
=2\int_0^1 \min\{tx,1\}dx-1.$$
Splitting the integral at $1/t$ gives
$$
F_Z(t)=2\int_0^{1/t}txdx+2\int_{1/t}^1dx-1=\frac 1t+2-\frac 2t
-1=1-\frac 1t$$
hence we derive that
$$
F_Z(t)=\left(1-\frac 1t\right)\mathbf{1}_{t\geq 1}.
$$

Random vector, finding CDF


Access Element in Iframe with Selenium

Question: I try to access an element via XPath, but it is not working somehow. The element is in an IFrame, could that be the reason?
If so, what do I need to do in order to be able to access it still?
Or might it be an issue, that I nested two html's (HTML Code Picture)? What would be a workaround for that?
The error message I get:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='oslist']/table1/tbody/tr2/td2/table/tbody/tr1/td/a"}
  Command duration or timeout: 1.14 seconds

Java Code:
 @Test
 public void testGenerierter() throws Exception {

     driver.findElement(By.id("cmdSigOn")).click();
     driver.findElement(By.id("k278")).click();
     driver.findElement(By.id("k279")).click();
     driver.findElement(By.id("k332")).click();
     Thread.sleep(3000);
     driver.switchTo().frame("1");

     Thread.sleep(3000);
     driver.findElement(By.xpath(".//*[@id='oslist']/table[1]/tbody/tr[2]/td[2]/table/tbody/tr[1]/td/a"));
     driver.findElement(By.id("LogoutButton")).click();

}

HTML Code
XPath from Firefox
Comment: Can you provide the actual website address?
Answer: Try this :
driver.switchTo().frame(0);

You are passing an integer, so double quotes are not required. And try to verify the correct iframe index number and your following xpath.
Comment: I have try,  but the same error. It doesnt find a frame with 0 or 1
Answer: Ok guys this is the Solution. i take the method with the Webelement
driver.switchTo().frame(driver.findElement(By.name("1")));

Answer: you are getting an exception on the xpath which means you are getting error on line driver.findElement(By.xpath(".//*[@id='oslist']/table[1]/tbody/tr[2]/td[2]/table/tbody/tr[1]/td/a"));
@Test
public void testGenerierter() throws Exception {

 driver.findElement(By.id("cmdSigOn")).click();
 driver.findElement(By.id("k278")).click();
 driver.findElement(By.id("k279")).click();
 driver.findElement(By.id("k332")).click();
 Thread.sleep(3000);
 driver.switchTo().frame(1);
   Thread.sleep(3000);
 driver.findElement(By.xpath("Give the Relative xpath here"));
 driver.findElement(By.id("LogoutButton")).click();

}
PS : Why are you using absolute xpath.Relative xpath is the best practice
Comment: You can share the screenshot of the code on which you are finding xpath or the URL
Comment: I have try absolut and relativ path. The path generate Firefox with the plugin firepath. I have try absolut because i have separeted iframes
Comment: I have adjusted my question with the Picture where i find the xpath

Access Element in Iframe with Selenium


Basis in R4 with only two vectors in the set

Question: Okay I have a set of vectors {(-2, 3, 1, 0), (3, 0, -1, 2)} and I need to create a basis in R4.
How do I do that? These vectors and lineary independent but I need two more vectors for the basis.
Comment: [Gram-Schmidt process](https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) is the most commonly used procedure if you want orthogonality.
Comment: linear independence means they must not lie on the same line.  most vectors in $\mathbb{R}^4$ do not lie on the line formed by your two vectors, so picking randomly is a pretty good method.
Answer: If you just want four linearly independent vectors in the end (you don't care about orthogonality and such), then picking from the standard basis vectors also works. For instance, it is pretty clear that $(0,1,0,0)$ is linearly independent from the two vectors that you have. Now you just have to check the other three (odds are any of them would work, but you will have to check to be certain).


remove both duplicate rows from DataFrame with negative and positive values pands

Question: DF csv

This CSV and i am using it as Dataframe

colA,colB,colC
ABC,3,token
ABC,50,added
ABC,-50,deleted
xyz,20,token
pqr,50,added
pqr,-50,deleted
lmn,50,added

output

colA,colB,colC
ABC,3,token
xyz,20,token
lmn,50,added

Comment: Can you specify the condition more detail? thank you
Comment: Can you please share what you have tried ? Also from your input and output it's not clear what you are expecting, can you explain the expected output?
Answer: Methods based on abs would incorrectly remove two positive or two negative values.
I suggest to perform a self-merge using the opposite of colB:
# get indices that have a matching positive/negative
idx = (df.reset_index()
         .merge(df, left_on=['colA', 'colB'], right_on=['colA', -df['colB']],
                how='inner')['index']
       )
# [1, 2, 4, 5] (as list)

# drop them
out = df.drop(idx)

output:
  colA  colB   colC
0  ABC     3  token
3  xyz    20  token
6  lmn    50  added

Answer: You want to identify all the 'positive and negative' by taking the absolute value. Then drop duplicates based only on colB (ignoring the text in colC). Don't keep any (keep=False) to make sure both are dropped.
df.abs().drop_duplicates(subset='colB', keep=False)

A small advice, given this is your first post: Please always try to put complete code examples, and make sure you ask a clear question. That makes it easier for other people to understand your problem and reply.
Also, if this answers your question, don't forget to "accept" this answer.
Comment: given your question is not really complete: what happens for example if you have "50, 50, -50"? Do you want to drop all 3 occurrences? Or keep only one of the '50'? Try to complete your question :)
Answer: not sure exactly what you mean, this gets the desired output though:
df['abs_colB'] = np.abs(df['colB'])
df.drop_duplicates('abs_colB', keep='last').iloc[:, :-1].reset_index(drop=True)

colA
colB
colC

0
ABC
3
token

1
xyz
20
token

2
lmn
50
added
Comment: for sure the 'drop' condition is not based on all columns of the `df` and only keeping 'last'... wherd do you think the ordering comes from?
Answer: def function1(dd:pd.DataFrame):
    dd.loc[dd.colC.eq("added"),"col1"]=range(0,len(dd.loc[dd.colC.eq("added")]))
    dd.loc[dd.colC.eq("deleted"),"col1"]=range(0,len(dd.loc[dd.colC.eq("deleted")]))
    return dd.assign(colB=dd.colB.abs()).drop_duplicates(subset=["colB","col1"],keep=False).drop("col1",axis=1)

df1.groupby('colA',sort=False).apply(function1).reset_index(drop=True)

out:
 colA  colB   colC
0  ABC     3  token
1  xyz    20  token
2  lmn    50  added


Simplify Summation of combination

Question: how can I simplify this to a phrase without a sigma?!
$$
{1\over r+1}{2r \choose r} + \sum_{i=1}^r \left( {i+1\over r+1} {2r-i \choose r-i}{s+i-2 \choose i} \right)
$$
thanks!
Answer: There isn't much you can do. Mathematica tells me the summation equals:
$$\frac{2 \binom{2 r-1}{r-1} \left(\, _3F_2 \left[ {2,-r,s-1 \atop 1,-2 r} ;1 \right] -1\right)+\binom{2 r}{r}}{r+1}$$
Where $_3F_2$ is a generalized hypergeometric function.
That basically means: as far as $\sum$s go, this one fits a sort of "nice" form, but there probably won't be a satisfying closed form.
Here is a table of your entire equation for varying values of $r$ (row number) and $s$ (column number):
$$
\begin{array}{cccccccccc}
 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\
 2 & 5 & 9 & 14 & 20 & 27 & 35 & 44 & 54 & 65 \\
 5 & 14 & 28 & 48 & 75 & 110 & 154 & 208 & 273 & 350 \\
 14 & 42 & 90 & 165 & 275 & 429 & 637 & 910 & 1260 & 1700 \\
 42 & 132 & 297 & 572 & 1001 & 1638 & 2548 & 3808 & 5508 & 7752 \\
 132 & 429 & 1001 & 2002 & 3640 & 6188 & 9996 & 15504 & 23256 & 33915 \\
\end{array}
$$

EDIT: It appears your entire equation also equals
$$\frac{s}{r!} \prod_{k=r+1}^{2r-1} (s+k)$$
which might be what you started from in the first place!
EDIT: and of course, assuming $r, s$ are positive, that equals
$$\frac{s}{r} \binom{s+2r-1}{r-1}.$$
I'm seeing if I can find a good proof.
Comment: I can't find a satisfying proof. It would get very hairy to use induction. I found the formula in my first edit by looking up rows and columns from the table up in the OEIS, and noticing the patterns. I then tried it out in Mathematica and it was right.
Comment: Tkanks! but would you please write the solution of it?
Comment: I mean how you find this? $$\frac{s}{r!} \prod_{k=r+1}^{2r-1} (s+k)$$
Comment: The second formula simply followed from messing around with the first one a bit. Why did you not give any context for the problem? You tagged it [tag:catalan-numbers], and I recognize the formula but what are you trying to count?
Comment: i tagged #catalan-numbers because of the first part of phrase... I think it relevance to #catalan-numbers somehow! thanks! your answers are so useful.. i'll try to find the relevancy between the table and first formula... also any guidance from you can help... thanks again!
Comment: Someone marked this question as a duplicate of [this one](http://math.stackexchange.com/questions/1699118/calculate-sum-1-le-i-le-r-fraci1-r12r-i-choose-r-isi-2-choose-i) which has a proof

Simplify Summation of combination


Carved fingerboard between frets on a guitar

Question: I've played the electric guitar for about ten years. I've seen and tried out various kinds of necks, but today I stumbled upon a fingerboard that goes beyond my understanding.
It looked like this:

My question is; Why would someone want a fingerboard carved in between the frets like this?
"How it feels to play" is of course a matter taste, but doesn't such a neck:
A) excessively tighten the string (increase pitch) if pressed too hard
and
B) require a completely different fingering technique?
Is this some known kind of a fingerboard, or just some random players wild tryout?
Comment: http://en.wikipedia.org/wiki/Scalloped_fretboard#Scalloping
Comment: See also: http://music.stackexchange.com/a/9537/6556
Comment: A former pupil used to use that pressing technique as part of vibrato.
Answer: It is called a scalloped fingerboard. It is used by lead guitarists who do a great deal of string-bending when playing melodies. And yes, playing one effectively requires a certain technique, because if one uses too much finger pressure, the notes and chords go way out of tune.
Here is a page at Warmoth Custom Guitar Parts where they explain different kinds of scalloping.
The most famous advocate of the scalloped fingerboard is the heavy metal guitarist Yngwie Malmsteen. For many years the Fender guitar company has made a Yngwie Malmsteen signature model Stratocaster that comes from the factory with a scalloped fingerboard, and from time to time they have offered other models with a scalloped fingerboard as well. So yes, this is a well-established feature of certain mass-produced electric guitars.
Comment: It really is an expert level modification - you need to be incredibly precise with the pressure you use on the string. That does allow you to be very fast (although which one is cause and which is effect may be up for debate)
Comment: Thanks for the answer! I stand enlightened. I'll vote up as soon as I have 15 reputation :)
Comment: I would argue that Richie Blackmore is just a BIT more famous than Yngwie Malmsteen :P


How to remove focus from submit button

Question: How can I remove focus from submit button? I don't know why it is there in the first plate, and it looks really ugly here is a screenshot :

And here is how it should look like, it regains its appearance after I click beside it and hover it.
Answer: This worked :
var selectedInput = null;
$(document).ready(function() {
    $('input, textarea, select').focus(function() {
        this.blur();
    });
});

Comment: Note that by blurring the button on any focus you won't be able to submit the form by pressing enter on the button, which is a standard behavior most people expect.  If you are worried about the visual look why not try removing the outline as I noted and leave the focus alone?
Comment: @bmoeskau it doesn't work with removing element and yes I want to disable enter for submitting as well.
Comment: It shouldn't be an accepted answer. You should never remove a focus from any element (this breaks keyboard navigation for example).

This can be easily removed using CSS, but you should provide some other form of feedback as well (for example, when you remove an outline, you change a background).

https://www.a11yproject.com/posts/2013-01-25-never-remove-css-outlines/
Comment: Never say never. My app that uses a handheld keyboard wedge scanner requires this. Otherwise if you press a button and scan a barcode,
Answer: Try this in your button's CSS, or that of the enclosing  (whatever has focus) if that's what you are using in the markup (reference):
outline:0 none;

Bear in mind that a distinct focus style is a valuable accessibility/usability feature, so you should provide some alternate focus hint that is more visually pleasing to you, rather than removing it completely.
Comment: Please stop using `-moz-outline`; `outline` has been supported since Firefox 1.5.

+1 for the a11y reminder.
Comment: Also see: http://stackoverflow.com/questions/71074/how-to-remove-firefoxs-dotted-outline-on-buttons-as-well-as-links
Comment: I'm using button not anchor tag
Answer: In your body or form... <form onready="document.getElementById('submit').blur();">
...
<input type="submit" id="submit" />
</form>
Comment: I already tried something similar and this as well not working m8
Answer: The first submit button in a form is always "in focus", hence, when you hit enter, your form gets submitted.
See responses to a similar post: Stopping IE from highlighting the first submit-button in a form
Comment: @naivists on contrary it works fine in IE, firefox is the focusing it
Comment: most likely, Mozilla is trying to implement HTML5 and this is what you see. Of course, you can create a simple javascript which runs on document load event and calls `blur()` on that particular submit button. However, this sounds awkward ;-)
Comment: as much as it sounds akward it doesn't work as well, I tried it already, on several ways..
Comment: @naivists This focus is an issue for me when dealing with "web accessibility" and keyboard users. The focus should be on the input, but the button. How to fix this?
Answer: You can code your button as:
<button onClick='this.form.submit()'>Button Text</button>

That removes the "submit" functionality to code and thus the focus problem.

How to remove focus from submit button


Vou criar um select e gostaria que ele atualizasse a quantidade de registros

Question: Estou criando um sistema e na parte de registro de produtos em php a um select com a opção de quantos produtos vão ser registrados, gostaria q ao escolher o select atualizasse para aparecer o numero de linhas para registro, como posso proceder????
Gratidão =D
Comment: Bem-vindo, você pode começar fazendo [tour](https://pt.stackoverflow.com/tour) e para obter respostas que solucionem sua dúvida / problema leia [Como fazer uma boa pergunta?](https://pt.stackoverflow.com/help/how-to-ask), [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve) e [Como formatar minhas publicações usando o Markdown ou HTML?](https://pt.stackoverflow.com/help/formatting).
Answer: A melhor forma é criando os campos dinamicamente através de javascript. Quando o usuário selecionar o número de produtos que serão registrados, você dispara o evento que criará os campos:
https://jsfiddle.net/caiubyfreitas/9cezx9wr/
Observe que os campos serão aninhados na DIV identificada por "container":
<code>var container = document.getElementById("container")
</code>


URL Amigável com parâmetro variavel

Question: Tenho a seguinte expressão regular para URL Amigavel:
RewriteRule ^categoria/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$ categoria.php?idc=$1&nome=$2&pg=$3 [NC]

gostaria de deixar o 3 parâmetro, o pg, opcional, ter ou não ter. Da forma que estou utilizando é obrigatório fornecer o 3 parâmetro.
Comment: Tem vários exemplos no site, e tem mais de um com parâmetros opcionais, veja qual serve melhor: http://pt.stackoverflow.com/search?q=url+amigavel
Answer: Tentou isso?
RewriteRule ^categoria\/([a-z0-9-]+)\/([a-z0-9-]+)(\/([a-z0-9-]+))?\/?$ categoria.php?idc=$1&nome=$2&pg=$4 [NC]

Assim você coloca um grupo dentro do outro e faz o parâmetro pai ser opcional englobando a barra. Na variável de resposta é só pular o parâmetro pai ($3) até encontrar o parâmetro filho ($4).

URL Amigável com parâmetro variavel


Piano: conscious vs subconscious playing

Question: In particular when practicing scales (say, C major, one octave apart, similar motion) or jazz standards, I've noticed that my playing becomes automated. I don't consider every step carried out by my hands, they just do it. In one way I understand this, some things goes too fast and too many things are going on for consciously/thinking about every step. When I consider more complex things (though that scale is enough for me), such as accompanying oneself while improvising, or seeing skilled players like Chick Corea, I understand that this automation is a necessity and a goal, it seems.
My problem is, when my hands attempt this "subconscious" playing I mess up a lot. When playing my scales, or tunes I've practiced to boredom with, I'm too bored/neglective, resulting in that I don't think about my hands. They attempt to do something automated, and as a result it's almost random whether it comes out right.
Any suggestions for what to do? Otherwise I'll go with something classic like "Slow down the tempo, break it down, and take it step by step." The subconscious/automated stage should not be skipped I presume, the question is how to make it function, how to change it.
Answer: If you are still messing up scales, then they're not in your sub (or even un) conscious yet.
When was the last time you were running, and thought ' does my heel or toe need to hit the ground first?' Chances are, if you did think that, you'd probably fall over... Running has reached the stage where it's at least subconscious, so it's not necessary to analyse what's going to happen. It takes a lot of practice - repetition - to achieve that level. I ask students to recite the two times tables while playing scales. Successful ones have reached that state!
One of the things with improv. is not actually thinking about what's happening now but what's going to happen next. So to a great degree, there has to be some automation. And that won't happen until the playing has become automated, obviously. It doesn't have to sound automated - and if it does, that's another hurdle to overcome - but the physicality of it must be. If it's not, then it's back to the drawing board (instrument!) and work at whatever until it is. Good luck!
Comment: The old saying applies here: amateurs practice until they can get it right. Professionals practice until *they can't get it wrong*. It doesn't feel like it, but practicing beyond the point where you can get it right has massive benefits.
Answer: Hands playing automatically is called "muscle memory", in fact this is a misnomer because muscles don't have a memory - not this sort of memory anyway. The part of the brain called the cerebellum memorises motor actions. This takes away a load from the conscious parts of our brain.
https://www.thoughtco.com/anatomy-of-the-brain-cerebellum-373216
The most important technique for getting the cerebellum to memorise correctly is to teach it correctly. If you constantly practise scales with mistakes, the cerebellum will eventually learn the mistakes. Those mistakes will become automatic and then you will have a heck of a job getting rid of them because the mistakes are now subconscious!
The answer is simple - practise slowly and carefully. If you can reliably play a scale with 100% accuracy, even at a snail's pace, your cerebellum will learn it that way too. Now, contrary to what I said, muscles do have a sort of memory, but it is very simple. They can be trained to improve physical movements (stretches and so on) but they can't learn sequences of movements.
Once you have learned the movements perfectly and slowly, all you have to do is to train your fingers to be able to keep up with the messages from the brain.  Very often you you don't even need to do this. If the slow version is perfect you can suddenly just play at double the speed without any difficulty.
Note There is an amusing meme about this. Try searching for "If you can play it slowly, you can play it quickly". It has become a joke but actually the message is correct, if we rewrite it, "If you can play it slowly and perfectly, it's a small step to being able to play it quickly and perfectly."

Anecdote
There was a famous classical pianist (I'll see if I can remember his name and find the actual reference). The story goes that he was staying with a friend and practising one of his concert pieces very, very slowly. A visitor came to the house and, hearing this, innocently asked "Is that a child playing in your sitting room?" The host replied, "No that's Maestro ____. He always practises like that.
P.S. If anyone knows who the famous pianist was, please let me know so I can find it online. Thanks.
Comment: Is it Liszt? I'm not sure though
Answer: 'Eye to fingers' playing - barely hitting the brain - is a very useful accomplishment.   As is the development of muscle memory for tricky patterns and passages.
But if it's letting you down on a particular piece, yes you'll need to backtrack and sort it out.
Answer: It depends on whether your goal is improv or classical recital performance.  Your description of "automatic playing" is featured as a goal in Pepe Romero's book on Classical Guitar technique.  From his father he learned that a piece of music should be memorized, not only the notes but the feeling of playing every note, chord, etc.  To the point where you can sit quietly and hear the entire piece in your mind, and feel as if you are playing it.  With this level of automation the performer can transcend any mental stress during a performance.  You are almost having an out of body experience.
If your goal is improv and you find your self drifting into terrain that is not harmonious the one exercise is to play over changes slowly.  The most basic (and doesn't mean it's easy) is I --> V --> I etc.  Just toggle back and forth and try to "walk" through the major scale hitting chord tones as you go.  The skill being developed is not in the hands but Voice Leading, in the ear.  Once you can hear key tones then as you fly up and down the instrument you need not worry so much about being in key as you can really play anything.
I might be misunderstanding your question but I hope one of these paragraphs is helpful.  It is worth noting that some people might argue that improv is really rehearsed, whether the player realizes it or not.
Answer: Unconscious means that you are able to play the motifs, figurations, passages like you handle chords, triads, arpeggios and scales and ornaments (mordents, turn-arounds and trills) in classical music and riffs and licks in pop and jazz.
This means you have to analyze the form, the harmony, the chords, the chordprogression,  and you must have the entire passages in your mind.
This is possible if you know the figurations like letters, the motifs like words or elements of phrases.
My own approach is
a) reducing the music to the harmonic content
b) to practice the ornaments playing them like a single note, a figuration or ornament like a passage.
c) transposing a piece in other keys (section by section)
This means: the music has to be 100% in my consciousness and also in my fingers ( motoric memory) before I'm able to play it unconsciously.
Otherwise I always struggled and stuttered if the fingers were missing a note. It was very hard to enter again in a passage and I had to start from the beginning.
Comment: Playing pieces in different keys won't really help motor memory using piano. It may well be the case on guitar, but that's where the similarity ends. I agree it'll certainly help *knowing* the piece. But then I always start to think 'why did the composer write this in this key?'...


Como alterar a página .html automaticamente a partir de um tempo pré determinado?

Question: Possuo um sistema para exibição de conteúdos e necessito que a partir de um tempo pré determinado a minha página .html altere para um outro conteúdo (outra página) automaticamente.
NOTA:

O dispositivo para exibir o site não conterá dispositivos de entrada como mouse, é necessário que a partir do carregamento da página a função seja executada.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <link rel="icon" type="image/x-icon" href="img/favicon.png"/>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>.:: Painel Cirurgias ::.</title>
 <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
 <link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.css"/>
 <link rel="stylesheet" type="text/css" href="css/inside.css"/>
 <link rel="stylesheet" type="text/css" href="css/font-awesome.css">
 <link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui-1.10.3.custom.css"/>
 <link rel="stylesheet" type="text/css" href="css/select2.css "/>
 <link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.4.css"/>

<?php

include_once('db_functions.php');

ini_set('default_charset','UTF-8');

$id = isset($_GET['id'])?$id=$_GET['id']: NULL;
$id = isset($_POST['id'])?$id=$_POST['id']: NULL;

$con = dbConnect();

?>

   <?php

       include('paginator.php');

       $page = isset($_GET['page'])?$_GET['page']:1;

    $busca = isset($_GET['busca'])?$_GET['busca']:null;

    $painels = findPainels($con,$busca);

    $painelsPag = getPageElements($painels,$page,11);

   ?>

   <?php if($painels):?>

      Id
      Status
      Data
      Hora
      Paciente
      Tipo
      Hospital
      Médico
      Convênio
      Cliente
      Intermediário

      <?php foreach ($painelsPag as $painel):

          if ($painel["Cliente"] === 'ORTHOSEVEN'){
        $painel["Cliente"] = ''.$painel["Cliente"].'';
       }

       elseif ($painel["Cliente"] === 'BM9 IMPLANTES'){
        $painel["Cliente"] = ''.$painel["Cliente"].'';
       }

        if ($painel["Intermediario"] === 'ORTHOSEVEN'){
         $painel["Intermediario"] = ''.$painel["Intermediario"].'';
        }

        elseif ($painel["Intermediario"] === 'BM9 IMPLANTES'){
         $painel["Intermediario"] = ''.$painel["Intermediario"].'';
        }

         else {

          $cor = "#1E90FF";
         }

      ?>
       <tr bgcolor="<?=$cor="#66CDAA"?>" class="<?=$painel['id']?null:'muted'?>" data-id="<?=$painel['id']?>">
       <tr bgcolor="<?=$cor?>" data-id="<?=$painel['id']?>">
        <?=$painel['id']?>
        <?=$painel['Status'];?>
        <?=date('d/m/Y',strtotime($painel['Data']))?>
        <?=$painel['Hora']?>
        <?=$painel['Paciente']?>
        <?=$painel['Subtipo_Cirurgia']?>
        <?=$painel['Hospital']?>
        <?=$painel['Medico']?>
        <?=$painel['Convenio']?>
        <?=$painel['Cliente']?>
        <?=$painel['Intermediario']?>

      <?php endforeach;?>

    <?php printPaginator($painels,$page,11);?>
   <?php else:?>
   <?php endif;?>

<?php include("base.php"); ?>

<?php include("base.php"); ?>
Comment: Ao invés de usar `window.location.reload(1);` você fazer um form submit. Ex. `var form = $('  ) $('body').append( form) form.submit()`
Comment: @Bah essa mudança de página teria que ocorrer a partir de que evento? Por exemplo: Clicar no submit do formulário, ao passar o mouse em algum local, quando a página já estiver carregada?
Comment: Dá uma olhada nesse arquivo aqui http://twixar.me/wJ1n, É possível atualizar a pagina sem precisar de javascript
Comment: @Bah respondi a sua pergunta, era isto o que realmente desejava?
Comment: Cara vc quer que de tempo em tempo a página seja encaminhada para outra página, tipo fazendo um refresh com outro conteúdo é isso?
Comment: @Bah a minha resposta esta correta para você? O que ficou faltando?
Answer: Uma alternativa sem o uso de JavaScript é com a meta tag Refresh, com ela vc pode dizer quanto tempo vc quer que o documento espere antes de ser encaminhado para outra página, vc pode ler mais aqui https://www.w3.org/TR/html5/document-metadata.html#statedef-http-equiv-refresh
Funcionaria assim, imagina que vc tem tres página (p1.html, p2.html e p3.html), e a cada 10 segundos (10s) vc quer que uma página seja redirecionada para outra. Tipo, fica 10s na p1.html, depois vai para p2.html e fica mais 10s, depois vai para p3.html etc...
Para fazer isso dentro da tag  de cada documento vc precisa colocar uma <meta http-equiv="refresh" content="10; p*.html">, repare que no content="10; o 10 se refere aos segundos que vai ficar na página antes de encaminhar para a outra.
Logo vc teria essa estrutura na p1.html

    <meta http-equiv="refresh" content="10; p2.html">

Isso vai fazer que depois que a p1.html carregar, 10 segundo depois vai te encaminhar para p2.html
E esse mesmo modelo se repetiria no  da p2.html e p3.html só mudando o direcionamento para página que deseja, e colocando o tempo que quer em cada página
Answer: Seguindo o seu raciocínio onde ao adentrar a determinada página .html, a partir de um tempo pré-determinado o "usuário" será encaminhado para outra página .html e vise-versa.
Para isto você precisa utilizar alguns eventos e métodos do javascript, os quais são:

Evento DOMContentLoaded

Método setTimeout()

Método Window.location

DOMContentLoaded

O evento DOMContentLoaded é acionado quando todo o HTML foi completamente carregado e analisado, sem aguardar pelo CSS, imagens, e subframes para encerrar o carregamento. Um evento muito diferente - load - deve ser usado apenas para detectar uma página completamente carregada. É um engano comum as pessoas usarem load quando DOMContentLoaded seria muito mais apropriado.
Observação: Javascript Síncrono pausa a análise do DOM.

setTimeOut()

O setTimeout() é um método do  WindowOrWorkerGlobalScope (e successor do Window.setTimeout()), onde define um temporizador que executa uma função ou parte específica do código quando o temporizador expira.
Observação: A passagem de parâmetros adicionais para a função na primeira sintaxe não funciona no Internet Explorer 9 e abaixo. Se você quiser ativar essa funcionalidade nesse navegador, deverá usar um polyfill (consulte a seção Polyfill ).

Window.location

O Window.location é uma propriedade de leitura que retorna um objeto Location com informações de localização do documento atual. Embora Window.location seja apenas um objeto de leitura de localização, você pode também atribuir uma DOMString para ele. Isto significa que você pode trabalhar com location como se fosse uma string na maioria dos casos: location = 'http://www.exemplo.com' é um sinônimo de location.href = 'http://www.exemplo.com'.

Abaixo segue um exemplo de funcionamento, onde o cenário é o seguinte:
Você possui duas (2) páginas (pagOne.html e pagTwo.html), um evento de verificação se o .html já foi totalmente carregado (document.addEventListener("DOMContentLoaded"..)) e uma função para alterar a página a partir de um tempo pré determinado, utilizando os métodos citados (alterarPagina() + setTimeOut() + window.location.replace());
PagOne.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Página UM</title>

VOCÊ ESTÁ NA PÁGINA UM

PageTwo.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Página DOIS</title>

VOCÊ ESTÁ NA PÁGINA DOIS

NOTA:

Tome cuidado com os eventos, sugiro que leia a documentação dos mesmos para verificar com mais detalhes o seu funcionamento.
Comment: Mas o problema maior é que as paginas não são fixas, no meu select está para exibir os registros nos ultimo 60 dias, pode ser que gere 10 paginas ou 7 pag. Ai vai variar e alem de mudar de pagina terei de colocar um reflesh na tela a cada 1 min.  Seria essa minha grande dificuldade.


Does the "for" loop in C require a "{}" after it?

Question: I had this code in my program:
if (primeiro != atual){
                    for (i = 0; i < atual -> numeroChaves; i++)
                    // comment
}

And I was receiving the following error:
d8641900: In function 'printaArvore':
d8641900:130:7: error: expected expression before '}' token
       }
       ^

So I made the following change in the code:
if (primeiro != atual){
                        for (i = 0; i < atual -> numeroChaves; i++){}
                        // comment
    }

and it runned smoothly.
My doubt is: is it some problem with my code, or it is a rule applied in all cases?
The funny part is that, in other part of my code, I have a similar situation (no "{}" after the for loop), but after it I have a line with a valid command, and it runs perfectly.
Comment: It needs *something*: either braces, or a line of content
Comment: @sapi Note the empty statement `;` qualifies as something. So `for(i = 0; i < 10; ++i);` is valid, and does nothing.
Comment: Any loop or test requires **something** after it. The same rules apply. If no braces are provided, the next line alone is executed. If braces are provided, then all within the braces are executed.
Comment: What are you trying to accomplish with that code?
Answer: "for" loop in C needs one statement after it.
If you need several statements, then you can enclose them with { and }.
(Of course, you can also enclose zero or one statement.)
And ; can represent an empty statement.
So any of the followings are correct.
for (int i=0; i<10; i++);
for (int i=0; i<10; i++) {}
for (int i=0; i<10; i++) function_that_do_nothing();
for (int i=0; i<10; i++) 1;
for (int i=0; i<10; i++) function_that_do_something();
for (int i=0; i<10; i++) just_a_statement;
for (int i=0; i<10; i++) { statements... }

Additionally,
for (initialization; condition; statement)
    one_statement;

cannot be separated, so the followings are equal.
for (int i=0; i<10; i++)
    for (int j=0; j<10; j++)
        a_statement;

for (int i=0; i<10; i++) {
    for (int j=0; j<10; j++)
        a_statement;
}

for (int i=0; i<10; i++) {
    for (int j=0; j<10; j++) {
        a_statement;
    }
}

The same thing goes for if or while.
Comment: Thanks! So, in the caseof "for (int i=0; i<10; i++) 1;" , a number is understood as as statement? Curious!
Comment: `1;` is a statement that does nothing like `true;`, `false;`, or `0;`. Also, `i = i;` is a statement that does nothing in effect (but the CPU can take a very short time at this statement if the compiler does not abandon this statement).
Comment: Yes, any expression can be a statement. But nothing followed by a semicolon is also a statement.
Comment: In the specific case of a loop, my personal favorite is `for (...) continue;` I dislike `for (..);` as I find myself not noticing the bare semicolon.
Answer: No, the braces aren't required, but they're a good idea.
The syntax of a for statement is:
for ( expressionopt ; expressionopt ; expressionopt ) statement
(You can also replace the first "expressionopt ;" with a declaration, but that's not important here.)
The important part is the statement at the end. A for statement requires exactly one statement as part of it.
That can be any kind of statement, including a null statement (consisting of a single semicolon) or a block, also known as a compound statement.
A compound statement consists of an opening {, followed by zero or more declarations and statements, followed by a closing }.
So you can write:
for (i = 0; i < 10; i ++)
{
     printf("i = %d\n", i);
}

but the braces are part of the syntax of the compound statement, not of the for statement. The above may also be written as:
for (i = 0; i < 10; i ++)
     printf("i = %d\n", i);

or even:
for (i = 0; i < 10; i ++) printf("i = %d\n", i);

As a matter of style, I personally prefer to always use a compound statement as the controlled statement of a for (or if, or while, etc.), because (a) it's easier to be consistent, and (b) it's more maintainable; if I want to add a second statement before or after the printf, then the braces are already there.
One thing to watch out for: if you accidentally write:
for (i = 0; i < 10; i ++);  /* extra semicolon */
{
     printf("i = %d\n", i);
}

that's still perfectly legal -- but for controls only the empty statement consisting of that stray semicolon; the block following it is separate, and will be executed exactly once rather than 10 times.
Answer: The braces aren't strictly necessary; what you need is at exactly one (possibly empty) statement following the for. You can accomplish this by putting just a semi-colon, terminating an empty statement:
// It's a little more readable to put the semicolon on a line by itself
for (i=0; i<atual->numerChaves; i++)
;

or, as you did, by including an empty compound statement consisting of empty braces.
Comment: You need *exactly* one (possibly null) statement.


How to delete objects from two apps with the same model name?

Question: I have two apps news and article which both have exactly the same model name Comment:
class Comment(models.Model):
    author = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, default='', blank=True)
    body = models.TextField()
    post = models.ForeignKey(Photo)
    published = models.BooleanField(default=True)

Now, in a view I want to delete certain comments from both apps:
Comment.objects.filter(author=someauthor).delete()

How can I achieve that without changing the model names?
Answer: You can use import ... as ... so that both model names do not conflict:
from news.models import Comment as NewsComment
from article.models import Comment as ArticleComment

...

NewsComment.objects.filter(author=someauthor).delete()
ArticleComment.objects.filter(author=someauthor).delete()


Plotting the fitted values and their confidence intervals

Question: Can one one suggest any suitable plot that shows the observed values, their fitted values and  95% confidence intervals for the fitted values?
Comment: Almost a dup:  https://stats.stackexchange.com/questions/145062/visualising-uncertainty-in-slope-and-offset-for-a-regression-line/432775#432775
Answer: I usually see that information presented by using a curve for the predicted values and a shaded interval for the confidence interval.

For comparison here is a more literal interpretation of your request, which a individual marker and interval for each factor value.

I'm not aware of a good view of when there are multiple factors. The confidence intervals really belong with the factors and not the response (different factor values could produce the same predicted response value but with different confidence intervals). I suppose you could treat the factors categorically and plot each factor combination separately. Here's a try at that, rotated to make it a little easier to read the four factor values.
Comment: Out of curiosity, what software was used to generate these plots?
Comment: @chl I used [JMP](http://jmp.com) on a Mac, a product I help develop.


Re-submit form after confirmed AJAX form

Question: I have a form with submit AJAX button. When clicking this button, it calls function callbackAjax(). In this function callback, I checked a condition A to show a warning dialog if A is FALSE. The warning dialog has a message and two buttons, Confirm and Cancel. Cancel action will close dialog and do nothing. Confirm action will continue doing the callback function with condition A is true.
function renderForm($form, $form_state) {
  $form['submit'] = array(
    '#type'  => 'submit',
    '#ajax'  => array(
      'callback' => 'callbackAjax',
    ),
  );
}

function callbackAjax($form, &$form_state) {
  if (!$condition) {
    // Show dialog with confirm button
    // If confirmed, doing code in else clause
  }
  else {
    // Save data
  }
}

Please tell me how to re-submit form to save data after I clicked button Confirm which be rendered from AJAX callback?
I tried to set button Confirm as same as Submit button from main from, to call AJAX again, but it shows error.
Thanks for your help.
Comment: why don't you do it in validate?
Comment: Hi Namari, it is not actually a validation. I want to show confirmation dialog with a warning, which does not stop user action with form_set_error. User can decide to continue his action even if the condition is FALSE. The condition checker must not be in javascript.
Answer: I found the solution, at least it worked in my case. I want to share if someone need it.
function renderForm($form, $form_state) {
  $form['submit'] = array(
    '#type'  => 'submit',
    '#ajax'  => array(
      'callback' => 'callbackAjax',
    ),
  );
}

function callbackAjax($form, &$form_state) {
  if (empty($form['#skip_validate']) && !$condition) {
    // Show dialog with confirm button
    // If confirmed, doing code in else clause
    $confirm_form = drupal_get_form('renderConfirmForm', $form, $form_state);
    $commands[] = ajax_command_open_dialog($confirm_form);
  }
  else {
    // Save data
  }
  ...
}

function renderConfirmForm($form, &$form_state, $main_form, $main_form_state) {
  $form['continue'] = array(
    ...
    '#ajax'  => array(
      'callback' => 'renderConfirmFormCallback',
    ),
  );
  $form['close'] = ...;
  $main_form['#skip_validate'] = TRUE;
  $form['#main_form'] = $main_form;
  $form['#main_form_state'] = $main_form_state;
  return $form;
}

function renderConfirmFormCallback($form, &$form_state) {
  callbackAjax($form['#main_form'], $form['#main_form_state']);
}


Remove rows with duplicate value for a column in SQL

Question:
From the above table, I want to remove the rows that have the duplicate CODE column. Out of the duplicate rows, the row with the smallest ID_CHECK should be retained.
Output:
Comment: What is the DBMS you are using?
Answer: If I understand correctly, this should be your SQL query:
Select Names, Code, ID_CHECK
FROM
(
Select Names, Code, ID_CHECK,
ROW_NUMBER() OVER(Partition by Name,Code Order By ID_CHECK) as rnk
FROM table
)tmp
WHERE tmp.rnk=1;

Let me know if this works.


significant figures while multiplying measurements with just a number

Question: I am confused with the multiplication rules when it comes to multiply a decimal number with a number like 2. For example, if I want to calculate tidal force between the earth and the moon, I have a bunch of decimal numbers measured before such as mass, distance, radius etc. and there is also a number 2, which comes from the formula, i.e. the derivative of gravitational force (~1/r^2).
Significant figure rules state that I should round the result according to the number with the least number of significant figures. But it is 2 here, and if I apply it, I lose a lot of accuracy in the result.
What do you do in such calculations? Is it Ok to ignore the significance of 2 here?
Thanks
Comment: The 2 in this equation is exact, so it has as many significant figures as you want.
Answer: The rule refers to numbers that appear as a consequence of measures. In general, the $2$ and other exponents that appear in formulas are considered exact, as one usually operates on the assumption that the formula is accurate.
If one is willing to nitpick, one can discuss whether the $2$ in that exponent is really the best we can do, and physicists have measured up to what extent it is a two or not. In most cases the accepted error is very small (say, in 15${\rm th}$ digit) so it is harmless not to consider it.


SQL Server Report Server (SSRS) via WCF: HTTP request is unauthorized with client authentication scheme 'Ntlm'

Question: I have a .Net Core 3.1 application which is trying to connect to a SQL Server Report Server via WCF, in order to programmatically generate reports on demand.
But the program is not able to authenticate against the Report Server.
Here is the relevant program code:
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxReceivedMessageSize = 10485760; //10MB limit

// Create the execution service SOAP Client
var rsExec = new ReportExecutionServiceSoapClient(
    binding,
    new EndpointAddress("http://my-ssrs/ReportServer")
);

// Setup access credentials.
var clientCredentials = new NetworkCredential(
    "MyReportServerUserName",
    "MyReportServerPassword",
    "."
);
if (rsExec.ClientCredentials != null)
{
    rsExec.ClientCredentials.Windows.AllowedImpersonationLevel =
        System.Security.Principal.TokenImpersonationLevel.Impersonation;

    rsExec.ClientCredentials.Windows.ClientCredential = clientCredentials;
}

// ************************************************
// Get following Exception when next line executes.
// ************************************************
await rsExec.LoadReportAsync(null, "/path-to/my-report", null);

When the last line ("rsExec.LoadReportAsync") is executed, I get the following exception:
The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'NTLM'.

The Report Server is on the same Windows Domain.
After some research, I've tried changing the ClientCredentialType = HttpClientCredentialType.Windows but this generated a different exception, as follows:
The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'.

Does anyone have any suggestions about what I might try?
Comment: This link may help you: https://social.msdn.microsoft.com/Forums/en-US/f458b52c-03d1-46c6-b502-8c8966035bae/the-http-request-is-unauthorized-with-client-authentication-scheme-ntlm-the-authentication-header?forum=sqlreportingservices
Answer: Had the same problem. Solved it by additionally setting the proxy credential type:
binding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.Ntlm;


Interpreting coefficients when dependent variable is a fraction/proportion?

Question: I'm a little confused about how to interpret coefficients when the dependent variable is a proportion/fraction and the independent variables are absolute numbers. For example, let's say I have a regression of the following form:
share of villages with roads = a +b*(money invested by government) +e , where investment is in USD.
In this case, how will I interpret b coefficient? If investment increases by 1 USD, does the share of villages increase by b percent? b percentage points? b/100 percent?
Answer: In general, b tells you how many units y changes when x changes by 1 unit. Therefore, in your setting, if Gov investment increases by +1 USD, then the share of villages with roads increases by b.
You have to be careful about what measures/transformations you are using, and think about which one gives you a (more) meaningful interpretation. Also, beware of heteroskedasticity!
As a side note, the interpretation of b changes when logs are used. In particular:

if y is in levels and x is in logs, then b/100 is the units change in y when x changes by 1%.
if y is in logs and x is in levels, then b is the % change in y when x changes by 1 unit.
if y is in logs and x is in logs, then b is the % change in y when x changes by 1%.


Adding markers from Google Maps in Asynctask

Question: I want to add a marker to Google Maps after I've done something in AsyncTask.
However, when I attempt to add a marker onPostExecute after the operation,
An error will occur:
<code> java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
</code>
I searched for this problem, but it didn't help.
How do I add a marker inside OnPostExecute in Asyncask?
This is an arrangement of my code. It works normally until DoInBackground.
<code> public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mMap;
Document doc = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(final GoogleMap googleMap) {
    GetXMLTask task = new GetXMLTask(getApplicationContext());
    task.execute("http://openapi.its.go.kr:8081/api/NCCTVInfo?key=1526041502162&ReqType=2&MinX=" + 126 + "&MaxX=" + 127 + "&MinY=" + 35 + "&MaxY=" + 38 + "&type=ex");
}

@SuppressLint("NewApi")
private class GetXMLTask extends AsyncTask<String, Void, Document> {

    public GetXMLTask(Context applicationContext) {
    }

    @Override
    protected Document doInBackground(String... urls) {
        URL url;

        try {
        } catch (Exception e) {
        }
        return doc;
    }

    @Override
    protected void onPostExecute(Document doc) {
        MarkerOptions makerOptions = new MarkerOptions();
        makerOptions
                .position(new LatLng(0, 0))
                .title("title");
       mMap.addMarker(makerOptions);  //<=====ERROR=====
        }
    }
}
</code>
Answer: mMap object didn't set anything. So it will return null. You can set like that:
<code>@Override
public void onMapReady(final GoogleMap googleMap) {
    mMap = googleMap;
    GetXMLTask task = new GetXMLTask(getApplicationContext());
    task.execute("http://openapi.its.go.kr:8081/api/NCCTVInfo?key=1526041502162&ReqType=2&MinX=" + 126 + "&MaxX=" + 127 + "&MinY=" + 35 + "&MaxY=" + 38 + "&type=ex");
}
</code>


NServiceBus worker unregistration not working

Question: I'm trying to unregister a worker node as described here, but the procedure doesn't seem to work correctly. If the distributor has any control messages related to the disconnecting worker when running the unregistration script, next time messages come in, it will consume those (effectively sending more work to the node). It's only afterwards that the distributor will reject control messages coming from the node.
Has anyone got this to work correctly = the worker should not receive any new messages RIGHT AFTER unregistration?
Answer: What you describe is the intended behaviour for the unregister operation. It was designed and implemented like that.
It does not actively remove the existing ready messages for the worker from the distributors storage queue. It only makes sure that the worker will not send any new ready messages back to, and thus request more work from, the distributor after the unregister.
Comment: So when is it safe to stop the worker for maintenance, making sure there's no messages in its queue? Our requirement is that we can't delay message processing while we service the worker (5 mins or so)