How do I access a field value in the $row variable in a field view theme template?

Question: I'm overriding a field template for one of my views and I want to be able to access another field value from the $row variable. The documentation on the template file shows this:

When fetching output from the $row, this construct should be used:
  $data = $row->{$field->field_alias}

My field is called field_calendar_title, but the following doesn't work as expected:
$row->{$field->field_calendar_title}

I get the following error:

Fatal error: Cannot access empty property...

Is the field "alias" different from the name of the field in the content type?
"Cleansed" output from var_dump of $row:
stdClass Object
(
    [node_title] => ...
    [nid] => 568
    [field_data_field_performance_date_delta] => 0
    [field_data_field_performance_date_language] => und
    [field_data_field_performance_date_bundle] => event
    [field_data_field_performance_date_field_performance_date_val] => 2012-03-02 19:00:00
    [field_data_field_performance_date_node_entity_type] => node
    [_field_data] => Array
        (
            [nid] => Array
                (
                    [entity_type] => node
                    [entity] => stdClass Object
                        (
                            [vid] => 878
                            [uid] => 0
                            [title] => ...
                            [log] =>
                            [status] => 1
                            [comment] => 0
                            [promote] => 0
                            [sticky] => 0
                            [nid] => 568
                            [type] => event
                            [language] => und
                            [created] => 1329332968
                            [changed] => 1331836509
                            [tnid] => 0
                            [translate] => 0
                            [revision_timestamp] => 1331836509
                            [revision_uid] => 1
                            [body] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => ...
                                                    [summary] => ...
                                                    [safe_summary] => ...
                                                )
                                        )
                                )
                                [field_resident_company] => Array ( [und] => Array ( [0] => Array ( [tid] => 3 ) ) )
                                [field_series] => Array ( [und] => Array ( [0] => Array ( [tid] => 36 ) ) )
                                [field_venue] => Array ( )
                                [field_rotator_image] => Array ( )
                                [field_exclude] => Array ( [und] => Array ( [0] => Array ( [value] => 0 ) ) )
                                [field_performance_image] => Array ( )
                                [field_premiere] => Array ( [und] => Array ( [0] => Array ( [value] => 1330714800 [timezone] => UTC [timezone_db] => UTC [date_type] => datestamp ) ) )
                                [field_closing] => Array ( [und] => Array ( [0] => Array ( [value] => 1330714800 [timezone] => UTC [timezone_db] => UTC [date_type] => datestamp ) ) )
                                [field_exclude_update] => Array ( [und] => Array ( [0] => Array ( [value] => 0 ) ) )
                                [field_performance_date] => Array ( [und] => Array ( [0] => Array ( [value] => 2012-03-02 19:00:00 [timezone] => UTC [timezone_db] => UTC [date_type] => datetime ) ) )
                                [field_performance_id] => Array ( [und] => Array ( [0] => Array ( [value] => 1436 [format] => [safe_value] => 1436 ) ) ) [field_event_status] => Array ( [und] => Array ( [0] => Array ( [value] => open ) ) )
                                [field_calendar_title] => Array ( [und] => Array ( [0] => Array ( [value] => PSYCHIC EXP [format] => [safe_value] => PSYCHIC EXP ) ) )
                                ...
                        )
)

Answer: From the looks of the var_dump you should be able to find your field value with this:
$row->_field_data['nid']['entity']->field_calendar_title['und'][0]['value'];

I really hope there's a better way than that though!
Comment: Sorry I corrected the syntax in my question and it still didn't work. Tried this too and no luck $row->field_calendar_title;
Comment: Hmmm...I think from the error message `$field` is undefined...have you tried doing a `var_dump($row)` to see what's actually in there? You'll probably spot the field you're after pretty easily :)
Comment: Hey Clive, yup I did a var_dump and the field exists under _field_data along with the rest of the field values...
Comment: If you can pop the output of `var_dump($row)` into your question as an edit I might be able to spot the value you need
Comment: @SomethingOn I've updated the answer, it's not pretty but it should work :)
Answer: A simpler approach:
$rendered_field = $view->render_field($fieldname, $view->row_index);

Here, $fieldname is the original (not the view-aliased) fieldname, e.g. 'field_myfield'.
Answer: Maybe a bit late, but for future reference here's my answer:
The description is pretty vague, but you should literally use:
$row->{$field->field_alias}
In your template file it is also noted that:
Variables available:

$view: The view object
$field: The field handler object that can process the input
$row: The raw SQL result that can be used
$output: The processed output that will normally be used.

In $field there's a field called field_alias. So $row->{$field->field_alias} is actually pointing to, in your case, field_calendar_title.
Try making a var_dump of $field and you'll see for yourself.
Hope this helps anyone coming across this post.
Gerben
Comment: It's never too late, still trending question. 1. I don't want to use monstrous @Clive's example, though it works 2. I do want to understand how to work with given variables: $row, $filed, etc. Your suggestion returns only a number (maybe nid or smth), but how can I access precisely my field. What if I have two different fields that I want to get?
Answer: The simplest way is : $fields["field_name"]->content; Where field_name -> cck field name.
Hope that will help !!
Cheers ! Raj
Comment: there is no `$fields` variable available in field template


What causes 'You are not authorized to access this page' during create/edit of any menu?

Question: I got a very odd error for "new" admin user on Drupal 7. There are a few admin users in this site but only the "new" one that is unable to create, edit or list links on any menu. The error message is like so:

You are not authorized to access this page

But this new admin user has the same role as other admins.
Does anyone know what can causing this?
Comment: We cannot debug a site to which we don't have access. Listing all the possible causes, hoping to guess what happened, is not the purpose of a Q&A site.
Answer: Make sure you flush caches and rebuild permissions (from status page) and run cron.
If these fail check if any custom module implements hook_node_access
A rogue Rule could also be the culprit
Comment: I really afraid of rebuild permission. Will this causes anything during and after the process?
Comment: The site currently has over 5000 permissions in use.


Como trocar informações em modo full-duplex?

Question: Observe os dois códigos abaixo:
Cliente.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define SRV_ADDR "127.0.0.1"
#define SRV_PORT "9009"

int make_socket(void){

    int ecode, sockfd;

    struct addrinfo *results=NULL, hints;

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_family=AF_INET;
    hints.ai_socktype=SOCK_STREAM;
    hints.ai_protocol=IPPROTO_TCP;

    if((ecode=getaddrinfo(SRV_ADDR, SRV_PORT, &hints, &results))!=0){

        sockfd=-1;

    }else{

        struct addrinfo *it=NULL;

        for(it=results; it!=NULL; it=it->ai_next){

            if((sockfd=socket(it->ai_family, it->ai_socktype, it->ai_protocol))==-1){

                continue;
            }

            if(connect(sockfd, it->ai_addr, it->ai_addrlen)==0){

                break;
            }

            close(sockfd);
        }

        freeaddrinfo(results);

        if(it==NULL){

            sockfd=-1;
        }
    }

    return sockfd;
}

short get_msg(char *msg, size_t n){

    int rv;

    if(fgets(msg, n, stdin)!=NULL){

        size_t len=strlen(msg);

        msg[len-1]='\0'; //elimina o \n

        rv=0;

    }else{

        rv=-1;
    }

    return rv;
}

int main(void){

    int sockfd=make_socket();

    if(sockfd!=-1){

        short rv;
        char msg[101];

        printf("\n");

        do{

            do{

                printf("Você >");

                if((rv=get_msg(msg, 101))!=0){

                    printf("\n* Falha na leitura!");
                    printf("\n  |.__Escreva a mensagem novamente.\n\n");
                }

                send(sockfd, msg, 101, 0);

            }while(rv!=0);

            if(strcmp(msg, "!exit")!=0){

                recv(sockfd, msg, 101, 0);

                printf("Estranho: %s\n", msg);
            }

        }while(strcmp(msg, "!exit")!=0);

        close(sockfd);
    }

    return 0;
}

Servidor.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int make_socket(void){

    int sockfd;
    struct addrinfo *results=NULL, hints;

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags=AI_PASSIVE;
    hints.ai_family=AF_INET;
    hints.ai_socktype=SOCK_STREAM;
    hints.ai_protocol=IPPROTO_TCP;

    if(getaddrinfo(NULL, "9009", &hints, &results)!=0){

         sockfd=-1;

    }else{

          struct addrinfo *it=NULL;

          for(it=results; it!=NULL; it=it->ai_next){

              if((sockfd=socket(it->ai_family, it->ai_socktype, it->ai_protocol))==-1){

                  continue;
              }

              if(bind(sockfd, it->ai_addr, it->ai_addrlen)==0){

                  break;
              }

              close(sockfd);
          }

          freeaddrinfo(results);

          if(it==NULL){

              sockfd=-1;

          }else{

              if(listen(sockfd, 1)==-1){

                  sockfd=-1;
              }
          }
    }

    return sockfd;
}

short get_msg(char *msg, size_t n){

    int rv;

    if(fgets(msg, n, stdin)!=NULL){

        size_t len=strlen(msg);

        msg[len-1]='\0'; //elimina o \n

        rv=0;

    }else{

        rv=-1;
    }

    return rv;
}

int main(void){

    int sockfd, csockfd;

    if((sockfd=make_socket())!=-1){

        if((csockfd=accept(sockfd, NULL, NULL))!=-1){

            short rv;
            char msg[101];

            printf("\n");

            do{

                recv(csockfd, msg, 101, 0);

                printf("Estranho: %s\n", msg);

                if(strcmp(msg, "!exit")!=0){

                    do{

                        printf("Você >");

                        if((rv=get_msg(msg, 101))!=0){

                            printf("\n* Falha na leitura!");
                            printf("\n  |.__Escreva a mensagem novamente.\n\n");
                        }

                        send(csockfd, msg, 101, 0);

                    }while(rv!=0);
                }

            }while(strcmp(msg, "!exit")!=0);

            close(csockfd);
        }

        close(sockfd);
    }

    return 0;
}

Agora observe a execução de ambos:
Cliente:
t-002@localhost:~/Documents/C$ gcc -Wall client.c -o client
t-002@localhost:~/Documents/C$ ./client

