Want to use Recycler View Inside Nested Scroll View

Question: I am using a recycler view with multiple views nested in it recycler work fine and it also scroll smoothly but when I put recycler view inside the nested scroll view the scroll of nested view is lag or you can say delay for few second when the new item is add in recycler view
.For clarity I already set the recycler view nested scroll to false
and I am using NestedScrollView because I want to show progress bar when user come to end of recycler view and load more item and I also try to add block descendant to xml file but not work
my xml code:
<androidx.core.widget.NestedScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/home_fragement"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"

    android:overScrollMode="never"

    tools:context=".Content_Maint_Fragment.HomeFragment"

   >

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:focusableInTouchMode="true"
    android:focusable="true"
    android:descendantFocusability="blocksDescendants"
    android:layout_height="match_parent">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/home_recyclerView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"

                    android:overScrollMode="never"

                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"

                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent">

                </androidx.recyclerview.widget.RecyclerView>

        <ProgressBar
            android:id="@+id/progressBar2"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"

            android:layout_height="wrap_content" />

</LinearLayout>
</androidx.core.widget.NestedScrollView>

Comment: Does this answer your question? [How to use RecyclerView inside NestedScrollView?](https://stackoverflow.com/questions/31000081/how-to-use-recyclerview-inside-nestedscrollview)
Comment: not working for me
Comment: please tell me another solution in my the nested scroll view just lag for milli second i donot why and i want make scroll view smooth like youtube in home view basically scroll view only lag at time of new item is added
Answer: android:nestedScrollingEnabled="false"

Add this to your RecyclerView
Comment: not working please tell another way


Dados sobreescritos ao gravar log de acessos em arquivo

Question: Estou com um problema que creio ser de fácil solução, mas não sei como resolver.
Abaixo segue um script para gravar quem acessou a página. Funcionou legal, mas ele sobrescreve um acesso em cima do outro, e eu preciso que cada IP que acessou fique gravado, um embaixo do outro.
Além disso não sei como acertar o horário, está aparecendo com 5 horas a mais.
<?php
   /* se o arquivo não existir, será criado, dê
      permissão 777 na pasta onde ele será criado */
   $arquivo = "includes/spy.txt"; // arquivo que gravará os dados
   $data = date("d/m/Y H:i:s"); // Data do acesso
   $ip = $_SERVER['REMOTE_ADDR']; // IP de acesso
   $host = getHostByAddr($ip); // Host de acesso
   $pagina = $_SERVER['PHP_SELF']; // Página de acesso
   $browser = $_SERVER['HTTP_USER_AGENT']; // Browser de acesso
   $fp = fopen($arquivo, "w+");
   fwrite( $fp,
      "Data: $data | IP: $ip | host: $host | Pagina Acessada: $pagina | Navegador: $browser"
   );
   fclose($fp);
?>

Answer: Mude o modo do fopen para a (append):
$fp = fopen($arquivo, 'a+');

veja a diferença das flags do fopen no manual do PHP (destaquei os pontos chave):

w+    Abre para leitura e escrita; coloca o ponteiro do arquivo no começo do arquivo e reduz o comprimento do arquivo para zero. Se o arquivo não existir, tenta criá-lo.
a+    Abre para leitura e escrita; coloca o ponteiro do arquivo no final do arquivo. Se o arquivo não existir, tenta criá-lo.

Quanto à data, o problema provavelmente é o timezone do servidor. A linha abaixo deve resolver (use antes do date):
date_default_timezone_set('America/Sao_Paulo'); // Europe/Lisbon

Comment: Oi Diego. Legal, se esta resposta resolveu o seu problema, você pode marcá-la como "aceita" clicando no ícone que tem embaixo da pontuação da resposta. Mais detalhes em http://meta.pt.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta
Comment: Meu amigo, muitissimo obrigado! Funcionou perfeitamente!
Answer:     <?php
       /* se o arquivo não existir, será criado, dê
          permissão 777 na pasta onde ele será criado */
       date_default_timezone_set('America/Sao_Paulo');
       $arquivo = "includes/spy.txt"; // arquivo que gravará os dados
       $data = date("d/m/Y H:i:s"); // Data do acesso
       $ip = $_SERVER['REMOTE_ADDR']; // IP de acesso
       $host = getHostByAddr($ip); // Host de acesso
       $pagina = $_SERVER['PHP_SELF']; // Página de acesso
       $browser = $_SERVER['HTTP_USER_AGENT']; // Browser de acesso
       $fp = fopen($arquivo, "a+");
       fwrite( $fp,
          "Data: $data | IP: $ip | host: $host | Pagina Acessada: $pagina | Navegador: $browser"."\r\n"
       );
       fclose($fp);
    ?>

OU
<?php
   /* se o arquivo não existir, será criado, dê
      permissão 777 na pasta onde ele será criado */
   date_default_timezone_set('America/Sao_Paulo');
   $arquivo = "includes/spy.txt"; // arquivo que gravará os dados
   $data = date("d/m/Y H:i:s"); // Data do acesso
   $ip = $_SERVER['REMOTE_ADDR']; // IP de acesso
   $host = getHostByAddr($ip); // Host de acesso
   $pagina = $_SERVER['PHP_SELF']; // Página de acesso
   $browser = $_SERVER['HTTP_USER_AGENT']; // Browser de acesso
   $fp = fopen($arquivo, "a+");
   fwrite( $fp,
      "Data: $data | IP: $ip | host: $host | Pagina Acessada: $pagina | Navegador: $browser"."\r\n"."\r\n"
   );
   fclose($fp);
?>


Ler ponteiro de string em C

Question: Esta é a pergunta:
4. Faça um programa que receba do usuário o tamanho de uma string e chame uma
função para alocar dinamicamente essa string. Em seguida, o usuário deverá informar
o conteúdo dessa string. O programa imprime a string sem suas vogais.
O codigo funciona normalmente quando a palavra não tem um espaço (' '), nao imprime as vogais, mas quando a palavra lida tem espaço, por exemplo: 'bom dia', imprime tudo nada a ver, símbolos, algm pode ajudar?
Codigo abaixo
<code>char *ptr;
int i, x;
printf("Tamanho do vetor:\n");
scanf("%d", &x);
ptr = malloc(x * sizeof(char));
scanf("%s", ptr);
for (i=0; i<x; i++) {
if (*(ptr+i) != 'a' && *(ptr+i) != 'e' && *(ptr+i) != 'i' && *(ptr+i) != 'o' && *(ptr+i) != 'u') {
printf("%c", *(ptr+i));
}
}
</code>
Comment: Com o formato que você especificou no scanf ele encerrará a leitura ou quando chegar ao final da linha ou quando encontrar o primeiro branco. Como você não testa se chegou ao final da string você vai imprimir lixo de memória. No seu exemplo sua string conterá apenas "bom".
Comment: então como poderia fazer?
Answer: a maneira mais indicada para trabalhar com string no c( palavras composta) seria usar o scanf(" %[^\n]s");. O [^\n] vai ler todo a sua string ate o \n, e o espaço que se da entre " e o % é uma maneira de limpar o buffer do teclado. Pode ser esse seu problema
Comment: obrigado, consegui arrumar

Ler ponteiro de string em C


Discord bot does not respond to my messages (js)

Question: Recently, I have made a Discord bot using node.js and VS Code. I can see my bot being online. However, it does not respond to my messages. (The bot has the required permissions.)
I could not understand the problem, I would be so delighted if you gave me a hand.
Here is my bot.js code
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const config = require("./config.json");

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message' , message => {
    if(message === 'ping') {
        message.channel.send('Pong!');
    }
})

client.login(config.token);

Here is my config.json code
{
 "token": "I wrote my token in here"
}

