Remove leading comma from a string

Question: I have the following string:
",'first string','more','even more'"

I want to transform this into an Array but obviously this is not valid due to the first comma. How can I remove the first comma from my string and make it a valid Array?
I'd like to end up with something like this:
myArray  = ['first string','more','even more']

Comment: Simply use `myString.slice(1);`
Comment: @NikhilBenKuruvilla this will remove any character even if it's not a comma. Here's first character comma-only removal http://stackoverflow.com/a/39047793/696535
Comment: Possible duplicate of [Delete first character of a string in Javascript](https://stackoverflow.com/questions/4564414/delete-first-character-of-a-string-in-javascript)
Comment: Pawel, what would be the expression to remove the first semicolon no matter where it is from the beginning of the string?  I have to use this:

function removeFirstSemicolon(str) {
 str = str.trim();
 str = str.replace(/^;/, '');
 return str;
}

That might be more helpful -- there is often white space before and after the character so really I have to use trim twice.
Answer: To remove the first character you would use:
var myOriginalString = ",'first string','more','even more'";
var myString = myOriginalString.substring(1);

I'm not sure this will be the result you're looking for though because you will still need to split it to create an array with it. Maybe something like:
var myString = myOriginalString.substring(1);
var myArray = myString.split(',');

Keep in mind, the ' character will be a part of each string in the split here.
Answer: In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)

However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
  str = str.substring(1);
}

Comment: +1 for the conditional as well. Its always better to assume a comma may not be there.
Comment: This is a better answer and should be the accepted answer.
Comment: It's not necessary to run the substring twice to check the first character: `if (str[0] === ',')` just to make it slightly more performant.
Answer: One-liner
str = str.replace(/^,/, '');

I'll be back.
Comment: This one is better than the chosen answer.
Answer: var s = ",'first string','more','even more'";

var array = s.split(',').slice(1);

That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.
Answer: Assuming the string is called myStr:
// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');

// Split stripping quotations
myArray=myStr.split("','");

Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.
Answer: var s = ",'first string','more','even more'";
s.split(/'?,'?/).filter(function(v) { return v; });

Results in:
["first string", "more", "even more'"]

First split with commas possibly surrounded by single quotes,
then filter the non-truthy (empty) parts out.
Answer: To turn a string into an array I usually use split()
> var s = ",'first string','more','even more'"
> s.split("','")
[",'first string", "more", "even more'"]

This is almost what you want. Now you just have to strip the first two and the last character:
> s.slice(2, s.length-1)
"first string','more','even more"

> s.slice(2, s.length-2).split("','");
["first string", "more", "even more"]

To extract a substring from a string I usually use slice() but substr() and substring() also do the job.
Answer: s=s.substring(1);

I like to keep stuff simple.
Answer: You can use directly replace function on javascript with regex or define a help function as in php ltrim(left) and rtrim(right):
1) With replace:
var myArray = ",'first string','more','even more'".replace(/^\s+/, '').split(/'?,?'/);

2) Help functions:
if (!String.prototype.ltrim) String.prototype.ltrim = function() {
    return this.replace(/^\s+/, '');
};
if (!String.prototype.rtrim) String.prototype.rtrim = function() {
    return this.replace(/\s+$/, '');
};
var myArray = ",'first string','more','even more'".ltrim().split(/'?,?'/).filter(function(el) {return el.length != 0});;

You can do and other things to add parameter to the help function with what you want to replace the char, etc.
Answer: this will remove the trailing commas and spaces
var str = ",'first string','more','even more'";
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');

Answer: remove leading or trailing characters:
function trimLeadingTrailing(inputStr, toRemove) {
    // use a regex to match toRemove at the start (^)
    // and at the end ($) of inputStr
    const re = new Regex(`/^${toRemove}|{toRemove}$/`);
    return inputStr.replace(re, '');
}

Remove leading comma from a string


Cannot implicitly convert type 'void' to 'double'

Question: Wrote a method which returns the inch equivalent of its centimeter argument but it says cannot implicitly convert type void to double.
How do i correct this?
Heres the code:
     private void button1_Click(object sender, EventArgs e)
    {
        Double inches = InchEquivalent(10.5);
    }

    public void InchEquivalent(double centimeters)
    {
        double answer;
        answer = centimeters * 0.394;
        MessageBox.Show(answer.ToString());

        return;
    }

Comment: Take some time to read through this tutorial: http://msdn.microsoft.com/en-us/library/ms173114.aspx
Comment: You need to make `InchEquivalent` *return* `double`, right now it is specified to return `void`.
Comment: `InchEquivalent` does not return anything.
Comment: You may want to brush up on programming fundamentals as a whole.
http://msdn.microsoft.com/en-us/library/aa716286%28v=vs.60%29.aspx
https://www.coursera.org/course/programming1
Answer: As the guys in the comments tried to tell you, you have to give the function a return type like this:
public double InchEquivalent(double centimeters)
{
    var answer = centimeters * 0.394;
    MessageBox.Show(answer.ToString());

    return answer;
}

Mind the double instead of the void in public double InchEquivalent and the return answer; instead of just return;
But I would recommend keeping the function pure and responsible for only one thing (that is don't do the MessageBox.Show in there (I guess it's only for debugging anyway), and you can make it static if you like:
private void button1_Click(object sender, EventArgs e)
{
    var inches = Centimeters2Inches(10.5);
    MessageBox.Show(inches.ToString());
}

public static double Centimeters2Inches(double centimeters)
{
    return centimeters * 0.394;
}

Answer: Ok, you've got a function that does units conversion.  The units conversion input centimeters and outputs inches.  Very good.
The input is done via a function parameter.  Excellent choice.
The output is done using a MessageBox to show it to the user.  This may work for quick testing and throwaway code, but it's not a good approach in the long run.  There are basically two problems:

It isn't reusable.  Now you want to use the output in some way, but you can't, because it isn't returned.
It violates the Single Responsibility Principle.  The format of the string shown to the user is part of the conversion.  There's no way for the caller to add some explanatory text to the message box.  Or to specify that it should appear in a textbox instead of a messagebox.

A better design would be for the conversion to output the value in inches as a return value, and let some other code take care of the presentation.


Integrar servidor samba4 ao microsoft active-directory

Question: Tenho um server windows server 2003 em produção rodando como controlador de domínio, tenho as contas, grupos etc. tudo certinho e funcionando ali.
Eis que recebo aviso da microsoft que o server 2003 deixará de ser suportado pela microsoft conforme todos já devem saber
Então comecei a testar a samba4 com suporte a DC (domain controller) e rodou muito bem, pode ser gerenciado pelo RSAT ( Remote Server Administration Tools ), só não sei como fazer agora essa parte de migrar as contas, grupos etc. do DC microsoft para esse feito em samba4, também ouvi dizer algo tipo promover um e/ou replicar, essa parte ai é que não sei fazer, na verdade não sei nem se isso é possível fazer dentro desse ambiente que tenho "samba4 <-> microsoft"
Answer: Ola,
Este procedimento é bem simples.
 1 - Ingressar o Samba 4 como DC do Win2003;
 2 - Transferir as ROLES e FSMO do Win2003 para o Samba 4, para que este seja o DC primário da rede;
 3 - Caso desejar, despromova o DC Windows 2003.
Segue o link:
https://wiki.samba.org/index.php/Join_an_additional_Samba_DC_to_an_existing_Active_Directory
Comment: tente passar todo o conteudo necessário do link para o SOpt, pois assim se o link quebrar a resposta continuará válida.


WP_MAX_MEMORY_LIMIT in wp-config.php seems to be ignored

Question: I am using WordPress v.3.8.1 with WMPL (WordPress Multilingual Plugin) v.3.1.4 and WPML Media Pugin v.2.1.3.
In php.ini file I have...
memory_limit = 512M

I already have a info.php file with <?php phpinfo(); ?> where I can see that memory_limit = 512M.
In wp-config.php file I have before wp-settings.php inclusion...
define( 'WP_MAX_MEMORY_LIMIT', '384M' );

When I am trying to use "Media Translation" I get this error after 50/400 media have been processed...
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 523800 bytes) in /wp-includes/plugin.php on line 1939

I am sorry for the duplicate https://wordpress.stackexchange.com/q/137698/45047 but I really need some guidelines.
Thank you!
Comment: I have contacted my hosting provider and he told me that he hasn't put a limit to RAM - default is 128MB - so from the error message I can see that I am already over default.
Answer: Just send email to your hosting provider and he will change it also you must have same limit in php.ini and config.php, just send email to your provider and he will reebot your server..
Comment: Thank you for your answer. As I wrote (see comment above) I am already over the server's limit. So I think the error would say "Fatal error: Allowed memory size of **134217728 bytes** exhausted (tried to allocate 134741528 bytes) in /wp-includes/plugin.php on line 1939"
Answer: you have to make it same on both files.

in php.ini
in wp_config.php

after this just reboot your server(if you have access).
Comment: I don't understand why it has to be the same in both files (I guess you mean `define( 'WP_MAX_MEMORY_LIMIT', '512M' );`). Anyways I have done that with **no result**. Also if you use this `SetEnv PHPRC /location/todir/containing/phpinifile` in root's .htaccess you don't have to reboot the server.
Answer: i had the same issue with uploading and I found that on php.ini you have also to change the filesize_limit, which by default is set to 2M, you will find this on the lines 920 - 922 :
; Maximum allowed size for uploaded files.
;http://php.net/upload-max-filesize
 upload_max_filesize=64M

You can change the number as it's pleases you.


Como receber um array de resultados em uma variavel

Question: Bom dia,
Estou tentando realizar um projeto bem simples usando o framework Codeigniter, mas sempre tive essa dúvida antes mesmo de implementar um framework, sempre me bato muito para receber dados que são um array, e mostrar esses resultados na tela para o usuario, geralmente eu realizo uma consulta no banco de dados e quero mostrar esses resultados para o usuario, não tenho conseguido usar com o foreach pois sempre me mostra apenas o ultimo resultado, e quero todos os registros que a consulta ao banco de dados me retornou.
Será que alguém pode me ajudar? ou passar um link para algum artigo sobre o assunto?
Tenho um exemplo que eu mostro para o usuarios os horarios que estão no banco de dados e ele seleciona alguns desses horarios, mas antes de cadastrar os horarios que ele selecionou eu quero que, imptima na tela com echo para confirmar a solicitação do usuario.
MODEL
public function select_horarios(){
    $this->db->select('hora');
    $this->db->from('horarios');
    $query = $this->db->get();

    if($query){
        return $query->result_array();
    }else{
        return false;
    }
}

