Is it advisable to use a (smoking) pipe cleaner to clean a flute?

Question: In this question it was asked how to clean the inside of a flute.
The answers include different tools, all of them basically a stick with a piece of cloth, ranging from an 8$ stick to a 25$ stick.
Pipes (for smoking) and flutes have several things in common:

They are slim and tubular.
Many pipes and flutes are made out of wood.
Both can be very expensive and need to be cleaned.
Pipes and flutes become wet inside: the flute is wet from saliva and breath moisture; the pipe is wet from condensation when it cools down.

Pipe cleaners are sold as cheap as 4.77$ (132 pieces). They are long enough to be used to clean flutes as well.
Is it advisable to use (soft) pipe cleaners to clean the inside of a flute?
Comment: Overlaps with [this question](https://music.stackexchange.com/q/62642/2600). Short answer: No, the  wire in the middle is more than likely to scratch the polished surface. In case of emergency you may use it, but take card of bending, so the rough wire end does not get in touch. A reusable swab is surely cheaper in the long end and transports less dust *into* the instrument.
Comment: I mean christ, just chop a strip off an old T-shirt and poke it through with a chopstick if you really don't want to spend 5 quid on a flute cleaning rod
Comment: Don't try to make music thru a pipe,  and don't smoke thru a flute.
Comment: I wouldn't, they probably leave lint.  I mean, it's not like you worry about leaving lint behind in a pip: you burn the damn thing.  If you're worried about the money just get one of these, they already ahve a stick attached IIRC https://www.amazon.co.uk/Trevor-James-Flute-Gauze-Through/dp/B006UUDH68/ref=sr_1_9?s=musical-instruments&ie=UTF8&qid=1507628313&sr=1-9&keywords=flute+rod
Comment: @Some_Guy It was a hypothecical question: I do neither own a flute nor a pipe.
Comment: At least extinguish the (smoking) pipe cleaner first.
Comment: @Philipp fair enough, sorry for being a snarky bastard
Answer: No.  It would be very inefficient.  Use a cleaning rod, bought or improvised, with a piece of cloth, typically an old handerchief.
Comment: you can gently use an all cotton pipe cleaner (the correct type is sold by instrument repair tool manufacturers) to clean around the keys and rods, although you have to be careful to not mar the pads.  Pipe cleaners that are made for cleaning actual pipes often have abrasive plastic embedded in the wire to to help scrub the pipe, and are unsuitable for cleaning polished or plated metal.  Crafting "pipe cleaners" used for children's crafts are also unsuitable.


ASP Table doesnt save state

Question: I created an ASP Table Control and added a row to it programatically. I then repeated the process to add another row. The first row that I added disappeared and only the newest row is being displayed. Is there a property that needs to be set to allow the state of the table to be saved?
EDIT:
All I do is click a button on the page and it adds a row to the table. Repeated clicks of the button only add one from to the table. If it helps, here is the function that adds the rows.
 Protected Sub addItemButton(sender As Object, e As EventArgs)
    'get the id of the item they selected
    Dim id As String = CType(sender, Button).Text
    'clear out the data being displayed
    gridViewItemSearchItems.DataSource = Nothing
    gridViewItemSearchItems.DataBind()
    'add this item to the line table
    Dim itemToAdd As Item = gp.Items.GetItemByKey(id)

    Dim tableRow As New System.Web.UI.WebControls.TableRow()

    Dim cellId As New System.Web.UI.WebControls.TableCell
    cellId.Text = itemToAdd.Key.Id

    Dim cellDesc As New System.Web.UI.WebControls.TableCell
    cellDesc.Text = itemToAdd.Description

    Dim cellMSRP As New System.Web.UI.WebControls.TableCell
    cellMSRP.Text = gp.Items.GetItemMSRP(itemToAdd.Key)

    Dim cellCost As New System.Web.UI.WebControls.TableCell
    cellCost.Text = itemToAdd.CurrentCost.Value

    Dim cellUnitPrice As New System.Web.UI.WebControls.TableCell
    cellUnitPrice.Text = itemToAdd.StandardCost.Value

    Dim cellDiscount As New System.Web.UI.WebControls.TableCell
    cellDiscount.Text = "12%"

    Dim cellQuantity As New System.Web.UI.WebControls.TableCell
    cellQuantity.Text = "1"

    tableRow.Cells.Add(cellId)
    tableRow.Cells.Add(cellDesc)
    tableRow.Cells.Add(cellMSRP)
    tableRow.Cells.Add(cellCost)
    tableRow.Cells.Add(cellUnitPrice)
    tableRow.Cells.Add(cellDiscount)
    tableRow.Cells.Add(cellQuantity)

    tblItems.Rows.Add(tableRow)
End Sub

Comment: How are you adding the rows (in what event)? Could you post your code?
Comment: @CAbbott Its done in a after a button is clicked. So after in an OnClick function
Answer: Since you're adding the rows to your table dynamically, they have to be re-created on each successive post-back.
Look at this answer for an explanation as to why dynamically added controls can disappear: ASP.NET dynamically created controls and Postback
EDIT: It is possible to dynamically add controls during a post-back, my answer here shows a way to do that using ViewState. Although, this does become very cumbersome. You might want to re-think the design of the page.
Comment: Awesome, thanks for the help. I am going to give this a shot now.

ASP Table doesnt save state


Como verificar o remetente usando o algoritmo RSA

Question: Me surgiu uma dúvida no passar de minhas pesquisas que nao consegui solucionar.
Vejamos uma forma de end-to-end que use RSA, Alice precisa uma hora enviar sua chave pública para Bob e vice versa para se comunicarem, porém se alguém executar um MITM a segurança vai ser nula, como entao verificar se a chave pública recebida do remetente é realmente Bob/Alice? Para caso nao for ignorar a mensagem.
Comment: Algoritmo Diffie-Hellman?
Answer: Não existe um meio fácil de fazer isso, é por isso que na prática se usa certificados e não simples pares de chaves. Um certificado é:

Uma chave pública...
Associada a uma identidade (um nome)...
E ambos assinados por alguém de confiança.

Digamos que Alice e Bob se conhecem, mas eles nunca trocaram chaves criptográficas entre si. Num determinado momento, alguém se dizendo ser Bob tenta iniciar uma comunicação, mostrando uma chave pública que ele diz ser de Bob. Alice não tem como saber se essa chave é ou não de Bob, a menos que ela use um canal alternativo para confirmar esse fato (ex.: telefonando pra Bob e pedindo pra ele dizer a "impressão digital" - fingerprint - da chave; assumindo é claro que ninguém consiga grampear o telefone e imitar a voz de Bob...).
Felizmente, tanto Alice quanto Bob conhecem Charlie, e ambos já trocaram chaves com Charlie. Uma maneira de Bob provar para Alice que ele e mesmo Bob é pedindo pra Charlie confirmar isso a Alice. Por exemplo, enviando uma mensagem segura pra Alice onde a chave de Bob está anexada. Isso até funciona, mas é muito pouco prático. Uma opção melhor é juntar a chave de Bob com o nome "Bob" e pedir pra Charlie assinar, usando sua chave privada*. Charlie conhece a chave de Bob, e sabe que ela pertence a Bob, então ele pode assinar sem problemas. Bob então pode enviar isso para Alice, e Alice - conhecendo a chave pública de Charlie - verifica a assinatura e confirma que a chave recebida de Bob de fato pertence a ele.
Nesse caso, Charlie estaria agindo como um terceiro de confiança (trusted third-party): se Charlie mentir pra Alice, assinando um certificado que não pertence a Bob (ex.: o nome "Bob" associado à chave pública de Mallory), não tem a princípio como Alice saber, e ela estaria vulnerável a um MitM. Por isso é importante que Alice confie bastante em Charlie, não só na sua integridade mas na sua capacidade de identificar corretamente alguém antes de assinar sua chave, e também de armazenar essas chaves com segurança.
Isso é difícil de garantir em larga escala, pois exigiria que cada um fosse bastante cuidadoso com todos esses aspectos. Por essa razão, na maioria dos usos práticos se opta não por deixar qualquer um assinar certificados de terceiros (Web of Trust), mas sim concentrar essa tarefa em umas poucas organizações, chamadas Autoridades Certificadoras (Certificate Authority - CA). Toma-se medidas para que todo mundo conheça as chaves públicas dessas CAs (por exemplo, distribuindo-as no próprio Sistema Operacional), e exige-se que todos que quiserem um certificado contratem uma delas para verificar sua identidade e assinar sua chave.
Esse sistema não é perfeito (basta uma CA ter sua chave privada comprometida para que alguém possa agir em nome de qualquer outro) mas é o que é mais usado hoje em dia (ver "Infraestrutura de Chave Pública" - Public-key infrastructure - PKI), por exemplo quando se usa o browser para visitar um site que nunca foi visitado antes - o certificado contém o nome do domínio, uma chave pública, e ambos assinados por uma CA reconhecida. No contexto de um end-to-end, pode ser indesejável ter que confiar num terceiro para verificar a identidade dos participantes, mas a única alternativa viável seria trocar essas chaves pessoalmente e/ou usar um canal de comunicações alternativo para auxiliar na validação. Ambos muito pouco práticos, infelizmente...

*Nota: eu disse "chave" pra simplificar, mas na prática não se deve usar a mesma chave RSA tanto para assinar quanto pra cifrar - são necessários dois pares de chaves por participante para se realizar uma comunicação segura usando esse algoritmo.


Finding Optimal Number of Clusters in Expectation Maximization Algorithm

Question: I know that there are several methods (Elbow method, silhouette analysis etc) which can help me to find the best number of clusters.
My questions are:

What are the best methods to use in Expectation Maximization (EM) Algorithm?
Can I use elbow method (as if it were for K-means algorithm) to get the "best" number of clusters, but to use in EM Algorithm?

Thanks in advance.
Comment: "Elbow" or SSwithin criterion is a raw, unnormalized source of more advanced indices such as CH (Calinski-Harabasz) or DB (Davies-Bouldin). Read a brief outline at the bottom in [this](https://stats.stackexchange.com/a/358937/3277) answer
Answer: The "elbow" method never works well...
Instead, use any of the other internal measures such as Silhouette, Dunn, CH Index, BIC, AIC, C index, etc. that are much better and should also work for EM.
If you really want to stick with the worst method (Elbow), you could try to look for an elbow in the score function of EM too. Just as with k-means we'd expect the loglikelihood to improve as you increase the number of clusters. There could be an elbow there too, where the rate of improval slows down.


R tables::tabular() use of Format() to get rid of scientifc and round

Question: I have a quick question. I am using tables::tabular() and have some summary statistics which are displayed in scientific e notation.
I found out that using Format(scientific=FALSE) * mean() in this context helps me to get rid of the scientific e notation in the means, and other summary statistics i present.
Now, I also want to round this number with the format 0.123456789 (most of the means are means of ratios between 0 and 1 but not all) to show the digits left and maximum 4 to the right of the comma i.e. 0.1234. I tried simply putting the digits=4 option into the Format and while it seems to work when alone in the Format() function, it doesn't somehow when I also have scientific=FALSE in there. Rather, with Format(scientific=FALSE, digit=1), I still get 5 digits to the right of the comma.
Do you know what is happening and how i can fix it?
Highly appreciate your help,
cork
Comment: Could you include a reproducible example?
Answer: Have you already tried to use a global statement at the beginning like this: options("digits" = 4)?
All the best,
Patrick
Comment: Hi Patrick,
do you mean by global in the tabular function? I am quite a novice, so I don't fully understand what you mean. I guess I have to read up upon the functionality of options in functions again.
Comment: Write it  just before your regular R code in your script.
Comment: Thank you Patrick and user2554330 for your efforts, I switched to using table1 package which did what I originally sought out to do for me.


Nested Fragments Communication

Question: I'm currently having trouble with nesting fragments , I've created a SlidingTabLayout with two tabs , each tab with it's corresponding Fragment , In one tab I've added 5 child fragments to the parent fragment returned by the FragmentPagerAdapter, but I'm having trouble with the communication between the parent fragment and it's fragment children ,
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

            FragmentTransaction childManager=getChildFragmentManager().beginTransaction();
            childManager.add(R.id.linear08,new YearFragment08(),"year08");
            childManager.commit();
            YearFragment08 year08=(YearFragment08)getChildFragmentManager().findFragmentByTag("year08");
            year08.setinfo("This is fantastic");

}

`
public class YearFragment08 extends Fragment {
TextView yearInfo;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.year_frag08,container,false);
    yearInfo=(TextView)v.findViewById(R.id.txt_yearInfo_08);
    return v;
}
 public void setinfo(String data){
    yearInfo.setText(data);
}

And THIS is the result .
02-09 21:45:48.078    2177-2177/com.compassasu.compass E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.compassasu.compass, PID: 2177
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.compassasu.compass.Fragments.YearFragment08.setinfo(java.lang.String)' on a null object reference
        at com.compassasu.compass.Fragments.HistoryFragment.onActivityCreated(HistoryFragment.java:33)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1970)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1051)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:545)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
        at android.view.Choreographer.doCallbacks(Choreographer.java:670)
        at android.view.Choreographer.doFrame(Choreographer.java:606)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

All I want to know is how does a child fragment receive data from the parent fragment .
Answer: The problem is that you are trying to find the fragment by its tag before it has actually been added. Note the documentation for FragmentTransaction.commit():

Schedules a commit of this transaction. The commit does not happen
  immediately; it will be scheduled as work on the main thread to be
  done the next time that thread is ready.

As you can see the fragment is not added immediately so that is why null is returned when you try to get the Fragment.
To fix this you can use FragmentManager.executePendingTransactions() after committing the transaction to add the fragment immediately:
getChildFragmentManager().beginTransaction()
        .add(R.id.linear08,new YearFragment08(),"year08")
        .commit();

getChildFragmentManager().executePendingTransactions();
YearFragment08 year08=(YearFragment08)getChildFragmentManager().findFragmentByTag("year08");
year08.setinfo("This is fantastic");

Also note that a better way to do this would be to create the YearFragment08 fragment first and use Fragment arguments to pass the info you want to show in the Fragment. Then you would not need to use the above workaround since you will not need to call yearInfo.setText("Hi") when the Fragment is first created. You can find an example of creating a Fragment with arguments here.
Update
As noted in the lengthy comments although the first approach allows getChildFragmentManager().findFragmentByTag("year08") to return the fragment it is still not a good idea to call any methods on the Fragment that access its views until onViewStateRestored(...) or after has been called.
This is because when using the FragmentManager to add the parent fragment the child fragment's onCreateView method will not be called immediately after calling executePendingTransactions() so the child fragment's referenced views are null. If the parent Fragment is used directly in the layout this is not a problem as onCreateView of the child fragment is called as part of executePendingTransactions() and its views will not be null.
The best thing to do in this case would be to use the other approach as mentioned that uses Fragment arguments if you need to set initial values for views within fragments.
Comment: 02-09 22:30:07.148    7381-7381/com.compassasu.compass E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.compassasu.compass, PID: 7381
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.compassasu.compass.Fragments.YearFragment08.setinfo(YearFragment08.java:27)

Still didn't work unfortunately
Comment: Actually it did work as you now made it into the `setText` method of your `Fragment`. New issues is the `yearInfo` text view is `null` in your `setInfo` method. Are you sure it is assigned in the `onCreateView` method of `YearFragment08`? Double check the `year_frag08.xml` file for a `TextView` with `id=txt_yearInfo_08`.
Comment:
Comment: Do you know how to use a debugger? Put a break point in the `onCreateView` method and verify yourself the `TextView` cannot be found. If you don't know how remove `yearInfo.setText(data);` temporarily from the `setInfo` method. Replace it with a call to `Log.d("My Tag", "I made it here")` so you can see this fixes the problem in your original question. Set some static text using `android:text` on the `TextView` in the layout file so you can see if this view is shown once the `Fragment` appears onscreen.
Comment: I finally found the issue you are likely facing by taking a closer look at the stack trace. Since you are using a `ViewPager` the parent fragment is not yet added to the layout so when you add the child fragment its `onCreateView` method has not been called yet. Because of this it would be best  to move to using arguments as I mentioned in the answer to first display the text. However, move the code you currently have in `onActivityCreated` into the `onResume` method temporarily and it will work.

Nested Fragments Communication


Criei minha entidade em symfony - Crud

Question: Usei o comando:
php bin/console generate:doctrine:crud

ele gerou todas pagina e controladores no meu projeto, porem quando entro na rota para criar um usuario da o seguinte erro:
Expected argument of type "string", "AppBundle\Form\UserType" given

Alguém sabe como concertar, ou já aconteceu isso?
Se precisar coloco aqui o codigo, mas é o padrão gerado pelo symfony.3
Comment: Cole o código do controlador gerado, por gentileza.
Comment: Já consegui resolver. Na versão do Symfony  < 2 8 se passava no parâmetro da createForm uma new TypeAbstract agora passa TypeAbstract:class.
Answer: Na versão do Symfony < 2 8 se passava no parâmetro da createForm uma new TypeAbstract agora passa TypeAbstract:class.

Criei minha entidade em symfony - Crud


Não consigo rodar meu projeto em react native no meu celular

Question: Estou criando uma aplicação em react native, que é um projeto de uma pokedex, que recebe informações da API do pokemon e mostra na tela as informações. Não estou conseguindo usar o meu celular para vizualizar como a aplicação está ficando.
Já instalei o node, chocolatey, java, android studio e o yarn. Estou usando o yarn no terminal para tentar rodar o projeto.
estou usando os seguintes comandos dentro do terminal do vscode:
yarn
yarn start
abro outro terminal (ainda dentro do vscode)
adb reverse tcp:8081 tcp:8081
yarn android
aí me surge o seguinte erro:
yarn run v1.22.18
$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 936 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
info Installing the app...
:ReactNative:Unexpected empty result of running '[node, C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js, config]' command.
:ReactNative:Running '[node, C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js, config]' command failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\Adriano Jos�\adriano\mobileapppokemon\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 213

* What went wrong:
A problem occurred evaluating script.
> node:internal/modules/cjs/loader:936  throw err;  ^Error: Cannot find module 'C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js'    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)    at Function.Module._load (node:internal/modules/cjs/loader:778:27)    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)    at node:internal/main/run_main_module:17:47 {  code: 'MODULE_NOT_FOUND',  requireStack:
[]}

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
:ReactNative:Unexpected empty result of running '[node, C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js, config]' command.
:ReactNative:Running '[node, C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js, config]' command failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\Adriano Jos�\adriano\mobileapppokemon\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 213

* What went wrong:
A problem occurred evaluating script.
> node:internal/modules/cjs/loader:936  throw err;  ^Error: Cannot find module 'C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js'    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)    at Function.Module._load (node:internal/modules/cjs/loader:778:27)    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)    at node:internal/main/run_main_module:17:47 {  code: 'MODULE_NOT_FOUND',  requireStack:
[]}

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

    at makeError (C:\Adriano José\adriano\mobileapppokemon\node_modules\execa\index.js:174:9)
    at C:\Adriano José\adriano\mobileapppokemon\node_modules\execa\index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\index.js:192:9)
info Run CLI with --verbose flag for more details.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Tem uma ferramenta chamada EXPO, serve para criar aplicativos mobile para IOS, Android e Web, utilizando React Native, acredito que esse erro não vai ocorrer utilizando esta ferramenta, da uma pesquisar sobre ela
Answer: Fala Adriano,
Acredito que o seu erro está ocorrendo bem aqui:
^Error: Cannot find module 'C:\Adriano José\adriano\mobileapppokemon\node_modules\@react-native-community\cli\build\bin.js'

Perceba que o seu caminho possui um caminho com caractere especial, nesse caso, o é do Adriano José.
Alterando para um caminho que não possua esse caractere especial (ex.: C:\adriano\mobileapppokemon) resolverá o problema o app funcionará normalmente.
Espero ter ajudado.


How can I prevent the parameters hash from my flash being displayed along with the ERB output in the view template

Question: I have implemented an application helper to dynamically provide the class of a flash message to the view for styling with Bootstrap. The setup works but along with the ERB, the actual parameters hash is being output to the view. I have look at all of my application code in the helpers and views and can't pinpoint the source. I've also looked at the output HTML and it was not indicative of the source problem. Below are the helpers and views as well as a snapshot of the troubled output result.
Troubled View Output
http://screencast.com/t/9KZHxjqm1Pq
--
# layouts/application.html.erb
...

  <%= render "layouts/header" %>

  <% if flash.any? %>
  <%= render 'shared/flash_messages' %>
  <% end %>

  <%= yield %>
  ...

--
# views/shared/_flash_messages.html.erb

<%= flash.each do |key, value| %>
  <div class="<%= flash_class(key) %> fade in">
    x
    <%= "#{value}" %>
  <% end %>

--
# helpers/application_helper.rb
module ApplicationHelper

  def  flash_class(level)
  case level
    when :notice then "alert alert-info"
    when :success then "alert alert-success"
    when :error then "alert alert-error"
    when :alert then "alert alert-error"
  end
end

end

Answer: It's because you are doing
 <%= flash.each

So the result of each is displayed, as well as anything produced by the block. Change the <%= to <%
Comment: Brilliant, that fixed it! In my very, very new state I overlooked this root cause. Thanks so much for the quick answer, @Frederick Cheung.


javascript function always returns false

Question: I am trying to validate a html form using jquery,ajax and php. I've written  this function in jquery that checks for the availability of a username using ajax post request.However, the problem is that it is always returning a false. I'm new to jquery and javascript. I've tried quite a bit but I'm unable to figure out the problem. Please help.
<code>function isvalid_username()
{
var username=$('#username').val();
var option=false;
        if(username == "")
        {
            $('#username').removeClass('valid').addClass('invalid');
            $('#username_feedback').addClass('error').html("Please choose a username!!");
            option=false;
        }
        else if(username.length < 4)
        {
            $('#username').removeClass('valid').addClass('invalid');
            $('#username_feedback').addClass('error').html("Your username must be atleast 4 characters.");
            option=false;
        }
        else
        {
            $.post('php/check_username_avail.php',{ username : username },function(data){

                if(data == "false")
                {

                    $('#username').removeClass('valid').addClass('invalid');
                    $('#username_feedback').addClass('error').html("Sorry! That username is already taken. Try a different one.");
                    option= false;
                }
                else if(data == "true")
                {
                    $('#username').removeClass('invalid').addClass('valid');
                    $('#username_feedback').html("");
                    alert('Now it should return true');
                     option=true;
                }
                else
                {
                    $('#username').removeClass('valid').addClass('invalid');
                    $('#username_feedback').addClass('error').html(data);
                    option=false;
                }
            }).error(function(){
                alert("An error occurred. Unable to validate username");
            });
        }
        return option;
}
</code>
EDIT: I've read the other post. But I still don't find a way to validate the form. I want to use this submit handler function with my code:
<code>$('#signup_form').submit(function(event)
{
  if(isvalid_first_name() && isvalid_username() && isvalid_email() && isvalid_password())
  {
    alert('Submitting the form');
  }
  else
  {
   event.preventDefault();
   $('#submit_feedback').html("Please correct the above problems first");
  }

});
</code>
If it can't be done this way, then what other technique should I use to validate the form on clientside?
Comment: FYI, `error` is deprecated, use `fail`
Comment: Ok! done. Also understood the problem with my code. But didn't get the solution.
Comment: If I use promises, Then how should I change my handler so that the form validation is not affected?
Answer: Well because you not waiting for AJAX to complete and returning option right away which is already false. Try below code.
<code>    function isvalid_username(){
      var username=$('#username').val();
      var option=false;
        if(username == "")
        {
            $('#username').removeClass('valid').addClass('invalid');
            $('#username_feedback').addClass('error').html("Please choose a username!!");
             return option;
        }
        else if(username.length < 4)
        {
            $('#username').removeClass('valid').addClass('invalid');
            $('#username_feedback').addClass('error').html("Your username must be atleast 4 characters.");
             return option;
        }
        else
        {
            $.post('php/check_username_avail.php',{ username : username },function(data){

                if(data == "false")
                {

                    $('#username').removeClass('valid').addClass('invalid');
                    $('#username_feedback').addClass('error').html("Sorry! That username is already taken. Try a different one.");
                     return option;
                }
                else if(data == "true")
                {
                    $('#username').removeClass('invalid').addClass('valid');
                    $('#username_feedback').html("");
                    alert('Now it should return true');
                    option=true;
                    return option;
                }
                else
                {
                    $('#username').removeClass('valid').addClass('invalid');
                    $('#username_feedback').addClass('error').html(data);
                     return option;
                }
            }).error(function(){
                alert("An error occurred. Unable to validate username");
            });
        }
}
</code>
Comment: You cannot return from ajax call. In jquery, this will always returns the promise interface


let $f : \mathbb{R} \setminus \{0\} \to \mathbb{R}$ be differentiable on $\mathbb{R} \setminus \{0\}$

Question:
let $f : \mathbb{R} \setminus \{0\} \to \mathbb{R}$ be differentiable on $\mathbb{R} \setminus \{0\}$
  And :
$$f(xy)=f(x)+f(y)$$
  And:
  $$f'(1)=1$$
  prove that : $$f(x)=\int_1^{|x|} \dfrac{dt}{t}$$

Suppose:Not aware of $e^x , \ln x $ .
I can not. please help me !
Comment: You can't prove that, because any _other_ logarithm also works. At best you can prove that $f(x)=\int_1^{|x|}\frac ktdt$ for some $k$.
Comment: @Arthur. when $ k=1$ ?
Comment: If we want to prove that $k=1$, then we need to know more about $f$ than we already do. Like $f'(1)=1$, for instance; if we add that to our assumptions along with $f(xy)=f(x)+f(y)$, then we can prove that $k=1$.
Comment: @Arthur. I edited .now it's true ?
Answer: As stated in a comment, $f$ can actually be any scalar multiple of what you claimed it is. First, note that $f(1)=f(1\cdot 1) = 2f(1)$, and so $f(1)=0$. Further,
$$f'(x)=\frac{\partial }{\partial x} (f(x)+f(y))=\frac{\partial}{\partial x}f(xy) = yf'(xy)$$
Letting $x=1$ gives us $f'(1)=yf'(y)$, i.e.
$$f'(y) = \frac{f'(1)}{y}$$
An application of the FTOC tells us that, for $y>0$
$$f(y) = \int_1^y\frac{f'(1)}{t}\,dt = \int_1^{\vert y\vert}\frac{f'(1)}{t}\,dt$$
Now note that $0=f(1)=f(-1)+f(-1)\implies f(-1)=0$. Then the FTOC tells us that, for $y<0$,
$$f(y) = \int_{-1}^y \frac{f'(1)}{t}\, dt=-\int_{-y}^{1}\frac{f'(1)}{t}\,dt = \int_{1}^{\vert y \vert}\frac{f'(1)}{t}\, dt $$
The second equality holds because the integrand is odd (or alternatively, using the substitution $t\mapsto -t$).
Answer: Let $x > 0$ .  Now Define $g(t)=f(e^t)$ for all $t \in R$. We come up $$g(t+s)=g(t)+g(s)$$  Now by differentiating both side with respect to $t$ we have $$g'(t+s)=g'(t)$$
for all $s \in R$, this means $g'(t)=g'(0)=f'(1)=1$ (contant) for all $t \in R$.  Therefore $$g(t)=t+g(0) = t$$  now by changing variable $x=e^t$ we have $$f(x)= \ln x = \int_1^{x} \dfrac{dt}{t}$$


Im6 chord in a minor II-V-I

Question: In a minor II-V-I progression, we usually have a IIm7(b5) chord followed by a V7(b9,b13) chord, resolving into Im7. I always thought the diminished 5th in the II chord (also the minor 9th in the V7 chord, same note) was like a "hint" that a minor chord was coming, since it corresponds to the minor 6th of the I chord. That would be F in A minor/C major.
If you analyze the progression from a relative major standpoint:
VIIm7(b5) _ V7/VI(b9,b13) -> VIm7

In a major harmony, the VIm7 is related to the Aeolian mode and should have a minor 6th, right?
However, it came to my attention that some standards, like Autumn Leaves and Caravan (no II here, but a long time spent on V7b9), have this chord written and played as Im6 sometimes, with a major 6th instead. Is there a particular reason for this?
Edit: Is this a chord substitution? Some substitutions are based in harmonic concepts, like the tritone substitution. Does this major 6th thing have such an underlying concept?
Comment: [A minor 6th chord is spelled 1 b3 5 6 which with a root of E is  E G B C#](http://music.stackexchange.com/questions/16932/why-does-a-cm13-chord-use-a-instead-of-ab). It's like any other substitution in Jazz it's function is _similar_, but the flavor is different.
Comment: I don't understand the downvote. This is a very relevant question.
Comment: Which chord is Im6 in Autumn Leaves? I've seen many different music sheets for the song, but never once seen a m6 chord  there; it isn't on the real book either. Ι've never seen any major 6th chord either there. But if you saw a I6, it is a common substitution for Imaj7
Comment: Em6 in G major versions, last chord of it's A section. Please note that it's Im6 in minor harmony (VIm6 in a major key like Autumn Leaves). https://www.youtube.com/watch?v=KoxY_xPmJXg
Comment: So, your question is why is there a C in the E minor chord?
Comment: No, C is the minor 6th of E. I'm asking about the C#, which is the major 6th. Is my question unclear?
Comment: Thank you for the link! However, I know how the chord is spelled. Most substitutions are based in harmonic concepts, like the tritone substitutions. Can you elaborate on this particular major 6th substitution? Does it have some kind of underlying concept? This is what I want to know.
Comment: @Shevliaskovic, you're right that books don't typically write in a `min6` chord. I think it was Miles Davis who popularized that sound--he actually [played the natural 6th](https://www.youtube.com/watch?v=dsp5OASh7bg#t=1m04s) in the melody over the minor i chord. This sound has become fairly common because many musicians use the intro from that same recording, which features a `G min 6` arpeggio in the bass and piano.
Answer: You are right that in minor the minor sixth of the key is part of the II chord, and it is a tension (b9) that is very often used on the V chord. However, it is not a valid tension on the I chord, because the minor sixth is an avoid note on that chord (basically because it is a half step above a basic chord tone, the 5). In this blog post you can read more about avoid notes.
On the other hand, the major sixth is a valid tension on the I chord in minor. A minor 6 chord always contains the major sixth. It comes from the melodic minor scale. The I chord in minor comes in three basic flavors: Im6 (with a major 6th), Im7 (with a minor 7th), and Im maj7 (with a major 7th). The corresponding chord scales are melodic minor (for Im6 and Im maj7), and dorian (for Im7).
Comment: The linked blog post is an outstanding resource. It might be worth mentioning that a `I min6` chord doesn't *require* melodic minor. Dorian can also be used over a `I min6` chord.
Comment: @jdjazz: Thanks! ( I wrote that post :) And indeed, of course a minor 6th chord doesn't require anything, it's just that melodic minor is the most common and most natural choice, because it has no avoid notes when played over a m6 chord. Dorian contains all chord tones as well, but its 7th degree is an avoid note over that chord because it is a half step above the 6th. Melodic minor and dorian relate to a m6 chord a bit like Dorian and Aeolian to a m7 chord: both are possible but one is more natural because of the lack of an avoid note.
Answer: I think the answer to your overarching question is: there's no requirement that the ii chord or the V chord share the same scale/chord tones as the i chord. The ii-V-i progression will still sound good even whether or not a common scale is used across all three chords.
For example, it's not uncommon to play a Locrian ♯2 scale over the ii chord, an altered scale over the V chord, and then a melodic minor scale over the i chord. If you take a ii-V-i in G min, this would be equivalent to playing these chords and scales, respectively:
|       Aø7       |       D7alt      |       Gmin      |       Gmin      |
| C melodic minor | E♭ melodic minor | G melodic minor | G melodic minor |
There are plenty of notes that aren't shared across these three scales, but those scales nonetheless sound good over the ii-V-i.
That said, there might be reasons for choosing to play Aeolian vs. Dorian vs. melodic minor over the i chord. Matt L. mentions one possible reason for choosing dorian over Aeolian--because Dorian has fewer avoid tones. On the other hand, one might choose Aeolian for continuity with the V alt chord, as you suggest in your original post. Another factor one could consider when choosing a scale is the melody--if the melody uses a ♭6th over the i min chord, then maybe the solos should too. But there is no prescribed scale and the soloist often has freedom to choose which to use. So the Aeolian can be a great sound even despite its ♭6 avoid tone, but there's no rule that Aeolian is required over the i min chord to create continuity with the iiø or V7alt chords.
A couple notes:
A i min6 chord is extremely common on Autumn Leaves, in large part thanks to Miles Davis, who in bar 7 plays the natural 6th in the melody instead of the root. (This link starts after the intro, and the natural 6th is heard at 1:06.)
Playing i min6 instead of i min7 doesn't qualify as a substitution because we're playing the same chord, just with different alterations.

Im6 chord in a minor II-V-I


How to Map Desired Confidence Interval to a Quantile value

Question: I want to calculate the N% confidence interval for some time-series data set. I have the standard errors for this data series and the error variance of the time-series is assumed to be Gaussian. I understand that we can use a factor of ±1.96 multiplied by the standard error of each data point to obtain the 95% confidence interval (because it is the quantile 0.975 of the Gaussian distribution) [the exact specifics of the standard errors is not important].
I know I am able to get this value of 1.96 by calculating the Inverse Cumulative Distribution Function for the Normal distribution (`InvCDF(0.975) ~ 1.96), what I don't understand is how to map the quartile value (0.975) to the desired confidence interval. What I want is to be able to say is: "I want the 87% confidence interval" and then calculate InvCDF(X), but what is X in this case? And what function relates the quantile value to the confidence interval?
Thanks for your time.
Comment: Are you asking about how one obtains $0.975$ from the 95% specification?
Comment: Yes. That is exactly why I am asking...
Answer: For a two-sided confidence interval, a N% confidence interval requires the quantile 1-(1-N)/2 for the upper bound of the interval and (1-N)/2 for the lower bound. In this way, the (1-N)% of the mass is split symmetrically in both tails of the normal distribution. For a 87% confidence interval you would have 1.87/2=0.935 and (1-0.87)/2=0.065 and the quantile values are ± 1.514.


