Record drums for cheap

Question: As of in the title, I'd like to record my acoustic drumset fairly cheap, but I have no idea of what I need to buy to do it.
My drumset is made of:

hi-hat
snare drum
2x Tom's, and a floor Tom
kick
2 crashes, 1 ride, 1 crash/ride, 1 splash

Now I only got a MacBook Pro with Logic Pro X
Have you got any suggestions for me?
Answer: Yes. Get two identical mics, condensors if you can afford them, if not then SM-57s. You also need at least a two channel audio interface with two or more mic preamps. Bare minimum total is about $300 - $400 (US) new. If you can afford more than two channels with more than two mic pres and a third mic, that's even better. A kick mic like a D112 will be fine for the third but an SM7, RE-20, or MD-421 would be best if you can swing one of those for mic three.
Do a web search for "recorderman mic technique" or "recorderman overheads" to find the complete guide to this mic setup. It's a modified Glyn Johns technique that gives a great stereo spread and full sound with solid time alignment with just two mics. Basically you position one mic over the hi hats, another behind the right shoulder of the drummer, and you use a piece of string, rope, or even a cable to measure and match the distances from the mics to the kick and share.
If you have three mics then put the third on kick, but not right in the hole. Give it one to five feet and just move it around until it sounds best.
If you can afford more mics and channels, then either one or two room mics if you have a good room and want that sound, or start doing spot mics on snare and toms. You can use SM57s or 58s for these, or MD-421s if you can. I like a large diaghram condensor on snare but that's moving into higher budget territory.
Overall, start with fewer mics of higher quality that you can keep and use forever (my oldest mic is the first one I got: SM-57 from 20+ years ago and I still use it) and you can expand your mic locker through the years until you have a pro collection.
Start by researching the recorderman technique.

Edit: here's a link to a good guide to recorderman miking: http://jonstinson.com/the-recorder-man-drum-miking-technique/
Salient points:

first mic over the snare (maybe a little over the hat) pointed right at the snare two drumsticks away from center of the snare
second mic behind the drummer over the opposite shoulder pointed at the snare center also two drum sticks away
use the kick pedal to clamp a cable or string to the kick head, run the cable/string up to one mic, then down to the center of the snare head and hold it there. Take the point on the cable touching the mic and move it over to the other mic and make sure the distances are the same. Adjust the mics slightly until they match. Normally two people are needed for this part.

The reason I continue to use this technique for overheads, even with lots of spot mics on the kit pieces, is that it gets the kit very well without relying on a good room. The most expensive part of awesome drum sounds is building or renting a great sounding, large room. With recorderman I've gotten great sound in a small, tin-lined storage space. Actually a great drummer is the most expensive part, then a great room. I'll take a great drummer and two SM-57s in a plastic shack over a flat sounding drummer who can't tune drums and a dream mic locker at my choice of studio every time.
Comment: This seems to make the point that there's no 'cheap' way to do quality recording. And I believe it's right. Add up the prices paid, and I know that it's the way to go - I have most of this kit - and there is no cheap way to quality record. And that's just drums! +1.
Comment: @Tim depends on what you mean by "cheap". $1k for the laptop, say $400 for mics and interface and sundries (cables, Reaper), and maybe a little something for a place to play in, and you could do pretty well for only $1,500. Compare that with any decent amount of studio time and it seems like a bargain. What people should really take away is the ***technique*** is the most important part. Some of your (by "you" I mean anyone reading this) favorite recordings were done with a few mics and a four track tape deck, almost certainly. Skills trump gear every time.
Comment: Yep, on the low end, I would think. First, the PC and sound interface is a given, so if that is too expensive, then don't bother and use your cell phone. And yes, the technique and all the dynamics involved is quite interesting.

Record drums for cheap


NSURLSession's NSURLCache not working as expected

Question: I'm seeing weird behaviors when using NSURLCache and exhausted all options but posting here... so here it is:
I'm trying to implement NSURLCache as underlying caching mechanism in combination with NSURLSession. And using Charles and simple println() I observe that no matter what I do, my app continues to go back to the server and re-requests previous requests.
I validated that my server sends the following headers consistently:
 Cache-Control:public, max-age=31449600
 Content-Length:74289
 Content-Type:image/jpeg
 ETag:"abcdf"
 Expires:Sun, 03 Jan 2016 20:58:01 GMT
 Last-Modified:Sat, 09 Nov 2013 08:05:53 GMT

Yet when I make the following request:
let req = NSURLRequest(URL: NSURL(string: URLString)!, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 15)