CONTROLLER
public function index(){
    $this->load->model('administrativo/abrirfechar_agenda', 'agenda');

    if(isset($_POST['acao']) && $_POST['acao'] == 'Abrir Agenda >>'){
        $data = $this->input->post('data');
        $horarios = $this->input->post('horarios');

        //Data Formatada
        $data_form = date('d/m/Y', strtotime($data));

        if(empty($data)){
            echo 'Selecione a Data';
        }else if(empty($horarios)){
            echo 'Informe os horarios para a data '.$data_form;
        }else{
            //INICIANDO A CONSULTA PELA DATA E HORARIOS SELECIONADOS

            //Tratamento de matriz
            foreach($horarios as $linha){
                $horas = $linha;
            }
            //INICIANDO O CADASTRO NO BD PARA ABERTURA DE AGENDA.
            echo "Passou na validação ".$horas;
            }
    }

    $dados['horarios'] = $this->agenda->select_horarios();
    $this->load->view('administrativo/abrirfechar_agenda', $dados);
}

VIEW
echo form_label('Selecione os Horários: ', 'horario');
    echo "
";

    foreach($horarios as $linha){
        echo form_checkbox('horarios[]',$linha['hora']);
        echo $linha['hora'];
        echo "
";
    }

Comment: Por favor, poste o código que está tentando implementar, desde model, view e controller.
Answer: Model
public function get_all($limit = NULL, $offset = NULL)
{
        $this->db->select('cli_id, cli_nome');
        $this->db->from("cliente");
        $query = $this->db->get();
        $data = $query->result();
        return $data;
}

$results = $this->Cliente_model->get_all_where($limit, $offset);

foreach ($results as $row) {
  echo $row->cli_nome;
}

Comment: Este é um exemplo como uso o codeigninter para exibir dados do banco de dados;
Comment: só coloquei o nome da função errada get_all_where -> get_all e Também esqueci de retirar os 2 atributos que não estão sendo utilizados.
Answer: Neste caso, se você vai selecionar quais os usuários selecionou, sem ver a sua view completa, eu faria dessa forma:
// controller
public function index(){
    $this->load->model('administrativo/abrirfechar_agenda', 'agenda');
    $dados['horarios'] = $this->agenda->select_horarios();
    $this->load->view('administrativo/abrirfechar_agenda', $dados);
}

// model
public function select_horarios(){

    $this->db->select('hora');
    $query = $this->db->get('horarios')->result();

    if($this->input->post('data') && $this->input->post('horarios')){ // Se houver post data, horarios
        $horarios_selecionados[] = array();
        foreach($query as &$value){ // busco todos os horários
            // neste caso, fazemos então a comparação se existe já o horário cadastrado
            // se sim, ele adiciona na array, para que consigamos dizer ao usuário qual horári
            // já tem cadastrado
            $this->db->where('horario', $value);
            $this->db->where('data', $this->input->post('data'));
            $value->horarios = $this->db->get('horarios')->result();
            $value->data = $this->input->post('data');
        }
    }

    if($query){
        return $query;
    }else{
        return false;
    }
}

// view
foreach($horarios as $value){
    foreach($value->horarios as $h_selecionado){
        echo $h_selecionado."
";
    }
}

Comment: Agora para este exemplo consegui mostrar os resultados dos horarios que estão no banco de dados, mas não consigo mostrar na tela os horarios que o usuario selecionou, pois com o código que postei só me mostra o ultimo resultado. e quero todos os horarios que ele selecionou
Comment: Andre mas esta retornando todos os horarios que o usuario digitou que estão iguais no banco de dados, esta certo mas preciso consultar a data, por exemplo se não dia 02/01/2019 já tiver cadastro do horario 09:00, não posso cadastrar nesta data
Comment: Tente dessa forma que lhe passei agora.
Comment: Veja se dá certo da forma que lhe passei... claro que é uma solução superficial, sem ver sua view e nem o banco de dados...
Comment: Dá certo Sim Andre fiz algumas modificações e funcionou perfeitamente, obrigada pela ajuda... como não entendo como funciona o site o que devo fazer para fechar a pergunta já que voce já solucionou minha duvida?
Comment: Você pode votar (seta para cima, na minha resposta, e marcar como correta - V abaixo das setas) obrigado :)
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/89080/discussion-between-sr-andre-baill-and-sol25lua).


Combining RoboCopy with FtpUse

Question: Our clients need to transfer specified files from their network to ours through FTP. The transfer must be invoked automatically whenever one of the specified files changes. For this purpose, RoboCopy is perfect. However, RoboCopy does not support transfer to FTP addresses.
So, I would like to map our FTP site to a drive letter on the client server. I found that FtpUse is perfect for mapping an FTP to a drive letter. The mapping works as expected and I can see the contents of the FTP site in Windows Explorer - I can also write data to the mapped FTP drive.
So, let's say I've mapped the FTP site to drive Q on my local machine with this command:
ftpuse Q: [ftp address] [password] /USER:[username]

And try to setup RoboCopy with this command:
robocopy [source dir] Q:\ *.xls *.xlsx /COPY:DAT /LOG+:"[LogDir]\FtpCopyLog.txt" /V /NP /MON:1 /MOT:1 /R:10 /W:30

When RoboCopy runs, it fails with the following error message:

ERROR 87 (0x00000057) Copying File [source dir]\test2.xlsm
  The parameter is incorrect

I have tried to map the drive and run the RoboCopy command under the samme user account, but it does not seem to solve the problem.
Hope someone can help.
Any help would be greatly appreciated.
Comment: You can read/write from/to the mapped drive via GUI, but you can't do it from the command prompt?  What commands are you using in COPY/XCOPY?
Comment: Never used FtpUse but what if you setup a Linux Samba Staging Server that both servers accessed? Robocopy to Samba Share and all the Linux server did was provide a network share
Comment: This is an Windows to Windows setup and it seems like a huge job to setup an extra server for this file transfer task.
Comment: Thoughts... can you test a simple copy using COPY or XCOPY, just to confirm whether it's actually ROBOCOPY at fault, or an issue with the drive presented by FTPUSE.EXE.  Second, and it's probably just your example, the error is flagged for a .XLSM file, but this file type isn't in your command.  Just wondering whether there's something else going on here...
Comment: Thanks for your input @simonc. I tried to use COPY and XCOPY and it gives me an error message much like when using robocopy: "File creation error - the parameter is incorrect".
However, I've succesfully copied files from the FTP (Q:) drive to my local drive. So it probably has something todo with permissions. Any ideas?
Comment: It gets even more strange. I tried creating the mapped drive again using the command stated above. Then I used this XCOPY command to copy a file to the mapped FTP drive:
xcopy test2.xlsm q:\test
- with success! Then I tried to execute the exact same XCOPY command again, and then it fails with the same error message as before, "File creation error - the parameter is incorrect". I guess it must have something todo with the file existing on the FTP site. Does anyone have an idea of what goes wrong?
Answer: Try using WinSCP in mirror mode.  WinSCP can be downloaded from here:
http://winscp.net/eng/download.php
Using WinSCP you won't need to map a drive, it just connects to FTP directly and does the work for you.
Here's a small BAT script that makes this similar to ROBOCOPY.
WATCH OUT: I've added -delete option that removes remote files which no longer match local folder. Double quotes are needed because there are spaces in local path.
set FTPSERVER=v2008
set FTPUSER=username
set FTPPASS=password
set FTPLOCALE=C:\Users\User\Desktop\Local folder
set FTPREMOTO=/public
winscp.com /command "open ftp://%FTPUSER%:%FTPPASS%@%FTPSERVER%/" ^
  "synchronize remote -delete ""%FTPLOCALE%"" %FTPREMOTO%"

Answer: When the copy executes you have permission to create files but not to overwrite them.  How big are the files?  From what I gather every time a file is edited the file is copied again in its entirety and you overwrite the old file with the new version.  There is no way to evaluate what has changed in the file and just append the new data?  Since you are not trying to append data and the tools you are using do not allow you to overwrite the file you could in theory write some type of intermediary script that deletes outdated files when they are detected immediately prior to copying the new file in place.  That sounds like a clunky solution but then the whole thing also sounds like a clunky process.  Personally I would re-evaluate what the goal is here and such but I am trying to stick to just answering the question.  Good luck!
Answer: Since you already using windows why not use power shell to do this?  You can specify only new files and schedule the task with windows task scheduler all with built in windows tools.  No need to pay for built in functionality. I assume it is not a secure FTP connection that your using. Some quick scripting will get you a very flexible cheap solution.  I have several power shell scripts that pull and push FTP files base on specific criteria.

PowerShell Connect to FTP server and get files | Stack Overflow
PowerShell FTP Client Module | Microsoft Technet

Combining RoboCopy with FtpUse


How much information do you get if you draw a red card?

Question: I'm trying to figure out what this question is asking and what it is I'm trying to calculate exactly.
I'm told:
You have cards 2-5 of each suit, except the 2 and 3 of the red cards.
So 12 cards total.
I've calculated:
All the probability distributions (conditional, joint), the entropies (conditional, joint), mutual information.
It sounds like the question is NOT asking for a conditional entropy?
Or am I understanding entropy incorrectly? It's an AVERAGE amount of information, right?
I'm not too sure what I'm trying to calculate...
Comment: Did you mean "*of* each suit" and "*of* the red cards"?
Comment: Yes I did. Thanks. I fixed it.
Answer: Learning that the card is red takes you from 14 (not 12) equally likely possibilities to two equally likely possibilities. So now you are one bit short of complete knowledge of the card, whereas you originally were $\log_1 14$ bits short. You won $\log_214-1$ bits of information.
Comment: Thank you. I think I get it. I understand that there is 1 bit of uncertainty left. The log 14 is the amount of bits needed to represent one card choice (out of 14 cards)? If I had picked a black card instead of a red one, I would have only gained 1 bit of info and been left with an uncertainty of (log 14 - 1)?
Comment: @Hagen von Eitzen: At the beginning there are $4\times 4-2\times2=12$ cards.
Comment: Ok, so then it would be log 12 total uncertainty, and if you pick one card that's red, you've eliminated 4 cards, so log 4 = 2 bits? leaving you with log 12 - 2 ? But wait, that doesn't make sense because you can't do the reverse, and log 4 + log 8 != log 12.


