Is it possible to have two finite order topological generators of a noncompact Lie group?

Question: What is an example of a noncompact Lie group $ G $ and two finite order elements $ a,b \in G $ such that the closure (in the manifold topology) of the subgroup $ <a,b> $ is all of $ G $?
Ideally the example would be a matrix group $ G $ and $ a,b $ would be given explicitly as finite order matrices.
It turns out that such a pair of finite order elements always exists if $ G $ is compact semisimple
https://mathoverflow.net/questions/431456/semisimple-compact-lie-group-topologically-generated-by-two-finite-order-element/444664#444664
For example $$
a=\frac{i}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}
$$
$$
b=\begin{bmatrix} \overline{\zeta_{16}} & 0 \\ 0 & \zeta_{16} \end{bmatrix}
$$
generate a dense subgroup of $ SU_2 $.
Comment: Does $\mathbb R^2$ with the usual generators work or am I mistaken?
Comment: Never mind, I see I missed the finite order requirement.
Comment: $SL(2,R)$ will work.
Comment: @MoisheKohan ya I was wondering about that maybe since $ S, ST $ are finite order and generate $ SL(2,Z) $ then $ \sqrt{S}, ST $ would be finite order and maybe be topological generators for $ SL(2,R) $? Where $ S, T $ are the standard generators for the modular group https://en.wikipedia.org/wiki/Modular_group
Comment: Just take any two fixed finite order elements which do not commute and whose fixed points are close enough.
Answer: Here is how to find such examples in, say, $G=PSL(2, {\mathbb R})$. First of all, if $a, b$ are noncommuting elements of finite order $\ge 3$, they generate a Zariski dense subgroup (this is a nice exercise in understanding Lie subgroups of $G$). Now, you just have to choose $a, b$ so that they generate a nondiscrete subgroup. For instance, take them both the Zassenhaus neighborhood of $1\in G$. Or, if you prefer, make them violate the Kazhdan-Margulis lemma: Fix the order and make sure that the fixed points in the hyperbolic plane are close enough. Or make $a, b$ violate the Jorgensen inequality...
With more thought, you will realize that such elements exist in any complex semisimple Lie group $G$. The key is to observe that compact elements of the Lie algebra form a Zariski dense subset. Then you use the fact that if $a, b\in G$ generate a nondiscrete subgroup and $\log(a), \log(b)$ generate the Lie algebra of $G$, then $a, b$ generate a dense subgroup of $G$.
Comment: Does your result from the second paragraph also apply to all real algebraic semisimple Lie groups $ G $? Would you be interested in posting your argument from the second paragraph as an answer to https://math.stackexchange.com/questions/4537024/simple-lie-group-topologically-generated-by-two-finite-order-elements ?
Comment: I do not know about all real, I wrote only about complex Lie groups.


Scrollview won't scroll all the way down

Question: I have a scroll view which works fine. Almost. I'm building in Any/Any. The problem is that the scroll view won't scroll past the view controller. I have a switch that is mostly in the view controller window, but the rest is off the box (not really sure how to describe it; it's in the view in the scroll view, but the view is longer than the view controller so part of it is hidden).
The scroll view will scroll down until it hits the part where the view controller would end if you were looking at it in Xcode. There is some more stuff under the switch (labels and another switch). To view these you have to forcefully scroll down. Xcode shows no constraint errors (little red circle with white arrow).
Hopefully this makes sense
Comment: It sounds like the scroll view's `contentSize` is too small.
Comment: Check this out it worked for me https://www.youtube.com/watch?v=rjTS9fyWqdg
Comment: Change you scrollviews height. Make it smaller -> worked for me. Good luck.
Answer: A ScrollView needs to know the height and width of the content it is holding in order to know how much to scroll and which direction. Here is a quick read on how ScrollViews work in iOS: https://www.objc.io/issues/3-views/scroll-view/
You can set this programmatically using the contentSize property, but this requires you to know and or calculate the contentSize, which is pretty tedious in most cases.
The correct way of defining the contentSize in iOS is to define AutoLayout constraints in your View. Here is an excellent tutorial on doing just that:
https://www.natashatherobot.com/ios-autolayout-scrollview/


What choir pieces are suited to warm up a new, small choir?

Question: Soon I will have the pleasant duty of leading an amateur choir at a two-week summer camp. I am looking for warming up pieces that are easy, but fun. It should be possible to learn them without having to read the sheet music, but also a bit more advanced singers should have fun.
Answer: I've found rounds especially good as warm-up pieces, as they can be taught to a mixed ability group without sheet music (and it doesn't matter what your ratio of male to female singers is!).
There are some excellent rounds and simple part-songs in the Voiceworks series of books (Peter Hunt) - my favourites are in Voiceworks 2 and include:

Ba-nu-wa (African round, has a particularly good final line)
Chicka Hanka (which you can keep building on over a period of time, adding more improvised noises, bass line etc) - a pdf of this song is at http://ukcatalogue.oup.com/product/music/series/choralseries/vw/9780193435506.do?sortby=bookTitleAscend
There's a girl that I love (a round with a punchline)

Online you'll find various campfire songs, and these would also work well as warm-up pieces. These two sites (as an example) have midi to help you learn the songs:
http://guidinguk.freeservers.com/songs.html
http://songs-with-music.freeservers.com/
Sing for Pleasure also produce some good books on rounds and simple part-songs:
http://www.singforpleasure.org.uk/resources/publications.php
I've made particular use out of their 'Round and Round' book.
As another option, you could use well-loved pop songs or musical theatre pieces to get everyone buzzing, singing in unison or simple two/three part harmony. Examples that spring to mind are 'Do you hear the people sing' from Les Miserables, 'Do Re Mi' from The Sound of Music, and 'Let It Be' by The Beatles.
Have fun!


Image or icon on particular node output

Question: Is there any way to replace image/icon for a particular node output ?
A simple Example:
I am getting input from user sucn as
"is your car running in petrol or diesel ?" if he selects the diesel then in node output instead of displaying diesel it should display the Diesel icon which i provide.
Is there any module for that because i have several input like this..Thanks
Answer: If your field is a reference field like node reference or term reference, then you can add an image field in the referenced entity for associating the image. Then in your node tpl file, you can load the referenced entity and print the image. If you do not want to write a custom tpl, then this can be done using the Display Suite module. But unless you need Display Suite for other purposes, the tpl way is better.
Answer: If it's a basic select field, an if/then in your node TPL file can display the icons based on the field value. Something like:
<?php
if (!isset($node->field_petrol_diesel['und'][0]['value'])) {
  if ($node->field_petrol_diesel['und'][0]['value']=='petrol') :
    print '';
  elseif ($node->field_petrol_diesel['und'][0]['value']=='diesel') :
    print '';
  endif;
} ?>

The first IF checks to see if the field has a value. It then checks to see what the value is, and displays an icon accordingly. You would need to change the field name (field_petrol_diesel) and the icon paths to match your site.

Image or icon on particular node output


Flutter Search bar in ActionBar like yelp app

Question: I am trying to build an application location base and I want a search bar like this image shows. That search bar should be able search for locations and text. Does anyone have a pre-built search bar like this?
Answer: You can create you own custom app Bar.Simply give appBar property(in Scaffold) an PreferredSize and design as you like. Below is the implementation:
<code>class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  return Scaffold(
    appBar:PreferredSize(
        preferredSize: Size.fromHeight(45.0),
                //give child any Widget you like
       child: Center(
        child: Container(
           width:MediaQuery.of(context).size.width*0.9,
          height:100,
          child:Center(child: Text("CUSTOM APP BAR")),
          color:Colors.blueAccent,
        ),
      ),
    ),
  );
 }
}
</code>


Why does the sequence $a_n = a_{n-1}^2 - 1$ end up in $0,-1,0,-1,\cdots$?