Comment: You have to include the Guild Messages intent in your client's intents
Comment: I had added both GuildMessages and MessageContent. I had taken a look at @ZsoltMeszaros 's link and I noticed something. I should have written `client.on('messageCreate'` instead of writing `client.on('message' `. Thanks, it is working now :D
Comment: Add `console.log(message)` to your `client.on('message' , message => {` function and see what you got
Comment: I have taken a look at the documentation (https://discordjs.guide/popular-topics/intents.html#the-intents-bitfield) and tried to add Guild intents. I ended up like this :
const { Client, IntentsBitField } = require('discord.js');

const myIntents = new IntentsBitField();
myIntents.add(IntentsBitField.Flags.GuildPresences, IntentsBitField.Flags.GuildMembers);

const client = new Client({ intents: myIntents });
Unfortunately , it did not work.
Anyways, thank you all for help :D
Comment: How about adding both GuildMessages and MessageContent?
`const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });`
Answer: Your code dosent work because your not checking for message.content which holds the message's content.
It should be somthing like this:
client.on('message' , message => {
    if(message.content === 'ping') {
        message.channel.send('Pong!');
    }
})

Comment: Thanks for the help, I solved the problem by writing `client.on('messageCreate'` (instead of `client.on('message'` . And also I added message.content, like you said.


Trills in sheet music

Question: When you see a trill in sheet music how to you know if you alternate the givin note and the half step above it or the whole step above it or any other interval?
Answer: I think it's the note that is directly above the starting note in the key. For example if I was in G major and i saw the trill sign on the note B I would play a C because it's the next note in the scale. Or if I was in F♯ minor key and the trill was on the note F♯ I would play the trill with G♯ because that's next in the scale.
However there could be an accidental in that bar and in that case, play that note.

Hope I helped, sorry if this is just nonsense.
Comment: Not nonsense. If there has been an accidental previously in the bar this would apply to either of the trill notes if appropriate.  If there has not been an accidental but the composer wants the (unwritten) trill note to be either half a step higher or half a step lower then it is indicated alongside the trill mark.
Answer: You just play whatever pitch would result from putting a notehead one position higher than the main note.  Basically, you use the current accidental in force for that note position.  Of course unless there is an explicit accidental written above the trill in which case you use that.

Trills in sheet music


What Is The Derivative Of f(x^3)

Question: I want to find the derivative of $f'(x^3)$. I tried using chain rule and I got $3x^2f'(x^3)$. Is that correct?
Comment: Yes, you are correct. Do you mean "I want to find the derivative of $f(x^{3})$"?
Comment: do you want the derivative of $f(x^3)$ or $f'(x^3)$? If its the first one then yes, you have correctly applied the chain rule. If you want the second, then it should be $3x^2f''(x^3)$.
Comment: Perfectly correct, if what you mean is $\bigl(f(x^3)\bigr)'$.
Answer: If your function is $g(x)=f'(x^3)$, then it would be by the chain rule $g'(x)=f''(x^3)3x^2$.
Otherwise, if you meant $f(x^3)$, it would be $f'(x)3x^2$.

What Is The Derivative Of f(x^3)


Is the following map well defined?

Question: I am currently studying basic group theory. I am having trouble trying to prove that given a group $G$, and two subgroups $K$ and $H$ such that $H \leq K \leq G$ the following map is well defined:
$$\varphi:  G/K\times K/H \longrightarrow G/H$$
$$(gK,kH)\longmapsto gkH$$
As, one could take $g_1,g_2 \in G$ such that $g_2^-1g_1\in K-H$ so that $g_1K=g_2K$ but $g_1H \ne g_2H$. This means that (if $1$ is the group identity) although $(g_1K,1H)=(g_2K,1H)$, we have that  $\varphi(g_1K,1H) \ne \varphi(g_2K,1H)$ so the function is not well defined.
But, I don't know if this is a valid counterexample as thanks to a similar question (finite index subgroups) a map similar to this one gives a bijection between the sets.
Thanks.
Comment: Sorry, I mixed up the order of $K$ and $H$
Comment: No, I mean that the function is independent from the class representative. That is to say that if two elements are equal on the domain then their images under the function are equal
Answer: Your counterexample is valid.
Even simpler case. Take $H = \{ 1 \}$. You would get $G/K \to G$ defined by $g K \to g$, which certainly is not well defined.
Where do you see the similar map in the question that you link?
Comment: The similar map is in the second answer where they mention something related to the canonical map where they mention that the fiber is the image of the function I am defining.
Answer: You're quite right that this map is not well-defined. There are well-defined homomorphisms $K/H \to G/H \to G/K$ forming what we call a short exact sequence of groups, but there is generally no splitting of such a sequence, that is, a homomorphism $G/K \to G/H$ that picks preimages. The point here is that you may still pick preimages for any coset in $G/K$, and that there are precisely $K/H$ available choices for each coset. This yields a set-theoretic bijection $G/H \cong K/H \times G/K $: an element in $G/H$ corresponds bijectively to its image under the projection $G/H \to G/K$ along with the choice of preimage encoded by $K/H$.
For example, consider the sequence of subgroups $4\mathbb{Z} \leq 2\mathbb{Z} \leq \mathbb{Z}$. The short exact sequence I mentioned above becomes $2\mathbb{Z}/4\mathbb{Z} \to \mathbb{Z}/4\mathbb{Z} \to \mathbb{Z}/2\mathbb{Z}$. There is no splitting of this sequence by order considerations, but the preimage of, say, $0 \in \mathbb{Z}/2\mathbb{Z}$, which is $\{0,2\} \subset\mathbb{Z}/4\mathbb{Z}$, corresponds bijectively to $2\mathbb{Z}/4\mathbb{Z}$, and similarly for the preimage of $1 \in \mathbb{Z}/2\mathbb{Z}$, which is $\{1,3\} \subset\mathbb{Z}/4\mathbb{Z}$.
Comment: Is the $\varphi$ map above a preimage function from $G/K \rightarrow G/H$? Because what I ultimately want is a set theory bijection between those two sets.
Comment: @MiguelAngelAlarconBustos The map $gK \mapsto gH$ is generally not even a function.

Is the following map well defined?


Drop shadow on AppBarLayout

Question: I have used Design Support Library's AppBarLayout to show Toolbar and TabLayout in my project.
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:background="#FF0000">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:scrollbars="horizontal"
        android:layout_below="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways" />

</android.support.design.widget.AppBarLayout>

This AppBarLayout cast a drop shadow in Lollipop, however, there is no drop shadow in pre-lollipop devices.
How can I show the drop shadow in pre-lollipop devices as well?
Answer: Do note this only works for lollipop and above. It won't work pre lollipop device so you have to create custom xml for shadow like below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_alizarin"
        android:titleTextAppearance="@color/White"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <View
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="@drawable/toolbar_dropshadow" />
    </FrameLayout>
</LinearLayout>

 @drawable/toolbar_dropshadow:
  <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="@android:color/transparent"
        android:endColor="#88333333"
        android:angle="90"/>
    </shape>

@color/color_alizarin

<color name="color_alizarin">#e74c3c</color>

Comment: Doesn't work with `CoordinatorLayout`, Apparently we had to use `AppBarLayout`, and it doesn't draw shadow correctly
Answer: <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:fitsSystemWindows="true">

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />

            <application.project.freelincerapp.tabs.SlidingTabLayout
                android:id="@+id/slidingTabLayout"
                android:layout_width="match_parent"
                android:fitsSystemWindows="true"
                android:layout_height="wrap_content" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/appBarLayout"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

        <View
            android:id="@+id/toolbar_shadow"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:alpha="0.90"
            android:layout_below="@id/appBarLayout"
            android:background="@drawable/custome_shadow"/>

    </RelativeLayout>

Answer: Create an xml file under drawable and name it custom_shadow.xml. Now copy          and paste the following code..

<gradient
    android:centerColor="@android:color/transparent"
    android:endColor="@android:color/transparent"
    android:startColor="@android:color/transparent" />

<corners android:radius="0dp" />

Answer: <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/ab_shadow_height"
                android:background="@drawable/sh_bar" />
        </FrameLayout>

    </android.support.design.widget.CoordinatorLayout>

Drop shadow on AppBarLayout


Alter all webform fields

Question: If we want to alter webform item e.g. add a colon : to a label of a specific field, we use this:
$form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";
But what if we want to apply that colon to all field labels and not just that one my_form_component?
Current code:
function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
  if (strpos($form_id, 'webform_client_form_') === 0) {
    $form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";
  }
}

Answer: You should be able to do it with a recursive function, looping through the render array and adding a colon to any elements that have a #title element.
function addColonsToTitles(&$element) {
  if (isset($element['#title'])) {
    $element['#title'] .= ':';
  }

  foreach (element_children($element) as $index) {
    addColonsToTitles($element[$index]);
  }
}

function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
  if (strpos($form_id, 'webform_client_form_') === 0) {
    addColonsToTitles($form['submitted']);
  }
}

Comment: This solves it, but I also expected for the colons to appear in emails. They actually appear by default, but toggling HTML setting for emails in Webforms for some reason strips colons. Anyway, thanks.
Comment: You asked how to change form labels. The labels in the email will not be form labels, and the manner of adding colons would be entirely different. You can open a new issue for that.

Alter all webform fields


lagrange multipliers and the cases involved

Question: I am stuck on the case $x=0$ or $y=0$ or $z=0$
let $f(x,y,z)= x^2+y^2+z^2$ and $g(x,y,z)= x^4+y^4+z^4=11$
Then:
$2x=4x^3\lambda$
$2y=4y^3\lambda$
$2z=4z^3\lambda$
if $x \neq 0, y \neq 0, z\neq 0$ then:
$4x^3yz\lambda=4y^3xz\lambda=4z^3\lambda$ divide by $4\lambda$
$x^3yz=y^3xz=z^3xy$
$x^3yz=y^3xz$ divide by z:
$x^3y=y^3x \to x=z$ Doing the same thing to the other equations gives:
$x=y=z$
let $x=y=z=a$ then $3a^4=11 \to a=\pm\frac{11^{\frac{1}{4}}}{3^{\frac{1}{4}}}$ which gives im not sure what because the algebra is just god awful here.
let x=0
Now what do I do?
Answer: $x=y=z=0$ is not a solution.
If $x=y=0$ and $z \ne0$
$z=\pm 11^{1/4}$
If $x=0$ and $y.z\ne 0$ then, because of $2y=4y^3\lambda$ and $2z=4z^3\lambda$ we have
$y=\pm z=\pm(11/2)^{1/4}$
The problem is simmetric for $x,y,z$.


Extract first two lines of PDF with Python and pyPDF

Question: I'm using python 2.7 and pyPDF to get the title meta info from PDF files. Unfortunately not all of PDF have the meta info. What I want to do now is grab the first two line of text from a PDF. Using what I have now how can I modify the code to capture the first two lines with pyPDF?
from pyPdf import PdfFileWriter, PdfFileReader
import os

for fileName in os.listdir('.'):
    try:
        if fileName.lower()[-3:] != "pdf": continue
        input1 = PdfFileReader(file(fileName, "rb"))

        # print the title of document1.pdf
        print fileName, input1.getDocumentInfo().title
    except:
        print ",",

Answer: from PyPDF2 import PdfFileWriter, PdfFileReader
import os
import StringIO

fileName = "HMM.pdf"
try:
        if fileName.lower()[-3:] == "pdf":
            input1 = PdfFileReader(file(fileName, "rb"))

            # print the title of document1.pdf
            #print fileName, input1.getDocumentInfo().title

            content = input1.getPage(0).extractText()
            buf = StringIO.StringIO(content)
            buf.readline()
            buf.readline()

except:
        print ",",

My pwd contains this "HMM.pdf" file and this code is working on python 2.7  properly.
Comment: can you show me a full example based off of my current code... it's not output anything when I add in the code you gave above.
Comment: hmm am I missing something still no output. have 5 pdf files in a folder i run the script and nothing
Comment: Try running each command on the interpreter and observe the output. I checked the above code, its working as long as there is valid file in the input1.
Comment: are you sure its working? make sure the line #print fileName, input1.getDocumentInfo().title us commented cause that line gets the title from the PDF meta info. Might be displaying false data.
Comment: Updated the exact code that i ran. It is working properly. Debug your program to check whats missing.


Injected HTML not loading resources?

Question: I'm dealing with what I guess would be a very unusual scenario. I need to manipulate the contents of an iFrame, and to do that, I'm playing with the its DOM. However, I'm noticing that certain elements - like CSS links, images, etc, aren't loading. My code looks like this:
var htmlString = "resources, images, links, the whole shebang here";
var doc = new DOMParser().parseFromString(htmlString, "text/xml"); //"text/xml" part is necessary

frame.contentDocument.replaceChild(doc.getElementsByTagName("html")[0], frame.contentDocument.documentElement);

It works, in that the elements are injected, however many resources don't have their load triggered. I know that it should be working, but for some reason it is not. Is there any way to trigger the load of resources?
EDIT: This seems to do the trick for now.
var resources = frameDOM.querySelectorAll("[href],[src]");
for(var i = 0; i<resources.length; i++){
    var resource = resources[i];

    if(resource.src != null){
        resource.src = resource.src;
    } else if(resource.href != null){
        resource.href = resource.href;
    }
}