Can guitar hum possibly be due to a bad pickup

Question: I am struggling with hum on my archtop that has a Kent Armstrong HJGS-1 floating pickup.  If we touch the outside plastic covering of the pickup or to the ground lug on the pickup, the hum reduces dramatically so it seems like a grounding issue.
What I've tried:

I replaced all of the wires in the guitar but no change.
I pulled the pickup off the guitar and soldiered new 4" wires directly to a jack, the hum is still evident.
We've tried multiple amps.  We've moved the guitar around the house.  We've compared the hum with another guitar on the same amp with the same 1/4" cable.  No hum.

I've done a ton of reading on the subject but I'm stumped.
Questions:

Is it possible that the pickup is indeed generating the hum?  Maybe there is some grounding issue internal to the pickup?
Any addition ways we can test the pickup to make it is the problem?  It shows something like 7.9k ohms and I've figured out the polarity using the metal whack test but otherwise i'm not sure what to try.

Thanks for any help.
Comment: 1) Typically hum is due to faulty grounding, but this could possibly be because of a faulty pickup. 2) What happens when you touch the strings, or when you switch the pickup in and out? 3) this is really the important question here - I'd suggest asking it separately. Grounding is essential - doing it wrong will give hum.
Comment: Thanks for the feedback @DrMayhem.  I've moved my #3 question to it's own: http://music.stackexchange.com/questions/44613/proper-way-to-use-a-shield-and-ground-wire-when-rewiring-a-guitar
Comment: My guitar is able to be kinda radio, catching waves. Some guys suggested me to isolate "hardware stuff" in body with a foil.
Answer: I'm certainly not an authority but I can at least detail what I've learned so far.

Although I bet it is possible for the pickup to be at fault, in my case I'm pretty sure by now that this was a wiring/grounding problem.  Replacing the wire with the 18 gauge shielded wire made a big different right off the bat.  Before I was using a single-core 22 gauge cat5 style wire which made the hum worse.  It also seems like joining the negative and ground wire makes a big difference as well although I'm still learning about this.
In terms of grounding, I'm not sure how to test the pickup.  After doing some more searching I found this great guitar pickup polarity test page which showed how to test the polarity of the pickup by watching the DC voltage on the pickup when it is struck (nicely) with a metal screw-driver.  You should get a positive DC voltage when the metal goes into the pickup and a negative deflection when it is removed.

I also started another question about the proper way to use a shield and ground-wire when rewiring a guitar.


How to selectively rsync folders while retaining tree structure?

Question: On my local machine I have a folder structure like this
/a/b
/a/c
/d/e
/d/f

I want to rsync /a/c and /d/f to a remote server so that after which it has folder structure like
/a/c
/d/f

Do I have to call rsync twice or is there an option can automatically retain the folder structure?
Answer: Good question. You need to use the -R or --relative flag. From the man page:

-R, --relative Use  relative  paths.  This means that the full path names specified on the command line are sent to the server rather than
  just the last parts of the filenames. This is particularly useful when
  you want to send several different directories at the same time. For
  example, if you used this command: rsync -av /foo/bar/baz.c
  remote:/tmp/ ... this would create a file named baz.c in /tmp/ on the
  remote machine. If instead you used rsync -avR /foo/bar/baz.c
  remote:/tmp/ then  a  file  named  /tmp/foo/bar/baz.c would be created
  on the remote machine, preserving its full path.  These extra path
  elements are called "implied directories" (i.e. the "foo" and the
  "foo/bar" directories in the above example).
Answer: To preserve the directory structure, as above, use the -r or --recursive option (recurse into directories).
Then it is up to you how to make a seleciton. Use the -f, -F, --filter, --include or --exclude options.
If needed, you can also use --inclide-from-file or --exclude-from-file, specially if you end up with more than one or 2 filters/includes/excludes.


CSS selector to find the first tbody

Question: My HTML code

               something

 hari

              foo

Xpath solution
"//tbody[1]"
Problem
I am looking for a CSS expression which should select first tbody which is a direct child of table, not the one inside tr.
If I use the CSS as tbody, then it would select 2, but I am looking for a way to fix it here. I know table>tbody will work, I am looking for if any more is there or not. As in my case I can't use table>tbody.
Comment: how about td:nth-child(1) {
  color: red;
}
Comment: @Danield I want to select `tbody` first one not the nested one.. :)
Comment: There is no way to select only the first one without using `>`
Comment: @Babai, take a look at my answer without >
Answer:  tbody tr td:first-of-type {
     color: red;
 }

DEMO
td:first-of-type will works too.

:nth-of-type(1) and :first-of-type are the same. Docs
Answer: Try using the immediate child selector >:
.myclass > tbody

Or if you just want the first one inside that div, you can do:
#myelement:first-child tbody

Comment: Does it select the first `tbody` ?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/36207/discussion-between-babai-and-mattytommo)
Answer: Use the direct child selector >. It will only select elements that are a direct descendant of another element
.myClass > tbody

Make sure to specify the class of the table so that you don't select the table further down in the DOM
Answer: This selector below will select the first tbody inside the table with class myclass, and not the one inside the descendant tr.
table.myclass > tbody

CSS selector to find the first tbody


htaccess does not redirect when uploading Wordpress

Question: Yesterday, I uploaded a Wordpress site on "public_html/wordpress" folder for testing purpose. It worked fine. The URL was "mysite/wordpress".
But today, I deleted the "wordpress" folder, uploaded Wordpress src again to the upper level "public_html" folder. However when I went to "mysite.com", it still redirects to "mysite/wordpress". And of course, a 404 error appears because I had previously deleted the "wordpress" folder.
Even if I typed "mysite.com/index.php", it still redirected to the wrong place "public_html/wordpress"
This is ALL the content of the .htaccess file on "public_html".
DirectoryIndex index.php

I'm completely new to wordpress, please helps me ASAP.
Comment: you don't need to rename and all, just go through permalink settings and save that again. it will works.
Answer: This is due to permalink configuration in Wordpress. If WP admin is loading then visit permalink setting page and change all links to remove /wordpress from URLs.
If WP admin is not coming up then via PHPMyAdmin update wp_options table to fix all URLs that have /wordpress in them. (option_id=39 is one of them).
Comment: Then rename wordpress directory to something else try it out in a new browser to avoid browser caching.
Comment: after visiting `wp_options`, I saw 2 entries with option_name of `siteurl` and `home`. Those are all configued to `http://mysite.com` as default. And the `Permalink` seems fine, too


some number theory method can be used to solve this example quickly?

Question: I have extract some notes from my notes:

one way to found which of four example is uniform function is that try by hand and take some examples. I will search for a method that we can easily infer just the second one has uniform capability. is there any hint or idea to quickly choose the second one instead of try by hand and examples one by one?
for the last one:
$h(1)=1, (h3)=4, h(2)=4$ so means not uniform because $x=3$ and $x=2$ has the same slot.
Comment: the letter $k$ appears only at the example part, does $k$ and $m$  mean the same thing? can you include example of how you verify to show that you have made an effort for this question? are the domain defined explicitly for you?
Comment: try to show more attempts so that the rest can help you. on this site, the more effort you show, you more likely you will get help.
Answer: You want to distribute stuff to $k$ slots. Computing over modulo $k-1$ would not make you attain $k$ slots, hence immediately, we reject the first and third choice.
You can then try some simple number, say when $k=4$ to reject the last case.
Note that $k-1$ and $k$ are coprime. if $a$ and $k$ are coprime, we know that $ax \pmod{k}$ would achieve a bijection.
Comment: if $a$ and $k$ are coprime, then $a^{-1}\pmod{k}$ exists, try to use that to prove $f(x) = ax \pmod{k}$ is a bijection.
Comment: yes, try to prove it :)


can you replace enable_if to disable a function it if constexpr?

Question: So I know you can use enable_if to disable a function template (e.g. if the type is not integral) - but can you do the same with constexpr?
i.e. is there an equivalent for this:
template<class T, typename = std::enable_if_t<std::is_integral_v<T>> >
T test2()
{
    return {};
}

with constexpr - something like:
template <typename T>
T test()
{
    // we expect various integral and floating point types here
    if constexpr (std::is_integral_v<T>)
    {
        T output{};
        return output;
    }
    else
    {
       // trigger compiler error
       return{};
    }
}

so I want:
test(1); // compile ok
test(std::string("hello")); // compile fail

Comment: [static assert](https://en.cppreference.com/w/cpp/language/static_assert)?
Answer: You can use static_assert with a type-dependent expression that is always false in constexpr if.
template<class> inline constexpr bool dependent_false_v = false;
template <> inline constexpr bool dependent_false_v<decltype([](){})> = true; // requires C++20
template <typename T>
T test(T)
{
    // we expect various integral and floating point types here
    if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>)
    {
        T output{};
        return output;
    }
    else
    {
       // trigger compiler error
       static_assert(dependent_false_v<T>);
    }
}

Comment: May as well just do `static_assert(std::is_integral_v)` and get rid of the `if constexpr`.
Comment: http://eel.is/c++draft/temp.res#6.1 "The program is ill-formed, no diagnostic required, if:

    (6.1)
    no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template [...]" -- there is "no valid specialization" of your `else` substatement.  Your example code is ill-formed, ndr.  All you did with your `dependent_false_v` is obscure it so the compiler didn't generate a diagnostic.