Você >Olá
Estranho: Não posso conversar agora :(
Você >Okay amigo :(
Estranho: !exit

Servidor:
t-002@localhost:~/Documents/C$ gcc -Wall server.c -o server
t-002@localhost:~/Documents/C$ ./server

Estranho: Olá
Você >Não posso conversar agora :(
Estranho: Okay amigo :(
Você >!exit

Notou que a comunicação entre o servidor e o cliente foi feita em sentido duplo, porém não de forma simutânea? Pois bem, essa forma de troca de dados se chama half-duplex. Um exemplo mais prático disso são os walkie-talkies:

Aqui observa-se o seguinte: Enquanto um dos walkie-talkies fala o outro só poderá ouvir, ou seja, a transmissão de dados ocorre em função do tempo. É quase a mesma coisa que o meu servidor e cliente lá em cima, porém lá foi pré-estabelecido quem falava primeiro e ainda por cima era necessário esperar o outro responder para poder falar de volta.
Portanto, venho com a seguinte dúvida: É possível estabelecer uma conexão entre um cliente e um servidor escritos/programados em C onde os dados são trocados de forma dupla ou bidirecional simutânea, ou seja, em modo full-duplex?
Comment: De uma olhada nesse projeto [https://github.com/.../full-duplex-chat-tcp-ip](https://github.com/apsrcreatix/Socket-Programming-With-C/tree/master/07-full-duplex-chat-tcp-ip) acredito que atenda sua especificação.
Answer: Uma maneira de fazer isso é criar duas threads (ou dois processos filhos no Unix/Linux), sendo que uma thread faz recepção e outra faz envio.
Pseudo-código de 1 servidor que trata apenas 1 conexão e depois finaliza, mas faz send e receive "simultâneos":
1. cria socket
2. faz bind
3. faz listen
4. faz accept
5. cria thread de recepção
6. cria thread de envio
7. fica parado na thread principal (por exemplo, faz um getchar)

Tanto a thread de recepção quanto a thread de envio utiliza o mesmo socket retornado pela função accept.
Thread de recepção:
1. faz receive
2. se retornou erro ou fim de conexão, finaliza programa (chama exit)
3. não foi erro nem fim da conexão, então processa dados recebidos
4. volta para 1

Thread de envio:
1. gera dados a serem enviados
2. faz send
3. se retornou erro, então finaliza programa (chama exit)
4. volta para 1

Uma outra maneira, e provavelmente a mais comum, de fazer isso é utilizando programação por eventos.
Neste caso, utiliza-se uma função da pilha TCP chamada select (que na prática hoje é obsoleta), ou uma função do s.o. (epoll no Linux, ou GetQueuedCompletionStatus no Windows) para verificar se existe algum evento pendente no socket da conexão.
Este "evento" pode ser relacionado a recepção ou a envio.
No Linux um evento de recepção significa que pode ser feita uma recepção no socket em questão, que pode (mas não é garantido) ter dados prontos para serem recebidos. E um evento de envio significa que pode (mas também não é garantido) ser feito um send no socket em questão. Como não existe garantia de que pode ser tentada uma operação de envio ou recepção, utiliza-se o socket em modo "não-blocante", assim na recepção ou no envio o programa não fica bloqueado para esperar que a operação seja efetuada.
No Linux o funcionamento é "reativo". Isto é, o programa pergunta para o s.o. (através do select ou epoll) se pode fazer uma operação de recepção ou envio, e quando recebe um evento do s.o. então o programa tenta efetuar a operação.
No Windows, ao contrário, o funcionamento é "proativo". O programa cria a conexão preparada para trabalhar com IOCP, e depois, efetua as operações. O programa não fica parado esperando a operação terminar. O programa sabe que a operação terminou quando recebe um evento através da função GetQueuedCompletionStatus referente à operação que foi iniciada anteriormente.
Na prática, tanto no Linux quanto no Windows a programação por eventos é feita usando threads, tendo uma thread ou mais reservadas para tratamento dos eventos recebidos através do epoll ou GetQueuedCompletionStatus.
Neste link (achado no Google) encontra-se um exemplo simples de uso de epoll sem threads adicionais em Linux, e neste outro link uma receita e um exemplo passo a passo de um server (também não usando threads adicionais) com IOCP em Windows.


How do I push to a new GitHub repo without including history?

Question: I've been working on a project locally for some time, and it's finally at the point that I'd like to upload it to GitHub to share.  Early versions of the project contained hard-coded database passwords that I'd like to avoid putting on GitHub, though.
Is there a way for me to push a "shallow" version of the repo -- just the files as they are now, without history -- to GitHub?  Something like git clone --depth 1 would be nice, except it seems like you can't "push clone" from localhost to GitHub, and GitHub doesn't seem to have an interface that lets me "pull clone" in the normal way.
I've spent a couple of hours doing web searches for "git push to github without history", "git push to github as shallow clone", "git push clone to github", etc., but nothing comes up that I can decipher as relevant to my problem.  The GitHub docs for this warn against committing passwords and things, but the only advice they give is to remove files, not history.  Similarly, the closest question I can find on Stack Overflow is this question whose answers also focus on deleting files.  I don't want this: I want to keep the files, I just want to remove the history that they once contained hard-coded passwords.
Ideally, I would be able to "shallow push" the project from localhost to GitHub, losing previous history but tracking history from that point forward.  Is this possible?
Comment: git repos inherently include history.  The only way to do that is to rewrite history using `git rebase`.
Comment: Are you wanting to preserve the history locally?  You could always squash everything into one commit and use that.
Comment: @Mobius Yes, I'd like to preserve history locally.
Answer: One thing you can do is copy the directory to a new folder and remove your .git directory. Then you can initialize the repository as if it were fresh:
git init
git add .
git commit -m "Genesis."
git remote add origin <remote repository URL>
git push -u origin master

This way you can preserve the history in another directory if you ever find the need to look something up.
Comment: In this case, you would lose any ability of interacting with the new from the old.  However, you should be able to create a `patch` if you needed to.
Comment: In a case like this, can I push a diff from the original local repo to the GitHub repo?
Answer: There is no such thing as a "shallow push".  There are shallow clones, and you could make a shallow clone and then push to it, but you can't make GitHub itself host a shallow clone.  If you could get GitHub to host a shallow clone, it looks like you could do what you want that way: I made one on my own server and did a few simple experiments that seemed to work (but I was not very thorough).
I also tested trying to push from a shallow clone to a new, empty GitHub repository.  That was refused:
 ! [remote rejected] master -> master (shallow update not allowed)

Hence, if you want to use GitHub, you'll have to make a new (separate and independent) repository.  This new repository is not compatible with your existing repository.
Answer: To add to @codenamev answer this is what worked for me

clone down repo, rename it
create new empty repo in GitHub, then in cloned down repo run:

  git init
  git add .
  git commit -m "create new template"
  git remote set-url origin firstname.lastname@example.com:<your organisation/repo>.git
  git push -u origin main <or other branch>

in GitHub go to settings and set newly pushed up branch to default branch


Check for compactness of subsets $A =\{(x, y) :xy = 1\}$ $B =\{(x, y) :x^2y^2 = 1\}$ of $\mathbb{R}^2$.

Question: I am working on following mathematical problem:
Check for compactness of following subets of $\mathbb{R}^2$.
$A =\{(x, y) :xy = 1\}$
$B =\{(x, y) :x^2y^2 = 1\}$
My attempt: I know that all I have to check whether subsets $A$ and $B$ are closed and bounded in $\mathbb{R}^2$ or not?
Checking for boundedness: Can we say that subsets A and B are not bounded in $\mathbb{R}^2$ since they contains points $(n, 1/n)$, where $x  = n \in \mathbb{N}$ tends to infinity. I am not entirely confident about the correctness of my approach. Could you please review my approach and let me know  if I am on the right track or not?
Additionally, if you have any alternative approaches to suggest, I would greatly appreciate your insights.
Checking for closedness
I feel both sets are closed but how can I proved that?
PS: I have asked the same question before, but this time I have some additional doubts regarding my approach. Thank you very much
Answer: Yes, both sets are closed and both sets are not bounded, hence they are not compact.
For the boundedness, your idea works. $(n,1/n)$ belongs to $A$ for all $n$, hence the norm of the elements of $A$ is not bounded. Similarly for $B$ with the same counterexample.
For closedness, just notice that $A=f^{-1}(\{1\})$ where $f:\mathbb R^2\to \mathbb R$ is the map $f(x,y):=xy$, which is continuous. Again, similarly for $B$ with the map $g(x,y):=x^2y^2$.
Comment: Thank you so much for clearing my doubt.


Urban Airship SDK Integration in iOS & push notification

Question: We have integrated Urban SDK using these guidelines.
We have tried to check the push notification using ad hoc profile where we have set below values in AirshipConfig.plist

inProduction=YES
productionAppKey=OUR PRODUCTION KEY
productionAppSecret= OUR PRODUCTION SECRET

Please check the below code which we have implemented in the AppDelegate file of project.

-(void) applicationDidFinishLaunching: (UIApplication *)application
{
.
.
.
.
 UAConfig *config = [UAConfig defaultConfig];
 config.automaticSetupEnabled=NO;
 [UAirship takeOff:config];

 if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        NSLog(@"------------REGISTER DEVICE------------: >= 8");
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    }
    else
    {
        NSLog(@"------------REGISTER DEVICE------------: <8 ");
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
.
.
.
.

}

#pragma mark Remote Notification methods

-(void) application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken // Device Registration
{
    [[UAirship push] appRegisteredForRemoteNotificationsWithDeviceToken:devToken];

}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [[UAirship push] appRegisteredUserNotificationSettings];

}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
   NSLog(@"%@", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"NOTIFICATION------------ didReceiveRemoteNotification ------------ %@", userInfo);
    [[UAirship push] appReceivedRemoteNotification:userInfo applicationState:application.applicationState];
}

When we are trying to send the notification to the registered device token, the server shows that device token as INACTIVE Device token.
Please show me what should I do for this.
Comment: Are you actually IN PRODUCTION or are you testing on your device from Xcode? If not, set it to false.
Comment: @QuentinHayot , i have created the build using adhoc profile and testing it in real device.
Comment: But it's still testing, it's not a release build, so you have to use the Development mode.
Comment: Actully in AirshipConfig.plist there are 5 key values.

inProduction,developmentAppKey,developmentAppSecret,productionAppKey,productionAppSecret

So if i am using adhoc profile , i should use
inProduction = true ,productionAppKey= key,productionAppSecret=secret. Isnt it ?
Comment: are you making this app for the app store ?
Comment: @QuentinHayot : I have tried with Development mode also. its still shows inactive
Answer: So, first it looks like you are missing a few app delegate methods.
Urban Airship handles APNS registration. Remove your manual registration calls as UA will just override them, and instead, enable notifications with [UAirship push].userPushNotificationsEnabled = YES;. It should prompt the user to accept notifications, and then the Urban Airship channel should be opted in.


Select option selecionado

Question: Eu preciso deixar o select option selecionado de acordo com o campo gravado no mysql. O formulário é para editar pos isso ele apresenta os campos disponíveis com o foreach.
Ex:
 <select name="segurado"  >
    <option value=""></option>
    <?php foreach ($result as $rs) { ?>
        <option value="<?php echo $rs["nome"]; ?>"><?php echo $rs["nome"]; ?></option>
    <?php } ?>
</select>

Desta forma o select mostra os campos da tabela segurados mas eu quero deixar o campo do registro selecionado para edição selecionado.

Talvez eu não tenha me feito entender direito: eu recupero o campo gravado no mysql e consigo colocá-lo no label do select mas não é esta a solução. Mas isso mostra que a variável para comparar é correta, ou seja a que foi gravada na tabela quando do cadastro. Como eu quero editar o registro, preciso que este campo gravado e recuperado seja setado como selected no options, que por sua vez está sendo alimentado pelo foreach e criando os elementos da mesma forma que no cadastro. Abaixo o exemplo de como preencho o option:
                            $sql = "SELECT * FROM seguradoras ORDER BY nome";
                            try {
                                $stmt = $DB->prepare($sql);
                                $stmt->execute();
                                $results = $stmt->fetchAll();
                            } catch (Exception $ex) {
                                echo($ex->getMessage());
                            }

Com ele preenchido, quero que ele mostre a variável que vem do banco no caso $residencial->seguradora
Melhorou galera ?
Answer: Quando atender a condição que você quer selecionar
coloque  o <option selected>
<select name="segurado"  >
    <option value=""></option>
    <?php foreach ($result as $rs) { ?>
        <option value="<?php echo $rs["nome"]; ?>" <?php if($rs["minha_opcao_selecionada"] === true ){ echo "selected"}  ?>  ><?php echo $rs["nome"]; ?></option>
    <?php } ?>
</select>

Comment: Zoy, o seu código está apresentando um erro de sintaxe mas não consegui identificar.
Comment: Já descobri. Muito obrigado.
Comment: Ficou assim:" segurado == $rs["nome"] ) { echo "selected";}  ?>  >    Faltava o ponto e vírgula após o echo "selected"  Valeu Zoy, muito obrigado.
Answer: Supondo que você abastece seu formulário com com entradas na tabela você poderia ter um campo especifico para isto tipo select com on ou off ou por verificando o item mesmo exemplos:
<?php
    // sua lógica de acesso ao banco...
?>
<select name="segurado">
    <option value=""></option>
    <?php
        foreach ($result as $rs) {
            // caso use um campo especifico
            if ( $rs['select'] === 'on' ) {
                echo '<option value="' . $rs['nome'] . '" selected="true">' . $rs['nome'] .'</option>';
            } else {
                echo '<option value="' . $rs['nome'] . '">' . $rs['nome'] .'</option>';
            }
            // ou pelo item mesmo
            if ( $rs['nome_do_item'] ) {
                echo '<option value="' . $rs['nome'] . '" selected="true">' . $rs['nome'] .'</option>';
            } else {
                echo '<option value="' . $rs['nome'] . '">' . $rs['nome'] .'</option>';
            }
        }
    ?>
</select>

Comment: Lauro, vou tentar mais um pouco antes de optar por criar o campo com on off
Answer: Se quiseres uma opção compacta aqui tens uma:
<select name="segurado">
    <option value=""></option>
    <?php foreach ($result as $rs): ?>
        <option value="<?=$rs['nome']?>" <?= ($rs['select'] == 'on') ?  'selected' : '' ?> ><?= $rs['nome'] ?></option>
    <?php endforeach; ?>
</select>

Comment: 13dev, o seu código está selecionando o primeiro registro da tabela e duplicando todos.
Comment: editado tenta agora assim
Answer: Bom, alterando o código e substituindo as variáveis finalmente consegui o resultado que queria:
<?php foreach ($results as $rs) { ?>
    <option value="<?php echo $rs["nome"]; ?>" <?php if ($residencial->seguradora == $rs["nome"] ) { echo "selected";}  ?>  ><?php echo $rs["nome"]; ?></option>
<?php } ?>

Muito obrigado a todos e um forte abraço !

Select option selecionado


Remove "submitted by" text on teaser only

Question: I read on How do I remove the "submitted by" text on node display? where you can remove this in the content type settings for the node itself, but is there a way to only change the teaser so it does not display "submitted by" text?
I'm looking for a non-preprocess function or module way to do this; I can't use my theme to deal with it.
I was hoping to avoid using Computed Field module for something so trivial.
Comment: Display Suite will do the trick.
Answer: That setting is checked and the information added in template_preprocess_node().
Which means that there is no other way than a preprocess function to change this. However, there is nothing stopping you from adding a preprocess function to a module, that works perfectly fine. You just need to make sure that your module runs after node.module by setting the weight in the system table to something higher than node (probably 0).
Code example by will:
In your .install file:
db_update('system')
  ->fields(array('weight' => 1))
  ->condition('type' => 'module')
  ->condition('name' => 'moduleName')
  ->execute();

And then in the .module file:
function moduleName_preprocess_node(&$variables) {
  // Do not display post information on teasers
  if ($variables['teaser']) {
    $variables['display_submitted'] = FALSE;
  }
}

Comment: thanks so much! i didn't realize it was so easy to set the weight in the system table. great stuff. the regex solution is nice as well but i usually save that type of thing until the last resort. much appreciated. i'll post some code to make this more clear
Comment: posting code sounds great, feel free to simply edit my answer and put it in there.
Comment: so to follow up, just put this in your moduleName_install function in your moduleName.install file: `db_query("UPDATE {system} SET weight = [1] WHERE type = 'module' AND name = 'moduleName'");` and this in your moduleName.module: `function moduleName_preprocess_node(&$variables) {
 // Do not display post information only on teasers
  $node = $variables['node'];
  if ($variables['teaser'])  { $variables['display_submitted'] = FALSE; }
}`
Answer: If you're comfortable with regex you could use hook_node_view to add a '#post_render' variable to the $node->content:
function myModule_node_view($node,$view_mode){
  if($view_mode=='teaser'){
    $node->content['#post_render'][]='myModule_post_render_teaser';
  }
}
function myModule_post_render_teaser($rendered){
  $regex='';//This selector would have to grab the rendered "meta submitted" div
  return preg_replace(etc. etc.);
}

Comment: `$regex = '/]*>[^<\/div>].*<\/div>/imsU';`
Comment: Why would you want to do that with a regex when it can be done easily with a preprocess function (which can be in a module too)? :)
Comment: "I'm looking for a non-preprocess function" :) I agree preprocess is the best way to handle it, I was just catering to his request:)
Comment: On complex sites I frequently include two modules, one that has a high system weight and one with a low system weight, this would only be a viable solution if your module provides some function that needs to run before node.module... but to reiterate... Berdir has the right solution ;)


