Uso de instanceof

Question: Criar uma classe abstrata Conta, e outras duas classes concretas ContaF e ContaJ que herdam da classe principal. Criar outra classe com um método que recebe uma lista de contaF e ContaJ e ArrayList<Conta> e calcule quantos elementos tem em ContaF e ContaJ
Estou quase finalizando:
public class InstanciaDe
{

public static void main( String[] args )
{

    ContaF Rafael = new ContaF();

    ContaJ Roberto = new ContaJ();

    ContaJ Carlos = new ContaJ();

    ArrayList<Conta> lista = new ArrayList<Conta>();

    lista.add(Rafael);
    lista.add(Roberto);
    lista.add(Carlos);

    for(int i=0 ; i < lista.size() ; i++){

        if (lista.get(i) instanceof ContaF) {

        }

        if (lista.get(i) instanceof ContaJ) {

        }
    }
}
}

Como posso guardar a quantidade pelo instanceof de cada e depois exibir?
Comment: `int nContaF = 0; if(lista.get(i) instanceof ContaF) nContaf++;`
Comment: Obrigado, estava pensando em algo parecido.
Answer: É só criar um contador:
import java.util.*;

class InstanciaDe {
    public static void main( String[] args ) {
        int contaF = 0;
        int contaJ = 0;
        ContaF Rafael = new ContaF();
        ContaJ Roberto = new ContaJ();
        ContaJ Carlos = new ContaJ();
        ArrayList<Conta> lista = new ArrayList<Conta>();
        lista.add(Rafael);
        lista.add(Roberto);
        lista.add(Carlos);
        for(int i = 0 ; i < lista.size() ; i++) {
            if (lista.get(i) instanceof ContaF) {
                contaF++;
            }
            if (lista.get(i) instanceof ContaJ) {
                contaJ++;
            }
        }
        System.out.println(contaF);
        System.out.println(contaJ);
    }
}
class Conta {}
class ContaF extends Conta {}
class ContaJ extends Conta {}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Foi muito útil, obrigado.
Answer: import java.util.*;

class Conta {}
class ContaF extends Conta {}
class ContaJ extends Conta {}

class InstanciaDe {

    public static void main(String[] args) {
        ContaF Rafael = new ContaF();

        ContaJ Roberto = new ContaJ();

        ContaJ Carlos = new ContaJ();

        ArrayList<Conta> lista = new ArrayList<Conta>();

        lista.add(Rafael);
        lista.add(Roberto);
        lista.add(Carlos);

        System.out.println(getInstanceCount(contas, ContaF.class));
        System.out.println(getInstanceCount(contas, ContaJ.class));
    }

    public static int getInstanceCount(List<Conta> contas, Class<? extends Conta> class1) {
        int count = 0;

        for (Conta conta : contas) {
            if (conta.getClass().equals(class1)) {
                count++;
            }
        }

        return count;
    }
}

Uso de instanceof


Prove that strong induction and standard/weak induction are logically equivalent.

Question: I would like some guidance in the right direction for my attempt.
Proof.
($\Rightarrow$): First assume strong induction to be true and we prove standard induction. Consider the set $A \subseteq \mathbb{N}$ defined by the conditions, $1 \in A$ and $n \in A \Rightarrow n+1 \in A$. We prove that $A = \mathbb{N}$. Define another set $B \subseteq \mathbb{N}$ such that $B$ contains all $m \in \mathbb{N}$ such that $m \notin A$. Clearly $1 \notin B$ since $1 \in A$. Now assume that $1,...,n \notin B \Rightarrow 1,...,n \in A$. In particular, notice that $n \in A \Rightarrow n+1 \in A$ (by definition of how $A$ is defined.). So by strong induction, we must have $A = \mathbb{N}$ as desired.
($\Leftarrow$): Now assume standard induction and we prove strong induction. Consider the set $C \subseteq \mathbb{N}$ defined by the conditions, $1 \in C$ and $1,...,k \in C \Rightarrow k+1 \in C$. Since $1 \in C$ and $k \in C \Rightarrow k+1 \in C$, we get that $C = \mathbb{N}$ (by use of standard induction). QED.
Please point out any circular reasoning, confusing use of notation or simply if some of my arguments don't make any sense.
Thanks in advance!
Comment: Hello Gerry. Sorry for the late response. The links are very helpful. I had polished off my proof with the feedback in mind.
Comment: Somehow I feel that your second step should be more complicated than your first
Comment: Previous related discussion: https://math.stackexchange.com/questions/335479/is-strong-induction-not-actually-stronger-than-normal-induction also https://math.stackexchange.com/questions/4286534/equivalence-of-mathematical-induction-and-strong-induction
Comment: And https://math.stackexchange.com/questions/1184541/what-exactly-is-the-difference-between-weak-and-strong-induction
Comment: Any thoughts on these links, Lucas, or on the answer that was posted yesterday?
Comment: If you want to be sure I see a comment intended for me, you have to put @Gerry in it so I get notified.
Answer: Your $\Leftarrow$ direction looks fine to me.
For the $\Rightarrow$ direction, I would be more explicit about justifying the assumption $1, \ldots, n \notin B$. In particular, you could mention something to the effect of "by way of contradiction, assume $B$ is non-empty. By the well-ordering of $\mathbb{N}$, this implies $B$ has a least element $m$ such that $m \leq b$ for all $b \in B$. Therefore since $1, \ldots, m-1$ are not in $B$, then they must be in $A$ by definition of $B$." Your argment then proceeds more or less as you've written it, modulo some fiddly bits.


How Akamai CDN serves the content from closes edge server to user ?a

Question: After going through some resources on google, got the idea how Akamai CDN edge servers works but got some questions about internals.

Say I have got static content cached at Akamai CDN(XXX.XX.XXX.XXX say in seattle) for my site xyz.com(YYY.YY.YYY.YYY) . Here at some Akamai interface I will route the call to my origin web server ip
and ask Akamai to cache the static content.
Now Whenever I type www.xyz.com in browser(for any resource be it static or dynamic), call will go to DNS server to resolve the IP for domain www.xyz.com .
DNS server will provide the IP address of configured Akamai Edge server(say XXX.XX.XXX.XXX which is hard coded in point 1) . My question is
How I will ensure DNS server provide the  edge server closest to user ? Will it always provide XXX.XX.XXX.XXX which is Seattle IP irrespective user is
trying to access the site from China or India ?
Comment: https://m.youtube.com/watch%3Fv%3Du0NtUPpebCo&ved=2ahUKEwiHuo62y_bkAhWCbVAKHaxPAd0QjjgwFHoECAQQAQ&usg=AOvVaw0Vnw4oOHWOR8tEprS36z_i i think this will tell you howto?
Answer: It's Akamai DNS 'magic' determining where to send the client to get the request.
As I understand it (after having a discussion with an Akamai network architect at an IP-Peering meeting) Akamai's DNS uses shortest path routing (typically BGP) from the enquiring DNS client to determine where the closest location is and provides that IP Address.
The DNS protocol defines how a client requests an address and howw a server provides it.  Just as a web server can provide a different resource according to the client requesting it, a DNS server can be written that can also do the same thing.
Internet Routing typically works on Border Gateway Protocol (BGP) where Autonomous Systems (identified by AS numbers) exchange information about which subnets are controlled by which system.  When determining how to route to an IP address routers typically choose the route which passes through the smallest number of Autonomous Systems.
So an Akamai DNS server receving a DNS request for a resource hosted at Akamai has the IP address of the requesting client.  This can be looked up in their internal database to determine which of the Akamai servers is 'closest' (in terms of the IP route) to that address and so the client can then return the address of the 'closest' server.
After having this conversation I did some trial lookups from different subnets and what I noticed was the first lookup typically took significantly longer than a 'normal' DNS lookup. Presumably this was because the system was looking up how to route to that address.  Subsequent lookups were as fast as usual, presumably because the answer is cached.

Extra information (how DNS works)
When a DNS client requests a name from a DNS server the server will either provide the name if it is authoritative for that domain, or it will look it up on other servers (if it is configured to be recursive) or it will provide a previously cached answer.  The global 'root' servers allow DNS servers to locate the DNS servers which are authoritative for any par5tcular domain so they can direct a recursive query.
DNS servers do not contain mappings for all addresses on the Internet - that would be impossible to maintain and people who operate domains need to be able to change their own DNS records.
Normally DNS servers are either authoritative or recursive (not usually both).  When looking up the address for a name which has a CNAME record the client then needs to lookup the IP address that the A record pointed to by the CNAME record has.  So if you have CNAME records pointing at Akamai edge servers then it will be the Akamai doamin that needs to be queried as the Akamia domain servers are authoritative for that domain.
When the request comes to the Akamai server it can lookup any information it wants to in order to work out what IP Address to return.  As they have an extensive peering (BGP connected) network they will work out which edge server is best placed to provide the data based on the shortest route between the edge server and the origin of the DNS query.
If the query is being made by a DNS server doing a recursive lookup then it may cache the answer, but as it would request the result with the same IP Address in the future it would normally get the same answer so this is not a problem.  Akamai can set how long the record should be cached for in their response providing the address (although a server may choose not to follow their direction with regard to cache lifetime).
As most clients have addresses resolved for them by a DNS server that's part of the same AS the routing length (number of different AS's involved) is the same for the DNS server looking up the address and the actual client machine that wants the address.
Comment: You said

`So an Akamai DNS server receving a DNS request for a resource hosted at Akamai has the IP address of the requesting client. This can be looked up in their internal database to determine which of the Akamai servers is 'closest' (in terms of the IP route) to that address and so the client can then return the address of the 'closest' server.`

My question is when I type `www.example.com` , call will first go to any DNS server(not Akamai DNS server) which has some hard coded mapping of Akamai edge
 server, then call will go to that hard coded Akamai edge server. Isn't it ?
Comment: So how Akamai will play any role at DNS server resolution and look into internal database to determine which of the Akamai servers is 'closest' to user  ?
Comment: I will put more explanation into my answer ...
Comment: Again you said `When the request comes to the Akamai server it can lookup any information it wants to in order to work out what IP Address to return` My question is again on this part only. Request workflow is `Browser > DNS server > Akamai Server > Akamai Edge Server `  I understand once request comes to first akamai server , it can find the closest edge server. But my question is about first akamai server i.e. how DNS will find which is the closes akamai server(not edge server) in the above request flow chain  ?
Comment: The DNS request must be resolved by an **Akamai** DNS Server as the DNS server needs to be authoritative for the domain.  The Akamai DNS server can do whatever it wants to to resolve the request.  I don't see what you don't understand.
Comment: Oh you mean to say that when I type `www.xyz.com` in browser request will go to directly to Akamai DNS server to resolve `xyz` instead to any DNS server ? But how browser will get to know request to Akamai DNS server not to any other DNS server ?
Comment: It's how DNS works.  You request www.xyz.com - it needs for a response from a server that is authoritative for xyz.com - if it then provides a CNAME for endpoint.some.domain it then needs a resoponse from a server that is authoritative for some.domain - as you point your resources using a CNAME to Akamai's domain you will utlimately get a response from Akamai's DNS servers.
Comment: Thanks I got the answer  I was looking for from  https://humanwhocodes.com/blog/2011/11/29/how-content-delivery-networks-cdns-work/ . It says `At it's simplest, the DNS server does a geographic lookup based on the DNS resolver's IP address and then returns an IP address for an edge server that is physically closest to that area`. So basically DNS server will itself provides the closest Akamai Edge server .
Comment: Thanks for letting me know - of course this is what my answer says so any comments on how to improve my answer would be appreciated to increase the quality of this site.  The lookup is based on routing as I outlined, not geographic location, because geographic location cannot be accurately determined (the AS can put addresses anywhere they have equipment) and of course we don't care about the physical distance, we care about the number of hops to get to the data (quickest access and download time).
Answer: The only thing you do is set up your DNS records to Akamai's specifications. You only put in the address and CNAME records that they give you. Akamai will handle the task of determining which edge router is closest to any particular user.
Comment: As CNAME(pointing to akamai edge server) entry is done at DNS server , Can you please throw some light how
Akamai is(or may be doing) internally mapping which esdge server is closest  to user ? Is it done by DNS server(not Akamai)
where it see user locationa nd find which Akamai edge server is closest to user ?
Answer: There is a good paper that describes the process.
Paper Name: "algorithmic Nuggets in content distribution"
Comment: Would be more helpful if you could summarize the process and provide a link to the paper you have mentioned.