Comment: @康桓瑋 It is an interesting question if those hacks succeed.  If there is no way to form the "valid" specialization of the template because the only valid type that would make it valid cannot be named in the context of the template, is there a valid specialization of the template?  What is the sound of one type clapping?
Comment: The dependent false is attempting to fool your compiler.  I am unaware of anything in the standard that makes it different than `static_assert(false)`?  Did the standard get changed since I last looked at it, or do I misunderstand?  (I get you are trying to make the false dependent on the type passed, but the rules about something always being false are more strictly worded whenever I go through them than that...)
Comment: @Yakk-AdamNevraumont [the discarded statement can't be ill-formed for every possible specialization](https://en.cppreference.com/w/cpp/language/if#Constexpr_if), isn't it?
Comment: @songyuanyao yes, and in your case, the discarded statement is ill-formed for every possible specialization.  The "dependent false" attempts to disguise this fact from the compiler detecting it; but your code is still ill-formed, ndr.  Or at least this was my conclusion last time I tried to standard delve that trick.
Comment: @Yakk-AdamNevraumont You mean there's no specialization defined for `dependent_false_v`, so it's always `false` and the discarded statement is ill-formed ?
Comment: @songyuanyao No, for the `test` template; there is a `constexpr if` substatement for whom there is no valid instantiation; `static_assert(dependent_false_v)` has no valid instantiation.  The existence of such a substatement of a `constexpr if` means that, if that substatement isn't instantiated, your program becomes ill-formed, no diagnostic required.  If that substatement is instantiated, it instead becomes ill-formed due to the `static_assert`.  This is the exact same logic for `static_assert(false)` and `static_assert(dependent_false_v)`.
Comment: In the `static_assert(false)` case the compiler, despite not being *required* to tell you your program is ill-formed, does so.  When you `static_assert(depdenent_false_v)` you manage to **fool** the compiler, so it doesn't detect the program is ill-formed, so it doesn't generate the diagnostic.  The program remains ill-formed, you just bypassed the compiler trying to help you and tell you you screwed up.  In 99.9% of cases, `dependent_false_v` tricks do this and only this; they prevent a helpful diagnostic of an ill-formed program.
Comment: @Yakk-AdamNevraumont Does that mean cppreference.com is wrong? It's showing this as a common workaround in serveral places.
Comment: @songyuanyao As far as I know, yes, it is wrong.  There are a handful of places where making something a dependent type actually matters, but almost all uses I know of don't match those places.  (I don't recall what they are off hand)
Comment: Otherwise, make it [well-formed](https://stackoverflow.com/a/57787933/11638718)?
Comment: So we have to define a specialization with value `true` ? @康桓瑋
Comment: this is exactly what I asked for: +1  - but just for simplicity the static assert (on its own) is probably nicer
Answer: It is as simple as this:
template <typename T>
T test()
{
  static_assert(std::is_integral_v<T>);
  T output{};
  return output;
}

Comment: good point! : )


Covering map from $S¹$ to $S^1$?

Question: I'm trying to show that the following map is a covering map:
$ p_{n}: S^{1} \rightarrow S^{1},\space(\cos(t), \sin(t)) ↦ (\cos(nt), \sin(nt))$
I've taken the approach of dividing $S^{1}$ into four overlapping sections: 1) positive first coordinate, 2) negative first coordinate, 3) positive second coordinate, 4) negative second coordinate.
The only thing I'm stuck on is that the 'slices', or $V_{i}$'s, that make up the pre-image of each of these sections are not a disjoint union. In fact, it seems that all the 'slices' are identical and so it only takes one 'slice' to cover each section. Is this okay? Every definition I can find describes the 'slices' as a union of disjoint open sets or a 'collection', but none specify whether this union can be finite, infinite, or whether it matters at all.
Am I already done with this proof and I'm just overthinking things, or have I taken the wrong approach?
Answer: Hint
Use that $p_n$ restricted to $\left(t_0,t_0+\frac{2\pi}{n}\right)$ is a homeomorphism with its image and show that the preimage of any point consists of $n$ points since $p_n(t_0)=p_n\left(\frac{2kn\pi t_0}{n-1}\right)$ for all $k\in\{0,\dots, n-1\}.$
Comment: Could you clarify your notation more? It would seem to me that $$p_{n}(t_{0}) \neq p_{n}(n(t_{0} + \frac{2k\pi}{n}))$$
Answer: I think it's better to approach this question.... $pictorially$.
So take the case n=4.
Hence the set $p^{-1 } \{1\}$ contains 4 elements.
Now let A be the points with first coordinate positive.
Now divide the circle into n=4 equal parts with each part having boundary the pre-images of 1. Now divide each of these parts into 4 equal parts. Then $p^{-1}(A)$ is shown as the red section..
So if you're taking any n, then the preimage of A consists of those sections lying close to the pre-images of 1. Hence these are you're slices.
Hope this helps you

Covering map from $S¹$ to $S^1$?


Difficulty reaching lower E to higher G in left hand on piano

