How to create a discrete representation of a distribution function?

Question: I have a polynomial function representing a distribution function: $x^4 -6x^3 + 9x^2 ; 0 \le x \le 3$ but I need to get a discrete set of $ n $ data points representative of this distribution. I've seen there's many existing code libraries to do this for more standard distributions like binomial and normal, but is there a way I can do this for a given polynomial distribution function?
I had the idea of trying to divide the region into rectangles of equal area, then choosing one value from within each rectangle, but I would not know how to go about solving for each rectangle.
Comment: There are many solutions.  Please tell us what you want to use this "representation" for.  I would guess, from your last paragraph, it might be for computing the percentage point function, but other interpretations are possible.
Comment: My guess is that "many existing code libraries to do this for more standard distributions" you are referring to code like RandomVariate[NormalDistribution[$\mu,\; \sigma$], $n$]; (Mathematica). Please confirm that you are asking for a random variate generating algorithm. Also, @Ben.
Answer: There are a lot of ways to do that. Here is one example that is easy to understand but is not efficient in Mathematica code for n=1000,
<code>testxall = {}; testyall = {}; n = 1;
 While[n <= 1000,
  testx = 3 RandomReal[];
  testy = 5.0625 RandomReal[];
  If[testy <= testx^4 - 6 testx^3 + 9 testx^2,
   testxall = AppendTo[testxall, testx];
   testyall = AppendTo[testyall, testy]; n++]]
lp1 = ListPlot[Transpose[{testxall, testyall}]];
pl1 = Plot[{x^4 - 6 x^3 + 9 x^2, 5.0625}, {x, 0, 3}];
Show[pl1, lp1]
</code>

The answer you asked for is the testxall array. What this does is generate rectangular {x,y} coordinates, and only count those that are less than or equal to the function. Note that the density is more compact in the x direction than in the y direction, but that is irrelevant.
Another, more efficient, way is to randomly generate probabilities, and that would be rather more commonly used.
Comment: How does this answer the question?  What exactly is the **discrete representation** of the distribution that was requested?
Comment: @whuber The reason why I answered the way I did is because that is the way I interpreted the question based on personal experience, i.e., been there done that. Now you are perfectly correct that there is a degree of ambiguity in the question, but even given that I fail to see what a "discrete set of  data points" could be referring to if not how I interpreted the question. Missing is the word "random."
Comment: I agree with Carl that an IID random sample is one reasonable way you could interpret a "discrete representation" of a continuous distribution.  Another reasonable interpretation would be to give deterministic points $x_1,...,x_n$ satisfying $F(x_i) = \tfrac{2i-1}{2n}$ so that you are getting points that are evenly spaced quantiles.  Depending on what you want, one or the other could be better, but I would think that these are reasonable ideas of what people might like when they ask for a "discrete representation" of a continuous distribution.
Comment: @Ben Please see my note to the OP above. I did not consider a possible meaning for evenly spaced quantiles because it did not satisfy "existing code libraries" without stretching the meaning in a way that would be relatively improbable for a relative newbie. I think that it is problematic to ask someone relatively new to statistics to use exact formal language when they do not yet know that language well enough to do so. I get a lot of smiles when I fill in the blanks.


Reporting quartiles in bar plots

Question: I have some non parametric data and my supervisor wants me to use bar plots to visualise it. He said because I'm using the median, that my error bars should be the 1st and 3rd quartiles....I get that and have done it....my issue is how to report ithat in the figure ledgend....do I  just report it as I would for  a box plot, i.e "bar plot shows 1st quartiles, 3rd quartile and median".  I would rather use box plots but supervisor wants me to stick to bar plots. Advice most welcome.
Comment: Most boxplots already display the median and the quartiles.  Thus, your supervisor's request amounts to asking you to erase the whiskers and outlier points.  I suppose that could make sense if the latter were numerous and distracting, but in any case it ought to raise objections in readers' minds: they will wonder what you are trying to hide.
Comment: My issue isn't about displaying the median and quartiles...it's how to report them in the figure legend. Im also not using boxplots, im using bar plots/graphs. If it was mean, I would report the SE or SD in text in the figure legend, but I'm using median and so unsure of how to report it in the text of the figure legend.
Comment: I don't follow, because you seem to be making a distinction between a boxplot and ... boxplots.  Most boxplots don't report that stuff in the legend because that is part of the construction of a boxplot.  If they did, they would call quantities by their standard names: they would say "this is the symbol for the median, these are the symbols for the quartiles."
Comment: No, I'm talking about using a bar graph instead of a box plots,  which is what my supervisor wants me to do.
Comment: I'm having to use the median because the data is not normally distributed. My supervisor wants me used bar graphs to visualise the data and has said because I'm using the median, my error bars will essentially be the quartiles.
Comment: Unfortunately, although your supervisor is right about the general approach, s/he may be incorrect about using quartiles.  For correct error bars for medians (or any quantile), please see http://stats.stackexchange.com/questions/122001, which (a) shows you should be using order statistics and (b) provides the theory describing which ones to use.  You can look those order statistics up in tables appearing in books like Hahn & Meeker's *Statistical Intervals.*
Comment: What's "nonparametric data"? If you mean "not normally distributed" that's not at all the same thing as "nonparametric" and similarly "parametric" is not at all the same thing as "normally distributed" -- one can fit parametric non-normal models and correspondingly, one can happily use nonparametric procedures on data drawn from normal distributions. Please amend your post to more clearly express the actual situation.
Comment: As a matter of general principle, a barplot is suitable for displaying counts or proportions in unordered categories. It's not really an ideal way to represent means or medians. (I guess you probably already understand that, though)
Answer: Who says you can't use the mean?
Your data are not from a normal distribution but that doesn't imply that you can't use the mean. For example, if I was looking at count data (which is certainly non-normal) I wouldn't usually have any issue at all with using the mean. As another example, if I was recording (say) waiting times, which tend to be roughly exponentially distributed (i.e. reasonably but not highly skew), I would also not have any problem using the mean. If the mean measures what I am interested in it might easily be a completely sensible thing to report.

I've already explained that I don't think this is a suitable display in a comment, but since that's not the question here I won't address it at length. Let's just for the moment take your display as a given, leaving aside other issues (except in passing).
I presume you're trying to go from something like (A) to something like (B):

In that case, I wouldn't call those "error bars" error bars because they don't represent error -- they're not measurement error and they're not standard errors of medians ... they're just an indication of the dispersion in the measurements.  (Note that whuber gives some useful information in comments if you do want to get a standard error of the median)
Your suggestion was reporting in your legend "bar plot shows 1st quartile, 3rd quartile and median"; I think it should be clear enough from that what you did so that should be fine as far as it goes. If I was writing text I'd be inclined to say something like "the top of the blue bar shows the median, the ends of the interval around it (marked in black) shows the upper and lower quartiles". Perhaps better still to my mind would be to have an inset box-legend in the plot conveying the information:

... though to some extent it will depend on what the standards are where you publish.
Comment: This is exactly what I am also searching for @Glen_b -Reinstate Monica
Could you please refer me to some sources on how could I do that kind of plot? Thanks
Comment: It's a variant of a dynamite plot; many packages can make a plot something like it (though I think it's a [poor choice](https://simplystatistics.org/2019/02/21/dynamite-plots-must-die/), for all that it's popular in some areas -- but some improvements can be made). I don't recall making that one, but apparently I did it in R (which would be easy enough right from the plotting tools that come built-with R but for which there is likely several packages to choose from as well, which will automate the process more).  You should be able to find more with a few searches (here & on the internet).

Reporting quartiles in bar plots


Como mostrar dados de um db em 3 fragments tabbed?

Question: Como mostrar os dados obtidos de um banco de dados em uma tab com 3 fragments. Eu já consigo obter os dados na activity que está a tab. Minha dificuldade está em jogar esses dados em controles que estão dispostos nos 3 fragment.
MainActivity
public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

    Button b= (Button) findViewById(R.id.btnClick);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Frag1 f1= new Frag1();
            Bundle bundle = new Bundle();
            bundle.putString("name", "Marcelo");
            f1.setArguments(bundle);

        }
    });

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment=null;
        switch (position){

            case 0:
                fragment=  new Frag1();
                break;

            case 1:
                fragment= new Frag2();
                break;

            case 2:
                fragment= new Frag3();
                break;
        }

        return fragment;
    }

    @Override
    public int getCount() {

        return 3;
    }

}

Fragment
public class Frag1 extends Fragment {
public TextView t1;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.frag1_layout, container, false);
    t1 = (TextView) v.findViewById(R.id.txtFinal1);

    return v;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Bundle bundle = getArguments();

    if (bundle != null)
    {

        String link = bundle.getString("name");
        t1.setText(link);

    }
    else{Log.d("TagStart","Nulo");}

}

