How to get the sessionToken for currentUser?

Question: I work on a web app hosted on heroku. As database I try to use back4app. With help of the back4app documention I have realized the log in. Since two days I try to get the session to work with it.
Therefore I have read a lot of blogs, articels and of course the parse documentation. But I'm not able to get it to work. I hope, you will find my problem. Following code is my lastest attempt:
const express = require('express');
const server = express();
const path = require('path');
const bodyParser = require('body-parser');

const port = process.env.PORT || 8080;

const back4app = require('parse/node');

back4app.initialize("xxx","yyy");
back4app.serverURL = 'https://parseapi.back4app.com/';

server.use(express.static('web'));
server.use(bodyParser.json());

server.get('/lgn', (req, resp) => {
console.log("server.get('/lgn',...");
    resp.sendFile(path.join(__dirname + '/web/login.html'));
});

server.post('/lgn', (req, resp) => {
    const data =  req.body;

    console.log("server.post('/lgn',...");

    if(data.email != undefined){
        console.log(data.email);
        resetPassword(data);
    } else{
        logIn(data, function(err, user){
            console.log(user.get("sessionToken"));

            //How to get the user object in other routes?
            console.log('session');
            back4app.User.enableUnsafeCurrentUser(); //is this a secure solution?

            back4app.User.currentAsync().then(function(userObj) {
                console.dir(userObj.get("sessionToken"));
            });

            if(user){
                resp.send( JSON.stringify( {url: '/'}) );
            } else{
                console.log(err);
            }
        });
    }
});

function logIn(data, cb) {
    // Create a new instance of the user class
    var user = back4app.User
        .logIn(data.username, data.password)
            .then(function(user) {
                console.log('User successful logged in with name: ' +     user.get("username"));
                cb(null, user);
            })
            .catch(function(error){
                console.log("Error: " + error.code + " " + error.message);
                cb(error);
    });
}

server.listen(port, (err) => {
    if (err) {
        return console.log('something bad happened', err)
    }
    console.log(`server is listening on ${port}`)
});

The userObj is null. But why? What I have to do, that I get the currentUser and his session in other routes?
(I have also tryed to work with back4app.Session, but didn't get, what I want.)
Answer: It is unsafe to use the currentUser methods in a Node.js app.
Instead of:
logIn(data, function(err, user){
            console.log(user.get("sessionToken"));

            //How to get the user object in other routes?
            console.log('session');
            back4app.User.enableUnsafeCurrentUser(); //is this a secure solution?

            back4app.User.currentAsync().then(function(userObj) {
                console.dir(userObj.get("sessionToken"));
            });

            if(user){
                resp.send( JSON.stringify( {url: '/'}) );
            } else{
                console.log(err);
            }
        });

Use:
logIn(data, function(err, user){
            // This is your session token. You will have to send it back to your client. The client should store it and send it to the server in the other routes.
            const sessionToken = user.get("sessionToken");
            console.log(sessionToken);

            //How to get the user object in other routes?
            //In order to get the user in other routes you will have to use the sessionToken like this:
            back4app.User.me({ sessionToken }).then(function(userObj) {
                console.dir(userObj.get("sessionToken"));
            });

            if(user){
                resp.send( JSON.stringify( {url: '/'}) );
            } else{
                console.log(err);
            }
        });

Comment: In addition to the answer, I wanted to let you know that you can use the Back4App API directly from your frontend code. I mean... you don't even need the Node.js application running on Heroku for most of the cases.
Comment: Thank you @DaviMacêdo, my hero. back4app.User.me( sessionToken ).then(...).chache(...) works ... A last question for this. In which documentation I could have found this? On https://docs.parseplatform.org/js/guide/ I can't find this.
Comment: It was actually added to the SDK very recently and no docs were written about it yet. I will make sure it will be added to the docs.


Load UIViewController

Question: Eu tenho um UIViewController com o Background preto onde seria minha UIViewController principal (onde fica o menu e etc) e eu faço isso:
CredenciaisViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"Credencial"];
[_viewContainer addSubview:obj.view];
    _viewContainer.alpha = 1;

A CredenciaisViewController tem o background vermelho e eu carrego ela em um UIView que está na minha UIViewController principal, mas quando ela se carrega dentro da view ela fica metade branca e os UiButtons quando estão na parte branca não funcionam.
Por que isso acontece?
E como faço para resolver?
Answer: Você não pode adicionar um UIViewController como subview de outra UIView. Para esse propósito, existe o Custom Container.
Daí então você pode adicionar através do método addChildViewController:childController em seu UIContainerView e não UIView como no seu exemplo.
No interface builder você pode localizar ele, assim:

De forma dinâmica, faça algo assim na ação do seu UIButton:
- (IBAction)mostrarCredenciais:(id)sender {
    CredenciaisViewController *credenciaisView = [self.storyboard instantiateViewControllerWithIdentifier:@"Credencial"];

    [self addChildViewController:credenciaisView];
    [credenciaisView didMoveToParentViewController:self];
    credenciaisView.view.frame = self.containerView.bounds;
    [self.containerView addSubview:credenciaisView.view];
}

Com isso você não precisa fazer então a conexão no storyboard do container com o UIViewController. Basta ligar o IBOutlet (que é um UIView normal), que no meu exemplo é o containerView.
Comment: Quando eu arrasto o ContainerView para a tela, ele cria uma ligação com outra UIViewController, eu preciso dessa ligação ou consigo chamar dinamicamente a UIViewController que quero?
Comment: Inseri o Container View na minha UIViewController que tem o Menu.
E liguei ela no:
@property(nonatomic,weak)IBOutlet UIView *viewContainer;
Quando clica no menu tentei carregado o conteúdo de 2 formas.
Primeira forma:
        CredenciaisViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"Credencial"];
        [_viewContainer addSubview:obj.view];
Segunda Forma:
CredenciaisViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"Credencial"];
        [self addChildViewController:obj];

Mas não carregou o conteúdo em nenhuma das duas formas.
Comment: Por que não fazer a conexão no próprio *storyboard* já que todos os elementos que você precisa estão lá?
Comment: Paulo, realmente é melhor, fiz no storyboard e carregou, porém ele carrega assim que rodo o projeto e não quando eu clico no botão, como faço para ele não abrir de cara?
Desculpa, estou começando com ios!
Comment: Ok, neste caso realmente tem que ser algo dinâmico. Editei minha resposta, veja se você consegue reproduzir.
Comment: Paulo, consegui reproduzir sim e carregou certinho o conteúdo, porém quando eu clico na tela (fora de qualquer botão) com o conteúdo carregado ele pisca a tela e carrega novamente o conteúdo, duplicando ele. Por que?
Comment: Eu consegui parar de duplicar os conteúdos, eu fiz isso:
NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
    [v removeFromSuperview];
}