Question: I'm practising the below piano piece and can't physically keep one finger on lower E and higher G at the same time (circles in picture). I think I must have the notes wrong or not reading the music correctly and missing something. Any help would be appreciated.
Comment: who could? only a few of us! But don't worry about this.  (With a sustain pedal this would be no problem of course!) You can play E e g e by 5 1 2 1 and hold the E only a half note. It will be still present in your ear - there are still 2 E in 2 octaves. hold the upper E a half note.
Answer: This is an arrangement of a pop song. Nobody bothers about the correct interpretation of such an arrangement. You can accompany with the sustain pedal. The left hand chords can be held as long you want, take care with the passing tones in the right hand (f# bar 2, f# and d bar 3 etc).
In a classical piece you have to be more correct.
But then you could apply a sostenuto pedal:

On a modern grand piano with three pedals, the middle pedal is usually a sostenuto pedal. It sustains only those notes that are being held down when the pedal is depressed, allowing future notes played to be unaffected. It is commonly abbreviated "S.P.", "Sost. Ped.", or "ThP." (from the German equivalent "Tonhalte-Pedal").

On some upright pianos and lower-quality grand pianos, the middle pedal sustains all notes in the bass register, but this is not a true sostenuto pedal. On other uprights, the middle pedal is a practice pedal (with a locking option), which makes the sound extremely quiet beyond the standard soft pedal. This is often achieved by dropping a felt cloth between the hammers and the strings when the practice pedal is depressed. Not all pianos have a sostenuto pedal, however. Some older, or modern low-quality uprights do not have this option.

https://en.wikipedia.org/wiki/Sostenuto
Comment: yes, but OP doesn't ask about Rachmaninoff, I couldn't play Rachmaninoff not after 60 years practice without a sostenuto pedal.
Comment: Feels a bit dismissive; it's not at all uncommon for some notes being given overly long durations, even in the most high-brow music.
Comment: I don't understand what you mean. My advice is referring to this 6 bars. What do you mean by high- brows?
Comment: With high-brow I meant music that is considered proper art, aka classical. You implied that the rules are different because this is pop music, whereas this notation is also common for music written by the great masters of old - see the Rachmaninoff example from my answer.
Comment: I think a proper sustain pedal works well enough too. The notation of a low note lasting much longer is really common - surely not everyone needs special pianos to accompany those works.
Answer: You do not always have to take notation literally; particularly note durations. When there are multiple voices in the left hand, it is common for one note or chord in the lower register to be given a very long duration, while shorter notes are proscribed in a higher register - often an octave or further apart. See this example from Rachmaninoff's Prelude in C# Minor:

He even does it with both hands; holding the low C#'s in the second measure far into the third. Try holding those octaves whilst performing the eighth-note chords; you would need four hands!
It is more about the impression of those low notes sounding for that duration; which you can do by playing them a little louder, and holding the sustain pedal for the duration. That works only if the higher notes are not staccato, which prohibits pedal. In your case, pedal would work fine.
Another example, this one from Liszt's Reminiscences de Norma:
Comment: This is a classical piece supposed to perform on a grand piano with a sostenuto pedal, yes?
Comment: @AlbrechtHügli Yes; it was written by Rachmaninoff for piano.
Comment: The sostenuto pedal was not common in pianos in Liszt's time.
Comment: @AlbrechtHügli Oh wait, I forgot about sostenuto. I do not think that he specified that pedal.
Comment: yes, but this is a quite different situation: Both hands are articulating a expressive motive. OP's example shows a simple arpeggio. A similar accentuation would be displaced here. The accompaniment is supposed to be calm and flowing.
Comment: @AlbrechtHügli Well, in that case I will acknowledge that I do not know it for sure. I feel like a regular sustain pedal should suffice, both for the old pieces and the new. That is what I hear when I listen to performances of the Rachmaninoff.
Comment: @AlbrechtHügli I added another example where the low notes are not accented
Comment: No problem. I don't have one. I would try to play the Rachmaninoff bars like you explain. But not this piece of OP is questioning about.
Comment: OK, the Liszt piece certainly affords a sostenuto pedal, the left hand is occupied the whole bar.
Comment: @AlbrechtHügli Right; I just thought that for such a notation, the sustain pedal would be acceptable too. But, I do not know for sure.
Comment: @KeizerHarm Those of us who haven't got sostenuto pedals *have* to use the sustain. But then the three ensuing chords *also* get sustained, which isn't precisely what Rachmaninoff  wanted.
Comment: @OldBrixtonian I get that now, but listening to [this recording](https://www.youtube.com/watch?v=YOx710drHnw) I am positive the performer is using the sustain. The first and second chord flow into one another a bit too smoothly. The third chord is separate, for it would be dissonant with the first two, but then the C#'s abruptly stop sounding as well.


Bad sampling or just bad correlation?

Question: I'm currenly trying to do a multivariate analysis to forecast yearly energy consumption for a given building (unit GJ).
A lot of my sample data shows vertical columns when creating a scatter plot.
As my data is not ideally spacially distributed, I suspect the source of these to be that the larger part of my data comes from streets where all buildings have the same specs.
The example below show a correlation analysis for the surface (Oppervlakte in Dutch) of a building (variable originating from the land registry, unit m2).

I suspected that the correlation coefficient wouldn't be very high as a lot of factors determine energy consumption, but I expected at least a usable forecast variable from this one.
The bad distribution of the samples is reflected in de density plots in both histogram and the scatter density.

Suspecting to much of the same type of buildings to be an issue I tried to plot again but only using unique numeric values for surface.
This results in a much higher correlation coefficient and more evenly distributed data, this is the kind of result I would expect:

My questions are the following:

Is the "density blob" / "histogram spike" an indication of bad
sampling?

Is my way of filtering the data a responsible way or is it better to
use all the data (if this is even possible with such a low
correlation)

Thanks in advance,
Michaël
(Are plots are using Seaborn in Python)

Thanks for the answers so far! :)
@Ben
The consumption samples are an export from the database of a company that does provide a billing platform for energy suppliers. The data is bound to their customers and the bulk of the data is from their few biggest customers. As each customer usually operates within a single city, the data could be way better distributed spatially. The predictive variables are rather scarce as I depend on public datasets to build a model. Volume would indeed be a way better predictor than surface alone, but the registry doesn't provide it. Surface is the living space, so only the floor surfaces of a building.
Thanks for the log-log regression tip, will have a look at that!
@Tanner
It was my understanding that a predictive variable has to be quasi normally distributed to be usable for a regression model. Ben's suggestion to also try log scales looks interesting.
Creating synthetic results was indeed my fear in this and this was the primary reason to ask my questions here.
There doesn't seem to be a rule as to usable correlation coeffients lower bounds. Only the general rule of > 0.5 being significant. What is your experience in this? Anything >0.25?
Comment: Expecting to find a strong correlation and then changing your analysis until you find what you expect might be common, but it's very very bad practice. If the results don't match your expectations, consider that your expectations might be wrong.
Comment: I agree. I tried it under the assumption that some oddly specific values might dominate the data (surface around 40 and 60m2) which show both in the scatter plot and histogram. I felt that missing data in between might skew correlation results and the filtered data looked way more "natural". It felt wrong though, hence my question.
Comment: Does "surface" account for different number of floors? Do you distinguish between commercial and residential buildings?
Comment: The registry has the following definition of "surface": "The usable area of a residential object". I can distinguish between "building purpose", e.g. residential, school, sports, shop, industrial... Current plots include all buildings regardless of the type os use.
Comment: Correlation by itself does not imply correlation. If you're sample size is large enough, a correlation of 0.001 could be significant. As to your point about normality, depending which derivation of the Linear Model you use (MLE vs LSE), the assumption of normality is.... lose at best. Yeah if your data is wildly skewed you might have issues, but your data is plenty "normal enough" that it isn't skewing your results.
Comment: If such low correlations could have significance, how could you filter potential variables? Wouldn't the resulting coefficients of a multilinear regression model highlight a variable's significance more than the correlation coefficient?
Answer: Since you don't describe your sampling mechanism, there is no way to diagnose "bad sampling" versus "this is just what the distribution looks like".  This is an inherent statistical problem that occurs in many types of analysi when you get a distribution that looks a it unusual --- is this because the distribution is just a bit unusual (but we should follow the data where it leads us) or is it that the sampling method was informative?  So in answer to your main question, no, a density blob is not necessarily an indication of bad sampling; it might just mean that there is a legitimate area of high density in the distribution.
What I would say here is that you have two variables that ought to be theoretically related by some nonlinear mathematical equation, so you should start with that equation in your regression and then search for unusual deviations from the expected nonlinear relationship.  To be specific, if Oppervlakte refers to surface area of a building then this measure should have a well-defined mathematical relationship with building volume,$^\dagger$ which might be expected to be (roughly) proportionate to energy consumption (though this is likely to be affected by greater energy efficiency for larger buildings).
For this reasons I would recommend using a log-scale for the Oppervlakte and energy consumption variables and doing some kind of log-log regression bassed on these transformations.  Think about whether you can obtain some "baseline" relationship based on a simplified deterministic relationship between surface area and energy consumption and then form your model to set this as a baseline effect but then add additional terms to measure deviations from this.  Your plot shows a significant amount of variation in the relationship, so the inferred correlation is going to be quite weak.  Ensure that your modelling choices are not made in order to get a desired conclusion, and accept that the answer might be that the variables in question are only weakly correlated.

$^\dagger$ You have not specified if "surface" includes only the surface area of the external walls, or also the roof, or also the point of contact between the floor and the ground, so it is hard to say what this relationship would be.  Also, to get a deterministic relationship you would need to assume that each building is a rectangular prism and you would want other dimensions (e.g., height, width).  Without these you might still be able to give a rough relationship based on some simplifying assumptions.
Answer: High Level: Your question doesn't have a "pure" mathematical answer per se, it really depends on context, but there are some principles we can use to think about this.
First to directly address your questions:
Is the "density blob" / "histogram spike" an indication of bad sampling? No, unless you know something specific. Your data could have any type of distribution, there is no garuntee that it is random / normally distributed. A common misconception is that large samples of data have a tendency towards normality. This is not true. You data distribution can look like anything, and that really doesn't tell us anything about your sampling.
Is my way of filtering the data a responsible way or is it better to use all the data (if this is even possible with such a low correlation)? To be honest I don't love it. The issue you seem to have with your data is it is censored to nearby values; the estimates are "rough" and not very precise. However, assuming this censoring is more-or-less random, it really shouldn't effect your statistical analysis. Sure, the graph looks a little funny, but it doesn't really change your analysis. I'd argue the reason you're getting a higher correlation with the reduced data is because you're oversampling from points on the high and low points of the distribution (where the variance tends to be lower based on your graphs) and undersampling from the middle (where your variance tends to be higher). So you're synthetically creating a data set that is overly confident.
Putting this all together: there is no reason to suspect your distribution is wrong based on the histogram. Your goal in sampling is to get as close to a random sample as possible. If your random sample includes a lot of building with the same specs... then that's you're true distribution, and you shouldn't change it.
An important point: An r of 0.28 may feel low for the type of data you're used to, but it really is quite usable, and sometimes that's just the kind of correlation you get in real life.

Bad sampling or just bad correlation?


Is possible to choose the file_default_scheme to save avatars?

Question: I'm using amazonS3 module and if I choose Amazon Simple Storage Service as my default download option, user's avatars are uploaded to my bucket in Amazon. I wish I could choose the default_scheme for avatars but checking the user_save function code I found these:
 if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
    $picture = $account->picture;
    // If the picture is a temporary file move it to its final location and
    // make it permanent.
    if (!$picture->status) {
      $info = image_get_info($picture->uri);
      $picture_directory =  file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');

So I think that it uses the default scheme selected. Is it possible to change it?
Thanks
Answer: file_default_scheme() returns a variable using variable_get(), unfortunately it just returns it straight without hooking out to any other modules.
For modules that call user_save() directly I don't see any way around this without patching the user module, there's just no way to intercept it.
For the user profile and registration forms you might be able to override the submit handlers, and call your own version of user_save() which contains logic to choose the right file scheme. I don't have time to test it but it would probably look something like this:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    // Remove the standard submit handler
    if(($key = array_search('user_profile_form_submit', $form['#submit'])) !== FALSE) {
      unset($form['#submit'][$key]);
    }
    // And add the custom one
    $form['#submit'][] = 'MYMODULE_user_profile_form_submit';
  }
}

function MYMODULE_user_profile_form_submit($form, &$form_state) {
  // Copy the code from user_profile_submit() and change the user_save()
  // line to MYMODULE_user_save()
}

function MYMODULE_user_save($account, $edit = array(), $category = 'account') {
  // Copy the code from user_save() and change the file scheme as required.
}

There might be some caveats to that I haven't though of but hopefully it'll provide a good place to start.
Answer: The code you show is executed from user_save() right after invoking hook_entity_presave(). You could implement that hook using the following code.
function mymodule_entity_presave($entity, $type) {
  if ($type == 'user' && is_object($entity) && !empty(entity->is_new)) {
    if (!empty($entity->picture->fid) && (!isset($entity->original->picture->fid) || $entity->picture->fid != $entity->original->picture->fid)) {
      $picture = $entity->picture;
      if (!$picture->status) {
        $info = image_get_info($picture->uri);
        $picture_directory =  'your scheme://' . variable_get('user_picture_path', 'pictures');

        file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
        $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);

        if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
          $picture->status = FILE_STATUS_PERMANENT;
          $entity->picture = file_save($picture);
          file_usage_add($picture, 'user', 'user', $entity->uid);
        }
      }
    }
  }
}

It's the same code used by user_save() with the exception that it doesn't use the scheme returned from file_default_scheme(), but it uses 'your scheme://'. (Remember to change that with the scheme you want to use.)
Once that code is executed, $picture->status is not 0, and the equivalent code used from user_save() will not be executed.
My code doesn't change picture->status when file_move() fails, which is what user_save() does too.
This is the code I would use, as it makes you duplicate as less code as possible.


solution of difference equation