O button da activity envia os dados para mostrar no TextView do fragment mas nada acontece. Nemhum erro acontece também.
Comment: Bem-vindo ao StackOverflow. Por favor, poste um trecho do código que você já tem para termos uma ideia melhor do problema, sugiro que leia esse artigo da ajuda do site: [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Comment: Obrigado pela dica Pedro Gaspar. Sou novato por aqui Já postei com o trecho do código.
Answer: Resolvido. Neste exemplo eu pego os dados de um DB do Azure e distribuo em 2 fragments tabbed. Um com os dados pessoais e no outro com enderço.
MainActivity
public class MainActivity extends AppCompatActivity  {

private MobileServiceClient mClient;
private MobileServiceTable<cadastroTable> mCadastroTable;
private CadastroTableAdapter mCadastroAdapter;
private Toolbar mToolbar;
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private String codigo,nome,endereco,bairro,cidade,estado;
private ArrayAdapter<String> listAdapter;
private TabLayout tabLayout;
public  Bundle bundle = new Bundle();

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

    mToolbar = (Toolbar) findViewById(R.id.tb_main);
    mToolbar.setTitle("");
    setSupportActionBar(mToolbar);

    try {

        mClient = new MobileServiceClient(
                "https://contaazure.azurewebsites.net",
                this));

        mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() {
            @Override
            public OkHttpClient createOkHttpClient() {
                OkHttpClient client = new OkHttpClient();
                client.setReadTimeout(20, TimeUnit.SECONDS);
                client.setWriteTimeout(20, TimeUnit.SECONDS);
                return client;
            }
        });

        mCadastroTable = mClient.getTable(cadastroTable.class);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.stl_tabs);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

        mSectionsPagerAdapter.getItem(0);

    } catch (MalformedURLException e) {
        createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
    } catch (Exception e) {
        createAndShowDialog(e, "Error");
    }

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        android.support.v4.app.Fragment fragment=null;

        switch (position){

            case 0:
                fragment=  new PessoalFragment();
                Bundle bundle = new Bundle();
                bundle.putString("nome",nome);
                bundle.putString("codigo",codigo);

                fragment.setArguments(bundle);

                break;

            case 1:
                fragment= new LocalizacaoFragment();
                Bundle bundle1 = new Bundle();
                bundle1.putString("endereco",endereco);
                bundle1.putString("bairro",bairro);
                bundle1.putString("cidade",cidade);
                bundle1.putString("estado",estado);

                fragment.setArguments(bundle1);

                break;

        }

        return fragment;
    }

    @Override
    public int getCount() {

        return 2;
    }

}

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

public  void refreshCadastroTable() {

      /// Aqui eu pego no DB do Azure os campos que serão que vão nas
      /// variáveis do bundle

}

private void createAndShowDialogFromTask(final Exception exception, String title) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            createAndShowDialog(exception, "Error");
        }
    });
}

private void createAndShowDialog(Exception exception, String title) {
    Throwable ex = exception;
    if(exception.getCause() != null){
        ex = exception.getCause();
    }
    createAndShowDialog(ex.getMessage(), title);
}

private void createAndShowDialog(final String message, final String title) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage(message);
    builder.setTitle(title);
    builder.create().show();
}

Nos fragments
PessoalFragment
public class PessoalFragment extends Fragment  {

private EditText edt_cdigo, edt_nome;
public  String _codigo, _nome, ;
public Bundle bundle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_pessoal, container, false);

     edt_codigo = (EdiText) getActivity().findViewById(R.id.codigo);
     edt_nome = (EditText) view.findViewById(R.id.nome);

    return view;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    bundle= getArguments();

    _codigo = bundle.getString("codigo");
    _nome = bundle.getString("nome");

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (bundle != null) {

        edt_codigo.setText(_codigo);
        edt_nome.setText(_nome);

    }

}

LocalizacaoFragment
public class LocalizacaoFragment extends Fragment  {

private EditText edt_endereco, edt_bairro, edt_cidade, edt_estado;
public  String _endereco, _bairro, _cidade, _estado ;
public Bundle bundle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_localizacao, container, false);

     edt_endereco = (EdiText) getActivity().findViewById(R.id.endereco);
     edt_bairro = (EditText) view.findViewById(R.id.bairro);
     edt_cidade = (EdiText) getActivity().findViewById(R.id.cidade);
     edt_estado = (EditText) view.findViewById(R.id.estado);

    return view;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    bundle= getArguments();

    _endereco = bundle.getString("endereco");
    _bairro = bundle.getString("bairro");
    _cidade = bundle.getString("cidade");
    _estado = bundle.getString("estado");

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (bundle != null) {

        edt_endereco.setText(_endereco);
        edt_bairro.setText(_bairro);
        edt_cidade.setText(_cidade);
        edt_estado.setText(_estado);

    }

}

Obrigado Lucas Pugliese pela ajuda.
Answer: Oh SectionsPagerAdapter tem um Frag1, mas em nenhum momento você atribui o Bundle a ele. Você na verdade está criando um Frag1 novo dentro do OnClick do botão.
Uma outra coisa que você tem que observar é o ciclo de vida da activity e do fragment, porque o clique do botão está acontecendo depois do onActivityCreated e nesse momento o Bundle sempre será null

Nesse seu caso em específico eu acredito que a melhor abordagem seria você criar um método SetText() no seu Fragment, criar um GetFragment() dentro do adapter para acessar o mesmo da Activity e simplesmente chamar o SetText() dentro do OnClick.
Comment: Obrigado!!! Era isso mesmo. **Oh SectionsPagerAdapter tem um Frag1, mas em nenhum momento você atribui o Bundle a ele**. Erro de iniciante como eu.
Comment: Posta como ficou o resultado final e vota na resposta. Obrigado por dar retorno ^^


Copy two elements from uint8_t array into uint16_t variable using pointers

Question: I have a uint8_t array. I sometimes need to treat two sequential elements as uint16_t, and copy them into another uint16_t variable. The elements may not necessarily start on a uint16_t word boundary.
At present I'm using memcpy to do so:
uint8_t bytes[] = { 0x1A, 0x2B, 0x3C, 0x4D };
uint16_t word = 0;
memcpy(&word, &bytes[1], sizeof(word));

gdb shows this works as expected:
(gdb) x/2bx &word
0x7fffffffe2e2: 0x2b    0x3c

Casting a reference to an array element to uint16_t causes only the array element being directly referenced to be copied:
word = (uint16_t)bytes[1];

(gdb) x/2bx &word
0x7fffffffe2e2: 0x2b    0x00

Using a uint16_t pointer and pointing it at an array element address cast to uint16_t * results in two sequential elements being referenced, but not copied:
uint16_t *wordp = (uint16_t *)&bytes[1];

(gdb) x/2bx wordp
0x7fffffffe2e5: 0x2b    0x3c

bytes[1] = 0x5E;

(gdb) x/2bx wordp
0x7fffffffe2e5: 0x5e    0x3c

Assigning a regular uint16_t variable the value dereferenced from the uint16_t pointer copies both sequential array elements:
word = *wordp;
bytes[1] = 0x6F;

(gdb) x/2bx wordp
0x7fffffffe2e5: 0x6f    0x3c
(gdb) x/2bx &word
0x7fffffffe2e2: 0x5e    0x3c

gcc produces no warnings when using the -Wall option.
How can I achieve the same result without the intermediate pointer?
Are there any concerns with using a pointer as described above, or with attempting to do so without the intermediate pointer?
Would using memcpy be considered preferable under certain scenarios?
The ultimate use of this is processing a Big Endian byte stream, so I'm using byteorder(3) functions as appropriate.
Comment: `memcpy` is considered preferable due to the strict aliasing rule. Another option is to shift and OR to create the `uint16_t`. That eliminates the endianness problems as well.
Comment: Is there any reason why you don't want to use the `memcpy` version? It's the safest in terms of avoiding *undefined behavior* and I'd expect any decent optimizer to optimize out copies if possible
Comment: There's no particular reason for not wanting to use `memcpy`; it's what I'm using in 99% of cases. I originally used shift and OR, but replaced it with `memcpy`.  Then I noticed chained uses of `memcpy` across chained function calls, and the doubt set in. I think I'm aware of the options, I just don't feel I have enough experience to compare them and evaluate which I should use and why.
Comment: It's worth noting that compiler optimizers which see a constant `2` as the size for a `memcpy` call will nearly always rewrite to involve no function call or loop at all, and just manipulate bytes using registers. The cost of that is then extremely negligible, no worry about function overhead or unnecessary memory access outside the caches.
Answer: uint8_t bytes[] = { 0x1A, 0x2B, 0x3C, 0x4D };
uint16_t word = 0;
memcpy(&word, &bytes[1], sizeof(word));

The above is good.  Copies the bytes directly.  If you are happy to copy the bytes over in order and not concerned about endianness, this is the way to do it.
See P__J supports women in Poland's answer for the proof that compilers are smart enough to optimize this usage so you don't have to worry about optimizing it youself.
word = (uint16_t)bytes[1];

The above simply zero-extends your 8-bit value into a 16-bit value (0x002B instead of 0x2B); presumably not what you want.
uint16_t *wordp = (uint16_t *)&bytes[1];
word = *wordp;

Do not do the above.  That results in undefined behavior.  A uint16_t has stricter alignment requirements than a uint8_t, and you can get an invalid address for the pointer type.  That is, being a two-byte data type, it requires addresses that exist on multiple-of-two boundaries (so 0x2, 0x4, 0x6, etc.) while uint8_t doesn't have such a restriction and can exist at 0x1, 0x2, 0x3, etc..  (See section 6.2.8 of C11 Working Draft for more on alignment)
Upon dereferencing it, you have also broken the strict aliasing rule by dereferencing an object with an incompatible type. (See section 6.2.7 of C11 Working Draft for more on compatible types)
Comment: Thanks Christian. In response to your statement on endianness. It depends on what I'm doing with the data. For situations where I care about the endianness I am using `ntohs()` to convert the bytes after copying them into the `uint16_t` variable.
Comment: Could you also please explain further about the strict alignment requirements, and how I could end up with an invalid address? Is there some way to get gcc to warn me? Or is the cast me firmly telling it I'm happy to shoot myself in the foot?
Comment: Updated with a bit more on alignment and strict aliasing.
Answer: memcpy is the safest way. And using modern compilers the most efficient as memcpy will not be called.
Example (volatile to orevent optimizations):
#include <stdint.h>
#include <string.h>

int main()
{
    volatile uint8_t bytes[4];
    volatile uint16_t word = 0;
    memcpy(&word, &bytes[1], sizeof(word));
}

and the memcpy is translated to
        movzx   eax, WORD PTR [rsp-3]
        mov     WORD PTR [rsp-6], ax

https://godbolt.org/z/57n879


standalone rsync and ssh work, but drush gets me a "Permission denied (publickey)"

Question: I've got a production site (on shared hosting for now) of which I just want to have backups at this stage. and I've got a backup instance which I want to overwrite with the prod site.
This is my /etc/drush/aliases.drushrc.php:
<?php
$aliases['bak'] = array(
        'root' => '/var/www/',
        'uri' => 'testvm',
        'db-url' => 'mysql://user:pass@localhost/drupal',
        'path-aliases' => array(
        '%dump' => '/var/bak.sql',
        '%files' => '/var/drupal_files',
      )
);