A determinant always $\ge 0$

Question: How can I prove that this determinant is always bigger (or equal) than $0$? I've done this using the hard working method of determinant calculation, but I'm curious how can be done using the determinant properties.
\begin{vmatrix}
 a_{1}^{2}+a_{2}^{2}+a_{3}^{2} &  a_{1}b_{1}+a_{2}b_{2}+a_{3}b_{3} \\
 a_{1}b_{1}+a_{2}b_{2}+a_{3}b_{3} & b_{1}^{2}+b_{2}^{2}+b_{3}^{2}
\end{vmatrix}
Is known that all of them are real numbers.
Answer: I guess that the simples way to do this is by noticing that
$$ \begin{pmatrix}
 a_{1}^{2}+a_{2}^{2}+a_{3}^{2} &  a_{1}b_{1}+a_{2}b_{2}+a_{3}b_{3} \\
 a_{1}b_{1}+a_{2}b_{2}+a_{3}b_{3} & b_{1}^{2}+b_{2}^{2}+b_{3}^{2}
\end{pmatrix}
= \begin{pmatrix}
|a|^2 & a \cdot b\\
a\cdot b & |b|^2
\end{pmatrix}, $$
where $a = (a_1,a_2,a_3)$ and $b = (b_1,b_2,b_3)$, and then
$$
\begin{vmatrix}
|a|^2 & a \cdot b\\
a\cdot b & |b|^2
\end{vmatrix}
= |a|^2|b|^2-(a\cdot b)^2 \geq 0
$$
follows immediately from the Cauchy-Schwartz inequality.
Answer: Notice that your matrix is equal to
$$\begin{bmatrix}
 a_{1}^{2}+a_{2}^{2}+a_{3}^{2} &  a_{1}b_{1}+a_{2}b_{2}+a_{3}b_{3} \\
 a_{1}b_{1}+a_{2}b_{2}+a_{3}b_{3} & b_{1}^{2}+b_{2}^{2}+b_{3}^{2}