Question: I am trying to solve the following difference equation:
$$-\frac{\epsilon}{h^2}U_{n+1}+\left(\frac{2\epsilon}{h^2}+\frac{1}{h}\right)U_{n}-\left(\frac{\epsilon}{h^2}+\frac{1}{h}\right)U_{n-1}=0,\mbox{ }\mbox{ }\mbox{ }\mbox{ }U_0=1,\mbox{ }U_1=0.$$
I try $U_{n}=Aw^n$ then I get
$$w_{1,2}=\frac{\left(\frac{2\epsilon}{h^2}+\frac{1}{h}\right)\pm\sqrt{\left(\frac{2\epsilon}{h^2}+\frac{1}{h}\right)^2-4\frac{\epsilon}{h^2}\left(\frac{\epsilon}{h^2}+\frac{1}{h}\right)}}{2\frac{\epsilon}{h^2}}.$$
This seems a bit far from what I want to get. I am trying to verify that the solution is
$$U_n=\dfrac{1-(1+\rho)^{n-N}}{1-(1+\rho)^{-N}},$$
where $0\leq n\leq N$ and $\rho=h/\epsilon$.
Comment: If you want to verify a solution you already have, just substitute it in the equation and check it is true, and also check the initial conditions.
Comment: In your third term in your difference equation, did you mean $U_{n-1}$?
Comment: Note that the homogeneous equation has solution $U_n=1$, equivalently you have a solution $w_1=1$. This makes life a lot easier.
Comment: @CameronWilliams, yes and thanks for that.
Comment: @MarkBennet, could you elaborate.
Comment: @Vaolter Suppose $au_{n+1}+bu_n+cu_{n-1}=0$ with $a+b+c=0$ then the roots of $aw^2+b^w+c=0$ are $1$ and $(-\frac ba-1)$. The root $1$ is obvious, and the sum of the roots is $(-\frac ba)$.
Answer: First of all note that, inside the square root, we have
$$
\left(\frac{2\epsilon}{h^2}+\frac{1}{h}\right)^2-4\frac{\epsilon}{h^2}\left(\frac{\epsilon}{h^2}+\frac{1}{h}\right) = \frac{1}{h^2}
$$
So the answers read
$$w_{1,2}=\frac{\left(\frac{2\epsilon}{h^2}+\frac{1}{h}\right)\pm \frac{1}{h}}{2\frac{\epsilon}{h^2}}.
\Longrightarrow w_1=1, w_2=1+\frac{h}{\epsilon}
$$
This means that the solution reads $U_n=A+B(1+\rho)^n$. Now let us impose boundary conditions . Since $U_0=1$, we get that $A+B=1$. Also, since $U_1=0$, we get that $A+B(1+\rho)=0$ or equivalently, $A=-(1+\rho)B$. Plugging this into the first equation, we get that $B=\frac{-1}{\rho}$, and that $A=\frac{1+\rho}{\rho}$, leading to a solution of the form
$$U_n=\frac{1+\rho}{\rho} \bigg[ 1-(1+\rho)^{n-1} \bigg].
$$
We can readily check that for $n=1$, we get $U_1=0$, and $n=0$, we get $U_0=1$.
bBut this is not what you are trying to recover. Your desired answer has $N$ in it, which is defined nowhere in the statement of the problem. My conjecture is that, $n$ is limited to the range $0,N$.
Let us now consider the following set of boundary conditions:
$$U_0=1,U_N=0$$
Imposing the first condition on  $U_n=A+B(1+\rho)^n$, we get $A+B=1$. Imposing the second condition, we get $A+B(1+\rho)^N=0$, which can be equivalently expressed as $A=-B(1+\rho)^N$. Plugging this into the first equation, we obtain $B=\frac{1}{1-(1+\rho)^N}$
. Also for $A$ we obtain $A=\frac{ -(1+\rho)^N}{1-(1+\rho)^N}$.
For the solution, we use the values of $A,B$ obtained above, and arrive at
$$
U_n=\frac{(1+\rho)^n-(1+\rho)^N}{1-(1+\rho)^N}$$
Dividing both the numerator and the denominator by $-(1+\rho)^N$, we arrive at
$$
U_n=\frac{1-(1+\rho)^{n-N}}{1-(1+\rho)^{-N}}$$

solution of difference equation


Is there any rule I violated in my 4-part harmony exercise?

Question:
The exercise was to make the harmony for the bass notes.
I'm studying with a book by myself so I'm not sure if I am doing this right.
Comment: So if I'm understanding this right, the book gave you the bass line and you had to fill the rest in? Did it give figured bass too? The parallel 5ths definitely a broken rule. Jump of a 6th in bass isn't awesome, but not technically wrong; it would be a little boring but you could just have bass be an "E" right there. You also have a couple moments where SA are octaves. This will create a hollow sound, so be aware of that. Last, your soprano line at end is odd. Again, not wrong but a leap of a 4th after smooth leading would be jarring.
Comment: @jjmusicnotes what do you mean by "figured bass" ? do you mean the inversion numbers ? if that's what your asking, yes. could you be more specific what part your talking about in "jump of a 6th in bass isn't awesome....." ?
Answer: This is actually rather nice, and quite impressive for someone learning on their own; nicely done!
Here are the comments I would give if you were my student:

The most egregious error is in m. 4, with the parallel perfect fifths D/A to E/B between the bass/soprano on beats 2 and 3. This is a definite error in this style that needs to be fixed.
There's a related error here of the V moving to IV6, which is a retrogression (as opposed to a progression). Your IV–V–IV6 is almost a predominant expansion, but if you really want to expand the IV chord, a better choice on beat 3 would be I64 (which would get you out of the parallel perfect fifths). Maybe try that! (Note: Some might not consider this an error.)
Your chords are all I, IV, and V. This is not an error, and perhaps this was intentional, but you may try throwing another chord or two in there. Instead of IV, maybe try ii or ii6. Instead of V64, maybe try viio6, which is actually much more common with the 1–2–3 or 3–2–1 bass.
A very small error is found moving into beat 4 of m. 6. Here, the soprano moves by leap into a B, and the bass moves by step into another B. The rule here is that, if the soprano and bass move by similar motion into a perfect consonance, the soprano must move by step. But here, the soprano and bass both descending into a perfect octave, and the soprano leaps. These are often called "hidden" octaves, but people have different names for them. It's a relatively obscure rule, but it's one I thought I would share; you could easily place a D in the soprano and make this chord a V43 if you like, or make it a viio6 with a few other changes.

Lastly, there are some questions in the comments about a leaping sixth. On beat 4 of m. 4, your bass F♯ leaps down a sixth to A and then immediately back up a sixth to the F♯. Typically, a leap larger than a third will resolve by step in the opposite direction. In other words, your leap down a sixth (which itself is a little large) would almost certainly want to resolve with stepwise ascending motion through B and C♯. But, if you were given these bass pitches, then that's not your error! (But in my opinion, it would be better to just move that A up an octave.) I strongly recommend not just putting an E there, because you'd be left with an illegal six-four chord.
Comment: @HyunYooPark In short, six-four chords have to be treated a particular way. The bass of a six-four chord can either be a passing tone between the chords on either side of it, a pedal tone, the same pitch as the next chord, or an arpeggiation of the given chord. In this case, the bass would be a neighbor, which would not be an acceptable option. Try searching around for "six-four chords" to learn more!
Comment: Thanks for your answer ! It really helped me a lot ! But I don't quite get what you're saying here  "I strongly recommend not just putting an E there, because you'd be left with an illegal six-four chord."  What is a "illegal six-four" ?
Answer: Rising Parallel fifths in bass and soprano parts, bar 4 beats 2 and 3? That's a comment rather than a Rule Violation. Some people are more relaxed about parallel fifths than others.
Comment: In this style writing, you generally want to avoid parallel fifths, especially between the bass and soprano because the outer voices draw attention to it. Parallel fifths hidden in the inner voices are not as obvious.
Comment: Thanks ! I didn't see that ! but if it is just a step movement I heard it's ok ?am I wrong ?
Comment: There's no exception for 5ths moving by step.  Bar 4 would be seen as a serious error in the context of this sort of harmony exercise.


Is there any time complexity difference between recursive and iterative approach?

Question: I am aware that we do have space complexity difference between a recursive and iterative algorithm. But , do we also have time complexity differences between them?
For example: If I have a program that counts the number of nodes in a list recursively and then I implement the same program as iterative, will I have any difference in its Time complexity i.e. O(n)? Thank you
Answer: Short answer: no.
Unless you optimize the algorithm using dynamic programming or such, there is no change to time complexity. There is also no change to space complexity, don't know where you got that idea..
However, in many programming languages there is an inherent overhead to using recursion, since they must store the stack as well, which uses more memory. This can be slower, especially if it is not tail recursion.


Can I use AccountManager to let users sign in with their Google account?

Question: I'm creating an app that will need users to create an account. (Like Facebook or Twitter would require you to.)
BUT, since it's an Android app, should/can I let them sign in with their Google Account using AccountManager or some other service? It'd be very helpful if they could just sign in to their Google account and their settings and other options would be saved to that account.
Main questions summed up:

Is it possible to let a user just use their Google account in my app?

If so, do I use AccountManager to have them sign in and save account information/settings?

What are other options?
Comment: For a while there was a ~hack that allowed you to request authentication to a Google App Engine app, and by using that app as your backend you could get an authenticated identifier and/or email address. Not sure if that still works, I heard it was being phased out.
Answer: Yes, you can get users to log into their Google Services using their Google credentials, for example, I  have an app on Google Tasks and I use the Android AccountManager to let users authenticate themselves using their Google account on the android device (No need for users to enter their password!)
There are some really good examples to get you started:

This is an in-depth look into how you can authenticate based on the users Android credentials, has an example of how things work and how the UI should be: http://www.finalconcept.com.au/article/view/android-account-manager-step-by-step-2
This is an example of getting AccountManager to work with a Google service like Google Tasks: https://developers.google.com/google-apps/tasks/oauth-and-tasks-on-android

The last example is using the same concept for accessing the Google Picasa service: http://code.google.com/p/google-api-java-client/wiki/AndroidAccountManager

