Prove reduction formula for $\int\frac{dx}{(a^2-x^2)^n}$ using integration by parts

Question: I'm having difficulty proving this integral reduction formula by parts
If
$$I_n=\int\frac{dx}{(a^2-x^2)^n}$$
, then
$$\int\frac{dx}{(a^2-x^2)^n}=\frac{x}{2a^2(n-1)(a^2-x^2)^{n-1}}+\left(\frac{2n-3}{2a^2(n-1)}\right)I_{n-1}$$
I managed to do it using a trigonometric substitution:
$$\int\frac{dx}{(a^2-x^2)^n}\space\begin{vmatrix}x=a\sin(\theta)\\dx=a\cos(\theta)d\theta\end{vmatrix}=\int\frac{a\cos(\theta)}{(a^2- a^2\sin^2(\theta))^n}d\theta=\int\frac{a\cos(\theta)}{a^{2n}\cos^{2n}(\theta)}d\theta\\=\frac{1}{a^{2n-1}}\int\sec^{2n-1}(\theta)d\theta$$
Using the reduction formula
$$\int\sec^n(\theta)d\theta=\frac{1}{n-1}\sec^{n-2}(\theta)\tan(\theta)+\left(\frac{n-2}{n-1}\right)\int\sec^{n-2}(\theta)d\theta$$
this integral becomes
$$\frac{1}{a^{2n-1}}\left[\frac{1}{2(n-1)}\sec^{2n-3}(\theta)\tan(\theta)+\left(\frac{2n-3}{2(n-1)}\right)\int\sec^{2n-3}(\theta)d\theta\right]$$
Based on the substitution $x=a\sin(\theta)$ and $dx=a\cos(\theta)d\theta$:
$$\sec(\theta)=\frac{a}{\sqrt{a^2-x^2}}\quad\tan(\theta)=\frac{x}{\sqrt{a^2-x^2}}\quad d\theta=\frac{dx}{\sqrt{a^2-x^2}}$$
So
$$\int\frac{dx}{(a^2-x^2)^n}=\frac{1}{a^{2n-1}}\left[\frac{1}{2(n-1)}\sec^{2n-3}(\theta)\tan(\theta)+\left(\frac{2n-3}{2(n-1)}\right)\int\sec^{2n-3}(\theta)d\theta\right]\\=\frac{1}{a^{2n-1}}\bigg[\frac{1}{2(n-1)}\bigg(\frac{a}{\sqrt{a^2-x^2}}\bigg)^{2n-3}\bigg(\frac{x}{\sqrt{a^2-x^2}}\bigg)+\left(\frac{2n-3}{2(n-1)}\right)\int\bigg(\frac{a}{\sqrt{a^2-x^2}}\bigg)^{2n-3}\bigg(\frac{dx}{\sqrt{a^2-x^2}}\bigg)\bigg]\\=\frac{1}{a^{2n-1}}\bigg[\frac{a^{2n-3}x}{2(n-1)(\sqrt{a^2-x^2})^{2n-2}}+\left(\frac{2n-3}{2(n-1)}\right)\int\frac{a^{2n-3}}{(\sqrt{a^2-x^2})^{2n-2}}dx\bigg]\\=\frac{1}{a^{2n-1}}\left[\frac{a^{2n-3}x}{2(n-1)(a^2-x^2)^{n-1}}+\left(\frac{2n-3}{2(n-1)}\right)\int\frac{a^{2n-3}}{(a^2-x^2)^{n-1}}dx\right]\\=\frac{x}{2a^2(n-1)(a^2-x^2)^{n-1}}+\left(\frac{2n-3}{2a^2(n-1)}\right)\int\frac{dx}{(a^2-x^2)^{n-1}}\\=\frac{x}{2a^2(n-1)(a^2-x^2)^{n-1}}+\left(\frac{2n-3}{2a^2(n-1)}\right)I_{n-1}$$
However I also wanted to prove this using integration by parts but I seem to be stuck:
$$\int\frac{dx}{(a^2-x^2)^n}=\int\frac{x}{x(a^2-x^2)^n}dx\space\begin{vmatrix}u=\frac{1}{x}\\du=-\frac{1}{x^2}dx\end{vmatrix}dv=\frac{x}{(a^2-x^2)^n}dx\\v=\int\frac{x}{(a^2-x^2)^n}dx\begin{vmatrix}u=a^2-x^2\\du=-2xdx\end{vmatrix}v=-\frac{1}{2}\int\frac{du}{u^n}=-\frac{1}{2}\left(\frac{u^{-n+1}}{-n+1}\right)\\=-\frac{1}{2(1-n)u^{n-1}}=-\frac{1}{2(1-n)(a^2-x^2)^{n-1}}\\\int udv=uv-\int vdu\\\int\frac{dx}{(a^2-x^2)^n}=-\frac{1}{2x(1-n)(a^2-x^2)^{n-1}}-\frac{1}{2(n-1)}\int\frac{1}{x^2(a^2-x^2)^{n-1}}dx$$
Don't know how to proceed from here, any help?
Comment: Related : https://math.stackexchange.com/questions/2998151/prove-the-reduction-formula-i-n-frac1n-cosn-1x-sinx-fracn-1  and https://math.stackexchange.com/questions/2964330/reduction-formula-for-integral-int-1-a2x2n-dx
Answer: Differentiation helps us to reduce calculation
$$\dfrac{d\{x(a^2-x^2)^n\}}{dx}a$$
$$=(a^2-x^2)^n-2nx^2(a^2-x^2)^{n-1}=(a^2-x^2)^n+2n(a^2-x^2-a^2)(a^2-x^2)^{n-1}$$
$$\implies\dfrac{d\{x(a^2-x^2)^n\}}{dx}=(1+2n)(a^2-x^2)^n-2na^2(a^2-x^2)^{n-1}$$
Integrating both sides, $$x(a^2-x^2)^n=(2n+1)I_n-2na^2I_{n-1}$$
Set $n=-m$
Answer: $$I_n=\int\frac{dx}{(ax^2+b)^n}$$
$$dv=dx\Rightarrow v=x\\ u=\frac1{(ax^2+b)^n}\Rightarrow du=\frac{-2anx}{(ax^2+b)^{n+1}}dx$$
$$I_n=\frac{x}{(ax^2+b)^n}+2n\int\frac{ax^2}{(ax^2+b)^{n+1}}dx$$
$$I_n=\frac{x}{(ax^2+b)^n}+2n\int\frac{ax^2+b}{(ax^2+b)^{n+1}}dx-2bn\int\frac{dx}{(ax^2+b)^{n+1}}$$
$$I_n=\frac{x}{(ax^2+b)^n}+2n\int\frac{dx}{(ax^2+b)^{n}}-2bnI_{n+1}$$
$$I_n=\frac{x}{(ax^2+b)^n}+2nI_n-2bnI_{n+1}$$
$$2bnI_{n+1}=\frac{x}{(ax^2+b)^n}+(2n-1)I_n$$
$$I_{n+1}=\frac{x}{2bn(ax^2+b)^n}+\frac{2n-1}{2bn}I_n$$
replacing $n+1$ with $n$,
$$I_{n}=\frac{x}{2b(n-1)(ax^2+b)^{n-1}}+\frac{2n-3}{2b(n-1)}I_{n-1}$$
For your integral, set $a=-1$ and replace $b$ with $b^2$
Comment: But is it possible to do it through an independent IBP process, an not from a different reduction formula?
Comment: @AnsonPang yes, but the process would be exactly the same.
Comment: Oh, I see, thanks.
Answer: Integrate by parts as follows
\begin{align}\int\frac{dx}{(a^2-x^2)^n}
= I_n&=\int\frac1{2a^2(n-1)x^{2n-3}}\ d\bigg[\left(\frac{x^2}{a^2-x^2}\right)^{n-1}\bigg]\\
&=\frac x{2a^2(n-1)(a^2-x^2)^{n-1}}+\frac{2n-3}{2a^2(n-1)}I_{n-1}
\end{align}


ShinyApp : Connection Reset By Peer

Question: The shinyapp I built earlier was running fine in my old laptop. Recently I got a new laptop with Windows10. After setting up everything, I tried to run the app but it the browser opens and closes immediately with the error :
Listening on http://127.0.0.1:5004
ERROR: [on_request_read] connection reset by peer
I have also set chrome as default browser....
I deployed this app in shinyapps.io it is working fine there.
I tried few more simple apps in Rstudio but the same issue coming. Looks like the issue is more related to some setting in Windows10. Can someone help me please.
Thanks in Advance.....
Answer: Without details on the specific code, I'd share my personal experience with the same error for your reference. In my case, I used RStudio to create a shiny app that save data to a local directory on my computer, while I told R to output files to directory "response", I hadn't created such directory under the working directory so came the error. Simply creating the sub directory named "response" solve this right away. Or for moving your project files to different places in the future, you can just check whether the folder exists, if not, create one shall save you a lot of time.

ShinyApp : Connection Reset By Peer


Java DSL for dynamic logic

Question: We have Groovy DSL using which we could store the logic to be executed in DB and execute the same groovy script in Java.
Is is possible with Java also?  I am using Java 11.
The requirement is to read JSON input and update the value for the given field. The field and the logic should be dynamic.
Comment: Did you mean without using a library? Or a [3rd party library](http://camel.apache.org/java-dsl.html) works? Note - This is off-topic for SO.
Comment: I prefer without a library. The requirement is to have N number of logic to be executed.
Answer: The question seems to be too "broad" and theoretical to some extent
If I understand it correctly, you're asking whether its possible to create a DSL in Java...
If so, the answer is Yes.
Whether it will have the same level of expressiveness as you can have in Groovy? No...
Java from the language syntax standpoint is a pretty outdated language, that's basically a first reason why have "newer" languages like Scala Groovy and recently Kotlin have emerged on top of JVM.
Having syntactical constructions for writing concise and expressive DSLs is something that Java offers in a very limited manner whereas more modern languages have more constructions up their sleeves.
That's possibly the reason why maintainers of DSL usually chose Groovy / Kotlin as a DSL language and not Java.
Examples:

Gradle - which is basically a groovy based DSL for building the project (recently it got a kotlin support too)
Jenkins pipelines - a Groovy DSL for running CI on the projects

Having said that, it's not true that there its totally impossible to build DSLs with Java only with APIs.
Here are the examples:
Mockito has a DSL for specifying expectations for tests. Example:
when(foo.bar(a,b,c)).thenReturn(d);

Another example of a (fairly successful IMO) attempt to create a DSL  is JOOQ
This library provides a very nice DSL for working with Relational Databases.
Here is an example of how does the DSL built with Jooq looks like (Java, not Groovy):
jooqContext
    .select()
    .from(MY_TABLE)
    .fetch()

So, you can borrow ideas of how DSLs can look like in these languages compare and decide for yourself.

Java DSL for dynamic logic


null object reference

Question:            Logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean)' on a null object reference

Código do adaptador
@Override
public View getView(int i, View convertView, ViewGroup parent) {
    View vista = convertView;

    if(vista==null)
        vista = inflater.inflate(R.layout.elemento_lista, parent, false);

    TextView titulo = (TextView) vista.findViewById(R.id.tvTitulo);
    TextView duracion = (TextView) vista.findViewById(R.id.tvDuracion);
    TextView director = (TextView) vista.findViewById(R.id.tvDirector);

    ImageView imagen = (ImageView) vista.findViewById(R.id.ivImagen);
    RatingBar calificacion = (RatingBar) vista.findViewById(R.id.ratingBarPel);

    titulo.setText(datos[i][0]);
    director.setText(datos[i][1]);
    duracion.setText("Duração " + datos[i][2]);
    imagen.setImageResource(datosImg[i]);
    calificacion.setProgress(Integer.valueOf(datos[i][3]));

    return vista;
}