E parou de duplicar quando eu clico no background da tela onde não tem botão, porém quando clico na tela fora de qualquer botão dá uma piscada, só gostaria de tirar isso, o restante está perfeito.
Comment: Esse é um comportamento estranho que não encontrei aqui, veja o [exemplo](https://drive.google.com/file/d/0B1o0NIBAU7UjejV2Nm5aUjR4TXM/view?usp=sharing) bem simples que fiz. Em nenhum momento teve esse comportamento de piscar.

Load UIViewController


Problema para redirecionar com javascript (window.location.href)

Question: Olá, desejo que usuarios só consigam acessar determinada area do site se tiverem uma senha de acesso.
meu código é esse:
function redirect() {
  var pass;
  pass = prompt("Qual a palavra mágica?");
  if (pass == "asdfouch") {
    window.location.href = '[link]';
  }
  else {
    alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");
  }
}

Se digito a senha errada eu recebo o alerta, porem nada acontece ao digitar a senha correta.
Answer: O erro é: constante de cadeia não finalizada
Essa linha
alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código
        errado :/");
parece estar quebrada!

function redirect() {
  var pass;
  pass = prompt("Qual a palavra mágica?");
  if (pass == "asdfouch") {
    window.location.href = 'https://pt.stackoverflow.com/unanswered';
  }
  else {
    alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");
  }
}
<button onclick="redirect()">Click me</button>
Comment: @FelipeAugusto a minha resposta estava correta independentemente de vc ter me dito que estava usando onclick no form. Se o onclick está no botão não poderia estar no form evidentemente. Nas proximas perguntas procure postar o codigo tal como ele está na sua aplicação, isso é, procure não gerar mais erros na postagem da sua pergunta para não dar trabalho extra sem necessidade a quem quer lhe ajudar
Comment: a quebra de linha foi erro na hora que eu estava digitando aqui no site apenas (infelizmente, pois teria resolvido o problema hahah)

Quanto ao botao no codigo html, ele usa esse mesmo atributo.
Comment: @FelipeAugusto não entendi, "digitando aqui no site", vc quer dizer que errou na formulação da pergunta e então o erro não é esse na sua aplicação? Que o erro ainda persiste? No executar da minha resposta está funcionando!
Comment: foi um erro apenas de formataçao aqui no proprio site. No programa a linha nao esta quebrada. Infelizmente o problema persiste.
Comment: o chamado da funçao no html é feito assim:
Comment: Ai está o motivo, você pode fazer assim: `` sem o uso do `form`
Comment: Funcionou, aplicando essa mudança. obg!
Answer: Além do window.location.href você pode usar window.location.replace

Se você quiser simular alguém clicando em um link, use location.href
Se você quiser simular um redirecionamento HTTP, use location.replace
Fonte: Como redirecionar para outra página? ( Stack em Inglês )

function redirect() {
  var pass;
  pass = prompt("Qual a palavra mágica?");
  if (pass == "asdfouch") {
     window.location.replace("https://pt.stackoverflow.com/unanswered");
  }
  else {
    alert("Ops, desculpe mas você ainda não tem acesso ou digitou o código errado :/");
  }
}
<input type="button" value="Posso entrar?" onclick="redirect()">


iOS4 code on iOS3 devices

Question: Is it possible to have iOS4 specific code (ie the MKMapView overlays) in an application, build using 4.0, set the Deployment Target to 3.0, and still have it work so long as the iOS4 code isn't called on a 3.x device?
I am trying to do that now, and only calling the iOS4 code if the device supports it, but I can't get it installed. GDB is freaking out. Here's what I get when I build for an iOS3 device:
dyld: Symbol not found: _OBJC_CLASS_$_MKOverlayView
Referenced from: /var/mobile/Applications/1EE8EC13-FA01-43CB-A617-9B5D268ECD13/maps.app/maps
Expected in: /System/Library/Frameworks/MapKit.framework/MapKit

Data Formatters temporarily unavailable, will re-try after a 'continue'. (Not safe to call dlopen at this time.)
mi_cmd_stack_list_frames: Not enough frames in stack.
mi_cmd_stack_list_frames: Not enough frames in stack.

I want this application to run on 3.0 and up, and use the new MKMapView overlay on 4.0 devices.
Specifically, I am implementing the tiled image overlay code demonstrated at WWDC, which uses a custom TileOverlay that implements the MKOverlay protocol, and a custom TileOverlayView which is a subclass of MKOverlayView.
Answer: You need to build with the Base SDK set to 4.0 and the Deployment Target set to 3.0.
Then, when trying to use a class that only exists in 4.0, use NSClassFromString("MKOverlayView") or whatever it's called. That will return nil if the class doesn't exist.
This post from Matt Gallagher has more detailed tips for this kind of situation:
http://cocoawithlove.com/2010/07/tips-tricks-for-conditional-ios3-ios32.html
Answer: Try weak linking the MapKit framework.

iOS4 code on iOS3 devices


Drupal 7 - eRecruiter profile with Solr Fatal Errors

Question: I just installed Drupal 7 using the eRecruiter profile release but I am gettig loads of errors. I know it's not me server as I run 10 other drupal site on my server and there is nothing showing up in the drupal logs.
These are the errors:
This one when I click in Job Search:
Fatal error: Call to a member function pre_execute() on a non-object in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/views/plugins/views_plugin_display.inc on line 2432
This one when I click on Resume Search:

Fatal error: Call to a member function pre_execute() on a non-object in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/views/plugins/views_plugin_display.inc on line 2432
And this when I click on My Resume:
Fatal error: Call to undefined function entity_i18n_string() in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/field_collection/field_collection.module on line 913
I used the exact drupal and module releases that were included with the profile from here:
http://epiqo.com/recruiter
I got the errors... did some searching on line and one person recomended updating Drupal and ALL the mondules. I did all the updates but the errors are still present.
I have installed Apache Solr and it's working fine and drupal says that it has found it.
I then tried to install it localy on my mac and I'm getting the same errors.
My php_error.log reported the following:
[01-May-2012 17:50:28] PHP Fatal error:  Access level to SearchApiViewsHandlerField::$additional_fields must be public (as in class views_handler_field) in /Users/xxx/Sites/vhosts/eRecruiter/profiles/recruiter/modules/search_api/contrib/search_api_views/includes/handler_field.inc on line 195
and:
I get the same sort of log message when I click on Job search, Resume search and my resume.
Here's a link to the online demo version: http://drupaljobs.epiqo.com/
I'm desperatly needing help with this as I have spent hours search forums and blogs.. got me nowhere :(
Any help will be much appreciated.
C
Answer: A lot of errors here, let's see if we can do something..
Job/Resume Search
Fatal error: Call to a member function pre_execute() on a non-object..

When you try to invoke the action, the result does not return the query object, and for that reason you have this error, for example.
php_error.log
PHP Fatal error: Access level to SearchApiViewsHandlerField

Changing from protected to Public Field made solve this issue.
My Resume
Fatal error: Call to undefined function entity_i18n_string() in

Entity 7.x-1.x-dev released on February 28, 2012 - 08:13 no longer contains the function entity_i18n_string().
Comment: thanks @Voislav, `Changing from protected to Public Field made solve this issue.` where and how do I do that? This is a profile so I didn't create any of the content types or view.
Comment: Hi @Voislav my last comment may have been missleading.. I havne't fixed this. I was tryin gto quote your line.where and how do I do that? This is a profile so I didn't create any of the content types or view.
Comment: yes I know, but I'm afraid that I do not know how I can help giving you a solution here and also for the [another](http://stackoverflow.com/questions/10507256/drupal-7-errors-after-upgrading-from-7-12-to-7-14/10507576#comment13613844_10507576) question., the true is that in fact I'm not a drupal expert. I just try it to help you with my limited knowledge that I learned on my own, I have never worked in industry.. sorry :(


Explain why $Cov(X-E(X\mid Y), Y) =0 $

Question: $$Cov(X-E(X\mid Y), Y) =0 $$
Above $Cov$ denotes Covariance.
My textbook says above identity always holds, but I can't figure why it is so.
Any hint or advice?
Also, if $Cov(X-E(X\mid Y), Y) =0 $ always holds, Does $Var(X-E(X\mid Y), Y) =0 $ always hold?
Comment: Your second question (about the variance) is not correctly formulated. Variance takes one argument, e.g. $Var(X)$ or $Var(E[X\mid Y])$. There is not such thing as $Var(X,Y)$.
Comment: right.. will remain it without edit for later viewers.
Answer: By definition,
\begin{align}
\operatorname{Cov}(X-\mathsf E(X|Y),Y)&=\mathsf E(X-\mathsf E(X|Y)-\mathsf EX+\mathsf E\mathsf E(X|Y))(Y-\mathsf EY)\\
&=\mathsf E(X-\mathsf E(X|Y))(Y-\mathsf EY)\\
&=\mathsf E(XY)-\mathsf E(Y\mathsf E(X|Y)) -\mathsf EX\cdot\mathsf EY +\mathsf EY\cdot\mathsf E\mathsf E(X|Y)\\
&=\mathsf E(XY)-\mathsf E(XY) -\mathsf EX\cdot\mathsf EY +\mathsf EY\cdot\mathsf EX\\
&=0
\end{align}
Here several properties of conditional expectations are used. For example, $\mathsf E\mathsf E(X|Y)=X$ and $Y\mathsf E(X|Y)=\mathsf E(XY|Y)$.
Comment: EE(X|Y) denote Expectation of E(X|Y) I think, but when calculates it, is it integrated by x or y ? Still I am confusing with myself..
Comment: @Beverlie In general we do not compute a expectation by integrating by $X$, $Y$ or any particular random variable. Instead, we integrate on the probability space $\Omega$ w.r.t. the probability measure. But if the function being integrated is $X$-measurable, then by change of variables, we may integrate w.r.t. the measure induced by the distribution function of a r.v. $X$. In this sense, we may consider the second expectation being an integration by $Y$.
Answer: Note that in the law of total expectation $$\operatorname{E}[\operatorname{E}[X \mid Y]] = \operatorname{E}[X]$$ the nested expectations on the LHS are such that the innermost expectation is with respect to $X$ for a fixed $Y$, and the outer is taken with respect to $Y$.  That is to say, $\operatorname{E}[X \mid Y]$ is a random variable that is a function of $Y$.  For the sake of conceptual convenience, call this function $g_X(Y) = \operatorname{E}[X \mid Y]$, and it obeys the property that $\operatorname{E}[g_X(Y)] = \operatorname{E}[X]$.
With this in mind,
$$\begin{align*}
\operatorname{Cov}[(X-\operatorname{E}[X \mid Y]), Y]
&= \operatorname{E}[X - g_X(Y), Y] \\
&= \operatorname{E}[(X - g_X(Y))Y] - \operatorname{E}[X - g_X(Y)]\operatorname{E}[Y] \\
&= \operatorname{E}[XY - g_X(Y)Y] - (\operatorname{E}[X] - \operatorname{E}[g_X(Y)])\operatorname{E}[Y] \\
&= \operatorname{E}[XY] - \operatorname{E}[g_X(Y)Y] - (\operatorname{E}[X] - \operatorname{E}[X])\operatorname{E}[Y] \\
&= \operatorname{E}[XY] - \operatorname{E}[g_X(Y)Y].
\\
\end{align*}$$
From here, it seems that no further simplification is possible.  But since $$g_X(Y)Y = Y \operatorname{E}[X \mid Y] = \operatorname{E}[XY \mid Y],$$ it follows that $$\operatorname{E}[g_X(Y) Y] = \operatorname{E}[\operatorname{E}[XY \mid Y]] = \operatorname{E}[XY],$$ where the rightmost expectation is with respect to $X$ and $Y$ jointly.  Thus the covariance is zero as claimed.

Explain why $Cov(X-E(X\mid Y), Y) =0 $


How to open a partition handle to get its information on a dynamic disk?

Question: For the purpose of logging in my application I need to get information about physical partitions on the disk, such as the info provided in PARTITION_INFORMATION_EX. I have no problem doing it for "Basic disks" using the following method:
First let's assume the following drive configuration:

Then the following code works fine:
//Say, if I want to get info for partion 1 on disk 0 (or volume C:)
HANDLE hPart = ::CreateFile(L"\\\\?\\GLOBALROOT\\Device\\Harddisk0\\Partition1",
    GENERIC_READ,
    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
    OPEN_EXISTING,  0, NULL);
if(hPart != INVALID_HANDLE_VALUE)
{
    PARTITION_INFORMATION_EX pix = {0};
    DWORD bytesReturned = 0;
    if(::DeviceIoControl(hPart, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pix, sizeof(pix), &bytesReturned, NULL))
    {
        //Got info OK
    }

    ::CloseHandle(hPart);
}

But if I try to retrieve the info on a "dynamic partition", say, disk 2, partition 1 (or 2nd half of spanned volume F:) and I try to use "\\\\?\\GLOBALROOT\\Device\\Harddisk2\\Partition1" in a call to CreateFile, it fails with error code 2, or ERROR_FILE_NOT_FOUND.
So the question is, how do I retrieve partition info on a dynamic disk?
Comment: Have you tried using WinObj to see what the actual device names are on your system?  Might give you a useful hint.
Comment: @HarryJohnston: I wish WinObj had a search feature. I tried looking and even though I can find symlinks for (disk) devices, I don't see all partitions for them as I get from the snap-in like I showed above.
Answer: Read the documentation:
Basic and Dynamic Disks
In particular, this section provides a hint:

Detecting the Type of Disk
There is no specific function to programmatically detect the type of disk a particular file or directory is located on. There is an indirect method.
First, call GetVolumePathName. Then, call CreateFile to open the volume using the path. Next, use IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS with the volume handle to obtain the disk number and use the disk number to construct the disk path, such as "\\?\PhysicalDriveX". Finally, use IOCTL_DISK_GET_DRIVE_LAYOUT_EX to obtain the partition list, and check the PartitionType for each entry in the partition list.
Comment: Thanks. I found it too. Unfortunately that last statement about `IOCTL_DISK_GET_DRIVE_LAYOUT_EX` is incorrect. Or I should say, it applies to "Basic disks" only. In case of a dynamic disk, like Disk 2 in my screenshot, it would appear as just one full-disk-size partition for a "Dynamic disk."
Comment: Yeah, the control code documentation confirms that: "only supported on dynamic disks that are boot or system disks, or have retained entries in the partition table."  Basically, it is telling you about the actual, underlying partitions on the physical disk - not about the higher-level dynamic volumes.
Comment: I think to get information on dynamic disks you might have to use [VDS or the Windows Storage Management API](https://msdn.microsoft.com/en-us/library/windows/desktop/bb986750(v=vs.85).aspx) as appropriate.
Comment: @HarryJohnston: I've never used VDS. You don't have a sample C code, do you?
Comment: No, I've never used it either.


Populating a pandas DataFrame

Question: I have a dataframe df:
    AuthorID  Year  citations
0          1  1995         86
1          2  1995         22
2          3  1995         22
3          4  1995         22
4          5  1995         36
5          6  1995         25

and another dataframe which I created and initialized all to zeros df2 where each index represents an AuthorID from df:
         1994  1995  1996  1997  1998  1999  2000  2001  2002  2003  2004
1           0     0     0     0     0     0     0     0     0     0     0
2           0     0     0     0     0     0     0     0     0     0     0
3           0     0     0     0     0     0     0     0     0     0     0
4           0     0     0     0     0     0     0     0     0     0     0
5           0     0     0     0     0     0     0     0     0     0     0
6           0     0     0     0     0     0     0     0     0     0     0

Now what I want to do is iterate through df and add the citation value to its correct location in the second matrix. So if I am to fill up df2 based on what I have above, it would look like this:
         1994  1995  1996  1997  1998  1999  2000  2001  2002  2003  2004
1           0     86     0     0     0     0     0     0     0     0     0
2           0     22     0     0     0     0     0     0     0     0     0
3           0     22     0     0     0     0     0     0     0     0     0
4           0     36     0     0     0     0     0     0     0     0     0
5           0     25     0     0     0     0     0     0     0     0     0
6           0     0     0     0     0     0     0     0     0     0     0

This is very simply put.
Now what I have done is the following:
for index, row in df.iterrows():
     df2.iloc[row[0]][row[1]] = df2.iloc[row[0]][row[1]] + row[2]

But it keeps giving me the following:
IndexError: index out of bounds

So I tried:
for index, row in df.iterrows():
     df2.at[row[0], row[1]] = df2.at[row[0], row[1]] + row[2]

and it gives me:
ValueError: At based indexing on an non-integer index can only have non-integer indexers

I also tried df.iat but that also didn't work.
Not sure what I am doing wrong. When I check df.dtypes they all returned int64
Answer: why cant you just pivot the first data frame like this
>> df.pivot(index='AuthorID', columns='Year', values='citations')

This will bring all the years as columns and index will be your AuthorID.
Comment: I really want to make some calculation with the citation not put it as is as I iterate. But i figured explaining it this way might be simpler. What I really want is to spread the value of the citations evenly over the 3 years that follow its publishing year. So authorid=1, year=1995, citation=86, will add 86/3 in df2[1]['1996'], df2[1]['1997'], and df2[1]['1998']
Answer: So, here's a long way to do what you want : assign 1/3rd values to other years than 1995 for each AuthorID.
x is your data-frame.
We will add years: 1996, 1997 and 1998 for each AuthorID below and store in y data-frame.
y = pd.DataFrame([[i, y, 0] for y in [1996,1997,1998] for i in x.AuthorID], columns=['AuthorID','Year','citations'])
z = x.append(y)

Below, we will assign 1/3 value of 1995 citations to all the other years for the same author.
for id in z['AuthorID'].unique():
    condition = (z['AuthorID']==id) & (z['Year']>1995)
    citation2 = (z.loc[(z['Year']==1995) & (z['AuthorID']==id),'citations']/3).values
    z['citations'][condition] = citation2

In [1541]: z.pivot(index='AuthorID', columns='Year', values='citations')
Out[1541]:
Year      1995       1996       1997       1998
AuthorID
1           86  28.666667  28.666667  28.666667
2           22   7.333333   7.333333   7.333333
3           22   7.333333   7.333333   7.333333
4           22   7.333333   7.333333   7.333333
5           36  12.000000  12.000000  12.000000
6           25   8.333333   8.333333   8.333333

Comment: this would work if I only had years 1995 to 1998, which isn't the case. What is wrong with iterating through the first df and adding to the second df2? I want to be able to be flexible to do other calculations if needed. I don't know why basic looping just won't work?

Populating a pandas DataFrame


ExpressJS - can't get data on update User

Question: I want to create an experience array in User model with new data, and the problem is that I don't get saved data in exec function so I can push new data in array on frontend. This is what I got so far.
router.post('/:username/experience', function(req, res) {
const username = req.params.username;

User.findOneAndUpdate(
    username, {
        $push: {
            experience: req.body
        }
    }, {
        safe: true,
        upsert: true
    })
    .exec(function (err, data) {
        console.log(data, "------>");
    });
})

This is my schema for experience, which is called in User model like experience: [ExperienceSchema].
const ExperienceSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    company: {
        type: String,
        required: true
    },
    from: {
        type: Date,
    },
    to: {
        type: Date,
    },
    workingNow: {
        type: Boolean,
        default: false
    },
    description: {
        type: String
    }
}, {
    usePushEach: true
})

Comment: Did you try adding `new: true` to the `findOneAndUpdate` options? Right after `upsert: true`  https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document#answer-32811548  But not sure if this is the issue here, just try
Comment: Hm yeah man, now I got the array with new objects, can you please explain?
Comment: Well `findOneAndUpdate` returns by default the original document. If you want the new updated document you need `new: true` thats it. Added answer because it resolved your problem.
Answer: Since findOneAndUpdate returns the original document (state before update) you need to add new: true to the options in order to get the updated document.
options:
{
  safe: true,
  upsert: true,
  new: true
}


Como pegar elementos de uma página diferente?

Question: Estou criando um sistema para pegar os 4 primeiros parágrafos de uma determinada página do Wikipédia e colar-los na div id="txtTextoResposta" da página que o usuário está, porem o problema que estou tendo, é que não sei como fazer para pegar o conteúdo de um outro site.
Meu código:
function resp(){
    var input = prompt();
    var wiki = document.download("https://pt.wikipedia.org/w/index.php?search=" + input);
    var x = wiki.getElementById("mw-content-text").getElementsByTagName("p");
    var linhas = x.length > 4 ? 5 : x.length;
    for (var i = 0; i < linhas; i++){
        document.getElementById("txtTextoResposta").innerHTML += x[i].innerText;
    }
}

Inventei a função document.download() para ilustrar melhor o que eu quero fazer.
Tentei também utilizando o jQuery, dessa maneira:
javascript: (function(e, s) {
    e.src = s;
    e.onload = function() {
        jQuery.noConflict();
        console.log('jQuery injected');
    };
    document.head.appendChild(e);
})(document.createElement('script'), '//code.jquery.com/jquery-latest.min.js')

$.get("https://pt.wikipedia.org/w/index.php?search=" + input, function(data) { $(".result").html(data); alert("Load was performed."); });
//Neste caso, o input tinha o valor "Kant"

Mas me retorna o seguinte erro:

XMLHttpRequest cannot load https://pt.wikipedia.org/wiki/Immanuel_Kant. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.educacional.com.br' is therefore not allowed access.
Comment: Você quer fazer isso com javascript? Não pretende cachear esses resultados para não ter que rodar essa rotina de grab repetidas vezes para o mesmo termo ? Posso sugerir uma solução em PHP.
Comment: Sim, é preciso que seja feito em javascript. Pois eu não estou fazendo isso para um site, e sim para usar no console do navegador.
Comment: Mas poderia usar um ajax fazer o carregamento em backend com PHP usando o XPATH e DOM e devolver a resposta para o javascript que imprimiria no console.
Answer: Eu não sei se isso ajudaria, mas você poderia fazer uma requisição a url externa com jquery
$.get( "url", function( data ) {
    $( ".result" ).html( data );
    alert( "Load was performed." );
  });
Método get
Em seguida utilizando o callback ler o conteúdo com DOM, espero que seja útil essa resposta!
Referencia para o uso de DOM
Comment: Editei minha pergunta, veja o erro que me retorna.
Comment: É eu imaginei que daria isso o navegador bloqueou por segurança. Mas não tinha certeza. Nesse caso tanto por perfomance quanto por restrições de segurança eu aconselho o ajax para um PHP.
Comment: É, mas como eu disse, não tem como, porque eu vou usar isso no console de desenvolvedor do Google Chrome e não em um site.
Answer: De acordo com a documentação da Wikipédia, disponível em https://www.mediawiki.org/wiki/Manual:CORS:

For anonymous requests, origin query string parameter can be set to *
  which will allow requests from anywhere.

Para fazer requisições anônimas, é preciso usar uma query origin=*.
Então, funciona se a sua variável wiki estiver definida da seguinte forma:
var wiki = document.download("https://pt.wikipedia.org/w/index.php?origin=*&search=" + input);

Comment: Não funcionou, retorna o mesmo erro.


How to extract a piece of string from vold.fstab

Question: I want to know how can I extract the sdcard path from the vold.fstab file in android phones.
dev_mount sdcard /storage/extSdCard auto/
devices/aform/msm_sdcc.3/mmc_host/
mmc1/

How do I extract the /storage/extSdCard only?
Answer: Please don't parse vold.fstab, it's an internal implementation detail of the platform, and it may change between releases.  You should only rely on public APIs like Context.getExternalCacheDirs().


Does ssh-copy-id overwrite previous keys?

Question: I haven't yet found any definitive answer on this using google.
It seems like the answer is no, but I need to know for sure before I go ahead and do it.
Does ssh-copy-id append the key to authorized_keys or does it overwrite the previous keys?
Thanks.
Addendum:
So the answer is right there in the man page. Go figure.
I guess the question can at least help fellow Google-jockeys like me who get a little too used to googling and finding tutorials (that often explain things in layman's terms for us poor folks who have only used Windows our whole lives).
Comment: You should learn to read the [man pages](http://linux.die.net/man/1/ssh-copy-id). They contain useful information.
Answer: man ssh-copy-id says:
By default it adds the keys by appending them to the remote
user's ~/.ssh/authorized_keys (creating the file, and directory, if necessary).

Answer: No, it appends.
http://linux.die.net/man/1/ssh-copy-id
ssh-copy-id is a safe operation.


How to save a vote of an anonymous user only after registering using modal window?

Question: Here is my usecase:

Only authenticated user can vote.
If an anonymous user tries voting, after the voting is done, the user is represented a modal window for login/register.
If the user registers or loges in, the vote is saved.

The vote calculation is done using cron or other module. I do not have tie up with any particular module (and fine with writing a basic one). I am currently trying my luck with Rules, Voting Rules, Fivestar and obviously, Voting API. For login/registration persona and fbauth is used, so no email verification is requierd.
A similar problem is discussed in A module that allows user to create content anonymously, then if they register, assigns the content to them, however my use case involved voting and email-free registration. Voting makes it more complicated while email-free registration (hopefully) makes it easier.
PS: I want to follow the same work flow for different nodes with plus1 (or similar) module, so a generic approach is requested.
Comment: just an idea: if add a vote event is exposed to rules,then on action store the node id where the vote was casted ,now assuming you are able to show the login form in popup- agai in hook_user_presave() and hook_user_save() or hook_user_login check if session values is set then use the vote api to cast the cote programmatically against that user,and then clear the session.
Answer: You could store anonymous votes in a cookie, then on login/register, check to see if that cookie exists and cast the votes accordingly.

When an anon user tries to vote, use user_cookie_save() to save the Entity Type and Entity ID of the Entity that the user was trying to vote on in a cookie. Name it something like pending_votes. At the same time, you can trigger your modal login window. It's possible that a user won't login/register at that time and it's also possible that they will attempt to vote on other Entities before finally logging in. So you'll probably want to store the Entity Type and ID as a serialized array.
Then you can hook into a user logging in with hook_user_login() and check for the existence of the pending_votes cookie. If it's there, use it's contents along with votingapi_set_votes() to cast the pending votes. (delete the pending_votes cookie afterwards so they don't cast more votes each time they log in)
Comment: Nice solution! Do you think I can use it with any popular voting modules, like Fivestar or Rate? Both gives API to execute function chunks before casting the vote.
Comment: The general idea should work with any module that uses the [Voting API](https://drupal.org/project/votingapi), which both Fivestar and Rate do.
Answer: Lazy Registration was designed for a similar reason but I'm not sure how stable it is. Either way, it will provide a good starting point for you.

The Lazy Registration module captures actions made by anonymous users and stores them against a temporary user account until they are ready to register.
Comment: That's a really interesting module. Thanks. I wasn't aware of it. It looks like it performs the actions by anonymous users regardless of whether they eventually register or not. And it would probably be a lot of work to get the voting_api and whatever front-end module the OP uses to integrate with it. But it's very interesting nonetheless.


Transpose and concatenate R data.tables

Question: This is a simple task in R, but it appears that there is a misunderstanding on my part. Any help clarifying is appreciated:
I have the following R data.table of a single text file:
dat = as.data.table(fread(...))

      type         proportion
  1:  type_3      0.5570502431
  2:  type_5      0.1108589951
  3:  type_1      0.0688816856
  4:  type_9      0.0601296596
  5:  type_8      0.0554294976
  6:  type_12     0.0450567261
  7:  type_2      0.0322528363
  8:  type_4      0.0202593193
  9:  type_7      0.0166936791
 10:  type_6      0.0145867099
 11:  type_10     0.0141004862
 12:  type_11     0.0040518639

There are approx. 500 of these text files, each of which I can read in as an R data.table and put into an R list. This is quite simple in principle:
list_of_data.tables = list(dat1, dat2, dat3, ...)

concat = do.call("rbind", list_of_data.tables)

This isn't the format I would like though. I would like to take the column type as the header of the final concatenated data.table, type_1, type_2, type_3, etc. Then, each row of the final concatenated data.table would be the column porportion for dat1, etc.
Here is the format of the final concatenated data.table:
     type_1 type_2 type_3 type_4 type_5 type_6 ...
dat1 0.557  0.110  0.068  0.0601 0.0554 0.045  ...
dat2 0.23   0.324  0.12   0.0723 0.002  0.004  ...
...

My first thought would be to transpose the original data.table with t(), but this doesn't make type the header. Furthermore, I am not sure how to label each row by dat1, etc.
What is the correct way to do such a simple thing?
Comment: Side note: `?fread` explains that it returns a data.table, no need to coerce. Also, `?rbind` explains that you can use `rbindlist` instead of `do.call`ing it.
Comment: Thank you for this, I didn't know this!
Answer: For each dat you need to spread the data
library(tidyr)
new.dat <- dat %>%
             spread(type, proportion)

Then for your list_of_new.dat, assuming they are in a list, you can bind them with
Reduce("full_join", list_of_new.dat)

Comment: `tidyr`...I was originally thinking of using `map` verbs as well, but since I didn't, you can use `tidyr` only. I've edited my answer. But I'm not sure where `%>%` comes from...maybe `dplyr`?
Comment: I think I would have to create a new column for each `dat1`, `dat2`, etc.
Comment: Labeling each row by which `data.table` it comes from in the R list, i.e. `dat1`, `dat2`, etc.
Otherwise, it works!
Comment: As long as you make your list in order, `dat1-N`, then `Reduce` will keep the same order...you can then use `rownames(desired) <- c("dat1"...`. Does that work?
Comment: What is the difference between `Reduce("full_join", list)` and `do.call("rbind", list)`?
Comment: Nothing really. `Reduce` might be faster than `do.call("rbind"`, but they should give you the same output.

Transpose and concatenate R data.tables


Linear transformation matrix wrto 2 basis $\beta = \{ (1,1,0), (1,0,1),(0,1,1)\}$ and $\beta' = \{ (2,1,1), (1,2,1),(-1,1,1)\}$

Question: Let $\beta = \{ (1,1,0), (1,0,1),(0,1,1)\}$ and $\beta' = \{ (2,1,1), (1,2,1),(-1,1,1)\}$ be two ordered basis of $R^3$. Then find a linear transformation $T:R^3 \rightarrow R^3$ which transforms from $\beta \rightarrow \beta'$. Use this matrix representation to find $T(x)$ , where $x=(2,3,1)$
My attempt:
Let $\bar e $ be standard basis
Let input basis be $x_1, x_2, x_3$ and output basis $\beta'= {y_1,y_2,y_3}$
$T(1,1,0) = (2,1,1)_{\bar e} = 1y_1 $
$T(1,0,1) = (1,2,1)_{\bar e} = 1y_2 $
$T(0,1,1) = (-1,1,1)_{\bar e} = 1y_3 $
So $[T]_{\beta}^{\beta'} =
\begin{bmatrix}
    1&0&0 \\
   0&1&0 \\
0&0&1
\end{bmatrix}
$
can you pls tell me is this matrix of linear transformation correct?
Now $(2,3,1)=a(1,1,0)+b(1,0,1)+c(0,1,1) = (a+b, a+c,b+c) \implies a = 2, b=0, c=1$
$T(2,3,1) = T([2,0,1]_{\beta}) = 2 T(x_1)+0T(x_2)+1T(x_3)=(3,3,3)_{\bar e}$ i..e, wrto standard basis T(2,3,1) = (3,3,3)
Pls correct me if i am going wrong.
Comment: Not ethat the matrix you are looking for takes vector in basis $\beta$ and returns it in basis $\beta'$. To check this you can consider the vector $(2,1,1)$ that is $(1,1,0)$ in basis $\beta$ and $(1,0,0)$ in basis $\beta'$. Thus you should have $$T(1,1,0)=(1,0,0)$$
Comment: so Identity matrix is linear transformation from basis $\beta \rightarrow \beta'$. In your below derivation, it should be $N^{-1}M$ which is different. Defenetely i made a mistake. Where i made, i am not able to trace
Comment: It is easy to make mistake without a clear distinction between vectors and components. I highly recommend to solve by matrix notation as I've shown and also verify simple cases by direct calculation.
Comment: But i am still curious to know my mistake.
Comment: You are considering $T(1,1,0)=y_1$ but what T take in input are the components with respect to the basis $\beta'$. Thus you should look for T such that $T(1,0,0)=(a,b,c)$ where (a,b,c) are the components of the vector (1,1,0) in the basis $\beta'$. The problem is that you don't know these components (which are $a=-\frac13,b=1,c=-\frac23$).
Comment: Still i am not getting. $T([1,0,0]) = T(a(1,1,0)+b(1,0,1)+c(0,1,1)) = T(\frac{1}{2}x_1 + \frac{1}{2}x_2 +\frac{(-1)}{2}x_3) = \frac{1}{2} y_1 +\frac{1}{2} y_2 - \frac{1}{2} y_3$ ....

$T[0,1,0] = [\frac{1}{2}, \frac{-1}{2}, \frac{1}{2}]$.... So matrix is different.
Comment: can you pls have a look?
Comment: I can try to elaborate anoter aswer following your method to show that it is completely equivalent to that I have just given.
Answer: Let solve the problem in matrix notation.
At first consider the matrix $M$ wich columns are the vectors of $\beta = \{ (1,1,0), (1,0,1),(0,1,1)\}$ that is
$$M=\begin{bmatrix}
1 & 1 & 0\\
1 & 0 & 1\\
0 & 1 & 1\end{bmatrix}$$
which, that's the key point, represent the change of basis from $\beta $ to the standard basis, thus
$$v_e=Mv_\beta \implies v_\beta=M^{-1}v_e$$
Now write down the corresponding matrix $N$ for the base $\beta^*$ and we have
$$N=\begin{bmatrix}
2 & 1 & -1\\
1 & 2 & 1\\
1 & 1 & 1\end{bmatrix}$$
$$v_e=Nv{_\beta*}\implies v_\beta*=N^{-1}v_e$$
Thus the transformation from $\beta \rightarrow \beta^*$ is espressed by
$$v_\beta*=N^{-1}v_e \quad v_e=Mv_\beta \implies v_\beta*=N^{-1}Mv_\beta $$
that is the matrix
$$[T]_{\beta}^{\beta'} = N^{-1}M=\begin{bmatrix}
-\frac13 & \frac43 & \frac13\\
1 & -1 & 0\\
-\frac23 & \frac23 & \frac23\end{bmatrix}$$
Comment: this looks perfect. I am not able to get where i went wrong in my method. can you pls have a look?
Comment: @anirudhb I try to check it!
Answer: Following your method, we are looking for a matrix $T$ which transform vectors from the basis $\beta=\{x_1, x_2, x_3\}$ to the basis $\beta'=\{y_1, y_2, y_3\}$, the $T$ is such that

$Tx_{1,\beta}= T(1,0,0)=(a_1,b_1,c_1)=x_{1,\beta'}$
$Tx_{2,\beta}= T(0,1,0)=(a_2,b_2,c_2)=x_{2,\beta'}$
$Tx_{3,\beta}= T(0,0,1)=(a_3,b_3,c_3)=x_{3,\beta'}$

thus we have
$$[T]_{\beta}^{\beta'} =
\begin{bmatrix}
a_1&a_2&a_3 \\
b_1&b_2&b_3 \\
c_1&c_2&c_3
\end{bmatrix}$$
where
$$a_1y_1+b_1y_2+c_1y_3=x_1$$
$$a_2y_1+b_2y_2+c_2y_3=x_2$$
$$a_3y_1+b_3y_2+c_3y_3=x_3$$
which can be written in matrix form as
$$N=[y_1\,y_2\,y_3]$$
$$M=[x_1\,x_2\,x_3]$$
$$NT=M\implies T=N^{-1}M$$
Notably we have
$$N=\begin{bmatrix}
2 & 1 & -1\\
1 & 2 & 1\\
1 & 1 & 1\end{bmatrix} \implies N^{-1}
=\begin{bmatrix}
\frac13 & -\frac23 & 1\\
0 & 1 & -1\\
-\frac13 & -\frac13 & 1\end{bmatrix}$$
$$M=\begin{bmatrix}
1 & 1 & 0\\
1 & 0 & 1\\
0 & 1 & 1\end{bmatrix}$$
$$\implies T=N^{-1}M=\begin{bmatrix}
\frac13 & -\frac23 & 1\\
0 & 1 & -1\\
-\frac13 & -\frac13 & 1\end{bmatrix}\begin{bmatrix}
1 & 1 & 0\\
1 & 0 & 1\\
0 & 1 & 1\end{bmatrix}=\begin{bmatrix}
-\frac13 & \frac43 & \frac13\\
1 & -1 & 0\\
-\frac23 & \frac23 & \frac23\end{bmatrix}$$
Comment: thnx a lot for the patience and making me understand. I will recheck my calculation part again. I am getting different answer interms of 1/2s
Comment: If you do not mind, can you pls calculate? I tried but i am getting matrix interms of 1/2 with sign change ....
Comment: @anirudhb I've added the full calculation details


Output from registers using inline assembly are zeroed out

Question: I've been through a couple of threads already, and everything seems to be worded correctly...but my output_01 is returning false.  It seems that the inline assembly is writing zeros to my variables...and I just can't figure out why.  Below is code from the main c file which calls the assembly, and the assembly it calls (and thrown in the header file as well, though I don't think it has any bearing...but the devil is in the details...right?
main file
#include stdio.h
#include "lab.h"

int output_01();

int main()
{
  printf("Starting exercise lab_01:\n");
  if(output_01())
    printf("lab_01: Successful!");
  else
    printf("lab_01: Failed!");
  return 0;
}

int output_01()
{
  int eax=0;
  int edx=0;
  int ecx=0;

  asm("call lab_01;"
      "mov %0, eax;"
      "mov %1, edx;"
      "mov %2, ecx;"
      :
      :"r" (eax), "r" (edx), "r" (ecx)
      :
  );
  if(eax==3 && edx==1 && ecx==2)
  {
    printf("\teax = %i\n",eax);
    printf("\tedx = %i\n",edx);
    printf("\tecx = %i\n",ecx);
    return 1;
  }
  else
  {
    printf("\teax = %i\n",eax);
    printf("\tedx = %i\n",edx);
    printf("\tecx = %i\n",ecx);
    return 0;
  }
}

assembly file
BITS 32         ;you must specify bits mode
segment .text   ;you must specify a section
GLOBAL lab_01, labSize_01
    lab_01:
        ;instructions:
        ;the following registers have the following values:
        ;eax = 1
        ;edx = 2
        ;ecx = 3
        ;Make it so that the registers have the following values, using only the allowed opcodes and registers:
        ;eax = 3
        ;edx = 1
        ;ecx = 2
        ;Allowed registers: eax,ebx,ecx,edx
        ;Allowed opcodes: mov, int3
        ;Non volatile registers: ebp, ebx, edi, esi
        ;Volatile registers: eax, ecx, edx
        ;Forbidden items: immediate values, memory addresses
        ;;;;;;;;;;;;; EXERCISE SETUP CODE - DO NOT TOUCH
        int3 ;make it 'easier' to debug
        push ebx; this is to save ebx onto the stack.
        mov eax, 1
        mov edx, 2
        mov ecx, 3
        ;;;;;;;;;;;;; YOUR CODE BELOW
        ;int3 ;make it 'easier' to debug
        mov ebx, eax ;hold 1
        mov eax, ecx ;eax is set 3
        mov ecx, edx ;ecx is set to 2
        mov edx, ebx ;edx is set to 1
        int3 ;make it 'easier' to debug
        ;;;;;;;;;;;;; YOUR CODE ABOVE
        pop ebx;
        ret
labSize_01 dd $-lab_01 -1

lab.h file:
extern int lab_01();

Comment: In addition to what Jester describes in his answer, you might also consider moving the `printf`s for eax, edx, and ecx above the `if`.  Since you print the exact same thing in either case, there's no need to duplicate them.
Answer: You listed the registers as input only. You have no outputs at all. The correct asm for this is:
asm("call lab_01;"
      : "=a" (eax), "=d" (edx), "=c" (ecx)
  );

Comment: I suppose I could quibble over the unneeded `;`, but this will fix the OP's problem.  It seems like the real question is: Is it safe to perform a `call` from inline asm?  Not really the OP's problem, but the instructor is teaching his students bad habits.  The non-standard calling convention isn't great either.


Estimating two break points in a broken stick model with random effects in R

Question: Five months ago, jbowman posted a very useful answer to estimate the break point in a broken stick model with random effects in R. I never use "computing" like ifelse and I would like to estimate two break points. I should write two other functions like b1 and b2 but I don't know how. Can someone please tell me how to do that in R? Thanks!
jbowman's code:
library(lme4)
str(sleepstudy)

#Basis functions
bp = 4
b1 <- function(x, bp) ifelse(x < bp, bp - x, 0)
b2 <- function(x, bp) ifelse(x < bp, 0, x - bp)

#Wrapper for Mixed effects model with variable break point
foo <- function(bp)
{
  mod <- lmer(Reaction ~ b1(Days, bp) + b2(Days, bp) + (b1(Days, bp) + b2(Days, bp) | Subject), data = sleepstudy)
  deviance(mod)
}

search.range <- c(min(sleepstudy$Days)+0.5,max(sleepstudy$Days)-0.5)
foo.opt <- optimize(foo, interval = search.range)
bp <- foo.opt$minimum
bp
[1] 6.071932
mod <- lmer(Reaction ~ b1(Days, bp) + b2(Days, bp) + (b1(Days, bp) + b2(Days, bp) | Subject), data = sleepstudy)

Comment: Are you interested in having the slopes be continuous at the breakpoints or not?
Answer: I've been trying to work this out as well (though not with random effects), and I can only get a little further along. I'd be happy if @jbowman could take a look.
A model that allows for a double break (i.e. with breaks at $k_1$ and $k_2$ with $k_2 \gt k_1$) with slopes that are continuous is
$ Y = \beta_0 +\beta_1 X_1 + \beta_2 X_2 + \beta_3 X_3 + \epsilon $
where
$$
X_1 = \left\{ \begin{array}{ll}
  X & if\ X \leq k_1\\
  k_1 & if\ X \gt k_1\\
\end{array} \right.
$$
$$
X_2 = \left\{ \begin{array}{ll}
  0 & if\ X \leq k_1\\
  X-k_1 & if\ k_1 \leq X \leq k_2\\
  k_2-k_1  & if\ X \gt k_2\\
\end{array} \right.
$$
$$
X_3 = \left\{ \begin{array}{ll}
  0 & if\ X \leq k_2\\
  X & if\ X \gt k_2\\
\end{array} \right.
$$
To convert this to R code, I think you can do this:
X1 <- function(x, k1) ifelse(x<=k1, x, k1)
X2 <- function(x, k1, k2) ifelse(x<=k1, 0, ifelse(x<=k2, x-k1, k2-k1))
X3 <- function(x, k2) ifelse(x<=k2, 0, x)

And then for breakpoints bp1 and bp2
out.lm <- lm(y ~ X1(x, bp1) + X2(x, bp1, bp2) + X3(x, bp2), data=yourdata)
Y <- out.lm$coef[1] + out.lm$coef[2]*X1(x, bp1) + out.lm$coef[3]*X2(x, bp1, bp2) + out.lm$coef[4]*X3(x, bp2)

Sadly, when i apply this to my own problem it produces rubbish :(  I'm no R programmer, hopefully someone with a bit more knowledge can help?
Ideally it'd be great to have a generic function to handle $n$ breakpoints.
Comment: A special note to get @jbowman 's attention as I can't add a comment to the question (too little rep).
Comment: Sorry, been awfully busy over the last few months, and I'll take a look at this over the next few days (whether or not you're interested any more!)
Comment: Yes indeed @jbowman, still interested!
Answer: Section 9.3 of this R code calculates random effect estimates for a broken stick model with multiple fixed break points.


Difference between survival analysis and classification?

Question: Since the time variable can be treated as a normal feature in classification, why not using more powerful classification methods (such as, C4.5, SVM) to predict the occurrence of an event? Why lots of people still use the classic but old Cox model?
In case of the right-censoring data, since the time would change for an instances, so I think same object with different time values could be treated as two different instances in classification. Is this OK? Is there are some highly-cited paper on this topic? Thank you!
Answer: I have a little trouble understanding your questions because they are not written well.  But I will address what I think you are asking. If I misinterpret anything you can tell me and we can try again.
1. In classification can predicting the occurrence/non-occurrence of an event be enhanced by including time as a variable in the classification algorithm.
Answer: Yes it could be very helpful.

Since the Cox proportional hazards model was original proposed in 1972 why is it used so much in survival analysis?
Answer: The model is used because it is a powerful technique that is especially helpful in determination of hazard ratios.  We don't stop using the t test because it was discovered by Gosset prior to 1920.
This question is one I have a hard time understanding. This is how I would rephrase it. But let me know if I have it wrong.  Since in survival analysis we have to deal with right censoring, could we for the purpose of classifying events use the same subject twice with two different times as distinct pairs to use in training a classifier to predict events?
Answer:  I don't really like this idea because the classifier treats the data as though they are independent.  But the two pairs you introduce this way could be highly correlated. There is some merit to the idea because the second time point does provide additional information that could help classification.

Survival analysis is not designed to predict events.  It primarily is used to estimate a survival curve which measures the probability that an event has not occurred by time t taking all previous events and censored observations into account.  Classification is used to predict a response given a set of variables (predictors).  In the context of time to an event classification is used to predict when an event will occur for a new subject while survival analysis just tries to characterize how the probability of an outcome increases with time.
Regarding sources for information in survival analysis there is a wealth of excellent books.  Look up the books by Jerald Lawless and the one by Kalbfleisch and Prentice for some good examples.  The book by Therneau and Grambsch is excellent for learning the Cox model.
Comment: @Micheal Good answer. Is it possible to extract an index from an estimated survival curve in order to use it to separate deaths from survivals?
Comment: I think that survival analysis makes the most of the time information of the events. I wouldn't go for the mere classification and find a way to introduce the time as a feature, survival analysis already takes into account that information. I didn't find clear literature about classification and survival analysis. It seems that a suited index could be the expected survival time. Actually I will go for a formal question. Thanks.
Answer: +1 for Michael Chernick, yet I'll add few words from a ML point of view.
Survival problem is specific -- it seems like a pure regression, but it adds a serious constrains (monotonicity between individual "sick/resistance factors" and output, autocorrelation of decision over time, asymmetry of error in case of censored data, etc.) -- and constrains mean information we can get for "free" instead of squeezing it from the data.
Thus, it is just beneficial to use survival-aware model for survival data -- Cox model may overtake plain SVMs and CARTs just because they would lose their accuracy advantage on recreating survival constrains. However, there actually are survival-aware ML methods -- survival CARTS in party, random survival forests, Cox model boosters... You can find some inspiration on CRAN Survival Task View.
Comment: I give a +1 to mbq for enlightening me about things I never knew before.


How do you think of which notes to play while singing?

Question: I asked something a little bit similar in the past.
I am mainly thinking of Paul Simon for this question, especially in the song "The sound of silence."
How does Paul think of which notes to go with what notes Art is singing? Is he playing notes which he believes sound right?

Answer: All the notes sung are harmonious with each other. They fit each other, they usually blend with the underlying chord - they are harmony.
As a very good guitarist, a person singing harmony to another will be listening to that person's vocal, but also to the guitar chords, which should contain most of what the harmoniser needs to work with. The intervals that go together nicely are thirds and sixths - inversions of each other, fourths and fifths, both of which can sound 'hard'. Not difficult hard, but not blending too harmoniously. But sometimes, to form a phrse that works against another's melody line, 4ths and 5ths are needed.
If you think if a basic major triad, there's a 3rd between 1 and 3,(C>E) another between 3 and 5,(E>G) and a 4th between 5 and 8.(G>C) The missing link is a 5th between 1 and 5 (C>G).
I mentioned good guitarist earlier. I've worked with several vocalists who play no instruments, but could harmonise perfectly, almost spontaneously, certainly with a little rehearsal. And I really don't know how! If I did, I'd bottle it and make a fortune! Certainly not great lessons or theory, just naturals. Like Simon and Garfunkel.
All that may be on the wrong tack, but related nevertheless. The notes played on guitar, in this case, all belong to certain chords which work in conjunction with others from the same key. The guitar is playing quasi arpeggios, made up from notes which constitute chords. These chords would have been established as the song was written. Maybe spontaneous, maybe blood, sweat and tears to produce a beautiful song. It could be that half way through, they wanted a particular note, and spent ages trying all sorts of ideas until the one we hear popped out.
Answer: As far as I am aware, the ability to sing or play notes that harmonize with a particular melody line is not something one consciously thinks about - but rather something that the musician or singer has a natural instinct for.
In other words, there is not a mental process that takes place where they think something like - "okay - the melody note is a C so I am going to play or sing a third above that which is an E so I will play or sing an E".
Certainly if you lacked the musical ear and instinct to just feel what note harmonizes with a given other note, you could painstakingly do the mathematical calculations and arrive at the harmony notes that will sound good (as described in Tim's accurate answer).  But that is not what takes place with a gifted musician such as Paul Simon or Art Garfunkel.
Some folks have a natural innate ability to do certain artistic things such as artists who can paint amazing paintings with little or no schooling and musicians who rise to the top of the industry and crank out hit song after hit song.  The ability to harmonize is something that some folks have and others do not.  And some - like Paul Simon, have honed their natural ability to the highest level.
Musicians like Paul Simon, can harmonize any melody without much conscious thought.  They go with their gut and sing or play what feels right in some deeper part of their conscious that mortal folks are not able to tap into.
Many talented musicians and vocalists don't need to know anything about music theory to be able to harmonize instinctively and effectively. Music theory only serves to tell us why it sounds good to our ear.
But I do believe that with practice, any musician with a basic ability to play by ear can improve their ability to play or sing harmony.
See the answers in this related question on Stack Exchange Music How to learn to sing harmony


Sum of Fourier coefficients less than the norm of the respective vector

Question: I have the following question to complete.
Let $X$ be an inner product space. Let $(e_{j})_{j\geq1}$ be an orthonormal sequence in $X$. Show that,
\begin{align}
\sum_{j=1}^{\infty}|(x|e_{j})(y|e_{j})|\leq\|x\|\|y\|,
\end{align}
for all $x,y\in X$.
I have tried to use the Cauchy-Schwartz Inequality.
\begin{align}
\sum_{j=1}^{\infty}|(x|e_{j})(y|e_{j})|\leq\|x\|\|y\|\sum_{j=1}^{\infty}\|e_{j}\|^{2}.
\end{align}
However, that remaining sum, as far as I know, does not converge.
I tried to use Parseval's Identity, but that didn't work either. Can someone offer me a hint?
Answer: The Cauchy-Schwarz inequality should just have $\|x\|\cdot\|y\|$ on the right hand side; you've got the statement of it mixed up.
In my post, the notation $(u|e_j)$ denotes the component of $u$ with respect to the unit vector $e_j$, which is equal to the inner product $\langle u,e_j\rangle$. This notation will never be used for anything other than a member of our orthonormal set $e_j$ in the second position.
Let $x_n$ be the projection onto the space spanned by the first $n$ of the $e_j$, and similarly for $y_n$. Then
$$\sum_{j=1}^n (x|e_j)(y|e_j) = \langle x_n,y_n\rangle \le \|x_n\|\cdot \|y_n\| \le \|x\|\cdot\|y\|$$
There's no sum of $\|e_i\|^2$ there. And the equality is simply the inner product with respect to the standard (orthonormal) basis in $n$ dimensions.
Putting the absolute values in? Well, we could always rotate the $x|e_i$ and $y|e_i$ components to be positive; by orthogonality, that wouldn't affect $\|x_n\|$, $\|y_n\|$, or any of the other components.
To clarify about the absolute values:
Define $x'_n$ as follows: $x'_n=|(x|e_1)|e_1+|(x|e_2)|e_2+\cdots+|(x,e_n)|e_n$ - the sum of the absolute values of the components times the basis vectors - and similarly for $y'_n$. We claim that $\|x'_n\|=\|x_n\|$ and $\|y_n'\|=\|y_n\|$. Why? Because
$$\|x'_n\|^2=\sum_{j=1}^n |(x_n,e_j)|^2 = \sum_{j=1}^n |(x,e_j)|^2=\|x_n\|^2$$
Then, applying this,
$$\sum_{j=1}^n |(x|e_j)|\cdot |(y|e_j)| = \langle x_n',y_n'\rangle \le \|x_n'\|\cdot \|y_n'\| = \|x_n\|\cdot \|y_n\| \le \|x\|\cdot \|y\|$$
by Cauchy-Schwarz for the first inequality and Parseval for the second. Done.
Comment: Doesn't Cauchy Schwartz state $|(x|y)|\leq\|x\|\|y\|$? If so, then for each element in the sum I can say $|(x|e_{j})||(y|e_{j})|\leq\|x\|\|e_{j}\|\|y\|\|e_{j}\|=\|x\|\|y\|\|e_{j}\|^{2}$. Is this not right?
Comment: The $e_j$ component of $x$ times the $e_j$ component of $y$ is one term of $\langle x,y\rangle$. Add all of them up (at least, if the $e_j$ are an orthonormal basis), and we get the inner product. At least, that's what I thought you were using that notation to mean. Using the full power of Cauchy-Schwarz to show that one component worth is less than the whole product of norms is incredibly wasteful.
Comment: Sorry, I am confused. In fact I am now confused with my original question. I did state in the title that this was in regards to the Fourier coefficients of a vector, but I didn't realise that the inner products in the sum are being multiplied.

I am aware that the Fourier coefficients for $x\in X$ are $(x|e_{j})$. Beyond that I am getting confused. Sorry for my mistakes.
Comment: Notation: I write inner products enclosed by the $\langle$ and $\rangle$ symbols. I interpreted your $|$ notation as components; since it was only applied with the orthonormal vectors $e_j$, these can also be read as inner products of $x$ and $y$ with that $e_j$ - but it's definitely a product of something for $x$ and something for $y$. Otherwise, why would there be two sets of parentheses?
Comment: Yes my $(\cdot|\cdot)$ notation implies an inner product.
Comment: Does this still mean your solution is correct? If so, could you please explain it a little more.
Comment: The only thing I am not understanding is, why is $(x|e_{j})$ the inner product of the component of $x$ with respect to $e_{j}$? Should it not be the inner product of $x$ with $e_{j}$. I do not understand how you have arrived at this.
Comment: It is the inner product of $x$ and $e_j$. It is also the $e_j$-component of $x$. That's kind of the point of a Fourier decomposition.
Answer: Use Cauchy -Schwraz inequlairty for sequences rather than inner product. $|\sum \langle x,e_i \rangle \langle y,e_i \rangle| \leq (\sum |\langle x,e_i \rangle|^{2})^{1/2}(\sum |\langle y,e_i \rangle|^{2})^{1/2} \leq \|x\|\|y\|$.
Comment: I know this inequality as Bessel's Inequality. It works!


The bundle identifier cannot be changed from the current value

Question: I am attempting to submit my game to the App Store.  For some reason I am getting this error message when I validate my archive and I have no idea why!

The bundle identifier cannot be changed from the current value

The bundle ID in my XCode project directly matches that of the product in iTunes.
Why on earth is submitting to the App Store so complicated.  I've done it three times now and always run into a million problems :/
I have:

An app created in ITC with the correct bundle identifier
A company certificate that I use for all my games / apps
An app ID that directly matches the bundles in both XCode and ITC
A production provisioning profile that matches the correct bundle ID
Comment: Please check this link https://discussions.apple.com/message/23508889#23508889
Answer: I'm having the same exact problem, plus it keeps complaining that there's an icon file missing for iPad that is clearly there, added to the plist AND in the Target's General/App icons area. I think Apple just makes things more difficult to try to slow developers down. Android is such a treat compared to this mess! I'll write back if I can figure it out.
EDIT: Holy cow after rebuilding the project from scratch and recreating the provisioning profile I finally noticed that my stinking app in ITC was not set to "Waiting for upload"... dumb on my part, but wow iOS, thanks for picking another app's bundle ID to give me the error instead of telling em what the real problem was!
Comment: I find some of their errors so misleading or downright unhelpful :/


Outer measure question.

Question: Ok, so let $A \subset [0,1/2]$ and $B \subset (1/2,1]$ then how would I prove that the outer measure of $(A \cup B)$ is the same as outer measure of A + outer measure of B.
Answer: Since $A\cap B=\emptyset$, so we have $\mu(A\cup B)=\mu(A)+\mu(B)-\mu(A\cap B)$ where $\mu(A\cap B)=0$.
Comment: but the outer measure isn't a measure.
Comment: You're right...but even then since $A$ and $B$ are disjoint $\exists$ disjoint open sets $U$ and $V$ such that $A\subset U$ and $B\subset V$...now take a suitable cover for $A\cup B$ and split it using $U$ and $V$.
Answer: For outher measure $\mu^*$ we have: $$\mu^*(A\cup B)\le \mu^*(A)+\mu^*(B).      ~~~~~~~~~~(1)$$ We have to show that $$\mu^*(A\cup B)\ge  \mu^*(A)+\mu^*(B).      ~~~~~~~~~~(2)$$
We have:
(i) $\mu^*(A)=\inf\{ \mu(X):A \subseteq X \subseteq [0,1/2]\}$;
(ii) $\mu^*(B)=\inf\{ \mu(Y): B \subseteq Y \subseteq (1/2,1]\}$;
(iii) $\mu^*(A\cup B)=\inf\{ \mu(Z): A \cup B \subseteq Z \subseteq [0,1]\}$;
where $Z,Y,Z$ are $\mu$-measurable(equivalently, Lebesgue measurable) subsets of $[0,1]$.
For each $\mu$-measurable set $Z$ with  $A \cup B \subseteq Z \subseteq [0,1]$, we have $\mu(Z)=\mu(Z\cap [0,1/2])+ \mu(Z\cap (1/2,1])\ge \mu^*(A)+\mu^*(B).$ The later relation implies that
$$
 \mu^*(A)+\mu^*(B)\le \inf\{ \mu(Z): A \cup B \subseteq Z \subseteq [0,1]\}=\mu^*(A\cup B).
$$

Outer measure question.


Correlation between Likert scale and four-categorical nominal scale

Question: I'm measuring a four-categorical nominal variable (attachment style) and another variable in Likert scale (narcissism). How can I find whether there is any correlation between any of the attachment styles and narcissism?
Thank you!
Comment: Maybe you want to see if each level of the nominal scale has the same distribution of Likert scores.
Comment: Yes, that's right. And if the difference in the distribution at each level is significant.
Comment: Hope examples in my Answer cover what you need. Try to get started and please let me know if you need explanations. Away from computer tomorrow, but back the day after.
Answer: Some experiments. There at least two ways in which Likert scores may
differ between two groups.
(a) For example, considering Likert scores as categorical, one group might be 'decisive' with mainly 1s and 5s with
almost no 3s, while the other might have lots of scores between 2 and 4
with almost no 1s or 5s. Medians may not be the best way to summarize the essence of the differences.
(b) For example, considering Likert scores as
ordinal (perhaps nearly 'numerical'), one group might have consistently
low Likert scores 1s and 2a, and the other might have mostly 4s and 5s.
In this case 'median' is meaningful, and the first group will have a lower
median that the other.
In (a), you may find what you're looking for by using a chi-squared test
for homogeneity of probabilities of the various scores from one group to another. By contrast in (b), a Kruskal-Wallis test might reveal differences in medians.
I have no idea whether your data are more like (a) or more like (b). Nor how many subjects you have in each of your 'attachment' groups. Nor do I have any idea how many subjects you have.
For illustrations of computations of the two kinds of tests in R, I have simulated some data that may have elements of
both (a) and (b), and that have enough 'subjects' that a chi-squared test
is feasible. For each group, vector p expresses proportions for each of the five Likert responses; R turns these into probabilities. [For example,
c(1,2,3,2,1) becomes probability vector $(1/9,\,2/9,\,3/9,\,2/9,\,1/9).]$
set.seed(923)
a = sample(1:5, 40, rep=T, p=c(1,2,3,2,1))
b = sample(1:5, 43, rep=T, p=c(1,1,2,3,3))
c = sample(1:5, 38, rep=T, p=c(2,3,2,1,1))
d = sample(1:5, 45, rep=T, p=c(3,3,1,1,1))

(a) Chi-squared test. We begin by tabulating the data and putting counts
into contingency table MAT.
a.tab = tabulate(a);  b.tab = tabulate(b)
c.tab = tabulate(c);  d.tab=tabulate(d)
MAT = rbind(a.tab, b.tab, c.tab, d.tab);  MAT

      [,1] [,2] [,3] [,4] [,5]
a.tab    5   10   13    9    3
b.tab    5    3    9   14   12
c.tab    5   18    7    3    5
d.tab   21   12    4    3    5

The chi-squared test finds highly significant differences among the distributions of Likert scores for the four groups.
chisq.test(MAT)

        Pearson's Chi-squared test

data:  MAT
X-squared = 54.488, df = 12, p-value = 2.235e-07

We should look at expected counts in the 20 cells of the table to see
that they are all greater than 3 and mostly greater than 5. There are
enough subjects that all cells are OK.
chisq.test(MAT)$exp
          [,1]      [,2]     [,3]     [,4]     [,5]
a.tab 8.674699 10.361446 7.951807 6.987952 6.024096
b.tab 9.325301 11.138554 8.548193 7.512048 6.475904
c.tab 8.240964  9.843373 7.554217 6.638554 5.722892
d.tab 9.759036 11.656627 8.945783 7.861446 6.777108

Pearson residuals can provide clues where to look for important differences.
The sum of the squares of these residuals is the chi-squared statistic, so
residuals with absolute values greater than 2 or 3 may point the way to
cells where observed counts are much different from expected counts (consistent
with the null hypothesis). For example, Group D has more than the expected
number of Likert 1 responses (21 observed, about 10 expected).
chisq.test(MAT)$res
           [,1]       [,2]       [,3]      [,4]       [,5]
a.tab -1.247655 -0.1122879  1.7902060  0.761138 -1.2321105
b.tab -1.416397 -2.4385567  0.1545311  2.367164  2.1707562
c.tab -1.128977  2.5997919 -0.2016439 -1.412187 -0.3021798
d.tab  3.598323  0.1005728 -1.6535826 -1.733861 -0.6826400

(b) Kruskal-Wallis test. We begin by looking at a boxplot of the Likert scores for the four groups. Samples medians are sufficiently different that we might expect significant differences of the locations of the groups. [Shapes of the distributions of the groups are also somewhat different, so there may be
differences other than differences in location.]

There are highly significant differences in locations of Likert scores for the four groups. Ad hoc tests using paired Wilcoxon tests (perhaps at
a significance level of 1% to guard against false discovery) would help to
establish specifically which groups differ from each other.
kruskal.test(list(a,b,c,d))

        Kruskal-Wallis rank sum test

data:  list(a, b, c, d)
Kruskal-Wallis chi-squared = 28.284, df = 3, p-value = 3.166e-06

Summary. Because the null hypothesis for the chi-squared test is not at all the same as the null hypothesis for the K-W test, you should think about
scenarios (a) and (b) at the beginning of this answer and do whichever test matches your assumptions and goals. (I rigged my simulation so that both tests would give significant results, but that might not be true for your real data.)
Comment: Thank you so much for this long explanation! The first one will work.


Connecting Analog Mixer to Audio Interface

Question: I have a analog mixer would like to connect it to a audio interface. The purpose of this is for social media live streaming. I'm eyeing the focusrite 2i2. Drum mics, guitar, bass  keyboard and 3 mics are connected to my analog mixer.
My question is , is focusrite 2i2 enough for this?
Answer: The 2i2 has two identical inputs and 2 preamps so it should work just fine. Keep in mind that will have to mix everything down to a stereo mix on your mixing board and send that mix to the 2i2 so you won't be able to do any individual level adjustments after the fact.
Comment: With that many inputs, let's say for example 5 drum mics plus the other instruments and mics you're looking at about 12 inputs. The 2i2 can accept and record 2 inputs at a time so the only way you can record or stream live with the 2i2 is mixing down to 2 tracks before you get to it. Once you're in the 2i2 you can use whatever plug ins and controls are available to you within whatever software you're using on those two tracks. If you want all those inputs to go separately into the computer you will need to get an audio interface that has as many inputs as you need.
Comment: Basically all the controls are done in the mixing board? Will you have an option to have additional line tracks on your software with focusrite to have controls on each line inputs?


Email/IP Reputation between private email servers

Question: I have a private self-hosted email server.
I'm aware that if I send emails to Hotmail/Yahoo/Gmail addresses, and the users Open the emails and Reply to the emails, my Domain & IP Reputation will increase (for that particular ISP), as their user is engaging with my emails.
However, if the addresses I send emails to are on domains ".gov" and ".mil", which I believe have self-hosted email servers too (not Hotmail/Gmail), does the Opening and Replying to email actions increase anything in my Domain & IP Reputation?
I had someone telling me:

1) We send emails to .GOV/.MIL address FROM our own IP.
  2) They receive + Open + Respond to the Email
  3) Our IP and email reputation goes up, at least from 2 factors:
  - Open Email
  - Respond Email (stronger)

I just want to confirm whether this is true or not.
To clarify, my emails are configured properly (SPF/DKIM/etc). I'm not having problems sending emails to .mil/.gov. My question is whether actions done by the recipients (.gov/.mil / any self-hosted recipient) affect anything in relation to my overall IP/Domain reputation.
Answer: AFAIK opening email and responding to it are NOT typical factors collected and used for domain nor IP address reputation on private mail systems at all. The real methods include:

Blocking the most clear spam altogether e.g.

mail from nonexistent domains
IP addresses that aren't supposed to send email (e.g. dialup networks)
messages failing SPF, DKIM and DMARC checks
senders on DNS-based Blackhole List (DNSBL)

Content based filtering

Static rulesets
Bayesian filtering (self-learning)

Moving messages to and from the junk folder is a clear hint for a mail system to consider the message as spam or false positive. Opening a message is not so relevant.
Comment: I don't think that's a quality source. You should give an example on **how** a commonly used mail system tracks this kind of activity and what kind of reputation database it builds from it. If you can't find any, it's not common, and might even be a fairytale.
Comment: Thank you. As per this article, for example: https://neilpatel.com/blog/improve-email-deliverability/ -- "As these emails are received and opened by engaged users, your IP will start to build trust, in a manner of speaking, with the ISP.". It makes sense that Gmail/Yahoo/Hotmail look into the user engagement, especially if they reply, as a factor for trusting a domain. My question is more if this matters, at all, for self-hosted recipients, such as emails to @....gov and @....mil addresses.


Não consigo mudar a cor background dos números da minha tabela

Question: Estou tentando criar um tabela com 100 números que realize sorteios de acordo com a quantidade de números que eu quiser. No entanto eu preciso a cada sorteio  ser capaz de visualizar o numero que foi sorteado e para isso tenho que destacar ele. Estou tentando destacar os números de amarelo. E não estou conseguindo. A aparentemente o meu javaScript não está interagindo com o HTML. Alguém sabe o que posso fazer num caso desses ?
obs: Caso esteja confuso eu vou escrever em outras palavras, a medida que clico no botão sortear devo realizar 1 sorteio e marcar o numero na tabela e assim em diante.
<!DOCTYPE html>

Loteria AJAX - PLUS

Quantidade de número:<input type="text" id="numero">

<button type="button" id="sorteio" >Sortear</button> <button type="reset" >
Limpar</button>

Resultado:

0	1	2	3	4	5	6	7	8	9

10	11	12	13	14	15	16	17	18	19

20	21	22	23	24	25	26	27	28	29

30	31	32	33	34	35	36	37	38	39

40	41	42	43	44	45	46	47	48	49

50	51	52	53	54	55	56	57	58	59

60	61	62	63	64	65	66	67	68	69

70	71	72	73	74	75	76	77	78	79

80	81	82	83	84	85	86	87	88	89

90	91	92	93	94	95	96	97	98	99

 </script>

Comment: O seu código não deu para rodar, mas, quanto ao `background` você está setando assim **id.style.background = "#FFFF00";** e o correto é assim **id.style.backgroundColor = "#FFFF00";**. Também não entendi a pergunta, pois, se é para mudar o `background` do texto, então você que mudar a cor do texto, que no caso seria **id.style.color = "#FFFF00";**
Answer: Olá, refiz algumas partes do seu codigo, agora ele esta colorindo de amarelo os escolhidos e printando na tela, caso o numero seja repetido ele pinta o back de vermelho. Seus erros foram muitos por falta de atençao pois os ids dos numeros estavam alguns errados tipo o numero 98 com o id 8. Segue o codigo a baixo.

<!DOCTYPE html>

Loteria AJAX - PLUS

Quantidade de número:<input type="text" id="numero">

<button type="button" id="sorteio" >Sortear</button> <button type="reset" >
Limpar</button>

Resultado:

0	1	2	3	4	5	6	7	8	9

10	11	12	13	14	15	16	17	18	19

20	21	22	23	24	25	26	27	28	29

30	31	32	33	34	35	36	37	38	39

40	41	42	43	44	45	46	47	48	49

50	51	52	53	54	55	56	57	58	59

60	61	62	63	64	65	66	67	68	69

70	71	72	73	74	75	76	77	78	79

80	81	82	83	84	85	86	87	88	89

90	91	92	93	94	95	96	97	98	99

</script>


nginx forwading request to different url with load balancing

Question: I am new to nginx, I am using it for request forwarding purpose, each incoming request is getting forwarded to another server/url below is my configuration :
    http {
        include       mime.types;
        default_type  application/octet-stream;
        sendfile on;
        keepalive_timeout  65;

        server {
            listen       8008 ssl;
            listen       localhost:8008 ssl;
            listen       xyz.exmaple.com:8008 ssl;
            server_name  xyz.exmaple.com;
            more_set_headers 'Server: ABC';

            ssl_protocols TLSv1.2;
            ssl_prefer_server_ciphers on;
            ssl_ciphers "EECDH+AESGCM,EDH+AESGCM";
            ssl_certificate /logs/ssl/SSL.crt;
            ssl_certificate_key /logs/ssl/key.key;

location /app/ {

            proxy_pass      https://proxy1.example.com:8888/abc/efg;
            proxy_read_timeout 60s;

            # May not need or want to set Host. Should default to the above hostname.
            proxy_pass_header Server;
            proxy_set_header          Host            $host;
            proxy_set_header          X-Real-IP       $remote_addr;
            proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
            add_header  X-Frame-Options "SAMEORIGIN" always;
            more_set_headers 'Server: ABC';

        }

        }

}

Every request on https://xyz.exmaple.com:8008/app/ is getting forwarded to https://proxy1.example.com:8888/abc/efg
Now I have two urls :
1) https://proxy1.example.com:8888/abc/efg
2) https://proxy2.example.com:8888/abc/efg

I want round robin load balancing for this two URL, How can i achieve that ?
Answer: Use upstream to solve this issue. Example:
http
{
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    upstream backend
    {
        server proxy1.example.com:8888;
        server proxy2.example.com:8888;
    }

    server
    {
        listen 8008 ssl;
        listen localhost:8008 ssl;
        listen xyz.exmaple.com:8008 ssl;
        server_name xyz.exmaple.com;
        more_set_headers 'Server: ABC';

        ssl_protocols TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+AESGCM,EDH+AESGCM";
        ssl_certificate /logs/ssl/SSL.crt;
        ssl_certificate_key /logs/ssl/key.key;

        location /app/
        {
            proxy_pass https://backend/abc/efg;
            proxy_read_timeout 60s;

            # May not need or want to set Host. Should default to the above hostname.
            proxy_pass_header Server;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            add_header X-Frame-Options "SAMEORIGIN" always;
            more_set_headers 'Server: ABC';
        }

    }

}

Comment: I tried with this, now problem i face is when i am directly forwarding request to proxy1 or proxy2 domain, i got response within second but with above configuration with upstream, i am getting response at 2 minutes for single request


Does every Dirichlet series admit an analytic continuation? If so, to what extent?

Question: The identity theorem for analytic continuation shows that uniqueness of analytic continuations of functions is very easy to characterize. This helps us a lot when we are trying to extend functions like the Riemann zeta function or the gamma function.
However, examples such as the one in this post show that existence of analytic continuations of functions is not so easy. My question is, given a Dirichlet series
$$ F(s) = \sum_{n=1}^{\infty} \frac{a_{n}}{n^{s}} $$
defined on a half-plane $\text{Re }s > \sigma_{0}$ for some $\sigma_{0}$, does $F$ necessarily admit a complex-analytic extension to a larger domain? If so, what is the largest domain to which we can extend $F$?
My dubious conjecture is that if $F$ is well-defined on a half-plane, then it admits a meromorphic extension to all of $\mathbb{C}$, but I don't know if this is really true. Is this reasonable or not? How can I determine this?
Answer: First, meromorphic continuation is definitely too much to ask for, as the example $\log \zeta(s) = \sum_{p^r} \frac1r \frac1{(p^r)^s}$ shows: it has logarithmic singularities at $s=1$ and at every zero of $\zeta(s)$.
Even a continuation with branch cuts cannot necessarily extend to $\Bbb C$: the prime zeta function is an example of a Dirichlet series with the imaginary axis as its natural boundary.
I think that in a suitable sense, "most" Dirichlet series have its line of convergence as a natural boundary (in other words, no merormophic extension at all!). I couldn't find a clean statement to this effect, but you can look for example at some work of Bhowmik and Shlage-Puchta from 2007.
Answer: Look at $$F(s)=\prod_{n\ge 2} (1-n^{-ns+1})$$
It converges and it is analytic for $\Re(s) > 0$ and its zeros are at $$\Omega=\{  \frac{2i\pi k}{n\log n}+\frac{1}{n}, k\in \Bbb{Z}, n\ge 2\}$$
Every point of $i\Bbb{R}$ is an accumulation point of $\Omega$,
so $F$ can't extend analytically to any point of the imaginary axis.


next_permutation() in algorithm std does not seem to modify array

Question: I have the following program using function next_permutation() and the output:
 8 int main ()
 9 {
10     int myints[] = {1, 2, 3};
11
12     cout << "Before : " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
13
14     do {
15         cout << "loop : ";
16         cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
17     } while ( next_permutation(myints, myints + 3) );
18
19     cout << "After : " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
20
21     return 0;
22 }

$ ./a.out
Before : 1 2 3
loop : 1 2 3
loop : 1 3 2
loop : 2 1 3
loop : 2 3 1
loop : 3 1 2
loop : 3 2 1
After : 1 2 3

I am expecting line 19 to output "3 2 1" per the description of next_permutation() (http://www.cplusplus.com/reference/algorithm/next_permutation/, which has same sample program), but as can be seen the output is "1 2 3".  Can someone please help me understand.
Thank you,
Ahmed.
Answer: The function does precisely what the documentation that you linked says that it should do:

If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If that was not possible (because it is already at the largest possible permutation), it rearranges the elements according to the first permutation (sorted in ascending order) and returns false. (emphasis is added)

That is exactly what is going on: since your do / while loop has just finished, you know for sure that the call of std::next_permutation had returned false. Therefore, the array that you passed into that last call has been arranged in descending mode, making it impossible to produce the next highest permutation. That is also why you see the first permutation in the printout that follows the loop - the documentation says that when the call returns false, the input is sorted in ascending order.
Comment: In the original code, at line 11, the following statement was present "sort (myints, myints + 3);"   (which I deleted, and program behaved same as I expected).  I have seen similar lines in other sample programs.  Is there really a need for the sort(), since I am creating the array in ascending order?
Answer: next_permutation sorts the array if it returns false, so this is the expected behavior. This is described here on cppreference.
Hope this helps!


Number of rows of a file is not known a priori

Question: An exercise in C tell me to read infos from a file txt in which the number of rows is not known a priori. For example I have a file like this:
name surname tel
name1 surname2 tel2

I tought to use this function fscanf() in this way
FILE *fp

...

while(fscanf(fp, "%s%s%s\n", name, surname, tel) != EOF)
{
  //function
}

is it a right way?
Answer: H2CO3 is right fscanf returns the number of fields matched.
The real problem is usually that you don't know how many rows are in the file and so you do not know how large a structure or array to allocate for the data.  One solution is to use a std:vector which can grow.
It is surprising how often code reads the file twice. Once to count the lines, allocate storage and then again to read the data.  That can be a sane solution.
Comment: @Jim You can't :) David, please fix your answer - this question is about C, not C++.