Answer:  var doc = new DOMParser().parseFromString(htmlString, "text/xml"); //"text/xml" part is necessary

Nope, text/xml part is not necessary, in fact it's totally wrong in your case.
The right way to do would be
 var doc = new DOMParser().parseFromString(htmlString, "text/html");

I hope you get the difference between XML & HTML.
Comment: Solution would be to parse & append SVG later in to the iframe.
Comment: I do, actually, but in my case it *is* required, since "text/html" strips out certain namespaced attributes that SVG requires.
Comment: It's not just SVG that it does that with, though. I'm going to be loading content from different sources, and I don't want "text/html" stripping things out and causing issues.
Comment: Why don't you simply use the .innerHTML() browser function ? It will parse the whole string on it's own.
Comment: innerHTML is slower than an already rendered DOM Object, especially when it comes to large HTML strings. Plus I need to make a few changes to it before it gets into the iframe. I updated my question with a solution I found.
Comment: You can create a dummy element, set it's innerHTML & do whatever modifications you want to. Also if you think that innerHTML is relatively slower in parsing, then my friend trust me browsers would be using the same DOMParser internally. Moreover I am very sure that your solution would make it a lot slower too.
Comment: Those are good suggestions, however I remember trying them and having issues. I'll reconsider them, though, so thanks.

Injected HTML not loading resources?


How to match tab and newline but not space with REGEX?

Question: I am trying to match "tab" and "newline" meta chars but without "spaces" with REGEX in Java.
\s matches evrything i.e. tab, space and new line... But, I don't want "space" to be matched.
How do I do that?
Thanks.
Comment: Check out this http://www.hscripts.com/tutorials/regular-expression/metacharacter-list.php
Answer: One way to do it is:
[^\\S ]

The negated character class makes this regex to match anything except - \\S (non-whitespace) and " "(space) character. So, it will match \\s except space.
Answer: Explicitly list them inside [...] (set of characters):
"[\\t\\n\\r\\f\\v]"


What is zero mean and unit variance in terms of image data?

Question: I am new to deep learning. I am trying to understand some concepts. I know "mean" is an average value and "variance" is deviation from mean.I have read some research papers, all say that we pre-process our data first. But how these concepts are related to image pre-processing? Why these concepts are used as pre-processing of image data?
Actually i am unable to understand that how these techniques contribute towards classification.I searched it on google but may be i searched with less descriptive keywords
Please bear my very basic question,
Comment: Actually variance is the average of the squares of differences from the mean.  Are you asking about "standardisation" or "rescaling"as preprocessing step?  It is designed to avoid a single explanatory variable dominating the others just because it has a wide range of numerical values.
Comment: Excellent answer for why we normalize feature vectors, from wikipedia: "Since the range of values of raw data varies widely, in some machine learning algorithms, objective functions will not work properly without normalization. For example, the majority of classifiers calculate the distance between two points by the Euclidean distance. **If one of the features has a broad range of values, the distance will be governed by this particular feature. Therefore, the range of all features should be normalized so that each feature contributes approximately proportionately to the final d.**"
Comment: This is usually referred to as [image normalization](https://en.wikipedia.org/wiki/Normalization_(image_processing)), and you can find reasons for it in the link.
Comment: That comment would be stronger if it elaborated on how 0-mean unit variance rescaling is related to images.
Comment: @Sycorax Images are treated as regular feature vectors that are fed to the model. There is nothing special about images, all statements regarding normalization apply equally to images and other feature vectors.
Answer: This is a very good question and you need to understand this to gain more understanding into deep learning.
Basically, you have raw images, lets take one image. This image has 3 channels and in each channel pixel values range from 0 to 255.
Our goal here is to squash the range of values for all the pixels in the three channels to a very small range. This is where Preprocessing comes in.
But dont think preprocessing only involves the mean and std devtn techniques there are many other like PCA, whitening etc.
1) Using mean:
By computing the mean of say, the first red pixel values across all the training images will get you the average red color value that is present across all the training images at the first position. Similarly you find this for all the red channel values, green channel values. Finally you get an average image from all the training images.
Now if you subtract this mean image from all the training images you obviously transform the pixel values of the images, the image is no longer interpretable to the human eye, the pixal values now lie in range from positive to negative where the mean lies at zero.
2) Now if you again divide these by std deviation you essentially squash the pixel value range before to a small range.
BUT WHY ALL THIS?
I will say from my experience that doing this preprocessing on the images and then giving these transformed images to the classifier model will run faster and better. That's why.
As you are into deep learning, look into batch normalization after you understand this normalization concept
Comment: Batch normalisation is related to internal shift in distribution and have nothing to do what we are talking.
Comment: "from my experience the model runs faster and better", doesn't sound that convincing.
Comment: I would argue with the why part: it won't "run faster". It will *learn* faster, but inference time is of course constant.
Comment: The reason unit variance pixel inputs learn better is that the initial weights of a NN are sampled from a normal distribution with unit variance (plus some tricks).   With input and weights on the same scale, the gradients are on the same scale too.  This means the NN gradients straight away model the data, rather than first finding the correct scale to model the data.


How to trigger a Rule when content is viewed with Panels activated?

Question: Easy problem: when users visit a node page on my website, one of the node's integer fields should be changed. Answer: Rules. Now comes the tricky part...
I installed Panels and enabled the node template node_view via the Pages UI. I added the Pane "Node being viewed" content (build mode: Full content), but none of my Rules with an event Content is viewed is triggered anymore on the node pages. After searching around a whole day on the internet, I think my problem is a classic, but I didn't find a clear answer anywhere. Hopefully, we can get over it here once and for all.
Here are some things that I tried so far:

This comment suggested to disable the No extras option in the Pane's settings (which works), but that also renders the comments, comment form, etc.; which is not what I want, since I add those as separate Panes.
Combining the power of Conditional Rules and Rules URL Argument. The general idea is to check on Drupal is initializing whether the path starts with node, save the nid arg(1) as a variable, load the node and make the necessary changes afterwards. Unfortunately, I couldn't find a way to use the nid in the path without using custom PHP (I want to avoid that).
Forgetting about Rules and trying to code is also fine for me, but I haven't found the correct hook yet. Using hook_node_view doesn't work, because it doesn't get called (that's precisely why the Rules aren't triggered). I also tried to use
function hook_init() {
  if (arg(0) == 'node') {
    $node = node_load(arg(1));
  }
}

in my custom module, but that results in some theme related errors, so I'm afraid that my node templates are getting messed up by this. Lastly, different sources referred to hook_ctools_render_alter, so that seemed promising. Though, after some debugging, I quickly gave up trying to understand how this hook works. If this is the correct way to go, I would like to have some more information about the hook or some example code.

Do you have any suggestions to fix this frustrating problem?
Note: I'm using the currently latest versions of all modules, i.e. CTools 1.11, Panels 3.8 and Rules 2.9.
Comment: Are you on the latest ctools? .18 or .19 had a change that broke the rule for content is viewed when using panels. My issue post.. https://www.drupal.org/node/2556253
Comment: Actually, it looks like you'll need to apply that patch because ctools is still on 1.19. I use content I'd viewed on panels fine for lots of things.
Comment: @NiallMurphy: I applied the patch in your link and it solves the problem, so I reviewed it on drupal.org. Hopefully the CTools maintainers can quickly commit it. I'll keep this question open a little longer and see what happens. Thanks!
Comment: The latest ctools 1.10 didn't include this fix fyi.
Comment: @Niall Murphy: Correct, I have already updated my question accordingly.
Answer: You should use Rules Bonus Pack which allows to create a new event when a panel variation is loaded.
Detailed instructions:

Download Rules Bonus Pack and enable "Rules Bonus: Miscellaneous" sub module.
From the panel settings page you will see a new "Reactions" tab. On this tab you will select the new option "Create a Rules event for this variant".
Now open the rule and add a new event. You will find a new section "Rules Bonus: Miscellaneous" with the selected panel variation. Use this event instead the "Content is viewed" one.

It should work as you expect.
Alternative solution
An alternative solution is to write a custom module. You should take a look to the Rules Bonus Pack source code. You can find some inspiration to solve the problem.
Instead using hook_node_view() you can implement hook_ctools_render_alter().
First you should check the handler (node_view) and after load the node data from the ctools/panels context.
Example:
function yourcustommodule_ctools_render_alter(&$info, &$page, &$context){
  // Verify if the page/node is the one you want to interact with
  // and set the field value as you wish.

  // First check if the handler is node_view:
  if($context['handler']->task == "node_view"){

    // Then verify the node content from the context sub array
    // The $context variable contains the node data but you
    // have to dig in.
    $node = $context['contexts'][key($context['contexts'])]->data;

    // [... your code ...]

}

Happy coding :-)
Comment: Thank you for your answer. I also came across this module during my search, but I really don't want to use any development release on my live website.
Comment: Ok, I've edited my original post with an alternative solution.
Comment: Hi @Jeroen, I've updated the example code using *hook_ctools_render_alter()*. With this code you should be able to interact with the node content.
Answer: I think it has got something to do with the node's 'view mode'. Which view mode are you showing the node in, in Panels - Teaser, Default or any custom view mode?
The following steps may help the rule to get triggered when content is viewed in the desired view mode:

Go to Admin > Configuration > Workflow > Rules > edit your rule
Under 'Condition', choose 'Data Comparison' > Compare 'view-mode equals Teaser/Full content/etc.'
Save the rule

I hope you are aware that your rule will get triggered whenever the content is viewed in this view mode anywhere in the site and not just in Panels.
Hope this helps.
Regards,
Supriya Rajgopal
Comment: I have just added to my question that my Pane uses the *Full content* build mode, but the same issue arises for all building modes. Also, I already have the condition you suggested in my Rule. The problem is that the Rule itself is not triggered, so it doesn't even check the build mode condition. Since the Rule is correctly triggered when a teaser is viewed in a View (which is included in a Panel), it seems to me that the problem should have something to do with Panels.


table cell font in RTF with lowagie Document

Question: I am trying to create RTF document with tables with empty cells.
I use the com.lowagie.text.rtf.* package in java.
The font of the empty cells are all Times New Roman size 12.
How can I set the font of the empty cells to a different Font?
I have used RtfCell cellSpacer = new RtfCell(new Phrase("", new RtfFont("Arial", 9, RtfFont.NORMAL))); but because the string "" is empty the font doesn't take effect. When the "" is filled with something except a space the font does take effect.
Thank you.
Answer: A solution to this problem is that the space must be given as a Non Breaking space to the Phrase constructor!
String nbs = "\u00A0";
RtfCell cellSpacer = new RtfCell(new Phrase(nbs, new RtfFont("Arial", 9, RtfFont.NORMAL)));
Answer: I think the issue is this validation on line 198 on Phrase.java, which is called from the constructor Phrase(String string, Font font). Basically, it checks that the string is not empty, otherwise it won't create a chunk containing the text and font you specify.
It seems that you should either:

Pass a space to the constructor:
new Phrase(" ", new RtfFont("Arial", 9, RtfFont.NORMAL))
Create a new custom class (class AllowsEmptyPhrase extends Phrase), copy the constructors and remove the unwanted behaviour.
Comment: Thank you for your answer. As you can see in my question I have tried passing a space to the constructor but didn't work. I haven't try to extend the Phrase class, yet.


Use bsdiff being the source and target file the same one. Other difference algorithms suitable for this?

Question: I am trying to patch a file using bsdiff, my problem is that I have to do it having few memory available. According to this constraint I need to modify the source file with the patch in order to get the target file.
Bsdiff basic are as follows:
header: not very relevant in this explanation.
Control data block:

mixlen-> number of bytes to be modified combining the bytes from the source
file and the bytes obtained from the diff block.
copylen-> number of bytes to be added. This is totally new extra data
that need to be added to our file. This bytes are read from the
extra block.
seeklen-> number used to know which we have to read from the source file.

Compressed control block.
Compressed diff block.
Compressed extra block.
<code>Patch file format:
  0        8       BSDIFF_CONFIG_MAGIC
  8        8       X
  16       8       Y
  24       8       sizeof(newfile)
  32       X       control block
  32+X     Y       diff block
  32+X+Y   ???     extra block
  with control block a set of triples (x,y,z) meaning "add x bytes
  from oldfile to x bytes from the diff block; copy y bytes from the
  extra block; seek forwards in oldfile by z bytes".
</code>
So the problem is that bsdiff considers I always have the source file without any modification, so it uses it to modify data that I have already modified (if I consider the source the same file as the target). Firstly I tried to reorder the modifications to do, but in some cases these modifications affect memory that will be used in the future for another modification. Maybe the algorithm is not suitable what I want.
Does exist another algorithm suitable for this? Is there any implementation of BSDIFF or similar doing what I need?
Before going more in depth with Bsdiff I did some research, finding VCDIFF(used by Xdelta) but it also seems to have the same behavior I haven't dug into the code though, so I don't know yet if it generate the patch in the same what as Bsdiff does.
Another point to remark would be I am trying to implement it in C.
Edited 04/10/2016:
I have tried to reorder the patch, because having the addresses to modify ordered from smaller to the bigger I thought I could handle this problem storing the original memory data into a buffer until the next modification which requires that original data had been done, but it seems that the patch order is important also, maybe in Bsdiff it modifies several times the same part of memory until it gets the right data. Any idea will be very welcome if someone knows about this.
Best regards,
Iván
Answer: We cannot eliminate the dependency on source data without impacting the compressed delta size. So, you will need to have source data unmodified to make BSDIFF work in the scenario you explained.


Python NameError: not defined

Question: I am trying to create an accumulating total based on users input.
class Accumulator:
    # Create self value == 0
    def __init__(self, newval = 0):
        self.value = newval

    # Addition function
    def add(self, newval):
        return self.value + newval

Then I have several different functions that go here. After the functions are all complete I set my operator equal to anything other that 'T' which instantly terminates the program. Here when i try: newval, operator is where I get my first error, secondly I will get the error "add" is not defined.
operator = 'z'

while operator != 't' or operator != 'T':
    try:
        newval, operator
    except:
        #Prompt user to enter a number and valid operator
        newval, operator = input("Enter a valid number, space, then an operator: ").split()

Below here, depending on what the users inputs for the operator calls whatever function associated with the letter. Take "A" for example:
elif operator == 'a' or operator == 'A':
        print(add(self, newval))
        self.value = add(self, newval)

Then My program should keep the accumulating total and continue running... untill the user enters 't' or 'T'.
Comment: just a quick comment: `operator` is the name of one of python's module. so maybe not good idea to use this name as variable.
Comment: I agree with @Marcin, please avoid using python module name for variable.
Comment: Ok I will. I didn't realize operator was a module.
Answer: You have to use self.add if you are using inside class
elif operator == 'a' or operator == 'A':
    print(self.add(self, newval))
    self.value = self.add(self, newval)

If you are not using inside same class then you have to use object varibale
a = Accumulator()
...
...
elif operator == 'a' or operator == 'A':
    print(a.add(self, newval))
    self.value = a.add(self, newval)

Comment: Still tells me: Traceback (most recent call last):
  File "C:/Python34/Python Files/test5.py", line 52, in
    self, operator
NameError: name 'self' is not defined
Comment: can I send you an email so you see what I am doing wrong?
Comment: I have tried both ways and still can't get it working.
Comment: If you can update question with full code then also I can help.
Comment: I finally got it. Thanks tho @Lafada I appreciate the help
Comment: If you can add your solution, it will help others too.

Python NameError: not defined


Models em Django fica tudo em um arquivo?

Question: estou iniciando meus estudos em Django, venho de frameworks como Rails, Laravel, Asp.Net, e me deparei com uma diferença que até estranhei de no Django os models ficarem todos juntos, isso é normal? Tem uma forma de deixar cada model em um arquivo? A comunidade não estranha isso?
Answer:
É normal?

Depende de você. Para aplicações pequenas, geralmente não precisa de muitos arquivos, pode simplesmente juntar todos em um.

Tem uma forma de deixar cada model em um arquivo?

Tem, mas você terá muito mais trabalho com isso, pois no Python o arquivo é que define um módulo. Criando um model em cada arquivo, você estará criando um módulo para cada model. Isso não faz sentido, além de adicionar uma redundância grande no código:
<code>import foo.models.usuarios.Usuarios
import foo.models.cidades.Cidades
...
</code>
O nome do model acabará se repetindo como nome do módulo.

A comunidade não estranha isso?

Não, pois essa é a filosofia do Python. Um diretório define um pacote (package) e um arquivo define um módulo (module). Muitas outras linguagens que citou não utilizam esse formato.
Mas, além de tudo, perceba que nem todos os models ficarão no mesmo arquivo. O Django trabalha com o conceito de apps e cada app possui seu próprio arquivo de models. Ou seja, apenas os models que estão relacionados e pertencem à um mesmo app que estarão no mesmo arquivo. Se sua aplicação crescer, acabará tendo vários apps e, consequentemente*, vários arquivos de models.


como posso pegar um item selecionado de uma flatlist e passar para outra flat list?

Question: import React,{useState, useContext, useEffect} from 'react';
import { View, Text, Platform, SafeAreaView, TouchableWithoutFeedback, Keyboard, Alert, } from 'react-native';
import {format} from 'date-fns';
import { Container, ListPiscinasRecebidas, ListPedidoPiscinas, Title, TitlePedido, TextPiscinaValor, ButtonAddPiscina, FecharPedidoButton, FecharPedidoText } from './styles';
import {AuthContextLojista} from '../../contextsLojista/authLojista';
import firebase from '../../services/firebaseConnection';
import Header from '../../componentsFabrica/headerFabrica';
import PickerLojista from '../../componentsLojista/pickerLojista/index.android';
import ListaDePiscina from './ListaDePiscina';
import ListaPedidoPiscinas from './ListaPedidoPiscina';
export default function FazerPedido(){
const { userLojista: usuarioLojista } = useContext(AuthContextLojista);
const { userLojista } = useContext(AuthContextLojista);
const uid = userLojista && userLojista.uid;
const [selecioneFabrica, setSelecioneFabrica] = useState(null);

const [valor, setValor] = useState('');
const [nomeDaPiscina, setNomeDaPiscina] = useState([
    { key: '1', nomeDaPiscina: 'Italianaa', valor: 1111 },
    { key: '2', nomeDaPiscina: 'Italianaa2', valor: 1111 },
    { key: '3', nomeDaPiscina: 'Italianaa3', valor: 1111 },
    { key: '4', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '5', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '6', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '7', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '8', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '9', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '10', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '11', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '12', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '13', nomeDaPiscina: 'Italianaa4', valor: 1111 },
    { key: '14', nomeDaPiscina: 'Italianaa4', valor: 1111 },
]);

function handleSelectPiscina(data) {
    Alert.alert(
        'Cuidado preste Atenção!',
        `Você deseja Adicionar ${data.nomeDaPiscina} - Valor: ${data.valor}`,
        [
            {
                text: 'Cancelar',
                style: 'cancel'
            },
            {
                text: 'Continuar',
                onPress: () => handleSelect(data)
            }
        ]

    )
}

function handleSelect(){

}

    return (
        <TouchableWithoutFeedback onPress={()=> Keyboard.dismiss()}>
        <Container>

            <Title>{userLojista && userLojista.nomeDaLoja} </Title>
            <SafeAreaView>
                    <PickerLojista onChange={setSelecioneFabrica} selecioneFabrica={selecioneFabrica} />
            </SafeAreaView>

            <Title>Piscinas da Fabrica</Title>
            <ListPiscinasRecebidas
            showsVerticalScrollIndicator={false}
            data={nomeDaPiscina}
            keyExtractor={item=> item.key}
            renderItem={({ item }) => (<ListaDePiscina data={item} handleSelect={handleSelectPiscina}/>)}
            />

             <TitlePedido>Meu Pedido</TitlePedido>
            <ListPedidoPiscinas
                    showsVerticalScrollIndicator={false}
                    data={handleSelect}
                    keyExtractor={item => item}
                    renderItem={({ item }) => (<ListaPedidoPiscinas data={item} handleSelect={data} />)}

            />
                <FecharPedidoButton>
                    <FecharPedidoText>Fechar Pedido</FecharPedidoText>
                </FecharPedidoButton>
        </Container>
        </TouchableWithoutFeedback>
    );
}

Answer: Use onPress e guarde o item no state.
// no Componente da lista ...

renderItem={({ item }) => {
  <TouchableOpacity onPress={() => handleSelectList(item)}>
   <ListaDePiscina data={item} handleSelect={handleSelectPiscina}/>
  </TouchableOpacity>
 }
}

// ...

Ou dentro do componente <ListaDePiscina />, adicione um componente (ex. TouchableOpacity) que tenha onPress em sua prop.
Na função em onPress, receba o item que foi pressionado e manipule para adicionar em uma nova lista no state que tenha os itens que selecionados.
Obs.: No código de exemplo a função handleSelectList(item) não foi criada. Mas ela deveria fazer algo como:

Receber os itens que anteriormente foram selecionados (opcional, depende do seu objetivo);
Adicionar os itens recebidos com o novo item;
Setar os dados manipulados a cima no state.
Comment: obrigado pela ajuda, estou tentando resolver isso tem muito tempo e não tenho conseguido, tentei fazer da maneira que você falou mas não consegui
Comment: no momento estou ocupado com o trabalho, mas executo o código por cá para podermos solucionar, caso ainda não tenha conseguido.
Comment: tudo bem, me desculpa incomodar, é que estou com muita dificuldade mesmo e eu gostaria de resolver isso, mas eu acho que é avançado demais pra mim.


What is the correct core update workflow?

Question: I want to use composer to manage Drupal 8 dependencies, but I'm not sure what is the right core update workflow.
At the moment I'm using drush to update core to latest beta release, but I also have some dependencies in my composer.json file, so after the update I'm using composer install to install all the contrib vendor dependencies.
It appears that running composer install overrides some files in the core directory, although I've just updated core to latest version.
I've also tried to manually edit the composer.json file and replace the "drupal/core" line with the specific beta release, e.g. "drupal/core": "~8.0-beta14",, but it still overrides files in the core directory.
What is the right workflow?
Answer: I presume that you are using drupal-composer/drupal-project as the basis for your project.  If not, take a look at that project, and compare it with yours.
Also, you said that you want to use composer to manage Drupal 8 dependencies, so I presume that you have selected your contrib modules via composer require drupal/devel rather than drush dl devel.
If you are doing all of these things, then you should use composer update to update Drupal core and all of your contrib modules.  As long as you retain your composer.lock file, composer install should not change the version of any of your dependencies.  You should not use drush pm-update at all.  It should not matter to you whether or not files in the core directory are updated or not, as this directory is managed by Composer.  You are better off not committing composer-managed directories to your repository, although you can if you wish.
Of course, you should run drush updatedb whenever composer update replaces Drupal core or any module.
To avoid getting development versions, set your minimum stability to 'beta' in your composer.json file using Composer stability flags.
If you are using drupal-composer/drupal-project to manage your site, then all of the root-level files such as README.txt, .htaccess and index.html become owned by your project. That means that you should check them in to your git repository; Composer will not update them, you must update them yourself when they change.  These files should change only rarely, but drupal-composer/drupal-project has a script to update these files.
Comment: Lets assume that I'm using composer update instead of drush pm-update, how do I update files such as README.txt, .htaccess, etc..? And how come drush update gives different core than composer update? And should I replace drupal's version in my composer.json to 8.0-betaX before each update? I don't want to use dev. version..
Comment: Updated the answer.
Comment: +1 greg_1_anderson - this looks great, is this the definitive way to do security updates for Drupal 8? with D7, it's: http://drupal.stackexchange.com/a/71578
Comment: This looks like it works if one had initially installed Drupal 8.1 with these steps: https://www.drupal.org/node/2471553 (I found this to work without error)
Comment: "Of course, you should run `drush updatedb` whenever composer update replaces Drupal core or any module." - thank you and if you had initially installed drupal with these steps,  https://drupal.org/node/2471553 then you need the full path to the particular drush with your Drupal 8 install (as they used to run the install as the final step). You first need to cd into web and once in /web the command to update the db with the full path would therefore be: `../vendor/drush/drush/drush updatedb` (I found this to work).
Comment: If you don't use this full path i.e. `../vendor/drush/drush/drush updatedb` you may (depending on your set up), get the error: "Command updatedb needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run[error]
this command." So use the full path, cheers!
Answer: Yes, you can manage Drupal core with composer. There are a couple of things to be aware of though.
You will probably get timeouts due to a number of items composer has to run through, especially if you run in a local VM. If you run composer install you will likely get the composer error:
 [RuntimeException]
  Could not delete core/.nfs0000000000000000000001:

Make sure you use require
{
  "require": {
   "drupal/core": "8.3.*"

Also add an extension to the timeout in the config
    "installer-paths": {
        "core": ["type:drupal-core"],
        "modules/contrib/{$name}": ["type:drupal-module"],
        "profiles/contrib/{$name}": ["type:drupal-profile"],
        "themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "modules/custom/{$name}": ["type:drupal-custom-module"],
        "themes/custom/{$name}": ["type:drupal-custom-theme"]
    }
},

"config":{
            "process-timeout": 1600
       },

Also if that does not work you can run composer install from outside SSH in your VM.
This will bypass any NFS share timeouts and unpack Drupal in the right place.
Answer: The following is OK for patch releases 8.4.x > 8.4.y, but not OK for minor releases 8.4.x > 8.5.x. Jump to UPDATE 3 below for what I believe is "the answer" for minor release updates.
1- Backup any files that come with Drupal which you have modified, such as .htaccess, robots.txt, etc. (those 2 are the most commonly changed).
2- [I am told delete lock file is wrong, see UPDATE below] Delete the composer.lock file (in the top level folder of your site). This gets recreated in step 5.
3- Check your composer.json  (in the top level folder of your site) and make sure that the "drupal:core" is in the require section and not in a replace section, for example
"require": {
"drupal/core": "^8.4"
},

not
"replace": {
"drupal/core": "^8.4"
},

If "drupal/core" is in the replace section, move it to the require section and delete the replace section.  If there are other entries in the replace section, just remove the "drupal/core" not the entire replace section - but I think "drupal/core" is normally the only thing there.
Put what version you want to update to in "drupal/core", examples:
"drupal/core": "^8.5" - will update to the latest version of 8.5.
"drupal/core": "8.4.6" - will update to version 8.4.6.
5- Run this (in the top level folder of your site):
composer update drupal/core --with-dependencies

6- If no errors, then do the usual, run the updates and clear cache:
drush updatedb
drush cr

Or if not using drush, go to /update.php to run updates, then to admin/config/development/performance and hit the "Clear all caches" button.
7- If you had backed up files in the first step (.htaccess, robots.txt) put them back. But check to see if Drupal made updates to those files and add those changes to yours.
DONE
If there were errors with the composer update in step 5, it is usually due to issues with versions of the stuff in the vendor folder.
This is a great post in dealing with such issues:  https://www.jeffgeerling.com/blog/2018/updating-drupalcore-composer-drupal-core-doesnt-update and read Jeff's other 2 posts on Drupal and Composer to get more knowledge about that.
I was told by 2 people on Twitter that composer.lock should not be deleted (Step 2 above).  The composer update drupal/core --with-dependencies command recreates the lock file anyways.
In testing this method I find it works fine for 8.4.3 > 8.4.6 (for example) but I get errors for 8.4.6 > 8.5.x.  Will report back when I figure it out.
Example of errors:
Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - symfony/yaml 3.4.x-dev conflicts with symfony/console[v3.2.8].
    - symfony/yaml 3.4.x-dev conflicts with symfony/console[v3.2.8].
    - symfony/yaml 3.4.x-dev conflicts with symfony/console[v3.2.8].
    - drupal/core 8.5.0 requires symfony/yaml ~3.4.5 -> satisfiable by symfony/yaml[3.4.x-dev].
    - Installation request for drupal/core 8.5.0 -> satisfiable by drupal/core[8.5.0].
    - Installation request for symfony/console (locked at v3.2.8, required as ~3.2.8) -> satisfiable by symfony/console[v3.2.8].

This post by Jeff Geerling addresses similar issues, but so far no luck for me: https://www.jeffgeerling.com/blog/2018/updating-drupalcore-composer-drupal-core-doesnt-update
So... the only thing that seems to work for me for 8.4.x > 8.5.x is the "nuclear option" that so many others seem to use, which is run composer update.
I guess that is OK so long as you are sure about the module versions in composer.json.  Maybe one should lock them down to the current version.  For example:
"drupal/address": "1.3"

rather than:
"drupal/address": "^1.3"

But is the the right answer?
OK the answer that seems to be everywhere is to do the "nuclear option":
A. Delete the /vendor folder.
B. Run composer update and simply update your modules along with core. Or, lock down the module versions in composer.json if you don't want to update them.
One person on Drupal Slack said "the whole philosophy of Composer is that you should always be updating packages, as frequently as possible".  Packaged includes modules I think. So it  makes some sense I guess.
Once I got from 8.4.6 to 8.5.0, this worked fine to get from 8.5.0 to 8.5.1 composer update drupal/core --with-dependencies just as it did for 8.4.3 to 8.4.6.
I am starting to conclude that "the answer" is that deleting the vendor folder and the composer.lock file, then using composer update is fine, and that one should simply make sure the version numbers for dependencies in the composer.json file are what you want. It's not that big a deal to manage what module versions you want to keep or allow to update in composer.json.
For example:
"drupal/admin_toolbar": "1.18",  means stick with 1.18
"drupal/admin_toolbar": "^1.18",  means go ahead and update but within 1.x (not 2.x)
This is backed up by a comment (General Redneck) on this post: https://www.jeffgeerling.com/blog/2018/updating-drupalcore-composer-drupal-core-doesnt-update
"One of the things I've found as I work in support is that locking down the versions of modules and core is a good idea so that you CAN thermonuke the thing when you want because there are times when some of the various plugins even don't want to behave correctly."
By the way, the composer.lock file is no help with composer update because it gets blown away (as opposed to composer install where he lock file is read):
Running composer install will:

Check if a composer.lock exists
If not, perform a composer update to create one
If composer.lock exists, install the specified versions from the lock file

Running composer update will:

Check composer.json
Determine the latest versions to install based on your version specs
Install the latest versions
Update composer.lock to reflect the latest versions installed

Ref: https://www.engineyard.com/blog/composer-its-all-about-the-lock-file
I see this is mentioned above: https://github.com/drupal-composer/drupal-project. I have used that and it's fine but it is not a requirement for using Composer with Drupal. It is confusing as it sort of "sounds" like it is from the name. When I first started with Drupal 8 I thought it was required, so built my first D8 site with that, thinking it was best practice.
That "version" of Drupal has he docroot in a /web folder, not in the top folder of the project. Also there is a bunch of stuff added to .gitignore compared to normal Drupal:
/drush/contrib/
/vendor/
/web/core/
/web/modules/contrib/
/web/themes/contrib/
/web/profiles/contrib/
/web/libraries/

So, this version of Drupal is really more meant for sites which are using continuous integration to do a new build of Drupal on every deploy, using composer install. If you deploy with a more normal method, you obviously have to commit all the above stuff to your git repo or it will not get deployed to your server [1], and that stuff is all needed for Drupal to run.
[1] if git is involved with your deploy - if you deploy with SFTP, ignore this.
Comment: `composer update drupal/core symfony/config webflo/drupal-core-strict --with-dependencies` has never failed me yet. Works over several minor versions, e.g. 8.3 -> 8.6
Answer: Using the drupal/core package on packagist.org we can actually manage the core, the contrib modules (, themes and profiles) and the other vendors via composer.
I've setup the following files in my root directory and executed composer install
composer.json
{
  "require": {
    "composer/installers": "^1.0.20",
    "drupal/core": "8.0.*"
  },
  "extra": {
    "installer-paths": {
      "core": ["type:drupal-core"],
      "modules/contrib": ["type:drupal-module"],
      "profiles/contrib": ["type:drupal-profile"],
      "themes/contrib": ["type:drupal-theme"]
    }
  },
  "scripts": {
    "post-install-cmd": [
      "./post_install.sh"
    ]
  }
}

post_install.sh
#!/usr/bin/env bash
export RAW_DRUPAL="https://raw.githubusercontent.com/drupal/drupal/8.0.x"
curl $RAW_DRUPAL/example.gitignore > example.gitignore
curl $RAW_DRUPAL/.gitattributes > .gitattributes
curl $RAW_DRUPAL/.htaccess > .htaccess
curl $RAW_DRUPAL/.csslintrc > .csslintrc
curl $RAW_DRUPAL/.editorconfig > .editorconfig
curl $RAW_DRUPAL/.eslintrc > .eslintrc
curl $RAW_DRUPAL/.eslintignore > .eslintignore
curl $RAW_DRUPAL/index.php > index.php
curl $RAW_DRUPAL/update.php > update.php
curl $RAW_DRUPAL/web.config > web.config
curl $RAW_DRUPAL/autoload.php > autoload.php
curl $RAW_DRUPAL/robots.txt > robots.txt
mkdir -p sites/default
curl $RAW_DRUPAL/sites/example.sites.php > sites/example.sites.php
curl $RAW_DRUPAL/sites/development.services.yml > sites/development.services.yml
curl $RAW_DRUPAL/sites/example.settings.local.php > sites/example.settings.local.php
curl $RAW_DRUPAL/sites/default/default.services.yml > sites/default/default.services.yml
curl $RAW_DRUPAL/sites/default/default.settings.php > sites/default/default.settings.php

Enjoy :)
Comment: I guess I will need all that curl magic you've done. I was expecting all these needed files to be put in place by composer.
Comment: @hiphip The files outside of the core directory do not change often, so the above could be a script that you perform manually when drupal updates from one minor version to the next (i.e. 8.1 to 8.2)
Answer: "drupal/core": "~8.0-beta14" means any release greater than 8.0-beta14 and less than 9!  You'll want to remove the tilde to lock it to a specific release.  Then make sure to update your lock file by running composer up, and on the target system use composer install.
An easy way to get started is to build the codebase using https://github.com/drupal-composer/drupal-project.
When we need to update something such as upgrading core, you run "composer up" locally.  This will update the composer.lock file.
When other developers pull down, or in a deployment script, you would run "composer install", which uses the lock file.
The line in our composer.json for Drupal core is:
"drupal/core": "~8.0",