Answer: Tem que instanciar o inflater. Tente encaixar essa linha no começo do método getView():
inflater = activity.getLayoutInflater();

Precisará arranjar um substituto para a variável activity que traga efetivamente a Activity, talvez passando como argumento no construtor do seu adaptador. Infelizmente não lembro direito como se faz isso em Android. Boa sorte.

null object reference


JFrame background not changing

Question: I've got a simple program to change the background of a JFrame and the foreground of a JLabel.  The JFrame has a JLabel and 2 JButtons on it, one to change the words and the other to change the background.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class ColorChooserDemo extends JPanel {

static JFrame frame;
JLabel label;
JButton button1, button2;

public ColorChooserDemo() {
    this.setBackground(new Color(255, 0, 255));
    setLayout(null);

    label = new JLabel("This is Text");
    button1 = new JButton("Set Word Color");
    button2 = new JButton("Set Background Color");

    add(label);
    add(button1);
    add(button2);

    label.setBounds(130, 10, 111, 15);
    button1.setBounds(100, 40, 200, 35);
    button2.setBounds(70, 90, 250, 35);

    button1.addActionListener(buttonPressed);
    button2.addActionListener(buttonPressed);
    button1.setActionCommand("words");
    button2.setActionCommand("back");

    label.setFont(new Font("Helvetica", Font.BOLD, 20));
    button1.setFont(new Font("Helvetica", Font.BOLD, 20));
    button2.setFont(new Font("Helvetica", Font.BOLD, 20));
}

AbstractAction buttonPressed = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("words")) {
            Color c = JColorChooser.showDialog(null, "Choose a Color", label.getForeground());
            if (c != null)
                label.setForeground(c);
        }
        if (e.getActionCommand().equals("back")) {
            Color c = JColorChooser.showDialog(null, "Choose a Color", label.getForeground());
            if (c != null)
                frame.getContentPane().setBackground(c);
        }
        repaint();
    }
};

public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    frame = new JFrame("ColorChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new ColorChooserDemo());
    frame.setSize(400, 200);
    frame.setLocation((int) (screenSize.getWidth() - 400) / 2, (int) (screenSize.getHeight() - 200) / 2);
    frame.setResizable(false);
    frame.setVisible(true);
}

}
For whatever reasonframe.getContentPane().setBackground(c); doesn't work.
I've looked for solutions but nothing is working and I don't understand why.  Please help.
--EDIT--
I tried repaint(); and it still doesn't work.  Could it have to do with frame being static?
Comment: There are lots of reasons this might not work, but without a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) it would all be vauge guess work on our part
Comment: @Knox From memory, `setBackground` is a bound method, meaning it generates it's own `repaint` call
Comment: The label color does change, but not the JFrame?
Comment: Try repainting the content pane after changing colors with repaint()
Comment: @MadProgrammer I added the rest of the code.  I thought about putting the whole thing up originally, but I figured you might be able to help just from the snippet.
Answer: This is a good example of where something like static can stab you in the back...
So, in your code, you are doing...
frame.getContentPane().setBackground(c);

when you want to change the background color, but you have to ask yourself the question, what is the contentPane?  Since your component extends from JPanel (which is opaque) and sets it's own background color (this.setBackground(new Color(255, 0, 255));) (and because by default JFrame uses a BorderLayout) you component is covering the entire content area of the frame, so any calls to frame.getContentPane().setBackground(c) are simply not visible (because your panel is covering it).
Instead, you should simple use...
setBackground(c);

For clarification...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ColorChooserDemo extends JPanel {

    JLabel label;
    JButton button1, button2;

    public ColorChooserDemo() {
        this.setBackground(new Color(255, 0, 255));
        setLayout(new GridBagLayout());

        label = new JLabel("This is Text");
        button1 = new JButton("Set Word Color");
        button2 = new JButton("Set Background Color");

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        add(label, gbc);
        add(button1, gbc);
        add(button2, gbc);

        button1.addActionListener(buttonPressed);
        button2.addActionListener(buttonPressed);
        button1.setActionCommand("words");
        button2.setActionCommand("back");

        label.setFont(new Font("Helvetica", Font.BOLD, 20));
        button1.setFont(new Font("Helvetica", Font.BOLD, 20));
        button2.setFont(new Font("Helvetica", Font.BOLD, 20));
    }

    AbstractAction buttonPressed = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("words")) {
                Color c = JColorChooser.showDialog(null, "Choose a Color", label.getForeground());
                if (c != null) {
                    label.setForeground(c);
                }
            }
            if (e.getActionCommand().equals("back")) {
                System.out.println("...");
                Color c = JColorChooser.showDialog(null, "Choose a Color", getBackground());
                if (c != null) {
                    setBackground(c);
                }
            }
            repaint();
        }
    };

    public static void main(String[] args) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        JFrame frame = new JFrame("ColorChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ColorChooserDemo());
        frame.setSize(400, 200);
        frame.setLocation((int) (screenSize.getWidth() - 400) / 2, (int) (screenSize.getHeight() - 200) / 2);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

I would also strongly suggest you have a look at Laying Out Components Within a Container, How to Use GridBagLayout and How to Use BorderLayout for more details about how the layou management API works

JFrame background not changing


How to return large text in ORDS using JSON (more than 32k)

Question: I'm creating a Rest API in Oracle ORDS, and I need to return a base64 text that is larger than 32k. The Source Type is PL/SQL.
Original data is in a CLOB variable, but ORDS doesn't support this kind of return. I tried to use LONG, but I can't move the string to LONG when it's larger than 32k.

I tried to move the content from the CLOB to the LONG, but no success.
I tried to create two Long variables with the text I need, and concatenate it to the Long variable to output it, but no success as well.
I was able to return the content inside a ResultSet, but it will make the Json structure different from what I need.

<code>--This is the variable that has the large text (about 40k characters)
out_hexa        CLOB;
</code>
-- :boleto is the OUT parameter in ORDS (OUT, RESPONSE, LONG)
<code>--This wont work:
:boleto := out_hexa;
</code>
<code>--This wont work:
:boleto := substr(out_hexa, 1, 32765) || substr(out_hexa, 32765, LENGTH(out_hexa));
</code>
--This works, but the Json output is not the way I wanted, since it creates a second level in Json
Importante: In this case, :boleto is a ResultSet, and not a Long
<code>OPEN :boleto FOR
     SELECT out_hexa as dados from dual;
In this case the output is:
{
    "boleto": [
        {
            "dados": "JVBERi0xLjQKMSAwIG9iago8PAovVGl0bGUgKP7..."
        }
     ]
}

What I need is a Json in this format:
{
    "boleto": "JVBERi0xLjQKMSAwIG9iago8PAovVGl0bGUgKP7..."
}
</code>
Comment: Yeah, that's the way... I'm writing the Json myself and its working. Thanks!
Comment: ords DOES support a LOB returned, set your Source Type to media resource and your mime type to application/base64 - something like this https://www.thatjeffsmith.com/archive/2017/09/ords-returning-raw-json/
Comment: Hi there, ok, but in this case, I need to return an 'application/json' mime type, and the content of one field will be the base64 string.... any idea? thanks!
Comment: generate the json yourself
Answer: Couldn't find a way to do it automatically, so I'm writing the Json myself.
I'm reading the CLOB in chunks and writing it using HTP.prn:
<code>      OWA_UTIL.mime_header('application/json', FALSE);
      OWA_UTIL.http_header_close;
      htp.prn('{');
      htp.prn('"return_code" : "' ||out_status || '",');
      htp.prn('"return_message" : "' ||out_msg_retorno || '",');
      htp.prn('"boleto" : "');

      IF(out_status = '001') THEN
        :http_status      := 200;
        WHILE counter < length(out_hexa)+chunk_size LOOP
            htp.prn(substr(out_hexa, counter, chunk_size));
            counter := counter+chunk_size;
        END LOOP;
      ELSE
        :http_status      := 404;
      END IF;
      htp.prn('"}');
</code>
Answer: You can use this
APEX_UTIL.PRN (
p_clob   IN CLOB,
p_escape IN BOOLEAN DEFAULT TRUE );


Checking if NSMutableArray contains String

Question: I'm using the below code to check if a user's last name exists inside of my NSMutableArray (self.friendData). That said, even though the user last name exists inside of the self.friendData in the field "last name", it's still returning the else portion of the statement (stating it doesn't exist in the array). How can I fix this?
ViewController.m
 NSMutableDictionary *viewParams2 = [NSMutableDictionary new];
    [viewParams2 setValue:@"friends" forKey:@"view_name"];
    [DIOSView viewGet:viewParams2 success:^(AFHTTPRequestOperation *operation, id responseObject2) {

        self.friendData = (NSMutableArray *)responseObject2;

        NSString *myFriend = [self.neighbourDetail objectForKey:@"last name"];

        if ([self.friendData containsObject:myFriend]) {

            NSLog(@"It contains %@!", myFriend);
            self.addFriend.hidden = YES;

        } else {
            NSLog(@"It does not contain %@", myFriend);
            self.addFriend.hidden = NO;
        }

        [operation responseString];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", [error localizedDescription]);
    }];

self.friendData contents:
 "field_friendbio" =         {
            und =             (
                                {
                    format = "<null>";
                    "safe_value" = "There is currently no bio available for this user.";
                    value = "There is currently no bio available for this user.";
                }
            );
        };
        "field_lastname" =         {
            und =             (
                                {
                    format = "<null>";
                    "safe_value" = Niyo;
                    value = Niyo;
                }
            );
        };

Answer: Unless friendData is an array of strings, I think what you really meant is this:
if ([self.friendData containsObject:self.neighbourDetail])

EDIT:
NSMutableArray *searchResults = [[NSMutableArray alloc] init];

[self.friendData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    NSDictionary *friend = obj;

    if ([friend[@"field_lastname"][@"und"][@"value "] isEqualToString:myFriend])
        [searchResults addObject:friend];
}];

NSLog(@"Search Results:%@", searchResults);

Comment: See above edit (contents of self.friendData). I want to search friendData specifically for the last name pulled from neighbourData. That said, replacing myFriend with self.neighbourDetail still doesn't work :/
Comment: see my update, it needs to be the same data structure for `containsObject` I added the alternative solution,
Comment: I'm confused - search results is still empty when I use this code? Even if friend[@"last name"] is Equal to myFriend.
Comment: is `friendData` an array of dictionaries or models, in your edit I see `"field_lastname"` so the key need to match
Comment: Yes, friendData is an array of dictionaries. In that case, what should the above look like?
Comment: @Brittany according to what you posted the above should look like `friend[@"field_lastname"][@"und"][@"value "]`
Comment: I've changed that line to: if ([friend[@"field_lastname"][@"und"][@"value"] isEqualToString:myFriend]) , and the app crashes with the following error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleObjectArrayI objectForKeyedSubscript:]: unrecognized selector sent to instance 0x17461b3f0'
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/132658/discussion-between-meda-and-brittany).


Palavra chave "use" no php

Question: Estava utilizando uma api quando eu me deparo com o seguinte código:
$push->on('incoming', function (\InstagramAPI\Push\Notification $push) use ($ig, $socket) {
    ...
});