NSURLSession's willCacheResponse: delegate method doesn't get called at all:
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse!) -> Void) {

However, when simply requesting NSURLRequest(URL: NSURL(string: URLString)!) without specifying specific cachePolicy, then willCacheResponse: does get called. Nevertheless, the next time the same request is made, the app goes back to server...
I don't do any response object modifications in any NSURLSession delegate methods and my requests are all HTTP GET.
What am I missing?
I've read a lot that's out there on NSURLCache:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html
http://nshipster.com/nsurlcache/
http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
NSURLCache doesn't cache
various other SO threads...

Setup: Xcode6.1, Swift, iOS8+
Edit: I pushed a basic example to github to show my problem: https://github.com/opfeffer/nsurlcache
Check it out and let me know what I'm doing wrong!
Comment: Can we see a small, complete example of code that shows the problem? It would be helpful, for example, to know how you're actually making the request, and creating the session, including the session configuration object particularly.
Comment: What's the URL that you are requesting? Are you using GET or POST? Can you see from the logs what the client is sending to the server? Are any firewalls in the way causing problems?
Comment: @MattGibson: I added a sample app to github. Check it out! THANKS!!!
Answer: I see your GET request has parameters, and for that I think we are facing the same situation.
I reached a solution overriding NSURLCache doing some adjustments and accessing the underlying DB, you can see it here:
https://github.com/JCardenete/NTURLCache/tree/master/NTURLCache
NSURLCache - Disk caching for GET request with parameters not working
Comment: Oh interesting! Thanks for info, will certainly check it out!


How to quantify the similarity/difference between groups of selected features?

Question: Since I have a imbalanced data to deal with, I randomly down-sample the negative data to reach balanced data for following feature selection and classification. To test feature's robustness to different samples, the above process is repeated 30 times and I want to measure the difference among groups of selected features in each one of 30 rounds. Higher similarity claims the robustness of the selected features to difference samples.
How could I do this?
EDIT:
I have a thought of measuring "indirectly": Refitting the selected features in each of 30 samples using the whole dataset and observe the performance distribution, e.g., variance. For example, if I have m out of M features selected in the i-th sample, I can get a performance by using only m features but on the whole dataset. By doing so, 30 performances using different selected features but the same dataset can be obtained and by observing the variance of the performance distribution we can probably claim the following: Higher variance represents bad robustness of selected features because they are quite different among samples; lower variance might represent rather good robustness on the other hand.
But the problem is, low variance doesn't necessarily claim the selected features are similar across samples, because they are derived under the subsets of the dataset.
Comment: It is not good statistical practice to down-sample.  Any method that requires down-sampling is dubious.  Most people make the mistake of down-sampling because they do not understand [proper accuracy scoring rules](https://www.fharrell.com/post/class-damage).
Answer: I am not sure about an absolute metric for this, but a nice way to think about it could be with Hamming distance. For each of the 30 samples, create a vector of indicators of whether a feature was included or not. For example, if there are possible features 0,1,2,3,4, and only features 1 and 2 were selected in a round, the vector would be [0 1 1 0 0]. So you get 30 different vectors:
<code>[0 1 1 0 0]
[1 0 1 0 0]
...
[0 1 1 0 0]
</code>
You can compute a similarity metric between these vectors by counting the number of matches and dividing by the length. For example,
<code>sim([0 1 1 0 0], [1 0 1 0 0]) = 3/5 = 0.6
</code>
So a quick way to compute an overall similarity score would be to compute all pairwise similarities and compute the mean or median. A higher mean similarity score would mean a more robust feature selection method across samples.
Comment: Thanks! This sounds like a direct way of measuring similarity, I also come up with a relatively "indirect" way and added in the OP, correct me if wrong.
Comment: I think your idea of an "indirect" measure seems pretty useful, at least from a predictive performance perspective (and maybe that's all you really care about, after all!). It might be worth trying to implement the Hamming distance solution to see how the two ideas differ in practice.


Quero busca informação de uma tabela com EF

Question: Tenho o seguinte código form:
@model Domain.Entities.Tabela1
@using WebUI.HtmlHelpers
@using WebUI.Extensions
@{
    ViewBag.Title = "Tabela";
    Layout = "~/Views/Shared/_Master.cshtml";
}

                <form class="form" name="tabela1Form" ng-submit="save(tabela1)" novalidate style="width: 700px; margin-left: auto; margin-right: auto;">

                            Nome:
                                <input type="text" name="name" ng-model="tabela1.name" />

//Aqui eu gostaria de busca a informação
<input type="text" name="name" ng-model="tabela2.medida" />

Meu Entities Tabela1:
[Table("Tabela1")]
    public class Tabela1
    {
        [Key]
        public int tabela1ID{ get; set; }

        //Strings
        [Required(ErrorMessage = "O campo \"Nome\" é obrigatório")]
        public string Name { get; set; }
        [Required(ErrorMessage="O campo \"Unidade de Medida\" é obrigatório")]
        public string medida{ get; set; }

        //Collections
        public ICollection<Coleçao> campo { get; set; }

        public tabela1()
        {
            campo= new HashSet<Coleçao>();
}

Entitie tabela2:
public class tabela2
    {
        public static tabela2 Default = new tabela2();

        [Key]
        public int tabela2ID { get; set; }
        public string Unit { get; set; }
        [Required(ErrorMessage = "Digite um símbolo da unidade de medida")]
        public string Symbol { get; set; }

    }

ListView tabela1
 public class tabela1ListViewModel : PaginationViewModel
    {
        public IEnumerable<tabela1> tabela1{ get; set; }
    }

Meu controle:
  public ActionResult Newtabelar()
    {
        return View("tabelaForm");
    }

[Permission(Path = IndicatorPath.tabela, Permission = PermissionType.ReadWrite)]
public ActionResult EditItabela(int tabelaid, bool onlyRead = false)
{
    var tabela = tabela1Repository
        .tabela1
        .Include(x => x.tabela3)
            .Include(x => x.tabela4)
            .Include(x => x.tabela5)
            .Include(x => x.tabela6)
        .FirstOrDefault(x => x.tabela1id == tabela1id);

    ViewBag.OnlyRead = onlyRead;

    return View("tabela1Form", tabela);
}

Bom a tabela1 um ele busca ok, porém a tabela2 quero jogar os campo que ela tem em um select no form ele não busca, minha view foi feita com angular, como devo proceder para resolver esse problema. obrigado desde já.
Comment: Como assim "não busca", pode explicar melhor? Dá erro? Qual código você está usando para obter os valores da tabela?
Comment: não consigo trazer as informação da tabela2 para o campo desejado.
Comment: A tabela1 tem relação com outras duas e a tabela2 não.
Comment: O que exatamente você quer acessar, que não esta conseguindo?
Comment: eu quero acessa o campo unit da tabela2, nao sei se pelo angulajs que eu pego as informação e colocar no
Answer: Você poderá usar uma ViewModel:
public class ViewModel1
{
   public Tabela1 tabela1 { get; set; }
   public Tabela2 tabela2 { get; set; }
}

Action:
public ActionResult Index()
{
    var viewModel = new ViewModel1();

    // Preencha as propriedades do objeto viewModel1

    return View(viewModel);
}

Dai você poderá usar o model tabela2 na sua View.
Comment: Vou tentar la obrigado
Comment: infelizmente  não conseguir implementar o código
Comment: qual foi a dificuldade?
Comment: Preencha as propriedades do objeto viewModel1
Comment: As propriedades são tabela1 e tabela2, você deve instancia-las, preencher os objetos como desejar, e depois usar na sua view


Implement insertion sort in c++ using Stack or Queue?

Question: Classical insertion sort algorithm with array is
<code>void insertion_sort (int arr[], int length){
        int j, temp;

    for (int i = 0; i < length; i++){
        j = i;

        while (j > 0 && arr[j] < arr[j-1]){
              temp = arr[j];
              arr[j] = arr[j-1];
              arr[j-1] = temp;
              j--;
              }
        }
}
</code>
So should it implemented by using stack or queue?
Comment: I'd be curious how you think you would do that.
Comment: It's not possible to sort with a single stack. It is possible to sort with a single queue with something like bubble sort, using O(1) space to hold a single element. With 2 stacks, something like bubble sort can be implemented. With 2 queues or 3 stacks, a bottom up merge sort can be used. In the case of 3 stacks, a polyphase bottom up merge sort is faster, but more complicated. Because ordering is reversed when moving data from stack to stack, the program needs to keep track if it should be doing ascending or descending sequences, adding to the complication.
Answer: If you use a vector, you gain the performance that all the memory you're working with is contiguous, but lose performance because you have to copy.
If you use a linked list of any type, you gain because you don't have to copy, but you lose because your memory is scattered all over the place.
As such, this will depend on the number of items being sorted, the processor cache, and probably a whole host of other things.
Given that this sorting algorithm is known to be slow for any numbers of N, the correct solution is to not worry about performance at all and just use std::sort.


How can I make my script run from executable python file on Unix if it uses functions imported from other files? (ModuleNotFoundError)

Question: I made a script to validate and clean a complex DataFrame with calls to a database. I divided the script into modules. I import them frequently between files to use certain functions and variables that are spread across the different files and directories.
Please see image to see how files are distributed across directories:
Directory structure

An example would look like this:
# Module to clean addresses: address_cleaner.py
def address_cleaner(dataframe):
...
return dataframe

# Pipeline to run all cleaning functions in order looks like: pipeline.py
from file1 import function1
...
def pipeline():
df = function1
...function2(df)
...function3(df)
...
return None

# Executable file where I request environment variables and run pipeline: exe.py
from pipeline import pipeline
import os
...
pipeline()
...

When I run this on Unix:
% cd myproject
% python executable.py

This is one of the import cases, which I import to avoid hardcoding environment variable string names:
File "path/to/executable.py", line 1, in <module>
from environment_constants import SSH_USERNAME, SSH_PASSWORD, PROD_USERNAME, PROD_PASSWORD
ModuleNotFoundError: No module named 'environment_constants

I get a ModuleNotFoundError when I run executable.py on Unix, that calls the pipeline shown above and it seems as if all the imports that I did between files to use a function, variable or constant from them, especially those in different directories didn't reach to each other. These directories all belong to the same parent directory "CD-cleaner".
Is there a way to make these files read from each other even if they are in different folders of the script?
Thanks in advance.
Comment: This is not a [mcve], please post code and error message as text
Answer: Either create proper python modules that you can install and manage with pip or (easier) just always use your root as your working directory. Set the import paths accordingly and then just run the file from the root folder such as python generate/generate_dataframe.py when you are in the joor-cd-cleaner directory.
Comment: Okay, I see what you mean. My intention was to create a pipeline function that called each individual function, which in turn they each call to some file in the constants directory, and then run the pipeline function from an executable file. I use the paths mainly to locate the files I want to process and the where I want to output them. Thanks for your quick reply. I will try to implement what you mention above.
Comment: well you can also use Pyinstaller https://datatofish.com/executable-pyinstaller/ to handle all of this for you.
Comment: You can also either set the working directory or import the files from paths that you create using the path of the pipeline file right now. To get this path, see https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory


use taxonomy terms as values for radio buttons by code

Question: I've built a function for select / checkboxes but I can't get it working for radio buttons.
/**
 * helper function to get taxonomy term options for select widget
 * @arguments
 * @return array of select options for form
 */
function popover_get_tax_term_options($machine_name){
    //$options = array( '0' => '');

    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;

    $options_source = taxonomy_get_tree($vid);

    foreach($options_source as $item ) {
        $key = $item->tid;
        $value = $item->name;
        $options[$key] = $value;
    }

    return $options;
}

Calling this in a form hook works with: ( shows all terms )
$form['third']['field_functioncat'] = array(
    '#type' => 'checkboxes',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
);

But when I call it with radio it doesn't work: ( only shows the title with 1 radio button )
 $form['third']['field_functioncat'] = array(
    '#type' => 'radio',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
  );

Answer: #options

values must be in array: http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
example:
'#options' => array(
            0 => t('None'),
            1 => t('Team'),
            2 => t('Business'),
            3 => t('Talent'),
        ),

Comment: did you even read the question? In my question the values returned to `#options` **is** an array and besides that the answer is within my question...
Answer: Hmm why didn't I see this... I used radio instead of radios.
Changed the code and now it works:
$form['third']['field_functioncat'] = array(
    '#type' => 'radios',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
  );


C#: serialize and deserialize XML with different class name

Question: I am getting XML from sql server and i am able to deserialize it with proper Human class.
public class Human
{
public string name {get;set;}
}

after giving value for name property i want to serialize it with different root name, because i want to deserialize it again with new class name
public class Boy
{
public string name {get;set;}
}

please give a solution
Comment: "please give a solution"? That's not how StackOverflow works. Please show us what you tried, and why that didn't work first. What errors are you getting, what result are you expecting and what is the actual result at the moment? It's much easier to help if we know what problems you are facing.
Comment: You need three classes : Human, Boy, and name.  You can use the same name class in both Boy and Human.
Answer: You can change the root element name, pass in the serializer the XmlRootAttribute parameter.
var human = new Human { name = "Smit" };

var xs = new XmlSerializer(typeof(Human), new XmlRootAttribute("Boy"));

using (var fs = new FileStream("test.xml", FileMode.Create))
    xs.Serialize(fs, human);

Comment: If you construct an `XmlSerializer` using an `XmlRootAttribute`, you must cache the serializer for reuse later, or else you will have a severe resource leak.  See [the documentation](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) and also [XmlSerializer Performance Issue when Specifying XmlRootAttribute](https://stackoverflow.com/questions/1534810) or [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/questions/23897145).


How to put constants in React components, wrapped in recompose

Question: How do you write a component specific constant, STATUS, that you can set this.state.status? I think the problem is the this context. If the this.STATUS is hardcoded in strings, it works.
import { compose } from 'recompose';
import React, { Component } from 'react';

class TestComponent extends Component {
    static propTypes = {};

    // can you put the STATUS constant on the component?
    static STATUS = {
        SENT: 'SENT',
        ERROR: 'ERROR',
    };

    state = { status: null };

    // functions cannot use this.STATUS
    f = () => {
        this.setState({status: this.STATUS.SENT});
        // undefined is not an object (evaluating '_this.STATUS.SENT')
    }

    render() {
        const { msg } = this.statusMessage();
        return ();
    }

}

export default compose(
  withRouter,
  connect(() => ())
)(TestComponent);

Answer: Because STATUS is a static property of the class, you have to access it as follows:
this.constructor.STATUS.SENT

You can access it via this.status if you declare it as a property of the instance:
STATUS = {
  SENT: 'SENT',
  ERROR: 'ERROR',
};

or via a getter:
get STATUS() {
  return {
    SENT: 'SENT',
    ERROR: 'ERROR'
  };
}

Answer: Why you don't set directly SENT and Error into your state ?
Like this :
this.setState({
 SEND: 'SENT'
 ERROR: 'ERROR'
 status: null
});

And after you set your status directly like this :
f = () => {
    const { SENT } = this.state
    this.setState({status: SENT});
}

Cheers


TableRow adicionado via programa nao esta trazendo todos os campos!

Question: Estou tentando fazer um ScrollView - TableLayout - TableRow via programa, porem usando um Layout XML como base dos dados internos das TableRows.
Acontece que sempre que tento adicionar o texto do ultimo campo (mensagem) deste layout ou somente inflo o layout, ele faz sumir algumas definicoes que estao direto no xml e o campo dt_envio deixa de aparecer.
Devo estar fazendo alguma coisa errada, mas nao consigo encontrar o erro!
Alguem poderia me ajudar?
fragment_comunicado.xml

<LinearLayout
    android:layout_width="170dp"
    android:layout_height="120dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/logoEscola"
        android:layout_width="170dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:src="@drawable/logo_escola" />
</LinearLayout>

<FrameLayout
    android:id="@+id/content_frame_comunicado"
    android:layout_width="match_parent"
    android:layout_height="290dp"
    android:layout_marginEnd="20dp"
    android:layout_marginStart="20dp">
</FrameLayout>

fragment_comunicado_tablerow.xml

<ImageView
    android:id="@+id/img_remetente"
    android:layout_width="65dp"
    android:layout_height="71dp"
    android:gravity="center"
    android:src="@drawable/ic_chat" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_seta_close" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/remetente"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:singleLine="true"
                android:text="Remetente Remetente Remetente Remetente Remetente"
                android:textColor="@color/azul_painel"
                android:textSize="7pt"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/dt_envio"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="right"
                android:text="99-99-9999"
                android:textSize="5pt"
                android:textStyle="italic" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/assunto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="Assunto Email"
            android:textColor="@color/azul_painel"
            android:textSize="6pt"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/mensagem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="Inicio Email"
            android:textColor="@color/azul1_painel"
            android:textSize="6pt"
            android:textStyle="bold|italic" />

    </LinearLayout>

</LinearLayout>

FragmentComunicado.java
public class FragmentComunicado extends Fragment{

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    final View rootView = inflater.inflate(R.layout.fragment_comunicado, container, false);
    ((MenuPrincipal)getActivity()).setActionBarTitle("Comunicado");

    //** Fazer Chamada pesquisa dos comunicados por: aluno e ano

    FrameLayout fl = (FrameLayout) rootView.findViewById(R.id.content_frame_comunicado);
    fl.removeAllViews();

    ScrollView sv = new ScrollView(rootView.getContext());
    FrameLayout.LayoutParams lpsv = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    sv.setLayoutParams(lpsv);

    TableLayout tl = new TableLayout(rootView.getContext());
    TableLayout.LayoutParams lptl = new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    tl.setLayoutParams(lptl);
    sv.addView(tl);

    for (int i = 1; i <10; i++){
        TableRow tr = new TableRow(rootView.getContext());
        tl.addView(tr);

        View tablerow = inflater.inflate(R.layout.fragment_comunicado_tablerow, tr, false);

        ImageView img_remetente = (ImageView) tablerow.findViewById(R.id.img_remetente);
        img_remetente.setImageResource(R.drawable.logo_escola);

        TextView remetente = (TextView) tablerow.findViewById(R.id.remetente);
        remetente.setText("Coord. Educacao Infantil");

        TextView dt_envio = (TextView) tablerow.findViewById(R.id.dt_envio);
        dt_envio.setText("02/01/2016");

        TextView assunto = (TextView) tablerow.findViewById(R.id.assunto);
        assunto.setText("Inicio Curso de Ferias");

        TextView mensagem = (TextView) tablerow.findViewById(R.id.mensagem);
        mensagem.setText("Bom dia Srs Pais, Nosso curso de ferias inicia-se cheio de atividades para nossos pequenos!!! Nesta semana teremos aventura no zoologico");

        tr.addView(tablerow);

    }

    fl.addView(sv);

    return rootView;

}
}

Answer: Oie pessoal,
Era questao de "tirar as orelhas dos olhos" mesmo.
Quando montei minha TableRow via programa, esqueci de montar o layout_height e o layout_width. Assim que montei, funcionou perfeitamente. :D


"Track Event" is seen in Console (GA Debug) but network request isn't seen in Network Panel

Question: I am confused with the track event issue.
<code>//_gaq.push(['_trackEvent', 'Cat', 'Act', 'Label', 1.1]);
_gaq.push(['_trackPageview', '/new']);
</code>
This is working, I can see this in GA Debugger:
<code>_gaq.push processing "_trackPageview" for args: "[]":  ga_debug.js:18
Track Pageview ga_debug.js:18
Tracking beacon sent!
</code>
And I can see the __utm.gif request in Network Panel.
But when I changed the code to :
<code>_gaq.push(['_trackEvent', 'Cat', 'Act', 'Label', 1.1]);
//_gaq.push(['_trackPageview', '/new']);
</code>
Here is the output in console from GA debugger:
_gaq.push processing "_trackEvent" for args: "[Cat,Act,Label,1]":  ga_debug.js:18
Track Event
But I never see a 'Tracking beacon sent!'. And I cannot see a __utm.gif request in Network Panel. After waiting for days, I did not see any records in the GA Report. So I am very sure it's never sent.
Am I doing anything wrong in this case? Thanks very much for any kind of help!
UPDATE:
I finally tested a couple of times and knew:
The value passed to Ga MUST BE AN INT type. So 1.1 is not working but 1 is working.
I think GA Debugger should add a warning and output it in the console :)
Comment: You should post an answer with the answer about the INT type; otherwise, this question appears as if it is unanswered and won't help others solve the same problem.
Answer: UPDATE:
I finally tested a couple of times and knew:
The value passed to Ga MUST BE AN INT type. So 1.1 is not working but 1 is working.
I think GA Debugger should add a warning and output it in the console :)
Answer: You could check the tag implementation using the chrome extension called Trackie


Como redirecionar site para outra pasta no nivel do public_html usando htaccess

Question: Tenho um site criado e os arquivos estão na pasta public_html. Criamos um novo na pasta 2018 que está no mesmo nível hierárquico da public_html
Como posso fazer para quando acessar o dominio.com.br, ele acesse a pasta 2018 e não a public_html?
Answer: Felizmente, por segurança, você não pode redirecionar por meio de .htaccess a um diretório de nível superior ao de seu document root. Por conseqüência, um diretório no mesmo nível não pode ser acessado.
Existem, claro, alternativas para solucionar seu problema. Cito duas:

Primeiro
Você pode colocar o diretório 2018 dentro do diretório public_html. Com uma configuração do .htaccess (vide abaixo), você pode fazer o site apontar para o conteúdo deste sub-diretório 2018. Veja:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^exemplo\.com\.br$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.exemplo\.com\.br$
RewriteCond %{REQUEST_URI} !nome_diretorio/
RewriteRule (.*) /nome_diretorio/$1 [L]

Basta trocar exemplo\.com\.br pelo domínio desejado. Troque também nome_diretorio pelo diretório do sítio reformulado - neste caso, 2018.
Segundo
Você pode pedir para o controlador do host que permita mais um diretório para seu site. Isso é improvável e pouco prático para ambos.
Comment: entendi, vou jogar dentro do public então, valeu!


Crystal Report 2008 Add Command Where Clause parameter

Question: Crystal Version - Crystal Reports 2008 Business Objects - XI
I have written a query to populate a subreport and want to pull in a parameter to that query based on input from a user. My question is, what is the correct syntax I need to put in the first line of the 'Where' clause to accept the parameter?
I created a parameter in Add Command it is called PickDate
Here is the query I am using in Crystal Reports:
   select
            table2.book_no,
            table2.time_stamp,
            table2.restdate,
            a.timestamp,
            a.event_type,
            a.status,
            a.people,
            a.new_date,
            a.comments,
            a.operator_id

    from table1 a, table2
    where table1.book_no  = table2.outage_no

I have tested the query, it is pulling all the data, now I just need help adding parameter to prompt user to enter datatime.
Comment: Did you try using the Select Expert in the subreport?  You should be able to say field = {?PickDate}
Comment: @Andrew `edit` thanks alot, that worked, I made mistake it should be field > `{?PickDate}
Answer: Did you try using the Select Expert in the subreport? You should be able to say field = {?PickDate}


In Messa Di Voce, I can only get loud by a little - not a lot. What should I do?

Question: I recently started practicing Messa Di Voce on certain notes.
I'm trying to do the exercise correctly, which means that if I start a note on an "AH" for instance in low volume, I need to get louder by only increasing the amount of air while keeping the entire configuration of the vocal tract stable.
I can do this exercise only to some degree of loudness. For instance if I started on volume level of 10% (out of 100), I can perhaps increase it only to about 30%, and I can't get louder than that without breaking the entire configuration and starting to strain in order to sound louder.
What should I do?
Work on breathing?
Answer: I'd very much recommend against "increasing the amount of air" as image since air use is a byproduct of efficient singing more than its driving factor.  Instead I'd work on making the air work harder in producing sound.  Opening up your head and chest resonances more, improving vocal closure (with the resultant decrease in the amount of air).
Basically if you put your hand in the vicinity to your mouth, you don't want to feel your breath when doing a mezza di voce but you do want the tingling of the sound.
Resonance is not something that starts at your vocal folds: to be effective you need to admit it downwards into your chest.  The more air you use, the less effective your chest becomes as a resonator since a large air flow precludes the sound energy from travelling downwards where it can contribute to the buildup of resonance.
Resonance makes your vocal folds work against a larger acoustical resistance, transferring their energy better.  If all your conscious change is letting more air out, they will work against less resistance and retain more of their vibrational energy (which makes them more rather than less likely to overload) instead of emitting it as acoustic sound.
Answer: Working on breathing will always help, as you will retain the air and that will allow you to focus on other things without worrying about that.
I would try some exercises right before doing the Messa Di Voce exercise. Try doing runs "in Ney/Mey/Ñei" (I mean using your resonators) like C3-E3-G3-C4-C4-C4-C4-G3-E3-C3, and going up to G4 or your desired note. Then try the same runs but in a more "belting" way (open more your jaw but still follow that "Ney path").
After that, try the Messa Di Voce exercise, focusing on this path that you've worked on.


How to use doMock in jest?

Question: I find that when using jest.doMock instead of jest.mock to mock a function (I will need to create multiple mock implementations for the same function in different it blocks), I find that the test fails with
Error
expect(jest.fn()).toBeCalled()

Expected mock function to have been called.

Also, if I require the module at the top of the test instead of doing it within the same it block, it gives me a different error:
expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function headObject]

Code

headObject(Collaborator being mocked)
// NOT IMPLEMENTED YET
module.exports = function() {}

Test code
it('checks to see if a resource exists when given a threshold', () => {
  jest.doMock('../s3/headObject', () => {
    return jest.fn(() => {})
  })
  const headObject = require('../s3/headObject')
  handler(event.correct_uses_propertyId_withExplicitThreshold, {}, () => {})
  expect(headObject).toBeCalled()
})

Source Code
const headObject  = require('../s3/headObject')
  module.exports = async function(event, context, callback) {
   headObject()
}

Previously
I used environment variables to change the mock implementation using mocks within __mocks__ like this:
const result = jest.genMockFromModule('../realModule.js')
const mockResponse = require('../../eventMocks/realModuleName/fixture.json')

function mock (bearerToken, address) {
  if (process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE) {
    return {
      history: []
    }
  }
  return mockResponse
}

result.mockImplementation(mock)

module.exports = result

and in my test, I would:
it('does not store empty results in S3', () => {
  process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE = true
  const res = LambdaTester(handler)
  .event(event.correct_uses_address)
  .expectResult(r => {
    expect(r.statusCode).toEqual(404)
    const body = JSON.parse(r.body)
    expect(body.message).toEqual(NO_ESTIMATE)
  })

  process.env.DONT_USE_TEST_ONLY_EMPTY_ESTIMATE = false
  return res
})

Answer: Late to the party.... doMock is a pain.
We use this setup within our tests:
// import function from module you want to mock
import getClientVersion from '../api/clientVersion';

// mock the whole module
jest.mock('../api/clientVersion');

// within a test, overwrite that specific function
getClientVersion.mockResolvedValueOnce(1);

Good thing with this is, that you can easily change the setup in each test.
Hope this helps someone who stumbles upon this questions
Comment: adding a downvote because, while this is useful, it doesn't answer the question that was asked
Comment: I was confused when I searched for `doMock` (since I had used it before) and didn't find it in the jest docs  This seems like a reasonable strategy!

How to use doMock in jest?


Disabling CKEditor in comments

Question: Does anyone know of a way to force plain text mode in comments for all roles?
Edit: is it in any way possible to do so through CSS? Thanks!
Answer: Try
function MYMODULE_form_alter (&$form, &$form_state, $form_id)
{
  // comments
  // http://api.drupal.org/api/drupal/modules--comment--comment.module/function/comment_form/6

  if ($form['#id'] == 'comment-form') {
    $form['comment_filter']['format'] = array(); // nuke wysiwyg from comments
  }
}

Comment: Please excuse my ignorance but where exactly does this function go? Thanks! Jane
Comment: This is an example of a hook that would go inside a custom module.  Though the term "custom module" may sound daunting, it is a fairly common task.  The best place to start is http://drupal.org/developing/modules
Comment: OK thanks! Will try, though yes it does sound quite daunting... :)
Answer: Take a look at admin/settings/ckeditor/editg. There you can change the visibility settings by field path (something like firstname.lastname@example.com_id). That should work.
Comment: What's the *editg* in `admin/settings/ckeditor/editg` ?! This takes me to the same page as `admin`
Answer: For Drupal 6, I would recommend the Better Formats module to control this. It allows to set a default input format on comments, but also allows different defaults per role and per content type. The Drupal 7 version is in development, but its status is a bit unclear at the moment because some of the features are now in core.
Comment: Yeah I have Better Formats (it's a Drupal 6 site) but either I am using it wrong or for some reason it's failing to disable ckeditor in comments... at least for the roles that have permission to use ckeditor.
Answer: I had the same problem in D7. To fix it I changed the default input format of comments to Plain Text (ckeditor did not have a profile for that input format). This removed ckeditor from comments.
To remove the input format hints I installed the better formats module.
Update: I just noticed that your question was how to force plain text mode for all roles. To simplify I would just change the way the input format process text from "filtered text" to "plain text".
Answer: I did it this way. I fixed input format to a non wysiwyg one and denied access of it.
/**
 * Implements hook_comment_form_alter().
 */
function comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['comment_body']['#after_build'][] = 'MYMODULE_customize_comment_form';
}

/**
 * Comment body after-build function.
 */
function MYMODULE_customize_comment_form(&$form) {
  // Hide text-format selector in comment form and fix format to filtered_html
  $form[LANGUAGE_NONE][0]['format']['format']['#value'] = 'filtered_html';
  $form[LANGUAGE_NONE][0]['format']['format']['#access'] = FALSE;
}

Disabling CKEditor in comments


Erro Data Report Group Footer VB6

Question: Opa!
Preciso adicionar um campo a mais num relatório data report do vb6 como na imagem

A conexão com o banco é feito via Driver ODBC 5.1 com banco MySQL.
Uso este SQL para geração do relatório:
SELECT *, venda.TotalS AS total_venda_agrupa, venda.totalc AS valor_total_venda, venda_forma_pagamento.descricao AS nome_forma_pagamento, vendaesc.QUANTIDADEprod as qtd, (vendaesc.QUANTIDADEprod * vendaesc.ValUniProd) As total_soma  FROM vendaesc,venda INNER JOIN venda_forma_pagamento ON venda_forma_pagamento.cod = venda.forma_pagamento where vendaesc.data='2016-03-30' AND venda.cod = vendaesc.venda   order by venda.cod

O que faz é apenas relacionar as tabelas e trazer os dados, coisa simples.
O novo campo é um RptFunction dos componentes do data report.
Antes de tentar adicionar este campo, o relatório não tinha nenhum Grupo Header/Footer, foi preciso adicionar para o novo campo não ficar na listagem de itens do relatório e sim abaixo de cada grupo de lista.
Ao adicionar este grupo, começou a dar este erro,
report section do not match data source

Algum sabe como solucionar isso, o que tem de errado?
Answer: Tente adaptar para uso do SHAPE APPEND assim:
If RSTest Is Nothing Then
    Set RSTest = New ADODB.Recordset
End If
If RSTest.State = adStateOpen Then
    RSTest.Close
End If

'Two tables
SQL = "SHAPE {SELECT vendaesc.venda as venda,vendaesc.tipo as tipo,vendaesc.prod as prod, vendaesc.ValUniProd as valuniprod, vendaesc.QUANTIDADEprod as qtd, (vendaesc.QUANTIDADEprod * vendaesc.ValUniProd) As total_soma  FROM vendaesc} AS Level1 " & _
        "APPEND ({SELECT venda.forma_pagamento_detalhe_nome as forma_pagamento_detalhe_nome,venda.forma_pagamento_parcelas as forma_pagamento_parcelas, venda.TotalS AS total_venda_agrupa, venda.totalc AS valor_total_venda, venda_forma_pagamento.descricao AS nome_forma_pagamento from venda INNER JOIN venda_forma_pagamento ON venda_forma_pagamento.cod = venda.forma_pagamento where venda.cod = vendaesc.venda order by venda.cod } AS Level2 " & _
            "RELATE venda.cod to venda.cod)"

RSTest.Open SQL, gConexao, adOpenStatic, adLockOptimistic
Set RptFPagamentoDetalhe.DataSource = RSTest

With RptFPagamentoDetalhe.Sections("Section1").Controls
    .Item("Text2").DataMember = "Level1"
    .Item("Text2").DataField = "venda"

    .Item("Text1").DataMember = "Level1"
    .Item("Text1").DataField = "tipo"

    .Item("Text3").DataMember = "Level1"
    .Item("Text3").DataField = "prod"

    .Item("Text4").DataMember = "Level1"
    .Item("Text4").DataField = "qtd"

    .Item("Text6").DataMember = "Level1"
    .Item("Text6").DataField = "ValUniProd"

    .Item("txtTotal").DataMember = "Level1"
    .Item("txtTotal").DataField = "total_soma"

    .Item("Text5").DataMember = "Level2"
    .Item("Text5").DataField = "nome_forma_pagamento"

    .Item("Text7").DataMember = "Level2"
    .Item("Text7").DataField = "forma_pagamento_detalhe_nome"

    .Item("Text8").DataMember = "Level2"
    .Item("Text8").DataField = "forma_pagamento_parcelas"
End With

Ta me retornando data filed empty

Erro Data Report Group Footer VB6


Puxar dados em JSON

Question: Estou com uma duvida sobre JSON.
Preciso puxar as informações que está dentro do array.
Porem não possui a referencia que seria o nome de champion que fica dentro da data que preciso localizar, a unica coisa possui é o key.
Base de JSON:
{
   "type":"champion",
   "format":"standAloneComplex",
   "version":"7.18.1",
   "data":{
      "Aatrox":{
         "id":"Aatrox",
         "key":"266",
         "name":"Aatrox",
         "title":"a Espada Darkin",
         "image":{
            "full":"Aatrox.png",
            "sprite":"champion0.png",
            "group":"champion",
            "x":0,
            "y":0,
            "w":48,
            "h":48
         }
      },
      "Viktor":{
         "id":"Viktor",
         "key":"112",
         "name":"Viktor",
         "title":"o Arauto das Máquinas",
         "image":{
            "full":"Viktor.png",
            "sprite":"champion4.png",
            "group":"champion",
            "x":0,
            "y":0,
            "w":48,
            "h":48
         }
      }
   }
}

Estou utilizando linguagem javascript com jquery. Ao puxar os dados não localiza. Como resolver isso?
$.ajax({
    type:'GET',
    url: 'http://ddragon.leagueoflegends.com/cdn/7.18.1/data/pt_BR/champion.json',
    dataType:'json',
    success: function(data) {
        var arr = [];
        arr.push(data);
        for(var i=0; i<arr.length; i++) {
            if(arr[i].data.key === 266) {
                console.log(arr[i].data.name);
            }
        }
    },
    error: function(data) { }
});

Answer: Tens de iterar as chaves da propriedade data.
Podes usar o Object.keys ou o for(var key in object).
Um exemplo seria:

var data = {
  "type": "champion",
  "format": "standAloneComplex",
  "version": "7.18.1",
  "data": {
    "Aatrox": {
      "id": "Aatrox",
      "key": "266",
      "name": "Aatrox",
      "title": "a Espada Darkin",
      "image": {
        "full": "Aatrox.png",
        "sprite": "champion0.png",
        "group": "champion",
        "x": 0,
        "y": 0,
        "w": 48,
        "h": 48
      }
    },
    "Viktor": {
      "id": "Viktor",
      "key": "112",
      "name": "Viktor",
      "title": "o Arauto das Máquinas",
      "image": {
        "full": "Viktor.png",
        "sprite": "champion4.png",
        "group": "champion",
        "x": 0,
        "y": 0,
        "w": 48,
        "h": 48
      }
    }
  }
};
var arr = []; // não sei bem porque precisas disto? é só para o exemplo pois já tens outra "arr no código que vais acrescentar com "data"?
arr.push(data);
for (var i = 0; i < arr.length; i++) {
  var obj = arr[i].data;
  Object.keys(obj).forEach(function(prop) {
    if (obj[prop].key == 266) {
      console.log(obj[prop].name);
    }
  });
}

Repara que o teu JSON retorna o valor de key em String! Por isso não podes usar === se comparas com um numero. Ou então usa uma string também assim: if (obj[prop].key == '266') {
Comment: Com a sua ajuda resolveu o meu problema!

Mas quando vou criar uma função, a variável **id** não reconhece.
Só para avisar não manjo muito em javascript, estou na fase de aprendizagem.
Comment: Estou aqui chutando meu celebro pra entender como vou colocar a variável dentro do function. Não estou conseguindo entender a logica.
Comment: @AugustoJunior qual é o código que precisa dessa variável? É uma função? Coloca aqui um jsFiddle com o código para ver.
Answer: Consegui fazer funcionar callback. Mas fiz uma função chamada champion() onde vai apenas acrescentar id, localizar o nome e assim retornar o valor.
Mas este condigo return obj[prop].name; está trazendo resultado como undefined. Ao testar console.log(obj[prop].name) está funcionando perfeitamente. Mas porque o valor retorna como undefined?
function callback(andress, fn){
    $.ajax({
        url: andress,
        type: 'GET',
        dataType: 'json',
        error: function(){},
        success: fn
    });
}

function champion(id) {
    callback('http://ddragon.leagueoflegends.com/cdn/7.18.1/data/pt_BR/champion.json', function(retorno) {
        var arr = [];
        arr.push(retorno);
        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i].data;
            Object.keys(obj).forEach(function(prop) {
                if (obj[prop].key == id) {
                    return obj[prop].name;
                }
            });
        }
    });
}

callback(url+'/lol/summoner/v3/summoners/by-name/'+hash.name+'?api_key='+key, function(retorno) {
    callback(url+'/lol/match/v3/matchlists/by-account/'+retorno.accountId+'/recent?api_key='+key, function(invocador) {
        var itens = '';
        for (var i = 0; i < invocador.matches.length; i++) {
            itens += '
'+champion(invocador.matches[i].champion)+'
';
        }
        $('.partidas_recentes').html(itens);
    });

    $('.mdl-layout-title').text(retorno.name);
});

Puxar dados em JSON


Divergence in spherical coordinates vs. cartesian coordinates

Question: The divergence in spherical coordinates is derived as
$$\nabla\vec A=\frac{1}{r^2}\frac{\partial(r^2A_r)}{\partial r}+\frac{1}{r\sin\theta}\frac{\partial}{\partial\theta}(A_\theta\sin\theta)+\frac{1}{r\sin\theta}\frac{\partial A_\varphi}{\partial\varphi}$$
However, this seems to fail at a simple example. Let's take the identity $\vec F(\vec r):=\vec r$ for example. The divergence of the vector field $\vec F(\vec r)=\begin{pmatrix}x\\y\\z\end{pmatrix}$ in cartesian coordinates is
$$\nabla\vec F(\vec r)=\frac{\partial}{\partial x}F_x(\vec r)+\frac{\partial}{\partial y}F_y(\vec r)+\frac{\partial}{\partial z}F_z(\vec r)=\frac{\partial}{\partial x}x+\frac{\partial}{\partial y}y+\frac{\partial}{\partial z}z=3$$
But in spherical coordinates the vector field would be fined as $\vec F(\vec r)=\begin{pmatrix}r\\\theta\\\varphi\end{pmatrix}$, so the divergence would be:
$$\nabla\vec F(\vec r)=\frac{1}{r^2}\frac{\partial}{\partial r}(r^2\cdot r)+\frac{1}{r\sin\theta}\frac{\partial}{\partial\theta}(\theta\sin\theta)+\frac{1}{r\sin\theta}\frac{\partial}{\partial\varphi}(\varphi)=3+\frac{\sin\theta+\theta\cos\theta}{r\sin\theta}+\frac{1}{r\sin\theta}$$
Which certainly isn't 3:

(Graphic from WolframAlpha)
So what am I doing wrong here?

Edit I successfully managed to completely confuse myself. I think I misunderstood the meaning of $A_r, A_\theta, A_\varphi$ - could anybody explain it to me? In my understanding the following should be true:
$$A_r=\vec A\cdot\hat e_r\qquad A_\theta=\vec A\cdot\hat e_\theta\qquad A_\varphi=\vec A\cdot\hat e_\varphi$$
With the unit vectors for spherical coordinates being as follows:
$$\hat {e} _{r}={\begin{pmatrix}\sin \theta \cos \varphi \\\sin \theta \sin \varphi \\\cos \theta \end{pmatrix}},\qquad \hat {e} _{\theta }={\begin{pmatrix}\cos \theta \cos \varphi \\\cos \theta \sin \varphi \\-\sin \theta \end{pmatrix}},\qquad \hat {e} _{\varphi }={\begin{pmatrix}-\sin \varphi \\\cos \varphi \\0\end{pmatrix}}$$
However, this doesn't make much more sense, as - if I understood it correctly, $\varphi$ and $\theta$ would be $45^\circ$ (and $r=1$) which results in weird basis vectors and doesn't seem to help me.
Comment: no : $\begin{pmatrix}x\\y\\z\end{pmatrix}$ = $\begin{pmatrix}r\sin(\theta)\cos(\phi)\\r\sin(\theta)\sin(\phi)\\r\cos(\theta)\end{pmatrix}$
Comment: @metacolon. Your basis vectors are not defined globally from the Origin. Infact , a coordinate system sometimes don't even need any Origin. And the basis vectors you talk about are actually local basis vector. Basis vectors are defined at the point of interest itself and not at origin.
Comment: 1) It isn't a *definition* of divergence in spherical coordinates. You can derive the spherical version from Cartesian version. If you want to give a definition it should be coordinate free.
Comment: @Mann I adjusted my question accordingly
Comment: And secondly, your two vector field only symbolically looks same but they are actually not the same. Vector field in itself should again be invariant of coordinate system having different representation in different Coordinate system. Try parametric spherical surface equation and see what happens. The $r \cos \theta \cos   \phi ...$
Comment: @Mann but isn't my vector field in both representations simply the identity?
Comment: I am on mobile so I can't give detailed answer. But it seems you are confusing coordinate system with the underlying space. Your vectors, tensors, scalars can exist independently of any coordinate system in a space(say Euclidean space). But the way you want to see those objects is up to you(which coordinate system do you wanna pick). Right now, you are trying to pick two coordinate system to see the *same* vector. But as you can see they don't look the same if you try to plot them. Hence, you are not comparing the same vector fields under different coordinate systems.
Comment: @beelal what do you mean? Isn't this exactly the [definition](https://en.wikipedia.org/wiki/Spherical_coordinate_system) of spherical coordinates?
Comment: @metacolon again it's not the definition. By definition, spherical coordinates are defined as the intersection of three surfaces. r = c1 , theta = c2 and phi = c3 (defined properly for a unique point). What Beelal said is a conversion between spherical and Cartesian coordinate.
Answer: I am updating this answer to try to address the edited version of the question.
A nice thing about the conventional $(x,y,z)$ Cartesian coordinates is everything works the same way. In fact, everything works so much the same way using the same three coordinates in the same way all the time in Cartesian coordinates--points in space, vectors between points, field vectors--that it may be surprising that in just about any other coordinate system different things sometimes work differently from each other.
In Cartesian coordinates, you can identify the components of a point's coordinates with the components of the point's position vector.
And you can get the vector sum of two of those vectors by adding the coordinates:
$$
 \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}
 + \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}
 = \begin{pmatrix} 1+0 \\ 0+1 \\ 0+0 \end{pmatrix}
 = \begin{pmatrix} 1 \\ 1 \\ 0 \end{pmatrix}.
$$
But if you try to describe a vectors by treating them as position vectors and using the spherical coordinates of the points whose positions are given by the vectors, the left side of the equation above becomes
$$
 \begin{pmatrix} 1 \\ \pi/2 \\ 0 \end{pmatrix}
 + \begin{pmatrix} 1 \\ \pi/2 \\ \pi/2 \end{pmatrix},
$$
while the right-hand side of the equation becomes
$$
 \begin{pmatrix} \sqrt2 \\ \pi/2 \\ \pi/4 \end{pmatrix}.
$$
So spherical coordinates are really awkward to do vector operations in. You just can't do it like you can with Cartesian coordinates.
Another thing that's going on with these formulas is we have to make sense of things like $\frac\partial{\partial\theta}.$
If you have something that can vary as $r,$ $\theta,$ and $\varphi$ vary, then
$\frac\partial{\partial\theta}$ is looking for what happens when we hold $r$ and $\phi$ constant but vary $\theta.$
What happens to the location defined by the coordinates $(r, \theta, \varphi)$
if we hold $r$ and $\varphi$ constant but increase $\theta$ is that we move in a "downward" direction perpendicular to the position vector.
Given a starting point $(r, \theta, \varphi)$ for this motion, we define
$\hat{\boldsymbol \theta}$ as the unit vector in that direction.
Similarly, there is a unit vector $\hat{\boldsymbol \varphi}$ in the direction we would travel if we hold $r$ and $\theta$ constant and increase $\varphi.$
There is also a unit vector $\hat{\mathbf r}$ in the direction of constant $\theta$ and $\varphi$ but increasing $r.$
I name these vectors $\hat{\mathbf r},$ $\hat{\boldsymbol \theta},$ and
$\hat{\boldsymbol \varphi}$ because that's how they're named on the first Wikipedia page the question linked to. These are the same vectors named
$\hat e_r,$ $\hat e_\theta,$ and $\hat e_\varphi$ elsewhere.
Unlike the unit vectors $\hat{\mathbf x},$ $\hat{\mathbf y},$ and
$\hat{\mathbf z},$ which are always parallel to the $x,$ $y,$ and $z$ axes,
the unit vectors $\hat{\mathbf r},$ $\hat{\boldsymbol \theta},$ and
$\hat{\boldsymbol \varphi}$ depend on the coordinates of a point
$(r, \theta, \varphi)$ relative to which those vectors are defined.
Specifically,
$$\begin{align}
\hat{\mathbf r} &= \sin\theta \cos\varphi \hat{\mathbf x}
 + \sin\theta\sin\varphi \hat{\mathbf y} + \cos\theta \hat{\mathbf z}, \\
\hat{\boldsymbol \theta} &= \cos\theta \cos\varphi \hat{\mathbf x}
 + \cos\theta \sin\varphi \hat{\mathbf y} - \sin\theta \hat{\mathbf z}, \\
\hat{\boldsymbol \varphi} &= -\sin\varphi \hat{\mathbf x} + \cos\varphi \hat{\mathbf y}.
\end{align}
$$
You can visualize a physical model for these vectors by supposing that the Earth is spherical and is centered at the origin of the coordinate system. Then at any point on the surface of the Earth, $r$ is the Earth's radius,
$\theta$ is the co-latitude (like latitude, but it goes from zero at the north pole to $180$ degrees at the south pole), and $\varphi$ is the longitude.
Then $\hat{\boldsymbol \theta}$ is in the direction of increasing co-latitude, so it points due south;
$\hat{\boldsymbol \varphi}$ is in the direction of increasing longitude, so it points due east;
and $\hat{\mathbf r}$ is in the direction of increasing radius, so it points directly away from the center.
In particular, $\hat{\mathbf r}$ is a unit vector in the exact same direction as the position vector $\vec r,$
and the other two unit vectors are orthogonal to $\hat{\mathbf r}$ and to each other.
This clearly does not work as the basis of a set of position vectors for all the points in a three-dimensional space. If you wanted the vector describing the direction and distance from point $P$ to point $Q,$ do you use the vectors
$\hat{\mathbf r},$ $\hat{\boldsymbol \theta},$ and
$\hat{\boldsymbol \varphi}$ according to how they are defined relative to $P$ or according to how they are defined relative to $Q$?
The answer is (usually) neither, you don't typically use those vectors for that kind of calculation at all.
What those vectors are good for is as an orthonormal basis for things that occur locally at a point: a vector field at that point, the gradient of that field, the divergence of that field, and so forth.
Now if you have a vector field with the value $\vec A$ at some point with spherical coordinates
$(r, \theta, \varphi),$ then we can break that vector down into orthogonal components exactly as you do:
\begin{align}
A_r &= \vec A\cdot\hat{\mathbf r}, \\
A_\theta &= \vec A\cdot\hat{\boldsymbol \theta}, \\
A_\varphi &= \vec A\cdot\hat{\boldsymbol \varphi}.
\end{align}
Now consider the case where $\vec A = \vec r.$ Then $\vec A$ is in the exact same direction as
$\hat{\mathbf r},$ and therefore
$$ A_r = \vec A\cdot\hat{\mathbf r} = \lVert \vec A\rVert \lVert \hat{\mathbf r}\rVert = r. $$
On the other hand, $\vec A$ is orthogonal to each of the vectors
$\hat{\boldsymbol \theta}$ and $\hat{\boldsymbol \varphi},$ so
$$ \vec A\cdot\hat{\boldsymbol \theta} = \vec A\cdot\hat{\boldsymbol \varphi} = 0.$$
In summary, $A_r = r$ and $A_\theta = A_\varphi = 0.$
Moreover, no matter which way you go, $A_\theta$ and $A_\varphi$ both remain zero, so
$$
\frac{\partial}{\partial\theta}(A_\theta\sin\theta)
 = \frac{\partial A_\varphi}{\partial\varphi} = 0.
$$
If you are measuring the field at the point $(1,1,1),$ then $\hat{\mathbf r}$ at that point is
$\hat{\mathbf r} = \frac1{\sqrt3}\hat{\mathbf x} +
\frac1{\sqrt3}\hat{\mathbf y} + \frac1{\sqrt3}\hat{\mathbf y},$
and therefore
$\sqrt3\hat{\mathbf r} = \hat{\mathbf x} + \hat{\mathbf y} + \hat{\mathbf z},$ or in the usual $(x,y,z)$ Cartesian system, the vector $(1,1,1).$
Plugging in the correct values for all three components, the divergence formula gives the result $3.$
Now if you had a field that was not simply a radial field always going directly outward from the center or directly inward toward the center, that is, if there were some field vectors making other angles with the radial vectors, then you would see some non-zero values of $A_\theta$ and $A_\phi,$ and there would be a reason you needed the rest of the formula for divergence. You just happen to have chosen an example in which you have eliminated those components.
If you want a more interesting example, you might try a vector field such as
$\vec A = x \hat{\mathbf x},$ which has non-zero derivatives in all three directions at most points.
Comment: But how's that possible? If, for example, I had the cartesian vector $(1,1,1)$, which would result in the spherical equivalence of $(\sqrt 3, 45^\circ, 45^\circ)$. If I use $F$ as suggested by you, $\vec F(\vec r)$ would be $(\sqrt 3, 0, 0)$, which would (if I'm not mistaken) have the cartesian equivalent of $(\sqrt 3, 0, 0)\neq\vec F(1,1,1)=(1,1,1)$. I'm sure your right with your explanation and I'm getting greatly confused with coordinate systems, but could you maybe elaborate on the mistake I'm making?
Comment: To be more precise, if the other two components are zero, when are they _not_ zero? If all the information is contained in the first variable, $r$, what even is the use of the other two?
Comment: I think you are really confusing some meanings @metacolon. You need to look up the definition I had suggested above.
Comment: @Mann I think I understood it already, but as the answers didn't directly solve the problem, I'm hesitating to mark one as answer
Answer: It is sadly common when dealing with different coordinate systems, such as in this case, not to distinguish the function under consideration from its pullback under a coordinate transformation.
Pullback.
Let me introduce some terminology. Suppose we have sets $A$, $B$, and $C$ along with maps
$$A \xrightarrow{\Phi} B \xrightarrow{u} C.$$
We may then form the composition $u \circ \Phi$ of $u$ with $\Phi$, which is the mapping of $A$ into $C$,
$$A \xrightarrow{u \circ \Phi} C,$$
defined by letting
$$(u \circ \Phi)(a) = u(\Phi(a)) \quad\text{for all}\quad a \in A.$$
We call $u \circ \Phi$ the pullback of $u$ under $\Phi$, sometimes denoted $\Phi^\ast u$. Below we will also denote this map simply by $\tilde u$, thus
$$\tilde u = \Phi^\ast u = u \circ \Phi$$
will all denote the same map in the below considerations. (The trouble arises when people do not distinguish between $u$ and $\tilde u$.)
Spherical Coordinate Example.
Consider now the subset $A$ of $\mathbf{R}^3$ given by
$$A = [0, \infty) \times [0, \pi] \times [0, 2\pi] = \bigl\{ (r, \theta, \phi) : r \ge 0, 0 \le \theta \le \pi, 0 \le \phi \le 2\pi \bigr\}$$
along with the mapping $\Phi$ of $A$ into $\mathbf{R}^3$ given by
$$\Phi(r, \theta, \phi) = \begin{bmatrix} r\sin\theta\cos\phi \\ r\sin\theta\sin\phi \\ r\cos\theta \end{bmatrix}.$$
If for instance $u$ is a mapping of $\mathbf{R}^3$ into $\mathbf{R}$, we call the pullback $\tilde u = u \circ \Phi$ of $u$ under $\Phi$ the representation of $u$ in spherical coordinates.
As an example, suppose $u$ is defined by letting
$$u(x, y, z) = (x^2 + y^2 + z^2)^{\frac 12} \quad\text{for all}\quad (x, y, z) \in \mathbf{R}^3,$$
and let us compute the representation of $u$ in spherical coordinates. For a point $(r, \theta, \phi) \in A$, one has
$$\begin{align*}
\tilde u(r, \theta, \phi)
&= u(\Phi(r, \theta, \phi))
= u\bigl( r\sin\theta\cos\phi, r\sin\theta\sin\phi, r\cos\theta \bigr) \\
&= \bigl( (r\sin\theta\cos\phi)^2 + (r\sin\theta\sin\phi)^2 + (r\cos\theta)^2 \bigr)^{\frac 12} \\
&= r.
\end{align*}$$
Thus, $u$ is the mapping on $\mathbf{R}^3$ sending the point $(x,y,z)$ to $(x^2 + y^2 + z^2)^{1/2}$, whereas $\tilde u$ is the mapping on $A$ sending the point $(r, \theta, \phi)$ to $r$, i.e., projection on the first factor.
Observe that $u$ looks a lot simpler in spherical coordinates! It is therefore of interest to see if we can compute such quantities as the gradient $\nabla u$ of $u$ in terms of the gradient $\nabla\tilde u$ of $\tilde u$ and the mapping $\Phi$.
Vector Fields in Spherical Coordinates.
The representation of a vector field in spherical coordinates is worked out in the same way. Consider your example $F$ mapping a point $(x,y,z)$ in $\mathbf{R}^3$ to itself:
$$F(x,y,z) = \begin{bmatrix} x \\ y \\ z \end{bmatrix}.$$
Its pullback under $\Phi$ at a point $(r, \theta, \phi) \in A$ is given by
$$\begin{align*}
\tilde F(r, \theta, \phi)
&= F(\Phi(r, \theta, \phi)) \\
&= F\bigl( r\sin\theta\cos\phi, r\sin\theta\sin\phi, r\cos\theta \bigr) \\
&= \begin{bmatrix} r\sin\theta\cos\phi \\ r\sin\theta\sin\phi \\ r\cos\theta \end{bmatrix}.
\end{align*}$$
Note carefully that although $F$ is the identity mapping on $\mathbf{R}^3$, the representation $\tilde F$ of $F$ in spherical coordinates is not the identity mapping on $A$! However, an interesting question is whether one can recover $\operatorname{div} F$ from $\tilde F$ and $\Phi$, which is what the formula you provided is meant to do.
As for the notation «$F_r$, $F_\theta$, $F_\phi$», one means the projection of $\tilde F$ along the directions of the unit vectors $e_r$, $e_\theta$, and $e_\phi$, respectively. (It would be better to denote these by $\tilde F_r$, $\tilde F_\theta$, $\tilde F_\phi$, but we will not do so below.) Thus at a point $(r, \theta, \phi)$, one means for instance
$$F_r(r, \theta, \phi) = \tilde F(r, \theta, \phi) \cdot e_r(r, \theta, \phi),$$
where we have explicitly evaluated $e_r$ at $(r, \theta, \phi)$.
It is an exercise to show that
$$F_r(r, \theta, \phi) = r, \quad F_\theta(r, \theta, \phi) = 0, \quad F_\phi(r, \theta, \phi) = 0.$$
Using this, the formula you provide for the divergence of $F$ in spherical coordinates becomes
$$\begin{align*}
(\operatorname{div} F)(r\sin\theta\cos\phi, r\sin\theta\sin\phi, r\cos\theta)
&= (\operatorname{div} F)(\Phi(r, \theta, \phi)) \\
&= \frac{1}{r^2}\frac{\partial}{\partial r} \bigl( r^2 F_r(r, \theta, \phi) \bigr) \\
&= \frac{1}{r^2} \frac{\partial}{\partial r}\bigl( r^3 \bigr) \\
&= 3,
\end{align*}$$
which is correct.
Answer: You didn't transform your coordinates properly:
$$
\left [\begin{array}{c}
x\\
y\\
z\\
\end{array} \right]  \longrightarrow  \left[\begin{array}{c}
\rho \sin\theta\cos\phi\\
\rho\sin\theta\sin\phi\\
\rho\cos\theta\\
\end{array}\right]
$$


How to show discontinuity of a complex function at given points?

Question: Let $f:\mathbb C \to \mathbb C$ be defined by $f(z)=\sqrt{z}=\sqrt{r}e^{i arg_\alpha(z)/2}$ where $arg_{\alpha}(z)$ is the angle in $(\alpha,\alpha+2\pi]$ and $A=\{z\in \mathbb C: z=te^{i\alpha}, t\ge 0\}$, how to show the discontinuity of $f$ at $z\in A$? Any help to understand the problem?
Is the set $A$ a bunch cut or a set of bunch points?
Comment: What do you mean by 'the complex square root'?.  The statement is correct only if you choose square roots in a particular way. If you use the principle logarithm to define square roots then the statement you have made is false.
Comment: @KaviRamaMurthy Thanks for pointing that out. I mean $f:\mathbb C\to \mathbb C$ is defined by $f(z)=\sqrt{z}$.
Comment: That is a meaningless definition. every complex number has two square roots so $\sqrt z$ is not  a well defined function.
Answer: If you define $\sqrt {re^{it}}$ as $re^{it/2}$  when $0<t\leq 2\pi$ and take $\alpha =0$ then the statement is correct and it can be proved by showing that square root of $1+\frac i n$ tends to $1$ whereas square root of $1-\frac i n$ tends to $-1$. For other values of $\alpha$ you have to take $\alpha <t \leq 2\pi +\alpha $ instead of $0<\alpha \leq 2\pi$. In other words you haev to rotate $1\pm \frac i n$ by angle $\alpha$.
Comment: What is the set $A$?


How to avoid stopping when I play a wrong note on the piano

Question: When I play any sheet music by memory, if I realize (by ear) that I play one wrong note, I always stop/get stuck and cannot continue playing. This is very bad in case I need to perform.
So how to play a wrong note without stopping? Or I should just keep trying to play a sheet perfectly before performing, and refuse to play a sheet that I'm not sure I can play perfectly?
I have been learning piano for a few months now.
Comment: That sounds like years to me.  But there's nothing wrong with years of lessons.  Most professional pianists will have had 15 or 20.
Comment: Please consider making this question more specific. What piece? Where exactly is the problem spot (what measure? Which note(s) within that measure?)? Are you playing from memory? There are many different answers to questions like this, depending on the circumstance. Without knowing the specifics, this site can only offer generalizations that might have nothing to do with the real problem.
Comment: @BlaineWorkman and the question is, how do you manage to do that instead of stopping?
Comment: Honestly, I wouldn't worry about it right now. You might just not be familiar enough with various muscle memories to keep going if it's only been a few months to power through errors. After you have some more muscle memory for certain frequently encountered things (or just super familiarity with the piece) you can just continue through the motion.
Comment: @Aaron It happen with sheets that I play from memory, and usually in hard part/ measure that I often forget after (long) time. How do I improve or accept/ keep up with it?
Comment: When i play a wrong note i just act likes its intentional and keep playing.
Comment: @phoog yeah because it's over 60 months now :(
Answer: The source of the problem
The most common cause I've encountered for this kind or problem is practicing primarily from the beginning a piece.
The "mechanical" solution
Beginners tend to learn music by developing muscle memory that is associated with the sounds of that music. When the sound or the muscle memory is interrupted, the performer becomes lost. There are no other memory sources (e.g., knowing each individual note, the harmonies, being able to play by ear) to back things up. Thus, the music must be restarted from the very beginning.
It's similar to traveling to a familiar location when one always starts and end the trip from the same places. If there's a different starting place, or a wrong turn, or the familiar trip is somehow interrupted, one becomes lost unless there's good enough knowledge of what went wrong, the surrounding area, or some other cue to help get back on track.
The starting point to fixing this kind of problem is to practice starting from different places in the music — first with the sheet to help, then from memory.
Suppose a mistake occurs at measure X. First, practice measure X by itself. Then start one measure before. Then start at the beginning of the phrase. Try starting in the middle of a random spot near X. This will force your mind, ear, and fingers to learn to music from many different perspectives, and when done sufficiently, will carry you through even when mistakes are made.
The "complete" solution
In addition to the "mechanical" practice described above, there is also the musical/emotional meaning of the piece. Mistakes — and the difficultly in continuing past them — often stem from an incomplete connection with the feeling of the music.
When a mistake occurs, it is crucial, beyond just drilling the notes, to ask what those notes mean. What is happening in the phrase of which they're a part? Is it climactic? Tragic? Exciting? Is there a specific image or story involved? And what role does this note, chord, or passage play within that meaning? Is it the high point? A rest point? A passing-through point?
These kinds of emotional "through-lines" in music can carry us along even when "surface detail" (like notes, rhythms, dynamics, etc.) eludes us.
Consider that when you speak, you can forget a word, use the wrong word, stumble, forget what you were saying, and the person you're talking to still gets your meaning, because they have a feel for what you were saying. Music is the same. Capture the feel, and know "the story" of the music, and that will sustain you through missed notes.
Comment: Absolutely. In the past, I've been in bands that do exactly that. Mess up in verse 3, so we must start at the beginning again. Bonus is, sight-reading imroves as well, rather than memory. My usual analogy is - just finished cleaning a big window. Notice a speck of dirt in the middle. Need to clean it all again?
Comment: fun fact: AI has this problem.
Comment: Love the complete solution part. This was what I was missing in my early years of piano playing. Feel the music with emotion and you will find practice fun and less mistakes.
Comment: Brilliant answer in many ways!
Answer: This answer is just based on my personal experience. I never had this problem, and I'm mostly a guitarist who plays rock music. When I first started I often played along with recordings. If I missed a note, the music went on without me and I had to catch up. So perhaps you should play along with recordings also. Having to figure out where you were when you mess up is an important skill if you're ever going to play with other musicians.
Comment: IMO, it would strengthen your answer if you didn't say "based on my personal experience" and "I never had this problem". :-)
Comment: True, though playing with an external aid _is_ a good strategy to treat pausing involuntarily.
Comment: @Aaron I meant along the lines of "I never had this problem, and perhaps this is why..."
Comment: @Graham Can't *ever* work? You mean to tell me no solo artist ever made a recording worth playing along to? Would you be against practicing for solo pieces with a metronome, then? I agree with your point about it being harder to improve from a recording with timing variations, but if there are any good ways to learn expressiveness out there, surely replicating an expert must be one of them? Why shouldn't OP practice like that?
Comment: @Graham I respectfully disagree (or agree with both sides, though less vehemently?). When I perform the 1st mvt of the Bach Gm solo violin sonata, I warp the subdivisions like Silly Putty. But when learning, parsing the 64ths and 128ths requires a metronome and a slide rule. Certainly, you must abandon the metronome to practice expression, but that's not the only kind of practice. I often play with recordings when practicing orchestral pieces (I know, not solo) since it helps strong-arm this reflex to stop for a mistake. I'd argue playing with a solo self-recording could serve the same purpose
Comment: @Matt This fundamentally doesn't (and can't ever) work for solo pieces though, which is where the OP is coming from.  I do agree with you about the many benefits of playing with other people, but I'm afraid this isn't something which the OP can use.
Comment: @user45266 "Worth playing along to"?  No, I mean to tell you that trying to "play along" to someone else playing that piece is not a good way of practising, does not teach you phrasing or expressiveness, and for any non-trivial piece is basically not possible.  It fundamentally does not, and cannot, work for solo playing, because playing along with someone else is an entirely different and entirely unrelated skill.
Comment: @AndyBonner Definitely agree about using a metronome.  But the metronome isn't "expressive" (that's kind of the point :) and you can pull the speed right down and then gradually step it up as your fingers fall in line.  That's the mirror opposite of playing along to a full-speed version with a solo performer's variations in timing, I'd say, which is why I really don't disagree with user45266.  Although of course I'm just one guy on the internet, so hey. :)
Comment: @Graham "...the many benefits of playing with other people, but I'm afraid this isn't something which the OP can use." In regard to the "avoid stopping" issue, playing with others could be one of the most effective ways to gain that skill, even if it isn't directly about solo recital.
Answer: I've said that, if possible, you should play with people and in front of people. "With people" because you have a set of things you think are important, but when you play with others, your failing are clear and they will let you know. Most likely, it's time, intonation, dynamics, and listening to others, but it could be other things.
In your case, it's the mindset of playing in front of others that's important. Basically, "the show most go on". The song can't end and start over just because you threw clams. Good musicians in the practice room will give you room to get it right, but on the stage, you just need to acknowledge it to yourself, get over it, and move on.
There's a line that, when you play the wrong note, you should play it again, hard, so it sounds like you meant it. That might be a mindset to get into. If it's the same note at the same time, though, you should take that part slowly to get it under your fingers. Practice doesn't make perfect, it makes permanent, so if you keep practicing the wrong note, it'll always be there.
Comment: Playing the 'wrong' note several times works well in a jazz situation, but I doubt it'd work with pieces that are available on sheet music - thus are better known and also it's going to be difficult making the same 'mistake' if those tricky bars don't come round again.
Comment: The other aspect of playing *with* other people, i.e., within an ensemble, is that you very quickly learn to keep rolling even after a few honkers, as the group will steamroll right over you and leave you playing catch-up if you stop or stutter.
Comment: They're less likely to steamroll in the practice room than on the stage, but yes, @Tristan
Answer: You could simply be in the habit of stopping to correct mistakes. I advise my students that you practice in two ways (well, hopefully hundreds of ways, but at least these two): When first learning a piece you should never let a mistake go past without correcting it, and when preparing for a performance you should spend at least some time playing straight through without stopping for any reason. Perhaps you just need to spend more time in the second way of practicing. And it can be hard to "remember" not to stop, so many of the strategies already suggested here can be helpful: Book small, informal performances before "the big one": Play for friends, in a coffeeshop, on the sidewalk, for a video recording, etc. Play along with recordings.
You mention that you stop "usually in a hard part/measure that I often forget after (long) time." This suggests two solutions:

Practice the hard part extra! This is always good for simply getting better at hard parts; if one measure is twice as hard as those around it, shouldn't the surrounding measures need half the attention? It's also smart, when taking the measure out of context, to start in different places sometimes. If, say, m. 10 is hard, and you always practice it by starting in m. 9, then m. 9 becomes a weak point in your memory and you might have trouble going from 8 to 9.
If there is a spot where your memory often fails you, there might be a musical reason. Sometimes one section of a piece is similar to another. I sometimes play from memory while recording myself, then play the recording back while watching the music to and see where I went wrong. It's also helpful to analyze the form of the piece to understood why it takes these different turns. On a smaller scale, I've played Hindemith pieces and had trouble remembering certain very convoluted measures in which the notes seem almost "random," until sitting down and discerning the pattern that actually underlies them.

There are a few other reasons that one might stop when making a mistake:

The mistake simply interrupts you and distracts your memory from what comes next. This could be solved by performing from the music, or from various ways of strengthening one's memory of a piece (spending more time in the "from memory" part of preparing for a performance, making a "mental roadmap" of the piece, or analyzing the piece's structure). You suggest "refusing" to perform a piece until you can do so perfectly; I'm not sure I would go so far (would any of us ever perform, then?), but there's no harm in making sure you're well prepared.
You could be temporarily paralyzed by concern over having made a mistake. This would call for a change in the way you think about practice and performance, addressing your emotional responses to success or failure, and reducing the "stakes" of making a mistake. This could go deep; professional therapy can be an important part of a performing life.
Comment: I was about to write an answer all about the *two ways of practicing*, but you've basically covered what I would say. I think that part could be brought out (or highlighted) as an important concept for organizing one's practice sessions. hth. I think it's an excellent point but ended up buried in the middle of your text.
Comment: +100 if I could. This is the only answer which is actually correct.  All the others focus on "practise so you don't make a mistake".  You've got the correct answer which is "practise playing on after a mistake" - and that's a skill which needs practise just as much as putting fingers on keys.
Answer: 'Well, don't do that then' :-)
OK, that doesn't help much.   Yes, a wrong note can be an obstacle.  Particularly if you played the clunker because your hand was in the wrong position.   And because a lot of our music reading isn't about individual notes, but about patterns.  G,A,B is 'G then one up then one up again'.
I can only offer you the standard advice.  Practice slowly enough to NOT play wrong notes.   Four wrong attempts followed by one correct one isn't success, it's four practices of the wrong one!   Play it right, then play it right 10 more times.  'An amateur practices until he gets it right, a professional practices until he couldn't get it wrong.'
Answer: Just don't stop but keep going as if it didn't happen and don't worry about it, things will improve with time.  A lot of musicians "train" themselves to stop and consequently don't play nice with others.  Never ever stop.  However, this is a good time to work on your ear training. Ear training should not be seen as a separate skill but something to amalgamate or crosspollinate with your existing skills.
Most of us learn scales by their letter names, learn them by their numeric names.  Instead of seeing (and hearing) CDEFGABC, learn them as 12345678.  Thus, MARY HAD A LITTLE LAMB, regardless of the key, is:
3212333 222 355 3212333322321.
Start on the third tone of any scale and play those numbers and poof, you can sight transpose. Don't be satisfied with merely matching dots to a key.  Learn the vocabulary.  So if you are not sure what that fifth tone is when you are playing, if you know what a fifth sounds like, you will never have to guess, your brain will just know. You will hear it in your head and . . . just know.
It is no different from spelling a word you don't know.  You use your existing KNOWLEDGE of spelling rules and sounding out the syllables (spelling by ear/playing by ear).  There is nothing hocus pocus about it, it is employing your brain and not guessing nor learning music merely by rote.
Secondarily, this is the beginning of honing your improvisational skills. Should you hit a wrong note, you'll be able to use it as a passing tone, neighbor tone or tension tone to make your piece more interesting.  Don't be fooled into thinking a "classical" piece is a museum piece. I'm sure Bach or Chopin never played one of their own works the same way twice. They were improvisors who wrote out their music for students or profit. We don't have to be slaves to their notation.
So build your confidence, ear and brain by playing like nothing happened BUT MAKE NOTE OF IT and go back later to fix what your brain doesn't know yet.  Just like spelling, mistakes are lack of knowledge, not talent.  Just listen to all the "mistakes" this guy makes:
Comment: "...improvisors who wrote out their music..." I think this is a really important point. I've only  seen it in writing a few times, could be I need to read more, but it just seems to be a fact not well known.
Comment: "we don't have to be slaves to their notation": there's a fascinating passage in Artur Rubenstein's autobiography where he describes the transition he had to make with the popularization of recordings. Where previously he had been able to play fast and loose with the music he performed, recordings (and the advent of "urtext" editions) brought about an expectation of note-perfect, "as notated" performances.
Answer: It can be a bit jarring to keep playing when you know you've messed up. Feels like it messes with the whole rhythm.
Practice practice practice is the best thing to do. If you go through a piece and make a mistake, push it a couple more bars before stopping.
The main thing that got me through this issue when performing is knowing that nobody knows you've messed up. To you it seems like the end of the world but in reality if you keep playing nobody will know any different.
Comment: Great suggestion about stopping a short distance _after_ the mistake. This provides the best of both worlds - keep going _and_ don't let a mistake go without fixing it. This is exactly how experienced musicials practice. (They also do what @LaurencePayne says in his answer.)
Answer: I think an important thing to do is prioritize rhythmic integrity over pitch, or at least treat them as equal. From a listener's perspective I think a wrong pitch is fleeting, but stopping completely, going back even, is a complete collapse of the musical experience.
The way I look at it is this. The first "wrong note" or "mistake" that people recognize is a wrong pitch. For example, you hit an A instead of a B. When that happens, you stop, get frustrated, then start over probably from the exact point of the mistake.
What that does is take a mistake in pitch, and compounds it into a mistake in rhythm! It also trashes the sense that music is a series of coherent phrases, because you might start up again in the middle of a phrase. And let's make one thing very clear: music is a temporal art, no amount of going back and replaying something, in a performance, will "fix" anything. Once it's broken, it's broken... so keep playing.

...refuse to play a sheet that I'm not sure I can play perfectly?

That seems like circular thinking. How would you be able to play something perfectly without practicing it where surely you will make mistakes?
There is a Catch 22 here. You don't want to make mistakes while practicing, but part of the issue is how to avoid stopping when a mistake happens. You want to somehow create "opportunities for mistakes" so you can practice a not stopping reaction.
Potentially there are two different issue at hand. One is how to practice to overcome difficult passages where you make mistakes. The other is how to break the reflex of stopping when a mistake is made. Those are two different issues.
I think there are two main things to work on:

For trouble spots, break up practice into phrase based units and focus on the difficult sections. You can try various phrasing scopes depending on the situation. You could work on things around 4 to 8 bars, or break things down to smaller scopes even a small as two beats. In a sense this involves a deliberate start/stop approach, because you playing the whole piece.
To work on not stopping after a mistake, find material to practice where constant tempo and rhythm are the priority. I think you want spontaneity in this work. Sight reading is the obvious thing that comes to mind. Counting the beat out loud will be good too. Some things to try when you encounter those moments of hesitation: play what you can manage, maybe just the bass, or bass and treble, simplify dense of florid passages, at the very least if your hands stop, don't stop counting the beat, and get back to playing as soon as you can.

In both cases I think a good principle is taking some extra time, a "breather" to regain your composure, at a musical cadence point, is OK. That at least works within the natural start/stop structure of the music itself.
Overall, avoid stopping by focusing on the beat and rhythm.
Comment: re "refuse to play ... until I can play," I took it the OP meant "perform publicly"—in fact I see Aaron made that edit
Comment: @AndyBonner Yes, but it still seems wrong headed, as if you can practice away any chance of mistake, interruption, or hesitation.
Comment: Just a style suggestion: Start the post with the "prioritize rhythmic integrity" sentence. As is, you're kind of burying the lead.
Comment: Thanks @Aaron, I made that change. Sometimes writing answer is more stream of consciousness, I can get lost in my own thoughts.
Comment: It's a really good perspective. (I'm kicking myself for not thinking of it.) And moving both sentences is really strong. I hope this answer will continue to get more attention.
Comment: I often make this point to students. "Practice makes perfect"?? Who came up with that nonsense? What, like one day you're just going to say "Oh my gosh, that was it. Perfection. I'm done, I never need to practice again." Baloney; you just move the goalpost of "perfect" (in a healthy way). Excelsior.
Comment: (Related to the well-worn trope "practice doesn't make perfect, it makes permanent," cf all the advice on this page to play through mistakes :)
Comment: I'm also thinking of scenarios other than the piano recital. What if you are an accompanist and someone gives you new material? Is someone going to say get back to me in 6 months after it _perfect!_ No. Play it now, and keep the beat.
Answer: That problem was for me and I was looking for answers in a lot of places. What helped me: I played something that I really know every character and could start from anywhere in the piece (it's very important!) and played in front of a lot of people. You don't need a lot of people in front of your family before - call everyone at the piano a deep breath and think like this is the last time you play the piano How would you play then?
One of the things you should do so as not to get to such a situation is to learn each hand individually slowly until you can do it really quickly and immediately after it very slowly - until you really know each note it is very important. Another thing I do when I train is learning to start from the middle of the piece from a complicated place. It helps to get to know the characters better.


Equivalency between Indian Classical Saptak and Western Notes

Question: Can anyone tell me the equivalency between Indian Classical Saptak, i.e. Sa Re Ga Ma Pa Dha Ni Sa and Western Notes, C D E F G A B
It is Sa ~ C, Re ~ D, Ga ~ E, etc, or is it something else.
Please let me know
Reason I'm asking is, I'd love to be able to play https://noobnotes.net/do-re-mi-sound-of-music/ on Bansuri
Already this video sounds quite similar to Do a Deer A Female Deer
Comment: Have you seen this pdf: https://indianraga.com/wp-content/uploads/2016/11/Hindustani-Vocals-Syllabus-Levels-1-4.pdf
Comment: @albrecht-hügli Thank you for this resource. Currently I am practicing SwarAlankars
Comment: Related: https://music.stackexchange.com/q/75560/38256
Answer: I didn't know about it but I've recently seen this syllables when I was looking up Kodaly.
I think  Sa Re Ga Ma Pa Dha Ni Sa is not corresponding to the C D E F G but to the moveale Do Re Mi.

yes it is:
These seven swaras are shortened to Sa, Ri (Carnatic) or Re (Hindustani), Ga, Ma, Pa, Dha, and Ni. Collectively these notes are known as the sargam (the word is an acronym of the consonants of the first four swaras).
Sargam is the Indian equivalent to solfege, a technique for the teaching of sight-singin.
The tone Sa is, as in Western moveable-Do solfège, the tonic of a piece or scale.
(may be you'll have to look up "movable do" or "moveable do re mi" here in this SE, you'll find a lot explanations.)
https://en.m.wikipedia.org/wiki/Svara
Comment: @Marium Don't know if you're aware, but "movable" itself won't return anything useful, since "movable" just means "able to be moved". "Movable Do" is the operative phrase.
Comment: Hello @albrecht-hügli. Thank you for your explanation. Picture is worth thousand words. It helped me also understand the Komal notes. Will research `movable`.
Answer: So the short answer to your question is no, its not a one to one correspondence in the general case.
The long answer
So there is a fundamental differences in how pitches are defined in both western and Indian contemporary systems. In the western system there is a set of "standards" for defining pitches. One such example is the concert tuning : https://en.wikipedia.org/wiki/Concert_pitch.
The most commonly defined standard defines a pitch (lets say A4 = 440Hz) and uses the equal temperament tuning to define the other pitches. The formula is f(n) / f(n - 1) = 2 ^ (1/12). So for instance A#4 = 440 * 2^(1/12) Hz.
This defines an entire set of notes along with its defined frequencies. Some standards differ (some folks like defining A4 as 432 Hz) but the central argument of absolute pitches does not change.
The Indian classical traditions does not have such an absolute frame of reference. A "Sa" can be any real number frequency. Lets say that frequency is f. Then the "Pa" is 1.5 times "Sa" so 1.5f. Each of the notes in the Sargam is some fraction of "Sa" based on just intonation.
So while its possible to define your Sa as C and draw a correspondence (well almost, equal temperament is not a perfect mapping to just intonation), you can also defined your Sa as C4 - 10hz, which does not map to any of the concert pitches. (A notable example would be contemporary sitar players tuning their Sa in between C# and D as their Sa).
Comment: What you are describing is the "movable do" concept mentioned in the accepted answer. Also, Western music doesn't exclusively use 12TET. Older music may be played using just intonation or a variation thereof.
Comment: You are correct. Older music may be played using many different intonations (including just intonation). My answer however precisely pins down contemporary practice (for instance good luck finding practitioners still playing the well tempered clavier in non modern instruments). The west has pretty much phased out everything other than 12TET.
Comment: Besides just making a statement that you can float your tonic arbitrarily does not do justice to the statement "but why is that the case".


How to prevent duplicate IDS in foreach statement PHP

Question: I am doing a foreach that stores data to a datebase. The only problem am having is with the generated IDS. Each added item into database should have it's own unique fileID.
   foreach ($videos['items'] as $videoResult) {
     **$musicThis = Music::Where('file', '=', $videoResult['id']->videoId)->get();**
     if(count($musicThis) < 1) {
     $music_id = substr(md5(time()+$videoResult['snippet']['title']), 0, 11);
     $music = new Music;
     $music->filename = $videoResult['snippet']['title'];
     $music->fileDesc = $videoResult['snippet']['description'];
     **$music->fileID = $music_id;**
     $music->save();
     }
    }

When this is executed, my database ends up with the same fileID, which is not what I want. How can I do this right?
Comment: Do you need to be able to regenerate it ? If not, why not use a uuid4? see: https://github.com/webpatser/laravel-uuid
Comment: Even with uuid, won't I still be generating the random string?
Comment: Highly unlikely with version 4 :) See https://en.wikipedia.org/wiki/Universally_unique_identifier. `for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated.` I doubt you'll ever get there..
Answer: Simpler test case:
var_dump(1+"foo", 1+"bar");

Warning: A non-numeric value encountered
Warning: A non-numeric value encountered
int(1)
int(1)

You may want to concatenate rather than sum.
In any case, the overall logic is pretty confusing. time() has a 1-second resolution so it'll sometimes clash on duplicate titles, some times not.
Comment: Reasonable as in compared to using uuid4. Yes, theoretically you'll have the 16^11 options, but there is a higher chance of collisions compared to other options. Why take that risk at all?
Comment: Ah, I did miss that one. Still, given that the `time()` and the title are unique when generating the md5 hash, the substr of 11 chars of that hash has a reasonable chance of collisions. I would suggest dropping the md5 altogether for something more random?
Comment: @Robert Certainly, writing your own cryptography is rarely a good idea. If in this path, I'd just generate random letters (using the complete alphabet) or let the database assign consecutive integers.
Comment: BTW, `16^11` is `17,592,186,044,416`.