Question: I have this recurrence relation:
$$a_n=a_{n-1}^2-1$$
I can see that this sequence stays constant if $a_0=\phi$ or $1-\phi$ and it can also stably continue like $0,-1,0,-1,\cdots$. ($\phi=\frac{1+\sqrt{5}}2)$
The sequence will diverge to $+\infty$ if $|a_0|>\phi$.
I observed that whenever $a_0$ isn't $\pm\phi$ or $\pm(1-\phi)$ and $|a_0| \le \phi$, the sequence will converge to $0,-1,0,-1,\cdots$, no matter how close $a_0$ is to $\pm\phi,\pm(1-\phi)$. This makes sense to me intuitively, although I can't find a mathematical explanation.
How do I prove this, and which theory deals with this kind of problems?
Comment: @Ramanujan Standard terminology for the phenomenon here is that the sequence oscillates between values near $0$ and values near $-1$.
Comment: Note that you are not using standard terminology here: [a sequence converges to one value (or it doesn't converge)](https://en.wikipedia.org/wiki/Limit_of_a_sequence), it can't converge to a sequence.  What you mean is that the terms get closed to e.g. $(-1)^k$ for growing $k$ (in the first picture).
Comment: See https://math.stackexchange.com/questions/3466935/finding-julia-set-of-fz-z2-1
Comment: What if you find a value of $\epsilon$ such that $a_0=\phi-\epsilon$ eventually becomes $\phi-1$? Then it would stabilize?
Answer: You are looking at iterations of your function on the interval $[-\phi,\phi]$. Y
ou can renormalize so that the interval becomes $[0,1]$ by taking
$$b_{n} := \frac{1}{2} - \left(\frac{\phi}{2} - \frac{1}{2}\right) a_n.$$
You then easily find that
$$b_{n+1} = \lambda b_{n} (1 - b_{n})$$
where
$$\lambda = 2 \phi = 3.23607\ldots $$
This is now a special case of (iterations of) the logistic map (https://en.wikipedia.org/wiki/Logistic_map), and the behavior
in this special case is as you predict. (You can certainly prove this case directly, but just connecting the problem to a more well-known problem if you are interested.)
Answer: Let $f(x) = x^2-1$.
Assume $x = \phi+\epsilon$ for some $\epsilon\ne0$. Then
$$|f(\phi+\epsilon)-\phi| = |f(\phi+\epsilon)-f(\phi)| = |\epsilon f'(\phi) + o(\epsilon)|\,.$$
Since $f'(\phi) = 1+\sqrt{5}\gt 1$, this implies that if $a_n$ converges to $\phi$, then it stabilizes to $\phi$. It is then easy to see that this happens only if $a_0\in \{\phi, -\phi\}$.
The same reasoning yields the same result for $1-\phi$.
Let $g(x) = f(f(x))$.
You can see that $|g(x)+1| = |g(x)-g(-1)| < |x+1|$ for all $x\in [-\phi, 1/2]$. Thus for $a_{0}$ in this interval, $a_{2n}$ converges to $-1$.
You can show a similar result for $0$. I think (I have not had the time to check yet) that these interval are not adjacent, but studying what happens in the remaining interval should not be a problem.


While loop execution error

Question: I have a problem in sql query. I have to execute sql query  in while loop.Below are my program
<?php
    $database = new Database();
    $db = $database->getConnection();
    $query = $db->query("Select * from cart");
    $query->execute();
    while($cd = $query->fetch(PDO::FETCH_ASSOC)){
?>

            <?php
            $aa = $cd['cat'];
            $ab = $cd['id2'];

            $query = $db->query("Select * from $aa where id = $ab ");
            $query->execute();
            $cdd1 = $query->fetch(PDO::FETCH_ASSOC);
            echo $cd2 = $cdd1['detail'];
        ?>

            <?php echo $cd['num'] ?> x 123

<?php
    }
?>

My second sql runs based on first sql.
My problem
I am getting only one row means it is executing only once.
What I need
I need all row.
Answer: You're reusing the $query variable inside the loop. So when the loop repeats and does
while($cd = $query->fetch(PDO::FETCH_ASSOC))

it's now fetching from the second query, not the original one.
Use a different variable inside the loop.
    $query2 = $db->query("Select * from $aa where id = $ab ");
    $query2->execute();
    $cdd1 = $query2->fetch(PDO::FETCH_ASSOC);

Comment: Thank you sir you save my time.
Answer: You redefining $query inside of while scope. Yous use another variable (e.g. $query2 ) inside of the scope.

While loop execution error


Statsmodel how to take results where P>|t| < 0.05

Question: I used statsmodel summary to get information about my features and got the following result.
How can I filter these values so that I only get results where P> | t | <0.05
Comment: you could try loading this table as a dataframe and then use filter on the dataframe.
Answer: Assuming the summary results in stored in the variable summary_result.
You could try this:
# To Convert the table to dataframe
results_as_html = results_summary.tables[1].as_html()
df = pd.read_html(results_as_html, header=0, index_col=0)[0]

# Filter the df for P> | t | <0.05
df.loc[df['P>|t|']<0.05]

You could also get the dataframe directly if you are using summary2 method instead of summary method from statsmodel api
with summary2(), we could just do like
df = results.summary2().table[1]

# Filter the df for P> | t | <0.05
df.loc[df['P>|t|']<0.05]


If $(\mathbb{Q},+)$ is homomorphic to $( \mathbb{Q}^+, \times)$, then $f(x)=1$ for all $x\in \mathbb{Q}$

Question:
If $(\mathbb{Q},+)$ is homomorphic to $( \mathbb{Q^+}, \times)$, then $f(x)=1$ for all $x\in \mathbb{Q}$.

This is one of questions from my assignment. I've been working on it for 2 days, but still don't have a clue. Can somebody give me a hint?
Comment: One reason you may have been stuck on this is the garbled language of the question itself.  I'm surprised that others have offered detailed and useful advice without pointing this out.  "If $f$ is a homomorphism from $(\mathbb{Q},+)$ to $(\mathbb{Q}^{+}, \times)$, then $f(x) = 1$ for all $x \in \mathbb{Q}$" is a sensible question. Note that this phrasing *explains what $f$ is* before asking you to prove something about it. (FWIW, the phrase "$A$ is homomorphic to $B$" is not used. It's rather common to talk about isomorphisms without specifying them, but this *isn't done* with homomorphisms.)
Comment: What is $*$? ${}$
Comment: @Shannon: Please include the question in the body of the post, not just the title. Your post began with "This is one of the question from my assignment" and never stated the question in the post, only in the title. Titles of posts are like titles of books written on the spine: informative when you are looking on the main site, but should not be considered part of the 'narrative.'
Comment: @ArturoMagidin Thanks for doing revision for me. I was using my phone to post this question which caused some information hidden. Thanks for your suggestion.
Comment: @KannappanSampath multiplication. Sorry.
Answer: HINT. Given $x\in \mathbb{Q}$ and $n\gt 0$, there always exist $y\in\mathbb{Q}$ such that $ny = x$. What will happen to this equation when you apply $f$? What does that tell you?

Note. The original problem had $(\mathbb{Q},+)$ and $(\mathbb{Q},\times)$. Hence the following:
As stated, the claim is incorrect. Since $(\mathbb{Q},\times)$ is not a group, the only reasonable interpretation is that we are considering these objects as either semigroups, or monoids. But if we consider them as semigroups,  then $f(x)=0$ for all $x$ is a perfectly fine semigroup homomorphism from the additive semigroup of rationals to the multiplicative semigroup of rationals, so the claim is false.
If we consider them as monoids (so that $f(0)=1$ necessarily is true), then we do have that any $f\colon\mathbb{Q}\to\mathbb{Q}$ such that $f(a+b) = f(a)f(b)$ is necessarily of the given form.
(If these are meant to be groups, then the second one should be either $(\mathbb{Q}-\{0\},\times)$, or $(\mathbb{Q}_{\gt 0},\times)$. )
Comment: @Shannon: And did you *now* look at the hint I gave? (P.S.: The fact that $f(0)=1$ follows simply from the fact that you have a group homomorphism: it *must* map the identity of $(\mathbb{Q},+)$, which is $0$, to the identity of $(\mathbb{Q},\times)$, which is $1$).
Comment: the second one is ( \mathbb{Q^+}, \times). Sorry for my carelessness. I was trying f(x)=f(0+x)= f(0)f(x) ,the only thing I can get is f(0)=1.
Comment: @Shannon: To be more explicit: whatever $f(1)$ is, what is $f(\frac{1}{2})$, in terms of $f(1)$? What is $f(\frac{1}{3})$, in terms of $f(1)$. What is $f(\frac{1}{n})$, in terms of $f(1)$? What does that tell you about $f(1)$?
Comment: I got f(x)=f(x/n)^n. Is it right?
Comment: I got f(x)=f(x/n)^n, is it enough to conclude f(x) = 1 since f(x) and f(x/n) are both in Q.
Comment: What you say I think is not enough, you have to *explain*, not just guess (we aren't cooking pasta; you don't throw things at the wall and hope something sticks). Yes: for any $x$, $f(x)$ must be an $n$th power for every $n$. But the only rational number that is an $n$th power for *every* natural number $n$ is $1$, so $f(x)$ must equal $1$ for any $x$.
Comment: Yes, this is what I want to say. I tried to split x but not this way. Thank you so much.


View Events by Category using PHP Code Igniter

Question: I'm a not that advance in PHP, I need some assistance:
I have a table events with column name event_type
I want when I click business I would get all events under business category. Same goes to education...
This is my views, View Image here
This is a code snippet from by views, business category.
`

Business

                            Business is always Good when you talk of a good setup. Get
                            the best Meetings right here.

                        <a href="<?php echo base_url('index.php/home/category' . $data['event_type'])?>">View

`

I dont know how to configure my controller and my model
.
I am using Code Igniter 3.0 with PHP
Comment: Have a look here http://stackoverflow.com/help/mcve on how to ask good questions.
Comment: Please post what you done so far..You can't expect your work do be get done completely from here.So be precise
Answer: Ok.So what i get from your question is,you had table events with event_type and you want to fetch the event data depending on event clicked/triggered.
From your posted URL,it looks like Home is your controller and category is the function and you are passing event_type to that function
<?php echo base_url('index.php/home/category/' . $data['event_type'])?>

So your controller function will go like this (I hope you are following CI user guide to define controller);
//Controller function
    function category($event_type)
    {

    // pass the received event_type to your model
    $this->load->model('event_model');
    $data['events'] = $this->event_model->get_events($event_type);

    // Pass the data to your views
    $this->load->view('events',$data);
}

// Model code goes like this
function get_events($event_type)
{
  **// result() returns object where as result_array() returns array**
   $query = $this->db->get_where('events',array('event_type'=>$event_type))->result();
   if (count($query) > 0)
   {
      return $query;
   }
   else
      return false;
}

Let me know if any queries.
Comment: Im getting _Type: Error

Message: Call to a member function num_rows() on array

Filename: C:\xampp\htdocs\evento\application\models\home_model.php

Line Number: 53

Backtrace:

File: C:\xampp\htdocs\evento\application\controllers\home.php
Line: 123
Function: categories

File: C:\xampp\htdocs\evento\index.php
Line: 315
Function: require_once_     `
Comment: Thanks alot  no I gave up, it became quite complicated, but below I have found the answer, it was much simpler...see below @Anowar
Comment: Ok.Your call but please consider to work and write the best code because when your project goes big,scalability is the main concern
Comment: Thanks......im trying it now i get this _An uncaught Exception was encountered

Type: Error

Message: Cannot use object of type stdClass as array

Filename: C:\xampp\htdocs\evento\application\views\searchview\category.php

Line Number: 122

Backtrace:

File: C:\xampp\htdocs\evento\application\controllers\home.php
Line: 146
Function: view

File: C:\xampp\htdocs\evento\index.php
Line: 315
Function: require_once_
Comment: The error say it all, the query i have shown it return result as object and you are trying to parse it as array.So for your view code to work ,in model make this change.Instead of `result()` make it `result_array()`

Added comment in code.You can check my comment also
Comment: Yaaaiy, Thanks @Zeeshan, Works like majic, Im now able to view my categories.....Thanks alot
Answer:
Without model dependency

Home Controller:
public function category($event_type= false){
    if($event_type !=false){
        $this->db->select('*');
        $this->db->where('event_type', $event_type);
        $data[events] = $this->db->get('events')->result_array();

        //Also query & pass all event_type into view $data[event_type]
        $this->load->view('category_view', $data);
    }else{
        redirect('index.php/home/index'); //might be home page
    }
}

category_view:
 //Foreach events data by $events or check by var_dump($events)
//Generate url by foreach event_type or use custom
<a href="<?php echo base_url('index.php/home/category/business')?>">Business
<a href="<?php echo base_url('index.php/home/category/education')?>">Education

-------------------------------or----------------------------------------

Edited: With model (Using model and common query function).

controller:
public function category($event_type= false){
    if($event_type !=false){
        $this->load->model('model_name');

        $where = array('event_type'=>$event_type);
        $data[events] = $this->model_name->get_data('events', $where));

        //Also query & pass all event_type into view $data[event_type]
        $this->load->view('category_view', $data);
    }else{
        redirect('index.php/home/index'); //might be home page
    }
}

Model:
public function get_data($table, $where=false){
    $this->db->select('*');
    if($where != false){
        $this->db->where($where);
    }
    return $this->db->get($table)->result_array();

}

Comment: This redirects to my home without the results
Comment: If you are removing model dependency, you are breaking the MVC concept. Also its not good idea to execute your queries in controller as Model is for that.
Comment: @Zeeshan noted, Thanks, I  try to do adjustments to my code
Comment: Why we use model? is it mandatory  for each and every action?
We use model for database related operation, validation, common function etc.
Here @RobertKibet was in trouble so i think no need to make complex.
If you want to use model then just create a db query function in model and use that function in controller instead of  direct query.
Comment: This question shouldn't rise why Use model ? If you have decided to use MVC.
Also its for our sake.


Using Cosmos change feed triggered Function, is it possible to get whole transaction documents together?

Question: Given I save two documents within the same logical partition and in one transaction to Cosmos, and I have an Azure Function triggered by the change feed, would those two documents always arrive in the Function documents collection together? Or could they be split over two invocations of the Function?
Answer: Based on this comment on the documentation:

transaction scope is preserved when reading items from the change feed.

They should arrive together in the same batch because they have the same transaction number, unless the transaction is bigger than 4Mb which is the maximum response size, in which case they could be split into multiple responses.
Comment: Nice find - I didn't spot that. Thanks.


One dimension equivalent to area

Question: Some say that length is the $\mathbb R^1$ equivalent of $\mathbb R^2$ area or $\mathbb R^3$ volume but you can substract areas or have intersections of areas. I need to do the same in one dimension but I don't which term to use. Is length really the good term for that?
Comment: Note that "length" is the equivalent to "area" and "volume" *as measurements*, i.e., as numbers that give a size to a 2D or 3D region. However, while we also sometimes uses the words "area" and "volume" to describe the regions themselves, "length" is only ever used for the measurement. The 2D and 3D conflation of terminologies is leading to some confusion about your question, resulting in answers about measurement terminology instead of region terminology. "Region" is the best answer I can think of, though it is more generic than you apparently want.
Comment: I wouldn't use "area" to describe the region in a formal context to begin with.
Answer: The typical abstraction of area is a measure which is also an abstraction of length so it would seem likely that it's correct for your application as well.
Answer: What I was looking for was an Interval. I find the term way more intuitive and self descriptive than Length of even Measure. Thanks for the answers, but I'll stick with Interval.
Edit: I was wrong, it's a collection of intervals and not a single interval.
Comment: **Note:** If the answer to your question is *interval*, then in the OP you are misusing the term *area*. Length, area and volume are *numbers* which measure how big a shape is. In 1 dimension the shape might be called a line (or interval, or union of intervals); in 2 dimensions the shape might be called a surface, or region.
Comment: No, I would not call that an interval; that is two intervals, or a union of two intervals.
Comment: Note that "an interval" describes something connected. The two separate black lines on the right of your pictures are not "an interval". The phrase for what you are working with might more accurately be "a collection of intervals".
Comment: Just as a Cube has a certain volume, and a Rectangle has a certain area, an Interval has a length. Interval is really the name for the simplest 1-dimensional shape.
Comment: If you're looking for a word for the *object*, then "interval" is fine for a single segment; "union/collection of intervals" describes the example in your question. This corresponds to a "region" in the plane or in space. If you want a word for *how much* of that object you have, then "interval" is inappropriate. You really want "measure" (or, say, "total length").
Comment: @Winter: To be clear: Are you looking for a word for the object or for its measurable content?
Comment: @DanielLittlewood One might also say that the top-right shape is "an area of the plane"
Comment: @MeesdeVries $[5, 6] \cup [8, 9]$ is not an interval? I always thought so
Comment: @Blue Measure seems way to broad, it can be in any number of dimension. Can also be confused with a number read on a scientific instrument. What I'm looking for has a position (or positions) in the number line and a length (or lengths).
Comment: As $\{x\} = [x, x]$ is an interval, all subsets of $\mathbb R$ are unions of intervals …
Answer: The topological volume $V_n(S)$ of a solid $S$ of dimension $n$ is defined as $V_n(S) =  \int_S dV$.
As such, $V_2$ represents the surface (area) and $V_3$ represents the volume (usual 3D definition).
If we go through that reasoning, $V_1(S)$ refers to the length.
So, your picture is correct if you are speaking above $V_1(S)$.
Answer: What you are looking for are the elementary subsets of reals, which is defined as all the subsets that can be generated from the intervals, union, intersection and complement. If you add closure under countable union and countable intersection as well, then you get the Borel subsets.
If you want to be able to assign lengths to them, you might want countable additivity (length of a countable disjoint union is the sum of their lengths). It turns out that the Borel sets satisfy countable additivity under the Lebesgue measure.
These notions extend to higher dimensions. Note that in Euclidean geometry and many real-world applications the (simpler) Jordan measure suffices, though it does not satisfy countable additivity (since the rationals are not Jordan measurable) but only satisfies finite additivity.

One dimension equivalent to area


Looking for weird counterexample for Riemann integrability question

Question: I am looking for a counterexample to the following:

Let $f$ be [Riemann] integrable $[a,b]$, let $c \in (a,b)$, and let $$F(x) = \int_a^xf$$ for $a\leq x\leq b$.
Find $f,c$ such that $f$ is differentiable at $c$, but $F'$ is not continuous at $c$.

I've been working on this with multiple people for quite some time, and though the solution says a counterexample exists, we have not been able to find one.
Comment: I very much suspect it was a typo in the problem statement, and they meant to write "Find $f,c$ such that $F$ is differentiable at $c$, but $F'$ is not continuous at $c$".
Comment: @DanielFischer It is not a typo. I have spoken with the professor.
Comment: Then they are mistaken. Or they have a non-standard definition of continuity.
Comment: What is the issue with this counter-example mentioned in this answer http://math.stackexchange.com/a/2047181/72031 of your previous question?  It gives you exactly the function you need.
Comment: @ParamanandSingh I disagree. With the $f$ of that answer, $F'$ is continuous on its entire domain.
Comment: @DanielFischer: That is the best possible we can hope for. As your answer says,  we can't have $F'$ discontinuous at continuity of $f$. Only thing we may have is that $F'$ does not exist at points arbitrarily near $c$ and that linked answer gives that kind of example. Like you I also suspect a typo in the question. If the typo is corrected then $f(x) = \cos(1/x), c = a = 0$ is the example we need.
Answer: As I commented, I expect that the problem statement should have been

Find $f,c$ such that $F$ is differentiable at $c$, bit $F'$ is not continuous at $c$.

Finding examples for that, while not trivial, is not exceedingly difficult.
If we require that the integrand $f$ is differentiable at $c$, it becomes impossible to find an example. It is already impossible if we merely require $f$ to be continuous at $c$. We can write
$$F(x) = F(c) + f(c)(x-c) + \int_c^x \bigl(f(t) - f(c)\bigr)\,dt.$$
Let $\varepsilon > 0$ be given. By the continuity of $f$ at $c$, there is a $\delta > 0$ such that $\lvert f(t) - f(c)\rvert < \varepsilon$ for all $t \in (c-\delta, c+\delta)$. Then, for $x,y \in (c-\delta, c+\delta)$ with $x < y$ we have
$$F(y) - F(x) = f(c)(y-x) + \int_x^y \bigl(f(t) - f(c)\bigr)\,dt,$$
and so
$$\Biggl\lvert \frac{F(y) - F(x)}{y-x} - f(c)\Biggr\rvert \leqslant \frac{1}{y-x}\int_x^y \lvert f(t) - f(c)\rvert\,dt < \varepsilon.$$
Thus at all points of $(c-\delta, c+\delta)$ where $F$ is differentiable, we have
$$\lvert F'(x) - f(c)\rvert \leqslant \varepsilon.$$
So $F'$ is continuous at $c$.
Note: There can be points arbitrarily close to $c$ where $F$ is not differentiable, but that doesn't affect the continuity of $F'$ at $c$, for that one considers only the domain of $F'$.
If it was meant that there is no neighbourhood $(c-\eta, c+\eta)$ of $c$ such that $F$ is differentiable at all points of that neighbourhood, just take an $f$ that has a sequence of jump discontinuities converging to $c$. Such functions are easy to find even when one requires differentiability at $c$.


example reduced and divisible modules

Question: Let's consider definition of reduced modules and torsion modules:
A reduced module $C$ is defined by the property that $\mathrm{Hom}(A,C)=0$ for every divisible module $A$.
(see for example A Foundation of Torsion Theory for Modules Over Geeneral Rings by Hattori)
I can not find any example about reduced module in this sense.
Please help me find some. I really appreciate your ideas!
Comment: All caps is considered to be "shouting"; please don't use it.
Answer: Let $M$ be any module.
If $\{N_i\}_{i\in I}$ is a family of divisible submodules of $M$ (that is, each $N_i$ is a submodule of $M$, and each $N_i$ is divisible), then $N=\langle N_i\rangle$ is also a divisible submodule of $M$: it is a submodulee, and given $n_1+\cdots+n_k\in N$, with $n_j\in N_{i_j}$, and $r\in R$, there exist $m_j\in N_{i_j}$ such that $rm_j = n_j$, and then $r(m_1+\cdots + m_k) = n_1+\cdots + n_k$.
Therefore, if $M$ is any module, then it has a largest divisible submodule (namely, the submodule generated by all divisible submodules; note that the trivial submodule is divisible, so this collection is not empty). Call it $M_d$.
Claim 1. The only divisible submodule of $M/M_d$ is the trivial submodule. that is, $(M/M_d)_d = \{0\}$.
Proof. Let $K$ be a submodule of $M$ that contains $M_d$ such that $K/M_d$ is divisible; let $k\in K$, and let $r\in R$. Then there exists $u+M_d$ such that $r(u+M_d) = (k+M_d)$, so $k = ru+x$ for some $x\in M_d$, with $u\in K$. Since $M_d$ is divisible, there exists $v\in M_d$ (hence in $K$)  such that $rv= x$. Thus, $k=r(u+v)$, and $u+v\in K$. Hence $K$ is a divisible submodule of $M$, so $K\subseteq M_d\subseteq K$. That is, $K/M_d$ is the trivial submodule.
Claim 2. $M/M_d$ is reduced.
Proof. Let $A$ be a divisible module, and let $\varphi\colon A\to M/M_d$ be a module homomorphism. Since $\varphi(A)$ is divisible (a quotient of a divisible module is divisible), then by Claim 1 $\varphi(A)=\{0+M_d\}$. Thus, $\varphi$ is the trivial map. Hence, $M/M_d$ is divisible.
This gives you lots of nontrivial reduced modules: just pick any module $M$ that is not divisible, and consider $M/M_d$
Answer: How about letting the ring be $R=\mathbb Z$ and $C=\mathbb Z$? I claim $\mathbb Z$ is reduced. Suppose $0\neq\varphi\in Hom(A,C)$ where $A$ is divisible. If $\varphi(a)=k$, then $\varphi(-a)=-k$, so I can assume some positive value is achieved by $\varphi$. Let $n$ be the smallest positive integer in the image of $\varphi$. Then $\varphi(a)=n$, and also
$2\varphi(a/2)=n$. Thus $0<\varphi(a/2)<n$, which is a contradiction.
Answer: Jim and Arturo have given you everything you need to see this through. Let me take a slightly different tack. If there is a nonzero $f:A \rightarrow C$, with $A$ divisible, then the image of $f$, which is isomorphic to $A/ker(f)$, is a nonzero divisible subgroup of $C$ (as Arturo pointed out, homomorphic images of divisibles are divisible). This is not hard to show, and you probably already have. In any event, if $C$ is reduced, then $Hom(A,C)$ must be zero. To show the converse, prove that $C$ divisible implies $Hom(A,C)$ is not zero for some divisible module $A$. For this, take $A = C$ and $f$ the identity map on $C$. As Jim points out, $\mathbb{Z}$ is not divisible. The subgroups of $\mathbb{Z}$ are the cyclic subgroups generated by nonnegative integers $a$. Can such a subroup be divisible? If so, the equation $nx = a$ has a solution in $<a>$ for every nonzero integer $n$. But this cannot happen; try $a = 3$ and $n = 2$, or, in general, take $n$ relatively prime to $a$ so that the rational number $a/n$ is not an integer. Put everything together and you have that $Hom(A, \mathbb{Z}) = 0$ for every divisible group $A$. Arturo has given you a nice way to extend things to modules over a general ring $R$. In this context, the usual interpretation of the "divisibility equation" $nx = a$ is that $n$ is a regular element of the ring $R$, so that an $R$-module $A$ is divisible if and only if $nA = A$ for all regular $n$ in $R$.

example reduced and divisible modules


why does fork() return all possible outputs in this combination?

Question: Question:
I need clarification/help on my understanding of fork() outputs. I know how to program more detailed and larger code in c with fork() and use other concepts like pipe, ipc, threads(posix). But my understanding with predicting return output is bad which is why I'm trying to figure this out I believe my case 1 is correct but my other cases are ambiguous or similar to that because i'm not quite solid with output of fork().
My knowledge with program output is decent, I understand basic algorithms that contain for-loop, while-loop, if/else, data structures, recursive outputs.
However, I am lacking knowledge on how programs using fork() exactly outputs and how parent/child processes combinations are exactly as stated below.
My Approach:
Originally we have a parent process running p0 then pid forks a child process.
So, all possible outputs will always contain 0 because num=0 initially and before the first prinf() statement num is not set to any other number.
I believe the timing for parent and child process execution is random because it can come out in any order.
case 1: p0 prints 02 because there can be a case where pid is a parent. Then the forked child process p1 prints 01. Final answer would be 0201
case 2: p0 prints 01 because there can be a case where pid is a child (is it a child of the main process from kernel? ). Then the forked child p1 is a parent so it prints 0102. Final answer would be 0102
case 3: p0 prints 00 since pid is not a child or parent. Then the forked child p1 prints 12 because it is a child and a parent at the same time. Final answer would be 0012.
case 4: p0 prints 00 since it is not a parent or child. Then the forked child process p1 prints 21 because it can be a parent and a child at the same time.
Final answer would be 0021.
Code:
#include <stdio.h>
int num = 0 ;
int main(int argc, char *argv[])
{
  int pid ;
  pid = fork() ;

  printf("%d",num) ;

  if (pid == 0) {
    num = 1;
  } else if (pid > 0) {
    num = 2 ;
  }
  printf("%d",num) ;
}

Answer: 0102 or 0012 or 0201 or 0021
Comment: the parent and child are racing on that `printf` to `stdout`. There isn't much else to it.
Comment: You have no control over when each of the two processes will run or in which order. If you want the processes work in a specific order, you have to use some sort of interprocess synchronization.
Comment: Yes, but what I'm trying to understand is how does one find the pattern of all possible outputs because that is what im not understanding because I can randomly print numbers like 0120 but it isn't included in the 'answers'.
Comment: Read [Advanced Linux Programming](http://advancedlinuxprogramming.com/). It has several chapters explaining `fork` and how to use it and when.
Comment: C is, disregarding loops and such, pretty much sequential. Statements are performed from top to bottom, in the order you have programmed it. So if the code should print the number `0` before either `1` or `2`, then the number `0` will *never* be printed after you print either `1` or `2`. That means the case `0120` is *impossible* to get.
Answer: I guess you are overcomplicating it. What happens after a fork(), is that you have two instances (father and son) executing, each of them performing two output operations.
The two instances are independent and don't know anything about each other, so one will not wait for the other to complete and you have a so-called race condition. The only guarantee is that each process will output first 0, then 1 (or 2), because that's the order of operations in each of them. But you can't say how the four output operations will be interleaved.
Comment: I'm starting to understand that a parent process will always print 02 and child process will always print 01 so the combinations of output really comes from interleaving basically?
Comment: would 0120 be a possible output?
Comment: No, because you must retain the correct order for each instance: first `0`, then `1` or `2`. `0120` could have been `01` and `20` or `02` and `10`, and both do not respect that.
Comment: When you say the first  outputs must be 0 and then 1 or 2. Does that mean position 0 is 0 then position 1  is  1 or 2? Because what if position 1 is 0 does that mean fork() failed?
Comment: No, `0012` is ok. Imagine the two instances are running in separate windows: one will output `01` and the other `02`. Right? Now try to interleave the two outputs: `0102`, `0012` are ok, but `0120` is not, because there is no `0` following a `1` or `2` or `0` in the separate outputs.
Comment: Yes, exactly. What's more, if you printed more than one character per `printf`, the outputs could be even interleaved at a character level, so if one process printed `HELLO WORLD` and the other `foo bar baz`, you could get `HELfoo  LObarW bazORLD` as output, as long as the order of the two independent outputs is not changed.
Answer: Let's call the parent process A, and the child B.  A is always going to print a 0 followed by a 2. B is always going to print a 0 followed by a 1. The timing of A with respect to B is undefined. The output from A could print before, interleaved, or after the output from B.
There are actually six possible outcomes as shown below. However, you'll only see four different output patterns, because you can't tell whether A or B printed first, when the output starts with 00.
AABB
0201

ABAB
0021

BAAB
0021

ABBA
0012

BABA
0012

BBAA
0102

Comment: That makes a lot of sense thanks for clearing it up. From my understand I will try to study this and understand more so I may respond later because I  just now understood that it basically depends on interleaving and time
Comment: I will review this output you displayed and if I have questions I will leave comments
Comment: So when AA or BB is occurring in the pattern that means there are no faults or interleaving but when AB, BA occurs that means there is a fault/error and interleaving occurs?
Comment: @geforce The A and B processes run independently, but share a single output device. On a multicore processor, A and B will run simultaneously and will race to generate output. If A wins, you'll see AABB. If B wins then BBAA. Sometimes the timing is so close that the outputs interleave, and you get something like ABAB. On a single core processor, the operating system will switch between A and B at regular intervals. So A might output a 0, and the OS switches to B which outputs 0 1, and then the OS switches back to A, resulting in ABBA. No faults/errors are involved, it's just multitasking.


Problemas com NaN Jquery

Question: boa noite, estou tentando gerar o resultado multiplicando os valores dessas textbox*valores do span, entretanto ele acusa que o valor não é um número, gostaria de entender qual implementação eu estou fazendo de errado.
Fiddle: https://jsfiddle.net/6mkzzvqz/57/
HTML

<form action="#">

        <input type="text" class="qtdpedidos" value="0"/>

 10.00

        <input type="text" id="qtdpedidos" class="qtdpedidos" value="0"/>

 10.00
  </div

</form>

Valor do Pedido: R$0.00

Jquery
 $(document).ready(function() {

                $(".pizza-add-sub").append('
+

-
');
                $(".qty-pizza").on("click", function() {

                var $button = $(this);
                var oldValue = $button.parent().find("input").val();
                if ($button.text() == "+") {
                  var newVal = parseFloat(oldValue) + 1;
                } else {
                  // Don't allow decrementing below zero
                     if (oldValue > 0) {
                        var newVal = parseFloat(oldValue) - 1;
                        } else {
                        newVal = 0;
                      }
                }
                $button.parent().find("input").val(newVal);

            var valorTotal = 0;
        $.each($(".quantity"), function(){
              valorTotal = Number($(this).find(".qtdpedidos").val()) * Number($(this).find(".item span").html());
              document.getElementById("resultado").innerHTML = parseFloat(valorTotal);
        });
             });
            });

Answer: Você necessita da soma dos dois textbox multiplicados pela soma das duas spans é isso? caso sim segue o script abaixo:
 $(document).ready(function () {

            $(".pizza-add-sub").append('
+

-
');
            $(".qty-pizza").on("click", function () {

                var $button = $(this);
                var oldValue = $button.parent().find("input").val();
                if ($button.text() == "+") {
                    var newVal = parseFloat(oldValue) + 1;
                } else {
                    // Don't allow decrementing below zero
                    if (oldValue > 0) {
                        var newVal = parseFloat(oldValue) - 1;
                    } else {
                        newVal = 0;
                    }
                }
                $button.parent().find("input").val(newVal);
                /*var v1 = Number($('#item1 span').html());
                var v2 = Number(document.getElementById("qtdpedidos").value);*/
                var valorTotal = 0;
                var valoresMultiplicar = 0;
                $(".qtdpedidos").each(function () {
                    valorTotal += parseFloat($(this).val());
                })

                $(".item span").each(function () {
                    valoresMultiplicar += parseFloat($(this).html());
                })
                $("#resultado").text((valorTotal * valoresMultiplicar).toString());
            });
        });

Detalhe:
Seu script estava com erro pelo trecho:
Number($(this).find(".item span").html())

Caso tenha que somar e multiplicar separadamente as spans e textbox segue script e html:

    <form action="#">

                    <input type="text" class="qtdpedidos" value="0" />

                10.00

                    <input type="text" id="qtdpedidos" class="qtdpedidos" value="0" />

                10.00

    </form>

Valor do Pedido: R$0.00

Script:

Answer: O problema esta ocorrendo no find do obj em: "$(this).find(".item span").html();" ele não encontra, vem "undefined". o que fiz foi adicionar um parent(), fiz algumas outras modificações mais não afetam o resultado.

$(document).ready(function () {
    $(".pizza-add-sub").append('
+

-
');
    $(".qty-pizza").on("click", function () {
        var newVal = 0;
        var $button = $(this);
        var oldValue = $button.parent().find("input").val();
        if ($button.text() == "+") {
            newVal = parseFloat(oldValue) + 1;
        } else {
            // Don't allow decrementing below zero
            if (oldValue > 0) {
                var newVal = parseFloat(oldValue) - 1;
            }
        }
        $button.parent().find("input").val(newVal);
  /*var v1 = Number($('#item1 span').html());
  var v2 = Number(document.getElementById("qtdpedidos").value);*/
        var valorTotal = 0;
        $.each($(".quantity"), function () {
            var qtd_pedidos = $(this).find(".qtdpedidos").val();
            var total_pizza = $(this).parent().find(".item span").html();

            valorTotal = Number(qtd_pedidos) * Number(total_pizza);
            document.getElementById("resultado").innerHTML = parseFloat(valorTotal);
        });
    });
});

Problemas com NaN Jquery


Recommendations for Linear Algebra Self Study (PhD preparation)

Question: This is my first post, so I do apologize if I've missed something important.
I'm preparing to pursue a PhD in statistics, and I've recently realized that my linear algebra knowledge is not "up to par."
The class that I took only stopped at orthogonal sub spaces, and I know that's just not sufficient.
Does anyone have any recommendations for a linear algebra textbook that would be sufficient for self study and get me to the level that I need?
I've heard some, good things about Linear Algebra Done Right and Linear Algebra Done Wrong.
Comment: Some popular recommendations in this answer: https://stats.stackexchange.com/a/21351/119261.
Answer: Hello Statistijed and welcome to Cross Validated! I am sure you will get a lot of different answers on here but my recommendation (given that you have a good grasp of everything in a basic undergrad linear algebra course (so I would say through Axler Ch.3 at least)) is to focus on "Numerical Linear Algebra" and "Matrix Computations". I find this computational approach to linear algebra to be more useful, atleast that has been the case for me so far.
So I'd recommend picking up either Watkins or Golub and Van Loan and working through whatever seems most interesting. At the very least make sure you get SVD in and maybe also LU factorization. The least squares problems might also be interesting to you.
This is just my opinion, of course. Good luck!
Answer: Good sources for learning linear algebra for statistics is books about multiple linear regression of multivariate statistics with appendices detailing what they need. Look at Seber and Lee  or Mardia, Kent & Bibby. Or more modern works like those listed at Looking for modern references in Mathematical Multivariate Statistics.  Then you will also see what kind of linear algebra you need to understand!
A linear algebra introduction geared for statistics is Linear Algebra and Learning from Data, which looks rather interesting.  This is an introduction structured around various tasks to do with data!
Answer: These spring to mind :
Matrix algebra useful for statistics.
Searle, S. R., & Khuri, A. I. (2017).  John Wiley & Sons.
Linear Algebra and Matrix Analysis for Statistics
Banerjee, S., & Roy, A. (2014). Crc Press.
Numerical linear algebra for applications in statistics.
Gentle, J. E. (2012). Springer Science & Business Media.
Also, this is a classic, although not specific to statistics:
Introduction to linear algebra (Vol. 3)
Strang, G.(1993). Wellesley, MA: Wellesley-Cambridge Press.
Answer:
Trefethen, Lloyd N., and David Bau III. Numerical linear algebra. SIAM, 1997

is comprehensive easy to read. A good portion of the book is available at the author's website.
Answer: Can't recommend specific books, but what you need to get well-versed on is:

Some introduction to vector spaces.
Linear applications and its basic properties.
Diagonalization and Jordan forms of matrices.
Inner products, norms and Gram's matrices.

If you master these topics, there's not much linear algebra that will put you in trouble


Pushforward of the vector field $\dfrac{d}{dx}$ by exponential, i.e $exp_{*}\dfrac{d}{dx}$ = $x\dfrac{d}{dx}$ on $R_{+}^*$

Question: I'm trying to proof the following statement coming from a book:
"Pushforward of the vector field $\dfrac{d}{dx}$ by exponential, i.e $exp_{*}\dfrac{d}{dx}$ = $x\dfrac{d}{dx}$ on $R_{+}^*$"
The only statement I have in my possession is that for $\phi$ a diffeomorphism between $M \rightarrow N$ , and $X$ a vector field, (which is a section of $TM$), on has the following property:
$\forall x$ in $N$
$(\phi_{*}X)(x) = d_{\phi^{-1}(x)}\phi$ . $X(\phi^{-1}(x))$
Hence, I tried applying the formula, $exp_{*}\dfrac{d}{dx}(x)$  =  $(d_{\exp^{-1}(x)}\exp)$ . $\dfrac{d}{dx}(\exp^{-1}(x))$ = $d_{\ln(x)}\exp$ . $\dfrac{d}{dx}(\ln(x))$
= $d_{\ln(x)}\exp$ . $\dfrac{1}{x}$ = $exp(1/x)$
But if the result I'm trying to prove is right, I should have that $\forall x$ in $R_{+}^*$
$x\dfrac{d}{dx}(x)$ = $x$
Am I missing something more conceptual ? Thank you in advance for explanation
Comment: Isn't the definition of the pushforward of $\phi : M \to N$ of the vector field $X$ on $M$ given by $(\phi_* X)f := X(f\circ\phi^{-1})$ for every smooth function $f$ on $N$? Note that $f\circ\phi^{-1}$ is a function on $M$ so we can apply $X$ on that.
Comment: In accordance to my courses on differentiable manifold, $\phi_{*}X$ is a vector field. So you must apply $x \in M$ to it. For me the notation of the associated derivative of $\phi_{*}X$ writes, $\mathcal{L}_{(\phi_{*}X)}: f \rightarrow \mathcal{L}_{(\phi_{*}X)}(f) = (\mathcal{L}_{X}(f\circ \phi)) \circ \phi^{-1}$. It's just a difference of notation.
Comment: I'm confused about the formula $(\phi_{*}X)(x) = d_{\phi^{-1}(x)}\phi$ . $X(\phi^{-1}(x))$. Shouldn't there be a function $f\in C^\infty(N)$ somewhere since the vector field $X$ is a derivative?
Comment: @md2perpe If $\varphi \colon M \to N$ is a diffeomorphism and $X$ is a vector field on $M$, the pushforward of $X$ by $\varphi$, denoted by $\varphi_* X$, is the vector field on $N$ which is obtained by transporting $X$ through $\varphi$. The formula given by OP, namely $(\varphi_* X)(p) = \mathrm{d}\varphi( \varphi^{-1}(p)) \cdot X(\varphi^{-1}(p))$ for $p\in N$, is the good one. It seems messy but in fact is a very natural definition, since $\mathrm{d}\varphi(\varphi^{-1}(p)) \colon T_{\varphi^{-1}(p)}M \to T_pN$ is a linear isomorphism
Comment: AFAIK there are a couple of definitions of vector space. One is as a derivation, i.e. $X$ acts on functions and gives functions, and it satisfies $X(fg) = (Xf) g + f (Xg).$ Another one is a section of $TM$ in which case it is a map taking a point $p\in M$ and giving a vector in $T_pM.$ When g0dLose writes "vector field $\frac{d}{dx}$" it seems like the definition as a derivation is used. On the other hand he also writes "$X$ a vector space, (which is a section of $TM$)". But I guess that there is a natural isomorphism between the two definitions.
Comment: @md2perpe Yes, there is a canonical isomorphism between these two notions, and there is nothing wrong with saying "$\frac{d}{dx}$ is a vector field" when meaning "a section of the tangent bundle": in differential geometry, we always write "Let $X = \sum_i X^i \partial_i$" be a vector field"! I agree this seems a bit weird at the first sight.
Comment: Which book is this from, please? It'd be nice to check a couple of things there if possible.
Comment: @rych "Introduction aux variétés différentielles" of Jacques Lafontaine
Answer: The pushforward of a vector field is well-defined just by a diffeomorphism (or in a Lie group), that is, if $\varphi :M\to N$ is such diffeomorphism then $\varphi _*:\mathfrak{X}(M)\to \mathfrak{X}(N)$, where $\mathfrak{X}(D)$ is the space of smooth vector fields on $D$.
The pushforward is defined by
$$
(\varphi _*X)_{\varphi (p)}f=X_p(f\circ \varphi )
$$
In this case if $\varphi :\mathbb{R}\to (0,\infty ),\, x\mapsto e^x$ you have
$$
\left(\exp_*\frac{\partial}{\partial x}\right)_rf=\left .\frac{\partial}{\partial x}\right|_{\ln r}(f \circ \exp)=(f'\circ \exp)(\ln r)\exp'(\ln r)=r\cdot f'(r)=\left .t\frac{\partial}{\partial t}\right|_{r}f
$$
where $\frac{\partial}{\partial t}$ is the canonical basis of $\mathfrak{X}((0,\infty ))$ and $f$ is any smooth function in $(0,\infty )$.
Comment: First, thanks for explanation, to me the pushforward was defined only on M, not on function. To me the "associated derivation of the pushforward" was defined on function; Which I denote by $\mathcal{L}_{X}$ for X a field, (and so for the case of the pushforward, replace $X$ by $\varphi_{*}X$.)
Comment: Secondly: According to your notation: $(\varphi_{*}X)_{p}(f) = X_{\varphi^{-1}(p)}(f\circ \varphi)$

On the other hand, according to my course: $X_{x}(f) = d_{x}f.X_{x}$

Hence: $X_{\varphi^{-1}(p)}(f\circ \varphi) = d_{\varphi^{-1}(x)}(f\circ \varphi).X_{\varphi^{-1}(x)}$.

Replacing by non abstract vector field and diffeomorphism one has:

$d_{\varphi^{-1}(x)}(f\circ \varphi).X_{\varphi^{-1}(x)} = f'(x)x.\dfrac{d}{dx}(ln(x)) = f'(x)x. 1/x = f'(x) = \dfrac{d}{dt}∣_{x}f $ What's wrong with what I've done ?
Comment: this $d_{\varphi^{-1}(x)}(f\circ \varphi).X_{\varphi^{-1}(x)} = f'(x)x.\dfrac{d}{dx}(ln(x))$ is wrong, as $\exp^{-1}(x)=\ln x$ is a point, not a function, you dont differentiate a point, what you differentiate is $f$
Comment: The formula comes from a book, it's 100% true, the fact is that in what I wrote, $X$ is a vector field to me, hence a section of $TM$ and so $X_{\varphi^{-1}(x)}$ belongs to $T_{\varphi^{-1}(x)}M$
Answer: $\def\R{\mathbb{R}}%$@Masacroso's is the answer, but I think we could also use the Fréchet derivative of the map between two copies of $\R$, $Dexp: \R_1\to\R_2$, $Dexp_x=e^x=y$; for an arbitrary $h\in \R_1$, $Dexp_x(h)=e^xh\in \R_2.$
The map derivative, on the other hand, is a pushforward of tangent vectors. We can use what's called canonical identification or natural isomorphism: $g_1: T\R_1\to\R_1$ and $g_2: T\R_2\to\R_2$. The relation formula (see @levap's answer here for example) between the pushforward and the Fréchet derivative of our map $exp$ is
$$exp_{*p}=g_2^{-1}\circ Dexp\circ g_1:T\R_1\to T\R_2$$
And so we have
$exp_{*x}(h\tfrac{d}{dx})=[g_2^{-1}\circ Dexp\circ g_1](h\tfrac{d}{dx})=[g_2^{-1}\circ Dexp_x](h)=g_2^{-1}(e^xh)=(e^xh)\tfrac{d}{dy}$,
where $\tfrac{d}{dy}$ is the basis vector on the $T\R_2$. Taking $h=1$ we finally have
$$exp_{*x}(\tfrac{d}{dx})=y\tfrac{d}{dy}$$


How to make functions of three cylinders?

Question: Three-cylinder with height $4$ $m$ and radii of the base $5,3,1$ $m$ are going to put (in this order). Give an explicit formula for the following functions, you examine the functions on continuity and draw their graphs.
a)The cross-sectional area $F(h)$ of horizontal sections of the body obtained as Function of the height $h\in[0, 12]$.
b) The volume $V(h)$ of the body of height $h\in[0, 12]$.
I don't understand this example, I don't know how to start, if someone can help me I would be really thankful
I understand that the they are on top of each other. But still don't know how to calculate a) and b)
Comment: What about the area between $0$ and $4$, $4$ and $8$, $8$ and $12$?
Comment: When I calculate that what i need to do?
Answer:
Is it not clear how the surface area of the cross section and the volume underneath is changing if you move the red plane from level zero to level 12?
$$F(h)=
\begin{cases}
\color{blue} {\pi2.5^2},&\text {if } 0\le h<4\\
\color{red}{\text{undefined }},& \text {if }h=4\\
?,&\text {if }4<h<8\\
?,&\text {if }h=8\\
?,&\text {if }8< h\le 12.\\
\end{cases}
$$
And similarly for the volume underneath...
$$V(h)=
\begin{cases}
\color{blue} {\pi2.5^2\times h},&\text {if } 0\le h\le4\\
\color{blue} {\pi2.5^2\times 4+\pi1.5^2\times (h-4)},& \text{ if }4<h\le8\\
?,&\text {if }8< h\le 12.\\
\end{cases}
$$
Graphs:
Comment: I don't know how to do it for volume
Comment: and how to count that '?'
Comment: Lady, @LadyA, I'll edit forya...
Comment: How to make graph? I don't understand and is h undefined for h=8?
Comment: Lady, for $h=4$ and for $h=8$ the area is undefined, because it depends on the way we place the cylinders on each other... Graph? Ok I plot a graph. Huhh. You ought to do something on your own.
Comment: How to do if I don't understand. Thank you.
Comment: How do I get volume if 8<h≤12?
Comment: I still don't understand what is here funciton, how i can find explizite one?
Comment: Lady, if $h$ is between $8$ and $12$ then $V(h)=\pi\times 2.5^2\times4+\pi\times1.5^2\times4+\pi\times0.5^2\times(h-8)$. There is no more explicite function than the one we have.
Comment: And how to examine the functions on continuity now?
Comment: Lady, $F$ is continuous over $[0,12]$ but at $4$ and $8$. At those latter points $F$ is not even defined because of the undefined nature of tha placing of the cylinders. $V$ is continuous all over the interval. But, now, you tell what kind of school you go to?
Comment: But I get that h for  8<h≤12 is 0,785, so h-8 I'll get negative number hm..
Comment: If $8\le h\le 12$ the $h-8$ is not negative.
Comment: School? What do you think? Guess and I'll tell you if you're right.
Comment: but i get that h there is 0,785
Comment: How can $h$ be $0.785$ if $h$ is between $8$ and $12$?
Comment: But pi*2,5^2 what is that now
Comment: oh area? sorryy


How should I choose a Ukulele?

Question: I am planning to buy a ukulele tomorrow, and I am a bit lost.  I did manage to figure out the differences between a Soprano Ukulele and a Concert Ukulele, so I have chosen an Concert Ukulele, which I assume fits my musical choices.
The problem is choosing a specific model, I've seen many brands available and I am currently considering the the Aloha 30C Ukulele and the Ibanez UKC 10.
I am not sure which one I should pick, the reviews I've found from the Aloha are all in French, nothing interesting really.
How can I evaluate these ukeleles?
Comment: Welcome to the site!  If you check out the FAQ, you'll see that we don't answer questions related to shopping / brand choices.  If you can edit your question to pertain to performance practice, then I'm sure you'll get some great answers.
Comment: I think there's enough here that we don't have to close. Asking questions about _how to evaluate_ different models is fine, and that's mostly what this is about.
Comment: If you can try them in a shop, I think this would help you decide. I find that when I try instruments, I just 'know' when I find the one I like. It's unscientific, but if you love the feel of it then you might end up playing it more :)
Comment: @am75 Problem is, I cannot try the Ibanez :(
Comment: ok. At that price range, the wood will almost certainly be plywood, so it's probably down to construction quality, which is hard to judge like this. Based on familiarity and googlability I'd go for the Ibanez. (I've never heard of Aloha - possibly a European brand - whereas Ibanez are well known to make quality guitars, and that Ibanez model has 5 [positive] reviews on musiciansfriend.com).
Answer: Most of the same considerations come in as for a guitar:

How do I choose my first guitar for self-learning?
How do you identify a good acoustic guitar?

Ukuleles are generally nylon strung, so you don't need to worry about truss rods. You might want to think about amplification, and electric-acoustic ukes are increasingly common.
The most important advice is equally true for all instruments: don't spend serious money on an instrument you haven't held in your own hands, and tried out.
What you're proposing to spend here is one step more expensive than the bottom-of-the-range ukuleles that seem to be everywhere. It might be worth spending €30 on a really cheap one, and learning the basics on it, so that you can visit a music shop and know what you're looking for when trying out more serious instruments.
Answer: Generally, Soprano is the most common size. It makes classical and traditional ukulele sound. The soprano is the lightest instrument. It is suitable for any level ukulele player, especially beginner ukulele player and those have smaller hands and fingers.
On the other side, the concert is bigger than the soprano. The concert is suitable for any level ukulele player but it may be comfortable for those who have larger hands and fingers.
https://ukulelesreview.com/best-ukulele-for-beginners/

How should I choose a Ukulele?


Android LazyList initial load of listview doesn't show images until scrolling

Question: I am currently using the LazyList view from here:  https://github.com/thest1/LazyList
Everything is working great BUT the initial load of the listview.  No images are loading.  I have to actually scroll down and then back up for the images to populate.  Below is the code for the adapter that I am using.  What am I doing wrong here?
UPDATE: Note that I took out the tags for the imageviews to see if it would help, but I still get the same results.
public class BattleAdapter extends ArrayAdapter<Battle> {

private ArrayList<Battle> data = null;
private Context context;
private int layoutResourceId;
private ImageLoader imageLoader;

public BattleAdapter(Context context, int layoutResourceId,
        ArrayList<Battle> data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
    this.imageLoader = new ImageLoader(context);
}

static class BattleHolder {
    public CropImageView imageRight;
    public CropImageView imageLeft;
    public TextView displayNameRight;
    public TextView displayNameLeft;
    public TextView numComments;
    public TextView numVotes;
    public TextView timeLeft;
    public ImageView winnerImg1;
    public TextView winnerTxt1;
    public ImageView winnerImg2;
    public TextView winnerTxt2;
    public TextView tiedTxt1;
    public TextView tiedTxt2;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    BattleHolder holder = null;

    if (convertView == null) {

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        holder = new BattleHolder();

        convertView = inflater.inflate(R.layout.versus_list_item, null);
        holder.imageLeft = (CropImageView) convertView
                .findViewById(R.id.versus_challenger);
        holder.imageLeft.setClickable(false);
        holder.imageRight = (CropImageView) convertView
                .findViewById(R.id.versus_challenged);
        holder.imageRight.setClickable(false);
        holder.displayNameLeft = (TextView) convertView
                .findViewById(R.id.versus_challenger_name);
        holder.displayNameRight = (TextView) convertView
                .findViewById(R.id.versus_challenged_name);
        holder.numVotes = (TextView) convertView
                .findViewById(R.id.num_votes);
        holder.numComments = (TextView) convertView
                .findViewById(R.id.num_comments);
        holder.timeLeft = (TextView) convertView
                .findViewById(R.id.time_left);
        holder.winnerImg1 = (ImageView) convertView
                .findViewById(R.id.winner_img1);
        holder.winnerImg2 = (ImageView) convertView
                .findViewById(R.id.winner_img2);
        holder.winnerTxt1 = (TextView) convertView
                .findViewById(R.id.winner_img1_txt);
        holder.winnerTxt2 = (TextView) convertView
                .findViewById(R.id.winner_img2_txt);
        holder.tiedTxt1 = (TextView) convertView
                .findViewById(R.id.tie_txt1);
        holder.tiedTxt2 = (TextView) convertView
                .findViewById(R.id.tie_txt2);
        holder.timeLeft.setSelected(true);

        convertView.setTag(holder);
    } else {
        holder = (BattleHolder) convertView.getTag();
    }

    Battle battle = data.get(position);

    if (battle != null) {

        User challenger = battle.getChallenger();
        User challenged = battle.getChallenged();

        holder.displayNameLeft.setText(challenger.getDisplayName());

        holder.displayNameRight.setText(challenged.getDisplayName());

        holder.numComments.setText(Integer.toString(battle
                .getCommentCount()));
        holder.numVotes.setText(Integer.toString(battle.getVoteCount()));

        if (battle.getTimeLeft() != null) {

            if (battle.getTimeLeft().startsWith("-")) {
                holder.timeLeft.setText("Time's up. Calculating winner");
            } else if (battle.getTimeLeft().endsWith("responded")) {

                String newString = String.format(battle.getTimeLeft(),
                        challenged.getDisplayName());
                holder.timeLeft.setText(newString);

            } else
                holder.timeLeft.setText(battle.getTimeLeft());
        }

        imageLoader.DisplayImage(challenger.getPicPath(), holder.imageLeft);

        imageLoader.DisplayImage(challenged.getPicPath(), holder.imageRight);

        if (battle.getWinnerID() == -5) {
            holder.winnerImg1.setVisibility(View.VISIBLE);
            holder.winnerImg2.setVisibility(View.VISIBLE);
            holder.winnerTxt2.setVisibility(View.INVISIBLE);
            holder.winnerTxt1.setVisibility(View.INVISIBLE);
            holder.tiedTxt1.setVisibility(View.VISIBLE);
            holder.tiedTxt2.setVisibility(View.VISIBLE);
        }

        if (battle.getWinnerID() != 0 && battle.getWinnerID() != -1) {

            if (challenger.getUserID() == battle.getWinnerID()) {
                holder.winnerImg1.setVisibility(View.VISIBLE);
                holder.winnerTxt1.setVisibility(View.VISIBLE);
                holder.winnerImg2.setVisibility(View.VISIBLE);
                holder.winnerTxt2.setVisibility(View.INVISIBLE);
                holder.tiedTxt1.setVisibility(View.INVISIBLE);
                holder.tiedTxt2.setVisibility(View.INVISIBLE);

            }

            else if (challenged.getUserID() == battle.getWinnerID()) {
                holder.winnerImg2.setVisibility(View.VISIBLE);
                holder.winnerTxt2.setVisibility(View.VISIBLE);
                holder.winnerImg1.setVisibility(View.VISIBLE);
                holder.winnerTxt1.setVisibility(View.INVISIBLE);
                holder.tiedTxt1.setVisibility(View.INVISIBLE);
                holder.tiedTxt2.setVisibility(View.INVISIBLE);

            }
        }

        if (battle.getWinnerID() == 0 || battle.getWinnerID() == -1) {
            holder.winnerImg1.setVisibility(View.INVISIBLE);
            holder.winnerTxt1.setVisibility(View.INVISIBLE);
            holder.winnerImg2.setVisibility(View.INVISIBLE);
            holder.winnerTxt2.setVisibility(View.INVISIBLE);
            holder.tiedTxt1.setVisibility(View.INVISIBLE);
            holder.tiedTxt2.setVisibility(View.INVISIBLE);
            Log.i("BattleAdapter", "No winner");
        }

    }

    return convertView;
}
}

Answer: Use AndroidQuery for this. ImageLoader is not anUniversal ImageLoader, Android has provided us AndroidQuery and its awsom to use, very fast and efficient.
Download jar from here: http://code.google.com/p/android-query/
Add this jar to your Build path.
private AQuery androidAQuery;
androidAQuery=new AQuery(this);
                androidAQuery.id(YOUR IMAGE VIEW).image(YOUR IMAGE URL, true, true,DEFUALT IMAGE(optional));

Answer: try this, Add the below permission in your manifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Comment: Question is about difficulty in loading images on initial load of the listview. Description states that the images are loaded fine after the list is scolled even a bit.


What makes the 4/4 back-beat rhythm of rock-n-roll so compelling?

Question: So much contemporary/pop music is tied to the rock-n-roll standard 4/4 back-beat rhythm, why is this?
Contemporary rock music (amongst other styles) loves a bit of dissonance, angular melody lines, distortion, and generally to dirty things up, but it still hangs on tightly to the 4/4 back-beat. Of punk this seems especially true and especially surprising.
Is there something psychological or physiological which makes this rhythmic pattern so compelling?
Is it simply cultural dominance, a sort of familiar comfort?
Why is unusual harmony 'interesting' whist unusual rhythm so hard to deal with?
Comment: not putting an answer because i think it contradicts your observation which i think is generally true, but i think of syncopation as rhythmic dissonance. I think the ear does crave this and it is one of the reason people love funk music. it gives you a bit of what you expect with a hint of something you don't expect to hear to keep you interested.
Answer: We have two legs, and so we tend to like rhythms which 'go into' two. We also tend to like tempos which match things we can do with our legs -- slower than a stroll hardly feels like a rhythm, faster than a sprint and we mentally recalibrate to half-tempo.
By the same token, there are lots of actions like scrubbing or sawing that are naturally fall into twos - back and forth.
I don't think it's right to point specifically at 'contemporary' music. Folk music and classical music are primarily in two-legged rhythms. 4/4 is the most common time signature, followed by 2/4.
At first glance, waltzes would appear to disprove my argument. But bars of 3/4 tend to come in pairs (One two three, Two two three.) so we're back to that walking rhythm. There are plenty of 'contemporary' songs in 3/4.
12/8 is more or less equivalent to 4/4 with triplets. 6/8 is more or less equivalent to 3/4. And so on.
The time signatures that don't fit into this are prime numbers higher than 3 - 5/4, 7/8. But these are rare in classical music, possibly more so than in contemporary art-rock, prog-rock and jazz.
Why is 4/4 more popular than 2/4? I'm not sure. Maybe that tiny bit of variety when scrubbing or sawing or marching or dancing is welcome.
Comment: Even walking, when you take two steps it's not "left-right|left-right" (2/2) but "left-and-right-and|left-and-right-and" (4/4) since each step is in two parts.
Comment: That's a really nice answer. It would also tie in nicely with the work place or chain gang song, and of course running or rowing type activities to motivating music.
Comment: By the way, exotic time signatures are *extremely* common in classical music of the past 100-or-so years.
Comment: @nonpop depends what you mean by "extremely common". I think the popular favourites still tend to be 3/4 and 4/4 - for example I went to see Prokofiev's 1944 *Cinderella* the other week, which is (almost?) all straightforward time sigs.
Comment: That's possible, and it might even be that their popularity is partly due to simple meters, as it's often easier to listen. But there are also popular (or at least famous) composers, like Messiaen or Ligeti, who often don't even bother to write time signatures as pretty much every measure (when they exist) has a different, often complex, one.
Comment: I don't think that this entirely answers the question: they were asking about the 4/4 **back-beat** popularity, not just 4/4 itself.
Answer: A strong, steady pulse makes a kind of very stable skeleton for the music. If it's there, you can do other things without completely breaking the style or making the piece incoherent. Compare it to this:

Play a strong, continuous low note. You can play almost anything on top of it and the music still seems to be "calm" and rooted in a way.
Play a strong, continuous high note. Almost every low note you play will feel like it takes the music to a new place. The root is missing.

Pulse and other stuff have a similar relationship. It's easier to break the other stuff without making the piece sound "wrong" or "not in style".
As for why 4/4, slim gave some possible reasons. I also think it's (pop-)cultural. Personally I find for example some places in Stravinsky's Rite of Spring much more rhythmically compelling than any rock piece I've ever heard. And those places have nothing to do with 4/4, and even less to do with steadiness.
Answer: most answers are good, but adding a possible answer to the 4/4:
A riff or beat (often) is around 4 or 8 beats, and therefore it is much easier to count out a rhythm with one or two measures of 4/4 instead of 2 or 4 measures of 2/4 (considering I have never seen 8/4 used before)
Comment: [No reason you can't use 8/4](http://en.wikipedia.org/wiki/List_of_musical_works_in_unusual_time_signatures#8.2F4), but 4/4 and 2/4 are normally different beats.  Besides that I don't see why 2/4 would be "harder to count".


Math term for the distance between the center and a chord of a circle

Question: I wonder if there is a single-word expression meaning the shortest distance between the center and a chord of a circle.
Radius is the distance from the center to the edge, so it is not the answer I'm looking for.
Especially, I want to express
[Example sentence]
<code>The ___ of this dot of the circle is 3.54.
</code>
Comment: Don't think so. The perpendicular distance from the centre to the chord will do it though.
Answer: It is the APOTHEM

In the given figure , we have the Chord of length $a$. Here , $r$ is the APOTHEM , while $R$ is the RADIUS , with the remaining $h$ being the SAGITTA.
$r+h=R$
reference :
https://mathworld.wolfram.com/Chord.html
https://mathworld.wolfram.com/Sagitta.html
https://mathworld.wolfram.com/Apothem.html
Comment: Learn something every day! Use the words though and no one will know what you mean
Comment: I get what you mean , though (1) There are many uses already [ Eg https://en.wikipedia.org/wiki/Sagitta_(geometry) & https://www.mathsisfun.com/definitions/apothem.html ] (2) The terms are more common in Certain Areas like optics & astronomy & trigonometry (3) These are Latin terms , hence they may be well known to Certain groups (4) Every common term now was uncommon in Early Stages [ Eg PI versus TAU & Neutron versus Neutrino ] # @Paul


AVPlayer : Fade in audio of a video

Question: I'm trying to fade-in the audio track at the start of a video using AVPlayer. I don't have any error when the video is played, it seems that the volume is already at 100%, and that my volumeRamp audio fade-in is not executed.
This is my code :
    guard let url = (self.videoView.player?.currentItem?.asset as? AVURLAsset)?.url else { return }

    let asset = AVAsset(url: url) as AVAsset
    let duration = asset.duration
    let durationInSeconds = CMTimeGetSeconds(duration)
    let playerItem = AVPlayerItem(asset: asset)

    let firstSecond = CMTimeRangeMake(CMTimeMakeWithSeconds(0, 1), CMTimeMakeWithSeconds(1, 1))

    // Configure audio mix to fade in

    let audioParams = AVMutableAudioMixInputParameters(track: asset.tracks.first!)
    audioParams.setVolumeRamp(fromStartVolume: 0, toEndVolume: 1, timeRange: firstSecond)

    let mix = AVMutableAudioMix()
    mix.inputParameters = [audioParams]
    playerItem.audioMix = mix

    self.videoView.player?.replaceCurrentItem(with: playerItem)
    self.videoView.player?.play()

Am I doing something wrong ? (I'm testing with simulator)
Answer: As mentioned here: Apple Library
AVAudioMix only supports file-based assets.

AVPlayer : Fade in audio of a video


MongoDB aggregation $divide

Question: I'm pretty new to javascript. I would like to calculate the average number of sales (averageSales = totalSales/ numOrders). However, I am having some difficulty. I would really appreciate any help or guidance.
const averageSale = await Order.aggregate([
        {
          $group: {
            _id: null,
            totalSales: { $sum: '$totalPrice' },
            numOrders: { $sum: 1 },
          },
        },
        {$project:{totalSales:1, numOrders:1, averagesale: { $divide: ['$totalSales', '$numOrders']}}},
      ]);

Here are a few of my documents
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import Order from '../models/orderModel.js';
import User from '../models/userModel.js';
import Product from '../models/productModel.js';
import { isAdmin, isAuth } from '../utils.js';

const orderRouter = express.Router();
orderRouter.get(
    '/',
    isAuth,
    isAdmin,
    expressAsyncHandler(async (req, res) => {
      const orders = await Order.find({}).populate('user', 'name');
      res.send(orders);
    })
  );
orderRouter.get(
    '/mine',
    isAuth,
    expressAsyncHandler(async (req, res) => {
      const orders = await Order.find({ user: req.user._id });
      res.send(orders);
    })
  );

  orderRouter.get(
    '/summary',
    isAuth,
    isAdmin,
    expressAsyncHandler(async (req, res) => {
      const orders = await Order.aggregate([
        {
          $group: {
            _id: null,
            numOrders: { $sum: 1 },
            totalSales: { $sum: '$totalPrice' },

          },
        },
      ]);
      const users = await User.aggregate([
        {
          $group: {
            _id: null,
            numUsers: { $sum: 1 },
          },
        },
      ]);
      const dailyOrders = await Order.aggregate([
        {
          $group: {
            _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
            orders: { $sum: 1 },
            sales: { $sum: '$totalPrice' },
          },
        },
        { $sort: { _id: 1 } },
      ]);
      const productCategories = await Product.aggregate([
        {
          $group: {
            _id: '$category',
            count: { $sum: 1 },
          },
        },
      ]);

      const productName = await Product.aggregate([
        {
          $group: {
            _id: '$name',
            count: { $sum: 1 },
          },
        },
      ]);

      const productBy = await Product.aggregate([
        {
          $group: {
            _id: '$qty',
            count: { $sum: 1 },
            name: { $sum: '$name' },
          },
        },
      ]);

      const averageSale = await Product.aggregate([
        {
          $group: {
            _id: null,
            totalSales: { $sum: '$totalPrice' },
            numOrders: { $sum: 1 },
          },
        },
        {$project:{totalSales:1, orders:1, averagesale: { $divide: ['$totalSales', '$numOrders']}}},
      ]);

      res.send({ users, orders, dailyOrders, productCategories, productName, productBy, averageSale });
    })
  );

import mongoose from 'mongoose';

const orderSchema = new mongoose.Schema(
  {
    orderItems: [
      {
        name: { type: String, required: true },
        qty: { type: Number, required: true },
        image: { type: String, required: true },
        price: { type: Number, required: true },
        product: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Product',
          required: true,
        },
      },
    ],
    shippingAddress: {
      fullName: { type: String, required: true },
      address: { type: String, required: true },
      city: { type: String, required: true },
      postalCode: { type: String, required: true },
      country: { type: String, required: true },
    },
    paymentMethod: { type: String, required: true },
    paymentResult: {
        id: String,
        status: String,
        update_time: String,
        email_address: String,
      },
    itemsPrice: { type: Number, required: true },
    shippingPrice: { type: Number, required: true },
    taxPrice: { type: Number, required: true },
    totalPrice: { type: Number, required: true },
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    isPaid: { type: Boolean, default: false },
    paidAt: { type: Date },
    isDelivered: { type: Boolean, default: false },
    deliveredAt: { type: Date },
  },
  {
    timestamps: true,
  }
);
const Order = mongoose.model('Order', orderSchema);
export default Order;

Answer: I am assuming you are trying to find the average sales price, there's no need to use $divide as $avg will do the job.
May I know what you meant by calculate the average number of sales (averageSales = totalSales/ numOrders) if this not what you are looking for?
db.collection.aggregate({
  "$group": {
    "_id": null,
    "totalSales": {
      $sum: "$totalPrice"
    },
    "numOrders": {
      $sum: 1
    },
    "avgPrice": {
      "$avg": "$totalPrice"
    }
  }
})

Mongo Playground
Official Documentation

MongoDB aggregation $divide


Prove if $x > 3$ and $y < 2$, then $x^{2} - 2y > 5$

Question: My solution is:
Multiply $x > 3$ with $x$, yielding $x^{2} > 9$
Multiply $y < 2$ with $2$, yielding $2y < 4$
Thus, based on the above $2$ yielded inequalities, we can prove that if $x > 3$ and $y < 2$, then $x^{2} - 2y > 5$.
Is this a correct proofing steps?
Comment: Maybe just add since $2y < 4 \implies -2y > 4$.
Comment: Looks good to me. For the first one, there is a minor wording issue - actually you are not multiplying with $x$, but you do square on both sides.
Answer: Just $x^2-2y>3^2-2\cdot2=5$
Answer: Looks good!
$$x>3 \implies x^2>9$$
$$y<2 \implies 2y<4 \implies -2y>-4$$
Add the two to get: $$x^2-2y>5$$
Answer: For a roundabout way to prove it, which is overkill in this case, but may prove useful in other cases, note that the blue terms are positive since $x -3\gt 0$ and $2-y \gt 0\,$, therefore:
$$
x^2-2y =\left((x-3)+3\right)^2 - 2\left(-(2-y)+2\right) = \color{blue}{(x-3)^2} + 6\color{blue}{(x-3)} + \color{red}{9} +2\color{blue}{(2-y)} - \color{red}{4} \gt \color{red}{5}
$$
Answer: $x > 3,$ $y < 2$ implies $(-1)y > -2$ which is equal to $(-2)y > (-4).$ Hence we get $x^2 - 2y > 9 - 4 = 5.$
Answer: As a slightly extended version of Michael Rozenberg's answer, this can very simply be written down as:$%
\newcommand{\calc}{\begin{align} \quad &}
\newcommand{\op}[1]{\\ #1 \quad & \quad \unicode{x201c}}
\newcommand{\hints}[1]{\mbox{#1} \\ \quad & \quad \phantom{\unicode{x201c}} }
\newcommand{\hint}[1]{\mbox{#1} \unicode{x201d} \\ \quad & }
\newcommand{\endcalc}{\end{align}}
\newcommand{\subcalch}[1]{\\ \quad & \quad #1 \\ \quad &}
\newcommand{\subcalc}{\quad \begin{aligned} \quad & \\ \bullet \quad & }
\newcommand{\endsubcalc}{\end{aligned} \\ \\ \cdot \quad &}
\newcommand{\ref}[1]{\text{(#1)}}
\newcommand{\then}{\Rightarrow}
\newcommand{\when}{\Leftarrow}
%$
$$\calc
    x^2-2y
\op>\hints{using $\;x > 3\;$ and the fact that $\;a-b\;$ is monotonic in $\;a\;$;}
    \hint{using $\;y < 2\;$ and the fact that $\;a-b\;$ is antimonotonic in $\;b\;$}
    3^2-2\times2
\op=\hint{arithmetic}
    5
\endcalc$$
In my opinion, this proof is the most direct reflection of the basic idea of this proof.


What is the network address (x.x.x.0) used for?

Question: It appears to be common practice to not use the first address in a subnet, that is the IP 192.168.0.0/24, or a more exotic example would be 172.20.20.64/29.
The ipcalc tool I frequently use follows the same practice:
$ ipcalc -n -b 172.20.20.64/29
Address:   172.20.20.64
Netmask:   255.255.255.248 = 29
Wildcard:  0.0.0.7
=>
Network:   172.20.20.64/29
HostMin:   172.20.20.65
HostMax:   172.20.20.70
Broadcast: 172.20.20.71
Hosts/Net: 6                     Class B, Private Internet

But why is that HostMin is not simply 64 in this case? The 64 address is a valid address, right? And whatever the answer, does the same apply to IPv6?
Perhaps slightly related: it also appears possible to use a TCP port 0 and an UDP port 0. Are these valid or used anywhere?
Comment: Most TCP/IP stacks treat port 0 as a wildcard, i.e. "give me an unused port".
Comment: D'oh, I should've known that. Thanks for pointing it out. :)
Answer: I know this is an old thread but I was researching this myself and I didn't stop at "host zero isn't used because it is the network number" because I couldn't see why that mattered. Even if it is the network number it shouldn't stop it being used as a valid address as the mechanism to determine network number (ANDing the netmask) will still work with it to determine the network number.
Not using the all ones host address because it coincides with the broadcast address I was comfortable with, as it is a valid destination address already so when used it would be impossible to distinguish between those.
The more fully explained reason we can't use host zero is that it is also a broadcast address - although RFC1812 section 18.104.22.168 states that a router receiving packets addressed to it "SHOULD silently discard" them (their emphasis - not mine). However the same paragraph does allow those packets to be treated as a broadcast.
Here is the full sub-section
   (2) SHOULD silently discard on receipt (i.e., do not even deliver to
    applications in the router) any packet addressed to 0.0.0.0 or {
    <Network-prefix>, 0 }.  If these packets are not silently
    discarded, they MUST be treated as IP broadcasts (see Section
    [5.3.5]).  There MAY be a configuration option to allow receipt
    of these packets.  This option SHOULD default to discarding
    them.

Comment: +1 for not stopping on "it is the network number". As a thought, this RFC standard clearly wastes IP addresses, because there seems to be no technical reason for discarding such packets, nor there's a reason to have two broadcast addresses per subnet. Think how many host addresses could have been used in this running-out-of-IPv4-addresses world!
Comment: +1 This notion of mask.0 being off bounds probably stems from early convention. Some time ago a Linux based server once had an IP address x.x.x.0/24, and it worked OK, except some windows applications refused to connect to it, citing the IP address being invalid. There were no IP routers involved in the equation, only switches.
Answer: Because the first address in a subnet refers to the subnet itself and is used for routing purposes.
Comment: The first host address in a subnet is *not* used for routing purposes--I keep seeing this misconception. An IP address plus a subnet mask is used for routing and performing the comparisons necessary. The ability to facilitate routing is not affected by using the first address in the scope as a host address. The network address is shown in routing tables for clarity and ease of calculations, not because it's being assigned or used up in the routing process. A route of 192.168.32.5/16->192.168.0.1 is just as valid as 192.168.0.0/16->192.168.0.1--which would you rather see?
Comment: +1 for mentioning the routing table significance of the network address. One liners are important too... =)
Comment: I am going to apologize.  I have been having a long running debate about the use of network 0 and network all 1's when subnetting.  Yesterday, on multiple occasions, I read network when the word was host.  So I am sorry.  I considered just deleting my other posts, but that would not have been honest.
Comment: @dbasnett, well thank you very much indeed, you didn't have to do that. Because this site tends to attract the more novice users I'd say that very often you'll see answers on here that have some minor inaccuracies simply because we try to write our answers for a very general audience so that people searching via google etc. are drawn to the site and gain some benefit. There are big grey areas in this question and some of the answers which you rightfully picked up on but this isn't a site for cisco experts to dig deep into detail, but more to answer in the spirit of the questions. Thank you.
Answer: As Wesley, Chopper3, and Willy pointed out modern convention uses the first address (all zeroes host number) for the subnet and the last address (all ones host number) as the broadcast address.
For historical reasons many OSes treat the first address as a broadcast. For example, pinging x.x.x.0 from OS X, Linux, and Solaris on my local (/24) network gets responses. Windows doesn't let you ping the first address by default but you might be able to enable it using the SetIPUseZeroBroadcast WMI method. I wonder if you could get away with using .0 as a host address on an all-Windows network.
Answer: Early in the internet days, x.x.x.0 was used as the broadcast address for a network.  That was later changed to x.x.x.255.  I remember that there were options on SunOS to configure the broadcast either as .0 or .255 during that period.  So I guess for safety, .0 and .255 have been always a reserved numbers.
Comment: +1 for answering why there are two reserved addresses when one is all that is really required.
Answer: The first number in a subnet is the network's address itself. so 192.168.0.0/24 is the number that is used to refer to that subnet. Of course, the last address is the broadcast address where broadcasts are sent to and then pushed down to all clients on that subnet. In IP networking, you always remove 2 from the broadcast address to find the total amount of addressable IP addresses. 192.168.0.0/24 has a broadcast of 192.168.0.255 and thus 253 addressable addresses. 192.168.0.0/26 has a broadcast of 192.168.0.64 and thus 62 addressable addresses.
(Chop and Willy beat me to it -- but I'm grumpy and don't feel like deleting my post. =) )
Comment: Many OSes treat the first address as a broadcast. For example, pinging x.x.x.0 from OS X, Linux, and Solaris on my local (/24) network gets responses. Windows doesn't let you ping the first address by default but you can apparently enable it using the SetIPUseZeroBroadcast WMI method. I wonder if you could get away with using .0 as a host address on an all-Windows network.
Comment: A /24 has *254* host-assignable addresses (from .1 to .254) while a /26 has 62 host-assignable addresses (correct, but because you used .64 as a broadcast address, which is wrong. Your "subtract 2" rule is wrong, you don't take it from the broadcast address, but from the number of valid addresses in that subnet, which is 2^(32-n) where n is the prefix length (/n). For example, 192.168.0.252/30 doesn't have 253 usable addresses (that is absurd), but do have 2^(32-30) - 2 = 2^2 - 2 = 4 - 2 = 2 usable addresses.
Comment: @Gerald Combs: Thanks for pointing out the exact limitations of the 0 address. This is actually the answer I'm looking for! Perhaps you can convert/repost it so I can accept?
Comment: Why stop at /24? A /23 subnet has 512 total addresses, of which n.255 and (n+1).0 fall smack dab in the middle of the subnet, are neither the network or broadcast addresses, and *should* be allocable. However, since the RFC1812 section 184.108.40.206 apparently does not make this distinction, one must assume that .0 will be discarded regardless of its position in the network.
Comment: +1 for being grumpy ... now where is my coffee
Comment: +1 for not being a 1 line answer
Comment: +1 for the same reason, it's a better answer than mine :)
Comment: @Shtééf It's now an answer.
Comment: A small correction: broadcast address of 192.168.0.0/26 is 192.168.0.63 - the rule is that the host part of the address must be all zeros.
Answer: Host number 0 in every subnet is reserved primarily because it used to be a broadcast address.
The RFC says, paraphrased, should discard, but alternatively, use as broadcast, but also usable as a host number via some non-default option.
Now, octet 0 as in x.y.z.0 may very well be a perfectly valid non-zero CIDR host number, but in the past it would very occasionally have problems at isolated sites due to implementation bugs (possibly leftover class-full code) in the site's HW or SW.
Today, octet 0 works well enough to be assigned by ISPs and cloud platforms, though no doubt some services deliberately don't hand it out based on past experience.
Interestingly enough, all it would take to support host 0 at any specific site is support by the exact devices present on the local subnet ... once the packet is aggregated upstream it wouldn't even be possible to know that it actually had (CIDR) host number 0 in use. The WAN would not care at all.
Finally, if the local subnet's hosts use the all-1's host number for broadcasts and don't special-case the all-0's host number, you could leave the router in default and have a local-only "hidden" station. That might be useful for protecting embedded systems, like hack-prone cheap consumer routers...
Answer: x.x.x.0 (or first address on a subnet) is the network address and is used to identify which traffic is on the same subnet, and which needs to be routed to a different network.
Comment: If I take 192.168.0/23 (Which start at 192.168.0.0, and ends at 192.168.1.255) then 192.168.1.0 is a valid IP. Thus your "x.x.x.0" is not always correct.
Answer: There are two reserved IP addresses per CIDR block.  One is "the" network number and it will be even(bit 0) off.  The other is the directed braodcast (subnet broadcast) and it will have the host portion of the network set to all ones (odd number).  Here is an example from my subnet calculator:
Network           Net Broadcast     CIDR Mask              UsableHosts
192.168.254.0     192.168.254.31    27   255.255.255.224   30          AVL  isPrivate, isClassC
192.168.254.32    192.168.254.47    28   255.255.255.240   14          AVL  isPrivate, isClassC
192.168.254.48    192.168.254.55    29   255.255.255.248   6           AVL  isPrivate, isClassC
192.168.254.56    192.168.254.59    30   255.255.255.252   2           REQ 2  isPrivate, isClassC
192.168.254.60    192.168.254.63    30   255.255.255.252   2           REQ 2  isPrivate, isClassC


Doob-Meyer decomposition of number of times the diffusion cross a barrier

Question: Let $X_t=\mu t+\sigma B_t$ for all $t\geq 0$ be a drifted Brownian motion, where $B$ is a standard Brownian motion, $\mu\in\mathbb{R}$ and $\sigma>0$. Let $c\in\mathbb{R}$ and $L_t=\sum_{0<s\leq t}\max(0,\Delta\mathbb{1}_{\{X_s \geq c\}})$ be the number of times that $X$ crosses $c$ from below. As $L$ is a non-decreasing process, hence, a sub-martingale. Then by Doob-Meyer's theorem there should be a unique decomposition of $L$ such that
$$
L_t=M_t+A_t
$$
a.s., where $M_t$ is a martingale and $A_t$ is a non-decreasing process.
The question is, how to identify $M_t$ and $A_t$?
Answer: Since $L$ itself is a non-decreasing process, $A_t = L_t$ and $M_t = 0$ is such a decomposition.  By uniqueness of the Doob-Meyer decomposition, this is the only such decomposition.


Basic Probability / conditional probability

Question: I have a question:
If $P(A)=0.5, P(B)=0.3, P(A\text{ and }B)=0.1$
Find $P(A\text{ and }B | A \cup B)$
My answer:
$$P(A\text{ and }B | A \cup B)=\frac{P[(A\text{ and }B)\text{ and }(A \cup B)]}{P(A \cup B)}$$
The denominator is 0.5 + 0.3 - 0.1 = 0.7
But what about the numerator?
By drawing the Venn diagram I know that $P[(A\text{ and }B) \text{ and } (A \cup B)]$ is actually $P(A \cup B) = 0.1$. But is there any way to do it mathematically ?
I cannot simply multiply $P(A\text{ and }B)$ and $P(A \cup B)$ because A and B are not independent right? So how can I do it?
Comment: Hint regarding the events (A and B) and (A or B): one of those is a subset of the other.
Comment: So I can just say since (A and B) is a subset of (A or B), therefore $P[(A and B) and (A or B)] = P(A and B) ?$
Comment: Please add the `self-study` tag, and read its [tag-wiki](http://stats.stackexchange.com/tags/self-study/info).
Answer: First note that "and" refers to intersection "$\cap$" and "or" refers to union "$\cup$".
Intersection distributions over union (similar to how multiplication distributes over addition). i.e.
$$A \cap (B \cup C) = (A\cap B) \cup (A \cap C)$$
So in your scenario we have
$$\begin{align*}
(A\cap B) \cap (A \cup B) &=  ((A\cap B) \cap A ) \cup ((A\cap B) \cap B)\\
&= (A\cap B) \cup (A\cap B)\\
&= (A\cap B)
\end{align*}$$
Note you have a typo in your original statement:
$P[(A\text{ and }B) \text{ and } (A \cup B)]$ is actually $P(A \cup B) = 0.1$.
It should be $P(A \cap B) = 0.1$ (you had the number right).


Tangent bundle of Jacobian of a curve

Question: In An Introduction to the Theory of Special Divisors on Algebraic Curves, Griffiths states that

Obviously the tangent bundle of the Jacobian is trivial.

Why is this the case?
(Unfortunately, I don't have access to the entire book.)
Comment: Related (but unfortunately still without answers):  https://math.stackexchange.com/questions/339566/triviality-of-the-tangent-space-of-an-abelian-variety.  Related and with answers (but in the context of Lie groups):  https://math.stackexchange.com/questions/308691/let-g-be-a-lie-group-show-that-there-is-a-diffeomorphism-tg-cong-g-times-t/308798#308798.
Comment: It's an abelian variety so in particular a smooth group scheme and one can easily show that if $e\colon \operatorname{Spec}(k)\to A$ is the unit section and $f\colon A\to k$ the structure morphism then $\Omega^1_{A/k}=f^*e^*\Omega^1_{A/k}$. Now $e^*\Omega^1_{A/k}$ is trivial since it is a sheaf on a point.
Answer: The Jacobian of a curve is a group scheme, it acts on itself transitively (by translations), and the tangent bundle is equivariant. In general, there is an equivalence between the category of equivariant vector bundles on a homogeneous space of a group scheme and representations of the stabilizer of a point. In the case of the Jacobian the stabilizer is trivial, hence any its representation is trivial, hence any equivariant vector bundle is trivial. In particular, so is the tangent bundle.

Tangent bundle of Jacobian of a curve