Eu percebi que a palavra "use" serve para utilizar determinada variável dentro do escopo daquela função interna, mas foi apenas uma conclusão que tirei, o que eu queria saber é, se é simplesmente isso e ponto final ou se há algo a mais.
Quando eu pesquiso por 'use' em php só aparece sobre o 'use' para importar classes, como por exemplo:
use React\EventLoop\Timer\TimerInterface;

O mais proximo que cheguei da resposta foi isso:

use doesn't include anything. It just imports the specified namespace
  (or class) to the current scope

Fonte: https://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it
Mas fala apenas sobre classes e namespace nada sobre variaveis, queria saber mais sobre esta palavra 'use', pois estou com algumas dificuldades para utilizar esta api e ela utiliza bastante deste recurso e não quero esta fazendo algo errado por não saber utilizar o recurso.
Comment: Acho que a resposta dessa [pergunta](https://pt.stackoverflow.com/questions/172133/qual-%C3%A9-a-finalidade-do-comando-use-e-qual-%C3%A9-a-sua-rela%C3%A7%C3%A3o-com-fun%C3%A7%C3%B5es-anonimas) pode esclarecer sua dúvida.
Comment: Também pode ajudar: https://pt.stackoverflow.com/q/32467/101
Comment: Como você pode ver nos links que indicaram acima, existem dois tipos de `use` no php. Um é para importar namespaces, e outro para capturar variáveis de outro escopo (uma implementação de closures). O seu exemplo é desse segundo tipo.
Comment: Então é isso, o 'use' neste caso vai deixar acessível a variável.
Comment: A mensagem *use doesn't include anything. It just imports the specified namespace (or class) to the current scope* creio que foi respondida em https://pt.stackoverflow.com/questions/151487/namespaces-e-use-quando-usar-e-para-que-servem/151492#151492
Answer: Use para escopo em função anônimas
Estamos usando aqui uma função anônima
$push->on('incoming', function (\InstagramAPI\Push\Notification $push) use ($ig, $socket) {
    ...
});

Quando utilizamos a palavras "use" em um função anônima como no exemplo acima, a variável passa para o escopo da função anônima, porem não como referencia, caso necessário passar como referencia basta fazer como o exemplo abaixo
$push->on('incoming', function (\InstagramAPI\Push\Notification &$push) use ($ig, $socket) {
    ...
});

Assim qualquer alteração na variável "$push" será refletida externamente.
Use em Namespace
use React\EventLoop\Timer\TimerInterface;

Quando utilizamos o "use" como namespace, informamos de onde ele pertence, como no exemplo acima, TimerInterface esta dentro de Timer que por sua vez esta dentro de EventLoop e por fim dentro de React.
E para que isso server? Imagine que exista um outro "TimerInterface", mas ele vai pertencer a outro lugar por exemplo
use LugarMagico\TimerInterface;

Porem se utilizamos os dois TimerInterface no mesmo lugar desta forma
use React\EventLoop\Timer\TimerInterface;
use LugarMagico\TimerInterface;

$timer = new TimerInterface();

Não será possível já que como que o php saberá qual TimerInterface é o que estou chamando, e para resolver isso é simples basta fazer o seguinte
use React\EventLoop\Timer\TimerInterface;
use LugarMagico\TimerInterface as TimerMagico;

$timer = new TimerInterface();
$timerMagico= new TimerMagico();

Desta forma eu atribuo um apelido, assim o php saberá qual estou chamando
fontes
Melhorei a minha resposta graças ao Guilherme Nascimento, respondi de acordo com a minha interpretação, porem o Guilherme respondeu com maestria nos seguintes links abaixo.
Namespaces e Use quando usar e para que servem?
Qual é a finalidade do comando "use" e qual é a sua relação com funções anonimas?
Comment: Caro Wictor o `use` com namespaces não tem nada haver com escopo. O use em classes é totalmente diferente do use em Closures ... O `use`em classes não faz "nada", mesmo com spl, no PHP ele serve somente para criar apelidos, como expliquei em https://pt.stackoverflow.com/questions/151487/namespaces-e-use-quando-usar-e-para-que-servem/151492#151492 ... E sobre o use em closures, expliquei aqui: https://pt.stackoverflow.com/a/172134/3635 .. Espero que ajude.
Comment: Obrigado, @GuilhermeNascimento, editei a pergunta :)

Palavra chave "use" no php


How to use NSUndoManager on macOS 10.12?

Question: I read in the documentation that NSManagedObjectContext now defaults to a nil NSUndoManager on macOS. How can I set NSUndoManager?
Answer: Create an undo manager and assign it to the managed object context.
<code>NSUndoManager *undoManager = [[NSUndoManager alloc] init];
managedObjectContext.undoManager = undoManager;
</code>


How to allow unsafe code in JetBrains Rider?

Question: I want to allow unsafe code in JetBrains Rider 2020.2.4 for linux. I have looked at this question, but the instructions do not seem to apply to this version of the application. How can I allow unsafe code in JetBrains Rider and get rid of the <code>'unsafe' context is redundant</code> message?
Answer: Solution Explorer -> Select your project -> Properties... (alt+enter) -> Select appropriate configuration in "Configurations" section -> Set "Allow unsafe code".


How does scikit-learn perform $\chi^2$ feature selection on non-categorical features?

Question: I'm experimenting with $\chi^2$ feature selection for some text classification tasks. I understand that $\chi^2$ test checks the dependencies B/T two categorical variables, so if we perform $\chi^2$ feature selection for a binary text classification problem with binary BOW vector representation, each $\chi^2$ test on each (feature, class) pair would be a very straightforward $\chi^2$ test with 1 degree of freedom.
Quoting from the documentation: http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.chi2.html#sklearn.feature_selection.chi2,

This score can be used to select the n_features features with the
  highest values for the χ² (chi-square) statistic from X, which must
  contain booleans or frequencies (e.g., term counts in document
  classification), relative to the classes.

It seems to me that we we can also perform $\chi^2$ feature selection on DF (word counts) vector presentation.
My 1st question is: How does sklearn discretize the integer-valued feature into categorical?
My second question is similar to the first. From the demo codes here: http://scikit-learn.sourceforge.net/dev/auto_examples/document_classification_20newsgroups.html
It seems to me that we can also perform $\chi^2$ feature selection on a TF*IDF vector representation.
My 2nd question is: How does sklearn perform $\chi^2$ feature selection on real-valued features?
Comment: I have no experience with scikit-learn, hence just a hint on the base of rapidminer-experience: 1. Integer values can be treated as categorical or real-valued. 2. Chi2-Feature-Selection on real-valued features most likely requires a discretization beforehand, hence if the integer is treated as real-valued, a discretization is also performed here. I suggest to look into the source code.
Comment: Thank you @steffen for your suggestion. This has been answered by one of the developers of sklearn here: http://stackoverflow.com/questions/14573030/perform-chi-2-feature-selection-on-tf-and-tfidf-vectors. It becomes quite clear if one thinks of the NULL hypothesis as "document class has no influence over feature frequency".
Answer: Found the answer here: https://stackoverflow.com/questions/14573030/perform-chi-2-feature-selection-on-tf-and-tfidf-vectors
Think of the NULL hypothesis as "document class has no influence over feature frequency".


Is it possible to transform the heat equation in cylindrical coordinates to a Cartesian-like form using a variable substitution?

Question: Consider the heat equation in spherical coordinates (considering only variation in the radial direction):
$$\frac{\partial\phi}{\partial t} = \frac{\alpha}{r^2} \frac{\partial}{\partial r}\left(r^2 \frac{\partial\phi}{\partial r}\right).$$
Using the following variable substitution,
$$\theta = r\phi$$
it is possible to convert this equation into a "Cartesian-like" form:
$$\frac{\partial\theta}{\partial t} = \alpha\frac{\partial^2\theta}{\partial r^2}.$$
My question is:
Is it possible to begin with the heat equation in cylindrical coordinates (again only considering variation in the radial direction),
$$\frac{\partial\phi}{\partial t} = \frac{\alpha}{r} \frac{\partial}{\partial r}\left(r \frac{\partial\phi}{\partial r}\right)$$
and, using a similar variable substitution, achieve this same "Cartesian-like" end form?  If it is possible, what transformation achieves this?
Answer: Use the substitution $z = r\phi$. We have $\frac{\partial \phi}{\partial r} = \frac{-z}{r^2}$ and $\frac{\partial^2 \phi}{\partial r^2} = \frac{z}{r^3}$. Then:
$$\frac{\partial \phi}{\partial t} = \frac{\alpha}{r} \frac{\partial}{\partial r} \left[r \cdot \left(\frac{-z}{r^2}\right)\right] = \frac{\alpha}{r} \cdot \frac{z}{r^2} = \alpha \cdot \frac{z}{r^3} = \alpha \frac{\partial^2 \phi}{\partial r^2}.$$
Comment: $$\frac{\partial \theta}{\partial t} = \frac{1}{r}\left(r\frac{\partial^2 \theta}{\partial r^2} + \frac{\partial \theta}{\partial r} - \frac{\partial \theta}{\partial r}\right)$$

$$\frac{\partial \theta}{\partial t} = \frac{\partial^2 \theta}{\partial r^2}$$

After some more research about my original question, I now believe that there is no known substitution to reduce the cylindrical equation to the desired form.  If there were such a substitution, there might be no need for Bessel functions to exist...
Comment: I don't think this is correct.  Since 'z' is a function of 'r', you would need to apply the product rule when evaluating any derivative containing a product or quotient of those variables.  For example,

$$\frac{\partial\phi}{\partial r} = \frac{\partial}{\partial r}\left(\frac{z}{r}\right) = \frac{1}{r}\frac{\partial z}{\partial r} - \frac{z}{r^2}.$$

If you continue with the example, the PDE will not be reduced to the desired form.
Comment: Thank you for kindly pointing out my mistake. Can I ask how you arrived at the "Cartesian-like" form of the PDE from the spherical coordinates form?
Comment: Take the (radial part of) the heat equation

$$\frac{\partial \phi}{\partial t} = \frac{1}{r^2}\frac{\partial}{\partial r}\left(r^2\frac{\partial \phi}{\partial r}\right)$$

and apply the substitution: $\theta = r \phi$.

The derivatives of phi with respect to time and position, considering the substitution, are:

$$\frac{\partial \theta}{\partial t} = \frac{\partial}{\partial t}\left(\frac{\theta}{r}\right) = \frac{1}{r}\frac{\partial \theta}{\partial t}$$

Continued in next comment...
Comment: $$\frac{\partial \phi}{\partial r} = \frac{\partial}{\partial r}\left(\frac{\theta}{r}\right) = \frac{1}{r}\frac{\partial \theta}{\partial r} - \frac{\theta}{r^2}$$

Substitute these derivatives into the original PDE and simplify:

$$\frac{1}{r}\frac{\partial \theta}{\partial t} = \frac{1}{r^2}\frac{\partial}{\partial r}\left(r^2\left(\frac{1}{r}\frac{\partial \theta}{\partial r} - \frac{\theta}{r^2}\right)\right)$$

$$\frac{\partial \theta}{\partial t} = \frac{1}{r}\frac{\partial}{\partial r}\left(r\frac{\partial \theta}{\partial r} - \theta\right)$$

Continued in next comment...


Is it possible to have nested divs in content fields on a view?

Question: I'm trying to create a view that displays certain content fields inside a div that are contained by other content fields.
For example. I am displaying an image, a title, a body, and a posted date.
I'd like to do something like this

      Title

         1/1/1999

         body text

Is this possible?
Answer: Just exclude from display all your fields.

Then, at the end, create a Global text area, where you can use tokens from your excluded fields.
Answer: exclude all the fields from display except the last field and rewrite the output of that field to apply the structure you need using tokens of the previous field.