The tilde () means any release within the 8 number (but not 9).
If you want to lock it to a specific version, you shouldn't use the tilde.
"drupal/core": "8.0-beta14",

then run "composer up" locally, commit the composer.json and composer.lock file, and then run "composer install" on other installations after pulling down the codebase.


Função paralela em website

Question: Tenho uma classe que gera um arquivo .xls para download. O problema é que ele tem mais de 30.000 entradas, então acaba demorando uns 10 minutos para gerar. E nesse tempo tenho que ficar com a página aberta carregando.
Lembro de uns sites que eu usava para converter arquivos nos quais após terminar o upload eu podia fechar a página, o navegador e até desligar o computador que quando o processo estivesse terminado eu iria receber um e-mail com o meu arquivo anexado.
Minha intenção é fazer o mesmo com este arquivo. O usuário clica para fazer download, em seguida é redirecionado para um página que diz que ele vai receber o arquivo no e-mail e enquanto isso ele pode fechar a página e fazer outra coisa.
Em minhas pesquisas acabei encontrando o pcntl_fork(), que parecia ser perfeito, até eu descobrir que ele só funciona se eu rodar o .php diretamente do terminal. Não encontrei nada que funcione em websites.
Answer: Resolvi de uma forma bem simples. Modifiquei o botão de gerar .xlsx para que ao invés de gerar, ele chame no terminal o código que gera com shell_exec("php nomeDoArquivo.php"), mas mesmo assim ele fica esperando o output do terminal, então acabava demorando igual.
Para resolver isso, como o output do terminal não me interessa¹ eu pedi para ignorá-lo modificando o comando para:
$your_command = "php nomeDoArquivo.php";
shell_exec( $your_command . "> /dev/null 2>/dev/null &" );

Fonte: Mat
[1]: Muito cuidado ao ignorar o output, se tiver algum erro no processo você nunca vai saber. Como meu script já envia um email com anexo eu já o configurei para quando der erro enviar um email para mim com a mensagem do erro.
Answer: Uma solução, talvez não muito elegante, seria colocar esse arquivo numa fila (gerenciada numa tabela de banco de dados e/ou diretório), e no servidor teria um script PHP em cronjob que faria o trabalho de gerar o arquivo e enviar para o email de tempos em tempos.

Função paralela em website


Localizar um grupo numérico na string

Question: Olá, gostaria de uma ajuda para localizar um grupo de 20 números dentro de uma string que possui caracteres e símbolos.
Digamos que minha string tem 165 caracteres, quero os números de 127 a 147 que são meu grupo "00001138271467122784", mas o tamanho da string nas outras linhas é variado, meu numero pode começar antes ou depois, a ordem de inicio e fim não é fixa.
Eu tenho '_' para poder delimitar, mas como?
SQL Server Management Studio
Comment: Não é isso Cigano, o tamanho da string é de 165 caracteres, o meu exemplo esta na posição inicial 127 e posição final 147, mas apenas neste exemplo, em outra linha a posição (localização) muda.
quero pegar todo o conjunto 00001138271467122784 que sempre é de 20 caracteres.

Esta é a string
file%3A%2F%2F%2Fmnt%2FABOX%2FRESULTS%2Fresults%2Fresults%2Ftxt%2F20160628105952000_083021988480019_38505_4524425_170_2239408_>>>00001138271467122784<<<<_41_53_ATENDENTE.txt
Comment: Este exemplo, "00001138271467122784", não tem nem 127 nem 147 como sequências. Poderia colocar mais exemplos?
Comment: Entendi. Obrigado por esclarecer ;)
Answer: Eis demonstração do uso da função charindex para encontrar o trecho que procura.
<code> -- código #1
declare @URL varchar(2000);
set @URL= 'file%3A%2F%2F%2Fmnt%2FABOX%2FRESULTS%2Fresults%2Fresults%2Ftxt%2F20160628105952000_083021988480019_38505_4524425_170_2239408_>>>00001138271467122784<<<<_41_53_ATENDENTE.txt';

PRINT charindex('00001138271467122784', @URL);
</code>
O código para pesquisar nas linhas de uma tabela pode ser algo como:
<code>-- código #2
declare @Txt char(20);
set @Txt= '00001138271467122784';

SELECT URL,
       [Posição]= charindex(@Txt, URL)
  from tabela;
</code>

ATUALIZAÇÃO

Acabei de descobrir um padrão os conjuntos que quero, estão entre o sexto '_' e o antepenúltimo '_' (9 da contagem) sempre assim, então preciso de algo que pegue a posição deles, do sexto e do Nono '_' e entre eles esta o campo que quero.

Considerando-se as explicações adicionais sobre o separador "_", pode-se criar uma função específica para obter o conteúdo entre os sexto e nono "_".
<code>-- código #4 v3
CREATE FUNCTION analisaURL (@pURL varchar(2000))
       returns @pToken varchar(200) as
begin
declare @I int, @Pos6 int, @Pos9 int;

-- obtém sexto "_"
set @Pos6= 0;
set @I= 0;
while @I <> 6
  begin
  set @Pos6= charindex('_', @pURL, (@Pos6 +1));
  set @I += 1;
  end;

-- obtém nono "_"
set @Pos9= @Pos6;
while @I <> 9
  begin
  set @Pos9= charindex('_', @pURL, (@Pos9 +1));
  set @I += 1;
  end;

return substring(@pURL, (@Pos6 +1), (@Pos9 - @Pos6 -1));
end;
go
</code>
Avalie com atenção o código da função, pois não foi testada. Recomenda-se acrescentar tratamento de erro na função.
A utilização da função fica desta forma:
<code>-- código #5
SELECT T.URL, dbo.analisaURL(T.URL) as Token
  from tabela as T;
</code>

Outra opção é utilizar função do tipo split string para dividir a URL em partes e a seguir selecionar somente a sétima parte de cada URL.
<code>-- código #3 v2
with cteSplitURL as (
SELECT T.URL, S.ItemNumber as seq, S.Item as token
  from tabela as T
       outer apply dbo.SplitURL(T.URL, '_') as S
)
SELECT URL, token
  from cteSplitURL
  where seq = 7;
</code>
O código #3 é o esboço do código; você deve acrescentar função do tipo split string que retorne tokens e a sequência dele no string.
Artigos contendo funções split string:

Tally OH! An Improved SQL 8K "CSV Splitter" Function
Split strings the right way – or the next best way
Comment: Olá @José Diz, obrigado pela ajuda mas nesse caso que sitou, eu sempre vou acabar encontrando o mesmo numero '00001138271467122784' eu gostaria de procurar na string o mesmo conjunto, digo pegar sempre uma cadeia de 20 números agrupados.
nao importa se tem (posicao 0)00123456....(posicao 20) quero sempre localizar um determinado grupo entende?
esses numeros são os unicos a terem 20 caraceteres numericos em sequencia.
Comment: Acabei de descobrir um padrão os conjuntos que quero, estão entre o sexto '_' e o antepenúltimo '_' (9 da contagem) sempre assim, então preciso de algo que pegue a posição deles, do sexto e do Nono '_' e entre eles esta o campo que quero.
Comment: @KalebGabriel: Quando possível, avalie o código #5.
Comment: irei estudar o código que me passou, isto que estou fazendo é um select para mirar as informações do banco para o qlikview.
Vou analisar direitinho, mas me disseram que eu poderia fazer com charindex pegar a posição e depois usar substring, mas eu nao consigo fazer o calculo no substring.
Comment: Tenho as linhas F:
CHARINDEX('_', uri, CHARINDEX('_', uri,CHARINDEX('_', uri,CHARINDEX('_', uri, CHARINDEX('_', uri, CHARINDEX('_', uri, 1) + 1) + 1) + 1) + 1) + 1) AS f