SQL SELECT REQUEST ON DATE(String) and IdPatient(Integer)

Question: For a medical application, I search to be able to register a new appointment between a patient and his physician from a click on a calendar gridview cell and after display the appointment on the calendar with an indicator.
Now, I have a SQL Select statement which is supposed to get data from a table Events in the database on date and idpatient parameter like this :
String query1 =
      "SELECT * FROM " + TABLE_EVENTS + "WHERE" + COLUMN_DATE_EVENTS + "=" + date +
      " AND" + COLUMN_ID_PATIENT + "= " + idPatient;

Parameters date and idPatient are passed as arguments of the function and seems effectively to be received.
My date field is defined as a string in my database.
When I insert the event with the function saveEvent before that,
the function
long result = database.insert(TABLE_EVENTS, null, contentValues)

returns "6.
Comment: [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/)
Comment: So what is your question?
Comment: I tried to get datas several times, but my cursor.getCount() is always to 0, so thinking it was maybe because there is a problem in saveEvent function, I "Log.d" display the result of my db.insert function and the result being not -1, I think it would have been inserted. My question is could it have a syntax problem in my request who does datas are not obtained from database ?
Comment: Can I effectively use an "=" symbol on a string date or is is illegal ?
Comment: That's the request I use to create my table Event. Could it be there is a problem private static final String CREATE_TABLE_EVENTS =
            "CREATE TABLE " + TABLE_EVENTS + "("
                    + COLUMN_ID_EVENTS + "INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
                    + COLUMN_DATE_EVENTS + "TEXT NOT NULL, "
                    + COLUMN_MONTH_EVENTS + "TEXT NOT NULL, "
                    + COLUMN_YEAR_EVENTS + "TEXT NOT NULL, "
                    + COLUMN_ID_PATIENT + "INTEGER NOT NULL, "
                    + COLUMN_ID_MEDECIN + "INTEGER NOT NULL " + ")";