Disable Ordering Columns after initialization (init complete) in datatables

Question: I would disable order possibility to user after datatables is draw.
I have a datatable, and I would order a data and remove possibility, for an user, to order data manually.
How can I do it?
I used below code:
table = $('#tbl-1').DataTable({
            "info": false,
            "searching": true,
            "paging": false,
            "iDisplayLength": 25,
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Tutti"]],
            "language": {"url": "include/it_IT.txt"},
            "order": [[1,"desc"]],
            //"ordering": false,
            //"orderFixed": {"pre": [ 1, "desc" ]},
             "fnInitComplete": function(oSettings, json) {
                    //alert( 'DataTables has finished its initialisation.' );
                    this.fnFilter("<?php echo $_POST['search'];?>");
                  },
            }).on('init.dt', function (e, settings, data) {
                wrappa(); //after custom function
            });

Comment: [http://www.datatables.net/forums/discussion/7377/disable-all-sorting-after-init](http://www.datatables.net/forums/discussion/7377/disable-all-sorting-after-init)
Comment: I just see it but dosen't work on my site
Comment: **Addressing some potential confusion**. If you're looking to disable auto-sorting of your (e.g. server-side sorted) table after datatables init, but keep the sorting functionality enabled for intentional use, [see here](https://stackoverflow.com/a/4964423). If you want to disable the sorting completely, see below for an answer.
Answer: old post but still not handled by dt api. Removing the events won't work if wanting to temporarily disable sorting. Instead use jquery to add and later remove a class onto each th, and in this class specify "pointer-events: none".
Answer: Due to the fact that the API does not have a way to do this, I would suggest the following approach
Declare your table at first
var table = $('#myTable').DataTable();

Re-Initialize your dataTable with to disable ordering
//Destroy your table before
table.destroy();
$('#myTable').dataTable( {
  "ordering": false
} );

reference:
https://datatables.net/reference/option/ordering
Comment: this isn't correct because i need to ordering first time, and only after ordering i must disable..
Comment: if you set `ordering : false` on the column OP wants to prevent the user to be able to sort on, he will loose his own ordering, eg `"order": [[1,"desc"]]`, as well.
Comment: This will disable the ordering completely


Countif/Sumif should show empty value instead of 0 in arrayformula

Question: I have a lot of arrayformulas wrapped around countif and sumifs functions. I want the countifs/sumifs to return an empty value ("") instead of 0.
My workaround is very expensive and long:
<code>=ARRAYFORMULA(IF(SUMIFS(Sheet!$C$1:$C; 'Sheet!$A$1:$A; ">="&$A3; Sheet!$A$1:$A; "<="&$B3)=0; ""; SUMIFS(Sheet!$C$1:$C; Sheet!$A$1:$A; ">="&$A3; Sheet!$A$1:$A; "<="&$B3)))
</code>
Here is an example sheet: https://docs.google.com/spreadsheets/d/1xyS0Y4gnG3zLyOGtycWytvTlA1NmqjEAy8H7QJatdSg/edit?usp=sharing
Is there a different way for this?
Comment: I have added an example
Answer: <code>=IFERROR(SUM(QUERY(Sheet2!A:C;
 "select C
  where month(A)+1="&MONTH(A3)&"
    and year(A)="&YEAR(A3); 0)))
</code>

<code>=IFERROR(SUM(FILTER(Sheet2!C:C;
 YEAR(Sheet2!A:A)=YEAR(A3); MONTH(Sheet2!A:A)=MONTH(A3))))
</code>


Unknown "formula"

Question: Hi I have problem with finding right "formula" (Is it what it is called) I am bad at maths so forgive me.
So problem is this. I can insert some number and then it calculates me answer with this "unknown formula". There are what I have. (Let's say that $F$ is "formula")
$$1F=1$$
$$2F=2$$
$$25F=25$$
$$600F=2825$$
$$1000F=4825$$
$$1100F=5325$$
$$1200F=5825$$
$$2500F=12325$$
$$5000F=24825$$
So I can't understand what logic or formula makes those numbers become those answers. If somebody can help or need more numbers, then I can provide them :I
Comment: @YuriyS: Not that OP is likely aware of this, but the notation "$xf$" to mean what you write as "$f(x)$" is not unheard of, especially in algebra. I don't care for that notation, but I would say this question is pretty good evidence that it is intuitively justified. For analysts, your notation is by far much more standard, and I admit I prefer it. Just saying...
Comment: Honestly it just looks like if $x < 35$ then $f(x) = x$, and if $x\geq35$, then $f(x) = 5x-175$. But this is assuming $f$ is supposed to be a function.
Comment: I think you are trying to define your $F$ as a **function** $F(x)$, then you should write (for example), $F(600)=2825$ - do I understand correctly what you mean?
Comment: To format math equations surround them with \$ symbols. For display format use \$$ on each side
Comment: Related: http://math.stackexchange.com/questions/1790642/general-formula-for-the-1-5-19-65-211-sequence
Comment: Sorry guys I am just bad in maths as english so wrong tags. But Jack seems be on right tracks. I just can't resolve this myself. :I
Answer: Your last six data points follow the formula
\begin{equation}
F(x)=5x-175
\end{equation}
This means multiply the first number times $5$ and subtract 175 to get the second number.
However your first three data points follow a different formula
\begin{equation}
F(x)=x
\end{equation}
A continuous answer would be
\begin{equation}
F(x)=\begin{cases}
      x \text{ for } x<25\\
      2x-25 \text{ for } 25\le x<50\\
      5x-175\text{ for } x\ge50
     \end{cases}
\end{equation}
Comment: ...then, pragmatically, $F(x) = \max(x, 5x-175)$?
Comment: Your additional values of $(34,43), (40,55)$ and $(50,75)$ follow a third rule of $F(x)=2x-25$ so there is more going on here than meets the eye. Where are you getting these numbers?
Comment: @Rellek    Your comment was not showing on my screen when I posted my answer. But I am curious where you got the $35$. Oh, nevermind, I see, $175\div5$.
Comment: Hi, your formula works with six last numbers, but when I use number 90 and 100 I got: 90 = 275 and 100 = 325
Comment: Look at @Joffan comment. That is the best answer.
Comment: Are 275 and 325 the wrong results for 90 and 100? Explain.
Comment: No they are right. I just didn't first understand... I think this is solved. Thank you all, you're just amazing! :)
Comment: I added an additional amount to my answer which gives a graph which is continuous.
Comment: @Reman, if you think your question is answered, you can click the checkmark at the top of this post to accept the answer. It will give reputation points to you and the person who answered you
Comment: Does it mean that numbers after 35 is not equal as base number eg. 34 is 34 but 36 is 36x5-175? Also do I must mark this solved, if must then how I can do it? :o
Comment: @ Yuriy S, Thanks I will mark it soon. Strangely though when I insert number 34 it becomes 43 and 36 becomes 47 so 34=43 and 36=47. And more... 25=25 and 26=27. Can there be some logic? :o
Comment: @ Yuriy S, I'm sorry! I mean same as before so $$40F=55$$  and $$ 50F=75$$
Comment: @Reman I corrected the value of $x$ where the two functions meet. It is $43.75$ not $35$.
Comment: Okay, here are some more values $$25F=25$$ $$26F=27$$ $$34F=43$$ $$36F=47$$ $$40F=55$$  and $$50F=75$$
Comment: I am messed up in "programming". I must find what value will become $200$ with following same formula with these other numbers. Formula is hidden in not accesable file and I try manipulate one value in code and build it to see result. :o
Comment: I modified my answer to incorporate the additional information which you provided.
Comment: Okay! After all calculations I can confirm this is solved! Many thanks for all of you!  @JohnWaylandBales, Indeed it gives so $$75x5-175=200$$
Comment: The number 75 should give you 200.

Unknown "formula"


Part of simple proof of nontrivial center in p-group

Question: I'm trying to understand the proof of a Burnside theorem (as stated in Beachy's Abstract Algebra p. 328): Let $p$ be prime number. The center of any $p$-group is nontrivial.
Now, In the proof they say that if we let $G$ be a $p$-group, then in the class equation $$|G| = |Z(G)|+\sum [G:C(x)]$$
for all $x$ that is not in the center and represent a conjugacy class, we see that every term in $\sum [G:C(x)]$ is divisible by $p$ since $x\not\in Z(G) \implies [G:C(x)]>1$. This last statement is what I do not understand, how do we know that $p \mid [G:C(x)]$ for any conjugacy class?
I know that the elements in the conjugacy class of $x$ is in bijection with the cosets of $C(x)$, i.e. $[G:C(x)]$, but how can we be certain that the number of elements in a conjugacy class of $x$/cosets of the centralizer of $x$ is divisible by $p$?
Best regards.
Answer: Hint: If $x$ is not in the center, then what contradiction would you get if $|G:C(x)|=1$.
Note: the values $|G:C(x)|$ can take are $1,p,p^2,...p^n$
Comment: The [index=number of cosets] of a subgroup is a divisor of the order of the whole group!
Comment: Oh my god, @NickyHekster , this is what I totally missed, it's like "you don't see the forest because of all the trees..". Of course $[G:C(x)]$ divides the group order, that is why the order must be some value of $1,p,p^2,...,p^n$.. Thanks!
Comment: Haha. "you don't see the forest because of all the trees.." You made me smile. :)
Comment: Hmm, since $C(x)$ is a subgroup, its order must divide $|G| = p^n$, thus it must be a power of $p^k$ where $k<n$. But how can you conclude that for any $x$ the number of cosets of its centralizer $[G:C(x)]$ also is a prime power?

If $x \not\in Z(x)$ and $[G:C(x)] = 1$ then this is false since by definition $ax = xa$ holds for $C(x)$ for some $a \implies a \in C(x)$ as well, so $[G:C(x)]$ must be at least 2?
Comment: $|G:C(x)|=|G|/|C(x)|=\frac{p^n}{p^k}$ where $k<n$ as you say.
Comment: @SwapnilTripathi : yes, I just realized that now, thanks a lot!
Comment: @Math83 - no problem, you learned something I guess!
Comment: @NickyHekster: Sorry, I thought it was the OP.
Answer: $|G|=p^k$ for some $k$ as it is a $p$ group, we are only talking about finite groups here, this statement may not hold for infinite groups.
Now as $C_G(x)<G$ therefore $|C(x)|$ divides $p^k \implies |C(x)|=p^i$ for some $0 \le i < k$, so, $|G:C(x)|=p^{k-i}$ and $k-i>0$ implies $p$ divides $|C(x)|$
Comment: Very underrated answer.
Answer: Let $P$ be the p-group, by class equation:
$|P| = |Z(P)| + \displaystyle\sum_{i=1}^r |P:C_P(g_i)|$
where $g_1, g_2, ..., g_r$ be representatives of distinct conjugacy classes of $P$ not contained in the center $Z(P)$.
Write the class equation above as:
$|P| = p^\alpha = a + b$ where $a = |Z(P)|$ and $b = \displaystyle\sum_{i=1}^r |P:C_P(g_i)|$.
By definition $C_P(g_i) \ne P$ for $i = 1, 2, ..., r$ so $|P:C_P(g_i)| = b \ne 1$. Because $b$ is the index of $C_P(g_i)$ in $P$, $b$ must be in the power of $p$, so $p$ divides $b$. Because $p$ obviously divides $p^\alpha$, and $p$ divides $b$, $p$ must also divide the remaining term $a$, so $a = |Z(P)|$ cannot equal $1$. Hence $Z(P)$ is not trivial.


How to interpret variance and correlation of random effects in a mixed-effects model?

Question: I hope you all don't mind this question, but I need help interpreting output for a linear mixed effects model output I've been trying to learn to do in R. I am new to longitudinal data analysis and linear mixed effects regression. I have a model I fitted with weeks as the time predictor, and score on an employment course as my outcome. I modeled score with weeks (time) and several fixed effects, sex and race. My model includes random effects. I need help understanding what the variance and correlation means. The output is the following:
Random effects
Group   Name    Variance
EmpId intercept 680.236
weeks           13.562
Residual 774.256

The correlaton is .231.
I can interpret the correlation as there is a a positive relationship between weeks and score but I want to be able to say it in terms of "23% of ...".
I really appreciate the help.

Thanks "guest" and Macro for replying. Sorry, for not replying, I was out at a conference and I'm now catching up.
Here is the output and the context.
Here is the summary for the LMER model I ran.
>summary(LMER.EduA)
Linear mixed model fit by maximum likelihood
Formula: Score ~ Weeks + (1 + Weeks | EmpID)
   Data: emp.LMER4

  AIC     BIC   logLik   deviance   REMLdev
 1815     1834  -732.6     1693    1685

Random effects:
 Groups   Name       Variance Std.Dev. Corr
 EmpID   (Intercept)  680.236  26.08133
          Weeks         13.562 3.682662  0.231
 Residual             774.256  27.82546
Number of obs: 174, groups: EmpID, 18

Fixed effects:
            Estimate Std. Error  t value
(Intercept)  261.171      6.23     37.25
Weeks          11.151      1.780    6.93

Correlation of Fixed Effects:
     (Intr)
Days -0.101

I don't understand how to interpret the variance and residual for the random effects and explain it to someone else. I also don't know how to interpret the correlation, other than it is positive which indicates that those with higher intercepts have higher slopes and those with those with lower intercepts have lower slopes but I don't know how to explain the correlation in terms of 23% of . . . . (I don't know how to finish the sentence or even if it makes sense to do so). This is a different type analysis for us as we (me) are trying to move into longitudinal analyses.
Comment: Zeda, it would be helpful to see more of the R output here, including the output's summary of the fixed effects
Comment: One thing I can see is that the estimated intraclass correlation for EmpID is $\hat{\rho} = 680.236/(680.236+13.562+774.256)$. That is, the estimated correlation between two individuals in the same level of EmpID is $\hat{\rho}$. I agree with @guest that more output (and some context) would be helpful.
Comment: Zeda, I've converted your reply as an edit, and merged your two unregistered accounts. Please, register this one so that you can follow up and update your post yourself.
Answer: Your fitted model with lme() can be expressed as
$y_{ij} = \alpha_0 + \alpha_1 x_j + \delta_{0i} + \delta_{1i} x_j + \epsilon_{ij}$
where $y_{ij}$ is the score of $i$th employee at $x_j$ weeks, $\alpha_0$ and $\alpha_1$ are the fixed intercept and slope respectively, $\delta_{0i}$ and $\delta_{1i}$ are the random intercept and slope, and $\epsilon_{ij}$ is the residual. The assumptions for the random effects $\delta_{0i}$, $\delta_{1i}$ and residual $\epsilon_{ij}$ are
$(\delta_{0i}, \delta_{1i})^T \stackrel{d}{\sim} N((0, 0)^T, G)$ and $\epsilon_{ij} \stackrel{d}{\sim} N(0, \sigma^2)$,
where the variance-covariance structure $G$ is a 2 x 2 symmetric matrix of form
$$\begin{pmatrix}
g_1^2&g_{12}^2\\
g_{12}^2&g_2^2
\end{pmatrix}$$
You can get the variance matrix between random effects terms from VarCorr(LMER.EduA)$ID.
Your result basically says that
$\alpha_0$ = 261.171, $\alpha_1$ = 11.151,
$g_1^2$ = 680.236, $g_2^2$ = 13.562, and $\sigma^2$ = 774.256.
$g_{12}^2$ can be found in VarCorr(LMER.EduA) or calculated as $0.23\times \sqrt{g_1^2 g_2^2}$.
Specifically $g_1^2$ = 680.236 shows the variability of the intercept across employees, $g_2^2$ = 13.562 is the amount of variability in the slope across employees, and 0.231 indicates the positive correlation between intercept and slope (when an employee's intercept increases by one unit of standard deviation, that employee's slope would increase by 0.231 standard deviations).
Comment: How would this work if you many random effects?
Comment: Please check that recent edits didn't alter the meaning of your reply (Personally, I just fixed some $\LaTeX$ expressions).
Comment: @chl: I really appreciate you for structuring my response in such a nice format (I know nothing about LaTex). More importantly you corrected my sloppy response regarding the covariance part. Thanks again, chl!
Comment: Credits should go to @GGeco who provided details about the VC matrix; as I said, I only texified part of your reply (and +1).


Ajuda com COMBOBOX, Selecionar cidades de acordo com estado escolhido

Question: Estou programando uma aplicação em php e tenho todos os estados e cidades do Brasil no banco Mysql.

Na tabela Estados tenho: id, nome, uf.
Na tabela Cidades tenho: id, nome, id_estado.

Criei um select para os estados e gostaria que quando clicasse no option de um determinado estado, aparecesse as cidades desse estado no select das cidades.
Abaixo o codigo
<?php include_once "conexao.php"; ?>

    Estado:
    <select name="estado" id="estado">
    <?php
        $sql = "SELECT `id`,`nome`, `uf` FROM estado WHERE `pais` = 1 ORDER BY `nome`";
        $res = $mysqli->query($sql);
        while($r = $res->fetch_array()) {
           $r = array_map('utf8_encode', $r);
           $sigla = $r["uf"];
           $nome = $r["nome"];
           $id = $r["id"];

           echo "<option value='$id'> $nome </option>";
        }

     ?>

    </select>
  Cidade:
    <select name="cidade" id="cidade">
        <option value="">Cidade</option>
    </select>

Comment: Amigo coloque os códigos para ficar mais fácil para te ajudar!
Comment: Coloque os códigos que você já fez até agora
Comment: @Phelipe fiz até aí...
Comment: @hugocsl como o value no primeiro select corresponde ao id de cada estado, o que eu pensei em fazer era capturar o value do option selecionado, e colocar no where do sql que listaria as cidades no outro select. Porém não tenho a menor ideia de como fazer isso.
Answer: O mais aconselhável é fazer uma requisição ajax para uma página que retorna um JSON com os valores de id e o nome de cada cidade referente ao ID que enviamos. Caso use Jquery o código vai ser algo como:
$('#estado').change(function(){
    $('.sair').remove();
    $.ajax({
        method: 'post',
        data: {id: $('#estado').val()},
        url: 'listar-cidades.php',
        success: function(retorno){
            for(i = 0; i < retorno.length; i++) {
                $('#cidade').append('<option class="sair" value="'+retorno[i].id+'" >'+retorno[i].nome+'</option>')
            }
        }
    });
});

O que estamos fazendo nesse código JS é sempre que o campo com ID mudar seu estado ele vai mandar uma requisição ajax para a página listar-cidades.php com o id que o usuário selecionou. Esse código espera um JSON formatado da seguinte forma:
[{"id":"1","nome":"Brasília"},{"id":"2","nome":"Taguatinga"},{...}]

Agora basta construir o script php que retorna esses dados recuperando o id que enviamos.
Comment: Estou começando a programar agora, meus conhecimentos estão limitados a html, css e PHP... Esse tipo de dica ajuda bastante a ampliar meu campo de visão! Obrigado!!
Comment: Dê uma pesquisada então em Javascript e em requisições ajax. São tecnologias essenciais no desenvolvimento web. O Jquary nada mais é que um  framework javascript.
Answer: Você precisa popular de forma dinâmica o select das cidades. Para isso você pode usar Ajax com JavaScript puro ou jQuery.
Funciona da seguinte forma: ao selecionar um Estado, o script irá enviar para uma página PHP o código do Estado, e essa página irá fazer a requisição ao banco de dados de todas as cidades com o código do Estado recebido, em seguida retornar um HTML com as options que será inserida no select das cidades.
Vou dar um exemplo básico usando jQuery, que fica mais fácil, e você pode aplicar no seu código com tranquilidade:
Capturar o value do select dos Estados quando for selecionado e chamar o Ajax:
$("#estado").on("change", function(){
    var id_estado = $(this).val();
    $.ajax({
        url: 'cidades.php',
        data: { estado: id_estado }
        dataType: 'html',
        complete: function(result) {
            $("#cidade").html(result);
        }
    });
});

No Ajax acima, eu envio o id do Estado selecionado para uma página PHP chamada cidades.php (você pode usar o nome que quiser). Esta página cidades.php vai ficar responsável de retornar a lista de cidades do Estado selecionado. Essa página não deve conter outra coisa senão os códigos PHP e a construção das options que será inserida no select das cidades. Não é uma página comum, com  etc...
Página cidades.php:
Como dito, a única utilidade desta página é retornar as options para o select cidades.
O esquema desta página seria:
<?php
$estado = $_GET['estado']; // recebendo o id do Estado enviado pelo Ajax

if(isset($estado) && !empty($estado)){

    // FAZER A REQUISIÇÃO AO BANCO DE DADOS USANDO A VARIÁVEL
    // $estado PARA PEGAR APENAS AS CIDADES COM ESSE id

    // AQUI FAZER UM LOOP NOS RESULTADOS
    while(ENQUANTO HOUVER RESULTADO VINDO DO BANCO){

        echo "<option value='$ID_DA_CIDADE'>$NOME_DA_CIDADE</option>";

    }

}
?>

Para chamar as cidades no carregamento da página, pois o primeiro Estado no select já vem selecionado, você pode usar o jQuery abaixo, que dispara um trigger no select:
$(window).on("load", function(){
    $("#estado").trigger("change");
});

Não esqueça de carregar o jQuery na sua . Você pode usar este:

Então, o script jQuery completo ficaria:

Comment: Amigo, na minha máquina o ajax não está enviando o ID do estado pra página que retorna as cidades... Testei o mesmo código na máquina de um amigo e funcionou perfeitamente.. Tem ideia do que pode ser?
Comment: O Ajax soh funciona em servidor. Se tentar na maquina local nao dah certo.
Comment: @MichaelCampos Seria isso?
Answer: Já é antigo este post mas vou por uma solução simples somente com PHP que esta útil pra mim.
Não sei se teria como aplicar no código pra funcionar aqui mas enfim.
No banco tem estados e cidades.
No perfil do usuário tem estado e cidade salvo.
Aparece para edição na sua página. Ele querendo trocar de estado, inseri um onchange que seta o select como selecionado e exibe no select cidades as cidades do estado selecionado. Se ele salvar, update no banco, caso contrário nada mudará ao atualizar a página.
Tosco, simples mas funciona sem outra linguagem. Na minha cabeça, de java, só entra o alert rsrsrsr

<?php
/*****************************************/

if (isset($_POST['estado'])) {
    $estadoSelect = $_POST['estado'];
}else{
    $estadoSelect = $uf; // este $uf é o que esta salvo do usuário numa session ou variável qualquer em algum lugar
}
/*****************************************/
?>

        ESTADO
        <select class="form-control" onchange="this.form.submit()" name="estado">
            <?php
                $select = SELECT("*", "estados", "");
                foreach ($select as $dados) { ?>
                    <option value="<?php echo $dados['estados_uf']; ?>" <?php if($estadoSelect == $dados['estados_uf']){ echo "selected"; } ?>><?php echo $dados['estados_nome']; ?></option>
                <?php } ?>
        </select>

        CIDADE
        <select class="form-control" onchange="this.form.submit()" name="cidades">
            <?php
                $select = SELECT("*", "cidades", " WHERE cidade_uf = '$estadoSelect'");
                foreach ($select as $dados) { ?>
                    <option value="<?php echo $dados['cidade_nome']; ?>" <?php if($cidade == $dados['cidade_nome']){ echo "selected"; } ?>><?php echo $dados['cidade_nome']; ?></option>
                <?php } ?>
        </select>

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


AWS - Acesso remoto à instância

Question: Boas! Eu criei uma instancia Linux Amazon e uma Windows, segui todos os passos para gerar key, importar e alterá-la via PuTTY, abri a chave, pedi a conexão com o cuidado do ec2-user bla bla bla, porém em nenhuma das instancia eu consigo logar. Dá time out. Via SSH (PuTTY) no LInux ou via RD no Windows. Inclui inicialmente regras restritas, agora permiti qualquer acesso full nas duas, e nada! Alguém pode ajudar? Agradeço a ajuda.
Answer: Acesso Windows RDP:

Security Group : Inbound : RDP : 0.0.0.0/0
Para obter a senha de administrador do windows você precisa do arquivo com extensão .PEM que foi gerado na geração do seu servidor. O nome dele aparecerá no diálogo seguinte.

Acesso Linux SSH:

Security Group : Inbound : SSH : 0.0.0.0/0
Converter a chave .PEM para .PPK com o PuttyGen;
Na conexão com o Putty, preencher o host e seguir a árvore de configuração através de Connection->SSH->Auth e selecionar o arquivo .PPK no botão Browse.

EXTRA:
Se tiver dúvidas na configuração do Firewall (Security Group), coloque uma regra "All Traffic" para "0.0.0.0/0" que será liberado para qualquer porta. Ficará mais simples de testar conectividade do seu servidor.
Answer: Alguns dos fatores que podem está ocorrendo.
1 - Acesse o painel de visualização de sua instância e clique na opção security group e depois em inbound e verifique se o source de ssh está com o ip 0.0.0.0/0
caso esteja assim está correto.
2 - Depois verifique se você seguiu os passos de configuração do putty como especificado pelo amazon aqui. Para utilizar o putty você tem que gerar uma chave privada a partir da chave .pem com extenção .ppk pelo puttygen e adiciona-la no putty. Já no ubuntu basta você baixar a chave .pem
e utilizar o camando:
ssh -i key.pem ubuntu@seu ip publico

para instâncias criadas com SO linux-amazon e windows o padrão de usuário é
ec2-user@seu ip público

para ubuntu é
ubuntu@seu ip público

Comment: Obrigado pelo retorno, porém já fiz isso tudo. Estou tentando por uma nova conta pra saber se é algo com esta em específico.

AWS - Acesso remoto à instância


Flush in entity causes infinite loop (Doctrine 2)

Question: there are two entities:
A: which will auto update something on B
B

in A there is a preupdate:
@ORM\PreUpdate
public function asd()
{
    foreach (\Doctrine\Repository\B::getInstance()->findxxxx($sdf) as $x)
    {
        $em->remove($x);
        $em->flush(); *******
    }
}

I traced the SQL log:
Doctrine\Entity\Accommodation.php: 1116
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\Event\ListenersInvoker.php: 102
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php: 1064
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php: 384
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php: 356
Doctrine\Entity\Accommodation.php: 1116
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\Event\ListenersInvoker.php: 102
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php: 1064
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php: 384
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php: 356
Doctrine\Entity\Accommodation.php: 1116
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\Event\ListenersInvoker.php: 102
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php: 1064
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php: 384
Doctrine\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php: 356
Doctrine\Entity\Accommodation.php: 1116

so it turned out the line with ******* causes this infinitive loop. Im inside a transaction. I know its not much, but can someody help me?
Comment: Does B have some properties that are references of A ? Also, even if that is surely not the cause of the problem, flush inside a loop should be avoided as possible. You need only one flush at the end, but if you have a lot of entries, look at [batch processing](http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/batch-processing.html) .
Comment: perfect ! It was very specific .
Comment: lol ... I was serious. I totally skipped the line about you're in transaction, otherwise I would give it the check.
Comment: I was inside a transaction. By checking ->getConnection()->isTransactionActive() and missing flush() when its active seems to be OK
Comment: seriously? Or irony? :) I mentioned in my started post that Im inside transaction
Answer: You shouldn't be using remove-> inside a PreUpdate and that is the likely cause of your problem.
See the documentation on PreUpdate, note the section down the bottom "restrictions for this event".
You should look at using a different event like onFlush or prePersist. In your case I would write that as an event listener, not as an entity method as you'll then have access to the unit of work and other useful stuff.
Comment: @JohnSmith Thank you very much, I had the same problem and testing if I was inside a transaction before flushing was the solution ! If you want to, you can write a solution with this and I'll upvote it, thank you so much you don't know how it save me ;)
Comment: I was inside a transaction. By checking ->getConnection()->isTransactionActive() and missing flush() when its active seems to be OK


Seeking an analytic proof of a vector identity

Question:
Show that for any vectors $\bf{u_1},\bf{u_2},\bf{v_1},\bf{v_2}\in\mathbb R^3$, we have $$(\bf{u_1}\times\bf{v_1})\cdot(\bf{u_2}\times\bf{v_2})=
\left|\begin{matrix}
\bf{u_1}\cdot\bf{u_2} & \bf{u_1}\cdot\bf{v_2}\\
\bf{v_1}\cdot\bf{u_2} & \bf{v_1}\cdot\bf{v_2}
\end{matrix} \right|.$$

I really don't want to "explode" it, is there a more analytic way to prove this identity? Thanks.
Comment: The box product is related to the determinant of the components. This would account for a smaller explosion.
Answer: First note that,
$(\vec a\times\vec b)\cdot\vec c=\vec a\cdot(\vec b\times\vec c)$
and then
$\vec a\times(\vec b\times\vec c)=(\vec a\cdot\vec c)\vec b-(\vec a\cdot\vec b)\vec c$
EDIT:  Consider $u_1=\vec a,$ $v_1=\vec b$ and $\vec c=(u_2\times v_2),$  then, $(u_1\times v_1)\cdot(u_2\times v_2)=u_1\cdot(v_1\times(u_2\times v_2))$
Now use second identity to expand $v_1\times(u_2\times v_2)$
Comment: @O.L. Consider $\vec c=(u_2\times v_2)$, then, $(u_1\times v_1)\cdot(u_2\times v_2)=u_1\cdot(v_1\times(u_2\times v_2))$
Comment: ??? there is no double cross product here
Comment: How to prove the identity on the second line?
Comment: @ᴊᴀsᴏɴ: i've added a link for the proof to the identity
Answer: An approach without too much calculation
The map $f:x\mapsto (\bf{u_1}\times\bf{v_1}$$)\cdot($$\bf{u_2}\times\bf{x}$$)$ is a linear form with kernel $\ker f= \langle\bf{u_2}\rangle$ and similary the map
$$g: x\mapsto\left|\begin{matrix}
\bf{u_1}\cdot\bf{u_2} & \bf{u_1}\cdot\bf{x}\\
\bf{v_1}\cdot\bf{u_2} & \bf{v_1}\cdot\bf{x}
\end{matrix} \right|$$ is a linear form and $\ker f=\ker g$ hence we conclude that there's $\lambda\in\mathbb R$ such that $f=\lambda g$. Now take  $\bf{u_1}=\bf{u_2}$ and $\bf{v_1}=\bf{v_2}$ and $\bf{u_1}\perp \bf{v_1}$ and we find $\lambda=1$


How to use shadcn/ui Range Date Picker inside Form?

Question: I have a problem with using The Range Date Picker inside the Form component. To be exact, I need an object to store the {from, to} values of the range, but using an object as a Form field value makes error messages not work. I just get undefined as an error message.
The current fix I'm using, is that I just modified the Form Message Component to render the errors a bit differently, but I think it's more of a hack than the proper way.
The code:
const formSchema = z.object({
  title: z.string().min(2, {
    message: "Title must be at least 2 characters.",
  }),
  date: z.object({
    from: z.date(),
    to: z.date(),
  }),
});

function NewEventPage() {
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: "",
      date: {},
    },
  });

  function onError(a) {
    console.log(a);
    /*
    title:
      message: "Title must be at least 2 characters."
      ref: {focus: ƒ, select: ƒ, setCustomValidity: ƒ, reportValidity: ƒ}
      type: "too_small"
    date:
      from: {message: 'Required', type: 'invalid_type', ref: undefined}
      to: {message: 'Required', type: 'invalid_type', ref: undefined}
    */
  }

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit, onError)}
        className="mx-auto mt-12 grid max-w-screen-lg grid-cols-2 gap-x-12 gap-y-8"
      >

          Create A New event

        <FormField
          control={form.control}
          name="title"
          render={({ field }) => {
            return (
              <FormItem>
                <FormLabel>Event Title</FormLabel>
                <FormControl>
                  <Input placeholder="The best title ever" {...field} />
                </FormControl>
                <FormDescription>Give a name for your event</FormDescription>
                <FormMessage />
              </FormItem>
            );
          }}
        />

        <FormField
      control={form.control}
      name="date"
      render={({ field }) => (
        <FormItem>
          <FormLabel>Date</FormLabel>
          <FormControl>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant={"outline"}
                  className={cn(
                    "w-full justify-start text-left font-normal",
                    !field.value && "text-muted-foreground",
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {field.value?.from ? (
                    field.value.to ? (
                      <>
                        {format(field.value.from, "LLL dd, y")} -{" "}
                        {format(field.value.to, "LLL dd, y")}
                      </>
                    ) : (
                      format(field.value.from, "LLL dd, y")
                    )
                  ) : (
                    Pick a date
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  initialFocus
                  mode="range"
                  defaultMonth={field.value?.from}
                  selected={field.value}
                  onSelect={field.onChange}
                  numberOfMonths={2}
                />
              </PopoverContent>
            </Popover>
          </FormControl>
          <FormDescription>
            Select the date for when the event will take place
          </FormDescription>
          <FormMessage />
        </FormItem>
      )}
    />

        <Button type="submit" className="col-span-2">
          Submit
        </Button>
      </form>
    </Form>
  );
}

Title shows the error, but date shows undefined:
Answer: You just have to give it a define Error message:
  const formSchema = z.object({
  title: z.string().min(2, {
    message: "Title must be at least 2 characters.",
  }),
  date: z.object({
    from: z.date(),
    to: z.date(),
  }).refine(
      (data) => data.from > addDays(new Date(), -1),
      "Start date must be in the future"
    ),
});

and remove date: {} from DefaultValues which is causing undefined.
Write like this:
function NewEventPage() {
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: "",
    },

Answer: I managed to solve it the following way:
const DATE_REQUIRED_ERROR = "Date is required.";

const formSchema = z.object({
   date: z.object({
       from: z.date().optional(),
       to: z.date().optional(),
   }, {required_error: DATE_REQUIRED_ERROR}).refine((date) => {
       return !!date.from;
   }, DATE_REQUIRED_ERROR),
   comment: z.string().min(1, {message: "A comment is required."}),
});

This is definitely not pretty. But this is the only configuration where I did not run into the following issue:

When clicking on submit without having input a value in the range date picker, it showed undefined as an error, because it detected that date.from is undefined and therefore triggered the error for the entire date object. But the date object itself did not have an error, only the date.from inside of it. The error is apparent not propagated up to the date object. That is the reason why it showed the error undefined. That is why I put the date.from as optional, so it would never cause an error.
Then I added the refine((date) => {...}) to the date object itself. In there, it checks if date.from is undefined. If it is, the DATE_REQUIRED_ERROR text will be displayed in the UI. By doing it this way, you "lift" the error from date.from to the date object itself and it is displayed correctly.

So why then the {required_error: DATE_REQUIRED_ERROR} too?
This has the following reason:

When having inserted a value in the date range picker and then having removed it again, for some reason, it triggers the Required error on the date object. If the required_error is not set, then the UI will just show Required. I personally disliked the two different error messages depending if you never isnerted a value or if inserted it and removed it again. That's why I added this, so these two errors are the same. If you don't care about that, you can leave it out.

I personally added the default values in the useForm so they are all there. But for me it also worked when not putting them in.
const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
        date: {
            from: undefined,
            to: undefined,
        },
        comment: ''
    },
});