Suggestion on RAID configuration

Question:
Possible Duplicate:
What are the different widely used RAID levels and when should I consider them?

We are going to setup a storage solution for our security surveillance software. We are going to buy servers from http://www.hetzner.de and we would like to deploy RAID configuration using the following combination:
RAID CARD = MegaRAID SAS 9260-4i
HARD DISKS = 4 X 3TB, Seagate Constellation ES.2 ST33000650NS
We have two different requirements for two different servers (same hardware)
A.  Write jpeg image files ranging from 30KB to 100KB at a speed of 100 files per second. At the same time we also deleting the old imagery at the same speed.
B. Write 40MB video files 1MB/sec to 3MB/sec  and we divide this throughput into 100 files at a time. At the same time we also deleting the old imagery at the same speed.
In the past we have been observing disk performance issues on RAID 5 with different hardware. I would request you to give us advice on:

Appropriate RAID configuration(s) that suits our two requirements separately.
What possible I/O thought we can get on your suggested configuration.
Send us I/O benchmark data you may have with similar hardware.

Hardware Specs:
CPU : Intel® Core™ i7-3930K Hexacore
RAM : 64 GB DDR3
Mother board : EX 10: Intel DX79TO
Hard disks : 4X3TB Seagate Constellation ES.2 ST33000650NS
RAID CARD : LSI MegaRAID SAS 9260-4i
Operating System :windows 2008 (possibly 2012)
Comment: Benchmarking is something ***YOU*** need to do (it is a type of [capacity planning](http://serverfault.com/questions/384686/)) -- for the rest, the duplicate link should get you going in the right direction.  If you feel this question is not a duplicate please flesh it out a bit more (tell us something about the evaluation you did and what specific questions you have) and I'll reopen it.
Answer: I'm guessing you are using zoneminder (?)
I would (and had) placed RAID6 of 6 disks on my videoserver (22 cameras). Basically the speed of the disks is not a problem, while the security of failing is critical. RAID 6 protect you from loosing up to 2 disks... The optimization of deleting can be make trough the "options" menu in the ZM configuration menu. Just hit the option "delete files on background".
Just make sure you buy nice peace of disks (i choosed SAS drives). The differences here :
http://www.intel.com/support/motherboards/server/sb/CS-031831.htm
Answer: Dont forget to connect a BBU to the Raid Controller and enable write Cache. Performance wise, and especially because of your requirement running 100 congruent IOs, I would suggest SAS Drives because of significant lower AccessTime. But it also depends on your sapce requirements and allowed costs.
Raid10 writes faster as Raid5 but with 4 drives you can not have an Hot-Spare. Raid6 is the most failproof (especially with large disk) but is slower than Raid5. Still my Advice would be 4x15K SAS on Raid6, with BBU and write-cache on the Controller.
What is your backup plan, and how much HD space is required?

Suggestion on RAID configuration


Categorical independent variable and binary dependent variable

Question: Which test can I use for analyzing the effect of a categorical independent variable, such as preoperative ASA score (1/2/3/4), on a binary dependent variable, such as postoperative complication (yes/no)?
I know that the chi squared test is an option, but this test does not tell me if the significant difference lies between ASA 1 and ASA 2 or between ASA 2 and ASA 3,...
Is there a statistical test I can use to know between which independent categories the significant difference is situated?
Answer: You can use logistic regression with an ordinal predictor variable. By choosing the encoding system for the predictor, you can get the information presented in a useful form. Here is a useful UCLA page overview for different categorical encoding systems, using R (there are similar pages for other languages.) For your purposes, maybe a successive differences coding is natural. Below I will simulate some data (using R) and present analysis, coding in different ways.
But first, similar questions have been asked before, see Logistic regression? multiple categorical and ordinal values to predict binary outcome,   Encoding of categorical data/feature/predictor for binary classification
set.seed(7*11*13)
ncats <- 5
k <- 100
ordvar <- factor(rep(1:ncats, each=k), ordered=TRUE)
Y  <- rbinom(ncats*k, 1, rep(seq.int(from=0.1, to=0.9, len=ncats), each=k))
ordnum <- rep(1:ncats, each=k)
mydf <- data.frame(Y, ordvar, ordnum)

mod.ordvar0 <- glm(Y  ~ ordvar, family=binomial, data=mydf)

mod.ordvar1 <- glm(Y  ~ ordvar, family=binomial, data=mydf, contrasts=list(ordvar=MASS::contr.sdif))

mod.ordnum <- glm(Y  ~ ordnum + I(ordnum^2), family=binomial, data=mydf)

The first model we estimated used R's standard encoding for ordinal predictors, which is orthogonal polynomials:
 summary(mod.ordvar0)

Call:
glm(formula = Y ~ ordvar, family = binomial, data = mydf)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.1945  -0.8782   0.4343   0.7585   2.0200

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.1435     0.1183   1.213    0.225
ordvar.L      3.2513     0.3068  10.598   <2e-16 ***
ordvar.Q      0.1498     0.2805   0.534    0.593
ordvar.C      0.1612     0.2465   0.654    0.513
ordvar^4     -0.1442     0.2151  -0.670    0.503
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 692.35  on 499  degrees of freedom
Residual deviance: 514.22  on 495  degrees of freedom
AIC: 524.22

But I guess that often (and in your case ...) successive differences (comparing level $i+1$ with level $i$) is more informative:
summary(mod.ordvar1)

Call:
glm(formula = Y ~ ordvar, family = binomial, data = mydf, contrasts = list(ordvar = MASS::contr.sdif))

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.1945  -0.8782   0.4343   0.7585   2.0200

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.1435     0.1183   1.213 0.225046
ordvar2-1     1.1472     0.3666   3.130 0.001751 **
ordvar3-2     0.7138     0.2932   2.434 0.014920 *
ordvar4-3     1.1386     0.3055   3.727 0.000194 ***
ordvar5-4     1.2150     0.4188   2.901 0.003716 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 692.35  on 499  degrees of freedom
Residual deviance: 514.22  on 495  degrees of freedom
AIC: 524.22

But note that these two models are equivalent, they give exactly the same fitted probabilities. In mathematical thers, the only difference is in the choice of a basis for a vector space. The last model is not equivalent, it is a reduced model, using the ordinal levels as numeric, and fitting only a linear+quadratic model, so two less parameters:
summary(mod.ordnum)

Call:
glm(formula = Y ~ ordnum + I(ordnum^2), family = binomial, data = mydf)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.1697  -0.8215   0.4468   0.7548   1.9728

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.58216    0.58633  -4.404 1.06e-05 ***
ordnum       0.74624    0.43060   1.733   0.0831 .
I(ordnum^2)  0.04420    0.07192   0.615   0.5388
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 692.35  on 499  degrees of freedom
Residual deviance: 515.15  on 497  degrees of freedom
AIC: 521.15 ```


Indication of general usage of piano pedal

Question: Traditionally, "P" and "*" are used to indicate the use of sustain pedal for the piano, and the release of it, respectively.
However, in composing my own piece, I often want to indicate the player that the sustain pedal be used in playing the present passage, but I do not want to specify the detailed pedal marks, which is up to the player's interpretation, as well as depending on the instrument and sound effect of the venue.
I recall some composers, like Schumann and Brahms, use "con pedale" and "senza pedale", respectively, to indicate such intention: that pedal be used or not be used in general, but the execution is left the to player.
But there may arise other problems.
First, I feel some people may misunderstand and suppose that the pedal should be used throughout the passage, and there can be no time interval when the pedal is kept being released. (I don't think there will be people who think I forbid the change of pedal completely, though.)
Second, still some people may think that the pedal should not be used in the preceding passage and the following passage, but only the present passage.
What do you think it best to denote my intention of pedal usage?
Is my worry reasonable?
Comment: I don't think that it matters anything as most people use the pedal ad libitum.
Answer: No, no-one will assume 'con pedale' or similar means 'put it down and leave it down'.  In fact, when that special effect IS occasionally required, it can be quite hard to find a command that conveys the information!
But yes, if 'con pedale' occurs part-way through a piece, it might be taken to imply 'senza pedale' previously.  And that might be no bad thing!  Many pianists use FAR too much pedal.
Answer: In general, notate anything that is up to the performer as  "Ad lib[erandum]" .  In your case, perhaps   "con pedale ad lib."  would do the trick.
Comment: Really no need for the 'ad lib'.
Comment: Alternatively, to make it even simpler one may just write it in plain English: "Use pedal as desired".
Comment: I reckon most of us use pedal instinctively (once we've mastered the technique(s)), so unless it's for a specific effect, 'please yourself' will do!


Prove that $\mathbf{L}$ is almost a normal modal logic.

Question:
Suppose we have a logic $\mathbf{L}$ containing all the propositional tautologies and the formula $\square(p\wedge q)\leftrightarrow(\square p \wedge\square q)$, and it is  closed by Modus Ponens, Substitution and the following rule (R): if $\varphi\leftrightarrow\psi\in\mathbf{L}$ then $\square\varphi\leftrightarrow\square\psi\in\mathbf{L}$. Prove that $\square(p\to q)\to(\square p\to\square q)\in\mathbf{L}$.

I'm really stuck with this exercise. I'm used to propositional calculus, where Modus Ponens and Deduction Thereom are the main tools. Any help is appreciated.
Comment: You can start by observing that what you want to prove is equivalent to $(\Box (p\to q) \wedge \Box p) \to \Box q$, and moreover $p \wedge q$ is equivalent to $p \wedge (p \to q)$.
Comment: Are you sure that you have copied the exercise correctly? Because this claim is false, so it's not surprising that you cannot prove it. I suspect that the actual exercise has, or at any rate should have, $\Box (p \wedge q) \leftrightarrow (\Box p \wedge \Box q)$ instead of $\Box (p \wedge q) \rightarrow (\Box p \wedge \Box q)$.
Comment: Yes, you're  right! But I still don't know how to start :(
Comment: I think it is preferable to write $\operatorname{\square} \varphi$ (with "\operatorname{\square}" made into an alias for best practice ;) ) rather than $\square \varphi$.
Comment: In fact, you wish to show is that $\mathbf{L}$ satisfies the **Distribution Axiom**. Is that correct?
Answer: Since $\mathbf{L}$ contains all propositionnal tautologies, you have
$$ \Big(p \wedge (p \to q) \Big) \longleftrightarrow \Big(p \wedge q \Big) \in \mathbf{L}$$
whence $$ \Big(\operatorname{\square} p \wedge \operatorname{\square} (p\to q) \Big)  \longleftrightarrow \Big(\operatorname{\square} p \wedge \operatorname{\square} q \Big) \in \mathbf{L}$$
Since $\mathbf{L}$ is closed under Modus Ponens, we get the weakening :
$$ \Big(\operatorname{\square} p \wedge \operatorname{\square} (p\to q) \Big)  \longrightarrow \operatorname{\square} q $$
which is logically equivalent to the Distribution Axiom indeed :
$$\Big(\operatorname{\square} p \wedge \operatorname{\square} (p\to q) \Big)  \longrightarrow \operatorname{\square} q \equiv \operatorname{\square} (p\to q) \longrightarrow (\operatorname{\square} p \to \operatorname{\square} q)$$
Hence the conclusion since $\mathbf{L}$ is closed under substitutions.


How to send to Amazon's Alexa Event Gateway?

Question: I am trying to test sending an event to the Amazon's Event Gateway for my Alexa Smart Home skill using Postman but I keep receiving an 'invalid access token exception.'  I have read the Amazon's documentation on this but apparently I am missing something.
When I enable my skill, my Smart Home Lambda receives the AcceptGrant.
<code>{
    "directive": {
        "header": {
            "namespace": "Alexa.Authorization",
            "name": "AcceptGrant",
            "messageId": "b2862179-bc56-4bb2-ac05-ce55c7a3e977",
            "payloadVersion": "3"
        },
        "payload": {
            "grant": {
                "type": "OAuth2.AuthorizationCode",
                "code": "ANSVjPzpTDBsdfoRSyrs"
            },
            "grantee": {
                "type": "BearerToken",
                "token": "Atza|IwEB..."
            }
        }
    }
}
</code>
My lambda sends a POST to 'https://api.amazon.com/auth/o2/token' to receive the Access and Refresh tokens. It then stores those tokens.  Next, my Lamdba responds with the following:
<code>{
    "event": {
        "header": {
            "namespace": "Alexa.Authorization",
            "name": "AcceptGrant.Response",
            "messageId": "b2862179-bc56-4bb2-ac05-ce55c7a3e977",
            "payloadVersion": "3"
        },
        "payload": {}
    }
}
</code>
I then get a message web page that I have successfully linked my skill - all is good.
Next, I try to send an event to Amazon's Alexa event gateway using the Postman app.  I put the Access token (I also tried the Refresh token) in the header as a 'BearerToken' type and the in the 'scope' of the 'endpoint' object.
POST https://api.amazonalexa.com/v3/events?Content-Type=application/json&charset=UTF-8
with a header that specifies a Bearer Token (Access token received earlier) and a body that contains the following:
<code>{
    "event": {
        "header": {
            "messageId": "abc-123-def-456",
            "namespace": "Alexa",
            "name": "ChangeReport",
            "payloadVersion": "3"
        },
        "endpoint": {
            "scope": {
                "type": "BearerToken",
                "token": "<access token>"
            },
            "endpointId": "MySmartSwitch-001"
        },
        "payload": {
            "change": {
                "cause": {
                    "type": "RULE_TRIGGER"
                },
                "properties": [
                    {
                        "namespace": "Alexa.ModeController",
                        "name": "mode",
                        "value": "Backup",
                        "timeOfSample": "2020-01-02T09:30:00ZZ",
                        "uncertaintyInMilliseconds": 50
                    }
                ]
            }
        }
    },
    "context": {
        "properties": [
            {
                "namespace": "Alexa.PowerController",
                "name": "powerState",
                "value": "ON",
                "timeOfSample": "2020-01-02T09:30:00Z",
                "uncertaintyInMilliseconds": 60000
            },
            {
                "namespace": "Alexa.EndpointHealth",
                "name": "connectivity",
                "value": {
                    "value": "OK"
                },
                "timeOfSample": "2020-01-02T09:30:00Z",
                "uncertaintyInMilliseconds": 0
            }
        ]
    }
}
</code>
The response received is '401 Unauthorized'
<code>{
    "header": {
        "namespace": "System",
        "name": "Exception",
        "messageId": "95bd23c3-76e6-472b-9c6d-74d436e1eb61"
    },
    "payload": {
        "code": "INVALID_ACCESS_TOKEN_EXCEPTION",
        "description": "Access token is not valid."
    }
}
</code>
Comment: CAn you offfer some elaboration on how you generated your BearerToken (with that URL?) I can't seem to figure it out.
Comment: i have same issue
Answer: I figured out the issue.  I was mistakenly sending parameters: Content-Type=application/json and charset=UTF-8 as well including them in the header - my bad.  You just need to include them in the header.
Comment: Hello "On the PERMISSIONS page, slide Send Alexa Events to indicate your skill will send asynchronous responses and/or change report events." In alexa skills page Im not able to find the Send Alexa Events button
Comment: Can you please tell me How do you send a simple "Hello world" message to Alexa asynchronously?
Do you need to use the events gateway?
If so what should be the **endpointid**?
Can you please post an example of a simple async Response to ALexa through the event gateway, all alexa has to do is voice out the response that's it.
Many Thanks Please note I have reached till the part where Bearer token is received successfully and then access and refresh tokens too all are good.


Concat E4X expressions in ActionScript 3

Question: Is there any way to concatenate E4X expressions? If I store "half" a path in a variable, can I concatenate the way I do with Strings?
Answer: You can always use array access by converting the E4X string into an array, seperated by the dots.
var xml:XML =
    <data>
        <c><x><y><z attr="This is an attribute">This is a text!</z></y></x></c>
    </data>

var path1:String = "a.b.c";
var path2:String = "x.y.z";
var path3:String = "@attr";
var path:Array = ([path1, path2, path3].join('.')).split('.');

var result:XMLList = new XMLList(xml);

for (var i:uint = 0; i < path.length; i++) {
    result = result[path[i]];
}

trace(result); // This is an attribute


Displaying html of page only if session exists

Question:   <?php

ini_set("log_errors", 1);
ini_set("error_log", "errorlog.log");

$recid= $_POST['recid'];
$username = $_POST['name'];
$email = $_POST['email'];
$ownername = $_POST['ownername'];

include ("connection.php");

$result = $db->query("UPDATE users SET verified='y' WHERE recid='$recid'");

$filename = str_replace(" ","_", trim($username) );
mkdir("Business_Pages/". $filename."/");

$jquery = "";
$jqueryui = "";
$jquerycss = "<link rel='stylesheet' href='http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css'>";
$postdata = "";
$pagecss = "<link rel='stylesheet' href='../../CSS/businesspages.css'>";
$wclogo = "";
$postinput = "<input type='text' id='post' placeholder='Post' name='post'>";
$postdate = "<input type='text' id='date' placeholder='Enter Date' name='date'>";
$accountinfo = "

                      $username

  $ownername

";
$links = "

";

$fp = fopen("Business_Pages/". $filename . "/" . $filename . ".html", "w");

fwrite($fp,"<?php session_start()");

fwrite($fp,"if(isset($_SESSION['id'])) { ?>");

fwrite($fp,"<!DOCTYPE html>  ");

fwrite($fp,"");

fwrite($fp,"");

fwrite($fp," ");

fwrite($fp,"<?php } ?>");

fclose($fp);

$to = "$email";
$subject = "Account Creation";
$message = "Congratulations you have been accepted to Wolfeboro Connection";
$from = "firstname.lastname@example.com";
$headers = "From:" . $from;

mail($to, $subject, $message, $headers)

?>

Im trying only to show the html if a session is valid but php is saying that its an unexpected if statement and
Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/content/96/10688096/html/verify.php on line 37 Thanks in advance
Comment: Why are you using `fp` and `fwrite`.. Do you want to show the page in the browser or want to write it into the file...??
Comment: Be careful with interpolation: depending on earlier code in the script, `"if( isset($_SESSION=['id')) { ?>"` might not output what you expect.  If `$_SESSION` is an array like it should be, the relevant line in the output file would read `if( isset(array=['id')) { ?>`.
Comment: correct i want to fwrite it to a file and my login goes to that file but i want it to not go to the file if you dont login
Comment: Well, instead of writing a file, what you can do is to define the file and specify the condition to check whether the session exists or not. If not, the user will be redirected to login page or somewhere else. otherwise the page will be shown...
Answer: If you are trying to display the page on the browser then you should do following instead of writing the file and then showing it. Just write below code into the file you want to check the session.
<?php
session_start();
if( isset($_SESSION['id'])) {
?>

<!DOCTYPE html>

<?php } ?>

Hope it helps.
Ok I found the error.. Check out below line
fwrite($fp,"if(isset(".$_SESSION['id'].")) { ?>");

Place this in your code and it should work correctly.. Let me know if any further problem arises...
Hey, This is the latest code I've tried on my machine and it worked... Have a look on it and let me know the results..
<?php
ini_set("log_errors", 1);
ini_set("error_log", "errorlog.log");

$fp = fopen("newtest.php", "w");
fwrite($fp,"<?php session_start();");
fwrite($fp,"if(isset(\$_SESSION['id'])) { ?>");
fwrite($fp,"<!DOCTYPE html>  ");
fwrite($fp,"");
fwrite($fp,"");
fwrite($fp," ");
fwrite($fp,"<?php } ?>");
fclose($fp);
?>

Hope it helps.
Comment: thats what is being written to the file as html and php im getting a error  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING
Comment: Well I haven't received that error.. you might be missing something.. Place your full code into the question.. there might be something which is being missed...
Comment: @PhilPilon.. Try `fwrite($fp,"<?php session_start();");`.. It might be because of missing semi-colon... Let me know the results..
Comment: @PhilPilon... I've changed the answer.. have you tried it.. Let me know the results if you can..
Answer: This is wrong
if( isset($_SESSION=['id')) {

you have unwanted = sign
try this
if( isset($_SESSION['id'])) {

Comment: You missed something in the statement.. `if( isset($_SESSION['id')) { ` should be like `if( isset($_SESSION['id'])) { `.. missing `]`..


Desvio padrão JAVA

Question: Aqui estão meus método para calcular o desvio padrão, que por algum motivo desconhecido por mim não funciona (deixei meu método de teste aqui em baixo também).
public strictfp Double getMedia(List<Double> valor) {
    try {
        return getSoma(valor) / valor.size();
    } catch (NullPointerException e) {
        throw new IllegalArgumentException("The list has null values");
    }
}

public strictfp Double getSoma(List<Double> valor) {
    Double soma = 0D;
    for (int i = 0; i < valor.size(); i++) {
        soma += valor.get(i);
    }
    return soma;
}

public strictfp Double getDesvioPadrao(List<Double> valor) {
    Double media = getMedia(valor);
    int tam = valor.size();
    Double desvPadrao = 0D;
    for (Double vlr : valor) {
        Double aux = vlr - media;
        desvPadrao += aux * aux;
    }
    return Math.sqrt(desvPadrao / tam);
}

#

Método de teste:
@SuppressWarnings("deprecation")
@Test
private void TesteDesvioPadrao() {
    List<Double> valor = new ArrayList<Double>();
    valor.add(13.0);
    valor.add(23.0);
    valor.add(4.0);
    valor.add(2.0);
    valor.add(11.0);
    valor.add(12.0);

    assertEquals(new Double(7.467708), ilbt.getDesvioPadrao(valor));

}

Comment: Favor não colocar RESOLVIDO no título, o site não funciona assim. De uma olhada no [tour]
Comment: Qual o erro? A pergunta não está clara
Comment: Qual o problema que está tendo? Pela sua pergunta não da para saber do que você precisa.
Comment: Quando eu rodo meu método de teste, "initializationError"
Answer: O erro está no cálculo do desvio padrão, no final do método getDesvioPadrao.
Nele você retorna a raiz quadrada da divisão da variância pelo tamanho da coleção. Como você está calculando o desvio padrão de uma amostra, deveria ser o tamanho da coleção subtraindo 1.
public strictfp Double getDesvioPadrao(List<Double> valor) {
    Double media = getMedia(valor);
    int tam = valor.size();
    Double desvPadrao = 0D;
    for (Double vlr : valor) {
        Double aux = vlr - media;
        desvPadrao += aux * aux;
    }
    return Math.sqrt(desvPadrao / (tam - 1));
}

Veja funcionando no repl.it
Comment: @Strigi Por favor, não adicione "resolvido" no título da pergunta. A única forma de sinalizar que a pergunte tem uma resposta é marcando alguma resposta como correta.
Comment: Obrigado, realmente faltava esse detalhe, porém o erro initializationError[Runner JUnit4] ainda persiste

Desvio padrão JAVA


How many real, rational and complex solutions has this system of equations?

Question: Let the system $\left\{\begin{aligned}
      a+b+c &= 3\\
     a^2+b^2+c^2 &=5\\
a^3+b^3+c^3 & =12
    \end{aligned}\right. $
How many real, rational and complex solutions has it?
I read System of three variables of simultaneous equations and found $ e_1 = 3, e_2 = 2, e_3 = 1 $. Then I do not understand the reason but I get the polynomial $ t ^ 3-3t ^ 2 + 2t-1 $. The question is how many , not what are the solutions, so at this point I do not know what to do ...  or if I'm in the right way.  Can you help me please?
Comment: So, how many real, rational and complex solutions are there for the polynomial $t^3-3t^2+2t-1$?
Comment: You just have to see if the equation $t^3-3t^2+2t-1=0$ has three roots over the rationals, over the reals and over the complexes. I'll start you off. It does have three roots over the complexes. $\ddot\smile$
Comment: You way is right. Now, show that your equation has an unique real root.
Comment: For the *rational* part, you may apply the rational root theorem. For the remaining part, it is enough to compute the discriminant of such polynomial, or locate its stationary points.
Comment: https://en.wikipedia.org/wiki/Rational_root_theorem
Comment: @LordSharktheUnknown and they're https://www.wolframalpha.com/input/?i=t%5E3-3t%5E2%2B2t-1%3D0
Answer: It has 6 solutions
Here they are
$$a_1 = 2.32472$$
$$b_1 = 0.56228·i+0.337641$$
$$c_1 = 0.337641−0.56228·i$$
$$a_2 = 2.32472$$
$$b_ 2= 0.337641−0.56228·i$$
$$c_2 = 0.56228·i+0.337641$$
$$a_3 = 0.337641−0.56228·i$$
$$b_3 = 0.56228·i+0.337641$$
$$c_3 = 5.118e−18·i+2.32472$$
$$a_4 = 0.337641−0.56228·i$$
$$b_4 = 1.11022e−16·i+2.32472$$
$$c_4 = 0.56228·i+0.337641$$
$$a_5 = 0.56228·i+0.337641$$
$$b_5 = 0.337641−0.56228·i$$
$$c_5 = 1.69412e−18·i+2.32472$$
Comment: I don't believe $c_3\ddot\smile$.
Comment: @LordSharktheUnknown Why don't you believe $c_3$
Comment: It should be the same as $b_6$, yet its imaginary part is completely different!
Comment: Sorry for that it has 5 solutions
Comment: It really does have six solutions for $(a,b,c)\ \ddot\frown$.
Comment: How did you find it?
Answer: Note
$$ 3^2=(a+b+c)^2=a^2+b^2+c^2+2ab+2bc+2ca=5+2(ab+bc+ca). $$
from this, one has
$$ ab+bc+ca=2. $$
Also
\begin{eqnarray}
3^3&=&(a+b+c)^3=a^3+b^3+c^3+3a^2b+3ab^2+3a^2c+3ac^2+3b^2c+3bc^2+6abc\\
&=&12+3ab(a+b+c)+3bc(a+b+c)+3ca(a+b+c)-3abc\\
&=&12+3(ab+bc+ca)(a+b+c)-3abc\\
&=&30-3abc
\end{eqnarray}
from which, one has
$$ abc=1. $$
Thus $a,b$ and $c$ are the roots of the following equation
$$ t^3-3t^2+2t-1=0. \tag{1} $$
So the coefficients of (1) are
$$ a_3=1,a_2=-3,a_1=2,a_0=-1 $$
and hence the discriminant is
$$ \Delta=18a_3a_2a_1a_0-4a_2^3a_0+a_2^2a_1^2-4a_3a_1^3-27a_3^2a_0^2=-23<0$$
and hence (1) has one real root and two complex roots.
Comment: But what is the nature of the roots?
Comment: @LordSharktheUnknown, see the update.


Check if string is a date in Elixir

Question: I am new to Elixir and wanted to know if there is a way to check if a string is a date without necessarily having to write your own function that makes use of regex?
Comment: What's the format of the date string?
Comment: String can be in any date time format
Comment: It's good to limit your potential input formats, because they can conflict. For example, "05-06-2017" could be valid as both May 6th or June 5th depending on what part of the world you're from.
Answer: It depends on the format of the date in the parsed string. Elixir's standard library contains Date.from_iso8601, which can be used as the following:
def is_date?(date) do
  case Date.from_iso8601(date) do
    {:ok, _} -> true
    _ -> false
  end
end

If you're expecting a string of another format, then Timex library may be useful for you, because it allows to specify the format of the parsed string. For example:
def is_date?(date) do
  case Timex.format(date, "{ISO:Extended}") do
    {:ok, _} -> true
    _ -> false
  end
end

Answer: I guess the most suitable option for you might be Timex.parse, but you could provide informations of your Date's format.
If you have a bit more complex format, I'm afraid that using your own "datetime helper" will be neccesary.

Check if string is a date in Elixir


react-router - withRouter results in this.props.router being undefined

Question: I've followed the documentation found at https://github.com/reactjs/react-router/blob/cbdc49442aba5cc6f225ff5546ac5f4a217fa4ec/upgrade-guides/v2.4.0.md but I'm struggling to get access to this.props.router using the new withRouter higher order component.
import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router';
import * as actionCreators from '../action_creators';

export const ComponentA = withRouter(React.createClass({
  componentDidMount() {
    console.log(this.props.router); //returns undefined
  },
  render() {
    return (

    );
  }
}));

//map redux state to props
function mapStateToProps(state) {
  return {
    views: state.main.get('views')
  };
}

export const ComponentAContainer = connect(
  mapStateToProps,
  actionCreators
)(ComponentA);

Unfortunately this.props.router always returns undefined. For some reason it doesn't seem to get injected as a property.
this.props looks like this:
addBranch: function()
addProject: function()
addView: function()
castDeviceAvailable: function()
castDeviceConnected: function()
castDeviceDisconnected: function()
castDeviceUnavailable: function()
closeBurgerMenu: function()
createProject: function()
deleteBranch: function()
deleteProject: function()
deleteView: function()
formValidation: function()
getCastDeviceAuthToken: function()
key: function(...)
get key: function()
loadView: function()
navigateToSettings: function()
newBuild: function()
newBuildSummary: function()
newCastDeviceAuthToken: function()
openBurgerMenu: function()
projectAdded: function()
projectDeleted: function()
projectUpdated: function()
ref: function(...)
get ref: function()
router: undefined
setBuildSummary: function()
setLatestBuilds: function()
setProjects: function()
setState: function()
setThemes: function()
setViews: function()
subscribeToView: function()
toggleBurgerMenu: function()
updateView: function()
viewAdded: function()
viewDeleted: function()
viewUpdated: function()
__proto__: Object

Any thoughts?
Answer: Have you tried wrapping connect instead? Like this...
export const ComponentAContainer = withRouter(connect(
  mapStateToProps,
  actionCreators
)(ComponentA));

Note: In doing so you should also remove the withRouter wrapper on your class definition.


Good references for time series?

Question: I am wondering if anyone has book references for time series. I would like something comparable (in popularity) to the 'ESL' or to 'Machine learning' from Murphy in the machine learning field.
Does anyone knows what are the most complete (in term of methods scope) books containing all about exponential smoothing (all of them), arima, sarima , arch, garch, neural network for time series, kalman filters, ... etc ?
Comment: Please be *very specific* about what objective standards should be applied to determine "comparable," "good," and "best," for without such clear standards this question is off-topic here.  Consult our [help] for more information.
Comment: Is that precise enough now ? I'm really just looking for a recomendation for a complete time series book. Should I ask this question on stack exchange instead ?
Comment: You wouldn't get far with this on SO! Because your modification provides a reasonably clear criterion for people to suggest answers, I have voted to reopen your question here.
Comment: I am new in Time Series and I was wondering why is that Time Series is not included on ESL (or any other book like this)? Time Series is a subfield of Statistical Learning, isn't it?
Answer: I don't know of a single time series book that is as comprehensive as Elements of Statistical Learning. However, here's a list of a few books that i've found helpful:
Free online. More of a forecasting focus, but definitely a good starting point. The slides under resources are also helpful:

Hyndman, R. J., & Athanasopoulos, G. (2013). Forecasting: principles and practice. Retrieved from http://otexts.org/fpp/

Probably the most comprehensive. With information about many of the model types you've listed:

Shumway, R. H., & Stoffer, D. S. (2010). Time Series Analysis and Its Applications. Springer.

Definitive resource on exponential smoothing:

Hyndman, R., Koehler, A. B., Ord, J. K., & Snyder, R. D. (2008). Forecasting with Exponential Smoothing. Springer.
Comment: +1 for Shumway and Stoffer.  My favourite, with frequency domain material, state space models, and R examples in later editions to boot.
Answer: Brockwell and Davis wrote two excellent time series books. Both cover a great deal of material and the writing is very clear. The first book is more introductory, and the second one has a more mathematical development.
http://www.amazon.com/Introduction-Forecasting-Springer-Texts-Statistics/dp/0387953515/
http://www.amazon.com/Time-Series-Methods-Springer-Statistics/dp/1441903194
Answer: I don't know about the 'ESL' or machine learning, but what about good ol' Tsay?
Some parts you mentioned are included, some not (e.g. Kalman filter):

Analysis of Financial Time Series by Ruey S. Tsay

When it comes to times series with applications and an easy-to-understand way of explaining he is my Tom Cruise, my top gun.
Answer: ESL is not for time series in my opinion. Tsay's book in addition to Cowpertwait's intro level book are the best combination.
Comment: No one said ESL was about time series...
Answer: Have a look at

James D. Hamilton. Time Series Analysis. Princeton Univ. Press, Princeton, N.J, 1994.

It is very thorough. I'm not sure about neural networks and "all" exponential smoothing, but the rest is in there.
Answer: Here is a good list of books on time series analysis. Note that there is a lot of difference amongst books that cater to people of different backgrounds (economists/engineers/statisticians). hth

Good references for time series?


Comparing species communities between sites with different numbers of replicates

Question: I'm working with ecological community data collected from different sites and want to make comparisons between the sites using descriptors like richness, Shannon Weiner's diversity, and Simpson's evenness. There are some sites with multiple temporal replicates and others with just one sample. What is the best way to summarize the community data for sites with multiple replicates so they can be compared with the sites with only one sample? For example, the dataset looks something like this, where the values are counts of each species:
<code>          SiteA_Rep1  SiteA_Rep2  SiteA_Rep3  SiteB  SiteC  SiteD_Rep1  SiteD_Rep2
SpeciesA      1           4           2         0      2        0           6
SpeciesB      0           2           0         7      4        1           2
SpeciesC      7           6           3         6      2        3           0
...
</code>
I am trying to summarize the data so that I have one count for each species at each site. I have tried taking the mean or median count for each species at a site with multiple replicates, but this inflates the richness because in effect I am increasing the sampling intensity at that site and increasing the chance that a rare species is encountered.
I have also looked at rarefaction methods for estimating richness, but I need the species counts for my other metrics.
Is there an ideal way to turn these replicates into one "sample" while preserving counts for each of the species?
Answer: You could calculate the metrics you want to compare (i.e. Shannon-Weiner and Simpsons indices) for each site, and then take an average of those metrics for the sites that were sampled on multiple occasions, before carrying out your comparisons to other sites.
Of course this does lose some of your information, by summarising the multiple samples into a single metric - but that is what you asked to do. If I were you I would consider presenting the results from all your sites separately - showing the metrics you obtain from multiple re-samples of the same site could be interesting. For instance, you might get different results because you sampled at different times of year. It would be interesting to know, for example, if Site B was more diverse than Site A in summer and Site B in winter.
Comment: Right, thanks for the suggestion! Can't believe I overlooked this option, but it makes the most sense


Check if line is a timestamp in Python

Question: I have a script that runs every 30 minutes on my server, and when it's done it writes a timestamp to the last line of the file. It does this to about 20+ files in one directory. I'm trying to write a Python script to check the last line of each file and return either a "In progress" or "Finished at:" message for each file depending on if that timestamp is present or not.
How do I get Python to determine if a string is a timestamp or not? It is formatted as HH:MM:SS, no month/date indications.
Comment: What are the alternatives that could be written?
Answer: You could try to match a regular expression:
import re
if re.match('\d{2}:\d{2}:\d{2}', line):

would work if the line starts with 3 2-digit pairs with colons in between; depending on what else you might find in line this could easily be enough.
Another option would be to try and parse it:
import time

try:
    time.strptime(line[:8], '%H:%M:%S')
except ValueError:
    print('Not a timestamp')
else:
    print('Found a timestamp')

This is a lot stricter; a ValueError is thrown whenever a line does not start with a timestamp that can actually represent a valid time value, so the hour must be in the range 0-23, minutes in the range 0-59 and seconds in the range 0-60.

Check if line is a timestamp in Python


Non-linear SVM classification with RBF kernel

Question: I'm implementing a non-linear SVM classifier with RBF kernel. I was told that the only difference from a normal SVM was that I had to simply replace the dot product with a kernel function:
$$
K(x_i,x_j)=\exp\left(-\frac{||x_i-x_j||^2}{2\sigma^2}\right)
$$
I know how a normal linear SVM works, that is, after solving the quadratic optimization problem (dual task), I compute the optimal dividing hyperplane as
$$
w^*=\sum_{i \in SV} h_i y_i x_i
$$
and the offset of the hyperplane
$$
b^*=\frac{1}{|SV|}\sum_{i \in SV}\left(y_i - \sum_{j=1}^N\left(h_j y_j x_j^T x_i\right)\right)
$$
respectively, where $x$ is a list of my training vectors, $y$ are their respective labels ($y_i \in \{-1,1\}$), $h$ are the Lagrangian coefficients and $SV$ is a set of support vectors. After that, I can use $w^*$ and $b^*$ alone to easily classify: $c_x=\text{sign}(w^Tx+b)$.
However, I don't think I can do such a thing with an RBF kernel. I found some materials suggesting that $K(x,y)=\phi(x)\phi(y)$. That would make it easy. Nevertheless, I don't think such a decomposition exists for this kernel and it's not mentioned anywhere. Is the situation so that all the support vectors are needed for the classification? If so, how do I classify in that case?
Comment: Not a complete answer but I had these slides at uni: https://patterns.enm.bris.ac.uk/files/lecture10-2010.pdf
Answer: Let $\mathcal{X}$ represent your input space i.e the space where your data points resides. Consider a function $\Phi:\mathcal{X} \rightarrow \mathcal{F}$ such that it takes a point from your input space $\mathcal{X}$ and maps it to a point in $\mathcal{F}$. Now, let us say that we have mapped all your data points from $\mathcal{X}$ to this new space $\mathcal{F}$. Now, if you try to solve the normal linear svm in this new space $\mathcal{F}$ instead of $\mathcal{X}$, you will notice that all the earlier working simply look the same, except that all the points $x_i$ are represented as $\Phi(x_i)$ and instead of using $x^Ty$ (dot product) which is the natural inner product for Euclidean space, we replace it with $\langle \Phi(x), \Phi(y) \rangle$ which represents the natural inner product in the new space $\mathcal{F}$. So, at the end, your $w^*$ would look like,
$$
w^*=\sum_{i \in SV} h_i y_i \Phi(x_i)
$$
and hence,
$$
\langle w^*, \Phi(x) \rangle = \sum_{i \in SV} h_i y_i \langle \Phi(x_i), \Phi(x) \rangle
$$
Similarly,
$$
b^*=\frac{1}{|SV|}\sum_{i \in SV}\left(y_i - \sum_{j=1}^N\left(h_j y_j \langle \Phi(x_j), \Phi(x_i)\rangle\right)\right)
$$
and your classification rule looks like: $c_x=\text{sign}(\langle w, \Phi(x) \rangle+b)$.
So far so good, there is nothing new, since we have simply applied the normal linear SVM to just a different space. However, the magic part is this -
Let us say that there exists a function $k:\mathcal{X}\times\mathcal{X}\rightarrow \mathbb{R}$ such that $k(x_i, x_j) = \langle \Phi(x_i), \Phi(x_j) \rangle$. Then, we can replace all the dot products above with $k(x_i, x_j)$. Such a $k$ is called a kernel function.
Therefore, your $w^*$ and $b^*$ look like,
$$
\langle w^*, \Phi(x) \rangle = \sum_{i \in SV} h_i y_i k(x_i, x)
$$
$$
b^*=\frac{1}{|SV|}\sum_{i \in SV}\left(y_i - \sum_{j=1}^N\left(h_j y_j k(x_j, x_i)\right)\right)
$$
For which kernel functions is the above substitution valid? Well, that's a slightly involved question and you might want to take up proper reading material to understand those implications. However, I will just add that the above holds true for RBF Kernel.
To answer your question, "Is the situation so that all the support vectors are needed for the classification?"
Yes. As you may notice above, we compute the inner product of $w$ with $x$ instead of computing $w$ explicitly. This requires us to retain all the support vectors for classification.
Note: The $h_i$'s in the final section here are solution to dual of the SVM in the space $\mathcal{F}$ and not $\mathcal{X}$. Does that mean that we need to know $\Phi$ function explicitly? Luckily, no. If you look at the dual objective, it consists only of inner product and since we have $k$ that allows us to compute the inner product directly, we don't need to know $\Phi$ explicitly. The dual objective simply looks like,
$$
\max \sum_i h_i - \sum_{i,j} y_i y_j h_i h_j k(x_i, x_j) \\
\text{subject to : } \sum_i y_i h_i = 0, h_i \geq 0
$$
Comment: @JanHadáček You are welcome! Good to know that my answer is understandable, I was worried that it might be too condensed :-)
Comment: Very nice explanation


DXGI Warning when using OpenGL on Windows 8?

Question: I'm writing a CAD application using OpenGL (not DirectX). When running the debug build on Windows 8 Pro (64bit), the following messages are printed to the debugger's console windows before the application terminates correctly:
DXGI WARNING: Process is terminating. Using simple reporting. Please call ReportLiveObjects() at runtime for standard reporting. [ STATE_CREATION WARNING #0: ]
DXGI WARNING: Live Producer at 0x0000009E51808AD8, Refcount: 2. [ STATE_CREATION WARNING #0: ]
DXGI WARNING:   Live Object at 0x0000009E5180A570, Refcount: 2. [ STATE_CREATION WARNING #0: ]
DXGI WARNING: Live                         Object :      1 [ STATE_CREATION WARNING #0: ]

I have no idea where this is coming from. DXGI seems to be related to DirectX, which I'm not using. Any hints?

Update
Following Paul-Jan's advice, I enabled device debugging, which produces the following messages:
D3D11 INFO: Create ID3D11Context: Name="unnamed", Addr=0x00000015EEB486D0, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097225: CREATE_CONTEXT]
D3D11 INFO: Create ID3DDeviceContextState: Name="unnamed", Addr=0x00000015EE96DE70, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #3145735: CREATE_DEVICECONTEXTSTATE]
D3D11 INFO: Create ID3D11BlendState: Name="unnamed", Addr=0x00000015EE97B6A0, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097270: CREATE_BLENDSTATE]
D3D11 INFO: Create ID3D11DepthStencilState: Name="unnamed", Addr=0x00000015EE9799F0, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097273: CREATE_DEPTHSTENCILSTATE]
D3D11 INFO: Create ID3D11RasterizerState: Name="unnamed", Addr=0x00000015EE97B340, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097276: CREATE_RASTERIZERSTATE]
D3D11 INFO: Create ID3D11Sampler: Name="unnamed", Addr=0x00000015EE97AE30, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097267: CREATE_SAMPLER]
D3D11 INFO: Create ID3D11Query: Name="unnamed", Addr=0x00000015F25D3060, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097279: CREATE_QUERY]
D3D11 INFO: Create ID3D11Texture2D: Name="unnamed", Addr=0x00000015EEB8CA50, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097234: CREATE_TEXTURE2D]
D3D11 INFO: Create ID3D11Texture2D: Name="unnamed", Addr=0x00000015EA313BF0, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097234: CREATE_TEXTURE2D]
D3D11 INFO: Create ID3D11Texture2D: Name="unnamed", Addr=0x00000015EEB41EC0, ExtRef=1, IntRef=0 [ STATE_CREATION INFO #2097234: CREATE_TEXTURE2D]
D3D11 INFO: Destroy ID3D11Texture2D: Name="unnamed", Addr=0x00000015EA313BF0 [ STATE_CREATION INFO #2097236: DESTROY_TEXTURE2D]
D3D11 INFO: Destroy ID3D11Texture2D: Name="unnamed", Addr=0x00000015EEB41EC0 [ STATE_CREATION INFO #2097236: DESTROY_TEXTURE2D]
D3D11 INFO: Destroy ID3D11Texture2D: Name="unnamed", Addr=0x00000015EEB8CA50 [ STATE_CREATION INFO #2097236: DESTROY_TEXTURE2D]
D3D11 WARNING: Process is terminating. Using simple reporting. Please call ReportLiveObjects() at runtime for standard reporting. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING: Live Producer at 0x00000015EEA57E08, Refcount: 3. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015EEB486D0, Refcount: 1. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015EE96DE70, Refcount: 0. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015EE97B6A0, Refcount: 0. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015EE9799F0, Refcount: 0. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015EE97B340, Refcount: 0. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015EE97AE30, Refcount: 0. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING:  Live Object at 0x00000015F25D3060, Refcount: 0. [ STATE_CREATION WARNING #0: UNKNOWN]
D3D11 WARNING: Live                         Object :      7 [ STATE_CREATION WARNING #0: UNKNOWN]

DXGI WARNING: Process is terminating. Using simple reporting. Please call ReportLiveObjects() at runtime for standard reporting. [ STATE_CREATION WARNING #0: ]
DXGI WARNING: Live Producer at 0x00000015F25D2EB8, Refcount: 2. [ STATE_CREATION WARNING #0: ]
DXGI WARNING:   Live Object at 0x00000015EE9AF870, Refcount: 2. [ STATE_CREATION WARNING #0: ]
DXGI WARNING: Live                         Object :      1 [ STATE_CREATION WARNING #0: ]

Comment: I have the same warning with win 7 and DX11 (not OpenGL). Did you manage the warning?
Answer: In Windows Vista and above, both DirectX and OpenGL actually work through DXGI. DXGI manages the devices. The actual rendering API used (OpenGL / DirectX) is called a producer in DXGI speak, so we can safely assume the message is about your generic OpenGL usage.
As it complains about both a producer and a live object having a referencecount of 2, could it be you are not destroying your OpenGL context properly? (i.e. succesfully calling wglMakeCurrent( NULL ) and wglDeleteContext) Such an ommission would not be a practical problem at all as both get implicity destroyed at proces termination, but would warrant a warning.
Comment: Thanks for you explanation! But no, my application correctly calls `wglMakeCurrent(NULL)` and `wglDeleteContext`. Maybe it's a bug in the driver?
Comment: Could be! I think you can safely assume these warnings are spurious and harmless, but if you are curious (I know I am!), you could try enabling Device Debugging from the DirectX Control Panel (see http://blog.rthand.com/post/2010/10/25/Capture-DirectX-1011-debug-output-to-Visual-Studio.aspx for instructions). This might provide the same information as calling "reportLiveObjects()" in a DX application would.
Comment: Thanks - I'll try that. If I manage to install DirectX Control Panel on Windows 8.
Comment: They are part of the Windows 8 SDK (see http://msdn.microsoft.com/en-us/library/windows/desktop/ee663275(v=vs.85).aspx).
Comment: Yes, thanks, I've installed it and updated my question with the result. Not very conclusive though.
Answer: I ran into the same warning information (ReportLiveObjects, Live Producer, Live Object,  STATE_CREATION WARNING #0: UNKNOWN,.....) with you, in a project with DirectX 11. But this information was not informative enough for me, and to you, I think.
For my project, the problem turned out to be that the texture file (.dds) has an incompatible format with other parts of my program, so the program cannot load the texture correctly. After I converted it into the correct format. This warning info went away.
So my conclusion here, is that you may need to use some debugging techniques, such as breaking points, logging, etc., in order to trace what the real problem is in your case.


If $A^3=A+I$, then $\det A>0$

Question:
If $A$ is a $n\times n$ matrix such that $A^3=A+I$, then $\det A>0$.

I don't know how to solve this problem. It's easy to see that $\det A\neq 0$. Suppose $\det A<0$. These are ways that I tried:
$\bullet$ $\det A^3=(\det A)^3<0$, thus $\det(A+I)<0$; $A^2+A+I=A^3+A^2=A^2(A+I)$, thus $\det (A^2+A+I)<0$.
$\bullet$ Let $\lambda_1,\lambda_2,\ldots,\lambda_n$ are all eigenvalues of $A$. Then $\lambda_i^3-\lambda_i$ is eigenvalue of $A^3-A$ for all $i=\overline{1,n}$. But $A^3-A=I$, then $\lambda_i^3-\lambda_i=1$ for all $i$.
$\bullet$ $\lambda_i^2+\lambda_i+1$ are eigenvalues of $A^2+A+I$. Since $\det (A^2+A+I)<0$, $\displaystyle \prod_{i=1}^n (\lambda_i^2+\lambda_i+1)<0$.
The problem is I don't know how to deal with complex eigenvalues, so I don't know how to connect all the above things.
Thanks in advance.
Answer: Hint
Assuming that the matrix is over $\mathbb{R}$.
Note that it is obvious that $A$ is invertible, hence $\text{det}A \neq 0$.
The polynomial $p(x)=x^3-x-1$ is an annihilating polynomial for your matrix $A$. Thus the minimal polynomial of $A$ would be either this is or one of its factors. Note that $p(x)$ has only one real root (let us call it) $r$ that lies in the interval $(1,2)$ (note: $r>0$).
Case 1: If the minimal polynomial for $A$ is $x-r$, then the only real roots of the characteristic polynomial will be $r$ (with multiplicity), the rest will be complex. In which case the determinant of $A$ being the product of eigen values will be positive because the complex roots will occur in conjugate pairs (hence the product will be positive) and the product of $r$ (with multiplicity) will be positive.
Case 2: use a similar argument when minimal polynomial for $A$ is the quadratic factor of $p(x)$.
Case 3: use a similar argument when minimal polynomial for $A$ is $p(x)$.
Comment: very good my thoughts exactly +1
Comment: @learnmore Thanks.
Comment: Yes that's what I'm wondering. How to prove that "the complex roots will occur in conjugate pairs"?
Comment: @TienKhaPham This is the [conjugate root theorem](http://en.wikipedia.org/wiki/Complex_conjugate_root_theorem). The proof is simple and given in the link.
Answer: Another solution; assuming that $A$ is with real coefficients, and putting $P(x)=\rm{ det}(A-xI)\in \mathbb{R}[x]$ and $j=\exp(2i\pi/3)$, we compute easily $A^5=A^2+A+I$ hence $${\rm det}(A)^5={\rm det}(A^2+A+I)={\rm det}(A-jI){\rm det}(A-j^2I)=P(j)P(j^2)=|P(j)|^2\geq 0$$ and as $det(A)\not =0$, we are done.
Answer: It seems like your hypothesis might be missing something, specifically that $A$ is real. Without that, consider the $1\times 1$ matrix, consisting of one of the complex roots of $p(t)=t^3-t-1$. Its determinant is complex.
Similarly, you can build a diagonal matrix as large as you like, so long as its diagonal entries are all roots of the polynomial, and it will satisfy the equation. If you don't pair all the complex entries up with their conjugate, or else have them in groups of three (their arguments are $\pm 2\pi/3$) you don't have a real valued determinant.
The only way around this, I suspect, is to force that the matrix is real valued, and so the roots appear with their complex conjugate if they are complex, and so their product is positive and real.
eta: Anurag is correct in all particulars, but you do need the assumption that the matrix is real.
Answer: the eigenvalues are given by $f(\lambda) = \lambda^3 - \lambda - 1 = 0$
claim: the real eigenvalue of $A$ is positive. you can prove the claim by finding the critical numbers $\pm \dfrac{1}{\sqrt 3}$ of $f$ and showing that local max
$f(-1/\sqrt 3) < 0$ and the only $x$-intercept is positive.
the eigenvalues of $A$ are repetitions of this eigenvalue and complex conjugate pairs. the determinant of $A$ which is the product all the eigenvalues must be positive.
Answer: Another way to go at this problem :
Rewrite the equation as $$A(A^2-I)=I$$
Then by definition A is invertiable and $$A^{-1}=A^2-I$$
Answer: Since $A(A^2 -I)=I,$ taking the determinant on both sides we get $(\det{A}) (\det (A^2 -I)) =1.$ Clearly $\det(A^2 -I) \neq 0$ because if it were then $1$ or $-1$ would be eigenvalues of $A$ and hence $1$ or $ -1$ would be roots of $x^3 -x-1=0,$ a contradiction. Therefore, $\det(A^2 -I) \neq 0$ and $\det A = (\det (A^2-I))^{-1}.$
Now $f(t)= \det(A-tI)$ is a continuous function in $t$ so if $f(-1)$ and $f(1)$ were to have opposite sign by the Intermediate Value Theorem there would exist $c \in (-1, 1)$ such that $f(c) =0.$ Thus $A$ would have an eigenvalue $c \in (-1,1)$ and such a $c$ would satisfy $x^3 -x-1=0.$ This contradicts the fact that $g(x) = x^3 -x-1$ does not change sign on $(-1, 1).$
Thus $f(1)f(-1) >0$ which implies $\det(A^2 -I) >0$ and hence $\det A >0.$

If $A^3=A+I$, then $\det A>0$


Git's Version of Update to HEAD

Question: I'm a newbie at git and want to understand how to collaborate with a few friends on a project using git. My problem is trying to understand how to "updated to HEAD (like in SVN)" in git. I understand git's a bit different, and I would appreciate any help.
So consider this situation. There is Person A and Person B. Person A changes a file by making 1 addition. He then performs:

Commit's on his own branch
Switch to master
pull origin master
git merge personAbranch
git push origin master

So, so far, this works, as on GitHub the repository has been updated with Person A's changes.
Now, assume that Person B during this whole time has been making changes of his own as well. He too, makes 1 addition. What should Person B do "update to HEAD" so that he can commit his changes as well. What Person B has tried is...

commiting his own change to his own branch.
Switching to master
git pull origin master
git merge master ian.

On the fourth line, he always gets a complaint of a conflict. Why?!
Any help would be greatly appreciated.
Answer: If git is complaining about a conflict, it means that person A and person B (could his name be Ian? ;) have modified the same file and the changes, well, conflict.  Either the file is a binary file, for which git can never resolve two different modifications, or it's a text file and the two modifications touch the same set of lines.
You will have to resolve the conflict.  You can use git mergetool to help with this.
(Conflicts are not unique to git.  They can happen with Subversion, too, for the same sort of reason.)
Comment: Thanks for the help Ken Thomases. I think when Ian and I tested it, I would have a file that would say "Test file." For me, I would add an additional line that says "Alex's Addition." Ian would simultaneously add a line on his computer that says "Ian's addition." I was hoping that git could merge the too, but I guess since they are on the same lines, then it won't work. However, would it help if Ian maybe placed his additional line further down the file (say, press Enter a bunch of times) so that it does not conflict with my line? Would git be able to merge the two?
Comment: No.  For example, how could git know if your line was meant to go immediately after the original line or after Ian's additions?

Git's Version of Update to HEAD


Linear regression closed form solution and having enough training points

Question: I was trying to understand better when we can learn a unique parameter for linear regression and how much data is required to get one.
Say that we want to learn a parameter $\theta$ such that empirical risk is minimized $R_n(\theta)$. For that we want:
\begin{align}
\bigtriangledown R_{n}( \theta )_{\theta = \hat{\theta}} &= 0  \\
\bigtriangledown\frac{1}{n} \sum^n_{t=1} (y^{(t)} - \theta \cdot x^{(t)}) &= \frac{1}{n}\sum^n_{t=1}-y^{(t)}x^{(t)}   + \frac{1}{n} \sum^n_{t=1}x^{(t)} {x^{(t)}}^{T}\theta
\end{align}
If we let $b = \frac{1}{n}\sum^n_{t=1}y^{(t)}x^{(t)}$, and $A = \frac{1}{n} \sum^n_{t=1}x^{(t)} {x^{(t)}}^{T}\theta$, then we can re-write it as:
\begin{align}
-b + A \hat{\theta} &= 0  \\
 A \hat{\theta} &= b
\end{align}
or also more commonly known as:
\begin{align}
b &= \frac{1}{n}x^{T}y  \\
A &=\frac{1}{n}X^{T}X  \\
X^{T}X \hat{\theta} &= X^{T}y
\end{align}
But it was not clear to me what conditions we required for $A$ or $X$ so that $A$ was invertible. It obvious that $A$ should span the $R^d$ where $d$ is the dimensionality of the data, but how does that translate how the training data should span that subspace? I guess I am specifically unsure about when $A$ is invertible in relation to $X^T X$.
This is mainly a linear algebra question, however, since I posted this in the context of machine learning too, it would nice to get a response that explains what conditions we need to have of the training points such that such that $X^TX$ is invertible. i.e what conditions we need on the rows of X such that $X^TX$ is invertible.
(Also, I am interested on an answer that is informative, but if it comes with a proof of the claims that will make me most happy)
Comment: You refer to regression in the title & use that tag, however in the body of the question, you seem to be discussing a classifier. In machine learning, people often think of regression & classification as being somewhat distinct. Can you clarify what topic you are thinking about? Are you thinking about both at a greater level of abstraction?
Comment: Oh dam, your right, I did write the word classifier. That was me being completely careless and using the term classifier incorrectly. I agree classifier and regression are very different. I apologize I will correct that.
Comment: No need to apologize. We just want to be clear. Thanks for editing.
Answer: It is necessary and sufficient that $X$ has full column rank where $X$ is arranged such that the $i^{th}$ row of $X$ is the $i^{th}$ observed vector.
Comment: For $N > d$ it just means that the rows of $X$ span $\mathbb{R}^d$.  In the applied setting you usually can access a rank function and you want to check $rank(X)=d$.
Comment: Yes, your assumptions are correct.
Comment: Could you remind me what a full column rank is? (sorry it's been a while since I did my linear algebra course) Thanks!
Comment: What is N and what is d? I am assuming that d is the number of features for one row of X (i.e. one training data has size d) and N is the number of training data points?
Comment: So what I understand so far is that we need to have independent columns of X, right? However, what does that imply on the training points that we get for X? (i.e. what does that imply on the rows of X)
Comment: Does that just imply that the rows of X must span $R^d$? i.e. that we have sufficient rows to span $R^d$?


How do I disable "Activate Task" in Eclipse

Question:
This window keeps on interrupting me while I am working; it got to a point where I can't even type a single letter. How could I fix or disable this?
Comment: You might learn how to use [Mylyn](https://www.eclipse.org/mylyn/) or consider uninstall it (_Help > About Eclipse IDE: Installation Details_). By the way, your Eclipse looks pretty old. Please upgrade.
Comment: I echo the point about upgrading, but you could go to Window->Preferences->Keys to explore key bindings.  You can add text to the filter and/or you can sort by binding. In my Eclipse, "Activate Task" is bound to Ctrl+f9 .
Comment: @howlger I downloaded eclipse from the website a week ago, how is it old?
Comment: @SawLatt Based on icons that were changed several releases ago, it can be said that your Eclipse is pretty old. For details see _Help > About Eclipse IDE_. Old releases are archived, but can still be downloaded.
Answer: go to Window->Preferences->general->Keys and unbind the activate task option
it will get resolve.


Prove that $f( E^o)$ is an open set if $E$ is bounded

Question:
I do not really understand how to proceed with this question;
To prove a), do I need to show that every point in $f(E^0)$ is an interior point?
I would greatly appreciate any help in this regard
Comment: Differentiable implies open map: http://math.stackexchange.com/questions/645657/proving-that-fu-to-mathbbrn-differentiable-is-an-open-map-when-det-oper
Answer: a). Since Jacobian is not zero at $x$, by the inverse function theorem, $f$ is injective in a local neighborhood of $x$. Thus $f$ is an open mapping, i.e. for any $x$ in $E^o$, there is an open set $x\in G\subset E^o$ that $f(G)\subset f(E^o)$ and $f(G)$ is open. This means that $f(E^o)$ is open.
b). Since $f$ is an open mapping, $f$ maps a close set to a close set, i.e. $f(\overline{E})$ is also closed, or $\overline{f(\overline{E})}=f(\overline{E})$. By the following formulas
$$
E\subset \overline{E}\quad\text{and }\quad \overline{E}=E^o\cup \partial E
$$
We have
$$
f(E)\subset f(\overline{E})\quad\text{and }\quad \overline{f(E)}=f^o(E)\cup \partial f(E)
$$
Hence
\begin{align}
f^o(E)\cup \partial f(E)&=\overline{f({E})}
\\
&\subset\overline{f(\overline{E})}=f(\overline{E})
\\
&=f(E^o\cup \partial E)
\\
&=f(E^o)\cup f(\partial E)
\end{align}
c). Since $E^o\subset E$, $f(E^o)\subset f(E)$. Thus $f^o(E^o)\subset f^o(E)$. Since $f(E^o)$ is open, $f(E^o)=f^o(E^o)$. So we have
$$
f(E^o)\subset f^o(E)\quad\text{and }\quad f(\overline{E})-f^o(E)\subset f(\overline{E})-f(E^o)\tag1
$$
Hence
\begin{align}
\partial f(E)&=\overline{f({E})}-f^o(E)
\\
&\subset \overline{f({\overline{E}})}-f^o(E)
\\
&=f({\overline{E}})-f^o(E)
\\
&\subset f({\overline{E}})-f(E^o)\tag {by (1)}
\\
&=f(E^o\cup \partial E)-f(E^o)
\\
&=(f(E^o)\cup f(\partial E))-f(E^o)
\\
&=f(\partial E)-f(E^o)
\\
&\subset f(\partial E)
\end{align}


Como eu consigo pegar o máximo e o mínimo de uma consulta?

Question: Eu tenho a seguinte consulta:
select DATEDIFF("D",DtVencimento,DtBaixa) as atraso
  from Entrada
 where Id='1' and DtEmissao >='01/01/2020'
   and DtEmissao <='01/12/2020'
   and ((VlBaixado is not null and VlBaixado != 0)
   and DtBaixa is not null)
   and DATEDIFF("D",DtVencimento,DtBaixa) < 0;

Quando ela me retornar mais de uma linha eu preciso identificar o maior e o menor valor. Por exemplo, no resultado abaixo:

atraso

-6

-10

-20

Eu preciso identificar o menor (-20) e o maior (-6) valor.
Alguém pode me ajudar a retornar esses valores numa consulta no SQL Server?
Comment: Vc quer que os valores sejam retornados em linhas separadas?
Comment: Não necessariamente, eu só gostaria de conseguir fazer uma com os valores máximo e mínimo. Eu não estou sabendo como fazer.
Comment: Se pode ser na mesma linha então você pode utilizar as funções Min e Max
Comment: Obrigado @imex eu já tentei usar, mas da forma como eu faço não estava resolvendo.
Answer: Você pode utilizar CTE:
WITH foo(atraso) AS
(select DATEDIFF("D",DtVencimento,DtBaixa) as atraso
 from Entrada
 where Id='1'
   and DtEmissao >='01/01/2020'
   and DtEmissao <='01/12/2020'
   and ((VlBaixado is not null and VlBaixado != 0)
   and DtBaixa is not null)
   and DATEDIFF("D",DtVencimento,DtBaixa) < 0)

SELECT min(atraso), max(atraso) FROM foo;

Comment: Obrigado, ajudou bastante, eu não sabia fazer dessa forma. Resolveu aqui para o que eu preciso.
Answer: SELECT max(atraso) Min,
       min(atraso) Max
from (
       select DATEDIFF("D",DtVencimento,DtBaixa) as atraso
         from Entrada
        where Id='1' and DtEmissao >='01/01/2020'
          and DtEmissao <='01/12/2020'
          and ((VlBaixado is not null and VlBaixado != 0)
          and DtBaixa is not null)
          and DATEDIFF("D",DtVencimento,DtBaixa) < 0;
     ) Tab

Comment: Opa, eu estava fazendo desse jeito, só que não estava dando certo porque eu não estava colocando nome no from. :-) Obrigado.


Set the number of digits after the point in double

Question: In c# double type how can i set the number of digits after the point, i need only 4.
thank you.
Comment: inputValue = Math.Round(inputValue, 4);

Adapted from http://stackoverflow.com/questions/2357855/round-double-in-two-decimal-places-in-c
Answer: You can't. Binary floating point doesn't work like that. You can format a double that way (e.g. using "f4" as the format string), but if you're dealing with values which have a natural number of decimal places, then you should probably be using decimal instead. Could you give us more information about what your values represent?
Comment: i m doing an equality between 2 points's x and there values are
5.0000 and 4.999999996
and i need it te be true
Comment: @Bass: If you're only doing an equality test, then nobugz's answer is probably the right way to go. I would still consider whether you want to use decimal instead though - it depends on the kind of values you've got.
Answer: You can't set the number of digits after the point on the double directly.
You can change the string representation of the double using a format string.
One example would be:
string.Format("{0:0.####}", number);

Or as Jon Skeet points out:
number.ToString("f4")

Answer: Use this to compare two floating point numbers to 4 digits in the fraction:
  if (Math.Abs(a - b) < 1E-4) {
    // close enough
    //...
  }

Comment: If you want to be absolutely sure they are equal then it should be Double.epsilon rather than 1e-4. If you want to say they are 'close enough' equal then you're code is fine
Comment: Double.Epsilon cannot work as-is, it is far too small.  A proper epsilon is something like a * 1E-15 but that has to be incremented for errors accumulated by each FP operation.