$aliases['prod'] = array(
        'root' => 'livesite.com:/home1/ruser/public_html/',
        'uri' => 'livesite.com',
        'db-url' => 'mysql://ruser:pass@localhost/drupal_drp3',
        'remote-user' => 'ruser',
        'path-aliases' => array(
        '%dump' => '/home1/ruser/prod.sql',
        '%files' => '/home1/ruser/drupal_files',
      )
);
?>

And all I'm getting through drush is:
Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: error in rsync protocol data stream (code 12) at io.c(605) [Receiver=3.0.9]
Could not rsync from livesite.com:/home1/ruser/public_html// to /var/www/        [error]

Even though I can rsync/ssh/scp with no issue to and from the live site. Certificates are in place, and working fine, but not for drush...
What I'm not seeing here???
PS I've seen What could cause remote drush commands to fail with ssh errors when ssh works in all other cases?, but the accepted answer does not make any difference for me.
Update:
I was using drush as root, so I tried creating a local user with same name as the remote user. I chowned the backup instance to the remote user.
ruser@drupal:~/.drush$ drush -v rsync @prod @bak
$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/ruser/.ssh/id_rsa';

Loaded alias @prod from file /etc/drush/aliases.drushrc.php [notice]

Loaded alias @bak from file /etc/drush/aliases.drushrc.php [notice]
You will destroy data from /var/www/ and replace with data from livesite.com:/home1/ruser/public_html//
Do you really want to continue? (y/n): y
Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="settings.php" --stats --progress livesite.com:/home1/ruser/public_html// /var/www/);
receiving incremental file list
rsync: failed to set permissions on "/var/www/.": Operation not permitted (1)
rsync: failed to set permissions on "/var/www/.htaccess": Operation not permitted (1)
./

Number of files: 14547
Number of files transferred: 0
Total file size: 92209263 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 313420
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 1017
Total bytes received: 316801

sent 1017 bytes  received 316801 bytes  42375.73 bytes/sec
total size is 92209263  speedup is 290.13
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1536) [generator=3.0.9]
Could not rsync from livesite.com:/home1/ruser/public_html// to /var/www/ [error]
Command dispatch complete

This user has certificates in place in the live site as well. But still no luck...
Comment: The answer you quote above should do the trick for you.  Run drush with the -s (simulate) flag to see exactly what shell commands Drush is using.  That should help you figure out why Drush is failing; once you get that far, post again if you can't figure out how to get Drush to emit the parameters you need for your configuration.
Answer: You are not specifying a remote-user on @bak so who are you performing operations as on the server at @bak? You are also not specifying any ssh config options. In this case, you are asking @bak to authenticate with @prod via ssh/rsync but you are not using agent forwarding so @prod can't see your private key. Try specifying something like
'remote-user' => 'user_on_bak',
'ssh-options' => '-T',

So that drush will execute as 'user_on_bak' and ssh will pass along your local key to @bak so when it opens a session with @prod it will have a key to pass along.
Comment: almost to the day, 2 years after posted :) The site does not even exist any longer, so can't really test, but sounds like common sense to me. thanks!
Answer: I would like to see what the permissions on /var/www and /var/www/.htaccess are.  try:

ls -l /var/www /var/www/.htaccess

they should be writable.  You should be able to:

touch /var/www/anewfile; touch /var/www/.htaccess

if you can't, then your local ruser user does not have permissions to those files.

sudo chown -R ruser:ruser /var/www

to change ownership of all files under /var/www


Excel VBA: nome do objeto (Label) na célula

Question: No excel, Tenho um botão no formulário, que vai mudar o caption de um label no mesmo formulário. Porém, tenho 22 labels nesse formulário. Qual label quero que a ação seja executada é variável e está definido numa célula a planilha.
<code>Dim LabelAtual As string:   LabelAtual = Range("A10").Value              'O valor na A10 é "LBL7" = o nome do label para editar.

Me.LabelAtual.Object = "Maria Carolina"
</code>
Não funciona, não está entendendo que LabelAtual é, nesse momento, LBL7. Talvez não seja string? Se alguém puder ajudar, desde já obrigado.
Comment: Da forma que eu fiz abaixo funcionou no meu excel.
Comment: O código que você coloca está no próprio form, ou está em um módulo separado?
Comment: Tente o seguinte: `LabelAtual = Me.Controls(Range("A10").Value)`. Diga se funcionou.
Answer: Para fazer isso basta inserir o código abaixo depois abrir um formulario (UserForm1), com um Botão (CommandButton1) e depois um Rotulo (Label1). Depois é só clicar duas vezes no Botão e inserir todo codigo abaixo:
<code>   Private Sub CommandButton1_Click()

     Dim LabelAtual As String:   LabelAtual = Range("A10").Value

     Label1.Caption = LabelAtual

   End Sub
</code>
Depois de executar é só clicar no Botão que o Rótulo (Label1) assume o valor que estiver na célula A10;


Do I need to go to music school to become a good composer?