Comment: When I display my sql request in the console with a Log.d, I obtain this result :    SELECT * FROM  events WHERE date LIKE 2020-04-23 AND patient_id = 2. So the date and id parameter seems to effectively not be the problem.
Comment: I tried to take off the "date" parameter of my request and just make that :           SELECT * FROM  events WHERE patient_id = 2. When I did that, my cursor.getCount() seems effectively get datas : I obtain "8" lines,                             but I would like get just datas from some dates.
Comment: parametrized queries ? Okay, I will already watch that. Thank you.
Answer: Sorry for the disturbance.
I hadn't seen before my last post, but in putting date parameter in this way,
instead directly in the query, it seems to work.
Cursor cursor = db.rawQuery(query1, new String[] { date },null);
Thank you still for your answers.
Answer: Here is the function I use.
I click on a gridView cell who opens a AlertDialog who shows name and firstname of the patient and the date and when I click one more time on the button in AlertDialog,
my function saveEvent register date as a string in database in this format :
2020-04-22
My function readEventsByIdPatient must after that get datas to display on the selected date the patient have a meet with his physician this day.
In the two Lod.d lines, I can see in the console my parameters date and idPatient are effectively get in the function.
public void readEventsByIdPatient(String date, int idPatient, SQLiteDatabase database) {
    Log.d("readEventsByDate", String.valueOf(date));
    Log.d("readEventsByIdPatient", String.valueOf(idPatient));

    List<Event> events = new ArrayList<>();

    String query1 = "SELECT * FROM " + TABLE_EVENTS + "WHERE" + COLUMN_DATE_EVENTS + "=" + date + "AND" + COLUMN_ID_PATIENT + idPatient;

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery(query1, new String[] { date },null);

    Log.d("cursorGetCount", String.valueOf(cursor.getCount()));

    if(cursor.getCount() > 0) {

        if (cursor.moveToFirst()) {

           do {

                String Date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
                String month = cursor.getString(cursor.getColumnIndexOrThrow("month"));
                String year = cursor.getString(cursor.getColumnIndexOrThrow("year"));
                int IdPatient = cursor.getInt(cursor.getColumnIndexOrThrow("patient_id"));
                int IdMedecin = cursor.getInt(cursor.getColumnIndexOrThrow("medecin_id"));

                Log.d("date", String.valueOf(Date));
                Log.d("month", String.valueOf(month));
                Log.d("year", String.valueOf(year));
                Log.d("IdPatient", String.valueOf(IdPatient));
                Log.d("IdMedecin", String.valueOf(IdMedecin));


Calculate the limit $\lim_{x \to 2} \frac{x^2\sqrt{x+2}-8}{4-x^2}$

Question: Calculate the limit
$$\lim_{x \to 2} \frac{x^2\sqrt{x+2}-8}{4-x^2}$$
I tried to factorise and to simplify, but I can't find anything good.
$$\lim_{x \to 2} \frac{\frac{x^2(x+2)-8\sqrt{x+2}}{\sqrt{x+2}}}{(4-x^2)}$$
Comment: Show your tries. If you actually tried
Comment: @YuriyS ok wait
Answer: You should use L'Hôpital's rule.
Comment: What's means l'hopital's rule ?
Comment: You should take derivative from numeraror and denominator separately
Comment: [See here](https://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule) for L'Hôpital's rule.
Answer: Substitute $t=\sqrt{x+2}$; if $x\to2$, then $t\to2$, so, after doing $x=t^2-2$, you get
\begin{align}
\lim_{t\to2}\frac{t(t^2-2)^2-8}{4-(t^2-2)^2}
&=\lim_{t\to2}\frac{t^5-4t^3+4t-8}{4t^2-t^4} \\[4px]
&=\lim_{t\to2}\frac{t^3(t^2-4)+4(t-2)}{t^2(4-t^2)} \\[4px]
&=\lim_{t\to2}\left(-t-\frac{4}{t^2(2+t)}\right)
\end{align}
Answer: L'Hôpital's rule is not necessary. Here are the steps
$$\lim\limits_{x\to 2} \frac{x^2\sqrt{x+2}-8}{4-x^2}$$
$$=\lim\limits_{x\to 2} \frac{8-x^2\sqrt{x+2}}{(x-2)(x+2)}$$
Let $t=\sqrt{x+2}$, then
$$\lim\limits_{t\to 2} \frac{8-\left(t^2-2\right)^2 t}{\left(t^2-4\right)t^2}$$
$$=\lim\limits_{t\to 2} \frac{\left(-t^5+4t^3-4t+8\right)}{(t-2)(t+2)t^2}$$
$$=\lim\limits_{t\to 2} \frac{-(t-2)\left(t^4+2t^3+4\right)}{(t-2)(t+2)t^2}$$
$$=\lim\limits_{t\to 2} \frac{-\left(t^4+2t^3+4\right)}{(t+2)t^2}$$
$$=\lim\limits_{t\to 2} \frac{-\left(t^2+2t+\frac{4}{t^2}\right)}{t+2}$$
$$=-\frac{\left(4+4+1\right)}{2+2}$$
$$=-\frac{9}{4}$$
Comment: Nice answer !!! +1
Answer: Since the OP does not know L'Hospital's rule (yet), this approach is probably not the best way. When you multiply top and bottom by $x^2\sqrt{x+2}+8$ you get the fraction: $\frac{x^5+2x^4-64}{(4-x^2)(x^2\sqrt{x+2}+8)}$ Both NUM and DENOM have a factor $x-2$ In case of the NUM, you could perform long division to arrive at $x^4+4x^3+8x^2+16x+32$ and in case of the DENOM, it is of course straight forward. Can you finish it from here?
Answer: It seems you may not know l'Hôpital's rule. It's also possible without the need for differentiation. Multiply numerator and denominator with the so called conjugate expression of the numerator:
$$\frac{x^2 \sqrt{x+2} - 8}{4-x^2}
= \frac{\left( x^2 \sqrt{x+2} - 8 \right)\left( x^2 \sqrt{x+2} + 8 \right)}{\left(4-x^2\right) \left( x^2 \sqrt{x+2} - 8 \right)}$$
Then simplify via $(a-b)(a+b) =a^2-b^2$ in the numerator:
$$\frac{x^4(x+2)-64}{\left(4-x^2\right) \left( x^2 \sqrt{x+2} - 8 \right)}$$
Now you should factorise so you have a common factor $x-2$ in the numerator and denominator. In the denominator that's easy via $4-x^2 = (2-x)(2+x)=-(x-2)(x+2)$. For the nominator, you know that the polynomial divides $(x-2)$ since $x=2$ is a root of the polynomial. You can use long division or Horner's method for this:
$$x^4(x+2)-64 = x^5+2x^4-64=(x-2) (x^4+4 x^3+8 x^2+16 x+32)$$
So back to the limit:
$$\lim_{x \to 2} \frac{x^2 \sqrt{x+2} - 8}{4-x^2}
=\lim_{x \to 2}  \frac{(x-2) (x^4+4 x^3+8 x^2+16 x+32)}{-(x-2)(x+2) \left( x^2 \sqrt{x+2} + 8 \right)}$$
Cancel the common factor $x-2$ and plug in $x=2$, simplify:
$$\lim_{x \to 2}  \frac{x^4+4 x^3+8 x^2+16 x+32}{-(x+2) \left( x^2 \sqrt{x+2} + 8 \right)} = \ldots = -\frac{9}{4}$$
If you have seen l'Hôpital's rule, the other answers give you an alternative.
Comment: I think when you simplified $x^4(x+2)$ you made a mistake
Comment: There was an exponent 4 missing (added); but I think the rest is alright. But you're welcome...
Answer: For the sake of being concise, I have chosen to omit most of the intermediary algebraic simplifications. Letting $u = x+2$, we get
$$\lim_{u \to 4} \frac{{u^{\frac 52} - 4u^{\frac 32} + 4\sqrt{u} - 8}}{4 - u^2 + 4u - 4}$$
By L'hopital, this is equal to
$$\lim_{u \to 4} \frac{\frac {5u^2 - 12u+4}{2 \sqrt{u}}}{4 - 2u} = \lim_{u \to 4} \frac{2 - 5u}{4\sqrt{u}} = -\frac{9}{4}$$


The complex tangent bundle of $\mathbb{C}P^1$ is not isomorphic to its conjugate bundle.

Question: In " Characteristic Classes" by Milnor and Stasheff on pages 167-168, the authors give a brief argument about why:
The complex tangent bundle of $\mathbb{C}P^1$ is not isomorphic to its conjugate bundle.
However I don't understand their argument. I think I understand that if we did have an isomorphism between these two bundles then it necessarily swaps the orientations on the fibers in the associated real bundles, thus in every fiber there is a fixed line that is invariant under the isomorphism. I don't understand the next sentence " ...the 2 sphere does not admit any continuous field of tangent lines." and why it implies what we are trying to prove. I think maybe they are trying to show that this implies that the tangent bundle splits and hence the Euler class is 0. But we know that it is nonzero so we have a contradiction. But I am pretty confused.
Answer: It is easy to show that an isomorphism of conjugate complex structures on a plane must be a reflection.
The axes of reflection determine a line field on the sphere.
If the field is orientable then it will have a non zero section and the sphere would have Euler characteristic zero.
If it is non-orientab;e then it will determine a on-zero first Z2 cohomology class,the Stiefel-Whitney class of the line bundle. But the first cohomology of the 2 sphere is zero.
Comment: Why the field orientable implies the existence of a nonzero section?
Answer: This may be the blind leading the blind, but I believe your argument is right.
The authors might also refer to their argument on p. 101, where they say that if the tangent bundle $TM$ of a smooth manifold is oriented and $e(TM) \neq 0$, then $TM$ can't admit any odd-dimensional subbundle $\xi$. This may be due to Property 9.4; we would have $2e(\xi) = 0$ and thus $2e(TM) = 2e(\xi) \smile e(\xi^\perp)= 0$, despite it being the case that $H^{\dim M}(M) \cong \mathbb{Z}$.
A related thing to think about is that, given a continuous line field $\xi$, picking a unit vector in each line would give a nowhere-vanishing vector field $v$ on $S^2$, which would contradict the hairy ball theorem. You'd need to show that given a continuous line bundle, you could continuously pick basis vectors, but I think that would follow from orientability.
Also, rotating each vector $v_p \in T_p S^2$ by $\pi/2$ would give another nowhere-vanishing vector field $w$, and together, $v$ and $w$ would parallelize the tangent bundle $TS^2$, which is impossible (for example because the Euler class is nonzero).


How to resolve the date time issue after published bot project code into azure web app

Question: I am working on Bot Technology, in my current Bot project I implemented the functionality as "based on time my bot tells greetings to the user like Good Morning, Good After Noon and Good Evening".
For that I wrote the below lines of code in my MessagesController.cs
<code>    var hour = todaydate.Hour;
    string sessionOfDay = "";

    if (hour >= 12 && hour <= 17)
    {
        sessionOfDay = "Afternoon";

    }
    else if (hour > 17 && hour <= 23)
    {
        sessionOfDay = "Evening";

    }
    else
    {
        sessionOfDay = "Morning";
    }
</code>
The above code working fine in my Local Machine. But when I was published my bot project into azure web app. After that my bot tells greetings to the user based on server time not an local time.
Can you please tell me how to fix the above issue?
-Pradeep
Comment: you can define a variable to find the difference between your local time and server time, then apply this difference on your scheduling.
Answer: In general, unless your users share their location with you, you have no way of knowing what timezone they are in. For users that choose to share their location, you can calculate the offset between sever time (UTC(+0)) and the user's time zone.
You might consider explicitly asking a user for their location and use the new location control: https://github.com/Microsoft/BotBuilder-Location for validation


can't mock an exception with pytest

Question: I do not seem to be able to test a getopt exception. A very simplified example is here (the main file):
import sys, getopt

def main():
    try:
        options, _ = getopt.getopt(sys.argv[1:], 'h')
    except getopt.GetoptError:
        print("here I want to go")

if __name__ == '__main__':
    main()

And the test file where I am trying to raise the GetoptError exception is here (the test file):
import getopt, mock, main

@mock.patch("getopt.getopt", mock.MagicMock(side_effect=getopt.GetoptError('')))
def main_test():
    try:
        main.main()
        assert False
    except getopt.GetoptError:
        assert True

Unfortunately no exception is raised. The test returns:
    @mock.patch("getopt.getopt", mock.MagicMock(side_effect=getopt.GetoptError('')))
    def main_test():
        try:
            main.main()
>           assert False
E           assert False

main_test.py:7: AssertionError

Can anybody point out what I am missing? Thank you.
Comment: `import mock` -- which version of Python that is? `mock` is in standard library since 3.3 as `unittest.mock`.
Comment: Python 3.7.4 (default, Jul 21 2019, 14:43:25)
[GCC 7.4.0] on cygwin
Comment: You are catching the exception in the `main` function so pytest will never be able to detect that it occurred. How to workaround this is not easy to tell from your example. Maybe move the try/except clause to `if __name__ == '__main__':`.
Comment: @tmt, that's it. I did not think about that. Now I know how to tackle it. Thanks a lot.
Comment: @BerndPrager Cool. Use `with pytest.raises` from the other answer as the correct way of asserting exceptions in pytest.
Answer: Use  with pytest.raises for testing exceptions:
def main_test():
  with pytest.raises(getopt.GetoptError)  as err:
     main.main()

Refer pytest assert for http://doc.pytest.org/en/latest/assert.html
Comment: E           Failed: DID NOT RAISE

can't mock an exception with pytest


$(\mathbb{Z}/p^r\mathbb{Z})^{\ast}$ is a cyclic group

Question:
I would like to prove that the group $(\mathbb{Z}/p^r\mathbb{Z})^{\ast}$ of the invertible elements of $\mathbb{Z}/p^r\mathbb{Z}$ with $p>2$ prime and $r>0$ is cyclic.

My text suggests to start proving that the kernel $W$ of the canonical  homomorphism  $(\mathbb{Z}/p^r\mathbb{Z})^{\ast}\to(\mathbb{Z}/p\mathbb{Z})^{\ast}$ is a cyclic group by verifying that $1+p$ has order $p^{r-1}$ in $W$.
I suppose, but I am not sure, that the said canonical homomorphism might be the projection $(\mathbb{Z}/p^r\mathbb{Z})^{\ast}\to(\mathbb{Z}/p\mathbb{Z})^{\ast}:a\mapsto\bar{a}$, and I would say that the kernel of the map   is $\{\bar{1}, \overline{1+p},\overline{1+2p}...,\overline{1+(p^{r-1}-1)p}\}$, so it has order $p^{r-1}$ (and therefore if the group generated by $1+p$ has the same order, it must be the kernel itself).
But I haven't been able to prove that $p^{r-1}$ is the least natural number $m$ such that $(\overline{1+p})^{m}=\bar{1}$...
Furthermore, once proved that $W\subset(\mathbb{Z}/p^r\mathbb{Z})^{\ast}$ is cyclic, I don't know how to see that $(\mathbb{Z}/p^r\mathbb{Z})^{\ast}$ is cyclic too...
Has anybody got any ideas?
I $\infty$-ly thank you in advance!!!
Comment: If you expand $(1+p)^m = 1 + \binom m1 p + \binom m2 p^2 + \cdots$ in a binomial expansion, you can show that the power of $p$ dividing $(1+p)^m-1$ is exactly the same as the power of $p$ dividing $\binom m1 p$. That will show you that $p^{r-1}$ is the least such natural number. After that, you should look to general group theory arguments - something like, a finite abelian group with a large cyclic subgroup must itself be cyclic. (By the way, there's an entirely different way to show that these groups are cyclic - see "primitive roots" in number theory.)
Comment: I broke up your text a bit (inserting line breaks) to make it a tad more readable. I hope you don't mind.
Comment: See http://www.mathreference.com/num-mod,unm.html for a direct proof that $(\mathbb{Z}/p^r)^*$ is cyclic. If $[\zeta]$ is a generator of $(\mathbb{Z}/p)^*$, then $[\zeta+p]$ is a generator of $(\mathbb{Z}/p^r)^*$.
Comment: See http://www-groups.mcs.st-and.ac.uk/~neunhoef/Teaching/ff2013/ff2013.pdf - Theorem 6.9 - Page 25. It may be help.
Comment: at amWhy: thank you for editing! I am a beginner with formatting here... and Chag Urim sameach! at Martin: very interesting proof and site. at AHH: downloaded the paper, so interesting, but not only because of $\mathbb{F}_p$. at Greg: very elegant way to see that $p^k|(1+p)^m-1\iff p^k|mp$, useful to understand some points behind the mathreference proof. Thank you a lot everybody!!!!
Answer: For $r=1$, you can see that $\big(\Bbb Z\big/p\Bbb Z\big)^\times$ is cyclic of order $p-1$ by realizing it as the multiplicative group of the finite field $\Bbb Z\big/p\Bbb Z$.
Now suppose $r > 1$, so that $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is an abelian group of order $p^{r-1}(p-1)$. Factor $p-1$ into primes as
$$
p-1 = q_1^{s_1}\dotsb q_t^{s_t}.
$$
We will prove that each Sylow subgroup of $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is cyclic and use the following lemma:

Lemma. Let $G$ be a finite group, and let $P_1,\dots,P_r$ be its nontrivial Sylow subgroups. If each $P_i$ is a normal subgroup of $G$, then
  $$
G \cong P_1\times \dotsb \times P_r.
$$

Since $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is an abelian group, each of its Sylow subgroups is normal, so we will be able to use the Chinese Remainder Theorem (CRT) to conclude that
$$
\big(\Bbb Z\big/p^r\Bbb Z\big)^\times \cong \Bbb Z\big/p^{r-1}\Bbb Z\times \Bbb Z\big/q_1^{s_1}\Bbb Z\times\dotsb\times\Bbb Z\big/q_t^{s_t}\Bbb Z \underbrace{\cong}_\text{CRT} \Bbb Z\big/p^{r-1}q_1^{s_1}\dotsb q_t^{s_t}\Bbb Z,
$$
i.e. that $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is cyclic of order $p^{r-1}q_1^{s_1}\dotsb q_t^{s_t} = p^{r-1}(p-1)$, as desired.
Proof sketch that the Sylow subgroups are cyclic:
First show that the Sylow $p$-subgroup of $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is cyclic as follows. Use the Binomial Theorem and induction on $r$ to show that if $p$ is an odd prime then $(1+p)^{p^{r-1}}\equiv 1\bmod p^r$ but $(1+p)^{p^{r-2}}\not\equiv 1\bmod p^r$. Deduce that $1+p$ is an element of order $p^{r-1}$ in $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$. (Recall that if $g^n = 1$, then the order of $g$ divides $n$.) Now we know that the Sylow $p$-subgroup of $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is cyclic.
Consider the canonical homomorphism $\varphi\colon\big(\Bbb Z\big/p^r\Bbb Z\big)^\times\to \big(\Bbb Z\big/p\Bbb Z\big)^\times$ defined by
$$
a + (p^r)\mapsto a+(p).
$$
Note that $\varphi$ is a surjection, and that it is indeed the map you specified. By the first isomorphism theorem,
$$
\frac{p^{r-1}(p-1)}{|\!\ker\varphi|} = \frac{\big|\big(\Bbb Z\big/p^r\Bbb Z\big)^\times\big|}{|\!\ker\varphi|} = \big|\big(\Bbb Z\big/p\Bbb Z\big)^\times\big|=p-1 \implies |\!\ker\varphi| = p^{r-1},
$$
hence the kernel of $\varphi$ is precisely the Sylow $p$-subgroup of $\big(\Bbb Z/p^r\Bbb Z\big)^\times$. For each prime $q\ne p$ dividing the order of $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$, the Sylow $q$-subgroup of $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ therefore maps injectively into $\big(\Bbb Z\big/p\Bbb Z\big)^\times$ under $\varphi$, and can thereby be identified with a (cyclic) subgroup of the cyclic group $\big(\Bbb Z\big/p\Bbb Z\big)^\times$. Hence we have shown that every Sylow subgroup of $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is cyclic. $\qquad\blacksquare$
Thus, by the lemma, we may write $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ as a direct product of its Sylow subgroups, each of which we know to be cyclic:
$$
\big(\Bbb Z\big/p^r\Bbb Z\big)^\times \cong \Bbb Z\big/p^{r-1}\Bbb Z\times\Bbb Z\big/q_1^{s_1}\Bbb Z\times\dotsb\times\Bbb Z\big/q_t^{s_t}\Bbb Z.
$$
By the Chinese Remainder Theorem, since all the primes $p,q_i$ are distinct, we have
$$
\big(\Bbb Z\big/p^r\Bbb Z\big)^\times \cong \Bbb Z\big/p^{r-1}q_1^{s_1}\dotsb q_t^{s_t}\Bbb Z,
$$
i.e., that $\big(\Bbb Z\big/p^r\Bbb Z\big)^\times$ is cyclic, as desired.
Comment: Where did you use the assumption $p>2$?
Comment: @Pierre-Yves Gaillard If $r\ge 3$, then $(\Bbb Z/2^r\Bbb Z)^\times$ is not cyclic. Indeed, it has two distinct subgroups of order 2. [cf. Dummit and Foote's *Abstract Algebra*, Exercise 23 of Section 2.3]
Comment: @Pierre-YvesGaillard I realize my previous comment doesn't really answer your question. The assumption $p>2$ is needed to show that the order of $1+p$ is $p^{r-1}$ in $G$.
Comment: Very elegant. I have been searching for a proof and I couldn't have found a better one. +1
Answer: This is taken from Alan Baker's A Concise Introduction to the Theory of Numbers.
Let $p$ be an odd prime, and let $g$ be a primitive root ($\operatorname{mod}p$). We prove now that there exists an integer $x$ such that $g':=g+px$ is a primitive root ($\operatorname{mod}p^j$) for all prime powers $p^j$. We have $g^{p-1}=1+py$ for some integer $y$ and so, by the binomial theorem, $g'^{p-1}=1+pz$, where
$$
z\equiv y+(p-1)g^{p-2}x\ (\operatorname{mod}p).
$$
The coefficient of $x$ is not divisible by $p$ and so we can choose $x$ such that $(z,p)=1$. Then $g'$ has the required property. For suppose that $g'$ has order $d\ (\operatorname{mod}p^j)$. Then $d$ divides $\phi(p^j)=p^{j-1}(p-1)$. But $g'$ is a primitive root ($\operatorname{mod}\ p$) and thus $p-1$ divides $d$. Hence $d=p^k(p-1)$ for some $k < j$. Further, since is $p$ odd, we have
$$
(1+pz)^{p^k}=1+p^{k+1}z_k,
$$
where $(z_k,p)=1$. Now since $g'^d\equiv1\ (\operatorname{mod}p^j)$ it follows that $j=k+1$ and this gives $d=\phi(p^j)$, as required.


Implementing an algebraic equation in Base R

Question: I'm new to algebraic equations in R and am trying to implement the following equation in R (below).
However, as precise as I have tried to be, I expect the answer to be 0.050865 but instead I get 11.43653.
I wonder what I am missing as I really can't find any mistakes?
delta_T=0.1522
n=18
NT=324
NC=162
p=0.264
N=NT+NC

V_T2 =  ((NT+NC)/(NT*NC))*(1 + ((n - 1)*p)) +
    ( delta_T^2 * (
      (((N - 2)*(1-p)^2 ) + (n*(N - 2*n)*p^2) +
         (2* (N - 2*n) * p * (1 - p)) ) /
         (2* (N-2)) * ( (N-2) - (2* (n-1)*p) )
    )  )

V_T2

# > [1] 11.43653 BUT I expect the answer to be 0.050865

Comment: Hell is parens and hierarchy of execution, your estimate is correct, and excellent to do prior to a thicket of parens, `(NT + NC) / (NT * NC) `[1] 0.009259259, `(NT + NC) / (NT * NC)*(1 + (n -1)*p) `[1] 0.05081481, `(N-2)*(1-p)^2 + n*(N-2*n)*p^2 + 2*(N - 2*n)*p*(1-p)`
[1] 1001.592, divided by `(2 * (N -2))*((N-2)- 2*(n-1)*p) `[1] 459823.2, `delta_T^2*(1001.592/459823.2)` [1] 5.045791e-05, `(NT + NC) / (NT * NC)*(1 + (n -1)*p) + delta_T^2*(1001.592/459823.2)`
[1] 0.05086527 - my first try at this, before chopping into parts was this [1] 2222.64. So, clearly care required, after estimating.
Comment: Wandering off the path, one might look at `NT + NC / NT * NC ` [1] 405. My parens told me it would come to this.
Answer: The reason you're getting the wrong answer is because, in the second term, you think you're doing
numerator
/
denominator

but what you're actually doing is
numerator
/
(2 * (N - 2))
*
((N - 2) - (2 * (n - 1) * p) )

So, in other words, you were missing parentheses around the denominator.
But, in general, it's helpful to break your code down into intermediate variables, when dealing with complicated equations, so it's easier to debug, and you can do sanity checks on them:
equation <- function(NT, NC, n, p, delta_T) {
    N <- NT + NC
    first_term <- N / (NT * NC) * (1 + ((n - 1) * p))
    numerator <- (N - 2) * (1 - p)^2 + n * (N - 2 * n) * p^2 +
         2 * (N - 2 * n) * p * (1 - p)
    denominator <- 2 * (N-2) * (N - 2 - 2 * (n - 1) * p)
    second_term <- delta_T^2 * (numerator / denominator)
    first_term + second_term
}


Does the set of all fields exist ?

Question: We often say "let F be a field", so I was wondering if we could consider, in ZFC, the set of all fields without some contradictions arising (so that we wouldn't have to use the global axiom of choice in the class of all fields to choose one)
Comment: From the (supposed) set of all fields, or even of all two-element fields, we can produce the "set" of all sets.
Comment: In addition to what @AndréNicolas said, you can think about sizes. If there was a set of all fields, you could also take the union of all fields (as sets), and the cardinality of this union would be an upper bound on the cardinalities of all fields. But there are fields of arbitrarily large cardinalities, a contradiction.
Comment: Some related posts:
http://math.stackexchange.com/questions/21475/what-are-some-examples-of-classes-that-are-not-sets
http://math.stackexchange.com/questions/1259858/why-is-the-collection-of-all-algebraic-extensions-of-f-not-a-set
http://math.stackexchange.com/questions/226413/why-is-the-collection-of-all-groups-considered-a-proper-class-rather-than-a-set
http://math.stackexchange.com/questions/237402/set-of-all-groups
Comment: @AndréNicolas Thanks, that answers my question (since with two elements, it's easy to make operations that would make it a field, imitating Z/2Z. And then the axiom of union would make the set of all sets)
Answer: Exercise: every set is an element of (the underlying set of) some field. (HINT: Given a set $x$, let $y$ be any set other than $x$; now give $\{x, y\}$ a field structure.)
If you believe this, then if $F$ were the set of all fields, $\bigcup F$ would be the set of all sets.
Note that there's nothing special about fields here; the same argument works for

groups,
topological spaces,
rings,
semigroups with exactly 18 elements,
etc.

However, you could ask: "What about up to isomorphism?" That is, is there a set $S$ of fields such that every field is isomorphic to an element of $S$?
Here, the argument above doesn't work, but the answer is still "no" - for $\kappa$ a cardinal, let $F_\kappa$ be a field gotten by adjoining $\kappa$-many transcendentals to $\mathbb{Q}$. This shows that $S$ has to contain sets of arbitrarily large cardinality, which in turn (exercise) can be used to build the set of all ordinals, violating the Burali-Forti paradox.
Again, this same argument can be applied to practically any kind of structure.
However, note that the set of fields with a fixed underlying set does exist (powerset + separation), and therefore so do sets containing (up to isomorphism) every field of size $<\kappa$ for any fixed $\kappa$.
Comment: (just a comment, related to the last paragraph): If we restrict to ordered fields, there are also the Surreal numbers Field (and the isomorphic maximal hyperreals Field) which contain all possible ordered fields as subfields. (Field instead of field because they are classes, not sets). See: [Surreals](https://en.wikipedia.org/wiki/Surreal_number)
Answer: Check out the Lowenheim-Skolem theorem. It states that, since the first order theory of fields is countable and has an infinite model (i.e. An infinite set exists that satisfies the theory), it must have an infinite model of every cardinality. This implies that the "set" of all fields is a proper class, since there exists at least one field of every cardinality and the "set" of all cardinal numbers is a proper class.

Does the set of all fields exist ?


Cocoa error 134030 when saving core data after database migration

Question: In the next version of my app I made a few changes to my core data model.  I made them on a new version of the model.  The changes are simple table and row additions.  I have my persistence store configured to automatically update the tables with NSMigratePersistentStoresAutomaticallyOption and NSInferMappingModelAutomaticallyOption.  This is the 6th update to my Core Data model so it has worked in the past.  When the app updates from the database from the pervious version I get the following error on the first time I try to save the NSManagedObjectContext.
2014-06-05 06:13:31.944 Topo Maps[4862:60b] Unresolved error The operation couldn't be completed. (Cocoa error 134030.)

I have looked at a lot of posts and comments about error 134030 and they all seem to be around not being able to delete an object or around not being able to update an object that was never inserted.  I am pretty sure neither of those are happening in my app.  When the app first starts up I set a string value on a core data object, then save the managed context, and that is when I get this error.
In the past when I had issues with getting the persistence store to upgrade I would get errors when trying to initialize a persistence store with my managed object model.
Any help would be greatly appreciated.
Thanks!!
Answer: Ok so I found out what is going wrong.  I feel like an idiot.  I wasn't printing out all of the data in the NSError.  It turns out that it was from updating an object that was never inserted.  My app saves a URI for the last used object and it was that URI that was causing the problems.  So it was actually not a database migration issue.  It was an issue with how the new version of my app handled the URI in settings.


Example of a topological space $X$ such that $C_0 (X)$ is not a $C^*$-sub-algebra of $C^b (X)$

Question: Let $X$ be an arbitrary topological space. If $X$ is locally compact and Hausdorff, then $C_0 (X)$ (space of continuous functions vanishing at infinity) is a $C^*$-sub-algebra of $C^b (X)$ (space of all bounded continuous functions).
Now, my question is how necessary these conditions "locally compact" and "Hausdorff" are for the above statement to be true.
If we take $X= \mathscr{H}$, an infinite dimensional Hilbert space, and consider the closed unit ball $B(0,1)\subset \mathscr{H}$, then the following function $$f(x)= \frac{1}{||x||},\, x\in B(0,1)^c\\
=1,\,x\in B(0,1)$$
is in $C^b (X)$, but not in $C_0 (X)$.
But it merely shows the proper containment of $C_0 (X)$ in $C^b (X)$. I think it is a right direction, but really I am confused here. I actually need an example of a topological space $X$ such that $C_0 (X)$ is not a $C^*$-sub-algebra of $C^b (X)$.
Thank you.
Answer: For any topological space $X$,  whatsoever,  one has that $C_0(X)\subseteq C^b(X)$.  This is because if  $f$ is in $C_0(X)$ then
$f$ is:

continuous by definition,

bounded because,  given any $\varepsilon >0$,  say $\varepsilon =1$,  there exists a compact set $K\subseteq X$ such that $|f(x)|<\varepsilon $ for
all $x\in X\setminus K$. In particular $f$ is bounded on $X\setminus K$,  and it is also clearly bounded on $K$ because $K$ is compact.

Even though what follows has no bearing on the question itself, it should be remarked that $C_0(X)$ might be very very small for certain choices of $X$.  This is because if $f$ lies in $C_0(X)$,  then
$$
  \{x∈ X: |f(x)|>ε\}
  $$
is a relatively compact open set, but some topological spaces, such as
infinite dimensonal normed spaces,  have no nonempty sets with these properties.  In this case one would therefore have that $C_0(X) = \{0\}$.
Answer: As Eric Wofsey noted here, $C_0(X)$ is still a $C^\ast$ algebra for any $X$.
In the development of a useful theory it is quite important that $X$ be locally compact Hausdorff because this ensures that we have enough functions in $C_0(X)$ to be useful, e.g. if we only assume $X$ to be some $T_3$ topological space, it could happen that $C(X)$ only contains constant functions so is just $\mathbb R$ essentially and $C_0(X)$ would only be $\{0\}$. So in order to be able to prove useful facts in$C^\ast$-algebras conditions on $X$ have to be imposed. Local compactness plus Hausdorff ensures enough functions and the existence of a one-point compactification that allows us sometimes to switch (to understand $C_0(X)$) to the classical best-understood case of $C(\alpha X)$ for $\alpha X$ compact Hausdorff (which has nice duality theorems etc.)


Find and prove a formula for $\|u\|$ where $u = [\sqrt 1, \sqrt 2, \sqrt 3, \ldots, \sqrt n]^T$.

Question: I tried using induction:
Let $x =[\sqrt 1, \sqrt 2]$. Then by Pythagoras $\|x\| = \sqrt 3$.
Suppose $\|u\|$ is defined for $u$ in $\mathbb R^{\sqrt n}$. Then $\|u\| = \sqrt{1 + 2 + 3 + … + n}$.  Since the length is defined for $\mathbb R^2$, $\|y\| = \sqrt{(1 + 2 + 3 + … + n) + (n + 1)}$ is well-defined. But that's the length of $u$.
Please, check and see what I need to do to fix/improve it. Thanks.
edit:
$u \in \mathbb R^n.$
Length in $\mathbb R^2$ is given by Pythagoras.
$\|u\|$ is well-defined by definition of length.
Comment: It seems like you have the main idea (i.e. the expression for $\|u\|$), but a lot of what you've written doesn't make sense.  What is $\Bbb R^{\sqrt n}$?  What do you mean by "suppose $\|u\|$ is defined"?  What do you mean by "since length is defined for $\Bbb R^2$?"  What do you mean by $\|y\| = \cdots$ "is well-defined"?  It reads like a mathematical word salad.
Comment: $u$ in $\mathbb R^{\sqrt n}$? – The length/dimension of the vector $u$ is $n$, not $\sqrt n$.
Comment: I edited my OP.
Comment: See also: http://math.stackexchange.com/questions/2260/proof-for-formula-for-sum-of-sequence-123-ldotsn
Answer: \begin{align}
\lVert u \rVert^2
= \lVert u \rVert_2^2
&= \sum_{i=1}^n u_i^2 \\
&= \sum_{i=1}^n (\sqrt{i})^2 \\
&= \sum_{i=1}^n i \\
&\overset{(*)}{=} \frac{n(n+1)}{2}
\end{align}
So we get
$$
\lVert u \rVert = \sqrt{\frac{n(n+1)}{2}}
$$
Comment: Thank you. How can I redo it by induction?
Comment: You might prove that equation $(*)$ for the sum of the first $n$ numbers by induction.
Comment: This is perfect. I see the whole picture now. Thanks.
Comment: I forgot to ask: what does the subscript $2$ mean in $\|u\|^2_2$?
Comment: There is a family of norms called $p$-norm: $\lVert u \rVert_p = (\sum u_i^p)^{1/p}$. The Euclidean norm is the case $p = 2$.


Non-homogeneous Burgers' equation $u_t + u u_x = -\sin x$

Question: While studying for an exam, I found this question from a previous exam:

Consider the forced Burgers' equation for $u(x,t)$ on the periodic domain $x \in [-\pi, \pi]$.
$$u_t + uu_x = -\sin(x)$$
(a) Show that the equation conserves total mass $M = \int_{-\pi}^{\pi} u(x,t)\,dx$.
(b) Find explicitly the smooth steady solutions.  Show that for these solutions $|M| > C$, and find the constant $C$.  Show that the limiting solution when $|M| = C$ has a "corner" at $x = \pi$.

So part (a) was pretty straight forward after integrating with respect to $x$ from $[-\pi,\pi]$.  I'm stuck on part (b).  Maybe I'm not sure what they mean by steady state solution?  Does it mean that $u_t = 0$?  Otherwise, I've tried:
Let $z(t) = u(x(t),t)$, so $z'(t) = x'(t)u_x + u_t = -\sin(x)$ provided that $x'(t) = u(x(t),t)$.  So I have a system:
$$z'(t) = -\sin(x(t))$$
$$x'(t) = u(x(t),t) = z(t)$$
From these we can conclude:
$$x''(t) + \sin(x(t)) = 0 $$
Which is an ODE you get when studying pendulums, and possibly a bit to complicated for this problem.  The corresponding ODE for $z$ was even worse.
Answer:
steady state solution? Does it mean that $u_t=0$?

Yes, this is exactly what it means. The equation simplifies to $(u^2)_x=-2\sin x$, which integrates to $u=\pm \sqrt{2\cos x+B}$ for some constant $B$. For this to make sense, we need $B\ge 2$. This leads to a lower bound on $\int |u|$, attained when $B=2$.

Show that the limiting solution when $|M|=C$ has a "corner" at $x=\pi$.

Indeed, because when $B=2$, the expression under the square root drops to $0$ at $\pm \pi$. The solution in this case is $\sqrt{2(1+\cos x)}=4\cos (x/2)$, $|x|\le \pi$, if I got trigonometry right.


Why does this grep command throws error?

Question: If I use this command it works as I need:
grep -o -e "{{ *[-_[:alnum:]]\+"

But if I use this one it throws error
grep -o -e "{{ *[_-[:alnum:]]\+"

Same as this one:
grep -o -e "{{ *[[:alnum:]-_]\+"

And this other:
grep -o -e "{{ *[[:alnum:]-\_]\+"

Seems that the [] from the RegExp can't start nor end with _
Why?
Error is:

grep: Invalid range end
Answer: The error is related to the hypen -: 0-9 means 0123456789. But what is the meaning of _-[:alnum:]? Putting - as the first character disables this special meaning, so the first regexp works as expected.
Comment: Strange, I thought you could omit the problem by escaping the `-` (works in Perl), but no matter how many backslashes I prepend it with, the error persists, even with `grep -E`. Tested with GNU grep 2.5.3.
Comment: yeah it must be that, I didn't realised. Thanks for asnwering!


Find series power of $F(x) =e^{-x}x^{2}$

Question: i need help for this problem; find  a power series for $F(x) \text{=}e^{-x}x^{2} $ and derivate and prove this expression  $$ \sum \limits^{\infty }_{n=1}\frac{(-2)^{n+1}(n+2)}{n!} =\text{4}$$
Comment: What part of the question are you struggling with?
Answer: For $f(x) = x^{2} \, e^{-x}$
\begin{align}
f(x) = x^{2} \, \sum_{n=0}^{\infty} \frac{(-1)^{n} \, x^{n}}{n!} = \sum_{n=0}^{\infty} \frac{(-1)^{n} \, x^{n+2}}{n!}.
\end{align}
Differentiation leads to
\begin{align}
f'(x) = (2 - x) \, x \, e^{-x} = \sum_{n=0}^{\infty} \frac{(-1)^{n} \, (n+2) \, x^{n+1}}{n!}
\end{align}
Now let $x = 2$ to obtain
\begin{align}
\sum_{n=0}^{\infty} \frac{(-2)^{n} \, (n+2)}{n!} = 0
\end{align}
or, by shifting the first term to the right hand side,
\begin{align}
\sum_{n=1}^{\infty} \frac{(-2)^{n} \, (n+2)}{n!} = -2.
\end{align}
Multiply both sides by $-2$ to obtain
\begin{align}
\sum_{n=1}^{\infty} \frac{(-2)^{n+1} \, (n+2)}{n!} = 4.
\end{align}
Comment: Tank you i very appreciate .
Comment: It seems that you treated $x^2 e^x$ and not $x^2 e^{-x}$
Comment: @ClaudeLeibovici  All is better now.


Is it possible to display an CALayer without an UIView?

Question: As far as I can tell, I need an UIView (or subclass of UIView) to display an CALayer on screen, right?
Then, what's the point of using CALayer for saving memory? The only point I see is when I would add several sublayers to a CALayer. Then those sublayers would not get copied 3 times for all the different tree types like presentation tree, render tree and so on. Is that right?
Answer: You can add CALayers as sublayers of another CALayer. Each individual layer does not have to be backed by a view, but the root layer in the hierarchy must be backed by a UIView.
The point is not to avoid having copies of the CALayers, which are quite lightweight, but to avoid having copies of UIViews or, more specifically, the graphics contexts that back UIViews. Those take up considerably more memory.
Comment: Actually, I don't believe that UIViews take up much more memory than a CALayer does.  On the Mac, NSViews certainly are a lot heavier than CALayers, but UIViews are much more lightweight.  In my performance testing, CALayers only come out slightly ahead of UIViews when rendering, and I didn't see much of a difference in memory footprint.
Comment: Good to know. I had assumed UIViews suffer from the same limitations as NSViews.


Why Input string was not in a correct format and exception was unhandled

Question: I am getting an error while taking array input from the user.
    static void Main(string[] args)
    {

        int[] arrSum = new int[] { };
        Console.WriteLine("Enter the array Size:\t");
        int n = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
        for (int i = 0; i < n; i++)
        {
           arrSum[i] = int.TryParse(Console.ReadLine(), out arrSum[]);
        }

        Console.WriteLine("Enter the number whose sum you want to find:\n");
        int j = Convert.ToInt32(Console.ReadLine());
        ArraySum(arrSum,n,j);

    }

    public static int ArraySum(int[] arr, int key, int n)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            int first = arr[i];

            for (int k = i+1; k < arr.Length; k++)
            {
                int second = arr[k];
                while (first + second == key)
                {
                    Console.WriteLine("The numbers whose sum is {0}" + key + "are:\n" + first + second);
                }

                if (first + second != key)
                {
                    return -1;
                }
                else
                {
                    return 1;
                }
            }
        }
        return 0;
    }

To take array size and elements and the number whose sum we need to compare among the given array elements from the user as input and return the possible pairs whose sum is equal to the given number.
Comment: `arrSum[i] = int.TryParse(Console.ReadLine(), out arrSum[]);` That line compiles fine for you? I can't see how it could. https://dotnetfiddle.net/asdIbc
Comment: Does the answer helped?
Answer: I am not sure if I met the same problem as you, but I modified your code as following. At first I created a safe console readline method for integer that there is no exception thrown if an invalid integer is entered:
 private static int GetIntFromInput()
    {
        while (true)
        {
            string value = Console.ReadLine();
            if (!int.TryParse(value, out int parsedInt))
            {
                Console.WriteLine("Invalid integer! Retry or Ctrl+C to abort program...");
                continue;
            }

            return parsedInt;
        }
    }

Then I modified your first method as following:
static void Main(string[] args)
    {
        Console.WriteLine("Enter the array Size:\t");
        int n = GetIntFromInput();
        if (n <= 0)
        {
            Console.WriteLine("Array has to be at least of size 1...");
            return;
        }

        Console.WriteLine("Enter the array elements of {0} as Array Size:\n", n);

        var arrSum = new int[n];
        for (int i = 0; i < n; i++)
        {
            int newInt = GetIntFromInput();
            arrSum[i] = newInt;
        }

        Console.WriteLine("Enter the number whose sum you want to find:\n");
        int j = Convert.ToInt32(Console.ReadLine());
        ArraySum(arrSum, n, j);
    }

With this my tests had been successful. Please note, that I did not replace the last Convert.ToInt32 for j.
As a note, please always verify user input as far as possible for not throwing exceptions. If anytime you will check anything not correctly it will crash sometime for sure...
have a great day!
Answer: I just have modified your array input code lines, pretty much straight forward. You can use int.TryParse as well just in case you wish to have a check
Console.WriteLine("Enter the array Size:\t");
int n = Convert.ToInt32(Console.ReadLine());
int[] arrSum = new int[n];
Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
for(int i = 0;i<n;i++){
    arrSum[i]= Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum,n,j);


React Filtering Data with Hooks

Question: I'm working with a dataset and want to implement a filtering option to only display what is selected (as filters do :) ). Here's the data and my code so far:
// Movies data =
[
 {
   name: "a",
   genre: "comedy",
   year: "2019",
 },
 {
   name: "b",
   genre: "drama",
   year: "2019",
 },
 {
   name: "c",
   genre: "suspense",
   year: "2020",
 },
 {
   name: "d",
   genre: "comedy",
   year: "2020",
 },
 {
   name: "e",
   genre: "drama",
   year: "2021",
 },
 {
   name: "f",
   genre: "action",
   year: "2021",
 },
 {
   name: "g",
   genre: "action",
   year: "2022",
 },
]

and in my code, I'm have a piece of state for the API response (all data) as well as filtered data per year
import { useEffect, useState, useMemo } from 'react';

const MovieData = () => {
  const [movies, setMovies] = useState([]); // all data. This will not change after API call
  const [results setResults] = useState([]); // this will change based on selection
  const [year, setYear] = useState({
    y2019: false,
    y2020: false,
    y2021: false
  });

  // making API call
  useEffect(() => {
    fetch("myapiep")
    .then(response => response.json())
    .then(data => setMovies(data))
  }, []);

  // get subsets of data
  const {m2019, m2020, m2021} = useMemo(() => {
    const m2019 = movies.filter(m => m.year === '2019');
    const m2020 = movies.filter(m => m.year === '2020');
    const m2021 = movies.filter(m => m.year === '2021');

    return {m2019, m2020, m2021}
  });

  // So far so good. Now this is where things get tricky for me
  // I want to, based on the selection, modify my results array
  useEffect(() => {
    // update results based on movie year selected
    if (year.y2019) setResults([...results, ...m2019]);
    // HELP: filter out results when year is unselected
    // this is not working
    else {
      const newArr = results.filter((movie) => !m2019.includes(movie));
    }
    if (year.y2020) setResults([...results, ...m2020]);
    else {
      const newArr = results.filter((movie) => !m2020.includes(movie));
    }
    if (year.y2021) setResults([...results, ...m2021]);
    else {
      const newArr = results.filter((movie) => !m2021.includes(movie));
    }
    // if none are selected, just return all movies
    if (!year.y2019 && !year.y2020 && !year.y2021) {
      setResults(movies);
    }
  }, [year]);

  // I'm suppressing the logic to toggle years (y20xx) true/false for simplicity, but can add it if folks judge necessary

  return (

      {results.map((movie) => (
          <Movie
            key={uuidv4()}
            name={movie.name}
            genre={movie.genre}
            year={movie.year}
          />
        ))}

  )
}

What works: set filter works, for instance, setting the filter to movies made in 2019 returns
[
 {
   name: "a",
   genre: "comedy",
   year: "2019",
 },
 {
   name: "b",
   genre: "drama",
   year: "2019",
 },
]

What doesn't: unset the filter.
Comment: What's not working exactly? Expect/actual output is helpful. I also suggest removing the request for general remarks -- it's off-topic. Thanks.
Answer: The below code snippet achieves the necessary logic (sans the React Hooks, API, and other items):

const movies = [{
    name: "a",
    genre: "comedy",
    year: "2019",
  },
  {
    name: "b",
    genre: "drama",
    year: "2019",
  },
  {
    name: "c",
    genre: "suspense",
    year: "2020",
  },
  {
    name: "d",
    genre: "comedy",
    year: "2020",
  },
  {
    name: "e",
    genre: "drama",
    year: "2021",
  },
  {
    name: "f",
    genre: "action",
    year: "2021",
  },
  {
    name: "g",
    genre: "action",
    year: "2022",
  }
];

const filterMyMovies = (byField = 'year', value = '2020', myMovies = movies) => (
  (myMovies || [])
  .filter(mov => !byField || !mov[byField] || mov[byField] === value)
);

console.log('movies in year 2020:\n', filterMyMovies());
console.log('movies in year 2019:\n', filterMyMovies('year', '2019'));
console.log('movies in genre drama:\n', filterMyMovies('genre', 'drama'));
console.log('movies with name d:\n', filterMyMovies('name', 'd'));
console.log('movies with NO FILTER:\n', filterMyMovies(null, null));

Explanation
Fairly-straightforward filtering of an array of objects, with only 1 column & 1 value. May be improvised for multi-column & multi-value filtering.
How to use this
The way to use this within React-Hooks is to invoke the 'filterMyMovies' method with the appropriate parameters when the filter-criteria changes. Suppose, the year is set to 'no-filter', then simply make call to the 'filterMyMovies' method  with the first & second params as null.
Suppose we need to filter by year and then by genre as well, try something like this:
filterMyMovies('genre', 'comedy', filterMyMovies('year', '2019'));

This will return 2019 comedy movies.

React Filtering Data with Hooks


Module not found when using gunicorn (Python, Flask)

Question: I am attempting to convert my Flask application to using a gunicorn server. Since I am using a Windows laptop, I have to deploy my app to Docker to test with gunicorn. The problem is, whenever I try to run the container, I get this error:
File "/service/app/server.py", line 4, in
import db
ModuleNotFoundError: No module named 'db'
The import statement in server.py for db.py doesn't work, even though they're in the same directory and it works when I am not using gunicorn.
Here is part of my dockerfile:
WORKDIR /app
CMD ["gunicorn", "--workers=3", "server:main"]

and my project structure:
\service
   \app
      server.py
      db.py

I tried to change the working directory in my dockerfile but it doesn't work.
Comment: before importing the db in your script, append the current path using `sys.path.append('.')`
Comment: I don't see how `WORKDIR /app` works, since you said the actual folder layout is `/service/app`
Comment: There's not enough information here for us to answer the question. How are you installing requirements in your Dockerfile? How are you copying your code into the image?
Comment: FROM python-image
ENV PYTHONUNBUFFERED=1
ENV DISABLE_COLLECTSTATIC=1
USER root
COPY . /service
WORKDIR /service
RUN python -m pip install --upgrade pip
RUN pip install --upgrade setuptools
RUN pip install -r requirements.txt
WORKDIR /app
CMD ["gunicorn", "--workers=3", "server:main"]
Answer: I think you should run this command:
CMD ["gunicorn", "--workers=3", "server:app"]


Relative variances of higher-order vs. lower-order random terms in mixed models

Question: TL, DR summary:
Is there any theoretical or empirical basis to support the following statement being true as a general rule of thumb?
"When estimating a mixed model, typically the estimated variances/standard deviations of random effects associated with 'higher-order' terms (e.g., random effects of two-way, three-way, and beyond interaction terms) turn out to be smaller than the estimated variances/standard deviations of random effects associated with 'lower-order' terms (e.g., the residual variance, variances associated with simple effects of grouping factors)."
The source of this claim is me. ;)

Okay, now for the longer version ...
Typically when I sit down to start analyzing a new dataset which I know will call for a mixed model, one of the first models that I fit (after the statistical foreplay of looking through the observations in the dataset, plotting various things, cross-tabulating different factors, etc.) is one that is pretty close to the "maximal" random effects specification, where every random effect that is in-principle possible to estimate from the data, is estimated.
Naturally, it is not uncommon that this nearly-maximal model will have some computational problems (convergence errors, or wacky variance/covariance estimates, or etc.) and that I have to trim back this model to find one that my data can more easily support. Fine.
In these situations, the method I have come to prefer for trimming random terms is not to rely on significance tests or likelihood ratios, but rather to just identify the random effects that seem to have the smallest standard deviations (which can admittedly be a little tricky when predictors are on very different scales, but I try to take account of this in my appraisal) and remove these terms first, sequentially in an iterative process. The idea being that I want to alter the predictions of the model as little as possible while still reducing the complexity of the model.
One pattern that I seem to have noticed after a pretty good amount of time spent doing this is that following this method very often leads me to trim random effects associated with higher-order terms (as defined above) of the model first. This is not always true, and occasionally some of the higher-order terms explain a lot of variance, but this doesn't seem to be the general pattern. In sharp contrast, I usually find that lower-order random terms -- particularly those associated with simple effects of the grouping factors -- explain a pretty good amount of variance and are fairly essential to the model. At the extreme, the residual term commonly accounts for close to the most variance, although of course removing this term wouldn't be sensible.
This entirely informal observation leads me to form the hypothesis that I stated at the beginning of this question.
If it is true, then it constitutes a useful piece of advice that might be passed down to people who are less experience with this kind of model selection process. But before I begin doing so, I want to check with other, more experienced users of mixed models about their reactions to this observation. Does it seem more or less true to you? Is it roughly consistent with your experience fitting many different mixed models to many different datasets? Do you know of any sensible, theoretical reasons why we might actually expect this to be true in a lot of cases? Or does it just seem like bullshit?
One possible answer here is that it is not true even in my own case, and I have simply deceived myself. Certainly a possibility that I am open to.
Another possibility is that it might be true in my own case, but that this could simply be a kind of coincidence having to do with the kinds of datasets that I tend to work with routinely (which, FYI, are datasets in psychological / social sciences, a slight majority being experimental in origin, but also a fair proportion of non-experimental stuff). If this is the case then there is probably no good reason for expecting my observations to hold in general in other fields that handle very different kinds of data. Still, if there is a coherent non-coincidental reason for why this might be expected to be true, even if only for these particular kinds of datasets, I would love to hear it.
And of course another possibility is that others have noticed similar patterns in their own data, and that it represents some kind of general rule of thumb that people find useful to keep in mind as they fit mixed models to various different data. If this is the case then it seems like there must be some compelling statistical-theoretical reason for why this pattern arises. But I really don't know what that reason would look like.
I welcome anyone's thoughts and opinions about this. Note that as far as I'm concerned, totally legitimate responses to this question might be as simple as comments like "Yeah I have noticed something similar in the data I've worked with, but I have no idea why it should be true" or conversely "I have noticed nothing remotely like this in the data I've worked with." Of course I also welcome longer and more involved discussions ...
Comment: I don't think you are deceiving yourself. I believe that what you are looking at is to be expected as "*simple grouping factors*" are more probable to actually have a real influence on your data than some contrived hierarchical grouping with random slopes etc. This "higher variance" makes sense also because the "finer your grouping becomes" the more probable it is that numerically you are going to fit that variation as "residual variation" (let alone real noise corruption). I am slightly worried/puzzled by your "*the residual term commonly accounts for close to the most variance*" phrase...
Comment: On another note: In general I am not a huge fun of the *random-effect selection* idea. I believe that this is primarily a design question and doing extensive testing on random effects doesn't makes much sense but rather partially beats the whole idea of a r.e. structure. I am not saying what you are doing is wrong: I would most probably do the exact same things (probably adding bootstrap on that test mix) if I had to answer the "pick the r.e. structure" question; just that I don't "endorse its message"!
Comment: This sounds like you actually have an additional layer in the mixed model hierarchy.  usually you have that $u_{(jk)}|\sigma_{jk}\sim N(0,\sigma_{jk}^2)$   where jk means the jth random effect of order k.  you then have that $\sigma_{jk}\sim f (\phi_k)$ for some distribution f.  This weakly constrains the variances of the same order to be similar in size.
Answer: I have discovered that the regularity I described in my question has in fact been written about by several authors in the literature on Design of Experiments (DoE). It has been called the "hierarchical ordering principle" and also sometimes the "sparsity-of-effects principle."
In the chapter on fractional factorial designs in Montgomery (2013, p. 290), he writes:

The successful use of fractional factorial designs is based on three key ideas:

The sparsity of effects principle. When there are several variables, the system or process is likely to be driven primarily by some of the main effects and low-order interactions.

...

Wu & Hamada (2000, p. 143) instead call this the "hierarchical ordering principle", and use the phrase "sparsity of effects" to refer to a related but distinct observation:

Three fundamental principles for factorial effects:
Hierarchical ordering principle: (i) Lower order effects are more likely to be important than higher order effects, (ii) effects of the same order are likely to be equally important .
Effect sparsity principle: The number of relatively important effects in a factorial experiment is small.
...

Li, Sudarsanam, & Frey (2006, p. 34) give two possible explanations for why hierarchical ordering should tend to occur. First they suggest that it is "partly due to the range over which experimenters typically explore factors":

In the limit that experimenters explore small changes in factors and to the degree that systems exhibit continuity of responses and their derivatives, linear effects of factors tend to dominate. Therefore, to the extent that hierarchical ordering is common in experimentation, it is due to the fact that many experiments are conducted for the purpose of minor refinement rather than broad-scale exploration

They next suggest that it is "partly determined by the ability of experimenters to transform the inputs and outputs of the system to obtain a parsimonious description of system behavior":

For example, it is well known to aeronautical engineers that the lift and drag of wings is more simply described as a function of wing area and aspect ratio than by wing span and chord. Therefore, when conducting experiments to guide wing design, engineers are likely to use the product of span and chord (wing area) and the ratio of span and chord (the aspect ratio) as the independent variables

References

Li, X., Sudarsanam, N., & Frey, D. D. (2006). Regularities in data from factorial experiments. Complexity, 11(5), 32-45.
Montgomery, D. C. (2013). Design and analysis of experiments (Vol. 8). New York: Wiley.
Wu, C. J., & Hamada, M. S. (2000). Experiments: planning, analysis, and optimization (Vol. 552). John Wiley & Sons.
Answer:
Blockquote

In general, I agree with the original hypotheses that higher-order terms are often associated with smaller variances.  But, this also depends on the type of data.
In plant breeding, a rule of thumb (Gauch, 1996, page 90) for multi-environment trials is that the variation in the data is:
70% location,
20% location-by-variety,
10% variety
Very approximate, but it is fairly consistent that the higher-order term "location-by-variety" variance is larger than the main-effect "variety" variance.
Ref: H G Gauch and R W Zobel, 1996.  Book: Genotype by Environment Interaction. Chapter: AMMI analysis of yield trials. CRC Press.
Comment: Thanks Kevin. I think it is very interesting that such a well-articulated rule of thumb exists in any experimental field. Do you have a citation or two to papers in plant breeding that discuss this rule of thumb? I'd be interested to see where it comes from.


What is an effect that changes one parameter depending on the rate of change of another parameter?

Question: Read my comment before you vote to close.
Is there an effect/vst plugin/flow that measures the rate of change of one parameter of a sound, e.g. volume, and can use that to change the amount of another parameter? (in what I'm currently working on, it would be changing the volume.)
Context: I'm trying to make something that sounds like a guitar volume swell (see this question for explanation), but through a digital effect
Comment: I don't think this belongs on here at all, it belongs on dsp.stackexchange.com . Secondly - I think you mean an Envelope Follower. Google it.
Comment: Instead of instructing everyone to go through the extra work of reading the comments, which can be deleted in time, how about just updating your question to clarify. As mentioned in my own comment, that's what is needed. I'd retract my close vote once the question is sufficiently clear.
Comment: @Tetsujin Doesn't an envelope follower measure another parameter, rather than the rate of change of that parameter? (of course the former may actually be what the OP wants).
Comment: @Tetsujin I think this would be a dsp question if I was asking technical signal processing questions, but I think I'm just asking if a certain musical tool exists. Why I'm talking about rate of change is that's how you measure attack, it's when volume increases quickly. Googled the envelope follower, and I think it's just what I need. Thanks! Probably not ideal in all circumstances, but for this guitar thing it's good.
Comment: My suggestion would be at least to update to reflect answers to topoReinstateMonica's questions.
Comment: @ToddWilcox at the time I vtc'd & suggested dsp, we didn't know quite what was being asked for. The 'vst plugin' bit was added well after that. Most of the clarification of use-case is still only in comments.
Comment: A couple of questions: 1) I've not heard about an existing effect that measures the rate of change of a particular aspect of sound, but if you're making a digital algorithm yourself, wouldn't it be within your power to create it? 2) It's not clear to me why to make something that sounds like a guitar volume swell, you'd need to measure the rate of a particular aspect of sound..?
Comment: Depending on what DAW you are using, you can probably chain limiters and compressors and noise gates achieve some kind of effect, although there are probably better ways to achieve the swelling effect you so seek
Comment: an env follower at its most basic uses in effect a gate with a variable attack [the violining thing], but added to that is often a filter, based on level. It's 'one parameter triggers another'. Another description would be 'side chaining'. I'm not really sure quite what the OP is after, whether it's some poorly-defined DAW effect plugin, or a DIY project for live guitar.
Comment: @topoReinstateMonica, yes, envelope filter... and gated reverb, see my answer.
Comment: I'm voting to close this question because I agree this likely belongs on dsp.SE, but the comments make clear that at minimum it needs an update to clarify the issue.
Comment: @Aaron Signal processing is not about musical effects in DAWs. I don't imagine it's primarily people who use DAWs and know about plugins that browse there. This question is me seeing if a musical tool exists, not having a technical dsp discussion.
Comment: @Aaron I don't see how it's unclear, other than the word "effect".
Comment: Why would this be a fit at DSP when the D in DSP stands for digital and the top voted answer here is about analog electronics? I'm completely lost on why this question is closed. Aside from that digital effects are on topic here. One of my more popular Q and As is about digital reverbs.
Answer: An envelope follower uses the volume from a sound to generate an envelope signal which can then be used to control a parameter of an effect. The most popular use for an envelope follower is to control a filter to create an auto-wah effect, but there are envelope followers that feature output of the envelope signal itself to be used to control other effects.
That said, for the end result you're looking for, I would also explore expanders and compressors. They react to volume changes with other volume changes. You could say they are envelope following effects that use the envelope to control volume. So if you can find the right time constants you should be able to make a swell.
Comment: Another potentially interesting one could be a _slew limiter_, which limits the rate of change and can change a rapid step into a smooth curve, and for example make a glide/glissando from stepped pitch changes. These are available as physical/analog components for modular synths as well. And a very interesting thing to look at is Electro-Harmonix Attack Decay pedal https://www.ehx.com/products/attack-decay/  ... which might do what the OP wants. Or the EHX Superego+ pedal https://www.ehx.com/products/superego-plus/
Answer: The one that comes to my mind, that is an actual, common effect, is gated reverb.
It's combination of noise gate and reverb. I don't really know the sound engineering of it beyond a summary. The noise gate part is based on amplitude (volume.) When the amplitude goes up high, like hitting snare drum, the reverb is applied, then when the amplitude drops down, the reverb is shut off. It's a famous effect from the 1980's applied on the snare drum for a big, fat, wet snare sound.
So, gated reverb is an amplitude parameter changing the reverb parameter.
I think envelope filters do the same thing, but with different output. They take amplitude as input (how hard you play) then change some other effect, like tone.
I imagine envelope filter would be the effect model for you to consider with your volume swell idea. Or, if you haven't looked at envelope filters before, check them out first. You may find something that already does what you're looking for.
Comment: Gated reverb at its most basic, original form [Peter Gabriel/Phil Collins/Hugh Padgham], is  literally just a gate applied to the ambient mics. They open when it's loud & close when it's quiet. First ever appearance, Peter Gabriel's The Intruder.


Incrementing value in a hash

Question: I want to increment the value of the first item by one.  I do not understand why my code is not working
puts sales_hash
sales_hash.values[0] = sales_hash.values[0] +1
puts sales_hash

I am adding 1 to the first value in sales_hash.  When I print out the sales_hash the first value remains the same.  What am I doing wrong?
Comment: Perhaps you want: `h => {:a=>1, :b=>2}; h[h.keys.first] += 1; h #=> {:a=>2, :b=>2}`. It's unusual to use the ordering of a hash's keys used in this way, but you can do it.
Answer: When you use Hash#values you receive an array that contains a copy of all the values in the hash. Therefor, your assignment does not change the hash itself but rather the array containing the values.
Moreover, you should be aware the elements in the hash are ordered by the order of their key's insertion, which might cause unexpected results if you access a certain "position" in the hash since insertions and deletions may change the order of the hash.
If you want to update a value in the hash, you should access it using it's key, for example: sales_hash[:my_sale] = sales_hash[:my_sale] +1
Comment: *Hashes enumerate their values in the order that the corresponding keys were inserted.*--But that issue is totally irrelevant to the op's problem.
Comment: @7stud thank you, I have updated the answer to state that more clearly. I believe it is relevant as the OP is attempting to modify a hash by position instead of by key.
Comment: The OP did not say he/she knows what is the first key.
Comment: Or sales_hash[:my_sale] += 1

Incrementing value in a hash


Javascript and DOM - insertBefore Only Excutes Once

Question: I have a simple script that copies a table row to a global javascript variable (I know using global variables are not a great idea in javascript, but this is only for development) and a function that inserts a copy of the row on an "onClick" event.
It executes and inserts a row. The problem is that it will only insert a row ONCE.
Here is a sample table

            Sample Cell

            Insert Row

Here is my sample javascript:

I'm stumped
Answer: You should clone the node each time the insertRow function is called, so that you get a new copy of element instead recycling the one cloned row.
copy_row = document.getElementByID('copyRow'); //Runs when page first runs

function insertRow(insertRow, insertBeforeMe){
 insertBeforeMe.parentNode.insertBefore(insertRow.cloneNode(true), insertBeforeMe)
}

Comment: That fixed it! Thank you. Do you have any idea why recycling the object would cause the script to fail?
Comment: You're welcome. I think recycling (inserting the same element again) will in effect remove the element from it's current parent, and insert it again to a different place (or maybe to exactly the same place, in your case). It will not get automatically copied/duplicated, so you are handling (removing and inserting) the same single element instance all the time. You need the cloneNode at proper place to create new rows/elements.
Comment: Ah! That makes perfect sense. Thank you.
Answer: It shouldn't even run once. JavaScript is case sensitive, so you must use:
document.getElementById

Not
document.getElementByID

Here is my working version of your script.


How can I paint a sector only with border-radius?

Question: As we know, in CSS, we can use:
width : 100px; height : 100px; border-radius : 100% 0 0 0;

To paint a sector with 90deg; and I want to use this way to paint a sector with any deg. But the front sector doesn't cover perfectly. It leaks a slice of red sector and I don't know how to handle it.

body {
  background-color: #fbb;
}

.box {
  width: 200px;
  height: 200px;
  position: relative;
  background-color: #f00;
  border-radius: 100% 0 0;
}

.box::after {
  content: '';
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fbb;
  border-radius: 100% 0 0;
  -webkit-transform-origin: 100% 100%;
  transform-origin: 100% 100%;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

Comment: While I've edited your question to *try* and make it more readable I have to point out that your first block of CSS is formatted incorrectly; the `=` characters should - for all those instances - be replaced with `:`
Comment: [You don't need those vendor prefixes](https://caniuse.com/mdn-css_properties_transform-origin).
Answer: You can cheat a bit and shift the whole overlay with an additional transform.

body {
  background-color: #fbb;
}

.box {
  width: 200px;
  height: 200px;
  position: relative;
  background-color: #f00;
  border-radius: 100% 0 0;
}

.box::after {
  content: '';
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fbb;
  border-radius: 100% 0 0;
  transform-origin: 100% 100%;
  transform: rotate(45deg) translate(-1px, 0px); /* <---- here */
}

It also seems to work by shifting the transform origin slightly.

body {
  background-color: #fbb;
}

.box {
  width: 200px;
  height: 200px;
  position: relative;
  background-color: #f00;
  border-radius: 100% 0 0;
}

.box::after {
  content: '';
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fbb;
  border-radius: 100% 0 0;
  transform-origin: 101% 100%; /* <---- here */
  transform: rotate(45deg);
}

You could also use a sharp box shadow.

body {
  background-color: #fbb;
}

.box {
  width: 200px;
  height: 200px;
  position: relative;
  background-color: #f00;
  border-radius: 100% 0 0;
}

.box::after {
  content: '';
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fbb;
  border-radius: 100% 0 0;
  transform-origin: 100% 100%;
  transform: rotate(45deg);
  box-shadow: 0 0 0 .5px #fbb; /* <---- here */
}

None of these are mathematically perfect, but they may suit your practical needs.


Get previous rows and next rows of linq result for special row

Question: I have a list of profile each profile have a own point how can I show a list that shows previous profiles(rows) and next profiles.
For example:
a 20
b 30
c 40
d 50
e 60
f 70
v 80
t 90

my goal is d but I want to show two previous rows and two next in list, too:
b 30
c 40
d 50
e 60
f 70

Comment: Do you have anymore info as to how you are retreiving `d` now?
Comment: *Previous* and *next* imply an **ordering** - what do you want to have your rows **ordered by** ?
Comment: Punctuation. Beautiful invention. Further, what type of list is this? Is there always 1 `d`? Looks like you could use IndexOf -/+ 2.
Comment: I solved that but I used extra objects.
Answer: In my goal ProfileId will be parameter. I retrieved whatever I wanted.
// here is my code.
var pp = from p in db.Profiles.OrderByDescending(u => u.score) select p;

foreach(var x in pp)
{
    t++;
    if (x.ProfileId == 58)
    {
        r = t;
    }
}
var zz = from d in pp.Skip(r - 2).Take(4) select d;


How can I simplify using active cell / copy / paste to transfer data between sheet?

Question: I am trying to transfer the data from sheet one to sheet two and combined the information on the second sheet. The code I have listed below works, but it seems very inefficient. I am trying to improve by VBA abilities and would love to here ways to shrink my code down, make it more efficient, and still achieve the same goal. Thanks for any help you can provide.
Sheet 1
Sheet 2
Sub batchorder()
Dim Pname As String
Dim Lplace As String
Dim numsld As Long
Dim rating As Integer
Dim lastrow As Long
Dim i As Long
Dim openc As Long

lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("A1").Select

For i = 1 To lastrow
    If Cells(i, 1).Value <> "" Then
        'Copy name to sheet 2
        Cells(i, 1).Select
        ActiveCell.Offset(0, 1).Select
        Selection.Copy
        Sheets("Sheet2").Select
        Range("A1").Select
        'Find the next open cell to paste to
        Selection.End(xlDown).Select
        Selection.End(xlDown).Select
        Selection.End(xlUp).Select
        ActiveCell.Offset(1, 0).Select
        ActiveSheet.Paste
        Sheets("Sheet1").Select
            'Copy place to sheet 2
             ActiveCell.Offset(1, 0).Select
             Selection.Copy
             Sheets("Sheet2").Select
             Range("B1").Select
            'Find the next open cell to paste to
            Selection.End(xlDown).Select
            Selection.End(xlDown).Select
            Selection.End(xlUp).Select
            ActiveCell.Offset(1, 0).Select
            ActiveSheet.Paste
            Sheets("Sheet1").Select
                'Copy sold to sheet 2
                 ActiveCell.Offset(1, 0).Select
                 Selection.Copy
                 Sheets("Sheet2").Select
                 Range("C1").Select
                'Find the next open cell to paste to
                Selection.End(xlDown).Select
                Selection.End(xlDown).Select
                Selection.End(xlUp).Select
                ActiveCell.Offset(1, 0).Select
                ActiveSheet.Paste
                Sheets("Sheet1").Select
                    'Copy rating to sheet 2
                     ActiveCell.Offset(1, 0).Select
                     Selection.Copy
                     Sheets("Sheet2").Select
                     Range("D1").Select
                    'Find the next open cell to paste to
                    Selection.End(xlDown).Select
                    Selection.End(xlDown).Select
                    Selection.End(xlUp).Select
                    ActiveCell.Offset(1, 0).Select
                    ActiveSheet.Paste
                    Sheets("Sheet1").Select
    Sheets("Sheet1").Select
    i = i + 3
    Else
    End If
Next i

End Sub
Comment: The code works, so https://codereview.stackexchange.com/ is the place to improve it. Although in this case, when code comes mostly from macro recorder, I would consider reading on how to avoid select statements. Also declaring as Integer is a bad practice, always use Long instead.
Comment: See [Avoiding .Select](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba)
Comment: Thanks for sharing the forum where I should post these types of questions in the future Ryszard. And thanks for the link to the avoiding .select thread QHarr.
Answer: Sub batchorder()

    Dim Row As Long
    Dim i As Long

    ' These two lines speed up evrything ENORMOUSLY.
    ' But you need the lines at the end too
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Row = Sheet2.UsedRange.Rows.Count  ' Row is nr of last row in sheet

    While Application.CountA(Sheet2.Rows(Row)) = 0 And Row > 1
        Row = Row - 1 ' skip empty rows at the end if present
    Wend

    For i = 1 To Sheet1.UsedRange.Rows.Count
        If Sheet1.Cells(i, 1).Value <> "" Then
            Sheet2.Cells(Row, 1).FormulaLocal = Sheet1.Cells(i, 2).FormulaLocal
            Sheet2.Cells(Row, 2).FormulaLocal = Sheet1.Cells(i + 1, 2).FormulaLocal
            Sheet2.Cells(Row, 3).FormulaLocal = Sheet1.Cells(i + 2, 2).FormulaLocal
            Sheet2.Cells(Row, 4).FormulaLocal = Sheet1.Cells(i + 3, 2).FormulaLocal
            i = i + 3
            Row = Row + 1
        End If
    Next

    ' Restore Excel to human state.
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

Comment: Thanks for the help Roemer. Can you explain what is going on with these two lines:     Application.ScreenUpdating = False
                              Application.Calculation = xlCalculationManual
Comment: I can, but that is not what this forum is for, and I may get reprimanded if I do. That is where Google is for namely. :D  BTW The commands are pretty self-explanitory. They literally do what they say what they do.
Answer: You should basically never use the select statement, it gets everything really messy quickly. Here's a basic combiner of mine. Just added the If statement to check whether the cell and in this case row is empty.
This should work but more importantly try to understand what it does to learn. I gave it some comments.
Sub batchorder()
Dim ws1 As Worksheet
Dim ws2 As Worksheet

' Just habits, but doing this here means that I won't have to write anything else than ws1 and ws2 in the future
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")

Dim lastrowWs1 As Long
Dim j As Long
' first row after ws2 headers
j = 2

' With statement to make the code nicer also ".something" now means ws1.something
With ws1

' Bob Ulmas method -- just a personal preference to find the last row.
lastrowWs1 = .Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

For i = 1 To lastrowWs1
    ' Check if the cell is not empty
    If Not .Cells(i, 1) = vbNullString Then
        'Basically range.value = other_range.value
        ws2.Range(ws2.Cells(j, 1), ws2.Cells(j, 4)).Value = WorksheetFunction.Transpose(.Range(.Cells(i, 2), .Cells(i + 3, 2)).Value)
        ' step 3 forward as the amount of rows per record was 4
        i = i + 3
        ' go to next row for worksheet 2
        j = j + 1
    End If
Next i

End With

End Sub

Comment: Mikael, This response was great. Thank you for commenting, it made it a lot easier to follow along. I tested the code and worked exactly the same. Thanks.


Comment approval permission to non-admin user

Question: I have three accounts in my Drupal 6 site:

admin (which is admin)
moderator
moderator2 (which is authenticated role defined)

Now I want to give permission to the moderator2 to approve comments just like I did from admin account by only going to <code>/admin/content/comment</code>. How can I do that?
Comment: Does going to `/admin/user/permissions` and ticking the box that says `administer comments` for the `moderator2` user do what you want it to do?
Answer: I take that "moderator2" is a username name used for a user account. In that case, if you want to give to moderator2 the permission to administer comments, then you have to associate the user account with a role you only give to those users you want to be able to administer comments, then you visit the page on admin/user/permissions, and select "administer comments" for that role.

In this case, I called the role "comments moderator" but I could have chosen another name.
If "moderator2" is a role name, then on the page at admin/user/permissions you see something similar to what shown in the following screenshot.

The permission is the same as before.
P.S. The only permission for which you are interested is "administer comments." The other permissions don't influence that one, and users with a specific role would be able to approve comments, even without to have (for example) the permission to access comments.
The only permission associated with the page at admin/content/comment is "administer comments."
<code>  $items['admin/content/comment'] = array(
    'title' => 'Comments',
    'description' => 'List and edit site comments and the comment moderation queue.',
    'page callback' => 'comment_admin',
    'access arguments' => array('administer comments'),
    'file' => 'comment.admin.inc',
  );
</code>


How to run Bayesian optimization experiments in parallel?

Question: Suppose I have the following hyperparameters for tuning:

learning_rate: [0.00001, 0.1]
epochs: [200,300,400,....,1000]
batch_size: [16,32,64,128]

If I want to run experiments using 4 parallel jobs, can I just divide one parameter space into 4 subspaces to achieve parallelism? For example,

1st job:
learning_rate: [0.00001, 0.0001]
epochs:[200,300,400,....,1000]
batch_size: [16,32,64,128]

2nd job:
learning_rate: [0.0001, 0.001]
epochs:
[200,300,400,....,1000]
batch_size: [16,32,64,128]

and so on.
Does this make sense?
Answer: The problem with partitioning the search space yourself upfront and then running Bayesian optimization independently on each of them is that it is quite likely that most of your partitions don't contain any parameters that would be remotely optimal. That's why you use Bayesian optimization which is supposed to quickly figure out where to concentrate search effort and which regions can be abandoned. It does that usually much better than we humans.
Thus, if you want to benefit from parallel execution, you should employ implementations of Bayesian optimization that use parallel execution internally. The Bayesian optimization method knows best where to look next and where to use parallel compute power. Thus, your multiple cores are used to investigate many promising parameters in parallel instead of wasting them in irrelevant regions.
Such parallel implementations of Bayesian optimization are available, e.g. in R: ParBayesianOptimization, and in python: GPyOpt.
Answer: https://cogneato.xyz
It wraps Facebook Ax + customizations. It'll do paralleizations. Just ask for "number of arms" equal to however many parameters you want to evaluate.
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).