O problema [object HTMLInputElement] aparece em um function em JS

Question: Estou começando na área do html, então venho aqui perguntar sobre um problema decorrent em meu código: eu criei um input de tipo text (onde a pessoa ira por seu nome), e para o nome da pessoa aparecer na minha pagina, eu usei um input de tipo boton para ela confirmar seu nome, onde na area de script criei uma function para ativar o texto do nome no html, mas há um decorrente problema em relação com o [object HTMLInputElement], e venho auqi pedir a ajuda de alguns especialistas, obrigado pela atenção.
AQUI ESTÁ O CÓDIGO:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculadora_avanced</title>

Olá!

<input type="text" id="usuarioname" name="usuarioname" value="Qual seu nome?" >
    <input type="button" id="entername" value="confirmar" onclick="entername()">

Comment: Bom dia. [Edite](https://pt.stackoverflow.com/posts/479362/edit) sua pergunta para adicionar mais detalhes e esclarecimentos a respeito do problema apresentado, para que possamos responder sua pergunta.
Answer: O Elemento input[type=text] precisa ter o atributo value acessado para você conseguir exibir o valor digitado no mesmo.
Altere seu código para:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculadora_avanced</title>

Olá!

<input type="text" id="usuarioname" name="usuarioname" value="Qual seu nome?" >
    <input type="button" id="entername" value="confirmar" onclick="entername()">

Se você usar a função console.log(na) e visualizar no Console do Navegador, vai ver que vai ser retornado o input.
O Javascript converte o objeto para o nome do mesmo quando você tenta utilizá-lo como string, o que gerou o "[object HtmlInputElement]" no seu código.
Utilize o atributo value sempre que quiser acessar/alterar o valor do input do seu HTML através do Javascript.
Mais informações na documentação da MDN
Comment: muito obrigado rapaz


Piano Concerto Evolution

Question: So I'm currently studying piano concerti, and I'm kind of stuck on a certain aspect of it.
How has the piano CONCERTO evolved from the classical period to the romantic period?
I always find comparing two different periods difficult, especially after I've listened to so much of the music now that it's all starting to blur together.
I'm mainly focusing on Mozart and Tchaikovsky, but any general pointers would be much appreciated.
Comment: Do you mean how has the *piano* evolved in terms of the instrument's design and construction, or how has the art of playing it evolved?
Comment: [Liszt](http://www.wbur.org/npr/141617637/how-franz-liszt-became-the-worlds-first-rock-star) invented a few things like the profile view of the pianist.
Comment: Sorry guys, I forgot to say concerto again in the second line, added now.
Answer: How did the piano as an instrument evolve construction wise?  Firstly, higher degree of accuracy in tools allowed for high quality instruments.  You could put higher tensions without destroying the frame, etc etc.  They also expanded the size of the keyboard and there were a ton of things done with tuning (an excellent intro to such things being "How Equal Temperament Ruined Harmony (And Why You Should Care)"), all of which made it a much more useful instrument to play.
How did the piano evolve in terms of ideal performance?  Well, for one you could look at the history of the Concerto, how it evolved and what was expected of a performer (I'm talking the origins, not the exact comparison you're using).  There also were more pianists by Tchaik's day -- the pianoforte was brand new for Mozart!  Thanks to all of the newfangled construction techniques and adding in it's popularity, a piano became The Thing to have in one's parlor, and have your womenfolk learn to dabble gracefully upon it.  Because there were more performers, there were more pieces written.  Because there were more pieces written, performers became more adept and required more difficult pieces that were then written, etc etc.  It goes on.
Liszt is an entertaining example of the piano's performance requirements as opposed to Mozart's -- Liszt was virtuoso and knew it.  He was also one of the first to make the piano an instrument that it was possible to be virtuoso OF.
Long and short -- it changed a lot.  If you're looking at performance, I'd compare Mozart and Liszt.  If you're looking at construction, you've got a more entertaining and less well lit road to follow.
Comment: These are some really good pointers, and yeah, I forgot to add the word concerto, so I was talking about the performance. Either way, thank you heaps for your detailed answer!
Answer: The evolution of the concerto form (for all instruments) follows the evolution of the musical forms in general. For example, the Classical period favored structure, intellectualism, rationalism, and economy of means; the Romantic period, which closely followed the Classical period, is the direct antithesis and reaction to the relative constraints of the Classical period. The hallmarks of the Romantic movement are emotion over rationalism, freedom over structure, more versus less, etc. In your examples of Mozart and Tchaikovsky, when listening, can you hear the smaller orchestra, the structure of the musical episodes (sonata allegro form), the limited range of the piano, and the relative compactness of his keyboard writing? Tchaikovsky, on the other hand, is grand, dramatic, much more contrast in dynamics, longer, and the structure (although still following the traditional sonata allegro form) is less obvious and less necessary. Remember also that, through natural human and industrial evolution, our lifestyle and social norms change, too. Think of how different we are today vs. 1912-1962.
In terms of performance, depending on how you define virtuosity, the piano writing and performance was no less technically demanding in the Classical (or even Baroque) than in the Romantic period. (Think again of an exposed ankle during Downton Abbey's days, vs. a string bikini today.) However, the soloist was still very much a part of the ensemble (for the most part), in that the interplay between the soloist and the orchestra was very much supportive of the other, rather than against each other. In the late Classical and most of the Romantic period, the idea of the struggle and drama of David vs. Goliath was more apparent. It's almost as if one were fighting the other, with the goal of vanquishing the other. And, as the previous poster pointed out, the soloist became the star of the concerto, and Liszt's long hair and dramatic mannerisms became part of the public's image of a concerto performance.
Answer: I think the biggest evolution of the piano concerto came through Beethoven's attempts to make the structure of the piano concerto more "tightly bound," particularly through the linking of the last two movements in the "Emperor" Concerto. He was also responsible for the evolution of piano as prima inter pares (first among equals) with the orchestra to the more modern conception of piano versus orchestra.
Liszt's main contribution was to link piano concertos into a single continuous movement; Brahms was the first to really expand the concerto beyond three movements.
But I keep going back to the Fourth Concerto of Beethoven—the opening for solo piano alone, followed by the slow movement of piano versus unaccompanied strings. I think that's the moment when the piano concerto progressed from classical to Romantic. That was perhaps the biggest single "quantum leap" in the evolutionary process.

Piano Concerto Evolution


Use CASE THEN in SQL

Question: I have three tables which I want to query in MySQL as follows:
Table Notes
id  | note
-------------------
1   | note 1
2   | note 2

Table Indices
id  | name
-----------
1   | height
2   | weight
3   | other

Table Detail
  note_id    |  indices_id |  value
-------------------------------------
    1        |     1       |   50
    1        |     2       |   60
    1        |     3       |   20
    2        |     1       |   40
    2        |     2       |   10
    2        |     3       |   50

I need to query the result as follows:
  indices.name    |  note_id = 1 |  note_id = 2
------------------------------------------------
    height        |     50       |   40
    weight        |     60       |   10
    other         |     20       |   50

I tried this query:
SELECT i.name,
(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n,indices i,detail d
WHERE n.id = d.note_id AND i.id = d.indices_id
GROUP BY i.name

But Column Col3 result is null
Any help much appreciated! Thanks very much!
Comment: It's a pity that MySQL allows the use of a GROUP BY clause with no aggregating functions. It's best to pretend to yourself that it doesn't
Comment: The query is invalid and MySQL should raise an exception. Instead it silently applies `ANY_VALUE` on your expressions, thus arbitrarily picking either the value you are looking for or null. Try `SET sql_mode = 'ONLY_FULL_GROUP_BY'`, so that MySQL doesn't allow such invalid queries anymore.
Answer: You need to use an aggregation function so that you don't get random row data on Col2 and Col3. MAX will work as it will ignore NULL values when the note_id doesn't match. Also, you should use explicit JOIN syntax:
SELECT i.name,
       MAX(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
       MAX(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n
JOIN detail d ON n.id = d.note_id
JOIN indices i ON i.id = d.indices_id
GROUP BY i.name

Output:
name    Col2    Col3
height  50      40
other   20      50
weight  60      10

Demo on dbfiddle
Comment: @Ajax: Please see the joins in Nick's query. The comma-separated joins you were using in your original query were made redundant in 1992. I wonder how you even got the idea to use them. Don't. If you are using a book or tutorial or are attending a class teaching you so, quit it.
Answer: This is a variation of Nick's answer.  The JOIN to nodes is superfluous:
SELECT i.name,
       MAX(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
       MAX(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM detail d JOIN
     indices i
     ON i.id = d.indices_id
GROUP BY i.name

Use CASE THEN in SQL


Modificar as chaves primárias padrão do Rails pode gerar algum problema?

Question: Por padrão, o Rails gera o campo id para todas as minhas tabelas e eu gostaria de saber se, futuramente, pode gerar algum erro caso eu mude o nome e o tipo da chave. Pergunto isso pois percebi que o Rails tem algumas convenções de nomenclatura que devem ser seguidas.
Peço desculpas se a pergunta for meio boba, mas estou preocupado com a possibilidade de ter problemas futuramente.
Answer: Você pode alterar a chave primária para outra coluna:
<code>class Project < ActiveRecord::Base
  self.primary_key = 'nomecoluna'
end
</code>
http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html


Code logic not computing correct data

Question: I'm desperately hoping someone can assist me with this error. Admittedly, I'm a novice and I've tried for literally 60+ hours to fix this but I just can't get there.
Right, here goes.
I have a football league table of 20 teams. It works, it's great, happy days. However, I needed to reduce it to 12 teams. A problem because I didn't create the website, someone else did a while back.
So I've needed to amend a table with 20, to 12. That's all.
Daunted, I rolled up my sleeves scoured the code and located this bit;
<?php

$query = $SITE -> Query ( 'SELECT a.*, b.name, b.colour, b.txtcolour,
(sum((a.wins*3) + (a.draws*1) - a.pts)) as points,
(sum(a.wins + a.losses + a.draws)) as pld,
(sum(a.glsfor - a.glsaga)) as gd
FROM got_standings a
inner join got_clubs b on (a.cid = b.id)
WHERE a.season = "'.$url[2].'"
GROUP BY a.cid
ORDER BY points DESC, gd DESC, glsfor DESC' );

if ($SITE -> Count ($query) == 0) {
$loop = 0;

while($loop <= 19) {
++$loop;
?>

After some trial and error in those 60 hours I've been trying to resolve, I changed;
while($loop <= 19)
to;
while($loop <= 11)
And low and behold, the system now prompted me to enter 12 teams into a league table, as oppose to 20. Superb. Or so I thought...
When I first enter the data into the table and 'submit', it works - as it did perfectly when 20 teams where listed before the above change. However, when I 'update'/make any continual changes to the league table, it also calculates the previous
So for 'Port Talbot Town' I enter "1 Win", "1 Draw", "1 Loss", "5 Goals Scored" "5 Goals Conceded"
And it works. It calculates 3 games played and 4 points (3 for a win, 1 for a draw, 0 for a loss)as shown here.
BUT, when I then enter other information, so entering the same information for 'Aberystwyth Town'and 'update', the information for the previous data (Port Talbot Town) is calculated again?as shown here.
I'm at complete loss. I'd be incredibly grateful and appreciative for any assistance.
The entire code is pasted at the bottom of this.
Please guys! Help an idiot out! 8)
<?php
}
} else if ($url[3] == 'league') {
if ($url[4] == 'standings') {
?>

<a href="<?=$CONF['site']; ?>sitecontrol/fixtures/<?=$url[2]; ?>/add/league">Add Fixture

<a href="<?=$CONF['site']; ?>sitecontrol/fixtures/<?=$url[2]; ?>/league/standings">Standings

<form action="<?=$CONF['site']; ?>mcms/applications/fixtures/submit.php?do=fixtures&action=standings&season=<?=$url

[2]; ?>&comp=<?=$url[3]; ?>" method="post" name="standings">

Welsh Premier League Standings

Pos.

Team

PLD

W

D

L

+

-

PTS

<?php

$query = $SITE -> Query ( 'SELECT a.*, b.name, b.colour, b.txtcolour,
(sum((a.wins*3) + (a.draws*1) - a.pts)) as points,
(sum(a.wins + a.losses + a.draws)) as pld,
(sum(a.glsfor - a.glsaga)) as gd
FROM got_standings a
inner join got_clubs b on (a.cid = b.id)
WHERE a.season = "'.$url[2].'"
GROUP BY a.cid
ORDER BY points DESC, gd DESC, glsfor DESC' );

if ($SITE -> Count ($query) == 0) {
$loop = 0;

while($loop <= 11) {
++$loop;
?>
<ul class="tr" id="team_<?=$loop; ?>">

<?=$loop; ?>

<?php

echo ( '
<select name="cid[]">
' );

$sql = $SITE -> Query ( 'SELECT id, name FROM got_clubs WHERE country = "Wales" ORDER BY name ASC' );

while($club = $SITE -> FetchArray($sql)) {
echo ( '<option value="'.$club['id'].'"' );
if ($club['id'] == '1') echo ( ' SELECTED' );
echo ( '>'.$club['name'].'</option>' );
}

echo ( '
</select>
' );

?>

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=wins[]]').val(parseInt($('ul#team_<?

=$loop; ?> li.td4 input[name=wins[]]').val())+1); return false;">+ <input type="text" name="wins[]" value="0" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=draws[]]').val(parseInt($('ul#team_<?

=$loop; ?> li.td4 input[name=draws[]]').val())+1); return false;">+ <input type="text" name="draws[]" value="0" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=losses[]]').val(parseInt

($('ul#team_<?=$loop; ?> li.td4 input[name=losses[]]').val())+1); return false;">+ <input type="text" name="losses[]"

value="0" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=glsfor[]]').val(parseInt

($('ul#team_<?=$loop; ?> li.td4 input[name=glsfor[]]').val())+1); return false;">+ <input type="text" name="glsfor[]"

value="0" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=glsaga[]]').val(parseInt

($('ul#team_<?=$loop; ?> li.td4 input[name=glsaga[]]').val())+1); return false;">+ <input type="text" name="glsaga[]"

value="0" />

- <input type="text" name="pts[]" />

<?php
}
} else {
$loop = 0;

while($row = $SITE -> FetchArray($query)) {
++$loop;
?>
<ul class="tr" id="team_<?=$loop; ?>">

<?=$loop; ?>

<li class="td-club" style="width: 160px; margin-left: 10px; background-color: #<?=$row['colour']; ?>; color: #<?

=$row['txtcolour']; ?>;"><?=$row['name']; ?><input type="hidden" name="cid[]" value="<?=$row['cid']; ?>" />

<?=$row['pld']; ?>

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=wins[]]').val(parseInt($('ul#team_<?

=$loop; ?> li.td4 input[name=wins[]]').val())+1); return false;">+ <input type="text" name="wins[]" value="<?=$row

['wins']; ?>" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=draws[]]').val(parseInt($('ul#team_<?

=$loop; ?> li.td4 input[name=draws[]]').val())+1); return false;">+ <input type="text" name="draws[]" value="<?=$row

['draws']; ?>" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=losses[]]').val(parseInt

($('ul#team_<?=$loop; ?> li.td4 input[name=losses[]]').val())+1); return false;">+ <input type="text" name="losses[]"

value="<?=$row['losses']; ?>" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=glsfor[]]').val(parseInt

($('ul#team_<?=$loop; ?> li.td4 input[name=glsfor[]]').val())+1); return false;">+ <input type="text" name="glsfor[]"

value="<?=$row['glsfor']; ?>" />

<a href="#" onclick="$('ul#team_<?=$loop; ?> li.td4 input[name=glsaga[]]').val(parseInt

($('ul#team_<?=$loop; ?> li.td4 input[name=glsaga[]]').val())+1); return false;">+ <input type="text" name="glsaga[]"

value="<?=$row['glsaga']; ?>" />

<?=$row['points']; ?> (- <input type="text" name="pts[]" value="<?=$row['pts']; ?>" />)

<?php
}
}

?>

<input type="submit" value="Update Standings" /> or <a href="<?=$CONF['site']; ?>sitecontrol/fixtures/<?

=$url[2].'/'.$url[3]; ?>">Cancel

</form>

Do not use the points column for anything other than points deductions. If a points deduction is carried out by the

Premier League, use the input box to enter how many points have been taken away, e.g. Portsmouth in 2009/10 would have

"9" in their points input box.

Matches played and points columns will update automatically. The position of each team in the league table will also be

automatically updated.

<?php
} else {
?>

<a href="<?=$CONF['site']; ?>sitecontrol/fixtures/<?=$url[2]; ?>/add/league">Add Fixture

<a href="<?=$CONF['site']; ?>sitecontrol/fixtures/<?=$url[2]; ?>/league/standings">Standings

Premier League Fixtures

<?php
$query = $SITE -> Query ( '
SELECT a.id, a.rid, home, away, homescore, awayscore, date, b.name as hometeam, c.name as awayteam FROM

got_fixtures a
inner join got_clubs b on (a.home = b.id)
inner join got_clubs c on (a.away = c.id)
WHERE a.cid="1" AND a.season = "'.$url[2].'" AND (a.home = "1" OR a.away = "1")
ORDER BY date ASC' );

while($row = $SITE -> FetchArray($query)) {
?>

<?=$row['rid']; ?>

<?=$row['hometeam']; ?>

<?=$row['homescore']; ?> - <?=$row['awayscore']; ?>

<?=$row['awayteam']; ?>

<?=date('D. jS F y, H:i', $row['date']); ?>

<a href="<?=$CONF['site']?>sitecontrol/fixtures/<?=$url[2]; ?>/edit/<?=$url[3]; ?>/<?=$row['id'];

?>">Edit or <a href="<?=$CONF['site']; ?>mcms/applications/fixtures/submit.php?do=fixtures&action=delete&id=<?

=$row['id']; ?>&comp=<?=$url[3]; ?>&season=<?=$url[2]; ?>">Remove

<?php
}
?>

Comment: consider changing title to a relevant one. Let people decide who you are based on your question. Do not self advertise.
Answer: Sounds like it's not inserting it correctly into the database. Look for a SQL query that has INSERT or UPDATE in it.
The SQL in the code above is displaying data from the database, not adding to it. Your problem will be elsewhere. As the while loop pulling from the database was hard coded with the value 19, then the update code will probably be as well.
Also login to your hosting account, go to PhpMyAdmin, and have a look at the database itself. See how that is set up.
Comment: Also if you are on Windows, try something like Baregrep > http://www.baremetalsoft.com/baregrep/ it'll make searching through the code a lot easier.
Comment: Thanks logic, appreciated mate.

The database in phpmyadmin is really bare! Not much to go on? http://i1116.photobucket.com/albums/k562/nilsatis88/6.jpg
Comment: No problem, yeah not much to see there. Can you post this code `mcms/applications/fixtures/submit.php`?
Comment: Fixed! Logic, I cant tell you how appreciative I am mate. Didn't even think to check that file. I did, found if ($SITE -> Count ($query) == 20) { and updated to 12. Superb. Will register/login and approve you reply. Thanks so much for your time mate.
Comment: Nice one Dan, glad you got it sorted!

Code logic not computing correct data


Verificacao de email em Java

Question: Estou fazendo um teste simples para verificar se o usuario digitou um email valido. So que estou com erro de sintaxe no token "@" invalido AssignmentOperator.
Codigo da classe principal:
public class Email {

static String email = "email@example.com";

public static void main(String[] args) {

}

public static void validarEmail(){

    //Verifica a posicao do @ no emal.
    int validarEmail = email.indexOf("@");
    //System.out.println(validarEmail);

}

public static void obterNome(){

    //Seleciona o que esta escrito antes do @.
    String obterNome = email.substring(0, 6);
    //System.out.println(obterNome);

}

Classe que verifica o Email:
public class VerificaEmail {

public static void main(String[] args) {

    Email e = new Email();

    //Verifica se o Email e valido.
boolean b = e.validarEmail(firstname.lastname@example.com);
    if(!b)
        System.out.println("Email Inválido");
    else
        System.out.println("Email Válido");

// Imprime o que esta antes do @.
String nome = e.obterNome(firstname.lastname@example.com);
System.out.println(nome);

}

Comment: "pessoa cannot be resolved to a variable" esse erro é justamente pq vc tá passando sem as aspas, deveria ser `boolean b = e.validarEmail("firstname.lastname@example.com");`
Comment: Se eu colocar em String e o email entre aspas nao funciona tbm.
Comment: Mas o erro quando o email (nas duas chamadas dentro de `VerificaEmail`) está entre aspas é diferente, certo?
Comment: se eu colocar os emails da classe `verificaEmail` entre aspas ele apresenta o seguinte erro **- teste cannot be resolved to a variable
 - Syntax error on token "@", invalid AssignmentOperator
 - pessoa cannot be resolved to a variable
 - The method validarEmail() in the type Email is not applicable for the arguments
  (String)**
E eles e o mesmo email da classe principal.
Comment: @Math Ja tentei fazer desse jeito com as aspas mais da erro tbm
Comment: Mas pelo menos deve ser outro erro, não é não?
Comment: @re22 Na verdade o jeito que ele colocou dava certo mais acabei descobrindo o que estava causando o erro. E utilizei outros metodos para solucionar o problema. Mas lembrando que o jeito que ele colocou tbm funciona so que e mais complexo e o meu ficou mais facil.
Answer: A melhor maneira de você validar um email é aplicar uma expressão regular.
Pattern como membro estático
na sua classe Email crie um membro privado estático e final do tipo Pattern
private static final String EMAIL_PATTERN =
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN, Pattern.CASE_INSENSITIVE);

Use um Matcher dentro do seu método validar email
public static boolean validarEmail(String email){
    Matcher matcher matcher = pattern.matcher(email);
    return matcher.matches();
 }

Note que é melhor deixar o Pattern como mebro estático e já compilado assim, você não precisa criar um novo a cada nova validação, você ganha em performance
Precisa que seja compliance com RFC822?
Exemplo RFC822
****Note que eu mudei o retorno do seu método para boolen, assim faz mais sentido para classes clientes chamarem seu método
Comment: Só uma nota: validação de e-mail com regex não é 100% seguro, pois não é totalmente *compliant* com a especificação (RFC). Podem ocorrer falsos positivos e falsos negativos, então a dica é sempre testar com cuidado para que a solução seja *boa o suficiente* para atender suas necessidades. Para maiores detalhes, ver [esta outra questão](http://pt.stackoverflow.com/q/1386/227).
Comment: Legal, valeu pela dica @utluiz Eu coloqueio uma referencia para antender a este caso do RFC. Caso necessário, solicite que faço uma tradução completa da resposta em inglês. Mais uma vez obrigado.
Answer: Sua classe Email precisa de um metodo Main? Se você quer gravar nela o email informado um construtor faria mais sentido.
public class Email {

static String email;

public Email(String email){
    this.email = email;
}

//public static void validarEmail(){
public boolean validarEmail()
    //Verifica a posicao do @ no emal.
    //int validarEmail = this.email.indexOf("@");
    //System.out.println(validarEmail);

    return ( this.email.indexOf('@') > 0 );
}

public static String obterNome(){

    //Seleciona o que esta escrito antes do @.
    return this.email.substring(0, this.email.indexOf('@'));
    //System.out.println(obterNome);

}

Ai na outra classe:
public class VerificaEmail {

public static void main(String[] args) {

    Email e = new Email("email@example.com");

    //Verifica se o Email e valido.
    if(!e.validarEmail())
        System.out.println("Email Inválido");
    else
        System.out.println("Email Válido");

    System.out.println(e.obterNome());

}

Comment: Utilizei seu código so que ainda tenho alguns erros que nao estou conseguindo solucionar. Nas linhas `return obterNome = this.email.substring(0, this.email.indexOf('@'));`
`Email e = new Email("firstname.lastname@example.com");`
`if(!e.validarEmail())`
`String nome = e.ObterNome("email@example.com");`.
Comment: Estava incorreto, editei o codigo aqui direto no post, então não percebi. Mas veja que a solução proposta pelo @Filipe Gonzaga Miranda eh muito mais interessante. O que fiz aqui foi apenas um ajuste no seu codigo.
Answer: Acabei encontrando uma forma mais simples para solucionar meus erros segue o codigo:
*Classe Email:
public class Email {
public static String email = "firstname.lastname@example.com";
public static String Nome;
public static int indiceEmail;

public static boolean validarEmail(){

    //Verifica se o email possui o @.
    indiceEmail = email.indexOf('@');
    if (indiceEmail > 0)
        return(true);
    else
        return(false);

}

public static String obterNome(){

    if (indiceEmail > 0)
        return Nome = email.substring(0, indiceEmail);
    else
        return("Erro!");

}

Classe principal:
public class VerificaEmail {
public static void main(String[] args) {

    Email e = new Email();

//Verifica se o Email e valido.
boolean b = e.validarEmail();
    if(!b)
        System.out.println("Email Inválido");
    else
        System.out.println("Email Válido");

// Imprime o que esta antes do @.
String nome = e.obterNome();
System.out.println(nome);

}

Dessa forma ficou mais simples e melhor de entender e sem alterar o intenção do autor.

Verificacao de email em Java


Is it safe and correct to run Drush under the same user account that the webserver runs on?

Question: I've found following informaion:

It's usually considered best practice to run Drush under the same user account that the webserver runs on (such as www-data). Some modules, such as XML Sitemap, Advanced Aggregator and cTools, often try to alter or generate files.

I also have some problem with Ctools cache.
I can use following command to run Drush under the www-data user:
sudo -u www-data drush....
But is it safe and correct to run Drush under the same user account that the webserver runs on?
Answer: In general, the answer is "yes", it is safe and correct.  However, the specific answer here depends on (a) your security policy, and (b) what you want to do with Drush.  Some people prefer to make the code files not writable by the web server.  If you had a setup like that, then you would not be able to run drush dl as the webserver user.
The other thing of note here is that any time you run any Drush command, all Drush commandfiles are given the opportunity to alter the command's behavior.  This means that it is generally NOT considered safe to run drush via sudo to root, unless you trust all of the code in your Drupal site to run as the root user.  This is not generally a concern for sudo -u www-data, though, as you are already trusting the code in your Drupal site to run as the web user.
Comment: I understand now that sometimes I can run Drush under www-data user (for example, some scripts for Munin monitoring). But during usual everyday work it is acceptable to run Drush under my personal user. ty.
Comment: On my dev machine, I make all of my webserver files owned by my personal login account, and set their group to www-data, and use g+w on directories that are writable by the webserver. In this environment, I run Drush as my personal login user, pretty much with no trouble. Files created by the webserver will be owned by the webserver, so sometimes I cannot change these w/out chown, but this is not often a problem.


Add margin to a specific section top and bottom using twitter bootstrap class

Question: How can I add margin to a specific section top and bottom using twitter bootstrap class? I can do this using my custom css like .my_section{margin:100px 0} but I want to do it by bootstrap class (if any).
Comment: You need to add custom class.
Comment: Thanks Mr monoj Kumar. I can do this by custom class . but I am looking for bootstrap typography.
Comment: I believe that there isn't such a function within Bootstrap, you will have to use a custom class for it. The closest Bootstrap has is `.jumbotron` class.
Answer: I don't think it's a bad idea to add your own class in order to apply the styling.
Firstly, it means that you're less like to accidentally apply the style override to another element on the page (or, more likely, someone who comes along later and adds another element with the same Bootstrap class).
Also you can use your class name to semantically describe the override:
<button class="spaced-button btn btn-primary"> ...

.spaced-button {
  margin:10px 0;
}


How can I parse external link url using native angular code?

Question: everyone. Sometimes I need some way to get some part of external site url in my angular code. But there's obviously no way to do it with native angular services, and I don't wanna use some Jquery library for parsing url. I need some service for url parsing which. Where can I find such service? Thx!
Answer: You can do it in Vanilla JavaScript.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

Source: https://gist.github.com/jlong/2428561
Comment: Can I get any GET parameter by this way?
Comment: Of course you can. In my example you'd parse `parse.search`. Also see: [How to get the value from URL Parameter?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter)
Comment: OMG! Do you really have to create a virtual `` element to parse a link?
Comment: You could also reuse an existing one, assuming the `href` attribute contains the same URL you want to parse.
Answer: I guess you could use the $sce service:
function($scope, $sce) {
 $scope.getHtml = function() {
   return $sce.trustAsResourceUrl(myUrlHere);
 };
}

As mentioned in other post, provided that this is not subject to CORS.
Answer: By Parsing, I'm assuming you mean fetching of content/data from a url.
Proving the url allows any domain ( 'Access-Control-Allow-Origin', '*' ) or your domain, Angular does have ajax functions built in, simular to jquery et all.
http://docs.angularjs.org/api/ng.$http
Copied direct from the anguar doc
$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Comment: No, actually, by parsing I meant getting some parts of url string for example get parameters.
Comment: oh ok : ) regular js will do then, Angular would not have any need to recreate that. - use of externalurlstring.split("/") and such - I thought Simone's answer is pretty cool


How to print "rendered node" version of Node Reference field in template?

Question: I have two content types: Type A and Type B. I have a Node Reference field on content Type A (using References module) that is set to be displayed using the "Rendered Node" version of that referenced node. It references nodes of content Type B. How can I print the content of that field as a rendered node in a custom template file for content Type A?
Comment: what do you mean by "print the content of that field"? do you mean body field?
Comment: Can you confirm that you are using https://drupal.org/project/References ?  I just want to edit the question, as how the field is stored varies between the various reference modules for Drupal 7.
Comment: @MPD - Good catch. I have edited my answer.
Comment: @MPD, yes, I am using References.
Answer: In your $node object, you will find the subordinate node object at $node->field_fieldname['und'][0]['node']. To render this in a page you have to turn it into a renderable array. You do this with node_view(),specifying the type of display mode. Try:
<?php
if(isset($node->field_fieldname['und'][0]['node'])) {
  $second_node = $node->field_fieldname['und'][0]['node'];
  $view_mode = 'teaser'; // or 'full' as the case may be
  $render_array = node_view( $second_node, $view_mode);
  print render($render_array);
}
?>

EDIT
MPD is correct. The above assumes that the field is a Node Reference field. If you are using an Entity Reference field, the code should be changed to:
 <?php
    if(isset($node->field_fieldname['und'][0]['entity'])) {
      $second_node = $node->field_fieldname['und'][0]['entity'];
      ...

Comment: Shouldn't that be `target_id` and not `entity`?
Comment: @MPD - Node reference uses ['nid'] for the id and ['node'] for the object. Entity reference uses ['target_id'] for the id and ['entity'] for the object. The node (or entity) object is included in the field data. Why access the id and separately load the object when it is already there?
Comment: @Triskelion  Odd.  I have never seen anything other than ['target_id'] when I dpm() or print_r() a node.
Comment: @MPD - I have found that the global `$node` may be incomplete. When I do a `print_r()`, I usually precede it with `$full_node=node_load($node->nid)`. You would be amazed at the differences I find :-)


Why output differs between R and SPSS when run Poisson glm on count data

Question: I am puzzled why output differs between R and SPSS when run Poisson glm on count data? While R returns Estimate, Standard Error, z value and Pr(>|z|), SPSS does Walt χ2, df and significance.
Answer: If you take the square root of the $\chi^2$ values from SPSS they should be identical to the values of $Z$ from R, providing the SPSS $\chi^2$ is based on 1 d.f.   Also, the Pr(>|z|) from R is the same as the significance for SPSS.
Comment: Thank you so much for the quick comment. This is very helpful. Can I report just χ2 values and significant codes from SPSS for a research paper?
Comment: I found that the square root of the χ2 values from SPSS is similar but not exactly the same as that of R. I might set something wrong for SPSS although I follow the instruction of IBM...
Comment: I was first going to mention that you need to obtain the same regression coefficients from each package first, and then sqrt(chi2) will be exactly equal to z.  The chi2 distribution for each regression coefficient has 1 degree of freedom (d.f.=1), which is the only case where sqrt(chi2)=z.   Above 1.d.f. for the chi2 distribution, this relationship does not hold.  Make sure you are not looking at the goodness-of-fit chi2, since the degrees of freedom are equal to the number of records minus the number of regression coefficients.   (GOF statistics might also report deviance and Pearson chi2).
Comment: I see. I will look at the regression coefficients. Thank you!


How to put a variable from one page to another in a tabhost?

Question: In fact I'm working on an android project I have a list of events, when I click on an event I can pass the name of the event and its image but I can not put the description in a tabhost how can I do it?
Comment: What do you mean by 'list of events'? listview?
Answer: Option 1:
You can try using setTag method on each row which stores your description.
<code>setTag(Object tag)
</code>
Sets the tag associated with this view.
Option 2:
I have similar situation in my project. This is how I achieved

When I created the list, I have created array of string object. I keep this as a global object in MYProjectApplication.java file. So it is available everywhere.
When the list is clicked I get the position and refer the corresponding description from the global string array.


How to appropriate use request in python to get Facebook data?

Question: I am writhing code in python to crawl Facebook data, I found one example in web but it seems not appropriate for my purpose, the main problem is in request sentence, here is the code:
x= g.request('search', {'q' : 'TaylorSwift', 'type' : 'page', 'limit' : 10})['data'][0]['id']

Does somebody know what's the means of this request and tell me how to modify it?
Comment: If you want get data from facebook the best point to start reading is https://developers.facebook.com/docs/graph-api . Crawling Facebook is not allowed, you will hard get any help with it here.
Answer:
g.request('search', {'q' : 'TaylorSwift', 'type' : 'page', 'limit' : 10})

That's just a request to the search endpoint, and what you can search for and with what parameters, is described here: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.4#search
Comment: Thank you very much, I want to search by group so how can I modify it?
Comment: You change the value of the `type` parameter perhaps …?
Comment: I try it, but it seems not work, a little weird, so do you know other idea?
Comment: I'd suggest you try your request in Graph API Explorer first – and once you get the results you want there, you translate it into the parameters your framework is expecting.


Rails fetch all including last row from association

Question: I have two model with has_many belongs to relation.
Scheme has_many navs

I need to fetch all the Schemes with only last nav value. I have 10 Schemes and each scheme has around 100k navs but I need only last record which is the current value.
With eager loading will load all the navs
Scheme.all.includes(:navs)

How can I apply condition to to get only last row of nav for each schemes while eager loading.
UPDATE with Log
If I run
Scheme.includes(:current_nav).limit(3)

these are the queries executed by AR
SELECT  `schemes`.* FROM `schemes`  LIMIT 3
SELECT `navs`.* FROM `navs`  WHERE `navs`.`schemeCode` IN ('D04', 'D01', 'D30')  ORDER BY id DESC

How the second query works, it will take all the navs whose schemeCode falls under list and order those by id DESC , but how it will be associated with particular scheme exactly.
Answer: How about creating an another association like this:
class Scheme < ActiveRecord::Base
  has_one :current_nav, -> { order('id DESC').limit(1) }, class_name: 'Nav'
end

Now you can:
Schema.includes(:current_nav).all

or:
Schema.includes(:current_nav).last(10)

will eager load only last nav of the queried schemes.
Explanation: includes is one of the methods for retrieving objects from database in ActiveRecord. From the doc itself:

Active Record lets you specify in advance all the associations that
  are going to be loaded. This is possible by specifying the includes
  method of the Model.find call. With includes, Active Record ensures
  that all of the specified associations are loaded using the minimum
  possible number of queries.

And, since we have the association setup with current_nav, all we had to do is to use it with includes to eager load the data. Please read ActiveRecord querying doc for more information.
Comment: @Senthil : Added explanation, I am glad that your problem is solved. I thought I wouldn't need to say it, but since I am overwhelmed by OPs on SO for not accepting answers even if it helps, so, kindly accept answer of your question on SO if they solves your problem. Have a happy programming.
Comment: Did it work the way you were expecting? I'll add the explanation soon.
Comment: Its fetching results , but if you give explanation it will be very great , since it works like magic.


Behringer UMC1820, signal detected even gain is on lowest level

Question: I bought Behringer UMC1820 yesterday. All is ok, but when I connect for example guitar to any input, signal is coming even when gain knob is on the lowest level. I think no signal should be coming if gain is down, or not?
Where is the catch? Sensibility of inputs? Some special configuration? Or luck on defective piece?
Thanks for any advice.
Answer: It depends. How is the knob labelled? Typically a mic/line input gain trim gives low gain at minimum, but you still get a quiet signal. Then the label at minimum would be something like -20dB. This is different from a fader which goes down to nothing, and is labelled "-infinity" (a symbol like an 8 on its side; <code>-∞</code>). So what you are experiencing is probably as expected.


Calling preprocessing.scale on a heterogeneous array

Question: I have this TypeError as per below, I have checked my df and it all contains numbers only, can this be caused when I converted to numpy array? After the conversion the array has items like
[Timestamp('1993-02-11 00:00:00') 28.1216 28.3374 ...]

Any suggestion how to solve this, please?
df:
    Date      Open      High       Low     Close     Volume
9    1993-02-11   28.1216   28.3374   28.1216   28.2197      19500
10   1993-02-12   28.1804   28.1804   28.0038   28.0038      42500
11   1993-02-16   27.9253   27.9253   27.2581   27.2974     374800
12   1993-02-17   27.2974   27.3366   27.1796   27.2777     210900

X = np.array(df.drop(['High'], 1))
X = preprocessing.scale(X)

TypeError: float() argument must be a string or a number

Comment: Well, the error is self-explanatory: it can't deal with datetime-objects or whatever your dates are.
Answer: While you're saying that your dataframe "all contains numbers only", you also note that the first column consists of datetime objects. The error is telling you that preprocessing.scale only wants to work with float values.
The real question, however, is what you expect to happen to begin with. preprocessing.scale centers values on the mean and normalizes the variance. This is such that measured quantities are all represented on roughly the same footing. Now, your first column tells you what dates your data correspond to, while the rest of the columns are numeric data themselves. Why would you want to normalize the dates? How would you normalize the dates?
Semantically speaking, I believe you should leave your dates alone. Whatever post-processing you're planning to perform on your numerical data, the normalized data should still be parameterized by the original dates. If you want to process your dates too, you need to come up with an explicit way to handle your dates to something numeric (say, elapsed time from a given date in given units).
So I believe you should drop your dates from your processing round altogether, and start with
X = df.drop(['Date','High'], 1).as_matrix()


Deal with Multiple Summations

Question: Im just wondering why these are not equal. Here's a link to it written out on wolframaplha https://www.wolframalpha.com/input/?i=sum_(k%3D1)%5Ea+sum_(j%3D1)%5Eb+(2k%2Bj)+%3D+(2a%5E2%2Ab%2Bab%5E2%2B3ab)%2F2 Below is the input, I wasn't sure how to write it here. Thanks in advance :)
\begin{equation}
\sum_{k=0} ^a \sum_{j=0}^b (2k+j) = (2a^2b+ab^2+3ab)
\end{equation}
Comment: Where is the $+$ gone ?
Comment: With $n=1$, $(2\cdot0+0)+(2\cdot0+1)+(2\cdot1+0)+(2\cdot1+1)=6$, while $2((0+1)(0+1))=2$.
Comment: Grrr, silently changing the question is bad practice, it makes the comments and answers irrelevant.
Comment: I suppose I'm left asking should they be equal? or why do you think they should be equal.
Comment: Well i thought they were equal, I got that using distribution, I know its wrong but i dont understand why and i dont know how to simplify it enough to get it to closed form
Comment: I think you wrote something wrong then. The equation you put in wolfram alpha and here doesn't fall from distribution of sum.
Comment: sorry, i didnt want people to go to the effort of answering that question to realise i made a mistake
Comment: You should document the change.
Answer: You can write
$$\sum_{k=0} ^n \sum_{j=0}^n (2k+j)=2\sum_{k=0} ^n \sum_{j=0}^n k+ \sum_{k=0} ^n \sum_{j=0}^n j=2(n+1)\sum_{k=0} ^n k+ (n+1)\sum_{j=0}^n j=3(n+1)\frac{n(n+1)}2.$$
Comment: You have enough information to check by yourself.
Comment: would that work if the upper limits on the two summations are different? e.g. m and n
Answer: I'm left to troubleshoot where you went wrong with this problem. First I'm not sure that it is immediately obvious that the two terms should be equal, one is the sum of $k,j$ the other is the product, sums are not products.
If you meant $\sum (2k\times j)$ then the two are equal.
If you meant $2\sum_k k+\sum_j j$ then the answer is that the sum over the other parameter gives a factor of $n+1$.
If you meant $2\sum_k \sum_j k+\sum_k \sum_j j$ then you will get equality.
If you want to evaluate these yourself it's pretty simple to do this starting at $\sum_{i=0} ^n i = \frac{n(n+1)}{2}$ and $\sum_{i=0} ^n i = (n+1)i$
Comment: sorry i made a mistake, I made up a simpler example of the question that i have to work out to try to understand the steps better. I used the distributive law without realising they were being added and not multiplied. this is the question I have to answer, show how you get to the RHS from the LHS. I dont know how to go about answering it any ideas? thanks a mill https://www.wolframalpha.com/input/?i=sum_(k%3D1)%5Ea+sum_(j%3D1)%5Eb+(2k%2Bj)+%3D+(2a%5E2*b%2Bab%5E2%2B3ab)%2F2
Comment: I think that's derivable from the third suspected error, and the hint I gave you.
Comment: ok thanks a mill

Deal with Multiple Summations


Multiple Regression with Categorical Variables - How to evaluate the Omitted Values?

Question: I'm trying to learn how to do multiple regression with categorical variables. I have a dataset of credit card balance data that looks as follows:

I then did a regression on all variables (in R):

I understand the concept of dummy variables and always omitting one of them, which R does for you automatically.
I haven't tried to optimize this model yet. But, I can see that GenderFemale is not statistically significant in predicting Balance. What I'd like to know is this. How can I determine if perhaps GenderMale is significant? Since Male was the variable omitted, how can I evaluate the significance of this variable?
Comment: What it shows is that the predicted mean for women is not different from the predicted mean for men. So the predicted mean for men is obviously not different from the predicted mean for women.
Comment: @mdewey - What if I had a situation where there was a statistical difference between genders? How would the output change so I would know this?
Answer: The meaning of any categorical coefficient in linear regression such as this is there is a difference in the average predicted dependent variable between the category and the omitted category, with a size of the coefficient. Using this data, females have a non-significant average predicted balance of 9.55 less than males, controlling for the other covariates.
Since this is a difference between the categories, changing the omitted category would give the exact same non-significant result, with a flipped ($+$) sign. Males will have +9.55 more than females.
If you want to test this on your data (I can't use the data given since it's not reproducible) you can change the omitted (reference) category of any factor in R using the relevel() function:
caseStudyData2$Gender <- relevel(caseStudyData2$Gender, ref = "Female")

And run the model again.
Comment: This makes sense. Would there ever be a situation where the included category is non significant but the excluded would be significant? I don't see how this might be possible, but just curious.
Comment: There can be with more than 2 levels, because each level will show the difference between them and the reference category, but the difference between them might very well be different. When only two categories exist, there shouldn't be any differences.
Comment: So if I have a categorical variable with say three levels and two show as not being significant, how can I determine if the reference category is or isn't (without rerunning the model and choosing a different reference category)?
Comment: Not really. you can get a general idea by looking at the difference between the categories. In your case, you see that in Ethnicity a gap of 16 is non significant (between Asian and the reference category). The difference between Caucasian and Asian is about 7 (16-9) so it should not be significant no matter which is your reference category (bearing in mind that significance is a matter of the std.error as well as the effect size, so one cant be sure)


Divs side by side and image span

Question: Is this behaviour somehow possible:

The structure:

  text…

  text…

  text…

the columns are using float
As far as I can see this is not possible with css.
Even with multiple columns this will not work because column-span accept only none or all.
Is there any workaround like a javascript plugin to make this work?
Thanks a lot
Comment: You can do the text using the [columns layout](https://developer.mozilla.org/en-US/docs/Web/CSS/columns). In this case for the yellow image you would use `image{max-width: 100%}`. You can't do the image to span over 2 columns however you can do the image to span over all 3 (in this case) columns by using image{column-span: all;}
Answer: It's indeed not possible to do it with floats only because the float columns can't track or calculate the size of the colored divs going cross column. However this is easily achievable with Flexbox.

Divs side by side and image span


XmlSerializer: XSD generated classes serialization issues

Question: Consider the following scenario. We have a XSD file defining a technical document interchange format (one root type composed of several complexTypes).
Additionally, there is a specification defining defining each and every field with value range and format.
Obviously, both documents have been created by different departments because the formats are defined differently. E.g.

XSD: Time is represented by xml type time (XmlSerializer format: HH:mm:ss.fff)
Spec doc: The following format must be used for time HH:mm.

Technical wise, things are easy. We used XSD.exe to generate the classes. But now the output file is looking different after using XmlSerializer. There is no chance to negotiate the format, since it was created due to a regulation affecting a whole market and therefore a lot of counterparties.
As per the moment we have to assume, that the formats of the specification document need to be respected. So I was looking for options to ensure this.

Add and implement IXmlSerializable interface to the generated classes of the affected complexTypes.  Unfortunately, this is not an option since the initialization of the XmlSerializer is throwing an exception: "There was an error reflecting type." Or is there any way to avoid this? Implementing the interface for the root type is not an option, since it's very large and complex.
Find a serialization library, where some kind of type format mapping can be provided, so that a custom format in fields can be implemented.  Right now, I didn't find anything like this. But perhaps someone can give me hint.
Modify the string content of the nodes via XPathNavigator after serialization.  Not the best approach but it would do the job.
Modify the generated classes directly in the generation output and add some proxy properties.  Actually not the best idea, since a regeneration (due to a new version of the XSD file) is overwriting all modifications. Unfortunately, properties cannot be redefined in a partial class, right?

I've ordered the list by the order of preference.
So did I miss an option? Which way would you go?
I know it's not the typical How do I use class xyz question, but still I'm hoping, that you can give me hint, how such kind of scenarios are handled usually.
Answer: Due to the tremendous feedback, I've decided to go with option 3.
Reason is simple. We can still use the standard class generation with XSD.exe and keep all benefits of XmlSerializer class.
For more information please refer to this article in the MSDN. The flow is pretty straight forward.

Select nodes with the given path
Read value untyped (string) and parse expected typed object
Write untyped value from typed object by using the desired format

We have tested it already and it's working like a charm.


the set of integers A,B are defined by A={13k-5;k=1,2,...,2013} and B={17n-10;n=1,2,...,2013}. Compute the number of elements in A union B.

Question: As, the number of elements in both sets are 2013 and |A∪B|=|A|+|B|-|A∩B|
but I don't know how to find |A∩B|. Can anyone help me please to find its solution.
Comment: this is exactly what the OP is asking
Comment: When is $13k-5=17n-10$?
Comment: Do you know the chinese remainder theorem ?
Answer: We have $k=-5=8\bmod 13$ and $k=-10=7\bmod 17$ iff $k=177\bmod 221$ (Note that $13\times17=221$).
So the values in $A\cap B$ are $177, 398, ... 26034=117\cdot221+177$. Hence $|A\cap B|=118$ and so $|A\cup B|=4026-118=3908$.


How to check in C # that a message sent by a producer has successfully reached the Kafka server?

Question: I can't find a way to confirm that a message sent to the Kafka server has been received correctly by the server.
I need a confirmation that the message was sent and received correctly in order to act on the C # code in case the message was not received by the server.
I have read that there is a property called ack to configure that, but I can't find how to receive such confirmation.
Comment: It sounds like you're bumping into the [two generals' problem](https://en.wikipedia.org/wiki/Two_Generals%27_Problem).
Comment: Could you provide your code or similar example? I think you could only get information about sending process.
Comment: @Flater Except that would only apply if Kafka brokers didn't respond, in which case, Kafka clients have built-in retry mechanisms, which may repeat messages, but it certainly isn't "unreliable"
Comment: @Crowley77 Please use the checkmark next to the answers if they've solved your problem
Answer: You'd use a DeliveryReport handler
Refer documentation - https://docs.confluent.io/clients-confluent-kafka-dotnet/current/overview.html
Async
var t = producer.ProduceAsync("topic", new Message<Null, string> { Value="hello world" });
t.ContinueWith(task => {
    if (task.IsFaulted)
    {
        ...
    }
    else
    {
        ...

        Console.WriteLine($"Wrote to offset: {task.Result.Offset}");
    }
});

Synchronous
public static void handler(DeliveryReport<Null, string>)
{
    ...
}

public static process(...)
{
    ...
    producer.Produce(
        "my-topic", new Message<Null, string> { Value = "hello world" }, handler);
}

Answer: This worked for me:
bool messagePublished;
var result = await _producer.ProduceAsync(yourTopic, yourMessage);

if (result.Status == PersistenceStatus.Persisted)
    messagePublished = true;

Notice that you have multiple PersistenceStatus values.
You can find more info on the official confluent documentation.


OpenGL - Rotation not working

Question: Background
I currently have an environment I have created to which I load some shapes (for reference to where I am) and am trying to get the controls to move forward, backwards, and rotate where I am looking.
I have the forward and backwards worked out using my lookat point and camera position point.  I am trying to rotate 360 degrees but appear to get some strange limits based on what I have so far. I am outputting my xangle to see where I am at always..
In order to rotate, I change the lookat variable (x,y, and z) while keeping the position (x,y,z) the same.
Problem
When continuously increasing the angle, I hit two reflection points where the appeared rotation changes direction. For whatever reason these seem to happen at 60 degrees and 300 degrees as shown below:

Obviously these angles are not correct.  I have evaluated the behavior that should happen as the rotation happens and the calculated Cartesian coordinates seem to be correct but the display of the angle is what is off.
My setupviewport sub:
Private Sub SetupViewport()
    Dim w As Integer = GLcontrol1.Width
    Dim h As Integer = GLcontrol1.Height

    Dim perspective1 As Matrix4 = cam.GetViewMatrix() * Matrix4.CreatePerspectiveFieldOfView(1.3F, GLcontrol1.Width / CSng(GLcontrol1.Height), 0.1F, 2000.0F)

    GL.MatrixMode(MatrixMode.Projection)
    GL.LoadIdentity()
    GL.Ortho(0, w, h, 0, -1, 1)
    GL.LoadMatrix(perspective1)
    GL.MatrixMode(MatrixMode.Modelview)
    GL.LoadIdentity()
    GL.Viewport(0, 0, w, h)
    GL.Enable(EnableCap.DepthTest)
    GL.DepthFunc(DepthFunction.Less)

End Sub

My camera class:
Class Camera
Public Position As Vector3 = Vector3.Zero
Public Orientation As New Vector3(0.0F, 0.0F, 0.0F)
Public MoveSpeed As Single = 0.2F
Public MouseSensitivity As Single = 0.01F
Public lookat As New Vector3()

Public manual_lookat As Boolean = False

Public invert_y As Boolean = False

Public Function aim_at_origin()
    Position.X = 0
    Position.Y = 0
    Position.Z = 2

    If invert_y = False Then
        Return Matrix4.LookAt(Position, Position + lookat, Vector3.UnitY)
    Else
        Return Matrix4.LookAt(Position, Position + lookat, -Vector3.UnitY)
    End If
End Function

Public Function GetViewMatrix() As Matrix4

    If invert_y = False Then
        Return Matrix4.LookAt(Position, lookat, Vector3.UnitY)
    Else
        Return Matrix4.LookAt(Position, lookat, -Vector3.UnitY)
    End If

End Function

End Class

The camera class establishes the matrix to multiply against the current one. The multiplication happens every frame when setupviewport is called.
I can't figure out why it has the reflection points at 300 and 60 degrees. To me 180 degrees or 360 would make sense.  It appears like the area of rotation is a total of 45 degrees from visually looking.
I am tagging this is MATH, C#, and VB .NET as answers can be acceptable in most programming languages.
In order to rotate, I call this class:
Private Sub rotate_view(ByVal delta_camanglex As Single, ByVal delta_camangley As Single)
    Dim curdistance As Single = 1
    curdistance = Math.Sqrt((cam.Position.X - cam.lookat.X) ^ 2 + (cam.Position.Y - cam.lookat.Y) ^ 2 + (cam.Position.Z - cam.lookat.Z) ^ 2)

    Dim invertx As Boolean = False
    Dim inverty As Boolean = False

    camanglex = camanglex + delta_camanglex
    camangley = camangley + delta_camangley

    If camanglex >= 360 Then
        camanglex = camanglex - 360
    End If

    If camangley >= 360 Then
        camangley = camangley - 360
    End If

    If camanglex < 0 Then
        camanglex = camanglex + 360
    End If

    If camangley < 0 Then
        camangley = camangley + 360
    End If

    cam.manual_lookat = True

    Dim sigma As Single = camanglex
    Dim theda As Single = camangley

    lookatx = curdistance * Sin(sigma * (PI / 180)) * Cos((theda) * (PI / 180))

    lookaty = curdistance * Sin((sigma) * (PI / 180)) * Sin((theda) * (PI / 180))

    lookatz = curdistance * Cos((sigma) * (PI / 180))

    cam.lookat.X = lookatx
    cam.lookat.Y = lookaty
    cam.lookat.Z = lookatz

End Sub

Comment: This is very confusing. Where in that code is your rotation supposed to happen? Why are you putting the view matrix into the projection matrix stack? Why are you multiplying view and projection in that order? What is that `glOrtho` doing there?
Comment: In order to rotate, I change the lookat variable (x,y, and z) while keeping the position (x,y,z) the same.
Comment: But how do you change it? That's the crucial point of the whole question.
Comment: @derhass I have updated my question to include my rotation class. It simply calculates where lookat should be
Answer: Do not use Euler angles for this as they have many issues like the one you got. Instead use cumulative transform matrices. It looks like this question is asked again and again... for some time now. So I decided to make an example how to do it with pure OpenGL 1.0 no GLM or funny stuff.

Definitions
Lets have Player control-able object called obj and camera eye. Each of them should be represented by separate 4x4 transform matrix.  The OpenGL stores them as 1D arrays. For more info see

Understanding 4x4 homogenous transform matrices

We want to control obj in its local coordinate system independent on camera view. If you are used to have both camera and object matrices multiplied together in GL_MODELVIEW to avoid GL_PROJECTION matrix abuse then you quickly realize that this is not solvable by simply glRotate/glTranslate calls in usual manner.
Because of that many people switch to Euler angles which can handle this easily but brings up a whole bunch of other problems (many nowadays games are still using them where they should not and there are a tons of bugs and issues because of it).
So add this to your project:
GLfloat mobj[16],meye[16];

Using GL for our matrices
This is simple just do this:
glMatrixMode(GL_MODELVIEW); // set matrix target we want to work with does not matter really which)
glPushMatrix(); // store original matrix so we do not mess something up
glLoadMatrixf(mobj); // load our matrix into GL
//here do your stuff like glRotatef(10.0,0.0,1.0,0.0);
glGetFloatv(GL_MODELVIEW_MATRIX,mobj); // get our updated matrix from GL
glPopMatrix(); // restore original state

With this we can use GL calls for our matrices outside the rendering loop. (for example in keyboard handler or in some timer).
Rendering loop matrices
Now if we want to render our object with our matrices then we need to set the GL matrices properly. Let assume Projection matrix is set then just Modelview is in question. The modelview matrix should be:
GL_MODELVIEW = Inverse(meye) * mobj

But OpenGL does not have any matrix inverse function. So this is the only thing we need to code. As the matrix is always 4x4 then it is not that hard.

I put all this together into this simple GL/C++/VCL example:
//---------------------------------------------------------------------------
#include <vcl.h>        // you can ignore this
#include <gl/gl.h>
#include <gl/glu.h>
#pragma hdrstop         // you can ignore this
#include "Unit1.h"      // you can ignore this
//---------------------------------------------------------------------------
// you can ignore this
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
// here some global variables
int     xs,ys;          // window resolution
HDC     hdc;            // device context
HGLRC   hrc;            // rendering context
// 4x4 transform matrices
GLfloat mobj[16];   // object transform matrix
GLfloat meye[16];   // camera transform matrix
// key codes for controling (Arrows + Space)
WORD key_left =37;
WORD key_right=39;
WORD key_up   =38;
WORD key_down =40;
WORD key_forw =32;
// key pressed state
bool _left =false;
bool _right=false;
bool _up   =false;
bool _down =false;
bool _forw =false;
bool _shift=false;
// sceene need repaint?
bool _redraw=true;
//---------------------------------------------------------------------------
// here inverse matrix computation
GLfloat matrix_subdet   (         GLfloat *a,int r,int s)
        {
        GLfloat   c,q[9];
        int     i,j,k;
        k=0;                            // q = sub matrix
        for (j=0;j<4;j++)
         if (j!=s)
          for (i=0;i<4;i++)
           if (i!=r)
                {
                q[k]=a[i+(j<<2)];
                k++;
                }
        c=0;
        c+=q[0]*q[4]*q[8];
        c+=q[1]*q[5]*q[6];
        c+=q[2]*q[3]*q[7];
        c-=q[0]*q[5]*q[7];
        c-=q[1]*q[3]*q[8];
        c-=q[2]*q[4]*q[6];
        if (int((r+s)&1)) c=-c;       // add signum
        return c;
        }
void  matrix_subdet    (GLfloat *c,GLfloat *a)
        {
        GLfloat   q[16];
        int     i,j;
        for (i=0;i<4;i++)
         for (j=0;j<4;j++)
          q[j+(i<<2)]=matrix_subdet(a,i,j);
        for (i=0;i<16;i++) c[i]=q[i];
        }
GLfloat matrix_det       (         GLfloat *a)
        {
        GLfloat c=0;
        c+=a[ 0]*matrix_subdet(a,0,0);
        c+=a[ 4]*matrix_subdet(a,0,1);
        c+=a[ 8]*matrix_subdet(a,0,2);
        c+=a[12]*matrix_subdet(a,0,3);
        return c;
        }
GLfloat matrix_det       (         GLfloat *a,GLfloat *b)
        {
        GLfloat c=0;
        c+=a[ 0]*b[ 0];
        c+=a[ 4]*b[ 1];
        c+=a[ 8]*b[ 2];
        c+=a[12]*b[ 3];
        return c;
        }
void  matrix_inv       (GLfloat *c,GLfloat *a)
        {
        GLfloat   d[16],D;
        matrix_subdet(d,a);
        D=matrix_det(a,d);
        if (D) D=1.0/D;
        for (int i=0;i<16;i++) c[i]=d[i]*D;
        }
//---------------------------------------------------------------------------
// here OpenGL stuff
//---------------------------------------------------------------------------
int TForm1::ogl_init()
    {
    // just init OpenGL
    if (ogl_inicialized) return 1;
    hdc = GetDC(Form1->Handle);             // get device context
    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory( &pfd, sizeof( pfd ) );      // set the pixel format for the DC
    pfd.nSize = sizeof( pfd );
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 24;
    pfd.cDepthBits = 24;
    pfd.iLayerType = PFD_MAIN_PLANE;
    SetPixelFormat(hdc,ChoosePixelFormat(hdc, &pfd),&pfd);
    hrc = wglCreateContext(hdc);            // create current rendering context
    if(hrc == NULL)
            {
            ShowMessage("Could not initialize OpenGL Rendering context !!!");
            ogl_inicialized=0;
            return 0;
            }
    if(wglMakeCurrent(hdc, hrc) == false)
            {
            ShowMessage("Could not make current OpenGL Rendering context !!!");
            wglDeleteContext(hrc);          // destroy rendering context
            ogl_inicialized=0;
            return 0;
            }
    ogl_resize();
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_BLEND);
    glShadeModel(GL_SMOOTH);
    ogl_inicialized=1;
    return 1;
    }
//---------------------------------------------------------------------------
void TForm1::ogl_exit()
    {
    // just exit from OpneGL
    if (!ogl_inicialized) return;
    wglMakeCurrent(NULL, NULL);     // release current rendering context
    wglDeleteContext(hrc);          // destroy rendering context
    ogl_inicialized=0;
    }
//---------------------------------------------------------------------------
void TForm1::ogl_draw()
    {
    // rendering routine
    _redraw=false;

    // here the whole rendering
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);   // background color
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    GLfloat ieye[16];   // inverse camera transform matrix
    matrix_inv(ieye,meye);

    glMatrixMode(GL_MODELVIEW);
    glLoadMatrixf(ieye);
    glMultMatrixf(mobj);

    // render player controlable object
    // centered by (0,0,0)
    // +z forward, +x right, +y up
    float x=0.5,y=0.1,z=0.7;    // half sizes of object
    glColor3f(0.7,0.7,0.7);
    glBegin(GL_TRIANGLE_FAN);
    glVertex3f(0.0,0.0,+z);
    glVertex3f( -x,-y,-z);
    glVertex3f( +x,-y,-z);
    glVertex3f(0.0,+y,-z);
    glVertex3f( -x,-y,-z);
    glEnd();
    glColor3f(0.5,0.5,0.5);
    glBegin(GL_TRIANGLES);
    glVertex3f( -x,-y,-z);
    glVertex3f( +x,-y,-z);
    glVertex3f(0.0,+y,-z);
    glEnd();
    // render x,y,z axises as r,g,b lines
    glBegin(GL_LINES);
    glColor3f(1.0,0.0,0.0); glVertex3f(0.0,0.0,0.0); glVertex3f(1.0,0.0,0.0);
    glColor3f(0.0,1.0,0.0); glVertex3f(0.0,0.0,0.0); glVertex3f(0.0,1.0,0.0);
    glColor3f(0.0,0.0,1.0); glVertex3f(0.0,0.0,0.0); glVertex3f(0.0,0.0,1.0);
    glEnd();

    glFlush();
    SwapBuffers(hdc);
    }
//---------------------------------------------------------------------------
void TForm1::ogl_resize()
    {
    xs=ClientWidth;
    ys=ClientHeight;
    if (xs<=0) xs = 1;                  // Prevent a divide by zero
    if (ys<=0) ys = 1;
    if (!ogl_inicialized) return;
    glViewport(0,0,xs,ys);              // Set Viewport to window dimensions
    glMatrixMode(GL_PROJECTION);        // use projection matrix
    glLoadIdentity();                   // set it to unit matrix
    gluPerspective(30,float(xs)/float(ys),0.1,100.0); // perspective projection 30 degrees FOV and 0.1 focal length view depth 100-0.1
    glMatrixMode(GL_TEXTURE);           // use texture matrix
    glLoadIdentity();                   // set it to unit matrix
    glMatrixMode(GL_MODELVIEW);         // use modelview marix
    glLoadIdentity();                   // set it to unit matrix
    }
//---------------------------------------------------------------------------
// here window stuff
//---------------------------------------------------------------------------
// window constructor
__fastcall TForm1::TForm1(TComponent* Owner):TForm(Owner)
    {
    ogl_inicialized=0;
    hdc=NULL;
    hrc=NULL;
    ogl_init();

    // init matrices
    glMatrixMode(GL_MODELVIEW);
    // object is at (0,0,0) rotatet so Z+ is pointing to screen
    glLoadIdentity();
    glRotatef(180.0,0.0,1.0,0.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mobj);
    // camera is behind object looking at object
    glLoadIdentity();
    glTranslatef(0.0,0.0,+20.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,meye);
    }
//---------------------------------------------------------------------------
// window destructor
void __fastcall TForm1::FormDestroy(TObject *Sender)
    {
    ogl_exit();
    }
//---------------------------------------------------------------------------
// common window events
//---------------------------------------------------------------------------
void __fastcall TForm1::FormResize(TObject *Sender)
    {
    ogl_resize();
    _redraw=true;
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender)
    {
    _redraw=true;
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::tim_updateTimer(TObject *Sender)
    {
    // here movement and repaint timer handler (I have 20ms interval)

    GLfloat da=5.0; // angular turn speed in [deg/timer_iteration]
    GLfloat dp=0.1; // movement speed in [world_units/timer_iteration]

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();

    if (_shift) // if Shift pressed control camera
        {
        // copy meye to GL
        glLoadMatrixf(meye);
        // handle keyboard with GL functions
        if (_left ) { _redraw=true; glRotatef(+da,0.0,1.0,0.0); }
        if (_right) { _redraw=true; glRotatef(-da,0.0,1.0,0.0); }
        if (_up   ) { _redraw=true; glRotatef(-da,1.0,0.0,0.0); }
        if (_down ) { _redraw=true; glRotatef(+da,1.0,0.0,0.0); }
        // obtain meye from GL
        glGetFloatv(GL_MODELVIEW_MATRIX,meye);
        }
    else{ // else control object
        // copy meye to GL
        glLoadMatrixf(mobj);
        // handle keyboard with GL functions
        if (_left ) { _redraw=true; glRotatef(+da,0.0,1.0,0.0); }
        if (_right) { _redraw=true; glRotatef(-da,0.0,1.0,0.0); }
        if (_up   ) { _redraw=true; glRotatef(-da,1.0,0.0,0.0); }
        if (_down ) { _redraw=true; glRotatef(+da,1.0,0.0,0.0); }
        // obtain mobj from GL
        glGetFloatv(GL_MODELVIEW_MATRIX,mobj);
        }

    glPopMatrix();
    // handle keyboard directly
    if (_forw )
        {
        _redraw=true;
        mobj[12]+=dp*mobj[8];       // mobj[12,13,14] is object position
        mobj[13]+=dp*mobj[9];       // mobj[8,9,10] is object Z axis direction vector
        mobj[14]+=dp*mobj[10];      // if not glScale is used then it is unit in size
        }

    // render if needed
    if (_redraw) ogl_draw();
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormMouseWheelDown(TObject *Sender, TShiftState Shift, TPoint &MousePos, bool &Handled)
    {
    // move camera matrix forward
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadMatrixf(meye);
    glTranslatef(0,0,+2.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,meye);
    glPopMatrix();
    Handled=true;
    _redraw=true;
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormMouseWheelUp(TObject *Sender, TShiftState Shift, TPoint &MousePos, bool &Handled)
    {
    // move camera matrix backward
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadMatrixf(meye);
    glTranslatef(0,0,-2.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,meye);
    glPopMatrix();
    Handled=true;
    _redraw=true;
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key,TShiftState Shift)
    {
    _shift=Shift.Contains(ssShift);
    // on key down event
    if (Key==key_left ) _left =true;
    if (Key==key_right) _right=true;
    if (Key==key_up   ) _up   =true;
    if (Key==key_down ) _down =true;
    if (Key==key_forw ) _forw =true;
    Key=0;  // key is handled
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
    {
    _shift=Shift.Contains(ssShift);
    // on key release event
    if (Key==key_left ) _left =false;
    if (Key==key_right) _right=false;
    if (Key==key_up   ) _up   =false;
    if (Key==key_down ) _down =false;
    if (Key==key_forw ) _forw =false;
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormActivate(TObject *Sender)
    {
    _left =false; // clear key flags after focus change
    _right=false; // just to avoid constantly "pressed" keys
    _up   =false; // after window focus swaping during key press
    _down =false; // many games are ignoring this and you need to
    _forw =false; // press&release the stuck key again to stop movement ...
    }
//---------------------------------------------------------------------------

It is simple single form VCL application with single 20ms timer in it. So port the events to your environment style code. You can ignore the VCL pragmas and includes. This example is driven by arrows. If shift is pressed then the arrows are turning camera otherwise the object. Space is moving object forward.
Here compiled Win32 standalone demo:

compiled demo

This approach has one drawback
With cumulating the transforms you are loosing precision. To remedy that you can exploit vector multiplication (cross product). Simply count the number of operations performed on such matrix and if threshold is reached normalize the matrix and reset the counter.
By normalization I mean ensuring all the axises are unit and perpendicular to each other Leaving the direction of main axis (usually forward of view or object) as is. Cross product of 2 vectors returns perpendicular vector to each. So for example if you extract the X,Y,Z axises (locations are described in the link in #1) and Z is the main axis then:
X = Y x Z
Y = Z x X
Z = Z / |Z|
X = X / |X|
Y = Y / |Y|

Where:
// cross product: W = U x V
W.x=(U.y*V.z)-(U.z*V.y)
W.y=(U.z*V.x)-(U.x*V.z)
W.z=(U.x*V.y)-(U.y*V.x)
// dot product: a = (U.V)
a=U.x*V.x+U.y*V.y+U.z*V.z
// abs of vector a = |U|
a=sqrt((U.x*U.x)+(U.y*U.y)+(U.z*U.z))

In case your coordinate system is not derived from unit matrix then you need to negate some axis or change the order of cross product operands to ensure the direction of your axises stays as should.
For more info take a look at:

How to preserve accuracy with cumulative transforms over time (full pseudo inverse matrix)
Comment: I understand the concepts you are showing but I really am struggling with converting it to C# or VB .NET since you wrote it in C++. I hate to ask, since you put a lot of effort into this answer, but are you able to do an example in either of those languages?
Comment: @EricF I do not code in any of them so no. You need just the inverse matrix and the events which are straightforward enough I think. The C# code should be almost identical except it handles arrays a bit differently. The important stuff is `ogl_draw()` and `tim_updateTimer(TObject *Sender)`

OpenGL - Rotation not working


My app dosent work on sony xperia z1 bu works on some other devices

Question: i have an text based app and it works fine in most devices and in emulator but on sony xperia z1 it causes force close,
1.is it possible to emulate xperia z1 on android virtual device manager?how?
2.do you have ideas about reasons of this problem?
Comment: Post the stacktrace of the force close.
Comment: Stacktrace please...
Answer: You should test your app on this phone and explore logcat for error details. If you have no access to the device you could do one of the following:

Install sony add-on and try to test on their avd: http://developer.sonymobile.com/knowledge-base/sony-add-on-sdk/install-the-sony-add-on-sdk/
If app is published on market there is section in admin area where you could see crash information if user have sent crash details after it happened.
There is a service where you could test your apps on almost any real device and see logcat - http://www.perfectomobile.com/ - it's pretty expensive, but I think they have free trial with limited number of devices - may be xperia is among these devices.


Find the Matrix Representation of the Linear Transformation $ T : \mathcal{ P_{\mathit{N} }[\mathit{ R}] \to {\mathit{R^{N +1} }}}$

Question: Let $\{ 1., x, \ldots  , x^N \}$ be the canonical basis of $\mathcal{ P_{\mathit{N} }[\mathit{ R}] } $ and let  $ T : \mathcal{ P_{\mathit{N} }[\mathit{ R}] \to {\mathit{R^{N +1} }}}$    such that
\begin{equation}
   T (p) =
   \begin{bmatrix}
     p(x_0)\\
     \vdots \\
     p(x_N)
   \end{bmatrix}
\end{equation}
in the canonical basis, How can I find the matrix representation of that linear transformation?
Comment: If you expand the definition of the matrix representation in this case, you'll discover that this is the $(N+1) \times (N+1)$ matrix whose columns are $T(1),T(x),T(x^2), \dots, T(x^N)$.
Answer: The approach I like is as follows: to find the $j$th column of the matrix, compute the (coordinate vector of the) image of the $j$th basis element. In this case, the $j$-th basis element is $x^j$. The image of this element is
$$
T(x^{j-1}) = \pmatrix{x_0^{j-1} \\ \vdots \\ x_N^{j-1}}.
$$
So taking $j=3$, we see that the matrix of $T$ (relative to the canonical bases of $\mathcal P_N$ and $\Bbb R^{N + 1}$) has the form
$$
\pmatrix{?&?&x_0^2 &?&\cdots & ?\\
? & ?& x_1^2 & ? & \cdots & ?\\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots\\
? & ? & x_N^2 & ? & \cdots & ?}
$$


Use of Taylor series expansion to find second derivative for sixth order method

Question: Use Taylor's expansion to derive sixth order method (i.e $\mathcal{O}(h^6)$) for approximating the second derivative ($f '' (x_0)$ ) for given sufficiently smooth function $f(x)$.
I have this things in my mind:

I can use this seven points: $x_0 - 3h,x_0 - 2h, x_0 - h, x_0, x_0 + h, x_0 + 2h, x_0 + 3h$

$$
f(x_0 + h) = f(x_0) + (h) f'(x_0) + \frac{(h)^2}{2} f''(x_0) + \frac{(h)^3}{3!} f'''(x_0) + \frac{(h)^4}{4!} f''''(x_0) + \frac{(h)^5}{5!} f'''''(x_0) + \frac{(h)^6}{6!}f''''''(x_0) + \frac{(h)^7}{7!}f'''''''(\xi)
$$
$$
f(x_0 + 2h) = f(x_0) + (2h) f'(x_0) + \frac{(2h)^2}{2} f''(x_0) + \frac{(2h)^3}{3!} f'''(x_0) + \frac{(2h)^4}{4!} f''''(x_0) + \frac{(2h)^5}{5!} f'''''(x_0) + \frac{(2h)^6}{6!}f''''''(x_0) + \frac{(2h)^7}{7!}f'''''''(\xi)
$$
$$
f(x_0 + 3h) = f(x_0) + (3h) f'(x_0) + \frac{(3h)^2}{2} f''(x_0) + \frac{(3h)^3}{3!} f'''(x_0) + \frac{(3h)^4}{4!} f''''(x_0) + \frac{(3h)^5}{5!} f'''''(x_0) + \frac{(3h)^6}{6!}f''''''(x_0) + \frac{(3h)^7}{7!}f'''''''(\xi)
$$
$$
f(x_0 - h) = f(x_0) - (h) f'(x_0) + \frac{(h)^2}{2} f''(x_0) - \frac{(h)^3}{3!} f'''(x_0) + \frac{(h)^4}{4!} f''''(x_0) - \frac{(h)^5}{5!} f'''''(x_0) + \frac{(h)^6}{6!}f''''''(x_0) - \frac{(h)^7}{7!}f'''''''(\xi)
$$
$$
f(x_0 - 2h) = f(x_0) - (2h) f'(x_0) + \frac{(2h)^2}{2} f''(x_0) - \frac{(2h)^3}{3!} f'''(x_0) + \frac{(2h)^4}{4!} f''''(x_0) - \frac{(2h)^5}{5!} f'''''(x_0) + \frac{(2h)^6}{6!}f''''''(x_0) - \frac{(2h)^7}{7!}f'''''''(\xi)
$$
$$
f(x_0 - 3h) = f(x_0) - (3h) f'(x_0) + \frac{(3h)^2}{2} f''(x_0) - \frac{(3h)^3}{3!} f'''(x_0) + \frac{(3h)^4}{4!} f''''(x_0) - \frac{(3h)^5}{5!} f'''''(x_0) + \frac{(3h)^6}{6!}f''''''(x_0) - \frac{(3h)^7}{7!}f'''''''(\xi)
$$

Is there any shortcut in matlab or julia to find this?
Answer: One shortcut is that $f''(x_0)$ is symmetric under reflection about $x_0$, so it's reasonable that your estimator should also be symmetric.  Thus it should be of the form
$$ F(f) =  a_0 f(x_0) + a_1 (f(x_0+h) + f(x_0 - h)) + a_2 (f(x_0 + 2h) + f(x_0 - 2h)) + a_3 (f(x_0 + 3h) + f(x_0 - 3h))$$
It should give $0$ for constants, $(x-x_0)^4$ and $(x-x_0)^6$ and $2$ for $(x - x_0)^2$. That makes  four linear equations to solve for four variables $a_0, \ldots, a_3$.
Answer: Considering any set of points, you could first write the general formula $$f(x+a_ih)=f(x)+a_i h f'(x)+\frac{1}{2} a_i^2 h^2 f''(x)+\frac{1}{6} a_i^3 h^3 f^{(3)}(x)+\frac{1}{24}
   a_i^4 h^4 f^{(4)}(x)+\frac{1}{120} a_i^5 h^5 f^{(5)}(x)+\frac{1}{720} a_i^6 h^6
   f^{(6)}(x)+\frac{1}{5040}a_i^7 h^7 f^{(7)}(x)+O\left(h^8\right)$$ where, in the present case, $a_i=-3+i$ with $(0\leq i\leq 6)$.
Now write $$\sum_{i=0}^6 A_i f(x+a_ih)$$ Set all coefficients equal to $0$ except the coefficient of $f''(x)$ that you make equal to $1$. This would lead to the following set of equations $$A_0+A_1+A_2+A_3+A_4+A_5+A_6=0\tag 1$$ $$-3 A_0-2 A_1-A_2+A_4+2 A_5+3 A_6=0\tag 2$$ $$\frac{1}{2} (9 A_0+4 A_1+A_2+A_4+4 A_5+9 A_6)=1\tag 3$$ $$ \frac{1}{6} (  -27 A_0-8 A_1-A_2+A_4+8 A_5+27 A_6)=0\tag 4$$ $$\frac{1}{24} (81 A_0+16   A_1+A_2+A_4+16 A_5+81 A_6) =0\tag 5$$ $$\frac{1}{120} (-243 A_0-32   A_1-A_2+A_4+32 A_5+243 A_6)=0\tag 6$$ $$\frac{1}{720} (729 A_0+64 A_1+A_2+A_4+64 A_5+729 A_6)=0\tag 7$$  which is easy to solve using matrix calculations.
This leads to $$A_0=\frac 1{90}\quad A_1=-\frac 3{20}\quad A_2=\frac 3{2}\quad A_3=-\frac {49}{18}\quad A_4=\frac 3{2}\quad A_5=-\frac 3{20}\quad A_6=\frac 1{90}$$ This makes $$\sum_{i=0}^6 A_i f(x+a_ih)=h^2 f''(x)+O\left(h^8\right)$$
It is sure that, for the specific values you selectes for the $a_i$, taking into account the symmetry as Robert Israel answered makes things faster.
For sure, you could use the same equations setting to $0$ the rhs of $(3)$ and to $1$  the rhs of $(4)$ to get the third derivative and so on.
For example, the third derivative would be given using $$A_0=\frac 1{8}\quad A_1=-1\quad A_2=\frac {13}{8}\quad A_3=0\quad A_4=-\frac {13}{8}\quad A_5=1\quad A_6=-\frac 1{8}$$ This makes $$\sum_{i=0}^6 A_i f(x+a_ih)=f^{(3)}h^3+O\left(h^7\right)$$
Answer: I came up with this Mathematica code
<code>m = 3;
a = Table[ToExpression["a" <> ToString[n]], {n, m, 0, -1}];
vals = Table[
   Normal[Series[f[x], {x, x0, 8}]] /. {x -> x0 + n h}, {n, -m, m}];
vals // TableForm
vals = Join[
   Table[vals[[i]] + vals[[2 m + 2 - i]], {i, m}], {vals[[m + 1]]}];
vals // TableForm
vals = Collect[ExpandAll[Dot[a, vals]],
   Table[Derivative[n][f][x0], {n, 0, 2 m + 2}], Simplify];
list = Table[
   CoefficientList[vals, Derivative[n][f][x0]][[2]], {n, 0, 2 m + 2,
    2}];
soln = Flatten[
   Solve[Table[list[[n]] == {0, 1, 0, 0}[[n]], {n, m + 1}], a]];
soln // TableForm
vals /. soln
</code>


What to do when translation imported using Locale has an inappropriate translation?

Question: I used Locale module to translate Drupal to my national language. But some words' translation is not appropriate. How can I change the translation of some words?
Answer: Go to  Administer -> Site building -> Translate interface -> Search (d6) or Configuration -> Regional and language -> Translate interface -> Translate (d7). You will see a search box. Simply search and edit string you think should be edited.
Comment: If this is what worked for you, you can tick "accepted" mark. If not exactly, well, at least I'm glad you learnt something usable to you by this.
Comment: I'm new and I do not know directly rules. It's my fault. I ticked "accepted". Thanks.
Comment: @user19455 Not a fault. You are not *obligated* to accept answers. Acceptance means "from all answers this is the one I used and it worked for me" - only set it if that's what you want to say to future readers. Not all good answers needs to be accepted.
Answer: One quick fix is to use the String Overrides module to override the translation of the specific words whose translation you disagree with.
A more community spirited solution would be to join the the translation team for your national language at https://localize.drupal.org/, and improve the translation by participating in the translation effort and discussions within the team about what is the best translation of a particular word or string.  If you get consensus about a change, the "official" translation of the word or string will be changed and you no longer need to override it.


Analytical description of rotation operator

Question: Let $\delta$ be the rotation with center $(1,2)$, that maps the point $(-1,3)$ to the point $(3,3)$.
(a) Describe $\delta$ analytically and determine the rotation angle.
(b) Let $g$ be the line with equation $x-3y-10=0$. Calculate an equation of the line $\delta (g)$.
(c) Let $\tau$ be the translation that maps $(-1,3)$ to $(3,3)$. What kind of transformation is $\tau\circ\delta$ ?
$$$$
For (a) do we have to write it in the form $\delta (x)=Ax$ ? To find the matrix do we have to shift the center to the origin first?
$$$$
EDIT:
In (c) do we have to calculate $\tau$ ? Or is the composition of a translation and a rotation always a specific transformation?
In this case the rotation $\delta$ and the translation $\tau$ map both the point $(-1,3)$ to $(3,3)$.
Is this important?
Comment: Since the center is $(1,2),$ you need $\delta(x)-(1,2) = A(x-(1,2)). \qquad$
Comment: You need $A((-1,3)^\top - (1,2)^\top) = ((3,3)^\top - (1,2)^\top),$ so $A(-2,1)^\top = (2,1)^\top.$ But notice that $A$ must not only satisfy that, but must also be a rotation matrix. $\qquad$
Comment: $$
\left[ \begin{array}{rr} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{array} \right] \left[ \begin{array}{r} -2 \\ 1 \end{array} \right] = \left[ \begin{array}{r} -2\cos\theta-\sin\theta \\ -2\sin\theta+\cos\theta \end{array} \right]
$$
Comment: Remember how matrix multiplication is defined: $$ \left[ \begin{array}{c} a & b \\ c & d \end{array} \right] \left[ \begin{array}{c} x \\ y \end{array} \right] = \left[ \begin{array}{c} ax+by \\ cx+dy \end{array} \right] $$
Comment: Ah yes! Then we use that $\delta ((-1,3))=(3,3)$, right? But is this condition enough to get the matrix $A$ ? @MichaelHardy
Comment: The rotation matrix is of the form $A=\begin{pmatrix}\cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{pmatrix}$, right? So we get $$A\begin{pmatrix}-2 \\ 1\end{pmatrix} = \begin{pmatrix}2 \\ 1\end{pmatrix} \Rightarrow \begin{pmatrix}-\cos \theta  -\sin \theta \\ -2\sin \theta + \cos \theta \end{pmatrix} = \begin{pmatrix}2 \\ 1\end{pmatrix}$$ So we get the system \begin{align*}-\cos \theta  -\sin \theta=&2 \\ -2\sin \theta + \cos \theta =&1\end{align*} And we get $\sin \theta=-1 \Rightarrow \theta=\frac{3\pi}{2}$. @MichaelHardy
Comment: Then we get the matrix $A=\begin{pmatrix}0 & 1 \\ -1 & 0\end{pmatrix}$ and so the analytic description of the rotation is $$\delta(x)-\begin{pmatrix}1\\ 2\end{pmatrix} = \begin{pmatrix}0 & 1 \\ -1 & 0\end{pmatrix}\begin{pmatrix}x-\begin{pmatrix}1\\ 2\end{pmatrix}\end{pmatrix}$$ Is that correct? @MichaelHardy
Comment: For (b) : We take two points of the line find their images and calculate the line through these points, right? The points $(10,0)$ and $(13,1)$ are on $g$. We have that $\delta \left (\begin{pmatrix}10 \\ 0\end{pmatrix}\right )=\begin{pmatrix}-1\\ -7\end{pmatrix}$ and $\delta \left (\begin{pmatrix}13 \\ 1\end{pmatrix}\right )=\begin{pmatrix}0\\ -10\end{pmatrix}$.
The line through $(-1, -7)$ and $(0,-10)$ is $$\delta (g): y-(-10)=\frac{-10-(-7)}{0-(-1)}(x-0) \Rightarrow y+10=\frac{-10+7}{1}x\Rightarrow 3x+y+10=0$$ Is that correct? @MichaelHardy
Comment: Could you give me a hint for (c) ? @MichaelHardy
Comment: Ah yes! I forgot the 2, right? So we get the system \begin{align*}-2\cos \theta  -\sin \theta=&2 \\ -2\sin \theta + \cos \theta =&1\end{align*} So we get $\sin \theta=-\frac{4}{5}$, right? @MichaelHardy
Answer: Since you've essentially answered this in comments, here it is for the record:
$$
\left[ \begin{array}{rr} -3/5 & 4/5 \\ -4/5 & -3/5 \end{array} \right] \left[ \begin{array}{r} -2 \\ 1 \end{array} \right] = \left[ \begin{array}{r} 2 \\ 1 \end{array} \right]
$$
So $\cos\theta = \dfrac{-3}5$  and $\sin\theta = \dfrac{-4}5.$
Comment: @MaryStar : A rotation followed by a translation is another rotation, through the same angle, but with a different center. The center is the one fixed point of the transformation. Here is the rotation centered at $[1,\,\,2]^T$ that you described.
$$
\left[ \begin{array}{r} x \\ y \end{array} \right] \mapsto \left[ \begin{array}{rr} -3/5 & 4/5 \\ -4/5 & -3/5 \end{array} \right]\left( \left[ \begin{array}{r} x \\ y \end{array} \right] - \left[ \begin{array}{r} 1 \\ 2 \end{array} \right] \right) + \left[ \begin{array}{r} 1 \\ 2 \end{array} \right]
$$
Comment: @MaryStar : Now let a translation follow that:
$$
\left[ \begin{array}{r} x \\ y \end{array} \right] \mapsto \left[ \begin{array}{rr} -3/5 & 4/5 \\ -4/5 & -3/5 \end{array} \right]\left( \left[ \begin{array}{r} x \\ y \end{array} \right] - \left[ \begin{array}{r} 1 \\ 2 \end{array} \right] \right) + \left[ \begin{array}{r} 1 \\ 2 \end{array} \right] + \left[ \begin{array}{r} 4 \\ 0 \end{array} \right]
$$ Since you're looking for a fixed point, put an "equals" sign where the arrow is and then solve for $x$ and $y.$ You get $x=3, y=1. \qquad$
Comment: The composition then is $$ \left[ \begin{array}{r} x \\ y \end{array} \right] \mapsto \left[ \begin{array}{rr} -3/5 & 4/5 \\ -4/5 & -3/5 \end{array} \right]\left( \left[ \begin{array}{r} x \\ y \end{array} \right] - \left[ \begin{array}{r} 3 \\ 1 \end{array} \right] \right) + \left[ \begin{array}{r} 3 \\ 1 \end{array} \right] $$
Comment: @MaryStar : Yes. $\qquad$
Comment: The angle of rotation is then \begin{equation*}\frac{\sin \theta}{\cos\theta}=\frac{\dfrac{-4}5}{\dfrac{-3}5} \Rightarrow \tan \theta=\frac{4}{3} \Rightarrow \theta=\arctan \left (\frac{4}{3}\right )\approx 53.13^{\circ}\end{equation*} right?
Comment: Could you give me a hint for question (c) ?
Comment: In (c) do we have to calculate $\tau$ ? Or is the composition of a translation and a rotation always a specific transformation?
Comment: How did you get $\begin{pmatrix}4\\ 0\end{pmatrix}$ ?
Comment: Ah it isthe difference between the mapped point $(3,3)$and the original point $(-1,3)$, right?
Comment: I see!! Thank you very much!! :-)


Override custom newQuery() in Eloquent

Question: For my Deal model, I'm using newQuery() to ensure that only unexpired and approved deals are ever queried. However, a few cases have come up where I don't want these two conditions to be in effect, and I want to query all deals.
What can I do?
public function newQuery($excludeDeleted = true) {
    return parent::newQuery()->where('end_date', '>', date('Y-m-d H:i:s'))->where('approved', 1);
}

Note: I'm not using Laravel, I'm just using the Eloquent library via Composer.
Answer: You are probably looking for conditional clauses - https://laravel.com/docs/5.4/queries#conditional-clauses
and some examples:
http://themsaid.com/laravel-query-conditions-20160425/

Override custom newQuery() in Eloquent


Module in exact sequence isomorphism

Question: I'm really struggling with this excercise although it does not seem that hard.
We are given a PID $R$ and a prime element $p \in R$. $M$ is an $R$-module and a short exact sequence is given by $0 \rightarrow R/(p) \rightarrow M \rightarrow R/(p) \rightarrow 0$. We need to show that either $M \cong R/(p) \oplus R/(p)$ or $M \cong R/(p^2)$.
Now I thought of using the fact that $M$ can be written as a direct sum of the form $M \cong R^{\rho} \oplus R/(p_1^{a_1})\oplus \dots \oplus R/(p_k^{a_k})$ where $p_i$ are prime and $a_i$ are positive integers. Also $\rho$ is unique. Now  I want to prove that the only $\rho$ that could let $M$ fit in such an exact sequence is zero and next that only $p$ can be such prime element.
The second part "only $p$ itself can come in" seems the most doable but I cannot see how to start...
Comment: The short exact sequence implies $R/(p) \cong M/N$ where $N$ is a copy of $R/(p)$.  As $p$ annihilates $R/(p)$, this means $pM \subseteq N$, Since $N$ is annihilated by $R/(p)$, we conclude that $p^2M=0$.  Then, with the decomposition you wrote, what are the possibilities for $M$?
Comment: Yes, that seems to work just fine. Thank you!
Answer: The given information is not sufficient to conclude. One needs to know the maps in the short exact sequence.
Case 1 corresponds to
$$
0 \to R/(p) \oplus 0 \to R/(p) \oplus R/(p) \to 0 \oplus R/p \to 0,$$
and Case 2 corresonds to
$$
0 \to (p)/(p^2) \to R/(p^2) \to R/(p) \to 0
$$
with the isomorphism $(p)/(p^2) \cong R/(p)$.
Comment: Perhaps I am making some assumption I shouldn't be, but is the information not enough?  If $M$ fits into such a short exact sequence, it must be an $R/(p^2)$-module, and $R/(p^2)$ is an Artinian local ring of length $2$.  Further $M$ must have length $2$, and the only indecomposables over $R/(p^2)$ are $R/(p)$ and $R/(p^2)$.  This only leaves the two desired possibilities for $M$ no?
Comment: Hi @metalspringpro, any $R/(p)$-module $M$ is also an $R/(p^2)$-module since $pM = 0$ implies that $p^2M = 0$. I did not see the condition of $M$ begin indecomposible. If so, this condition eliminates Case 1, and your arguement is correct and mine is not.
Comment: No $M$ need not be indecomposable; as I understood it, the OP was asking why $M$ was reduced to being one of the two possibilities $R/(p^2)$ or $R/(p) \oplus R/(p)$, but not claiming to be able to determine which.

Module in exact sequence isomorphism


How do I match something only if a character doesn't follow a pattern?

Question: I"m using Ruby 2.4  How do I write a regular expression that matches a series of numbers, the plus sign and then any sequence that follows provided that sequence doesn't contain another number?  For example, this would match per my rules
23+abcdef

as would this
1111111+  __++

But this would not
2+3

Neither would this
2+ L43

I tried this but was unsuccessful ...
/\d+[[:space:]]*(\+|plus).*([^\d]|$)/i.match(mystr)

Comment: `(\+|plus)` – do you also want to match the word `plus` in addition to `+`?
Answer: r = /\A   # match beginning of string
     \d+  # match one or more digits
     \+   # match plus sign
     \D*  # match zero or more characters other than a digit
     \z   # match end of string
    /x    # free-spacing regex definition mode

"23+abcdef".match?(r)
  #=> true
"1111111+  __++".match?(r)
  #=> true
"23 abcdef".match?(r)
  #=> false
"2+3".match?(r)
  #=> false
"2+ L43".match?(r)
  #=> false

If at least one character that is not a digit is to follow '+', change  \D* in the regex to \D+.
Comment: you can also use `\D` instead of `[^\d]`


Why installation is failed

Question: Installation did not succeed.
The application could not be installed: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
Installation failed due to: 'null'
Session 'app': Installation did not succeed.
                The application could not be installed: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
                Retry

Comment: post your manifest plz!
Comment: What application? how did you try to install it?
Answer: Check following things in manifest file.
Check your Activity name in manifest file.
or the Package name in main activity/class
<activity android:name="MainActivity"></activity>

Check permission tags in manifest tag in manifest file or package name should not contain any capital letters.
More information can found here.
Comment: post your manifest file as well in the question also have you tried the above solutions?
Comment:
Comment:

Why installation is failed


How to make my server available with "forever start server.js"

Question: I have spent multiple hours to try and get my server up and running. As a part of a class assignment we are migrating to ExpressJS. So the instruction go as follows:

Install latest version of nodejs and npm as well as express, morgan,and forever in our ssh server(Ubuntu based).
In our "website" folder we created a "public" folder to throw all web content in.
We then downloaded a server.js script the professor uploaded and we are to place it inside the "website" folder we have.
Then we set the path to the "website" folder. To be clear "website" contains the "public" folder and server.js script.
Write    `forever start server.js`   in the terminal

Forever processes server.js , but I do not get my website loaded,no matter the browser I access through(the terminal is also open). I tried writing forever list and all processes are stopped. I think the issue might be around here.
I have tried using:

forever start ./bin/www -did not work
sudo forever start server.js-did not work
sudo nohup forever start server.js-did not work
nohup forever start server.js-did not work

I really need to figure how to get this server up and running. If you need something from me let me know what and how to get it, please. I am a windows user and more than half of these commands I found researching other questions. If you need logs, or images also, please let me know where to find them to provide them to you since I have little technical knowledge for some of these things. - Thanks!
Comment: Welcome to Stack Overflow. Looks like you have your answer with `pm2`. That works well. For future reference: when you ask Stack Overflow questions, please give more details than *did not work* when something goes wrong.
Answer: You can try nodemon for dev. or pm2 for production if you're trying to keep your server running.
https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/
Comment: Thanks for the comment, in the end there was a need to delete node and reinstall it as well as express. It appears that one of the commands used to install express did not actually install it and was giving issues.