Question: I love music. I play the piano and know the basics of orchestration. I also know how to manage the computer programs required to make music.
Unfortunately, (or fortunately) I have many other interests. And observing how my life is going so far, I do not think I will go to music school (I'm about to graduate from school.)
Most likely, I will end up studying philosophy or something similar. But as stated earlier, I love music, and I don't want to drop it. I want to learn how to compose orchestral music like the masters, but I just don't have the time to invest in a complete musical career.
Can I do this even without formally studying music?
Comment: If you have the _hunger_ then you'll make it happen. Otherwise not. There's that line in Donald Fagen's New Frontier where he sings "…Till I finally make up my mind
To learn design and study overseas"
Comment: To "compose like the masters" you have to put in a lot of time. Even if you don't attend music school, this still applies. Not attending music school is not a shortcut (in fact, studying on your own will probably be less efficient – as Gary mentions).
Comment: Is your main goal to become a good composer or a good **orchestrator**?
Comment: @Dekkadeci It would be amazing to be both
Answer: I like to think one can compose music, songs, jingles, etc. without "formal" training, but ...
There is so much to each of the arts that it takes a mysterious and marvelous mental and emotional facilities to produce a decent creation (that has anything extra above the commonplace work) in any art. This includes music. There is always a possibility of genius so there is no telling when and where it will appear. You might have it, or it could just pop up as you begin to "do" music.
Training, schooling, and studying on your own are always helpful, though. And then practice, practice, practice, is usually needed, and can become a fun part of your life.
Being in a school setting (for the arts) gives you a better chance, however, for many reasons. First is learning the discipline you will almost surely need. Then there is being with others, interacting with them, and being inspired by what you see and hear, and developing your tastes of what to try and what to avoid.
You will be exposed to working with others and seeing what you can easily do to work with them, and discover areas you will have to study and develop for your own work. You may get chances to do things you need materials and help to try and understand.
For example, I played the piano, but got the chance to (some would say "had to") play trumpet, violin, guitar, clarinet, flute, and some other "things," all of them not very well. Without having to commit to any of these instruments, I still learned about them and what they are capable of. It is a great help (or was to me) to feel comfortable about writing for them.
So, depending on how well you can soak up experience on your own, I'd still suggest you sample some formal training in a music education setting. I was in a university that had a conservatory so I could take Music School courses while I was still a major in mathematics and philosophy. I feel like it saved me ten years of study on my own in one year of study in the conservatory.
Good luck to you, whatever you do, and enjoy the music!
Answer: I agree with Gary and would just add that for me, as a composer, the most fantastic thing about music college was having an orchestra you were encouraged to write for. Mixing with other musicians was important too: finding out what's possible on a harp, which trills are best avoided on bassoons and why you should never smile encouragingly at the brass.
Almost as important were composition tutorials, then harmony and counterpoint ones, then ear-training and improvisation classes, and lastly figured bass, over which I draw a veil.
BUT
There are websites where brass players demonstrate the different mutes, bassoonists show you how they flick and guitarists explain flat finger tunings. When I was a student, scores were extremely expensive. Now there are out-of-copyright ones you can download free, and YouTube clips showing the score as the music plays. And scores are also cheaper to buy. Norman DelMar's Anatomy of the Orchestra is full of useful practical information and there are plenty of books on orchestration. Piston's is wonderful, if a bit dated.
There are online courses in harmony and counterpoint, but choose carefully. This forum sees some very misleading examples. Ask a composer to be your tutor. You will need one. Get him/her to criticize everything you write. (I'm too old to use the cowardly upstart 'critique'!)
It's good that you're handy with the technology. Most composers prepare their scores in Sibelius, as you probably know. And of course film composers need to be able to synch to picture using something like Cubase.
Most Russian composers studied and worked in some other field than music, so it can be done. Though it helps if your parents are aristocrats. Any chance?
Comment: "Though it helps if your parents are aristocrats. Any chance?" Hahaha, no chance. :)
Comment: "and why you should never smile encouragingly at the brass" • OT, but… do tell!
Comment: Two pieces of advice to conductors are attributed to Richard Strauss: "Never smile encouragingly at the brass." and "The left thumb must never leave the waistcoat pocket." When I was a student - ages ago! - these were well known. Somehow the first quote has become corrupted into the less funny "Never *look* encouragingly..." The original source was, I think, the conductor Maurice Miles, who, I think, had studied under Strauss (https://www.gettyimages.co.uk/detail/news-photo/composer-richard-strauss-in-front-of-the-mozarteum-salzburg-news-photo/143112563) at the Mozarteum in Salzberg.
Comment: @Old Brixtonian: Perhaps because you don't want the brass to smile back?
Comment: Oops! SalzBURG, not -berg.


Select Option não busca ou não grava o valor selecionado pelo usuário

Question: Estou tentando pegar o valor selecionado pelo usuário em uma option faz dias e não tem jeito não estou conseguindo uso duas tabelas uma chamada contato e outra situação, na situação tenho os valores esperando, andamento e concluído.
Faço uma busca nesta tabela com fecth_array até ai tudo bem porém quando eu seleciono umas das opções não estou sabendo gravar e enviar a variável para a tabela contato. Peço ajuda de vocês pois já estou neste dilema a dias um
Obs.: Quando clico no botão alterar não esta enviando a variável que o usuário selecionou e sim o ultimo item do array que é concluído então mesmo que eu escolha andamento esta levando a variável concluído.
echo'<select name="sitprot" id="sitprot">';
$sql="select * from situacao"; // neste permite  mostrar e alterar e as opções para ser gravado no banco.
$resultado2=mysql_query($sql);
while($dados1=mysql_fetch_array($resultado2)){
    $marca1=$dados1['situ'];
    echo "<option value='$marca1'>$marca1</option>";
    echo $marca1;
}
echo '</select> ';
echo 'Alterar	';

Comment: Se está iniciando no PHP comece não usando as funções mysql_*, [Por que não devemos usar funções do tipo mysql_*?](http://pt.stackoverflow.com/q/579/91). vc faze envio pelo link? ou tem mais algum código ai?
Comment: obrigado pela dica das funções mudarei para PDO ou msqli como sugestionado , sim uso o link mesmo passando as variaveis id e situ como mostra na ultima linha .
Comment: Tem um outro while dentro desse?
Comment: Leonardo,  ou vc usa um form e um botão para fazer um submit, ou faz como o KaduAmaral fez na resposta dele.  Com form e um botão de submit seria um pouco mais simples.
Answer: Isso acontece porque o while ficou alterando a variável $marca1 durante todo o loop, quando terminou a variável ficou com o último valor do loop, exemplo:
$i = 0;
while($i++ < 10){
   $marca = $i;
}

echo $marca; // Resultado: 9 - último valor dentro do while

Então, você tem que pegar o valor do option com Javascript:

<select name="sitprot" id="sitprot">
  <option value="1">Valor 1</option>
  <option value="2">Valor 2</option>
  <option value="3">Valor 3</option>
  <option value="4">Valor 4</option>
</select>
Alterar

Obs.: Notei que sua variável $info[id] está sem aspas, sempre use aspas (simples) em array associativos, exemplo: $info['id'].
Answer: Obrigado Primeiramente pelo apoio bom
Abaixo coloquei o seu codigo dentro do php então usei echo
echo '';
  echo 'Valor 1';
  echo 'Valor 2';
  echo ' Valor 3';
  echo  'Valor 4';
  echo ' ';
  echo 'Alterar';
depois coloquei dentro das tags head html o script

  document.getElementById('alterar').addEventListener('click', function(event){
   event.preventDefault();
  var valor = document.getElementById('sitprot').value;
  var link = 'status1.php?id=&situ='+valor;
  alert(valor);
  alert(link);
  //document.location.href = link;
});
não deu erro , porém quando clico em alterar e parece não entrar no script e não mostrar o alert

<select name="sitprot" id="sitprot">
  <option value="1">Valor 1</option>
  <option value="2">Valor 2</option>
  <option value="3">Valor 3</option>
  <option value="4">Valor 4</option>
</select>
Alterar

Answer: Existem dois tipos de ciclo de vida de uma aplicação web:

Lado do servidor
Lado do cliente

Como você quer que o link para a alteração receba um valor que muda de acordo com a sua manipulação da aplicação no Lado Cliente (no browser), você deve usar Javascript para alterar o href do link e não PHP, ao menos na parte que tem a ver com o fator Situação.
O código já está disponível nas outras respostas, então vou deixar uma resposta usando jQuery, abaixo:

$(function () {

  $('#link').click(function (e) {
    e.preventDefault();
    var situ = $('#sitprot option:selected').val();
    var id = /*<?php echo (int)$info['id']; ?>;*/ 1;
    var newUrl = 'status1.php?id=' + id + '&situ=' + situ;
    if (situ != 0)
      /*location.href = newUrl;*/alert('redireciona para ' + newUrl);
    else
      alert('selecione situação, por favor');
  });

});

<form id='f' name='f'>
  <select id='sitprot' name='sitprot'>
    <option value='0'>[selecione um valor]</option>
    <option>esperando</option>
    <option>andamento</option>
    <option>concluído</option>
  </select>
</form>

Alterar
Answer: Verifique se funciona, substituindo echo "<option value='$marca1'>$marca1</option>"; por
echo "<option value='{$marca1}'>{$marca1}</option>";
Comment: tentei porém deu na mesma coisa se estivesse usando o meu option obrigado


Prove by definition that $\frac{1-2n^3}{4n^3-2n^2-1} \to -\frac12$

Question: $a_n = \dfrac{1-2n^3}{4n^3-2n^2-1}$
My attempt (of the scratch):
$\left| \dfrac{1-2n^3}{4n^3-2n^2-1} + \dfrac{1}{2}\right|=\left| \dfrac{2-4n^3+4n^3-2n^2-1}{8n^3-4n^2-2}\right|=\left|\dfrac{-2n^2+1}{8n^3-4n^2-2} \right|=\dfrac{2n^2-1}{8n^3-4n^2-2}<\dfrac{2n^2}{8n^3-4n^2-2}=\dfrac{n^2}{4n^3-2n^2-1}<\epsilon$
But I don't know what to do next to choose my $N \in \Bbb{N}$
Answer: For large $n$, we have $4n^3 - 2n^2 - 1 > n^3$, in which case $\frac{n^2}{4n^3-2n^2-1} < \frac{n^2}{n^3} = \frac{1}{n}$.
Answer: Let $N \in \mathbb{N}$ s.t. $4N-2>n'+\delta$ for $n' \in \mathbb{N}$ and $\delta >0$, then $n \geq N$ implies $4n-2 \geq 4N-2 > n'+\delta$.
Let $N' \in \mathbb{N}$ s.t. $\frac{1}{N'^2}< \delta$ for $\delta >0$, then $n\geq N'$ implies $\frac{1}{n^2} \leq \frac{1}{N'^2} < \delta$.
If $n \geq \text{max}\{N, N'\}$ then $4n-2-\frac{1}{n^2} > n'+ \delta - \delta= n'$ and $\frac{n^2}{4n^3 -2n^2 -1} =\frac{1}{4n-2-\frac{1}{n^2}}<\frac{1}{n'}.$
Let $n'$ be such that $\frac{1}{n'}<\epsilon$.


Symfony forms: does it omits a `false` `attr`?

Question: I want to know in JavaScript if a particular feature is active or not.
I have a PHP class that has some has* methods.
So, in Twig I do this:
{{ form_widget(form.plan.seo, {'attr': {'class': 'feature', 'data-already-active': store.premium.hasSeo}}) }}

I expect it sets data-already-active to 0 or to 1 depending on the feature is active or not.
But the generated HTML is this if the has* method returns true:
<input type="checkbox" id="form_plan_seo" name="form[plan][seo]" class="feature" data-already-active="data-already-active" value="1" checked="checked">

while simply omits the data-already-active attribute if the has* method returns false:
<input type="checkbox" id="form_plan_social" name="form[plan][social]" class="feature" value="1">

More, has you can see, the value of the attribute data-already-active is not 0 or 1 nor true or false but is the name of the attribute itself:
data-already-active="data-already-active"

Is this normal? Have I a better way of setting this information in the checkbox?
Answer: Yep, that seems to be the normal behavior for assigning boolean values for the twig attrs values. An easy workaround would be to modify the code a bit:
{{ form_widget(form.plan.seo, {'attr': {'class': 'feature', 'data-already-active': store.premium.hasSeo ? "1" : "0"}}) }}

or if you want to have this working with your current twig definition you can also move this boolean to string logic into the form template.
Comment: I think the use of a ternary op is the easiest and most practice one in this use case. Thank you!


Delegation vs exposing properties

Question: i was looking at facade-like delegation in classes, for example let's suppose that you got the Equipment class ( with Equip() and UnEquip()  methods), and then you have a Player class which has a reference to the Equipment.
The way i would implement the Player class is to have some public methods like EquipItem and UnEquipItem, and those methods will delegate the tasks to the Equipment class. Now if the player also has another class that does stuff, like movement, then i would put again some public methods on the Player class that delegates to the Movement class, in a facade-like way. Now one of the disadvantages of the facade pattern is the growing interface the more classes or systems it handles. And let's suppose that i know that in the future, the Player class will have alot more functionality.
I don't know if this is the correct approach, nonetheless i was thinking if it would be possible to expose the Equipment and Movement references as properties, like so:
Class Player
{
     public Equipment equipment { get; set; }
     public Movement movement { get; set; }
}

Now, i know that exposing the object's state is bad, but this way you have a better control of the growing interface of the class, and have more focused methods on the Player class. So instead of:
player.Equip();

you can do
player.equipment.Equip();