E linha G:
CHARINDEX('_', uri, CHARINDEX('_', uri,CHARINDEX('_', uri,CHARINDEX('_', uri, CHARINDEX('_', uri, CHARINDEX('_', uri, CHARINDEX('_', uri, 1) + 1) + 1) + 1) + 1) + 1) + 1) AS g

não consigo fazer o calculo com os apelidos deles f e g
SUBSTRING(uri, f + 1, g - f - 1))) AS ucid
Comment: @KalebGabriel: Vejo como uma complicação essa sequência de charindex. Conhece o princípio KISS?  Se ainda não, acesse https://en.wikipedia.org/wiki/KISS_principle //
Comment: Uma pergunta, é possível usar o apelido de uma coluna dentro  de uma função?
por exemplo usei o charindex pra pegar as posições, meu charindex de apelido F e G são respectivamente as posições iniciais e finais, consigo usar no substring? Substring(uri, F, G)? nao deu certo nao reconhece
Comment: @KalebGabriel: O macete, nesse caso, é utilizar CTE: with cteX as (*código da consulta*) SELECT substring(URI, F, (G - F -1)) from cteX; // Ou subconsulta:  SELECT substring(URI, F, (G - F -1)) from (*código da consulta*) as T; // Acho que é isso.
Comment: Isso mesmo obrigado. \o/

Localizar um grupo numérico na string


Contador javascript para controller php

Question: Tenho um formulário com inputs dinamicos:
<form method="post" action="getDatabases/getCurso.php">

                                                    Curso
                                                    <input type="text" class="form-control" name="field_curso_curso[]" value=""/>

                                                    Conclusão
                                                    <select class="form-control" name="field_curso_conclusao">
                                                        <option></option>
                                                        <option>Concluido em:</option>
                                                        <option>Espero concluir em:</option>
                                                    </select>

                                                    Ano
                                                    <input class="form-control" placeholder="Ano" name="field_curso_ano[]" value=""/>

                                        <input type="submit"/>
                                    </form>

A parte dinâmica é montada pelo js:

Agora preciso montar um controller em php que pegue esses dados, como estou utilizando uma array em cada campo, estou fazendo assim:
    $instituicao = $_POST['field_curso_instituicao'];
    $curso = $_POST['field_curso_curso'];
    $conclusao = $_POST['field_curso_conclusao'];
    $ano = $_POST['field_curso_ano'];

mas preciso criar um laço de for para correr esses dados e armazenar no BD, e quero usar o contador contCurso da função js para o mesmo
De modo grosseiro, seria algo parecido com isso :
$queryBD = "insert into bd(instituicao,curso,conclusao,ano) values ("$instituicao","$curso","$conclusao","$ano")"

    for($i=0; $i= $contCurso; $i++){
      $queryBD;
}

O que eu quero saber é o seguinte: De que maneira posso passar o valor da variável de contador contCurso (javascript) para um laço de for em um controller separado em php?
Obrigada
Answer: Você pode só incluir o valor do contador em um campo escondido e usar isso, não?
<input type="hidden" id="inputContador" name="contador">

Aí ao invés de só aumentar a variável, você usa uma função pra aumentar o valor do contador já presente na página:

var addContador = function(){
    var acc = parseInt( $('#inputContador').val(), 10);
    console.log(acc);
    acc += 1;
    $('#inputContador').val(acc);
}

<input type="text" name="contador" id="inputContador" value="0" />

<button onclick="addContador()">+1</button>
Comment: Funcionou, agradeço, só uma pergunta: pra que serve o 10 em  var acc = parseInt( $('#inputContador').val(), 10); ??
Comment: é o segundo argumento da função ``parseInt()``, o primeiro é a string para converter em número e o segundo argumento é a base numérica usada (normalmente nem se coloca, mas eu sou paranóico do Javascript achar que o número é um octal, por exemplo).
Comment: legal, agradeço muito

Contador javascript para controller php


Sum of $ \frac{1}{1\cdot 3}+\frac{1}{1\cdot 3\cdot 5}+\frac{1}{1\cdot 3\cdot 5\cdot 7}+ \cdots$

Question:
Finding series sum of $$ \frac{1}{1\cdot 3}+\frac{1}{1\cdot 3\cdot 5}+\frac{1}{1\cdot 3\cdot 5\cdot 7}+\frac{1}{1\cdot 3\cdot 5\cdot 7\cdot 9}+ \cdots$$

Try: Let $\displaystyle a_{k}=\frac{1}{1\cdot 3\cdot 5\cdot 7\cdots (2k+1)}=\frac{2\cdot 4\cdot 6\cdots 2k}{(2k+1)!}$
So we have $\displaystyle a_{k}=\frac{2^k\cdot k!}{(2k+1)!}$
So our desired sum is $$\sum^{\infty}_{k=1}\frac{2^k\cdot k!}{(2k+1)!}$$
Now i am struck at that point
I did not understand how can i solve further,
Could some help me plaese , thanks
Comment: See related https://math.stackexchange.com/q/833920/72031
Answer: That term in the denominator is also called the double factorial, namely: $$(2n+1)!!=\frac{(2n+1)!}{2^n n!}$$
And our series can be rewritten as: $$S=\sum_{n=0}^\infty \frac{1}{(2n+1)!!}$$
Now from this link see (21), is given that: $$\sum_{n=0}^\infty \frac{x^{2n+1}}{(2n+1)!!}=\sqrt{\frac{\pi}{2}}\text{erf}\left(\frac{x}{\sqrt 2} \right) e^{\frac{x^2}{2}}$$
$$\Rightarrow S=\sqrt{\frac{e\pi}{2}}\text{erf}\left(\frac{1}{\sqrt 2}\right)$$ Where $\text{erf(z)}$ is the error function, defined as: $\displaystyle{\text{erf}(z)=\frac{2}{\sqrt{\pi}}\int_0^z e^{-t^2}dt}$
Answer: Let $$f(x)=\frac {x^3}{1.3}+\frac{x^5}{1.3.5}+...$$
We want the value of $f(1)$.  Note that
$$\frac{df}{dx}=xf(x)+x^2,\\f(0)=0$$


Proof by induction $\sum_{k=1}^{2n}(-1)^{k-1}\cdot k=-n$

Question: Hi I am trying to proof that
$\sum_{k=1}^{2n}(-1)^{k-1}\cdot k=-n$ by induction.
I end up here:
$-n+(-1)^{2n+2-1} \cdot (2n+2) = -n -2n -2 \ne -n$
Could someone help me find my mistake?
Thanks!
Comment: When we increment from $n=m$ to $n=m+1$ we add **two** terms,$$\sum_{k=2m+1}^{2m+2}(-1)^{k-1}k=(2m+1)-(2m+2)=-1.$$You seem to have only included the $k=2m+2$ term.
Comment: What matters is *how* did you end up there?
Comment: Thank you! Indeed, I have overlooked that I needed to add the **two** last terms of the sum.
Answer: For $n=1$,
\begin{equation*}
\sum_{k=1}^{2}(-1)^{k-1}\cdot k=(-1)^1\cdot1=-1.
\end{equation*}
Suppose it holds for $n$, i. e.,
\begin{equation}\label{1}
\sum_{k=1}^{2n}(-1)^{k-1}\cdot k=-n.  \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (1)
\end{equation}
Let's prove the result for $n+1$,
\begin{equation}
\begin{aligned}
\sum_{k=1}^{2(n+1)}(-1)^{k-1}\cdot k & = \sum_{k=1}^{2n+2}(-1)^{k-1}\cdot k \ \ \ \ \  \text{(we separate the last two terms of the sum)}\\
& =\sum_{k=1}^{2n}(-1)^{k-1}\cdot k+(-1)^{(2n+1)-1}\cdot(2n+1)+(-1)^{(2n+2)-1}\cdot(2n+2)\\
& =\underbrace{-n}_{\text{For} (1)}+(-1)^{2n}\cdot(2n+1)+(-1)^{2n+1}\cdot(2n+2)\\
& =-n+2n+1+(-1)(2n+2)\\
&=-n+2n+1-2n-2=-n-1\\
&=-(n+1).
\end{aligned}
\end{equation}
Answer: Plug in $n=1$ and see that the sum is $ -1 $.
Now, assume the property holds for some $n$. From this one is to show that it implies that the property holds for $n+1$. Notice that if $n=1$, the formula must hold for $n=2$. But since it holds for $n=2$, it must also be true for $n=3$, and so on. Hence the name: induction.
Proof that if $\sum_{k=1}^{2n} (-1)^{k-1}k = -n$ then $\sum_{k=1}^{2(n+1)} (-1)^{k-1}k$:
$$ \sum_{k=1}^{2(n+1)} (-1)^{k-1}k = \sum_{k=1}^{2n} (-1)^{k-1}k + (2n+1) - (2n-2) = -n + 2n + 1 - 2n - 2 = -n - 1 = -(n+1). $$ This is because of the induction hypothesis. Therefore the property holds for all positive integers $n$.


Electron-React ipcRenderer error "window.require is not a function"

Question: I'm following a lot of tutorials about integrating react and electron using ipcRenderer, but could not find any explanation why I'm getting an error "window.require is not a function" in my App.js.
import React from 'react';
import logo from './logo.svg';
import './App.css';
const { ipcRenderer } = window.require('electron');
function App() {

return (

Rendered

);

}

Please help.
Comment: i'm following this tutorial BTW.
[link](https://patrickpassarella.com/blog/creating-electron-react-app)
Answer: First of all, a 3 year old tutorial is not a reliable source, I recommend you take a look to Electron docs instead.
In the tutorial, webPreferences.nodeIntegration is set to true, which is not recommended for security reasons. You should not call directly electron in your renderer process (i.e. your React code).
If you want to use IPC to communicate between your main and renderer processes, you can use a preload script to expose what you need (but never IPC functions directly). If I take the example from the tutorial, here is the secure way to do it:
Preload
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  getData: (params) => ipcRenderer.send(channels.GET_DATA, params)
});

Renderer
const { electronAPI } = window;