You also need to change selected field in the Calender tag. This is due to the date.from field being optional. The selected field needs it to be definitely set. That's why I assured that through the ! operator.
<Calendar
  initialFocus
  mode="range"
  defaultMonth={field.value.from}
  selected={{from: field.value.from!, to: field.value.to}}
  onSelect={field.onChange}
  numberOfMonths={1}
/>

This is my full code. Note, that the comment field is not implemented in the UI yet and has a dummy value in the defaults:
"use client"

import {Form, FormDescription, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {z} from "zod";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {Button} from "@/components/ui/button";
import {cn} from "@/lib/utils";
import {format} from "date-fns";
import {CalendarIcon} from "lucide-react";
import {Calendar} from "@/components/ui/calendar";
import * as React from "react";

const DATE_REQUIRED_ERROR = "Date is required.";

const formSchema = z.object({
    date: z.object({
        from: z.date().optional(),
        to: z.date().optional(),
    }, {required_error: DATE_REQUIRED_ERROR}).refine((date) => {
        return !!date.from;
    }, DATE_REQUIRED_ERROR),
    comment: z.string().min(1, {message: "A comment is required."}),
});

export default function CommentSection() {
const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
        date: {
            from: undefined,
            to: undefined,
        },
        // TODO: remove this dummy value
        comment: "asdf"
    },
});