Sooo finally, my question would be what is the best approach in this scenario, or maybe i got something wrong ?. Thanks
PS: the example is from a game area, but the solution doesn't have to be necessarily applicable to games, i just thought it was simple to understand.
Comment: Note that properties don't technically expose state, they are just methods (like getX/setX methods in other languages).
Comment: the class is not `static` so where are you actuall instantiating an instance of the `Player` Class..? read up on [C# Basics Tutorials](http://www.tutorialspoint.com/csharp/csharp_classes.htm)
Comment: Personally, i'd go about this in a totally different approach. I wouldn't have `Movement` as part of the players properties, but perhaps have a `Game` class, which would be responsible for the movement of players in the game.
Comment: @MathodMan Oh sorry, the class isn't static just for demostration purposes, i just wanted to express the idea with as little code as possible so it was easier to understand
Comment: @YuvalItzchakov you are right, but note that i wasn't expecting a correct solution on the game thing, what i tried to convery was what would you do in a situation where your public interface would grow quit a bit. And how would you go about accesing it.
Answer: An alternate approach would be to develop a set of command actions that can be applied to the player which manipulate the state.  While the command objects would have extended access to the player, the outer API would keep the implementation details as a black box.
As an example:
public abstract class Action
{
   public abstract void ActOn(Player player);
}

public class EquipAction : Action
{
    private Item item;
    public EquipCommand(Item item) {
      this.item = item;
    }

    public void ActOn(Player player) {
       player.Equipment.Add(item);
    }
}

public interface IPlayer
{
    void PerformAction(Action action);
}

public class EquipmentSet
{
    public List<Item> Items { get; private set;}
}

public class EquipmentManager
{
    public Add(Item item) {
    }

    public List<Item> Items { get; }
}

public class Player : IPlayer
{
    public EquipmentManager manager;

    public PerformAction(Action action) {
       action.ActOn(this);
    }

    public List<Items> Equipment {
       return manager.Items;
    }
}

Now obviously, there's a lot more that should be done to make this fully capable to do what you want, but the idea would be to limit your public interface to player to the structure that you want to expose (e.g. attributes, equipment, status, .etc) and delegate all the verbs to actions.
Under the covers, the actual functionality of a Player could be broken up into as many components as would make sense to limit the size of each individual components.
Comment: interesting, so instead of the objects acting directly on the player, you access it inderectly throught commands ( and you still decided to expose the property to access the class instance). The only thing that worries me is that this way you would have to make one class per different command ( for example one for Equip() and one or Unequip(), is that correct ? ). So would this be a problem escalating to a lot of commands ? would it be acceptable to manage a mid-large quantity?
Comment: While you could have a large number of commands in the system, if you take the time to group them logically it will be easier to keep track of the individual commands than a large API on one object.  Additionally, with the right test strategy, each command can be tested independently which will make it easier to keep your system running correctly with fewer side effects.

Delegation vs exposing properties


Adding info from 3 textboxs into a jagged array to display in a listbox

Question: The Form layout
Im trying to create a windows form that allows the user to enter values into a jagged array in the form of a characters Name, Strength and Dexterity. Once they enter those values into a text box it has to be saved so users can view the information for characters that have been entered by using the List Box
    public Form1()
    {
        InitializeComponent();
        String[][] Arr = new String[3][];
        Arr[0] = new String[20];
        Arr[1] = new String[20];
        Arr[2] = new String[20];

    }

So ive created Strings for the user to enter the values for the 3 attributes. Now im not sure where to actually add the code (and what the code is). Should i put a line such as Arr[0] = NameTxtbox.Text
Comment: Are you just asking how to assign a click handler to a button?  Double-click on the button in the form editor.  I imagine some brief tutorials on WinForms development could go a long way here.  Also note that multiple arrays of values are a poor substitute for a single array of custom objects.
Comment: here is the doc: https://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(v=vs.110).aspx you can add event listeners on `TextChanged` event
Comment: I know how to assign a click handler to a button but what im not sure of is how to save the info from the 3 text boxes into the array, in the sense of Name must be saved into Arr[0] then Strength thats in the 2nd text box must be saved into Arr[1]
Comment: @JaceYatrakos: Well, `Arr[0]` is itself an *array*, so you can't save a single string to that.  Where in your weird data structure do you want to save that value?  Did you mean to save it to `Arr[0][0]`?  This would probably be *a lot* easier for you if you just create a custom object for your data and maintain an array (or generic list) of that object.
Comment: @David Sorry im really unsure of what you mean, im still trying to get the hang of C# forms so do forgive me. But are you saying that what i should rather do is have the info from the text box stored into a single array using the Textbox.TextChanged line?
Answer: Don't use multiple arrays of values as a substitute for a single array of objects.
Consider a simple object:
public class Character
{
    public string Name { get; set; }
    public string Dexterity { get; set; }
    public string Strength { get; set; }
}

Now, if you want your form to maintain a list of Character objects, then create a class-level property in your form:
private List<Character> Characters { get; set; } = new List<Character>();

Now whenever you save a character from the inputs (such as when clicking the "save" button on your form), you simply add it to the list:
Characters.Add(new Character
{
    Name = NameTxtbox.Text,
    Dexterity = DexterityTxtbox.Text,
    Strength = StrengthTxtbox.Text
});

So instead of trying to maintain a complex array of arrays of individual values, you have a simple collection of meaningful objects.  You can bind your ListBox to that same collection of objects.
Comment: So i havent touched on object creation so im piecing it together so let me make sure i understand it correctly: Create the Object Character with the variables Name,Dexterity and Strength, then the values in the text box are stored into the Name, Dexterity and Strength then whenever i save the character using the Save button it then calls a new instance of the Character Object to allow for another entry into the list?
Comment: @JaceYatrakos: That's the general idea, ya.  Basically any time you have multiple values which conceptually describe a *thing* then that *thing* is itself an object of some kind.  This is basically a variation of the refactoring pattern Replace Array With Object: https://refactoring.com/catalog/replaceArrayWithObject.html  You'll find that it's much easier to logically group values into meaningful objects.  And the improved semantics of giving those objects meaningful names makes your code easier for you to read and maintain.
Comment: Okay so i only have one more question in relation to your solution. Do i create the public class Character inside the public Form or outside it. Then do i put the rest like the Character.Add inside the Character class
Comment: @JaceYatrakos: I'd create it outside, keep it as a separate concern.  As your logic grows, this becomes a "model" in your "domain".  You might have custom objects like `Character` or `Weapon` or `AttackType` or anything that is a thing in the system you're building.  Ideally most of the logic of the domain would belong to models, and the UI (the forms) just invokes that logic.  Having a folder called "Models" and putting your custom things there would be a good start.
Comment: So im getting errors when i try add the Character.Add should it be written like this, Character.Add(new Character) {
Name = NameTxt.Text;
Dexterity = DexTxt.Text;
Strength = StrTxt.Text;
}
Also should this be added within the Character class
Comment: @JaceYatrakos: You have a typo in your code.  Notice your extra `)` after `Character`.
Comment: Im still confused, if you could please show me the actual code.
`code`  public class Character
        {
            public string Name { get; set; }
            public string Dexterity { get; set; }
            public string Strength { get; set; }
            Characters.Add(new Character
{
    Name = NameTxtbox.Text,
    Dexterity = DexterityTxtbox.Text,
    Strength = StrengthTxtbox.Text
        });
        }
Comment: @JaceYatrakos: The actual code is in the answer I posted.  What I'm showing there is the entire definition for the `Character` class, as well as a property for your form to store a collection of characters and a line of code for your form (likely in a button click event) to add an object to the collection of characters.  That is literally the "actual code".
Answer: As @David well points out your best bet is to learn a bit about winforms.
Here is some of microsofts documentation: https://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(v=vs.110).aspx
The Textbox fires events to TextChanged which you can 'listen' to to execute your own code: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged(v=vs.110).aspx
textBox = new TextBox()
textBox.TextChanged += () => {
   // your code here.
   var input = textBox.Text;
   Arr[1] = input.ToCharArray();
}

Answer: Inside of your Save Button handler add this
This Line :
string Info = textBox1.Text + " - " + textBox2.Text + " - " + textBox3.Text;
Concat all the strings the user entered into one string with - for spacing.
And This line
listBox1.Items.Add(Info);
adds the string to the listbox.
EDIT :
This is how you store them in an array.
string[] array = new[]{textBox1.Text , textBox2.Text , textBox3.Text};


How to estimate a critical value of Spearman's correlation for n=100?

Question: I have searched a lot, and I can only find tables that show critical values up to n=30. Can someone provide, or point me to, a simple method of estimating this value for different $\alpha$?
Answer: See Wikipedia: Spearman's rank correlation coefficient#Determining significance:
"One can test for significance using
$$t = r \sqrt{\frac{n-2}{1-r^2}},$$
which is distributed approximately as Student's $t$ distribution with $n − 2$ degrees of freedom under the null hypothesis."
Here $r$ is the sample estimate of Spearman's rank correlation coefficient. The reason critical values often aren't tabulated for $n > 30$ is that this approximation gets better as $n$ gets larger, and is very good for $n > 30$. The Stata statistical software package uses this formula to calculate $p$-values for all values of $n$.
Answer: For values over thirty the approximation (for a two-tailed test) is
$$\frac{\Phi^{-1}\left(1-\tfrac{\alpha}{2}\right)}{\sqrt{n-1}}$$
so for example with $\alpha = 0.05$ and $n=100$ the numerator is about 1.96 and the denominator about 9.95, giving a critical value of about 0.197.
This comes from $\rho$ having approximately a normal distribution for large $n$, with mean $0$ and variance $1/(n − 1)$, assuming independence of the observations.
Comment: Thanks. Can you provide a quotable source for this?
Comment: It seems to be standard in education, e.g. http://books.google.co.uk/books?id=3LhPwUhrVIcC&pg=PA397 or http://www.umich.edu/~exphysio/MVS250/SpearmanRankCorr.doc


Tkinter only works for one button press and not the others?

Question: I am using a Tkinter window to pass information over the serial port to an arduino that turns a stepper motor a certain number of steps. Basically I have buttons that correspond to the number of steps that i want the motor to take. When I press the buttons I want the motor to move that many steps. Ill post some snippets of my code BUT Basically my problem is that the window works beautifully for the first button press but then when I click other buttons to get the motor to keep moving I don't get anything. It almost seems like the Tkinter window only works for one click or gets stuck in the callback function or something.
The Callback Functions:
def firstGrating():
    arduino.write('1800')
    tkMessageBox.showwarning(title= 'Spectrometer', message = 'I am moving to the 1800 Grating...')
    tkMessageBox.showwarning(title= 'Spectrometer', message = 'Please Wait Until I Tell You That I AM FINISHED!!!')
    while True:
        message = arduino.readline()
        if len(message) > 10:
            tkMessageBox.showwarning(title= 'Spectrometer', message = message)
    return

def secondGrating():
    arduino.write('150')
    tkMessageBox.showwarning(title= 'Spectrometer', message = 'I am moving to the 150 Grating...')
    tkMessageBox.showwarning(title= 'Spectrometer', message = 'Please Wait Until I Tell You That I AM FINISHED!!!')
    while True:
        message = arduino.readline()
        if len(message) > 10:
            tkMessageBox.showwarning(title= 'Spectrometer', message = message)
    return

def thirdGrating():
    arduino.write('3600')
    tkMessageBox.showwarning(title= 'Spectrometer', message = 'I am moving to the 3600 Grating...')
    tkMessageBox.showwarning(title= 'Spectrometer', message = 'Please Wait Until I Tell You That I AM FINISHED!!!')
    while True:
        message = arduino.readline()
        if len(message) > 10:
            tkMessageBox.showwarning(title= 'Spectrometer', message = message)
    return

and this is the part where I try to setup my Tkinter window:
win = Tk()
win.geometry("600x400+500+500")
win.title('Spectrometer Controller')

mlabel = Label(text = 'Select One of The Available Gratings')
mlabel.pack()

mButton1 = Button(win, text = '1800', command = lambda: firstGrating())
mButton1.pack()#.grid(row=0, column=1)
mButton2 = Button(win, text = '150', command = lambda: secondGrating())
mButton2.pack()#.grid(row=0, column=2)
mButton3 = Button(win, text = '3600', command = lambda: thirdGrating())
mButton3.pack()#.grid(row=0, column=3)

win.mainloop()

Answer: You're right, it's getting stuck in the callback. Tkinter's mainloop() creates a conflict with a while loop and becomes unresponsive, so there's no way to press another button while the while loop is running.
You can look at the after() method to create a programmatic loop that will keep your GUI responsive. Here's an example:
def callback(flag):
    global loop
    if flag is True:
        print('message')
        ... other logic ...
        # start the after method to call the callback every 100ms
        loop = root.after(100, callback, True)
    else:
        # cancel the after method if the flag is False
        root.after_cancel(loop)

root = Tk()

# use a lambda expression to pass arg to callback in button commands
Button(root, text='start', command=lambda: callback(True)).pack()
Button(root, text='stop', command=lambda: callback(False)).pack()

mainloop()

You can also keep the GUI and the business in separate threads, but that's usually a PITA to set up. The after() method is usually just as effective.


Save FileField file to an external server

Question: When using FileField or ImageField, files are saved to a local folder in the Drupal install. This works great and all, but up till now the media files on my website are served from a discrete server (a CDN), and I'd really like to keep them separate.
Is there a module that extends File/ImageField to allow you to specify an external server (FTP and credentials) to use as a file server?
Any advice or pointers with this is appreciated.
(Ps I've seen the CDN module, but that requires the use of a server daemon or modifying the CDN's origin... and I'm not particularly fond of either implementation.)
<3
Comment: Did you complete this task?
Comment: @Mohini No, we ended up settling on a "solution" I am too embarrassed to share. :) (Hint: It involved a lot of manual processes.)
Comment: Did you used custom module. What kind of solution did you resolved to. Please let me know.
Answer: As far as I know, there is no other way to do this in Drupal 6 than what CDN does.
In Drupal 7, this is a completely different story, however. Drupal 7 uses stream wrappers when dealing with files and it is a) possible to implement custom stream wrappers with PHP code and b) the stream wrapper can be chosen per file/imagefield.
So if it is possible to access X with PHP (FTP, Flickr, Amazon S3, ..) then it should be possible to write a stream wrapper for it and therefore allowing Drupal to write the files to that place.
This probably doesn't help you in your situation, but maybe it will help someone else, when deciding to use Drupal 6 or 7 for a new project for example :)
Answer: It may be too powerfull and quite complex to set up but have you tested Media Mover ?
If you have shell access on your server, you may be interested in File Conveyor, a Python Daemon written by Wim Leers, a well know Drupal contributor. Of course after setting this up you'll have to rewrite your files URL to point to your CDN.