\end{bmatrix} = \begin{bmatrix}
 a_1 & a_2 & a_3 \\
 b_1 & b_2 & b_3 \\
\end{bmatrix} \begin{bmatrix}
 a_1 & b_1  \\
 a_2 & b_2  \\
 a_3 & b_3
\end{bmatrix}$$
and matrices of the form $AA^T$ always have nonnegative determinant.
Answer: The working method of determinant calculation is not so hard if you  use the Cauchy-Schwarz inequality appied to $(a_1,a_2,a_3)$ and $(b_1,b_2,b_3)$.
$|\langle (a_1,a_2,a_3);(b_1,b_2,b_3)\rangle |\leq \|(a_1,a_2,a_3)\|\|(b_1,b_2,b_3)\|$ which is equivalent to say that $|a_1b_1+a_2b_2+a_3b_3|^2\leq (a_1^2+a_2^2+a_3^2)(b_1^2+b_2^2+b_3^2)$.
Comment: That's a great idea.Thank you!

A determinant always $\ge 0$


Extract age from a string-python

Question: Consider this string:
s="""A25-54 plus affinities targeting,Demo (AA F21-54),
A25-49 Artist Affinity Targeting,M21-49 plus,plus plus A 21+ targeting"""

I am looking to fix my pattern which currently does not pull all the age groups in the string (A 21+ is missing from the current output).
Current try:
import re
re.findall(r'(?:A|A |AA F|M)(\d+-\d+)',s)