function onSubmit(values: z.infer<typeof formSchema>) {
    console.log(values);
}

return (
    <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
            <FormField
                control={form.control}
                name='date'
                render={({field}) => (
                    <FormItem className="flex flex-col">
                        <FormLabel>Date</FormLabel>
                        <Popover>
                            <PopoverTrigger asChild>
                                <Button
                                    id="date"
                                    variant={"outline"}
                                    className={cn(
                                        "w-full justify-start text-left font-normal",
                                        !field.value.from && "text-muted-foreground"
                                    )}
                                >
                                    <CalendarIcon className="mr-2 h-4 w-4"/>
                                    {field.value.from ? (
                                        field.value.to ? (
                                            <>
                                                {format(field.value.from, "LLL dd, y")} -{" "}
                                                {format(field.value.to, "LLL dd, y")}
                                            </>
                                        ) : (
                                            format(field.value.from, "LLL dd, y")
                                        )
                                    ) : (
                                        Pick a date
                                    )}
                                </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-auto p-0" align="start">
                                <Calendar
                                    initialFocus
                                    mode="range"
                                    defaultMonth={field.value.from}
                                    selected={{from: field.value.from!, to: field.value.to}}
                                    onSelect={field.onChange}
                                    numberOfMonths={1}
                                />
                            </PopoverContent>
                        </Popover>
                        <FormDescription>
                            The date you want to add a comment for.
                        </FormDescription>
                        <FormMessage/>
                    </FormItem>
                )}
            />
            <Button type={"submit"}>Submit</Button>
        </form>
    </Form>
);
}