The other options you have is to have users manually enter their username/password. For that you have to use a third party authentication API (like signpost for OAuth) for them to log in.
In my tasks/todo application I provide users both options to sign in, using their android credentials or using third party authentication for users that want to log in using some other account (an account which is not enabled on that device)
Let me know if you have more questions
Comment: So that screen would come up when they run the app for the first time? (It would say my app's name instead of TasksSample obviously) and then they'd stay signed in to the app or how does that work?
Comment: Yup, that would come up when you asked for access to use the users credentials on android. Once you get access, you can generate a temporary authorization token based on the users credentials (which you cannot directly see). This temporary token can be used to access the google (or other API like FB/Twitter as the case may be) API on the users behalf. Once the token expires, you can refresh it programmatically to regain access to the service without having to show the user such a screen.
Comment: is there any tutorial available for getting such tokens for gmail&facebook  , in order to be able to fetch data from them?
Comment: There is a very good example on facebook authentication on android here http://blog.doityourselfandroid.com/2011/02/28/30-minute-guide-integrating-facebook-android-application/ I can't find any example specific to gmail, but for google services in general (like tasks) you can use AccountManager http://developer.android.com/training/id-auth/authenticate.html
Answer: Although it is a new development, Google Plus Sign-in introduced as part of Google Play Services can also be used. More info can be found at Android developers blog. See example implementation from Banjo app

There seems to be a big limitation - The user need to have Google+ app installed on the device to use this.

Also this is a pretty good blog if someone is interested in implementing the solution.
Answer: @Soham gave you some very useful links but he didn't correct one major error: AccountManager is the entity that manages the accounts on your Android device - it has nothing to do with your google account! you can use google account and create a NEW account on your device using the AccountManager.
The rest you can learn from the links Soham gave you.


how to pass tokenid from one class to other class in iphone

Question: <code>hi friend i am passing tokenid throw this class to this here is my code how i am passing it wrong for

-(void)check
{
    //app.journeyList = [[NSMutableArray alloc]init];
    [self createEditableCopyOfDatabaseIfNeeded];

    NSString *filePath = [self getWritableDBPath];

    sqlite3 *database;

    if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
        const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)    {
            sqlite3_bind_text(compiledStatement, 1, [txtUserName.text UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(compiledStatement, 2, [txtPassword.text UTF8String], -1, SQLITE_TRANSIENT);
            //NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
            //          NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];

        }
        if(sqlite3_step(compiledStatement) != SQLITE_ROW ) {
            NSLog( @"Save Error: %s", sqlite3_errmsg(database) );
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"User is not valid" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
            alert = nil;

            //We have no data in database so send request to webserver.
            //apitest = [[UIApplication sharedApplication]delegate];
            //if (apitest.internetConnectionStatus != NotReachable)
//          {
//              [self sendRequest];
//          }
        }
        else {

            isUserValid = YES;
            if (isUserValid) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Valid User" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];

            }
        }

        sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database);
}

-(IBAction)update:(id)sender
{
    test1  *check = [[test1 alloc]initWithNibName:@"test1" bundle:nil];
    check.tokenapi1=tokenapi;;
    [self presentModalViewController:check animated:YES];
    //[self getStudents];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
    [webData release];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@",loginStatus);

    //this is to perfrom insert opertion on the userinformation table

    NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

    NSDictionary *result = [json_string JSONValue];

    tokenapi = [result objectForKey:@"TokenID"];
    NSLog(@"this is token id:%@",tokenapi);
    //
    BOOL errortest = [[result objectForKey:@"isError"] boolValue];
    if(errortest == FALSE)
    {
     values = [result objectForKey:@"Result"];
        NSLog(@"Valid User");
    }
    else
    {
        NSLog(@"Invalid User");
    }

    NSMutableArray *results = [[NSMutableArray alloc] init];

     for (int index = 0; index<[values count]; index++) {
     NSMutableDictionary * value = [values objectAtIndex:index];
     Result * result = [[Result alloc] init];
     result.UserID = [value objectForKey:@"UserId"];
     result.FirstName = [value objectForKey:@"FirstName"];
     result.LastName =[value objectForKey:@"LastName"];
     result.Email =[value objectForKey:@"Email"];
     result.ProfileImage =[value objectForKey:@"ProfileImage"];
     result.ThumbnailImage =[value objectForKey:@"ThumbnailImage"];
     result.DeviceInfoId =[value objectForKey:@"DeviceInfoId"];
     NSLog(@"%@",result.UserID);
         ID=result.UserID;
      NSLog(@"%@",ID);
     [results addObject:result];
     [result release];
     }

     for (int index = 0; index<[results count]; index++) {
     Result * result = [results objectAtIndex:index];
     //save the object variables to database here

     [self createEditableCopyOfDatabaseIfNeeded];

     NSString *filePath = [self getWritableDBPath];

     sqlite3 *database;
     //NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
//   NSNumber *timeStampObj = [NSNumber numberWithInt: timeStamp];
//   NSLog(@"%@",timeStampObj);
//   NSString *journeyid = [NSString stringWithFormat:@"%@_%@_%@", result.UserID, result.DeviceInfoId, timeStampObj];
     if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
     const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)";
     sqlite3_stmt *compiledStatement;
     if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)    {
     //sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT);
     sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
     sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
     sqlite3_bind_text(compiledStatement, 3, [txtUserName.text UTF8String],-1,SQLITE_TRANSIENT);
     sqlite3_bind_text(compiledStatement, 4, [txtPassword.text UTF8String],-1,SQLITE_TRANSIENT);
     sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
     sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT);

     }
     if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
     NSLog( @"Save Error: %s", sqlite3_errmsg(database) );
     }
     else {
     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Record added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
     [alert show];
     [alert release];
     alert = nil;
     }

     sqlite3_finalize(compiledStatement);
     }
     sqlite3_close(database);

     }

    [loginStatus release];
    [connection release];
    [webData release];
}

-(IBAction)click:(id)sender
{

    [self sendRequest];
    //this is to select username and password from database.
    [self check];

}

this where i am passing then token id using for updat userprofile with tokinid but it not taken here it show error in console it show tokenid invalid i thing i have to pass user id also for update vale as refrence for tokenid
</code>
Comment: there are a few ways                                              1.pass has pointer                                                    2 create a global variable                                            3 create a delegate
Comment: @Radu could u explain me in detail how to do this
Answer: You should use the Delegate pattern for passing a value from one class to others.
See the below SO post.
How do I set up a simple delegate to communicate between two view controllers?


Spark Streaming mapWithState seems to rebuild complete state periodically

Question: I am working on a Scala (2.11) / Spark (1.6.1) streaming project and using mapWithState() to keep track of seen data from previous batches.
The state is distributed in 20 partitions on multiple nodes, created with StateSpec.function(trackStateFunc _).numPartitions(20). In this state we have only a few keys (~100) mapped to Sets with up ~160.000 entries, which grow throughout the application. The entire state is up to 3GB, which can be handled by each node in the cluster. In each batch, some data is added to a state but not deleted until the very end of the process, i.e. ~15 minutes.
While following the application UI, every 10th batch's processing time is very high compared to the other batches. See images:

The yellow fields represent the high processing time.

A more detailed Job view shows that in these batches occur at a certain point, exactly when all 20 partitions are "skipped". Or this is what the UI says.

My understanding of skipped is that each state partition is one possible task which isn't executed, as it doesn't need to be recomputed. However, I don't understand why the amount of skips varies in each Job and why the last Job requires so much processing. The higher processing time occurs regardless of the state's size, it just impacts the duration.
Is this a bug in the mapWithState() functionality or is this intended behaviour? Does the underlying data structure require some kind of reshuffling, does the Set in the state need to copy data? Or is it more likely to be a flaw in my application?
Answer:
Is this a bug in the mapWithState() functionality or is this intended
  behaviour?

This is intended behavior. The spikes you're seeing is because your data is getting checkpointed at the end of that given batch. If you'll notice the time on the longer batches, you'll see that it happens persistently every 100 seconds. That's because the checkpoint time is constant, and is calculated per your batchDuration, which is how often you talk to your data source to read a batch multiplied by some constant, unless you explicitly set the DStream.checkpoint interval.
Here is the relevant piece of code from MapWithStateDStream:
override def initialize(time: Time): Unit = {
  if (checkpointDuration == null) {
    checkpointDuration = slideDuration * DEFAULT_CHECKPOINT_DURATION_MULTIPLIER
  }
  super.initialize(time)
}

Where DEFAULT_CHECKPOINT_DURATION_MULTIPLIER is:
private[streaming] object InternalMapWithStateDStream {
  private val DEFAULT_CHECKPOINT_DURATION_MULTIPLIER = 10
}

Which lines up exactly with the behavior you're seeing, since your read batch duration is every 10 seconds => 10 * 10 = 100 seconds.
This is normal, and that is the cost of persisting state with Spark. An optimization on your side could be to think how you can minimize the size of the state you have to keep in memory, in order for this serialization to be as quick as possible. Additionaly, make sure that the data is spread out throughout enough executors, so that state is distributed uniformly between all nodes. Also, I hope you've turned on Kryo Serialization instead of the default Java serialization, that can give you a meaningful performance boost.
Comment: @CᴴᴀZ For each batch, Spark takes the keys, partitions them by hash, and sends each batch to executor holding the state in memory. Think of it as an RDD partitioned by all keys that map to a given worker.
Comment: In my case I can see that every job are checkpointed in the batch. Why not only the last job?

What is your solution to keep an eye on the size of the state? To be able to optimise it.
Comment: @crak What is your checkpointing interval? And how are you seeing that every job checkpoints the data?
Comment: Every 10 batch. My eye was abuse, I have 12 job on 16 that do checkpoint. And it's logic, I have 12 mapWithState, I can see there footprint in spark ui. But without knowing which one have the most size.
mapWithState store just state not like the previous implantation?
Comment: @downvoter Feel free to elaborate what you find wrong.
Comment: @YuvalItzchakov: For `state to be distributed uniformly`, does Spark send updates to Workers on each `updateState` operation? What distributed abstraction does it use (RDD?), is this related to `broadcast` feature of Spark?
Answer: In addition to the accepted answer, pointing out the price of serialization related to checkpointing, there's another, less known issue which might contribute to the spikey behaviour: eviction of deleted states.
Specifically, 'deleted' or 'timed out' states are not removed immediately from the map, but are marked for deletion and actually removed only in the process of serialization [in Spark 1.6.1, see writeObjectInternal()].
This has two performance implications, which occur only once per 10 batches:

The traversal and deletion process has its price
If you process the stream of timed-out/ deleted events, e.g. persist it to external storage, the associated cost for all 10 batches will be paid only at this point (and not as one might have expected, on each RDD)


Equations of the characteristics of the fan of the Burgers equation $u_t+uu_x=0$

Question: I'm looking for the equations of the characteristics of the fan  of the Burgers equation
$$\frac{\partial u}{\partial t}+u\frac{\partial u}{\partial x}=0,\quad x\in\mathbb{R}, \ t>0$$
with initial condition
$$
u(x,0) = \begin{cases} 1,\quad &x<0\\  -1,\quad &0<x<1\\  0,\quad &x>1 \end{cases}
$$
My solution