Output:
['25-54', '21-54', '25-49', '21-49'] #doesnot capture the last group A 21+

Expected Output:
['A25-54','AA F21-54','A25-49','M21-49','A 21+']

As you see, I would like to have the last group too which is A 21+ which is currently missing from my output.
Also if I can get the string associated with the capture group. presently my output apart from not capturing all the groups doesnt have the string before the age group. eg: I want 'A25-54 instead of '25-54' , i guess because of ?: .
Appreciate any help I can get.
Answer: The missing part of the match is due to the fact your pattern contains one capturing group and once there is a capturing group in the regex, the re.findall only returns that parts. The second issue is that you should match either - followed with 1 or more digits or a literal + symbol after the first one or more digits are matched.
You may use
(?:A|A |AA F|M)\d+(?:-\d+|\+)

NOTE: You might want to add a word boundary at the start to only match those A, AA F, etc. as whole words: r'\b(?:A|A |AA F|M)\d+(?:-\d+|\+)'.
See the regex demo and the regex graph:

Details

(?:A|A |AA F|M) - a non-capturing group matching A, A , AA , AA F or M
\d+ - 1+ digits
(?:-\d+|\+) - a non-capturing group matching - and 1+ digits after it or a single + symbol.

Python demo:
import re
s="""A25-54 plus affinities targeting,Demo (AA F21-54),
A25-49 Artist Affinity Targeting,M21-49 plus,plus plus A 21+ targeting"""
print(re.findall(r'(?:A|A |AA F|M)\d+(?:-\d+|\+)',s))
# => ['A25-54', 'AA F21-54', 'A25-49', 'M21-49', 'A 21+']

Comment: FYI: You may contract the first group further as `(?:A(?: |A F)?|M)\d+(?:-\d+|\+)`. It is less readable but it follows the best practices: each alternative inside a group should not match at the same location as other groups.

Extract age from a string-python


linq-to-sql won't serialize references

Question: So I have a couple of tables in a linq-to-sql dbml file:

I have set up a WCF REST get endpoint to user. I cannot get it to pass back a JSON structured like this:
<code>{
    ID: '123',
    Username: 'fdsaf',
    ...
    Role:
    {
        ID: '123',
        ...
    }
}
</code>
If I set the DBML serialization mode from "None" to "Unidirectional," I can get the user object without the role. If I leave the serialization mode on none and remove the association, I can also get the user object. As a sanity check, I can also get the role with no user. As soon as I try to include a reference, it attempts to serialize twice (in the debugger) and I get the following error after what appears to be a successful function call on the client:

Additionally, I can get what I'm looking for if I open the association and turn the child property access to internal. However, I will sometimes want to pass back roles with collections of users, so this will not be sufficient.