Answer: I managed to solve it the following way:
const formSchema = z.object({
  title: z.string().min(2, {
    message: "Title must be at least 2 characters.",
  }),
 date: z
      .object(
        {
          from: z.date(),
          to: z.date().optional(),
        },
        { required_error: "Date is required." },
      )
      .refine((date) => {
        return !!date.to
      }, "End Date is required."),
});

function NewEventPage() {
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: "",
    },
  });

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


What is the best way to generate dynamic textboxes in ASP.Net web forms?

Question: I need to generate dynamic textboxes (upto 5-10 ) according to user response. So, what will be the best way to do it as regard performance,speed is concerned.
Comment: Create the textboxes using `jQuery/Javascript` and send back this data using `ajax`. Or Use `ASP:UpdatePanel` and send back asynchronously.
Answer: Here is a very helpful link and explained why
link from here

Always add the dynamic control in Page_PreInit()
Always assign ID when loading dynamically

For Example
protected void Page_PreInit(object sender, EventArgs e)
{
        Control c= LoadControl("./WebUserControl2.ascx");
        i=i+1;
        c.ID= i.ToString();
        PlaceHolder1.Controls.Add(c);
}

OR
protected void Page_PreInit(object sender, EventArgs e)
{
         LinkButton button1 = new LinkButton();
         button1.ID = "button1"
         button1.Text = "button1"
         PlaceHolder1.Controls.Add(button1);
}

Answer: int n=5;
for (int i=0;i<n;i++)
{
TextBox MyTextBox=new TextBox();
//Assigning the textbox ID name
MyTextBox.ID = "tb" +""+ ViewState["num"] + i;
MyTextBox.Width = 540;
MyTextBox.Height = 60;
MyTextBox.TextMode = TextBoxMode.MultiLine;
this.Controls.Add(MyTextBox);
}

for MVC this link might help u...
http://www.codeproject.com/Articles/434886/Dynamically-adding-controls-on-a-hierarchical-stru
Answer: TRy this way
for (int j = 0; j < 10; j++)
            {

              //Create Dynamic textboxes with required field validator .

                TextBox tbChildFirstName = new TextBox();
                Label lblChildFirstName = new Label();
                lblChildFirstName.ID = "lblChildFirstName" + j;
                lblChildFirstName.Text = "Children FirstName";
                lblChildFirstName.Width = 200;
                lblChildFirstName.SkinID = "Outlabel";
                tbChildFirstName.ID = "txtChildFirstName" + j;
                tbChildFirstName.Text = "Hi hello";
                pnlChildDetail.Controls.Add(lblChildFirstName);
                pnlChildDetail.Controls.Add(tbChildFirstName);
                RequiredFieldValidator rqf = new RequiredFieldValidator();
                rqf.ID = "rqf" + i;
                pnlChildDetail.Controls.Add(rqf);
                rqf.ControlToValidate = "txtChildFirstName" + j;
                rqf.ErrorMessage = "Children FirstName is required";
                rqf.Display = ValidatorDisplay.Dynamic;
                rqf.ValidationGroup = "EligibilityCheck";
                rqf.SetFocusOnError = true;
                rqf.Text = "*";
                tbChildFirstName.Attributes.Add("runat", "server");
                pnlChildDetail.Controls.Add(GetLiteral("
"));
                pnlChildDetail.Controls.Add(GetLiteral("
"));

            }

public Literal GetLiteral(string text)
    {
        Literal rv = default(Literal);
        rv = new Literal();
        rv.Text = text;
        return rv;
    }

Aspx
<asp:Panel ID="pnlChildDetail" Style="text-align: left; padding-left: 10px" Width="100%"
        runat="server">
    </asp:Panel>

More details for create dynamic textbox form database data count and how to get dynamic textbox value ?: see my blog


n-simplex in an intersection of n balls

Question: Consider a $n$-simplex, $n \geq 2$ with vertices $x_i,i=1,...,n+1$. For each edge $(i,j)$, consider $n$-ball $B_{ij}$ such that vertices $x_i$ and $x_j$ are antipodal on this ball. Fix a point $x_0$ in the simplex. The question: is $x_0$ in at least $n$ balls?
Some notes. It is impossible to make the question stronger by claiming that there is vertex $i=i(x_0)$ such that $x_0$ is in all balls $B_{ij},j \neq i$. Also, it is not true for $n+1$ balls (there are counterexamples for both cases if $n=3$).
Also, $x_0$ is in ball $B_{ij}$ if and only if $\angle x_ix_0x_j \geq \pi/2$, or equivalently, vertices $x_i$ and $x_j$ are on opposite sides of the hyperplane $H_i$ that contains $x_0$ and is orthogonal to the line through $x_i$ and $x_0$ (and similarly for $H_j$).
Also, this question is a stronger version of that question (Thanks to Alex Ravsky for solving it).
Any help is much appreciated. Thank you.
Comment: "Also, $x_0$ is in ball $B_{ij}$ if and only if $\angle x_ix_0x_j \geq \pi/2$, or equivalently, vertices $x_i$ and $x_j$ are on opposite sides of the hyperplane $H_i$ that contains $x_0$ and is orthogonal to the line through $x_i$ and $x_0$ (and similarly for $H_j$)." -- How do you prove this?
Comment: The first part holds because $x_i$ and $x_j$ are antipodal. The second holds because the hyperplane $H_i$ is orthogonal to the line through $x_i$ and $x_0$.
Comment: I'd suggest you choose another name for the sample point $x_0$, since $x_0$ is already a vertex of the simplex.
Comment: Thanks. I have named the vertices from $1$ to $n+1$.
Answer: I will use the notation $\mathbf{v}_i$ for the vector from $x_0$ to $x_i$.
Assume that $x_0$ is in the interior of the simplex. (By continuity, the statement will extend to boundary points.) Then
there are some positive weights $w_1,\ldots,w_{n+1}>0$ such that $\sum\limits_{i=1}^{n+1} w_i \mathbf{v}_i=\textbf0$.
Let us build a graph on the vertices $1,\ldots,n+1$. Let the vertices $i$ and $j$ be connected if $x_0$ is inside the ball with diameter $x_ix_j$; in other words, if $\mathbf{v}_i\cdot \mathbf{v}_j\le0$.
We show that this graph is connected. Assume the contrary; then the vertices can be split in two disjoint nonempty sets, say $A$ and $B$ such that $A\cup B=\{1,2,\ldots,n+1\}$. Since there is no edge between the two vertex sets, we have $\mathbf{v}_i\cdot \mathbf{v}_j>0$ for all $i\in A$ and $j\in B$.
Consider
$$
0 =
\left(\sum_{i\in A\cup B} w_i \mathbf{v}_i \right)^2 =
\left(\sum_{i\in A} w_i \mathbf{v}_i \right)^2 +
\left(\sum_{i\in B} w_i \mathbf{v}_i \right)^2 +
2\sum_{i\in A}\sum_{i\in B} w_iw_j(\mathbf{v}_i\cdot \mathbf{v}_j).
$$
In the last sum all terms are positive, contradiction. Now we have proved that the graph is connected.
A connected graph on $n+1$ vertices has at least $n$ edges, so at least $n$ balls contain $x_0$. Done.
Comment: really elegant! I was thinking about this problem for a while but could no get a clue of a proof. Can I ask how did you come up with these ideas?
Comment: Gilles: I think using vectors and dot products is standard. First I proved that there is a good ball at every vertex, but this gave only $(n+1)/2$. So I considered other distributions of the vertices. At the end I realized that we have such a graph.
Comment: Great! Thanks a lot.
Comment: This problem (and your nice solution) was used in problem 5 in the [2015 IMC](http://www.imc-math.org.uk/imc2015/imc2015-day1-solutions.pdf).
Answer: This does not answer the question. I don't prove anything here but just present the result of some simulations that suggest the answer to the question is yes.
My experience make me being careful about my intuition when it is about to think about geometrical construction in more then $3$ dimensions. So before investigating more this question I wanted to check if there is no counter example I could get with Mathematica.
I generated some random simplices with a random point inside and counted the number of balls covering the inside point. For all the tests I did, no counter example appeared. Moreover, the distribution of the number of balls in my simulations seem to be close to a normal distribution.
For example, I generated $1000$ random $3$-dimensional simplices as the convex hull of $4$ random points uniformly distributed in the unit cube. For each simplex I generated $1000$ random inside points with baricenter coordinate uniformly distributed.
Below this is the histogram of the number of balls covering the inside points considered.
We observe that it starts at $3$, which means we did not find counter example to the conjecture.
dimension$=3$; number of edges$={4 \choose 2}=6$.

Below I give more histograms obtained from simulations in higher dimension. For each I generated $100$ random simplices and and tested $100$ random inside points.
dimension$=4$; number of edges$={5 \choose 2}=10$.

dimension$=5$; number of edges$={6 \choose 2}=15$.

dimension$=6$; number of edges$={7 \choose 2}=21$.

dimension$=7$; number of edges$={8 \choose 2}=28$.

dimension$=8$; number of edges$={9 \choose 2}=36$.

dimension$=20$; number of edges$={20 \choose 2}=190$.

The code I used with Mathematica (it can certainly be optimized if you wanna run biger simulations)
<code>> RandomSimplex[dim_] := RandomReal[{0, 1}, {dim, dim + 1}]
> RandomBaricenter[dimension_] := Module[{baricenter},
>     baricenter =  RandomReal[{0, 1}, dimension + 1];
>     baricenter =  baricenter/Sum[baricenter[[i]], {i, 1, dimension + 1}];(*normalisation*)
>     Return[baricenter]]
> Distance[A_, B_] := Module[{dim},
>     dim = Dimensions[A][[1]];
>     Return[Sqrt[Sum[(B[[i]] - A[[i]])^2, {i, 1, dim}]]];]
> NumberClosePoints[simplex_, point_] :=   Module[{dim, number, i, j, M, A, B},
>     dim = Dimensions[simplex][[1]];
>     number = 0;
>     For[i = 1, i <= dim, i++,
>         For[j = i + 1, j <= dim + 1, j++,
>         A = Transpose[simplex][[i]];
>         B = Transpose[simplex][[j]];
>         M = (A + B)/2;
>         If[Distance[M, A] > Distance[M, point], number++,]]];
>     Return[number]]
</code>
and to run the tests and produce and histogram:
<code>> dimension = 3;
> nBar = 1000;(*number of barycenter tested*)
> nSimplices = 1000;(*number of simplices tested*)
> list = {};
> For[i = 1, i <= nBar, i++,
>   bar = RandomBaricenter[dimension];
>   For[j = 1, j <= nSimplices, j++,
>     simplex = RandomSimplex[dimension];
>     point = simplex.bar;
>     n = NumberClosePoints[simplex, point];
>     list = Append[list, n];
>     If[n < dimension, Print[{bar, simplex, n}],]];]
> Histogram[list]
</code>

n-simplex in an intersection of n balls


How to make pull to refresh in tableview buttom in iOS swift

Question: Want to add the pull to refresh in bottom of tableview.
First want to show the numbers in tableview 100 to 90.
Then add the pull to refresh in bottom of tableview. pull it want to display 80 to 70, then pull refresh 70 to 60, then pull refresh 50 to 40... etc final 1 to 10 means get stoped display "no data available". how to achieve this. help me thanks advance.
Here my code.
 @IBOutlet weak var dataTbl: UITableView!
    var numbers: [Any] = ["90","91","92","93","94","95","96","97","98","99","100"] // display first 100 to 90.

Loaded in tableview.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.numbers.count
    }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:UITableViewCell = self.dataTbl.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        cell.textLabel?.text = self.numbers[indexPath.row] as? String

        return cell
    }

searched in google for add the refresh in buttom of tableview. i got this code.
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
 spinner.color = UIColor.darkGray
 spinner.hidesWhenStopped = true
 tableView.tableFooterView = spinner

show spinner using
spinner.startAnimating()

hide it using
spinner.stopAnimating()

By using this code how to do pull to refresh help me.
Comment: But can't achieve it. -- means whats ...
Comment: what you want to do with above code?
Comment: where you called this `let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
 spinner.color = UIColor.darkGray`
Comment: pull to refresh in buttom of tableview, first display 100 to 90 then pull to refresh 80 to 90 like move with 10 to  1 means finally display no data
Comment: ru get my question?
Comment: i dnt know where to call ?
Comment: let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) spinner.color = UIColor.darkGray
Comment: callthis in scrollview delegate and get your arraycount -1 object < 10 do nothing else add 10 10 objects in your array and reload the table
Comment: for add spinner at bottom of tableview try to create one view which contain spinner and when you reach at bottom assign view and tableview footer view and once your data loaded remove table footer view or make it as nil
Answer: Use following delegate to detect the end of the table and to add spinner logic with table footer.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if tableView.contentOffset.y >= (tableView.contentSize.height - tableView.frame.size.height) {
                    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
     spinner.color = UIColor.darkGray
     spinner.hidesWhenStopped = true
     tableView.tableFooterView = spinner
            }
        }

Once you append those more entries to your data source then remove footer view
tableView.tableFooterView = nil

Comment: how to refresh elements 100 to 90 , 90 to 80, 80 to 70
Comment: If you are fetching it from server then you need to send offset to server to fetch next 10 records, when you get response from server then append those records to the previous data source
Answer: You will need to use the below code,
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if tableView.contentOffset.y >= (tableView.contentSize.height - tableView.frame.size.height) {
            //you reached the bottom of tableview, you can append the other 10 numbers to array and do reload
    }
}