To find the equation in the green box would I be correct in saying that because $u$ is constant on the charachteristic curves $\frac{dx}{dt}=u$ i.e
$x=ut+1$ as $x(0)=1$, which implies
$u=\frac{x-1}{t}$?
Comment: You would likely avoid downvotes by typing out at least the problem statement.
Answer: Yes, within the fan (expansion/rarefaction) region $u(x,t)=(x-1)/t$. A simple geometric explanation is that all characteristics there emanate from $(1,0)$, which gives $(x-1)/t$ as their $\Delta x/\Delta t$ slope.
It's important to note that the boundary of the expansion region is complicated. Here is a sketch [with a typo: $(1,1)$ should be $(x=0,t=1)$.]

The curvilinear part of the boundary satisfies the ODE
$$
\frac{dx_b}{dt} = \frac12\left(1+\frac{x_b-1}{t}\right),\qquad x_b(1)=0
$$
fromw where you can find its equation $x_b(t)$ (hint: it's quadratic polynomial).
Comment: Why do the charachteristic lines stop after they cross with a charachteristic emanating from another 'region'? i.e Why do the lines where $u=-1$  carry on beyond their initial cross with there where $u=1$?
Comment: If two characteristic lines crossed, the function $u$ would have two different values there (according to the slope of the lines). [Read about shock waves here](https://www.eng.fsu.edu/~dommelen/pdes/style_a/burgers.html#SECTION00852000000000000000)
Comment: I understand that however normally when we sketch charachterstic diagrams, we sketch the entire line so that each charachteristic line intersects many times, **as in the graph I have added to the OP**. So I am a bit confused. Don't the secondary, tertiary crossings etc. represent shocks also but at a later time?
Comment: I also do not think my solution for the equations for the charachteristics is correct, as if $u$ is constant on each charachteristic, then as all of these chaachteristics emanate from the same point  $u$ will be constant throughout the region which is incorrect.
Comment: On your first, rough, sketch, characteristics line may intersect. But when that happens, you should then understand how the shock forms and propagates, add shock waves to the diagram, and terminate characteristics at the shock. Then you'll have a correct diagram without intersections. See [this answer](http://math.stackexchange.com/a/1203654/) for an example of two-stage process.
Comment: For your second comment: your characteristics are correct. They emanate from a _point of discontinuity_, which is a special situation. The value of $u$ at a discontinuity point is not useful, it's better to ignore it at all. The value of u on each characteristic line is determined by the slope of that line. Again, I strongly recommend you to read up on solutions of Burgers' equation with discontinuous data (as in my link above). If you only dealt with continuous solutions up to now, you are going to make a lot of mistakes applying the same approach to discontinuities.


Retrieving the wrong selected radiobutton in a multi-fragmented viewpager

Question: I'm a long time lurker trying to learn Android coding (with Android Studio). So far I have solved all my issues just by googling them. But now I am really desperate, so I hope someone can help me.
I am trying to code a quiz:
I use a ViewPager to create a number of fragments (here 5). The first fragment (StartView.java) is just some text display with a button to start the quiz. The following fragments all have the same layout, just different questions. So I use only one layout (QuestionView.java and fragment_view1.xml). Each fragment has 5 radio buttons, grouped in a radiogroup. In addition, a button is used to advance to the next fragment. When this button is clicked, the text of the pressed radio button is retrieved and passed back to the main activity.
My Problem in short:
The code runs without error (on my Samsung Galaxy Nexus) but the code does not retrieve the right selected RadioButton. The first QuestionView fragment does give me the value of the selected radiobutton. But for the next QuestionView fragments I am always getting the selected radiobutton from the previous fragment.
A more extended description of the observed behavior:
(A) I run the program and press the start quiz button (on Fragment #0, i.e. the StartView). In the following instance of the QuestionView fragment (F #1), I select a RadioButton, say number 1. When I press the 'next' Button, this number is then printed in the logcat ("Question view - TEXT 1", correct behavior).
(B) So I advance to the next fragment (F #2), I again select a RadioButton, say number 3. But when I press the button, the RadioButton of the previous fragment is printed in the logcat (i.e.: the logcat reads "Question view - TEXT 1", and not number 3.) (C) In the next fragment (F #3), after selecting a radioButton (for example number 5) and pressing the 'next' button, the number from the previous fragment (#2) is printed in the logcat ("Question view - TEXT 3", I expected number 5). So the retrieved number is always the one of the previous fragment.
I hope I described my problem adequately. Please don't hesitate to tell me when I explained it poorly - english is not my native language, and explaining even less:).
Thank you very much, I appreciate your efforts.
Here is the code:
MainActivity.java
public class MainActivity extends FragmentActivity
    implements QuestionView.OnDataPass{

private ViewPager viewPager;
private MyAdapter pageAdapter;
private static final int ITEMS = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (findViewById(R.id.pager) != null) {
        if (savedInstanceState != null) {
            return;
        }
        viewPager = (ViewPager)findViewById(R.id.pager);
        pageAdapter = new MyAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pageAdapter);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

public static class MyAdapter extends FragmentPagerAdapter {
    private Fragment[] tabList = new Fragment[ITEMS];
    public MyAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return ITEMS;
    }

    @Override
    public Fragment getItem(int i) {
        if (tabList[i] != null) {
            return tabList[i];
        } else {
            switch (i) {
                case 0:
                    tabList[0] = StartView.newInstance("Introduction screen");
                    return  tabList[0];
                case 1:
                    tabList[1] = QuestionView.newInstance("Question 1");
                    return tabList[1];
                case 2:
                    tabList[2] = QuestionView.newInstance("Question 2");
                    return tabList[2];
                case 3:
                    tabList[3] = QuestionView.newInstance("Question 3");
                    return tabList[3];
                case 4:
                    tabList[4] = QuestionView.newInstance("Question 4");
                    return tabList[4];
            }
        }
        return null ;
    }
}

@Override
public void WorkData(String data) {
    Log.d("LOG", " Activity - TEXT   " + data);
}}

QuestionView.java
public class QuestionView extends Fragment {

    OnDataPass dataPasser;

    private TextView firstText;
    private Button btn;
    RadioGroup rgOpinion;
    ViewPager viewPager;

    public interface OnDataPass  {
        public void WorkData(String data);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_view1, container, false);
        firstText = (TextView) view.findViewById(R.id.viewOneText);
        firstText.setText(getArguments().getString("msg"));

        btn = (Button) view.findViewById(R.id.viewOneBtn);
        viewPager = (ViewPager) getActivity().findViewById(R.id.pager);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rgOpinion = (RadioGroup) getActivity().findViewById(R.id.radioGroup);
                RadioButton selected = (RadioButton) getActivity().findViewById(rgOpinion.getCheckedRadioButtonId());
                String text = selected.getText().toString();
                Log.d("LOG", " Question view - TEXT  " +text);
                dataPasser.WorkData(text);
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
            }

        });
        return view;
    }

    public static QuestionView newInstance(String text) {
        QuestionView f = new QuestionView();
        Bundle b = new Bundle();
        b.putString("msg", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        dataPasser = (OnDataPass) context;
    }
}

fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width = "fill_parent"
        android:layout_height= "fill_parent"
        android:src="@drawable/hintergrundbild"
        android:scaleType="fitXY"
        android:adjustViewBounds="true">
    </ImageView>

    <Button
        android:background="@drawable/red_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="weiter..."
        android:id="@+id/viewOneBtn"
        style="@style/button_text"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/viewOneText"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentTop="true"
        android:background="#3f51b5"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:text="MY PAGE TITLE"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff" />

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/radioGroup"
        android:layout_alignTop="@id/viewOneText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="53dp">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:id="@+id/radBut1"
            android:layout_above="@+id/radioButtonAnimationMovies"
            android:layout_alignLeft="@+id/radioButtonAnimationMovies"
            android:layout_alignStart="@+id/radioButtonAnimationMovies"
            android:checked="false" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2"
            android:id="@+id/radBut2"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:checked="false" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3"
            android:id="@+id/radBut3"
            android:layout_below="@+id/radioButtonAnimationMovies"
            android:layout_alignLeft="@+id/radioButtonAnimationMovies"
            android:layout_alignStart="@+id/radioButtonAnimationMovies"
            android:checked="false" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="4"
            android:id="@+id/radBut4"
            android:layout_below="@+id/radioButtonHorrorMovies"
            android:layout_alignLeft="@+id/radioButtonHorrorMovies"
            android:layout_alignStart="@+id/radioButtonHorrorMovies"
            android:checked="false" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="5"
            android:id="@+id/radBut5"
            android:layout_below="@+id/radioButtonComedyMovies"
            android:layout_alignLeft="@+id/radioButtonComedyMovies"
            android:layout_alignStart="@+id/radioButtonComedyMovies"
            android:checked="false" />
    </RadioGroup>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/radioGroup"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="449dp"
        android:layout_marginStart="449dp"></FrameLayout>

</RelativeLayout>

Answer: Instead of using getActivity(), which will look for the Id on the whole activity (not just current fragment)
rgOpinion = (RadioGroup) getActivity().findViewById(R.id.radioGroup);
            RadioButton selected = (RadioButton) getActivity().findViewById(rgOpinion.getCheckedRadioButtonId());

Try using the view you have defined previously on onCreateview() like this
rgOpinion = (RadioGroup) view.findViewById(R.id.radioGroup);
            RadioButton selected = (RadioButton) view.findViewById(rgOpinion.getCheckedRadioButtonId());

Comment: Hi Cilvet, thanks for your reply. Your comment explains a lot. So I changed my code and tried it, but I get a NullPointerException in the line `RadioButton selected = (RadioButton) getActivity().findViewById(rgOpinion.getCheckedRadioButtonId());`. But I sense where I am wrong.
Comment: you have to use the second code I posted! not the first one xD sorry I didnt answer earlier. If there is not a checked action button, it will probably crush since you are asking for one, so you have to check first