Fingering a chord with three pinky fingers?

Question: This is the opening of the second movement of Beethoven's Pathétique Sonata (Op. 13), Schenker edition, published by Dover.
This edition seems to suggest playing each of the three notes comprising the opening chord with a pinky finger. Regrettably, I seem to lack the requisite anatomy.
Have I misunderstood what the editor is suggesting, or have I found a misprint?
Comment: The middle 5 must be a typo don't you think?
Comment: That was my guess. I first realized that the middle 3 in the second measure presumably refers to my *right* hand (after contorting my left hand unpleasantly) and only then noticed this middle 5. I'm guessing typo, but I'm still a beginner so it occurred to me that maybe I had misunderstood.
Comment: What I want to know is how do you get three pinky fingers
Comment: The whole fingering looks like it's written for a Martian. I'd recommend you to ignore it completely (unless you _are_ a Martian of course).
Answer: The 5 on the 16th note is a misprint. Presumably it should be a 2 or 3. (Personally, I think the rest of the fingering for both hands in bar 1 is weird - but that's a different issue!)
Your edition copies the notation of the first edition (https://imslp.org/wiki/Special:ImagefromIndex/50958/torat) but for an "instructive" edition with fingering, etc, it would have been better if the editor had used a bracket [ to show that the 16th notes should be played with the right hand, or rewritten the music as in the Breitkopf und Härtel edition https://imslp.org/wiki/Special:ImagefromIndex/51718/torat).
First edition:

B&H edition:


Prove variation of Titchsmarsh convolution theorem

Question: I want to prove the following statement. Let
$$
f,\,g\in L_1(\mathbb{R}).
$$
Also
$$
\forall x<0 \quad f(x)=g(x)=0
$$
and
$$
\forall x\in\mathbb{R}\quad f*g=0,
$$
where $*$ denotes a convolution. Then $f\equiv0$ or $g\equiv0$ almost everywhere.
It is advised to prove it using Fourier transform. I have read through this question: convolution of non-zero functions, but I can't figure it out if I can apply this techinque to my problem, because I don't have compact support.
As advised in the comments, I note that this variation should be proved without the application of Titchsmarsh theorem.
Comment: reading https://en.wikipedia.org/wiki/Titchmarsh_convolution_theorem it seems like your variation follows from it, have you tried that?
Comment: @supinf yes, but then I have to prove the theorem itself.
Comment: ok i understand. Maybe you should add to your question that you are not allowed to use that theorem itself
Comment: @supinf edited the question
Answer: Lemma If convolution of two finite functions is zero, then one of these functions is zero almost everywhere.
Proof. Can be found here https://math.stackexchange.com/questions/1024340/convolution-of-non-zero-functions?noredirect=1&lq=1
Now take an arbitrary $A>0$ and assume
$$
f_A=f\cdot\chi_{[0;A]}
$$
and
$$
g_A=g\cdot\chi_{[0;A]}
$$
Observe that for $y\leq A$
$$
0=f*g(y)=\int_{-\infty}^{+\infty}f(x)g(y-x)\;dx=\int_{0}^{y}f(x)g(y-x)\;dx=\int_{0}^{y}f_A(x)g_A(y-x)\;dx=\int_{-\infty}^{+\infty}f_A(x)g_A(y-x)\;dx=f_A*g_A(y).
$$
Thus, $f_A$ or $g_A$ is zero almost everywhere (apply the Lemma), meaning that $f$ or $g$ is almost everywhere zero on every interval, therefore, it vanishes almost everywhere on $\mathbb{R}$.


Reading Specific Data In XML Files in Visual Basic

Question: The title says it all, I want to know how to read various pieces of data from .xml files in visual basic. My current, basic, xml file looks like:
 <?xml version="1.0"?>

-<ArrayOfActivity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

 -<activity>

 <memno>1239</memno>

 <curweek>0</curweek>

 <rundist>0</rundist>

 <runtime>0</runtime>

 <swimdist>0</swimdist>

 <swimtime>0</swimtime>

 <cycdist>0</cycdist>

 <cyctime>0</cyctime>

 </activity>

 -<activity>

 <memno>1293</memno>

 <curweek>0</curweek>

 <rundist>0</rundist>

 <runtime>0</runtime>

 <swimdist>0</swimdist>

 <swimtime>0</swimtime>

 <cycdist>0</cycdist>

 <cyctime>0</cyctime>
 </activity>
 </ArrayOfActivity>

I want to just read to values from, say, member number 1239, how do I go about this? I cannot make sense of any on-line help, I am fairly new to visual basic. I also save through this method:
 Public Sub SaveDataAct()
    If System.IO.File.Exists("e:\Test\test2.xml") = True Then
        System.IO.File.Delete("e:\Test\test2.xml")
    End If
    Dim serializer As New Xml.Serialization.XmlSerializer(GetType(List(Of activity)))
    Dim fs As New IO.FileStream("e:\Test\test2.xml", IO.FileMode.Create)
    serializer.Serialize(fs, dataentry)
    fs.Close()
End Sub

Comment: Post the xml as text using the icon with two arrows <> instead of a picture.
Comment: This is vb.net not vba
Comment: Thanks for the formatting help
Comment: I would recommend using Linq to Xml instead of XmlSerializer - it's more lightweight and allows navigating the Xml. This [thread](http://stackoverflow.com/questions/1066213/linq-to-xml-in-vb-net) contains some simple examples that should help you get started.
Answer: Like already mentioned by Pawel you should rather use Linq to Xml.
Your sample program would look like:
Imports System.Linq
...

Sub Main()
    Dim input As XElement = XElement.Load("e:\Test\test2.xml")

    //Query your Xml with Linq, almost similiar to Sql.
    //You can extend with any where/join/group/order by clause
    Dim output = From activies In input...<activity>
                 Where Integer.Parse(activies.<memno>.Value) <= 1293
                 Select activies

    //Output is an IEnumarable of XElement
    For Each activity In output
        Console.WriteLine("Member: {0}", activity.<memno>.Value)
        Console.WriteLine("Current Week: {0}", activity.<curweek>.Value)
        //...
    Next

End Sub

As you can see you can navigate directly thru an XElement with .<ChildElementName> and with ...<DescendantElementName> which is a pretty nice VB .NET feature.
More about LINQ
Answer: I would read it to a dataset like this:
 Dim XML_Read as DataSet = new DataSet
 XML_Read.ReadXML("e:\Test\test2.xml")

Then you will get access to the element you want this way:
 XML_Read.tables("activity").Rows(0).Item("memno")


Exchangeability and IID random variables

Question: Every IID sequence of random variables is considered to be exchangeable, i understand why its necessary for the random variables to be identically distributed to assume exchangeability, but why the need for independence, (or is there a need)?
In the context of the definition which loosely states that any permutation of the random variables has the same joint distribution, isn't it sufficient for the random variables to be identically distributed to be able to reorder them, or must both conditions be met?
Comment: "Every IID sequence of random variables is exchangeable" does not imply that "every exchangeable sequence of random variables must be IID."  Consider a sequence of 10 variables generated as follows: we flip a coin.  If it comes up heads, all 10 variables are set equal to 1, otherwise all 10 variables are set equal to 0.  This is an exchangeable sequence but obviously not independent.
Comment: You might be confusing the joint distribution with the collection of marginal distributions.  The former specifies much more than the latter.
Answer: I think, the word "identically distributed" is mostly misleading when not used to discuss independent random variables. Consider the following example:
$$\begin{pmatrix}X_1 \\ X_2 \\ X_3\end{pmatrix} \sim \mathrm{N}\left(\begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix},\begin{pmatrix}1 &0 & 0  \\ 0&1&0.1 \\ 0&0.1&1\end{pmatrix} \right)$$
The components of the vector $(X_1, X_2, X_3)^T$ are neither independent, nor exchangeable, but they are identically distributed: the marginal distributions are all standard normal: $X_i \sim \mathrm{N}(0,1)$, $i = 1,2,3$.
Next example:
$$\begin{pmatrix}Y_1 \\ Y_2 \\ Y_3\end{pmatrix} \sim \mathrm{N}\left(\begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix},\begin{pmatrix}1 &0.1 & 0.1  \\ 0.1&1&0.1 \\ 0.1&0.1&1\end{pmatrix} \right)$$
The components are now not independent but exchangeable. The marginal distributions are again identical, standard normal: $Y_i \sim \mathrm{N}(0,1)$, $i = 1,2,3$.
We have in the end the following implications:
$$ \text{i.i.d. } \Rightarrow \text{ exchangeability } \Rightarrow \text{marginals identical}.$$
The counterexamples above show, that the converse implications are all wrong.
Comment: +1: This answer is especially nice in providing clear, simple examples to demonstrate the assertions about the converse implications.  Welcome to our site!
Comment: I like the examples and how they demosntrate the implications you ascert, but i don't understand why "identically distributed is misleading when not discussing independent random variables"
Comment: It is probably a personal thing, but "identically distributed" gives me a feeling of symmetry amongst the random variables. This symmetry though only exists for the marginals, but not within the random vector. Hence, my feeling misleads me.
Answer: To answer this question you need to understand the "representation theorem" for exchangeable sequences of random variables (first stated by de Finetti and extended by Hewitt and Savage).  This (brilliant) theorem says that every sequence of exchangeable random variables can be considered as a sequence of conditionally IID random variables, with distribution equal to the limiting empirical distribution of the sequence.  This means that every sequence of conditionally IID random variables is exchangeable and every sequence of exchangeable random variables is conditionally IID.  Conditional independence does not imply marginal independence, and it is common for exchangeable sequences of random variables to be positively correlated (but they cannot be negatively correlated).
In regard to your question, this means that independence is not a requirement for exchangeability, but conditional independence is.  Most sequences of exchangeable random variables are positively correlated, owing to the fact that conditional independence generally induces an information link between the random variables.
Comment: Yes, that is correct.  The classic example of finite exchangeability is SRSWOR, which gives a hypergeometric distribution.  In that case there is negative correlation between the outcomes.
Comment: Negative correlation is possible for variables that are only *permutable* or *finitely exchangeable*. Infinite exchangeability needed for the rep theorem, does not admit negative correlation
Comment: I think the second paragraph is incorrect.  In the finite case with negatively correlation, conditional independence is clearly *not* a requirement.  Is not even possible as any form of conditional independence would lead to non-negative correlation marginally.  So  conditional independence can only be a requirement for infinite exchangeability.
Comment: @JarleTufto: Both the question and this answer refer to infinite sequences of random variables, not finite vectors of them, so I do not consider the finite case here.
Answer: There is no need for exchangeable random variables to be independent. For instance, if the vector $X$ follows a multivariate t distribution with mean zero , identity matrix as a scale matrix, and q degrees of freedom, then it's components are exchangeable, uncorrelated, and identically distributed, but not independent. Of course, by the exchangeability theorem it's components are conditionally iid (conditionally on a Gamma(q/2,q/2) in fact), but they are not independent.