You don't need to add UIScrollViewDelegate to achieve this, i hope UITableViewDelegate is enough. As UITableview inherits the property of UIScrollView
Hope this helps


Upload de imagem via forms com Django-StdImage

Question: Estou tentando fazer upload de imagem via forms e CreateView, poŕém só consigo através do admin do Django. Estou utilizando StdImage.
Todos os dados são cadastrados normalmente no banco de dados com exceção da imagem.
Tem alguma forma de subir a imagem dessa forma?
models.py:
class Pub(models.Model):
    name = models.CharField(max_length=20, unique=True)
    description = models.CharField(max_length=250)
    rate = models.PositiveIntegerField(choices=RATING, blank=False, default="-")
    created_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="bar")
    created_at = models.DateTimeField(auto_now_add=True)
    image = StdImageField(upload_to='static/img/', variations={'thumbnail': {"width": 300, "height": 400, "crop": True}}, blank=True, null=True)

views.py:
class PubCreateView(CreateView):
    model = Pub
    form_class = PubForm
    success_url = "/pubs/"

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.created_by = self.request.user
        return super(PubCreateView, self).form_valid(form)

forms.py:
class PubForm(forms.ModelForm):
    class Meta:
        model = Pub
        fields = ['name', 'description', 'rate', 'image']

html:
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}

        <button type="submit">enviar</button>
    </form>

Comment: como esta o settings.py e urls.py configurado para receber a img ?
Comment: @stack.cardoso O _settings.py_ com `MEDIA_ROOT = os.path.join(BASE_DIR, 'media')`e _urls.py__ com `+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)`. A imagem está sendo salva quando cadastro pelo /admin do django, apenas pelo html (form) que não subia. Alterei para utilizar **models.ImageField** e está funcionando via html, Manterei assim por enquanto.
Comment: Ha versão do dj que não possui mais os.path mas sim Path.join (BASE_DIR, 'media')
Comment: @stack.cardoso agradecço a ajuda! O problema estava no html. Não coloquei `enctype="multipart/form-data"` na tag . Após incluir passou a funcionar normal.
Comment: disponha. Sucesso para teu projeto :)
Answer: Resolvido
O problema estava no arquivo html. Por se tratar de upload de arquivo, deve colocar enctype="multipart/form-data" na tag <form>. Ou seja, o arquivo html ficou dessa forma:
    <form method="post" enctype="multipart/form-data" autocomplete="off">
        {% csrf_token %}
        {{ form.as_p }}

        <button type="submit">enviar</button>
    </form>

Após isso as imagens passaram a ser salvas no banco de dados normalmente.


Chi-Squared Test of Homogeneity

Question: Consider the table below that gives the proportions of a sample from each of two populations that fall into one of three categories (table edited after @whuber comment).
                            1   2   3   **4**
First Population Sampled  13% 19% 28% **40%**
Second Population Sampled 7%  11% 22% **60%**

Test the hypothesis that the population proportions are equal with a column (category) by calculating the p-value of the $\chi^2$ test statistic. Test assuming the size of the sample selected from each population that gave the above proportions was 100 people at level 0.10.
Answer: I have established the following hypotheses:
By the statement of the problem, I am assuming that this is a test for homogeneity. So the hypotheses would be:

$H_0:$ The populations are homogeneous with respect to the three categories. That is, $p_{1j} = p_{2j}$ for $j = 1, 2, 3$.

$H_a:$ The populations are not homogeneous with respect to the three categories.

However, I then realized that the row totals do not sum to 1, which has me concerned.
Is the homogeneity approach correct? I thought it may be a test of independence, but there are two populations.
Based on the comment below, the observed counts are:
                            1   2   3   4
First Population Sampled   13  19  28  40
Second Population Sampled   7  11  22  60

So we can proceed with the homogeneity test with $n = 200$.
Comment: Since each row must sum to 1 = 100%, I should created the fourth column as in my Edit to my post, and then am able to proceed with a test of homogeneity?
Comment: You are given that each sample was 100 people, so just use that to recreate a table of counts!
Comment: Hint: there's an invisible fourth column that you can (easily) recreate from the information given you.
Comment: Understood. So this now matches a homogeneity test with $n = 200$.
Comment: You can now answer your Q yourself! Please do so, so the Q do not linger on as unresolved!
Answer: "Anti-lingering" Comment:
Your stated contingency table is TBL as below:
TBL = rbind(c(13,19,28,40), c(7,11,22,60))
TBL
     [,1] [,2] [,3] [,4]
[1,]   13   19   28   40
[2,]    7   11   22   60

Verifying that both rows sum to $100,$ as stated:
rowSums(TBL)
[1] 100 100

A chi-squared test in R, shows significant departure
from homogeneity at 5% level with P-value $0.034 < 0.05 = 5\%.$
chisq.test(TBL)

        Pearson's Chi-squared test

data:  TBL
X-squared = 8.6533, df = 3, p-value = 0.03427

The Pearson residuals reveal explicitly that the 2nd
sample showed lower counts for categories 1 and 2
than the first sample, while the first sample showed a
lower count for category 4. [Taken together,
contributions to the chi-squared statistic from these
six cells accounted for almost all of the total
chi-squared statistic of about 8.6.]
chisq.test(TBL)$res
           [,1]      [,2] [,3]      [,4]
[1,]  0.9486833  1.032796  0.6 -1.414214
[2,] -0.9486833 -1.032796 -0.6  1.414214

The squares
of the Pearson residuals sum to the significantly large chi-squared statistic.
chisq.test(TBL)$res^2
     [,1]     [,2] [,3] [,4]
[1,]  0.9 1.066667 0.36    2
[2,]  0.9 1.066667 0.36    2
sum(chisq.test(TBL)$res^2)
[1] 8.653333

Chi-Squared Test of Homogeneity