I include this piece of information because it seems to indicate that the serializer is trying to serialize User > Role > User > Role ... etc., which is obviously insufficient. But there must be a middle ground between a circular and a zero-level-deep reference.
Code below:
<code>using (DataContext context = new DataContext())
{
    DataLoadOptions opts = new DataLoadOptions();
    opts.LoadWith<User>(u => u.Role);
    context.LoadOptions = opts;

    return context.Users
        .Where(u => u.ID == id)
        .Where(u => u.Hash == hash)
        .FirstOrDefault();
}
</code>
Comment: This approach doesn't work with JSON.
Answer: I would create a mapped object instead of a user and give it an array of roles, Mainly because you are passing back a raw data object which includes the password and raw hash of a user. You can then hide these in the mapping
Have one model for each,
UserObject with a child of Roles and a
RolesObject with a child of User.
Alternatively, have a property that you can serialize on each that will return pseudo objects
so roles could be an array of id/strings and so could users (then you ignore serialization on the relationship and serialize that instead, no circular reference problems)
Comment: Not really, you are querying a relational database which if you want to serialize out everything will give you circular references.

The xml cannot have circular references due to the nature of the doc type, so you have to get creative in how you pass the items through, to include children they must be orphaned, unless you serialize a different item without relationship info your object will have links to the hierachy and throw a wobbly

EntityFramework will do the same issue, in fact I'm pretty sure almost all ORMs will. It's not a library specific issue. You get the same issue with SOAP
Comment: This almost makes using linq-to-sql useless, though.
Comment: You need a specialised serialised object to do this (you can retain Ids fine, but the serialized object cannot contain a reference to the parent object as you do currently with the user/role)

Linq2SQL may have a way to add attributes to the parent/child to not serialize the item but I'm not aware of it. A disconnected mapping class lets you avoid exposing sensitive items as well as control exposed relationships for each set, you would return inactive roles that are linked. To put it simply... you don't use linq to sql to serialize an objects as it's a query tool
Comment: I was just hoping the simple logic to avoid circular references in the very obvious use case would have been included in the default json serializer: When serializing this child, do not include a reference to this parent. JSON.net includes this logic, but I can't figure out how to point WCF to use JSON.net as the default serializer.
Comment: You set the default endpoint behaviour to Json. There is an example here:
http://stackoverflow.com/questions/12902319/is-it-possible-to-set-the-request-response-format-in-web-config

linq-to-sql won't serialize references


How to determine shape of level curves of $V(y,z)= \ln{ \left( \frac{y^2 + (z+z_o)^2}{y^2 + (z-z_o)^2}\right)} $?