Is there difference if I call input.nextLine() as part of exception catching in every catch block or inside a final block at the end of try-catch?

Question: For example, here I put it only once, but I know that I can put it several times. What is the difference?
        try{
        if(tasks.size() <= 0){
            System.out.println("Nothing to remove, no tasks");
        }
        else{
            System.out.println("Enter index of task to remove");
            int index = input.nextInt();
            input.nextLine();
            tasks.remove(index);
        }
    }
    catch(InputMismatchException ex){
        System.out.println("Please enter only numbers");
    }
    catch(IndexOutOfBoundsException ex){
        System.out.println("Invalid index number");
    }
}

Comment: It's unclear what you're asking. Also, the code provided doesn't match the title of the question. Please [edit](http://stackoverflow.com/posts/33704283/edit) the question in order to receive better answers (and to avoid closing the question).
Answer: finally will be called always, regardless if you cough exception or not so yes, there is a difference.
Anyway assuming you are using Scanner you should avoid using try-catch as part of your logic (they should be used only if exceptional situations happen since creating exception may be expensive). Instead try to prevent throwing exceptions with little help of hasNextInt method.
So you can try with something like:
System.out.println("Enter index of task to remove");
while (!input.hasNextInt()){
    System.out.println("That was not proper integer, please try again");
    input.next();// to let Scanner move to analysing another value from user
                 // we need to consume that incorrect value. We can also use
                 // nextLine() if you want to consume entire line of
                 // incorrect values like "foo bar baz"
}
//here we are sure that inserted value was correct
int int index = input.nextInt();
input.nextLine();// move cursor after line separator so we can correctly read
                 // next lines (more info at http://stackoverflow.com/q/13102045/1393766)

Answer: The difference is clarity and simplicity.
The finally block will always execute, if present.  Code which is common to the entire block can be located there.  In the future if a different response is required it can be changed in a single location.
When common code is spread out in multiple locations you run the risk of changing some but not all instances which can result in unexpected failures.


Amp setting to have a longer lasting bend sound or sound ringing at all?

Question: I have a Boss Katana 50 amp and am fairly new to equipment setup for e-guitars. As I am learning "Maggot Head" from Funkadelic I have a lot of slow bends that do not have a lot of density on my setting. That means the sound is disappearing fairly quick when I pick a string.
Any common setup tips how to have a longer lasting tone?
Comment: "Maggot Brain", surely! For more sustain, either use more gain (this will also increase overdrive/distortion) or use compression. If you get too much hum between the notes, go into the Katana editor and switch on the noise gate.
Comment: as below mentioned you can try by using more gain, and maybe by adding more highs
Answer: Basically, you want the sustain part of the tone increased in relation to the attack part. There are three ways to do that with amps settings/ effects: either you increase the gain of the amp, you add an overdrive effect, or you add a compression effect. The first and second will alter your tone more or less drastically, the third should be a lot less noticeable. Check the section of your amp's manual that deals with effects, and play with some of the "Booster" effects it offers, or the "Comp" effect.
Also, take a closer look at your playing technique and your guitar setup. The amp can only amplify what comes out of the guitar. Make sure that the tone rings clearly throughout your bends and that it doesn't get killed by sloppy fingering or high frets.
Answer: Aside from settings on your amp and the suggestions above, you could use some slight vibrato at the top of your bend. Don't move the string too much but slightly up n down and you can get a longer ring out of it.
You'd be surprised with how much you can change the sound with your fingers and the way you play the guitar. Granted, this comes with experience and many hours of playing, you need to be comfortable with the guitar to be able to express that through your fingers.
Answer: On Maggot brain he uses a 60's/70's fuzz and wah. If you combine the Wah pedal with the vibrato technique mentioned above you can achieve some awesome sustain. You can achieve this using more gain but you will need to be a lot more accurate with your technique otherwise you will sound like you are failing a Guitar Hero song. It takes a lot of practice! good luck!
Answer: Of course it depends on the kind of amplifier, but I'm sure that if you increase the sustain, maybe the highs too, and try to bend with more power, you are surely going to get better bends


Adding custom data to the node object

Question: I have created a content type called providers and when editting said content types users can fill in extra information related to the content.
I have included said form fields using hook_form_alter, and the appropriate hook for _submit applied with it all working fine (saving to db etc)
Where I am stuck is I can access the data, by loading it via hook_ENTITY_TYPE_load call which allows me to access it in _form_alter but for some reason when viewing the node, I do not see the data.
Is there a specific way of loading external data on top of node object in d8?
below is how i load the data.
<code>    /**
     * Implements hook_ENTITY_TYPE_load($entities)
     */
    function remittance_providers_node_load(array &$entities) {
      //loop thorough the loaded entities
      foreach ($entities as $key => $entity) {
        // if provider node type is being loaded add our data on top of it.
        if ($entity->bundle() == 'providers') {
          $nid = $entity->id();
          $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
          if(count($commission_data)>0){
            foreach ($commission_data as $ckey => $comm) {
              $entities[$key]->commission[$ckey]['amount_from'] = $comm->amount_from;
              $entities[$key]->commission[$ckey]['amount_to'] = $comm->amount_to;
              $entities[$key]->commission[$ckey]['commission'] = $comm->commission;
            }
          }
        }
      }
    }