const getData = () => {
  electronAPI.getData({ product });
};

And if you expect a response from the main process, you most probably want to use invoke/handle, and not send/on with a useEffect. Here is an example.
Comment: you don't know how much you help me, cheers.
Comment: Excelente respuesta!


How to render or include files/data in bootstrap.groovy?

Question: I want to use some parts of code in different area of bootstrap.groovy. How do I "include" these parts and reuse it?
def init = {
    environments {
        production {
            include("bla.groovy)
            include("blaFoo.groovy)
        }
        test {
            include("blaFoo.groovy)
        }
        development {
            include("bla.groovy)
            include("bla1.groovy)
            include("blaFoo.groovy)
        }
    }
}

Answer: You just import the files and call the functions or instantiate the classes defined therein
import bla
import blaFoo
import bla1

def init = {
    environments {
        production {
            // This function is defined in bla.groovy
            blaFunc()
        } test {
            // This class is defined in blaFoo.groovy
            new BlaFoo()
        } development {
            // This closure is defined in bla1.groovy
            bla1.call()
        }
    }
}


Is Vuex really necessary in vue 2?

Question: Imagine the following medium/large App using vue 2 (With vue 3 this would be easy to answer thanks to the composition api), where we got App.vue with X amount of components:

Suppose that "Children c" and "Comp A" use the same state (or single source of truth like some people say). Having said that, we could use vuex to store the state in one place, the problem with that is that now we have a global state for some data that needs to be shared between two distant components, but to be honest I just don't know if that's a good practice.
Now if the same need appear with different states between some components, we would have to repeat the same approach, creating many globals vuex stores for some components that need to consume the same data.
Now we also have Vue 2.6 Observables, these observables does basically the same as vuex without the vuex dev tools support and is already built in in Vue 2, but there is not enough documentation about it.
This is a quote from Thomas Findlay's  book vue- the road to enterprise:

What do you think, is vuex really worth it in vue 2 for a medium/large application?
Comment: my answer [here](https://stackoverflow.com/a/57712105/8172857) gives an example of obeservable, and for the case component A and C you could use the dependency injection
Comment: If you don't see the benefit of having one source of truth, you haven't developed enough. Between Vuex and `Vue.observable()` they're similar when all you want are synchronous mutations, but Vuex also has actions, which allow you to wrap much more complex logic, promise based. The real trick in using one source of truth is balancing logic between what is the general store and each component's internal reactive state (`data`). Overusing the general store can be bad, as can be not using it enough (or not having one at all).
Answer: Generally, Vuex or Global state is only necessary when children of different parents need to access the same data. For example authentication is a good one to have in global state if the application has more than one branch.
Using the event bus is effective but once the application grows to a certain point, it can become convoluted and difficult to understand where the data is flowing to which components.
One should be diligent in determining what data actually needs to be global because there is a price to pay with overhead.
I understand your resistance, globals are ugly, however many developers choose to use Global state management so that it is there need be.

Is Vuex really necessary in vue 2?


what are the loudest bass strings?

Question: I have a 38" 5 string bass and I don't have an amp. I know amps are almost equal to the price of strings, but

I cannot whatsoever play a 100 gauge B string or high E,

I don't want to tune up an octave because I have a guitar,

Can I tune bass up 4-5 steps?
Comment: It's not integral to the question, but the size of a bass is typically measured by scale length, not total length, and 38" is a highly unusual scale length for a bass.  So, I don't really know what size your bass is.
Comment: @Edward Even though I didn't VTC, I agree that when a question is as confusing as this one, "needs details or clarity" is a valid close reason. The asker can simply edit to explain what they are actually asking and then it can be reopened.
Comment: I'm pretty confused. Are you asking if you can get some type of bass strings that will make it so you don't need an amp? No strings can replace an amp. Strings generally are all the same volume.
Comment: This question isn't making much sense. Loud strings? un-amplified there won't be a lot of difference if any between makes (product recommendation is off-side here anyway).Low B with .100 isn't usual - .125 is. High E - there isn't a high E on bass. You can tune up as much as you like, but the gauge of strings already on will determine when the neck snaps. Please make the question clearer. And - standard bass strings are ~34", not sure where 38" comes in. Very mixed up.
Comment: I don't understand the close votes.  It seems clear to me that the problem OP is trying to solve is that he wants his electric bass to be louder without an amp, and his idea to achieve this is select louder strings and possibly tune up a little.  You might think this is not a good idea- I agree- but then put that in your answer, instead of closing the question.
Comment: @Edward re-tuning the strings by a fourth up can increase the tension by a lot, possibly to a range that is dangerous for the instrument. It is irresponsible to give an advice when we are uncertain what is the scale, what are the string gauges and how they are tuned.
Comment: @user1079505 Is this in response to my answer?  Regardless of the scale length, tuning up a fourth only requires moving the strings over by 1.  There is nothing irresponsible about recommending that.
Comment: For this question to make sense it needs to be clarified if the instrument really has extended scale of 38", how is it tuned and what are the string gauges.
Answer: The electric bass guitar is not an acoustic instrument.  I will answer your question, but not before saying that you should absolutely NOT buy strings based on their acoustic volume.  Strings don't affect the volume of the instrument much at all.  Get an amp before all else.
If you want to play a bass without an amp, you should be using an acoustic bass.
Besides that, if you're willing to play with a pick, that will be much louder than your fingers.
Strings are low down on the list on things that could make the instrument louder.
That said, the main things that would make a set of strings loud are 1) weight and 2) brightness.
Weight can be had simply by buying a heavier set of strings.  Most companies will sell a set in "medium", "light", etc.  Buying the next heavier set will make the body of the instrument vibrate a little bit more intensely, thus increasing volume.  I do not advise getting volume like this because it affects playability much more than volume.  It also can reduce the brightness of the strings, which would mostly negate any volume benefits you got.
Brightness can be had by using roundwound stainless steel strings.  These will be louder in the high frequencies, which your ear is more sensitive to, and thus will sound louder.  I do not advise getting volume like this because the "meat" of the bass tone is in the bass frequencies, and a brighter tone will not let you hear the bass frequencies any better.
You can tune your bass up, with the right strings.  Though BEADG is the most common tuning for a 5-string bass, EADGC is also common.  You're effectively moving the EADG strings over one, and then adding a C string at the top.  To do this properly, you will need to replace the nut on your instrument with one that has smaller slots for the strings.  You get a slight loudness increase just by playing in a higher register, but your EADG strings don't actually get any louder.  You just have the option to play on the ADGC strings instead.

what are the loudest bass strings?


Can I remove variance of OLS estimators through averaging coefficients from cross-validation?

Question: Imagine working on a linear multiple regression problem with a design-matrix $\Phi$ based upon some independent variables $x_k,  k\in{}[1, r]$. The goal is to find an equation that explains the "true" relationship between a dependent variable $y$ and independent variables $x_k,  k\in{}[1, r]$ e.g. of a recorded physical experiment. It is defined as
\begin{equation}
\bar{y}=\Phi\theta
\end{equation}
with $\theta$ being the regression coefficients and $\bar{y}$ being predictions of the estimator. Why do I need penalized regression or subset-selection?
From what I have read, additional unnecessary columns in $\Phi$ create more variance in the estimators parameters  $\theta$  but no bias (p.94, Kennedy: A guide to econometrics). (I assume this is because any correlation with relevant variables will result in some non-zero coefficient for that term. Coefficients could also act in opposing directions (such as with sin(x) and x at low x values). Is that correct? If you could help me understand this with the covariance matrix, that would be great.)
Why am I not able to remove this variance by using cross-validation and by averaging coefficients of the best sets? Isn't their mean free of bias? I read about this approach in (Brunton: DATA DRIVEN SCIENCE & ENGINEERING. http://databookuw.com/databook.pdf) but could not find it anywhere else. It also suggests thresholding small coefficients.
I read https://stats.stackexchange.com/questions/472202/when-to-use-regularization-vs-cross-validation#:~:text=Cross%20validation%20is%20about%20choosing,to%2C%20result%20in%20similar%20solutions and understand that cross-validation does not do the same thing as regularization. But shouldn't it converge to the true parameters for infinite data?
If you know a good piece of literature covering this, please share it. I am a mechanical engineering student and this topic is way above anything we have ever done in classes.
Thanks in advance!
Comment: Could you explain how one could ever get started doing a regression analysis with a "completely unknown" matrix of explanatory variables??
Comment: @whuber I meant that their transformations are unknown. It does not really contribute to the question, so I removed it. It could consist out of many possible transformation, such as trigonometric functions, polynomiales, ..., that could be part of the equation.
Answer: I have found my own theory on what is wrong with this approach. Please correct me if I am wrong!
Like suggested by Kutz in https://youtu.be/NoQV1lc7OlU?t=416 or his book on pdf-page 192 http://databookuw.com/databook.pdf, cross-validation does not serve any model building purpose. It only gets used to get a better idea of the generalization error. Dividing the data-set up into k subsets, performing regression on them and averaging their coefficients is not a great idea. This is because for small datasets, the weights of the data-points get disrupted (Running regression on the entire dataset vs running on smaller dataset then take average of coefficient?). This way a lot of bias gets introduced. If the sets consist out of more data, this effect will be lower. But by having fewer sets (assuming an unchanged set of data), the variance-reduction effect will also be less.
I believe that this is simply trading some unknown amount of bias for lower variance. It probably is better to just go for a biased regression straight away.


Cannot call chrome.alarms.create() from a content script

Question: I'm developing a Chrome extension right now.
My problem is that when I call chrome.alarms.create(), I get the following error:
Uncaught TypeError: Cannot read property 'create' of undefined

I have these files in my extension package:
manifest.json
{
    "manifest_version": 2,
    "name": "Tool",
    "version": "1.0",
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": ["background", "tabs", "webNavigation", "alarms"]
}

myscript.js
chrome.alarms.create("aaa", {"when":Date.now()+5000});

chrome.alarms.onAlarm.addListener(function(alarm){
  console.log("hello");
});

background.js
chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "myscript.js"});
});

When I call chrome.alarms.create() in background.js, it works fine.
But, when I call the function in myscript.js, it causes the error.
What is the cause and how can I fix this problem?
Answer: You can't access most Chrome APIs from a content script. You will need to use the Messaging API to send a message to the background page which can then call the Alarms API.
https://developer.chrome.com/extensions/messaging
https://developer.chrome.com/extensions/content_scripts
Comment: Yep, also consider checking out [chromeps](https://github.com/andersp/chromeps) to help simplify message passing.