Question: Context:
I expect that a circle will be written as
$$R^2 = (x-a)^2 + (y-b)^2,$$
where $R$ is the radius, and $(a,b)$ is the center of the circle.
Question:
How to determine analytically that the level lines of
$$V(y,z)=  \ln{ \left(  \frac{y^2 + (z+z_o)^2}{y^2 + (z-z_o)^2}\right)}$$
are circles?
Comment: Take exponentials on both sides for constant values of $V$ and you will end up with the equation of a circle.
Comment: Please see my answer
Answer: Isocontours of $V$ are represented by constant values of the function, i.e., $V=C$, which yields
$$C = \ln{ \left(  \frac{y^2 + (z+z_o)^2}{y^2 + (z-z_o)^2}\right)} \implies
\mathrm{e}^C = \left(  \frac{y^2 + (z+z_o)^2}{y^2 + (z-z_o)^2}\right)$$
Now rearrange to have
$$A \left[y^2 + (z-z_o)^2\right] = y^2 + (z+z_o)^2 $$
or, equivalently
$$ (A-1) y^2 + A(z-z_o)^2 - (z+z_o)^2 = 0,$$
with $A = \mathrm{e}^C $. Upon completing the square*, one has (if I didn't mess up)
$$ y^2 + (z-B)^2 = \frac{D}{A-1}, $$
where $B = z_o(A+1)/(A-1)$, and $D = 4Az_o^2/(A-1)$.

*Credit to this step goes to this answer.


Proper way to join these tables?

Question: I am attempting to learn the difference in JOIN and LEFT JOIN. I watched several youtube videos and researched Google. However, I can't quite grasp why my JOIN query is not working. If I run the sql I get Column 'user_id' in field list is ambiguous.
sales table
sales_id   user_id   amount    date         status
3          1         1258.32   2013-07-02   S

users table
user_id   fname   lname
1         John    Doe

My Code:
$top = mysqli_query($mysqli, "SELECT user_id, fname, lname, SUM(amount) as total
FROM sales
LEFT JOIN users ON
user_id.sales = user_id.users
WHERE status = 'S' AND MONTH(date) = MONTH(CURDATE()) AND YEAR(date) = YEAR(CURDATE()) GROUP BY user_id ORDER BY total DESC LIMIT 5");

     while($row = mysqli_fetch_assoc($top)) {
           $topamount[]     = $row['total'];
           $topfnameuser[]  = $row['fname'];
           $toplnameuser[]  = $row['lname'];
     }

Answer: Since both sales and users have a column named user_id, you have to be specific in your SELECT list about which you want:
SELECT sales.user_id as user_id, fname, lname, SUM(amount) as total
FROM sales
LEFT JOIN users
ON sales.user_id = users.user_id
WHERE status = 'S' AND MONTH(date) = MONTH(CURDATE()) AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
ORDER BY total DESC
LIMIT 5

You also had the table and column names backwards in the ON clause. It's table.column, not column.table
Comment: Thanks once again!! You rock!
Answer: I think you have miss understanding with the using of LEFT JOIN,
Try this..
I have create table like you want, and I have error if i use your query and solve it so the query like this
SELECT fname,lname, SUM(amount) AS total
  FROM users LEFT JOIN sales
  ON users.user_id = sales.user_id
    WHERE sales.status = 'S' AND MONTH(sales.date) = MONTH(CURDATE()) AND YEAR(sales.date) = YEAR(CURDATE()) GROUP BY users.user_id
ORDER BY total DESC LIMIT 5

Answer: Focusing on the "attempting to learn the difference in JOIN and LEFT JOIN" part, outer joins are useful when you want to see all rows from one table, even those that have no corresponding rows in another related table.
Here's a simple example using students and test grades.
create table students (student_id serial primary key, student_name text);
create table tests (test_id serial primary key, test_name text, test_date date);
create table grades (
    student_id int,
    test_id int,
    grade char,
    primary key (student_id, test_id),
    foreign key (student_id) references students (student_id),
    foreign key (test_id) references tests (test_id));

insert into students (student_name) values ('joe');
insert into students (student_name) values ('amber');
insert into students (student_name) values ('steve');

insert into tests (test_name, test_date) values ('test 1', '2013-01-20');
insert into tests (test_name, test_date) values ('test 2', '2013-02-10');

insert into grades (student_id, test_id, grade) values (1, 1, 'A');
insert into grades (student_id, test_id, grade) values (1, 2, 'B');
insert into grades (student_id, test_id, grade) values (2, 1, 'B');
insert into grades (student_id, test_id, grade) values (2, 2, 'A');

The following query would return a list of students and their grades, including one row identifying students without any grades yet (in this case, Steve):
select s.student_name, t.test_name, t.test_date, g.grade
from students as s
left join grades as g on s.student_id = g.student_id
left join tests as t on g.test_id = t.test_id;

student_name | test_name | test_date  | grade
--------------+-----------+------------+-------
joe          | test 1    | 2013-01-20 | A
joe          | test 2    | 2013-02-10 | B
amber        | test 1    | 2013-01-20 | B
amber        | test 1    | 2013-01-20 | A
steve        |           |            |
(5 rows)

One really useful way to use outer joins is when you want to see only rows without matching rows in the related table.  You can also do this with a subquery, but using an outer join isn't a bad option:
select s.student_name
from students as s
left join grades as g on s.student_id = g.student_id
where g.student_id is null;
student_name
--------------
steve
(1 row)

...is functionally equivalent to:
select student_name from students where student_id not in (select student_id from grades);
student_name
--------------
steve
(1 row)

Answer: You use JOIN when a given id is in both tables that you are joining.
You use LEFT JOIN when a given id is in one table and maybe in the second one
In your case you should select from users and left join sales
SELECT u.user_id, u.fname, u.lname, SUM(s.amount) as total
FROM users u LEFT JOIN sales s ON s.user_id = u.user_id
WHERE s.status = 'S' AND MONTH(s.date) = MONTH(CURDATE()) AND YEAR(s.date) = YEAR(CURDATE())
GROUP BY u.user_id
ORDER BY total DESC LIMIT 5

Note the alias in table naming (users u). Then with that alias you can specify which column from which table to select.
Also I will recommend not to name a column "date" because it's a reserved word by MySQL. See: http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
Answer: Introduce a table alias so you can refer to it when referencing fields. Your issue is you have user_id in both tables and you have not defined which table to read the user_id from.
"SELECT s.user_id, u.fname, u.lname, SUM(s.amount) as total
FROM sales AS s
LEFT JOIN users AS u ON
s.user_id = u.user_id

Proper way to join these tables?


How to play audio byte array (not file!) with JavaScript in a browser

Question: For mostly security reasons, I'm not allowed to store a WAV file on the server to be accessed by a browser. What I have is a byte array contains audio data (the data portion of a WAV file I believe) on the sever, and I want it to be played on a browser through JavaScript (or Applet but JS preferred), I can use JSON-PRC to send the whole byte[] over, or I can open a socket to stream it over, but in either case I don't know who to play the byte[] within the browser?
Answer: The following code will play the sine wave at 0.5 and 2.0.  Call the function play_buffersource() in your button or anywhere you want.
Tested using Chrome with Web Audio flag enabled.  For your case, all that you need to do is just to shuffle your audio bytes to the buf.

References:

http://epx.com.br/artigos/audioapi.php
https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html

If you need to resample the audio, you can use a JavaScript resampler: https://github.com/grantgalitz/XAudioJS
If you need to decode the base64 data, there are a lot of JavaScript base64 decoder: https://github.com/carlo/jquery-base64
Comment: this dosen't work on firefox! isn't there a way to make it work ?
Comment: The noteOn() function has been replaced by start() since this answer was written. See https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Migrating_from_webkitAudioContext
Answer: I accomplished this via the following code.  I pass in a byte array containing the data from the wav file to the function playByteArray.  My solution is similar to Peter Lee's, but I could not get his to work in my case (the output was garbled) whereas this solution works well for me.  I verified that it works in Firefox and Chrome.
window.onload = init;
var context;    // Audio context
var buf;        // Audio buffer

function init() {
    if (!window.AudioContext) {
    if (!window.webkitAudioContext) {
        alert("Your browser does not support any AudioContext and cannot play back this audio.");
        return;
    }
        window.AudioContext = window.webkitAudioContext;
    }

    context = new AudioContext();
}

function playByteArray(byteArray) {

    var arrayBuffer = new ArrayBuffer(byteArray.length);
    var bufferView = new Uint8Array(arrayBuffer);
    for (i = 0; i < byteArray.length; i++) {
      bufferView[i] = byteArray[i];
    }

    context.decodeAudioData(arrayBuffer, function(buffer) {
        buf = buffer;
        play();
    });
}

// Play the loaded file
function play() {
    // Create a source node from the buffer
    var source = context.createBufferSource();
    source.buffer = buf;
    // Connect to the final output node (the speakers)
    source.connect(context.destination);
    // Play immediately
    source.start(0);
}

Comment: What is bufferView meant to be doing?
Comment: @patrickdamery it's a composition over the buffer that's used to mutate its contents (that's why you don't see any further use of it after the iteration ends)
Answer: If you have the bytes on the server then I would suggest that you create some kind of handler on the server that will stream the bytes to the response as a wav file.  This "file" would only be in memory on the server and not on disk.  Then the browser can just handle it like a normal wav file.
More details on the server stack would be needed to give more information on how this could be done in your environment.
Answer: I suspect you can achieve this with HTML5 Audio API easily enough:
https://developer.mozilla.org/en/Introducing_the_Audio_API_Extension
This library might come in handy too, though I'm not sure if it reflects the latest browser behaviours:
https://github.com/jussi-kalliokoski/audiolib.js
Comment: @Pi Of course not. It's a standard now. Why would IE implement a standard? Don't be silly!
Comment: Thanks! But this seems to use a floating sample, my wav audio raw data is mono 16K Hz and base64 bytes, do I need convert it? How?
Comment: The first link says that this function is now deprecated, and the replacement https://developer.mozilla.org/en-US/docs/Web_Audio_API#Browser_compatibility  is not supported by Internet Explorer! Is there any solution that works for all browsers?


PDF of Conditional Distribution

Question: Suppose that $X\sim N(0,1)$.  Find the distribution of $Y$ if $Y=X\mid X>0$.
Normally when I find conditional distributions, it's when one random variable is conditioned on another, and is the quotient of a joint and marginal PDF.  However, in this situation, this is a random variable that's conditioned on its own value... so I'm not quite sure what steps I should take to derive the PDF.  How do you do this?
Remember, I'm interested in HOW to derive the PDF, not simply knowing what it is.
Comment: I don't understand what is meant by $Y=X\mid X>0.$ Does this mean the conditional distribution of $X$ given the event that $X>0\text{ ?}$ If so this looks like an instance of the freshman mistake of thinking that $X\mid X>0$ is object whose distribution is sought, rather than that $X$ is a random variable whose conditional distribution given the event $X>0$ is sought.
Answer: As per usual, it is probably helpful to derive the CDF and then obtain the PDF by differentiation. We have $$ P(X>x \mid X>0) = \frac{1}{P(X>0)}P(X> x,X>0) = \frac{P(X>x)}{P(X>0)}1_{x>0} + 1_{x\le 0}.$$ The conditional CDF is just one minus this, so the PDF is $$ f(x\mid X>0) = -\frac{d}{dx}P(X>x \mid X>0) = -1_{x>0}\frac{1}{P(X>0)}\frac{d}{dx}P(X>x) = \frac{1_{x>0}}{P(X>0)}f_X(x).$$
In retrospect it might have been easier to simply guess that the conditional PDF should be the same as the old one for positive numbers (since the relative proportions amongst the positive numbers must be the same), and just needs a new normalization factor so it integrates to one over the positive numbers instead of over the real line.

PDF of Conditional Distribution


Not able to Switch Layout to RTL when arabic text is sent over Push Notification in Android

Question: So i'm trying to send Arabic Text over push notification, i have an image and a textview in a remoteview, when i send the text in english it works perfectly, but if i send it as arabic, then i'm able to receive the text but i'm not able to show it in RTL form, i've enabled RTL in manifest and also used
<code>android:autoMirrored="true"
</code>
but for some reason, the text aligns itself onto the right but the image remains on the left itself, which shouldnt be the case
this is my layout, any help would be deeply appreciated
<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4dp">

   <ImageView
     android:id="@+id/big_icon"
     android:layout_width="40dp"
     android:layout_height="40dp"
     android:paddingBottom="1dp"
     android:autoMirrored="true"
     android:layout_gravity="center_vertical"
     android:paddingLeft="2dp"
     android:paddingRight="2dp"
     android:src="@mipmap/icon"/>

   <TextView
     android:id="@+id/content_title"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:maxLines="2"
     android:layout_toRightOf="@+id/big_icon"
     android:layout_gravity="center_vertical"
     android:ellipsize="end"
     android:text="Notification Sample App"
     android:textAppearance="@style/TextAppearance.Compat.Notification.Title"/>

</RelativeLayout>
</code>
This is what i'm getting
Comment: Add the line `android:supportsRtl="true"` in  AndroidManifest.xml .
Comment: I've already enabled it, since my app supports localization, it's already there
Comment: Check https://stackoverflow.com/questions/44589596/android-set-rtl-support-on-push-notification.
Answer: use this inside textview android:textAlignment="start"
Comment: It's more about the image I feel, as you can see in the screenshot


Set document root in Zend Framework 1.12.x application in Azure Cloud Service

Question: in relation to my other question on how to set the document root for a Azure Web Site, I would like to know how to do the same with a Cloud Service.
I've used the Azure Powershell Tools to create a package of my application and succesfully uploaded it to the cloud. But setting document root is not working.
My ServiceDefinition.csdef looks like this:
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="myCloudService" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
    <WebRole name="myWebRole" vmsize="ExtraSmall">
    <Imports />
    <Startup>
      <Task commandLine="setup_web.cmd > log.txt" executionContext="elevated">
        <Environment>
          <Variable name="EMULATED">
            <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
          </Variable>
          <Variable name="RUNTIMEVERSIONPRIMARYKEY" value="5.3.17" />
          <Variable name="RUNTIMEID" value="PHP" />
          <Variable name="RUNTIMEURL" value="http://az413943.vo.msecnd.net/php/5.3.17.exe" />
        </Environment>
      </Task>
    </Startup>
    <Endpoints>
      <InputEndpoint name="Endpoint1" protocol="http" port="80" />
    </Endpoints>
    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="Endpoint1" endpointName="Endpoint1" />
        </Bindings>
      </Site>
    </Sites>
</WebRole>
</ServiceDefinition>

Now I've tried setting the physicalDirectoryPath for the site directly
<Sites>
  <Site name="Web" physicalDirectory="../htdocs">
    ...
  </Site>
</Sites>

and I've tried to use a VirtualApplication, but both don't seem to work.
<Sites>
  <Site name="Web">
    <VirtualApplication name="MyWeb" physicalDirectory="../htdocs" />
    ...
  </Site>
</Sites>

Any help?
Answer: Following a Blog entry, I found a solution that works. I'll sum it up to give a quick insight on how to do it:
Link: Change your azure websites root folder
You have to add da startup task in your ServiceDefinition.csdef file
<Startup>
    <Task commandLine="changeroot.cmd" executionContext="elevated" taskType="background" />
</Startup>

This instructs each instance on startup to execute 'changeroot.cmd'. This file hast to go into the /bin directory of your web role instance directory.
This contains the following code:
@echo off
cd "%~dp0"

icacls %RoleRoot%\approot /grant "Everyone":F /T

powershell.exe Set-ExecutionPolicy Unrestricted
powershell.exe .\changeroot.ps1
ECHO Changeroot Run. >> ..\startup-tasks-log.txt

This will execute the powershell changeroot.ps1 script, with elevated user right, that will move the physicalPath of the site in IIS once it is created. This also has to go into your /bin path in your web role.
It contains the following code:
$siteName = "Web"
$serverIP = "127.0.0.1"
$newPath = "htdocs" ## your document root

$pathset = $false
$trycount = 0

##loop until physical path has changed
while($pathset -eq $false) {
   $trycount += 1

   ##if the role id can be determined
   if([Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::CurrentRoleInstance.Id -ne $null)
   {
          $fullName = [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::CurrentRoleInstance.Id + "_" + $siteName
          $op = "Changeroot: Site Full Name: $fullName`r`n"
          Write-Output $op | Out-File -Encoding Ascii ..\startup-tasks-log.txt

          ##init server manager
          $serverManager = [Microsoft.Web.Administration.ServerManager]::OpenRemote($serverIP)
          if($serverManager -ne $null)
          {
                 $op = "Changeroot: Site Manager Setup`r`n"
                 Write-Output $op | Out-File -Encoding Ascii ..\startup-tasks-log.txt

                 ##load site
                 $site = $serverManager.Sites | where { $_.Name -eq $fullName }
                 if($site -ne $null)
                 {
                       $op = "Changeroot: Site loaded ($fullName)`r`n"
                       Write-Output $op | Out-File -Encoding Ascii ..\startup-tasks-log.txt
                       ##change physical path
                        $rootApp = $site.Applications | where { $_.Path -eq "/" }
                       $rootVdir = $rootApp.VirtualDirectories | where { $_.Path -eq "/" }
                       $dir = $rootVdir.PhysicalPath.EndsWith('\')
                       if($dir -eq $true) {
                              $rootVdir.PhysicalPath += $newPath + "\"
                       } else {
                              $rootVdir.PhysicalPath += "\" + $newPath + "\"
                       }
                       $serverManager.CommitChanges()
                       $op = "Root changed for $fullName (after $trycount tries)`r`n"
                       Write-Output $op | Out-File -Encoding Ascii ..\startup-tasks-log.txt
                       $pathset = $true
                       exit
                 }
          }
   } else {
          startup-tasks-log.txt
   }
   # Restart the loop in 5 seconds
   Start-Sleep -Seconds 5
}

This finally worked for me.
For a more detailed explanation please follow the link.
An added precaution:
Make sure you build your package (or deploy using publish-azureserviceproject) using a build machine that has a matching (or lesser) .net framework as your cloud host. If deploying on a Windows 8.1 machine, you may need to make sure your OSFamily is set to 4. In order to verify that your .net runtimes  aren't newer on your build machine than they are on your cloud host:

open a powershell on both machines
take a look at [System.Environment]::Version or if you're using powershell 2.0 or newer, you can look at the $PSVersionTable variable

The problems you'll run into if you don't do this - you likely won't be able to use any of the Azure Assemblies such as Microsoft.WindowsAzure.ServiceRuntime. Changing the Physical Path of a web site depends on knowing the web site name and this is only (dynamically) available in that assembly.
Comment: This solution no longer seems to work. running the changeroot task throws errors and causes the cloud service to not be started properly.
Comment: This solution does work unlike what I originally found - it just requires your deploying host to not have a newer .net framework than your cloud host. I was deploying from win 8.1 and WindowsAzure.ServiceRuntime assembly was not loading. I'm going to edit the answer to add this precaution simply so I can change my downvote to an upvote.


How can I in R, group by ID and summarise by mean with na.rm = TRUE

Question: I want to group by ID and summarise, whilst removing NAs.
please see example code below.
# Example data
ID <- c(1, 1, 1, 2, 2, 3, 3)
x <- c(2, 3, NA, 2, 3, 1, 1)
ID_x <- tibble(ID, x)

# 1. Works
ID_x %>%
  group_by(ID) %>%
  summarise_each(mean)

# 2. Does not work with na.rm=TRUE
ID_x %>%
  group_by(ID) %>%
  summarise_each(mean(., na.rm=TRUE))

Thanks in advance
Answer: Use the lambda (~
library(dplyr)
ID_x %>%
  group_by(ID) %>%
  summarise_each(~ mean(., na.rm=TRUE))

-output
# A tibble: 3 × 2
     ID     x
  <dbl> <dbl>
1     1   2.5
2     2   2.5
3     3   1

Also, in recent versions, the summarise_each will accompany a warning as these are deprecated in favor of across
ID_x %>%
  group_by(ID) %>%
  summarise(across(everything(), ~ mean(., na.rm=TRUE)))

Answer: A different option would be using funs. You can also use this:
ID_x %>%
  group_by(ID) %>%
  summarise_each(funs(mean(., na.rm = TRUE)))

Output:
# A tibble: 3 × 2
     ID     x
  <dbl> <dbl>
1     1   2.5
2     2   2.5
3     3   1


Check regexp condition inside while loop (shell)

Question: I have problem with running my simple shell script, where I am using while loop to read text file and trying to check condition with matching regexp:
#!/bin/sh
regex="^sometext"

cat input.txt |
{
  while read string
    do if [[ $string ~= $regex ]]; then
            echo "$string" | awk '{print $1}' >> output.txt
       else
            echo "$string" >> outfile.txt
       fi
    done
}

but I recieve only errors like
[[: not found

could you please advise me?
Answer: [[ expr ]] is a bash-ism; sh doesn't have it.
Use #!/bin/bash if you want to use that syntax.

That said, why use a shell script?
Awk can already do everything you're doing here - you just need to take advantage of Awk's built-in regex matching and the ability to have multiple actions per line:
Your original script can be reduced to this command:
awk '/^sometext/ {print $1; next} {print}' input.txt >> output.txt

If the pattern matches, Awk will run the first {}-block, which does a print $1 and then forces Awk to move to the next line. Otherwise, it'll continue on to the second {}-block, which just prints the line.
Comment: @anubhava I don't generally try to race.
Comment: Thanks for comment! I simplified my script a bit to post here. Full command after checking condition is `echo "$string" | awk '{print $1}' | base64 -d | iconv -f UTF-8 -t KOI8-R >> outfile.txt`
Comment: @Amber: Don't take it otherwise, all 3 of us answered pretty much same thing that's why I commented.
Comment: @Amber: I think I'll do it :)
Comment: @P.S. One way to simplify would make to make a shell script that just does the chain of commands you want to do on a particular line, and then use awk to invoke the shell script for only the relevant lines - `{print $1 | "myscript.sh"; close("myscript.sh"); next}` (the close ensures that the output from the script comes before any next printed line).
Answer: Because you're using shebang for /bin/sh and [[ is only available in BASH.
Change shebang to /bin/bash
btw your script can be totally handled in simple awk and you don't need to use awk inside the while loop here.
Comment: Yes that's correct if you don't have BASH then you can't use `=~` regex operator either.
Comment: Thanks a lot for pointing this. So if I have no bash I can't use this condition?
Answer: sh does not support the double bracket syntax - that's explicitly a bash-ism.
Try changing your shebang line to #!/bin/bash


How can I use ngControl in contenteditable element?

Question: How can I use ngControl in contenteditable element?
For example, I want:

With binding (?) it to model-driven "form" (table). I create him with formBuilder based on schema, that retrieve from server.
Currently I think that doesnt work, 'cause  (and others) element haven't property value. Then, possible to overload some methods to work with textContent property? Or exist other way to do this?
Thank you.
Answer: To be able to use contenteditable elements with Angular2 and controls, you need to create a custom directive that applies to the contenteditable  This directive must be ngModel / ngForm compatible so you will be able to use directives like ngForm and ngFormControl. Internally this directive will register a custom `Value
Here is a possible implementation:
const CUSTOM_VALUE_ACCESSOR = CONST_EXPR(new Provider(
  NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => ContenteditableAccessor), multi: true}));

@Directive({
  selector: '[contenteditable]',
  host: {'(blur)': 'onBlur($event)'},
  providers: [CUSTOM_VALUE_ACCESSOR]
})
export class ContenteditableAccessor implements ControlValueAccessor {
  onChange = (_) => {};
  onTouched = () => {};

  constructor(private eltRef:ElementRef) {
  }

  ngOnInit() {
    this.onChange(this.eltRef.nativeElement.innerText);
  }

  writeValue(value: any): void {
    if (value!=null) {
      this.eltRef.nativeElement.innerText = value;
    }
  }

  onBlur(event) {
    this.onChange(this.eltRef.nativeElement.innerText);
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { this.onTouched = fn; }
}

You will be able to use this directive this way in a component:
@Component({
  selector: 'my-app',
  template: `

      <form>
        First name:
        Some value
      </form>

        firstName: {{testCtrl.value}}

        firstName: {{testCtrl.valid}}

Update conditions

  `,
  directives: [ FORM_DIRECTIVES, ContenteditableAccessor ]
})
export class AppComponent {
  constructor() {
    this.testCtrl = new Control();
  }
}

Here is the corresponding plunkr: https://plnkr.co/edit/JbjXIa?p=preview.
For more details about ngForm / ngModel compliant custom components, you could have a look at this article in the section "NgModel-compatible component":

http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/


Como manipular Arrays Dinâmicos - PHP

Question: Estou tendo problemas para manipular 3 arrays individuais com indices dinâmicos que variam conforme entrada do usuario em um formulario em PHP, pois preciso passar os valores para uma ou mais instruções SQL para inserir no banco de dados dependendo da quantidade de índices nos arrays.
array(size=4)
   0 => string 'name' (length=4)
   1 => string 'email' (length=5)
   2 => string 'tel' (length=5)
   3 => string 'cod_var' (length=8)

array(size=4)
   0 => string 'Junior' (length=9)
   1 => string 'firstname.lastname@example.com' (length=26)
   2 => string '363' (length=3)
   3 => string '0' (length=1)

array(size=4)
   0 => string 'Junior Alpha' (length=8)
   1 => string 'firstname.lastname@example.com' (length=25)
   2 => int 399
   3 => int 1

Não consegui fazer um foreach/for para que rode simultaneamente nos 3 arrays e traga os resultados em ordem sequencial para concatenar no SQL.
INSERT INTO dataInfo(type, old_value, new_value) VALUES ("name", "Junior", "Junior Alpha");
INSERT INTO dataInfo(type, old_value, new_value) VALUES ("email", "email@example.com", "email@example.com");
INSERT INTO dataInfo(type, old_value, new_value) VALUES ("tel", "363", "399");
INSERT INTO dataInfo(type, old_value, new_value) VALUES ("cod_var", "0", "1");

Comment: Veja se essa abordagem não é mais adequada: https://ideone.com/xeDeUP .
Answer: Já tentou iterar sobre usando laço for?
for($i=0, $i < $array; $i++):
  // name
  $array[$i][0]..
  // email
  $array[$i][1]..
endfor;

Comment: Estava pensando de outra maneira, mas sua lógica é mais apropriada para meu cenário.

Fiz aqui e solucionou o problema.

Obrigado Rafael!
Comment: ao seu dispor bro!

Como manipular Arrays Dinâmicos - PHP


Confusion about probability

Question: I am really confused about a rather easy looking question.
Say we are to throw 2 dice and are looking to decide the probability of getting two number which has a difference of three.
What I am confused about is the following: considering the two dice identical (having the same colour) and unique (having different colour) seems to give me different answers.
Let us start with the case when the dice are different, say have colour red and green. Then the number of possible outcomes are 6x6=36 and we get difference 3 between the two numbers in the following way (6,3), (5,2), (4,1), (1,4), (2,5), (3,6). We consider (6,3) and (3,6) different since the dice have different colour. This means that the possibility of having difference 3 is 6/36 that is 1/6.
Now to the case when the dice are identical. In this case we have  21=6+5+4+3+2+1 different outcomes of the throw since in this case (3,1) and (1,3) for example is "the same outcome". This way we can get difference 3 in the following outcomes (1,4), (2,5) and (3,6) which leads to 3/21=1/7.
Is my calculation wrong? Or if it is correct than why is this the case?
Thank you for your help!
Comment: If you take the sample space to be the 21 distinguishable outcomes with identical dice -- that is theoretically perfectly ok. However, the 21 outcomes are NOT EQUALLY LIKELY (the doubles have half the frequency of the non-doubles), and so you can NOT compute probabilities with that sample space by doing (size of event)/21. Rather you would do Pr(event) =(sum of frequencies in the event), which in this case is 1/18 + 1/18 + 1/18 = 1/6 as before.
Comment: @James hmmm, (5,5) seems to be different in the two cases I described. I dont know, could you explain more why is this the case?
Answer: When the dice are identical, you can say there are 21 possible outcomes, but those outcomes do not have the same probability. The probability of throwing any given pair of unequal numbers, $\frac2{36}$, is twice that of throwing a given double ($\frac1{36}$). In effect, accepting only 21 outcomes in the identical-dice case is lumping some of the 36 outcomes of the distinct-dice case together.
With this in mind, the probability of getting a difference of 3 between the rolls is not $\frac17$ as you calculated, but $\frac6{36}=\frac16$ like in the distinct-dice case.
Comment: Ahh! I see! So it is the safest two always consider them differently coloured?
Comment: @mathemagic Yes, yes.
Comment: Thank You very much for the effort! I was disturbed by this for the past hour. Have a nice evening!

Confusion about probability


Exception: Unexpected error while getting the method or property getNextDataCell on object SpreadsheetApp.Range

Question: I'm trying to get last row and column of a sheet by using Google Apps Script.
When I try the code below it shows me the exception when getting last_col.
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sh = ss.getActiveSheet()

let last_row = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
let last_col = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.RIGHT).getColumn();

Exception

Unexpected error while getting the method or property getNextDataCell on object SpreadsheetApp.Range.

It seems last_row is successfully available but somehow the column is not.
When I tried to get lastest column and row by using GAS but it shows me the exception when getting last_col.
Comment: Welcome to [so].  Please briefly describe the spreadsheet, the Apps Script project and add a [mcve].
Answer: Try it this way:
function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  let last_row = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
  let last_col = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.NEXT).getColumn();
  Logger.log(last_row);
  Logger.log(last_col);
}

RIGHT is not one of the directions in the enum
SpreadsheetApp.Direction
Comment: I hope you realize that if there are any blanks in either column 1 or or row 1 then last row and last col will be wrong.


how to do Ftp polling with Spring integration DSL

Question: I am trying to create Dynamic ftp inbound adapters for the flow described below
<int-ftp:inbound-channel-adapter id="ftpInbound"
    channel="ftpChannel" session-factory="ftpClientFactory"
    filename-pattern="*.txt" auto-create-local-directory="true"
    delete-remote-files="false" remote-directory="${remotedir}"
    local-directory="/mock/test" auto-startup="true">
    <int:poller fixed-rate="1000">
        <int:transactional synchronization-factory="syncFactory" />
    </int:poller>
</int-ftp:inbound-channel-adapter>

To do this I have created the below flows with SI java dsl that I register using SI dynamic registration as below
public void createSubFlows(FtpConfig config) {

    DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
    Connection connection = config.getConnection();
    Feed feed = config.getFeed();
    sf.setHost(connection.getHost());
    sf.setPort(connection.getPort());
    sf.setUsername(connection.getUsername());
    sf.setPassword(connection.getPassword());

    IntegrationFlow flow = IntegrationFlows
            .from(Ftp.inboundAdapter(csf).preserveTimestamp(true)
                    .remoteDirectory(feed.getRemoteDirectory())
                    .regexFilter(".*\\.txt$")
                    .localDirectory(new File(feed.getLocalDirectory())),
                    e -> e.id("ftpInboundAdapter" + connection.getId()
                            + feed.getId())//
            ).handle(m -> System.out.println(m.getPayload())).get();
    this.flowContext.registration(flow)
    .id("ftp.flow" + connection.getId() + feed.getId()).autoStartup(true)
            .register();
}

The same works well but I wanted to also configure a dynamic poller similar to the one in the xml above . Is it possible to do the same with SI Java DSL
UPDATE
Looks like it works though not sure why it doesnt come in the content assist
e -> e.poller(Pollers.fixedRate(100).maxMessagesPerPoll(1))

Comment: wow..it works...thank u
Answer: Are you sure that e in the .from() doesn't have .poller()`:
   from(Ftp.inboundAdapter(csf)
          .preserveTimestamp(true)
                .remoteDirectory(feed.getRemoteDirectory())
                .regexFilter(".*\\.txt$")
                .localDirectory(new File(feed.getLocalDirectory())),
                e -> e.id("ftpInboundAdapter" + connection.getId()
                        + feed.getId()
              .poller())

?
Comment: Ok. What is the version? And how look that lambda if you convert it to class?
Comment: Glad to see you have managed that. Would great to have at least up vote for this the spending time
Comment: yup I thought it should but looks like it doesn't for me .
Comment: the version is 4.3.8 I think it should as seems is a SourcePollingChannelAdapterSpec, hmm seems it is working now not sure why it never came in the content assist :|
Comment: lol did silly issue ... sometimes need not rely on content assists by IDE's


Camera preview stretched

Question: I'm trying to create a custom camera preview activity, but as my camera preview view is not matches the screen height the cam preview is being shrinked and looks bad. Can someone help me and tell me how can I fix this?
Here is how it looks:

And my code:
public class CaptureFly extends Activity implements PictureCallback {
    private ImageButton takePicture;
        private ToggleButton flashOnOff;

        private Camera camera;
        private CameraPreview cameraPreview;

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

            init();
        }

        private void init() {
            flashOnOff = (ToggleButton) findViewById(R.id.capture_flash);
            takePicture = (ImageButton) findViewById(R.id.capture_btn);

            camera = CameraHelper.getCameraInstance();
            if (CameraHelper.cameraAvailable(camera)) {
                initCameraPreview();
            }

            flashOnOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    // stopPreview();

                }
            });
            takePicture.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    camera.takePicture(null, null, CaptureFly.this);
                }
            });
            initActionbar();
        }

        // Show the camera view on the activity
        private void initCameraPreview() {
            cameraPreview = (CameraPreview) findViewById(R.id.camera_preview);
            cameraPreview.init(camera);
        }

        private static String savePictureToFileSystem(byte[] data) {
            File file = MediaHelper.getOutputMediaFile();
            MediaHelper.saveToFile(data, file);
            return file.getAbsolutePath();
        }

        private void setResult(String path) {
            Intent intent = new Intent(CaptureFly.this, FlyPreview.class);
            intent.putExtra(Constants.EXTRA_IMAGE_PATH, path);
            startActivity(intent);
        }

        // ALWAYS remember to release the camera when you are finished
        @Override
        protected void onPause() {
            super.onPause();
            releaseCamera();
        }

        private void releaseCamera() {
            if (camera != null) {
                camera.release();
                camera = null;
            }
        }

        private void initActionbar() {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.nav_bg));
            // adds a back button
            getActionBar().setHomeButtonEnabled(true);
            getActionBar().setIcon(R.drawable.exit_ex);
            int titleId = getResources().getIdentifier("action_bar_title", "id",
                    "android");
            TextView abTitle = (TextView) findViewById(titleId);
            Typeface mTypeface = Typeface.createFromAsset(getAssets(),
                    "rockwell.ttf");
            abTitle.setPadding(20, 0, 0, 0);
            abTitle.setTypeface(mTypeface);
            abTitle.setText(getString(R.string.capture_an_image));
            abTitle.setTextSize(20);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

        @Override
        public void onBackPressed() {

            super.onBackPressed();
        }

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Log.v("--", "Picture taken");
            String path = savePictureToFileSystem(data);
            setResult(path);
            finish();
        }

XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="11" >

    <com.flyflasher.views.CameraPreview
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@drawable/nav_bg"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/capture_browse"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableLeft="@drawable/browse"
            android:gravity="left|center_vertical"
            android:padding="5dp"
            android:text="@string/browse_" />

        <ToggleButton
            android:id="@+id/capture_flash"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableLeft="@drawable/flash_on"
            android:gravity="left|center_vertical"
            android:textOff="@string/flash_off"
            android:textOn="@string/flash_on" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        android:background="#272721"
        android:gravity="center"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/capture_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@android:color/transparent"
            android:contentDescription="@string/app_name"
            android:src="@drawable/capture_btn" />
    </LinearLayout>

</LinearLayout>

Comment: Can you share layout.xml
Comment: It is happening because you set layout weight as 5. Your entire screen is divided by the weight you give (here 11). Out of 11, you gave 5 for ImageView. You have to increase weight for Imageview. Again you can reduce weight of last linear layout (the one with Image button)
Comment: @Paritosh yes but that way I will lose the layout looks.. there must be another solution
Comment: For maintaining ratio, we have to reduce width.
Comment: Is that black space below.buttons intended?
Answer: You need to set the display orientation of the camera by callind camera.setDisplayOrientation method. You can find the details in android docs.
Doing this it will also show the display a little squeezed based on the difference between the aspect ratios of the screen and camera preview size. So you may need to adjust the SurfaceView size accordingly. More info here

Camera preview stretched


Proving supremums of sequences

Question: If $l$=sup($x_n$), what is sup($kx_n$) where k$\in$$\mathbb{R}^{+}$? Prove your conjecture.
I have that sup($kx_n$)=$kl$. I can prove that it is an upper bound of $kx_n$, but I'm having trouble finishing the proof and showing that it is less than or equal to any other upper bound of $kx_n$.
Answer: Hint: Given $\varepsilon > 0$ and $x_n$ with $x_n>l - \varepsilon/k$, $k x_n > kl - k \varepsilon/k = kl - \varepsilon$. Why does this $x_n$ exist, and why is it enough to get your result?
Comment: Would the downvoter care to comment?
Comment: I'm confused as to how the $\epsilon$ helps in proving that another upper bound, say $p$, of $kx_n$ will be greater or equal to $kl$
Comment: @Lauralolo You need to prove two things: that $kl$ is an upper bound, and that it is the least one. You said you have already proven it is an upper bound. My hint will help you show it is the least one.
Comment: @Lauralolo What I am attempting to show here is that there are numbers in $k x_n$ which are arbitrarily close to $kl$. From this it follows that no number can be a smaller upper bound.
Answer: To show that $kl$ is the least upper bound, suppose, for a contradiction, that you can find a smaller lower bound. That is, suppose there exists $b \in \mathbb{R}$ with $b < kl$ and $kx_n \le b$ for all $n\in\mathbb{N}$. So for all $n\in\mathbb{N}$,
$$
kx_n \le b < kl.
$$
But then
$$
x_n \le \frac{b}{k} < l
$$
for all $n\in\mathbb{N}$.
Do you see the contradiction?
Comment: @avid19 Thanks, I didn't notice that. Will remove that line.
Comment: Actually you don't have to deal with $k=0$ as $k$ is said to be positive.

Proving supremums of sequences