</code>
I have installed devel and checked all its phases and I dont see it in there.
Comment: Are you printing this data in the template? What do you mean when you say you don't see it?
Comment: yes I am looking to print it out in a template,but when i go to  /devel/node/3 I cannot see the 'commission' data array in the provider entity. In the _form stage i could access the data by doing the following: $node = $form_state->getFormObject()->getEntity(); $node->commission[$i]['amount_from'] etc
Answer: I have found preceding value array with [x-default] shows the values.
I presume this has to do with the translation module
<code>function remittance_providers_node_load(array &$entities) {
  //loop thorough the loaded entities
  foreach ($entities as $key => $entity) {
    // if provider node type is being loaded add our data on top of it.
    if ($entity->bundle() == 'providers') {
      $nid = $entity->id();
      $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
      if(count($commission_data)>0){
        foreach ($commission_data as $ckey => $comm) {
          $entities[$key]->commission['x-default'][$ckey]['amount_from'] = $comm->amount_from;
          $entities[$key]->commission['x-default'][$ckey]['amount_to'] = $comm->amount_to;
          $entities[$key]->commission['x-default'][$ckey]['commission'] = $comm->commission;
        }
      }
    }
  }
}
</code>

Adding custom data to the node object


removing bb codes with regex replace

Question: I am trying to remove BBCode tags through Javascript however I am unable to understand how.
Adding all tags into an array eg:
var bbcodes = ["[b]", "[/b]"];

Then searching through my text and replacing the bbcode with "".
for (i=0; i < bbcodes.length; i++) {
    selTextStrip = selTextStrip.replace(bbcodes[i], "");
}

Having realised this will only replace the first occurrence I tried to add expression:
for (i=0; i < bbcodes.length; i++) {
    selTextStrip = selTextStrip.replace(new RegExp(bbcodes[i], 'g'), "");
}

However this would do the following:
Change [b]BBCode[/b] into []BBCode[]
How can I change the RegExp to suite all these tags:
"[b]", "[/b]", "[i]", "[/i]", "[u]", "[/u]", "[s]", "[/s]", "[left]", "[/left]", "[center]", "[/center]", "[right]", "[/right]", "[quote]", "[/quote]", "[code]", "[/code]", "[list]", "[/list]", "[img]", "[/img]", "[spoil]", "[/spoil]"

Further to this, If I want to remove the following tags from text -> [color=red]text[/color] what expression would I need to remove both [color=red] and [/color]? Noting that 'red' can change to any length and can also be a hex value ([color=#ff0000]text[/color])
I have tried adding [color=(.*?)] into the array however as before only 'color=' is removed not the #hex value nor the '[]'
Thanks in advance.
Comment: sorry, double up the escape character for javascript: `"\\[b\\]", "\\[\\/b\\]"`
Comment: you would need to escape the square brackets: `"\[b\]", "\[/b\]", ...`
Comment: I changed my array to: var bbcodes = ["\\[b\\]", "\\[\/b\\]"]; however only the 'b' was removed.
Comment: Brilliant, that worked. Any idea for the color one?
Comment: @Matt you can use this: https://github.com/thunderer/Shortcode . Just register `NullHandler` or `ContentHandler` as default handler for all shortcodes and they will be either completely erased or just stripped from shortcode tags. You can also use this: https://github.com/coduo/php-humanizer as it has already implemented shortcode removal features using the library above. Let me know if you need any help.
Answer: text.replace(/\[\/?(?:b|i|u|s|left|center|right|quote|code|list|img|spoil|color).*?\]/g, '')

will also provide the color=foo stripping.
Or use
text.replace(/\[\/?[^\]]*\]/g, '')

to strip all kinds of [foo something] tags.
Answer: You can use the regex \[\\?\w*\]
Look at this

removing bb codes with regex replace


this.Invoke(...) - is this bad practice?

Question: I have a function called ExecuteCommand that does things based on a user's input. These things can range from simply doing a Console.Writeline(), checking a check box on my form, or simulating keystrokes to another process, completely independent from my own. The function runs on a separate thread, so changing the UI will requiring some invoking. I have 2 ways of doing it... one of which I'm not sure is a good way but it's very easy.
Code below, the 3rd line is what I have a question with:
private void ExecuteCommand()
{
   this.Invoke((MethodInvoker)delegate()
   {
      if (current_line_index < command_que.Count)
      {
         current_line = command_que[current_line_index];

         if (current_line.StartsWith(">>Auto Enter"))
         {
            chkAutoEnter.Checked = false;
         }
         else if (current_line.StartsWith("+WinWait("))
         {
            string title_to_wait_for = current_line;

            title_to_wait_for = title_to_wait_for.Remove(0, "+WinWait(\"".Length);
            title_to_wait_for = title_to_wait_for.Remove(title_to_wait_for.Length - 2, 2);

            t_WinWait = new Thread(() => WinWait(title_to_wait_for));
            t_WinWait.Name = "WinWait";
            t_WinWait.Start();
         }
      }
   });
}

The code works perfectly... but I am not sure if it's good practice.
Alternativly, I know I can do something like this to change the UI:
private delegate void CheckCheckBoxHandler(bool checked);

private void CheckCheckBox(bool checked)
{
   if (this.chkAutoEnter.InvokeRequired)
   {
       this.chkAutoEnter.Invoke(new CheckCheckBoxHandler(this.CheckCheckBox), checked);
   }
   else
   {
       chkAutoEnter.Checked = checked;
   }
}

But as I have multiple controls on my form that will be changed from another thread, I'd have to add a bunch of functions to do that, versus the simple method in the first example.
Is the first way bad in anyway? Are there any risks involved I haven't come across yet? It seems to good to be true...
Thanks!
Answer: No it's not bad.  It doesn't matter which control that you call Invoke on since they all have the same effect.   Invoke calls the delegate on the thread that owns the control - as long as all your controls are owned by the same thread, then there is no difference.


Does the bowler's run-up actually contribute anything useful?

Question: Bowlers run up before performing a little hop to get momentum going and bowl the ball. Does the run-up contribute anything to the speed/spin of the ball? Or could you get a similar speed/spin by just hopping to get your moment going, without running?
I know pitching in baseball is different from bowling in cricket, but wouldn't you be able to get a similar amount of force behind the ball without running up? Isn't energy lost by the hop that bowlers perform when they extend their legs and pivot with the ball?
Answer: Running up does add some speed to the ball.
Simple physics:

Bowling speed = 130 km/h
Running speed + 15 km/h
=> Total speed = 145 km/h

The spin is different as well. While standing a bowler just has a circular movement based on their arm length. Running up causes that movement to be elliptical.
Example:

This isn't all, though. There's also velocity, air resistance and other factors which are missing in this example calculation. But yes, running up does help.
Comment: I imagine the run affects the strength of the throw as well, no?  Like a javelin thrower, able to get more torque behind the throw?


Passar ID do PHP por javascript para uma página

Question: Eu gostaria de enviar o id que eu pego com o php e enviar para uma página a cada 30 segundos...o que eu fiz até agora:
$idtarefa = $_GET['id'];

recebo o id, faço todo o html e ai no javascript eu fiz isso:

A ideia é que atualize a hora a cada 30 segundos de acordo com a id em uma tabela mysql, eu olhei vários scripts e fui até ai, mas com certeza tem algo errado que eu não sei o que é...no arquivo atualiza_base eu queria pegar o id com get dnv
Answer: Você pode fazer o seguinte.
Antes de incluir ou escrever o código javascript, definir uma constante com o seu id, exemplo:

E seu setInterval ficará assim:
setInterval(function() {
    ajax.open('get', 'atualiza_base2.php?id='+idTarefa);
    ajax.send();
}, 3000);

Para pegar o id novamente, basta fazer $id = $_GET['id'];
Caso não tenha sanado sua dúvida, dê mais detalhes sobre o arquivo atualiza_base.php
Comment: cara, não funcionou...:T
Comment: Pior que isso é a chave de todo um sistema...e não consigo passar essa id, batendo pino a 2 dias já
Comment: Pode dar mais informações sobre o erro e como está sendo implementado?


Is this method of applying content security policy ok?

Question: I am trying to add CSP to my web application, I have added the following meta tag in my index page:
<meta http-equiv="Content-Security-Policy" content="img-src 'self' data:;default-src *;style-src 'self' http://* 'unsafe-inline';script-src 'self' http://* 'unsafe-inline' 'unsafe-eval';" />

and Also the following my my web.config file on IIS:
<customHeaders>
     <add name="Content-Security-Policy" value="default-src 'self' 'unsafe-inline' http://*.domain.com;
                                                img-src 'self' http://*.domain.com data:"  />

      </customHeaders>

Is it necessary to add both meta tag and additional headers? or One of them is sufficient?
Does the meta tag policy override the custom header?
Does this script-src 'self' http://* 'unsafe-inline' 'unsafe-eval' mean that I can write inline JavaScript and use eval function inside my code? Does this rule override the policy set by headers? (because as far as I know in headers I have prohibited usage of inline JavaScript and eval function)
And my last question is if I use these settings, Should I use ng-csp or its other variant ng-csp="no-unsafe-eval" in my html?
Comment: If this implementation is to remediate flaws highlighted in Veracode and you still continuing 'unsafe-inline' 'unsafe-eval' won't resolve the problem.
Answer:
Is it necessary to add both meta tag and additional headers? or One of them is sufficient?

One is sufficient. If you can make your server send the policy in a response header, that's better. You don't need to also specify anything in a meta element too, and there's no advantage to it.

Does the meta tag policy override the custom header?

The meta policy will only override the header policy if the meta policy is stricter. See this answer:
What is happening when I have two CSP (Content Security Policies) policies - header & meta?
… which cites a part of the CSP that says, "adding additional policies to the list of policies to enforce can only further restrict the capabilities of the protected resource".

Does this script-src 'self' http://* 'unsafe-inline' 'unsafe-eval' mean that I can write inline JavaScript and use eval function inside my code?

It would do that if your header also specified those values for script-src. But your header policy does not. So the browser uses the strictest policy, regardless of where it's specified.

Does this rule override the policy set by headers? (because as far as I know in headers I have prohibited usage of inline JavaScript and eval function)

No, as the What is happening when I have two CSP (Content Security Policies) policies - header & meta? answer explains, you can't override a strict policy by specifying a less-strict policy elsewhere.
So you're best off specifying all your policy values in just one place, in a header (instead of meta).