Uniform convergence on the compact metric space

Question: Let $X$ be a compact metric space and let $f_n$ and $g_n$ be sequences of continuous functions from the metric space into the complex plane. If $\Sigma g_n$ converges uniformly and absolutely on $X$ and the absolute value of $f_n$ is equal or smaller than the absolute value of $g_n$ for each $n$, then, it is clear that $\Sigma f_n$ converges absolutely on $X$. However how can I show that $\Sigma f_n$ converges uniformly on $X$? I tried the Weierstrass M-test but failed... Could anyone please help me?
Comment: Use Cauchy convergence criterion.
Comment: What is Cauchy convergence criterion? Could you explain in more detail?
Comment: If $\forall \varepsilon >0$, $\exists N\in\mathbb{N}$, $\forall m\geq n>N$,  $|\sum_{k=n}^m f_n |<\varepsilon,$ then $ f_n$ converges uniformly.  The google translation tells me that it is called *Cauchy convergence criterion*,  which I'm not sure about.
Comment: I tried that too but cannot apply it to $f_n$. I cannot bound the partial sum of $f_n$ by $g_n$. Could you show me your way?
Comment: It is sufficient and necessary to show that $\sum |g_n|$ conveges uniformly. And by Dini's theorem, it is equivalent to show $\sum|g_n|$ is continuous.
Answer: This is wrong. It assumes that $\sum |g_n|$ converges uniformly, which does not follow from the assumptions.
Let $\varepsilon > 0$.
Since $\sum_{n=1}^\infty |g_n|$ converges uniformly, there exists $n_0 \in \mathbb{N}$ such that
$$n \ge n_0 \implies \forall x\in X \text{ holds }\sum_{k=n+1}^\infty |g_k(x)| = \left|\sum_{k=1}^\infty |g_k(x)|- \sum_{k=1}^n|g_k(x)|\right| < \varepsilon$$
Now for $M, N \ge n_0$ and $x \in X$ we have:
$$\left|\sum_{k=1}^M f_k(x)- \sum_{k=1}^N f_k(x)\right|= \left|\sum_{k=N+1}^M f_k(x)\right| \le \sum_{k=N+1}^M |f_k(x)| \le \sum_{k=N+1}^M |g_k(x)| \le \sum_{k=N+1}^\infty |g_k(x)| < \varepsilon$$
Therefore, $\sum_{k=1}^n f_k$ is uniformly Cauchy. This means that $\sum_{k=1}^n f_k$ is Cauchy in $C(X)$, the space of all continuous functions from $X$ to $\mathbb{C}$, equipped with the uniform metric: $$d_\infty(f_1, f_2) = \sup_{x \in X} |f_1(x) - f_2(x)|$$
Since $(C(X), d_\infty)$ is a complete metric space, the series $\sum_{k=1}^n f_k$ converges with respect to $d_\infty$, which in turn implies that $\sum_{k=1}^n f_k$ converges absolutely.
Comment: @Keith I know, I'm trying to fix it.
Comment: Only the sum of $g_n$ converges uniformly. It is not that the sum of absolute value of $g_n$ converges uniformly. How can I prove that  the sum of absolute value of $g_n$ converges uniformly?
Comment: @Keith Ah, I see. It does not have to follow from uniform and absolute convergence of $\sum g_n$, see [here](https://en.wikipedia.org/wiki/Uniform_absolute-convergence).
Comment: In the link there is the "distinction" between two concepts. What I intend is the uniform 'and' absolute convergence of $g_n$ not uniform absolute convergence.
Comment: @Keith Wait, but your problem states that $|f_n(x)| \le g_n(x)$. This automatically implies $g(x) \ge 0$ so $|g(x)| = g(x)$.
Comment: Oh sorry I will correct that.
Comment: @Keith Then this statement is false. Let $g_n$ be the sequence from the link, with the property that $\sum g_n$ converges absolutely and uniformly, but $\sum |g_n|$ does not converge absolutely. Now take $f_n := |g_n|$. For this sequence we certainly have $|f_n| \le |g_n|$ but $\sum f_n = \sum |g_n|$ does not converge uniformly.
Comment: I meant 'but $\sum |g_n|$ does not converge uniformly'. Ah, wait, the domain must be compact. I'm not sure then.


Passing params across components in ReactNative

Question: In my ReactNative application, I'm trying to pass some data across components using "route" in Navigation stack. I'm sending as in below code:
navigation.navigate('OtpScreen', { otpKey: '1234' });

I'm capturing in OtpScreen as below:
const OTPScreen = ({ navigation, route }) => {
   const { otpKey }= route.params;
}

Its throwing undefined 'params' when this screen is presented.
I've gone through sample code available in Snack
What could be the problem with my code?
Answer: Below your render type this
const param = route.params.otpKey;

I hope that helps!
Comment: Thanks a lot for the answer. But please observe that, I'm using navigation & route as part of the parameters and so it has to be "route.params.otpKey". I'll edit your answer. But its still not working.
Answer: I noticed that in the recent version of ReactNative, I've to use below line of code to fetch the params from navigation.
const otpKey = navigation.getParam('otpKey', '');

I think, we can't use "parmas" any more.


how to Remove "Add new Content" from the Main page

Question: I have a front page in which blocks and some contents (ie story) were displayed.
These stories were marked as "Promoted to front page"; later, I unchecked them.
These stories are now gone, yet the blocks were present.
Now I have the following content on my front page:
"No front page content has been created yet.
Add new content"
How do I remove this content or text?
Comment: This might help you out ::
http://drupal.stackexchange.com/questions/57258/removing-the-no-front-page-content-has-been-created-yet-message-from-the-fron/96171#96171
Answer: Just add this code to the page.tpl.php or page--front.tpl.php on Drupal 7.
find
<?php print render($page['content']); ?>

and replace with below code.
<?php  if(drupal_is_front_page())
                {
                    unset($page['content']['system_main']['default_message']);
            }
        print render($page['content']);
    ?>

And i believe you surely get all blocks or contents you posted on page.
and to remove page title on page like
Welcome to "website name"
find this code on page.tpl.php or page--front.tpl.php
<?php if ($title): ?>
<?php  print $title; ?>

<?php endif; ?>

and you can remove this code or else just make a comment over.
Comment: Depending on other parts of your site, it is possible that $page['content']['system_main']['default_message'] is not set, in which case the unset() call in your code example will throw an error.

This is also not the best solution. Seeing as the person has said they are not using the default home page functionality it makes more sense to use a different page as the home page.
Answer: There are a couple of ways in which you can accomplish this:

Front Page
Views

If you go the views route, enable the frontpage view, then go to admin/config/system/site-information and change the "Default front page" path to 'frontpage.'
Answer: First create one sample page using node/add/page in admin side of your website.
After creating the page, you can set the homepage of your website using
admin/config/system/site-information of your website. there you need to paste the url of your previously created page path in "Default front page" textbox.
After saving the configuration, the home page content will be replaced with your new page content.
Hope this can work for you!
Comment: If the main home page content is not actually going to be the body of this node it is not the best idea to do it this way, because resources are used loading the node for no reason, plus in this case the home page is not actually intended to be a node, but just a collection of blocks.
Answer: Out of the three ways above, which is the best way and guaranteed to work for drupal 7 bartik and zen themes?
Comment: The empty_page module solution will work with any theme.
Answer: If you just want a bunch of blocks on the home page (a very common requirement), the best easy way to do this is to use the empty_page module.
To use it you can:

Create an empty page (via the settings page of the module) with the
path "home" (or similar) and the title being the name of your site
(unless you want some other title for the home page).
On the site information settings page
(admin/config/system/site-information), set the home page path to
"home" (or whatever you made the path in the previous step).

This approach is good because you are not loading a node unnecessarily (in the case you use a blank node page as your home page) or processing the default drupal home page code, which is good for performance, and the module is simpler than the front page module.
Answer: The D7 main content is now a block, so just set the Main page content under blocks settings. Go to Structure > Blocks > Click configure on Main page content. On "Show block on specific pages" choose "All pages except those listed" and fill with <front>.
Source.
Answer: Just edit to /modules/node/node.module, look for $default_message line (around line 2621) and change 'No front page content has been created yet' to simply ''.
Comment: I don't think it is a good idea to hack the core.. http://drupal.stackexchange.com/questions/59054/why-dont-we-hack-core
Comment: Agreed, there are a lot of solutions to this problem that don't require hacking core.
Comment: No no no no no ... there are many other ways to do this without even thinking of touching core.


Exercise 2.5.5 david marker's

Question: please help me to solve it,
Let $L = \{E\}$ where $E$ is a binary relation symbol. Let
$T$ be the $L$-theory of an equivalence relation with infinitely many infinite
classes.
a) Write axioms for $T$.
b) How many models of $T$ are there of cardinality $\aleph_{0}$? $\aleph_{1}$? $\aleph_{2}$? $\aleph_{\omega_{1}}$?
c) Is $T$ complete?
I am eager to learn logic and this exercise!
Comment: What have you tried so far?
Answer: The axioms are easy,
for each $n$, the axioms
$$\exists x_1, \ldots , x_n(\wedge_{l\neq j} \neg x_i Ex_j)$$
$$\forall y\exists x_1, \ldots , x_n(\wedge x_i\neq x_j\wedge \wedge x_i Ey)$$
and of course the axioms saying $E$ is an equivalence relation.
In $\aleph_0$ there is only one model, with a countable number of classes, each one being countable. As a consequence the theory is complete.
For $\aleph_{\alpha}$, $0<\alpha$, let $\kappa_i$ be the number of classes with $\aleph_i$ many elements where $i\leq \alpha$. Then each $\kappa_1\leq |\alpha|+\aleph_0$ because there may be only a finite number of classes with a given cardinality. These numbers characterize the model. This if we look at models of size $\leq \aleph_{\alpha}$ there are $|\omega+\alpha|^{|1+\alpha|}$ many models. In particular for models of size $\aleph_0$ or $\aleph_1$ there are $\aleph_0^2=\aleph_0$ many models. For example a model could have $5$ countable classes and $\aleph_0$ many classes of size $\aleph_1$. Lastly remark that in this counting there are some that do not satisfy the axioms, eg a finite number of classes, but these will not affect the final result, as the true number of models will always be infinite.
Answer: a) You need to write down a sentence which states that "$E$ is an equivalence relation". Furthemore, for each $n\in \mathbb{Z}_+$ you need sentences which express that "for each element $x$ there exists at least $n$ distinct elements not related to $x$ via $E$" and "for each element $x$ there exists at least $n$ distinct elements which are related to $x$ via $E$".
b) Here we are only counting models up to isomorphism. For $\aleph_0$ there is only one model up to isomorphism (use for instance a back-and-forth argument). I am not sure about rest of the cardinals, since my set theory is bit rusty, but I suspect that there are many models.
c) The theory is complete, and one can prove this by applying Los-Vaught test: $T$ clearly does not have finite models and in part b) you have shown that every two countable models of $T$ are isomorphic.
Comment: It looks like you're assuming all the equivalence classes are infinite, which isn't how I interpreted the question.
Comment: Good point, the original question should be clarified.
Comment: The question as quoted states that $T$ is the theory of "an equivalence relation with infinitely many **infinite** classes", which seems unambiguous enough.
Comment: @BrianO What if it has infinitely many infinite classes + one finite class? :)
Comment: @ReijoJaakkola Read what it says again, again. "Infinitely many infinite classes" precludes that. This is the condition defining the theory you have to exhibit and work with.
Comment: Read what is says again, again, again. In no way does the description of $T$ that OP gave say that models of $T$ can't contain finite equivalence classes. The description only requires that there should be infinitely many equivalence classes which have an infinite number of members.

Exercise 2.5.5 david marker's


Automatically re-sorting tree

Question: Is there a way to have a tree which automatically re-sorts its elements, or when calling some method (not when inserting new element)?
I would like to have a tree, i.e. a set, of small structures like this:
struct item
{
    int value;
};

The set:
set<item> items;
auto p = items.insert(...);

And I would like to have a map holding iterators to the items held in set:
map<name, items::iterator> items_map;
items_map["abc"] = p.first;

After some time I would like to do lookup on the map and get the pointer to the item held in set to increase its value.
auto iter = items_map["abc"];
iter->value++;

Now I would like the set to automatically rearrange so that it reflects the updated value, I mean I would like the set to automatically sort itself (or after calling some method).
Is there a way to do so with current containers in STL?
Comment: you cant change items in a set anyway. storing iterators in a map feels like a bad idea too. just put the items in the map
Comment: because iterators get invalidated all the time
Comment: @Charles - thats we you cant even do it, they are const
Comment: So like `change_priority()` in a priority_queue?
Comment: Since [`std::set`](http://en.cppreference.com/w/cpp/container/set) holds unique elements, you should think about what incrementing an `item`'s `value` would do...
Comment: Also, maybe a `std::set>` might help? or a `std::set` where `struct item { std::string name, int value};` with some comparator? OR, `std::map` where the `int` is analogous to `value`?
Comment: Why storing iterators to a set is a bad idea?
Comment: The documentation says that when inserting new elements to a set the iterators are not invalidated.
Comment: @YotKay but can you ensure that the iterators are _always_ valid?
Comment: Std set and map are implemented as a binary search tree, probably red black tree. They are always sorted after using insert.
Comment: @pm100: storing iterators is bad if they are containers where their invalidation is frequent, such as `vector`... storing iterators to elements into `map`, `set` or `list` is perfectly fine, as they are invalidated only when the element itself is erased.
Comment: If the elements of the set are const then I could store pointers to items instead. It would work to update the value of item. But not to re-sort the items.
Answer:
I would like to do lookup on the map and get the pointer to the item held in set to increase its value.
Is there a way to do so with current containers in STL?

No. Elements of a std::set may not be modified. As such, the iterators are constant, and you couldn't use them to modify the elements.
The simple way to achieve similar effect would be to remove the old element, and insert a modified copy.  However, any iterator that used to point to the old element will of course be invalidated by the removal of the element and will not point to the modified one.

Is there a way to have a tree which automatically re-sorts its elements, or when calling some method (not when inserting new element)?

Sure, but there is no such structure in the standard library.
Comment: What kind of structure would you suggest to build such thing on my own?
Comment: You haven't explained much what you are using the structure for, but since you apparently need to look up by word, and also need sorted traversal by some other predicate, it seems that you need a multi-index container.
Comment: Like Boost MultiIndex?
Comment: According to this page (https://theboostcpplibraries.com/boost.multiindex), the Boost MultiIndex provides a method "modify" which does exactly what I wanted! That is great. "All interfaces will be notified and can calculate new hash values."

Automatically re-sorting tree


Ambiguous overload for 'operator>>'

Question: This is the error I'm getting:
ambiguous overload for 'operator>>' in 'contestantsInputFile >> contestantName'|
I am trying to pass a file to a function by reference in order to read a name into a variable called contestantName.
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string contestantName = "";
string contestantName(ifstream &);

int main()
{
    ifstream contestantsInputFile;
    contestantsInputFile.open("contestants_file.txt");
    contestantName(contestantsInputFile);
}

string contestantName(ifstream &contestantsInputFile)
{
    contestantsInputFile >> contestantName; //this is the line with the error
    return contestantName;
}

Comment: Where are you declaring the variable `contestantName`?
Comment: You have no variable called `contestantName`.
Comment: oops. actually I did have a variable called contestantName but I accidentally didn't include it in this question because I was trying to cut down the number of lines of code people would have to read. I added the variable in now.
Comment: true... ok I fixed it now to be contestantName
Comment: Now you have two things both named `contestantName` -- one is a `string` and one is a function.  Don't do that.
Answer: Your trying to read a function from a std::istream:
contestantsInputFile >> contestantName; //this is the line with the error

Maybe this is more what you were intending (untested):
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string readContestantName(ifstream &); // renamed to be a descriptive verb

int main()
{
    ifstream contestantsInputFile;
    contestantsInputFile.open("contestants_file.txt");
    std::string contestantName = readContestantName(contestantsInputFile);

    std::cout << "contestant: " << contestantName << "\n";
}

string readContestantName(ifstream &contestantsInputFile)
{
    std::string contestantName; // new variable
    contestantsInputFile >> contestantName; //this is the line with the error
    return contestantName;
}

Ambiguous overload for 'operator>>'


How to insert value to user entity custom field while creating new account?

Question: I am trying to insert a value into a custom field(field_custom_referral) which is created in the backend.When a user creating a account in our application, this particular custom field should be updated with custom value. Can anyone help me out here.
I tried below code in .module file but not working out:
function module_user_insert(Drupal\Core\Entity\EntityTypeInterface $entity) {
  $entity->set('field_custom_referral', '3');
  $entity->save();
}

Any suggestion will be appreciated.
Comment: What is the type of your field `field_custom_referral` ?
Answer: The hook_ENTITY_TYPE_insert in case of entity user expecting Drupal\user\UserInterface instance not Drupal\Core\Entity\EntityTypeInterface
change your hook to:
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function MYMODULE_user_insert(Drupal\user\UserInterface $user) {
  $user->set('field_custom_referral', '3');
  $user->save();
}


How to bind events on dynamic generated buttons in backbone?

Question: How do I bind click event on dynamic generated buttons in backbone.js?
 window.PackageView = Backbone.View.extend({

    tagName: "div",

    className: "package-template",

    events:{
      'click #display-nodes'  :  'main', // This button is declared in my HTML code and calls main method successfully.
      'click .display'        :  'disp', // This is dynamic button generated with class as display
    },

    getAction: function(nodeId){ // Get Actions from NodeId and generate buttons
      $('.nodes').append("<button>" + action.Name + "</button>"); //Generate Buttons
      $(".nodes button").addClass("display");
    },

    disp: function(){
        alert("Inside Disp Function");
    },

On clicking #display-nodes the nodes are displayed as required but .display is not working. How do I make this button call the function?
Comment: Can you post relevant markup as well?
Comment: Is `.nodes` nested beneath the `package-template` div? Example: `actionName`
Comment: If it is in fact nested, the button should still be added if you use `this.$('.nodes').append(...` instead of `$('.nodes').append(...`. In a Backbone view, `this.$` is a scoped jQuery object.
Answer: A Backbone view can receive events from dynamically generated DOM elements, through the events property, as long as the dynamically generated DOM elements are descendants of the view's el. The relevant code is in delegateEvents(). It uses jQuery's delegate() selector method.
The most likely reason it's not working for you is that the newly created <button> is not a descendant of the view's el. Am I right?
If this is the case and you want to keep the element outside of the view's el, you can remove it from your view's events property and delegate on another element in your view's init method.
Comment: @Eric - if it solved your problem and you're not waiting for further answers, you should mark as accepted answer.


Debugging a Laravel application using Zend Studio breakpoints

Question: I want to use server breakpoints in Zend Studio to debug a Laravel application. However I am unable to find any documentation involving how to set up Zend Studio breakpoints to work with a Laravel application.
The documentation for Zend Studio has information on utilizing breakpoints in the debug process, however this is only to debug individual PHP classes and not applications that utilize a PHP framework.
How can I integrate Zend Studio server breakpoints into my debugging workflow for a Laravel application?
Answer: For laravel theres couple tools that can help you debug your code, such as :
Dump and Die
you can use dd() to debug your code, its a feature that comes with laravel
DebugBar
https://github.com/barryvdh/laravel-debugbar
With this package, you can easily track your application. You can inspect queries, messages, requests, routes, views and so on.
Comment: This was not the answer I was asking for, however it does present good information for debugging Laravel apps, and you were the only one that attempted the answer so I am awarding you the bounty so it isn't wasted.
Comment: Thanks for the advice, however I was not looking for additional ways to debug laravel apps. I was looking for how to specifically use Zend Studio breakpoints to analyze/debug Laravel requests.


Error at loading Slider Revolution 5.0 Extrensions

Question: I downloaded a template and open it directly, it gives me an error for the slider.
!! Error at loading Slider Revolution 5.0 Extrensions.
Local Filesystem Detected !
Put this to your header:

Again I uploaded to local server, there is no error but an empty slider.
I checked the inspect element, it shows the errors in the below image:
Comment: That's a `404` error, the files doesn't exist on the path you've specified.
Answer: Looks like you're trying to get those files from a folder, js, in your source folder; that's not where they are located. With a quick Google search I found that those were located on another website, http://iccila.com.br.
The fixed

Answer: It is a cause of jQuery conflict. First I recommended upgrading your revolution slider.
Step to fix:

Go to bakend and click Slider Revolution
Click Global Setting.
Click on buttons

Insert JavaScript Into Footer:
  Defer JavaScript Loading:
Comment: This helped me so well. Thank you
Answer: Make sure revolution.extension.slideanims.min.js and other js files you are adding are in the folder js/vendor/revslider/public/assets/js/extensions/ and also that the js folder is in the same folder as this page that you are trying to open.
=======
If it isn't then specify the exact location in place of js/vendor/revslider/public/assets/js/extensions/
Answer: I had similar issues with Magento Rev Slider.
The problem was the caching extension that I have used. Amasty Full Page Cache.
I disabled and tried and everything worked fine.

So, I recommend you to check if all files exist with proper permission.
Then check and see if the page is cached.
Try and fully disable cache.
Also disable Chrome or browser Cache

It worked for me.
Answer: You also need to add this to your page revolution.extension.slideanims.min.js to your files.
I had the same exact problem I solved it by downloading this revolution.extension.slideanims.min.js file and then adding it to the folder
Then the mentioned code should be added at the bottom of the page.
Basically just look at your folder and see if all the mentioned js files exist. If they don't download them and add it manually.
Answer: You need server Environment to run Rev slider in local pc.
Like put all files in local host or upload in web server.
It will work.
Thanks


How to align the HelperText in center?

Question: TextFormField has a hintText and a HelperText , but i can seem to find a way to align the helperText in center , this is my code :
child: Container(

                  child: TextFormField(
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 21),
                    decoration: InputDecoration(

                      hintText: "hint text",
                      focusedBorder: UnderlineInputBorder(

                          borderSide: BorderSide(color: primaryColor)),
                      helperText: "THIS IS THE HELPER TEXT TO BE ALIGNED ",

                      helperStyle:
                          TextStyle(color: oASDC, fontSize: 15),

                    ),
                    onChanged: (value) {
                      setState(() {.......});
                    },
                  ),
                ),

is there a way to align the helper text in center?
Answer: You try this way:

https://i.stack.imgur.com/7LFJc.png

return TextFormField(
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 21),
      decoration: InputDecoration(
        contentPadding: EdgeInsets.only(left: 50, right: 50),
        hintText: "hint text",
        focusedBorder:
            UnderlineInputBorder(borderSide: BorderSide(color: Colors.green)),
        helperText: "THIS IS THE HELPER TEXT TO BE ALIGNED ",
        helperStyle: TextStyle(
          color: Colors.blue,
          fontSize: 15,
        ),
      ),
    );

Answer: From what I understand the position of the helperText is like the position of the errorText,
issue 1
issue 2
according to these issues, there seems to be no solution to this.
However, if you only need text , you can easily add Text widget below the TextFormField
like so:
Container(
                child: Column(
                  children: [
                    TextFormField(
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 21),
                      decoration: InputDecoration(
                        hintText: "hint text",
                        focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: primaryColor),),
                        // helperText: "THIS IS THE HELPER TEXT TO BE ALIGNED ",

                        helperStyle: TextStyle(color: oASDC, fontSize: 15),
                      ),
                      onChanged: (value) {
                        // setState(() {.......});
                      },
                    ),
                    Text(
                      'THIS IS THE HELPER TEXT TO BE ALIGNED',
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),

Answer: As far as I know, there is nothing conventional to align the helpertext.
Use contentPadding instead, not a proper way, but it's a day saver!
  Container(
    child: TextFormField(
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 21),
      decoration: InputDecoration(
          hintText: "hint text",
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.yellow)),
          helperText: "THIS IS THE HELPER TEXT TO BE ALIGNED ",
          helperStyle: TextStyle(
            color: Colors.red,
            fontSize: 15,
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 25)),
      onChanged: (value) {
        print(value);
      },
    ),
  ),

How to align the HelperText in center?


Prove $\{x \mid x^2 \equiv 1 \pmod p\}=\{1, -1\}$ for all primes $p$

Question: One way to prove that $\{x \mid x^2 \equiv 1 \pmod p\}=\{1, -1\}$ is to use the fact that $\{1, -1\}$ is the only subgroup of the cyclic group of primitive residue classes modulo $p$ that has the order 2. Is there a more basic way to prove this?
Comment: @AndréNicolas, I think I was writing this as an answer in parallel with your posting it as a comment.
Comment: It is now superfluous as a comment.
Answer: $$x^2\equiv1\mod p\iff p\text{ divides }(x-1)(x+1)$$
But a prime divides a product if and only if it divides one of the two factors.
Answer: The integers modulo $p$ form a field. A polynomial of degree $n$ over a field has at most $n$ roots in the field.
Comment: Note that there is no reason to exclude $p=2$ in your statement, the result remains valid in that case.
Answer: You can use group theory method.
$(\Bbb Z_{p}^{*}, \otimes_{p})$ is a cyclic group of an even number, so just $\varphi(2)=1$ element has order $2$, so the equation $x^2=1$ has only two solutions identity and that unique element of order $2$.

You can use number theory method.
$x$ satisfies the given equation if and only if $p|x^2-1=(x-1)(x+1)$ so if we assume $$x\in\{0,1,2,\dots,p-1\}$$
then the only possible answers are $1$ and $p-1$.


HTML/CSS Elemento fora do lugar

Question: Não sei onde estou errando, mas meu footer fica no meio da página.
É meu futuro portefólio, então nem tudo vai ser definitivo.
Outras sugestões são bem-vindas.

*{
 margin: 0;
 padding: 0;
 box-sizing: border-box;
 font-family:'Open Sans';
}

header{
 width: 100%;
 height: 65px;
 background-color: rgba(0, 0, 0, 0.5);
 position: absolute;
 z-index: 1;
}

h1{
 padding: 20px;
}

#menu ul{
 margin-right: 5%;
}

#menu li{
 margin-right: 0.5%;
 display: inline;
 padding: 20px;
 float: right;
}

#menu li a{
 color: #ffffff;
 font-family: 'Open Sans';
 text-decoration: none;
 padding: 10px;
}
#menu a:hover{
 text-decoration: underline;
}

h1{
 margin-left: 5%;
 color:#fff;
 text-decoration: none;
 float: left;
 font-size: 20px;
}

#banner{
 position: relative;
 background:url(img/code-3.jpeg) no-repeat;
 background-size: cover;
 width: 100%;
 height: 100vh;
 background-position:0px 0px ;
 /*margin-bottom: 30px;*/
}

#banner p{
 position: relative;
 text-align: center;
 color: #fff;
 font-family: 'Open Sans';
 font-size: 3.5em;
 top:48%;
 /*left: 400px;*/
}

.secao{
 position: absolute;
 width: 100%;
 /*height: 100vh;*/
 background-color: #eee;
}

.servicos{
 padding: 1.5%;
 margin-top: 60px;
 margin-left: 10%;
 width: 35%;
 float: left;
 border-radius:7px;
 /*height: 300px;*/
 color:#2d2d2d;
 /*background-color: #eee;*/
 text-align: center;
}

.servicos h2{
 font-family: 'Roboto';
 font-size: 2.4em;
 margin-bottom: 2%;
}

.servicos p{
 font-family: 'Open Sans';
 font-size: 120%;
 line-height: 30px;

}

.tecnologias{
 margin:10% 0;
 width: 100%;
}

.tecnologias h2{
 margin-bottom: 4%;
}

.tecno{
 display: inline-block;
 margin-left: 2%;
}

footer{
 position: relative;
 background-color: red;
 font-size: 40px;
}
<!DOCTYPE html>

 <title>Alexandre | Desenvolvedor Web</title>
 <meta charset="utf-8">
 <link rel="stylesheet" href="estilo.css">
 <link href="https://fonts.googleapis.com/css?family=Lato|Open+Sans:300|Roboto" rel="stylesheet">
 <link href="https://fonts.googleapis.com/css?family=Baloo+Bhaijaan|Montserrat|Slabo+27px" rel="stylesheet">
 <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">

Alexandre | Front End Developer

 Home

Sobre

 Contato

 Serviços

Posso Te Ajudar A Ter Um Site Só Seu

Quem Sou Eu

Oi! Me chamo Alexandre e sou Desenvolvedor Front End.

Isso quer dizer que se você tem uma empresa, um hobbie, ou um projeto e precisa de um site para exibir na web eu posso te ajudar.

Serviços

Trabalho com desenvolvimento de sites usando as mais atuais tecnologias buscando os melhores resultados possíveis.

Tecnologias Que Uso

HTML5

CSS3

JAVASCRIPT

WORDPRESS

teste

Comment: E como você quer que o footer fique?
Comment: Para o seu footer ficar sempre no final do ecrã vc tem que usar javascript, porque o tamanho do ecrã depende de cada utilizador. Vc está a dizer que o footer fica no meio do ecrã, no meu tenho que fazer scroll para o ver. Vc tem que pegar o tamanho do ecrã do cliente e depois ajustar seu footer de acordo com isso.
Comment: Eu quero que fique no fim da página. Achei que eu poderia estar errando em algum position no código.
Answer: Percebi 3 problemas problemas no seu código:
1) Ausência da tag .
2) position: absolute; na classe .secao: está fazendo com que o elemento com esta classe fique "solto" na página, ocasionando o footer no meio da página. Retire esse position.
3) Precisa dar forma, tamanho e posição para o footer (display, width, float):
   footer{
        position: relative;
        background-color: red;
        font-size: 40px;
        display: block;
        float: left;
        width: 100%;
    }

*{
 margin: 0;
 padding: 0;
 box-sizing: border-box;
 font-family:'Open Sans';
}

header{
 width: 100%;
 height: 65px;
 background-color: rgba(0, 0, 0, 0.5);
 position: absolute;
 z-index: 1;
}

h1{
 padding: 20px;
}

#menu ul{
 margin-right: 5%;
}

#menu li{
 margin-right: 0.5%;
 display: inline;
 padding: 20px;
 float: right;
}

#menu li a{
 color: #ffffff;
 font-family: 'Open Sans';
 text-decoration: none;
 padding: 10px;
}
#menu a:hover{
 text-decoration: underline;
}

h1{
 margin-left: 5%;
 color:#fff;
 text-decoration: none;
 float: left;
 font-size: 20px;
}

#banner{
 position: relative;
 background:url(img/code-3.jpeg) no-repeat;
 background-size: cover;
 width: 100%;
 height: 100vh;
 background-position:0px 0px ;
 /*margin-bottom: 30px;*/
}

#banner p{
 position: relative;
 text-align: center;
 color: #fff;
 font-family: 'Open Sans';
 font-size: 3.5em;
 top:48%;
 /*left: 400px;*/
}

.secao{
 width: 100%;
 /*height: 100vh;*/
 background-color: #eee;
}

.servicos{
 padding: 1.5%;
 margin-top: 60px;
 margin-left: 10%;
 width: 35%;
 float: left;
 border-radius:7px;
 /*height: 300px;*/
 color:#2d2d2d;
 /*background-color: #eee;*/
 text-align: center;
}

.servicos h2{
 font-family: 'Roboto';
 font-size: 2.4em;
 margin-bottom: 2%;
}

.servicos p{
 font-family: 'Open Sans';
 font-size: 120%;
 line-height: 30px;

}

.tecnologias{
 margin:10% 0;
 width: 100%;
}

.tecnologias h2{
 margin-bottom: 4%;
}

.tecno{
 display: inline-block;
 margin-left: 2%;
}

footer{
 position: relative;
 background-color: red;
 font-size: 40px;
 display: block;
 float: left;
 width: 100%;
}

Alexandre | Front End Developer

 Home

Sobre

 Contato

 Serviços

Posso Te Ajudar A Ter Um Site Só Seu

Quem Sou Eu

Oi! Me chamo Alexandre e sou Desenvolvedor Front End.

Isso quer dizer que se você tem uma empresa, um hobbie, ou um projeto e precisa de um site para exibir na web eu posso te ajudar.

Serviços

Trabalho com desenvolvimento de sites usando as mais atuais tecnologias buscando os melhores resultados possíveis.

Tecnologias Que Uso

HTML5

CSS3

JAVASCRIPT

WORDPRESS

teste

Comment: Era exatamente isso, valeu mesmo,
Answer:
"Acho que me expressei mal. Quero o footer no fim da página seguindo o
  fluxo, como na maioria das páginas. Com o position fixed ele fica na
  frente de outros elementos na página."

Você esta colocando em .secao como position: absolute; então o footer fica por atrás do .secao, por isso o footer desaparece e não segue o fluxo normal do site.

HTML/CSS Elemento fora do lugar


StructureMap and chaining arguments to classes?

Question: Here is the sequence in which objects need to be created. I'd like to initialize the whole thing in SM and only use the last one as target:
var firstObject = new FirstClass("First", "Last");
var servers = new List<FirstClass> { firstObject };
var secondObject = new SecondClass();
secondObject.Servers = servers;
var thirdObject = new ThirdClass(secondObject);
var fourthObject = thirdObject.SomeGetFunction(thirdObject);

After all this is configured in SM, I'd like to basically only use
var objectToUse = ObjectFactory.GetInstance<fourthObject>();

So far I'm only able to get half way there, but can not figure out how complete this whole configuration. First three objects are singletons, they are only needed to properly instantiate and configure the fourth one.
Answer: Here is how this can be accomplished. I'm not sure if this follows the best practices but gets the job done.
The first object to be created needs some settings from the config file; this was easy.
For<FirstClass>()
     .Singleton()
     .Use<FirstClass>()
     .Ctor<string>("First").EqualToAppSetting("FirstKey")
     .Ctor<string>("Last").EqualToAppSetting("LastKey");

The second one was more problematic because after creation two properties needed to be set and one of them was of type IEnumerable<FirstClass>, which I couldn't figure out how set up. As it turns out SM's 'context' object and interception was the answer.
For<SecondClass>()
     .Singleton()
     .Use<SecondClass>()
     .OnCreationForAll((context,x) =>
                           {
                               var server = new FirstClass[1];
                               server[0] = context.GetInstance<FirstClass>();
                               x.Servers = server;
                               x.Connections = 1;
                           });

Third one was again easy, we can let SM figure out dependencies.
For<ThirdClass>().Singleton().Use<ThirdClass>();

And the fourth and final one was tricky again since the object I was after was supposed to be created by a call to the ThirdClass. Again, build in 'context' proved to be useful here.
For<FourthClass>()
      .Singleton()
      .Use(context => context.GetInstance<ThirdClass>().SomeGetFunction("stringParam"));

Now all I have to do is to call ObjectFactory.GetInstance<FourthClass> and do operations from there.


What is the concept of Test cricket? How and when is it decided that a team has won or there is a draw?

Question: Test cricket is the often called the purest form of the game.
Conventionally it spans for 5 days with each day having 90 overs each except for the fifth day were 15 overs is mandatory to be bowled in the last hour of play. Note that this scheduled overs may be reduced/increased in case the match is affected by rain/any other disturbances.
But How and when is it decided that a team has won or there is a draw?
Answer: This is covered by Law 16 "The result" and in particular Law 16.1:

The side which has scored a total of runs in excess of that scored in the two completed innings of the opposing side shall win the match.

This means a win can be achieved in one of three ways:

The team batting in the fourth innings reaches a point at which they have scored more runs across their two innings than the opposing side scored in their two completed innnings. The team batting wins.
The team batting in the fourth innings loses all their wickets before they have scored as many runs as the opposing side scored in their two completed innnings. The team batting loses.
One team scores more runs in its one completed innings than the opposing side scores in both its completed innings. That side wins "by an innings".

A tie occurs if both sides have an exactly equal number of runs at the conclusion of the fourth innings (16.5.1):

The result of a match shall be a Tie when all innings have been completed and the scores are equal.

and anything else is a draw:

The result of a match shall be a Draw when it is not determined in any of the ways stated in 16.1, 16.2, 16.3, 16.4 or 16.5.1.

(16.2 refers to one-innings matches so is not applicable to test matches, 16.3 refers to umpires awarding a match and 16.4 refers to agreements to alter the result conditions; no such agreement exists in the standard ICC Test Match playing conditions).


What happens when fouled behind the goal line near the penalty area?

Question: Everyone remembers Benzema's "La croqueta" against Atlético Madrid in the 2nd leg of 2016/2017 Champions League's semi-final, right?

    (Source)
Now that you've remembered, my question is what if Benzema would have been fouled behind the goal line (outside the pitch) near the penalty area when the ball is still clearly in the field? How the game would have been then restarted, namely, if Benzema was fouled at this very moment:

The possible outcomes that I think of are:

Penalty (benefits non-offending team)
Indirect free kick from the nearest spot to the foul (benefits offending team)
Dropped ball from the nearest spot to the foul (benefits offending team)
Comment: @JonMarkPerry Who told you that? Fouls outside the field are judged just like any other, and deliberate fouls aren't even necessarily a caution, let along a sending-off.
Comment: a foul outside the playing field is seen as deliberate, and is an automatic red.
Comment: @Jon, thanks for your comment, but even if what you're saying was true (which may be true in this case, but not always), that's not exactly my question. I'm more interested in how the game should be restarted. Please see edit.
Comment: @JMP sorry, that is just incorrect.
Answer: Law 12.4 Fouls and misconduct / Restart of play after fouls and misconduct covers this explicitly:

If, when the ball is in play [...] a player commits an offence against a match official or an opposing player [...] outside the field of play, play is restarted with a free kick on the boundary line nearest to where the offence/interference occurred; a penalty kick is awarded if this is a direct free kick offence within the offender's penalty area.

Therefore it would be a penalty in the specific case you highlighted.
Comment: This answer is correct. Play is stopped for the free kick offence. Naturally, if it was an indirect free kick offence (as some fouls are), it would be taken from the boundary line, but since the answer has inferred a direct free kick offence, the correct restart is a penalty kick.
Comment: Unfortunately, @JonMarkPerry deleted his answer too early but he also had good official references, namely his reference to [this rule](https://www.fifa.com/mm/Document/FootballDevelopment/Refereeing/02/36/01/11/LawsofthegamewebEN_Neutral.pdf#page=25): *If play is stopped by the referee to administer a caution, then the match is restarted by an indirect free kick taken by a player of the opposing team from the place where the ball was located when the referee stopped the match*.
Comment: Yes, he made a wrong conclusion about awarding a penalty when the rule he was citing was talking about an indirect free kick. But now I think that the above rule adds some ambiguity to the problem, as an indirect free kick could also have been awarded. Yet, your reference is much stronger, but there's an ambiguity.
Comment: I can't find the quoted text in the new IFAB Laws (the quote was from the old FIFA Laws), so the problem may be moot. In any case, I'd interpret it as "If play is stopped by the referee *solely* to adminster a caution [...]", but I agree it's not entirely clear.
Comment: Either way the free kick would be on the line nearest the offence (or on the edge of the six-yard box as applicable). For a DFK inside the penalty area, it becomes a penalty as usual, which is the likely result here.
Comment: My point of contention was rather that the answer assumed that the foul was a direct free kick offence, which isn't always the case.
Answer: As the last sentence in his reference to the Laws of the Game by @Philip in his answer still wasn't crystal clear:

a penalty kick is awarded if this is a direct free kick offence within
  the offender's penalty area.

I have emailed IFAB to ask for their interpretation and I got an answer from Dr. David Roland Elleray MBE himself, Technical Director of The IFAB. With his kind permission I am now publishing it here:

Dear Gudrat
As contained in the revision of the Laws for 2016/17 (and extended in
  scope for 2017/18) it states in Law 12 that if a player commits an
  offence against an opponent off the field of play (with the ball in
  play) the referee awards a free kick on the boundary line closest to
  where the offence occurred. The free kick is direct or indirect
  depending on the offence.
If the offence is one punishable by a direct free kick and the point
  on the boundary line is within the offender's penalty area then a
  penalty kick is awarded. [emphasized by me]
I hope this clarifies matters for you.
Best wishes
  David Elleray
  Technical Director of The IFAB


Boolean value is not recognized when using CASE WHEN

Question: I am using SQL in snowflake. I am trying to use CASE WHEN to develop indicators for smoking status. When I run the code, I get an error:

Boolean value '428061000124105' is not recognized.

The code I am using is:
SELECT
  history.PATIENT_ID as pat,
  history.SMOKING_STATUS AS smoke,
 CASE
  WHEN smoke = '428061000124105' OR '428071000124103' THEN 'smoker'
  WHEN smoke = '8517006' THEN 'ex_smoker'
ELSE 'NA'
END AS smoking_status
FROM 'db'.'schema'.'table';

Is this a data issue? What is the best way to solve this?
Comment: `WHEN smoke IN ('428061000124105', '428071000124103') THEN 'smoker'`
Comment: Or `WHEN smoke = '428061000124105' OR smoke = '428071000124103' THEN 'smoker'`
Comment: `FROM 'db'.'schema'.'table';` isn't going to work, single quotes (`'`) are for literal strings, not delimit identifying objects.
Comment: What kind of values are in **history.SMOKING_STATUS** ?
Answer: Since you are providing column name only in when condition, SQL server is interpreting it as a boolean value.
Please try changing it to WHEN smoke = '428061000124105' OR smoke = '428071000124103' THEN 'smoker'
Answer: This might show why the error is happening:
SELECT column1 as smoke
    ,CASE
        WHEN smoke = '1234' THEN 'booleans are equal to text represntations of numbers'
        ELSE 'NA'
    END as smoke_test
FROM VALUES (true), (false);

gives:

Boolean value '1234' is not recognized

This is say, "you have a boolean value" (aka only true or false) and you are comparing it to a string. Don't do that.
If you insist of comparing 'true' or 'false' to text numbers. You can cast the boolean to a TEXT
SELECT column1 as smoke
    ,CASE
        WHEN smoke::text = '1234' THEN 'booleans are equal to text represntations of numbers'
        WHEN smoke::text = '1' THEN 'one'
        WHEN smoke::text = '0' THEN 'zero'
        ELSE 'NA'
    END as smoke_test
FROM VALUES (true), (false);

SMOKE
SMOKE_TEST

TRUE
NA

FALSE
NA

which is the same as
SELECT column1 as smoke
    ,'NA'as smoke_test
FROM VALUES (true), (false);

or you can cast bool to INT at which point the TEXT and NUMBER compare will do an auto cast to TEXT after turning BOOL so a null,0,1
SELECT column1 as smoke
    ,CASE
        WHEN smoke::int = '1234' THEN 'booleans are equal to text represntations of numbers'
        WHEN smoke::int = '1' THEN 'one'
        WHEN smoke::int = '0' THEN 'zero'
        ELSE 'NA'
    END as smoke_test
FROM VALUES (true), (false), (null);

Answer: It is considering the Boolean OR statement where it is not expecting it. Kindly try   as below using 'IN'.
SELECT
  history.PATIENT_ID as pat,
  history.SMOKING_STATUS AS smoke,
 CASE
  **WHEN smoke in ('428061000124105','428071000124103')** THEN 'smoker'
  WHEN smoke = '8517006' THEN 'ex_smoker'
ELSE 'NA'
END AS smoking_status
FROM 'db'.'schema'.'table';


When did voice parts start using treble clef?

Question: Parts for soprano, alto and tenor voices used to be written with the corresponding variant of movable C clef.  When did the transition to treble (G) clef happen, and what drove the change -- composers, publishers or performers?
To clarify what I'm looking for -- an answer to this question When did keyboard partitions start to use the G-clef for the upper staff ?  states that "many of the other C-clef placements were phased out over time" and I'm looking for more detail on when/why that transition took place for voice parts.
Answer: C and F clefs were used for plainsong pretty much from the start of staff notation. On the 4-line staff, the C clef could be on either of the top two lines, and the F clef was equivalent to the C clef one line above the staff.
The earliest known printed music dates from about 1465. G clefs for the top part were certainly in use by 1508 when Petrucci printed this (see page 14 of the PDF):
https://imslp.org/wiki/Special:ImagefromIndex/307180/torat - the Superius part from http://imslp.org/wiki/Motetti_a_cinque_(Petrucci,_Ottaviano).
The basic motivation for selecting clefs was to avoid leger lines. The modern F and G clefs are equivalent to a C clef on the leger line above or below the staff, so they are perhaps not such a big innovation as they might at first appear. In early music notation, the G clef was sometimes used on the bottom line for violin parts, and the F clef on the top line for low bass voice parts - those are equivalent to extending the range of C clef positions to two leger lines either side of the stave.
The F clef was sometimes used on the middle line as an alternative to the C clef on the top line.
A final random thought - I wonder why all known clefs indicate the pitch on a line, and never a space. That fact is enough to "explain" the existence of both F an G clefs - but why?
Comment: Make that thought into a question!
Comment: interesting stuff, but doesn't actually answer the question
Comment: Clef on a Space: the Final [notational] Frontier :-)
Comment: Observation: modern tenor voice parts use G clef down an octave, which is equivalent to C clef on the 3rd space.  Compare with old tenor clef on 4th line.


Prove that every non-zero ideal of ID is maximal.

Question:
$Q$ is an integral domain. $K$ is a principal ideal domain. $K \subset Q$ and $Q$ is integral over $K$. Prove that every non-zero prime ideal of $Q$ is maximal.

So we have $P \triangleleft Q$, which is prime, that is if $ab \in P$, than $a \in P$ or $b \in P$ . And Q is integral over K, i.e. for every $q \in Q$ there exist a polynomial over $K$, so that $q$ is root of the polynomial. Plus we have that every prime ideal of K is maximal.
Let $p \in P$. Then there exist such $k_i \in K$: $p^{n} + k_{n-1}p^{n-1}+ ... + k_1p + k_0 = 0$ than $p^{n} + k_{n-1}p^{n-1}+ ... + k_1p = -k_0$. So in the left side we got element of $P$, and in the right part is the element of K. What do i get from it?
Comment: It's enough to show that $K$ field implies $Q$ field.
Comment: Of course not. It just shows that particular element of $P$ is in $K$.
Comment: @user26857 but $K$ isn't a field.
Comment: See the answer below to understand what I've meant.
Answer: Note that if $K \subset Q$ is integral and $I \subset Q$ is an ideal, then $K /(K\cap I) \subset Q/I$ is integral. (Just reduce the equation of integral dependence)
Following the hint given in the comments by user26857 we need to show two things:
1) If $I \subset Q$ is a non-zero ideal, then $K \cap I$ is non-zero.
2) If $K$ is a field, then $Q$ is a field.
To show 1) we may use the calculation that you did. If $I \subset Q$ is a non-zero ideal, we have an element $p \in I \setminus \{0\}$, then we have $p \cdot (p^{n-1} + k_{n-1}p^{n-2}+ ... + k_1) = -k_0$. Now the LHS is in $K$, the RHS is in $I$, so the element is in $K \cap I$, also as $p$ is not a zero-divisor, the element is non-zero, showing that $K \cap I$ is not the zero ideal.
To show 2), suppose that $K$ is a field and let $p \in Q\setminus \{0\}$, then we have $p^{n} + k_{n-1}p^{n-1}+ ... + k_1p = -k_0$ Now $k_0$ is non-zero by the same argument as above, so as $K$ is a field we may divide by $k_0$ and obtain $\frac{p^{n-1} + k_{n-1}p^{n-2}+ ... + k_1}{-k_0} \cdot p = 1$, as $\frac{p^{n-1} + k_{n-1}p^{n-2}+ ... + k_1}{-k_0}$ is in $Q$, we have that $p$ is invertible, hence $Q$ is a field.
Finally, to show that 1) and 2) imply the statement, note that if $I \subset Q$ is a non-zero ideal, by 1), we have that $K \cap I$ is non-zero, also it is prime, thus as $K$ is a PID $I \cap K$ is maximal, so $K / (K \cap I)$ is a field. Now as $Q/I$ is integral over $K / (K \cap I)$ and $K / (K \cap I)$ is a field, we apply 2) showing that $Q/I$ is a field which implies that $I$ is maximal.
Comment: Actually this question is solved on M.SE but in two different threads: one shows that $K\cap I\ne0$ for $I\ne 0$, and the other one proves the result I've mention in my comment under the question, this is why I didn't close it.


$f:\mathbb R \to \mathbb R$ be a continuous such that $f(f(f(x)))=x,\forall x \in \mathbb R$ , is $f(x)=x , \forall x \in \mathbb R$?

Question: Let $f:\mathbb R \to \mathbb R$ be a continuous function such that $f(f(f(x)))=x,\forall x \in \mathbb R$ , then is it true that $f(x)=x , \forall x \in \mathbb R$ ? I can see that $f$ is bijective , hence strictly monotone . But I cannot progress further . Please help. Thanks in advance
Comment: If $f$ were monotone decreasing, then so would $f\circ f\circ f$ be, so it has to be increasing. Also, monotone functions are differentiable almost everywhere, which might be helpful.
Answer: First of all notice that $f : \mathbb{R} \rightarrow \mathbb{R}$. For all $x \in  \mathbb{R}$ the image by $f$ of $f(f(x))$ is $x$ so $f$ is surjective. Moreover $f$ is injective because: if $f(x)=f(y)$, then $x=f(f(f(x)))=f(f(f(y)))=y$. So $f$ is a bijection. Observe that that $f$ is strictly increasing, suppose $f$ is decreasing $f\circ f$ is increasing and $f\circ f\circ f=\text{id}$ is decreasing, which is impossible.
We can suppose $f(x)>x$,  we have that $f(f(x))>f(x)>x$, so $x=f(f(f(x))>f(f(x))>f(x)>x$ because $f$ is strictly increasing, but this is clearly impossible. On the other way $f(x)<x$ is also impossible, so the unique possibility is that $f(x)=x$ for all $x$. So $f=id$.
Answer: As Arthur notes, $f$ cannot be decreasing because then $f\circ f\circ f$ would also be. Therefore $f$ must be increasing.
Now fix an $x\in \mathbb R$ and consider what $f(x)$ can be.
If $f(x)>x$, then since $f$ is increasing we have $f(f(x))\ge f(x)$ and $f(f(f(x)))\ge f(f(x))$, which gives us
$$ f(f(f(x)) \ge f(f(x)) \ge f(x) > x $$
contradicting the assumption that $f(f(f(x)))=x$.
Similarly $f(x)<x$ leads to $f(f(f(x)))<x$, so the only possibility is that $f(x)=x$.


R examples for Durbin & Koopman "Time Series Analysis by State Space Methods"

Question: I was wondering if anyone has ported the examples from Durbin & Koopman "Time Series Analysis by State Space Methods" to R?
You can find RATS code for the examples online and obviosly SsfPack/Ox but no signs of an R companion for this book...
Answer: There is a package in CRAN (KFAS) which implements a good portion of the algorithms described in Durbin & Koopman, including "exact" non-informative distributions for the state vector, or parts of it.
Although it is not paticularly tied to Durbin & Koopman's book, you might also be interested in package dlm and the companion book Dynamic Linear Models with R.
Comment: I would also add that I bought "An Introduction to State Space Time Series Analysis (Practical Econometrics)", which was a very gentle introduction to the topic, and it too, used SsfPack/Ox. Makes it much less useful, in one sense, though it does have the benefit of once you implement it in dlm (in R) yourself, you can check your answer against an independent implementation.
Comment: I've run into the same problem as the OP, and also found that dlm and the Dynamic Linear Models with R book are very useful.
Comment: dlm package and DLMs with R book were very useful for me, too.
Answer: A walk through the Commandeur and Koopman's book with R examples is available here. Also check the official book's page where links to new software and tutorials are posted.
An entire JSS volume was dedicated to state space modelling in different software. See particularly the introductory paper and the R paper. Kalman Filtering in R has a good overview of available R packages for state space modeling.
Sections "Dynamic Regression Models" and "Multivariate Time Series Models" in TimeSeries CRAN View contain a few more references.


Circumflex in classical guitar notation

Question: Playing a piece called "Romanze" by Johann Kaspar Mertz (from one of the Bardenklänge books), I noticed there is a circumflex written next to some chords:
The excerpt is taken from page 6 (IMSLP publication). Does anyone have a clue what purpose those circumflexes have?
Answer: It meant "pluck this note with the thumb" - but I don't think this notation is still in common use.
Mertz published a Guitar tutor (here, in German: https://imslp.org/wiki/Special:ImagefromIndex/442101/torat)
The scan of page 10 is pretty low quality, but from the text of the "1ste Regel" (Rule No. 1) and the exercises that follow, even though the "^" symbol seems to be missing from the text of the "rule" itself, it seems clear enough that ".", "..", and "..." denote the first three fingers of the right hand, and "Daumen" is German for "thumb".
Comment: @Tim Herr Mertz is dead so it's hard to ask him why he mentioned what seems obvious, but the tutor seems to be aimed at absolute beginners. Most of the first 10 pages are explaining music notation, not about playing the instrument. His "Rule 2" in the image is quite explicit: "When three notes are played together, one should play the lowest note with the thumb, and the two higher notes with the first and second fingers." He goes on use the same circumflex-and-dots notation on individual notes, for "finger-picking" examples as well as chords.
Comment: Not knocking, but aren't the chances that the lowest note of a chord, particularly a note played on E A or D strings, with its tail hanging down, being played using thumb, pretty good anyway? Why would the player need to be told?  And - does the sign mean that particular note, or subsequent ones also?   Just asking!

Circumflex in classical guitar notation


Filtrar string REGEX C#

Question: Tenho uma string que retorna todo o conteudo de uma página html.
Nesta pagina, tem a seguinte linha:
<input style="width: 2.3em;" id="nacional" value="3,48" type="text">

Preciso somente do valor que está em value, ou seja, 3,48, lembrando que este valor muda automaticamente todos os dias.
Como posso filtrar esta linha e pegar o valor?
Answer: Fiz um Regexr com seu padrão. A expressão regular é:
value=\"([\d,]+)\"

No C# ela fica um pouco diferente.
var regex = new Regex(@"value=""([\d,]+)""");

Feito isso, basta selecionar o grupo 1 (grupo 0 é a correspondência inteira encontrada). Ou seja:
var match = regex.Match("<input style=\"width: 2.3em;\" id=\"nacional\" value=\"3,48\" type=\"text\">");
Console.WriteLine(match.Groups[1].Value);

Fiz um Fiddle.
Answer: Segue um exemplo que retorna qualquer caractere entre aspas duplas ou apóstrofo, dentro do atributo value.
value=['"](.*?)['"]

Comment: e como eu poderia implementar nesta linha?                                MatchCollection m1 = Regex.Matches()
Comment: Este é apenas o pattern, qualquer dúvida vale a pena dar uma olhada sobre [Regex C#](https://msdn.microsoft.com/pt-br/library/system.text.regularexpressions.regex%28v=vs.110%29.aspx)

Filtrar string REGEX C#


How do I minify inline CSS using Twig?

Question: Inside my html.html.twig template I've added a stylesheet inside the style elements using this.
<code>{% include directory ~ '/css/base/style.css' %}
</code>
Is there a way that I can strip it for all whitespaces? Can I apply the CssOptimizer class to it in any way? Can I also strip the stylesheet for comments?
Answer: This is not the right way to integrate a .css file inside a twig file in drupal8. You should use the standard procedure as I mentioned below.
 {{ attach_library('bartik/messages') }}
SO now for minifying the .css  you can use the 3rd party site- https://cssminifier.com/
So the after minifying the .css file, crate the library

messages:
  css:
    theme:
      css/components/my-minify.css: {}

Then attach the library in the twig by using the below sysntax

{{ attach_library('your-theme-name/messages') }}

Hope this will help you. If any doubt please don't hesitate to mention.
Answer: Take a look at the Advanced CSS/JS Aggregation module.
Comment: Thanks for feedback, i know abour it. As far as i know doesnt output inline css? And i still wonder how to do this using twigs :)
Comment: If you are not going to modify the file then why are you directly include in twig while you can do the same thing as @sekharctc mentioned!
Comment: Been 4 years, hope my comment seems not relevant :D

How do I minify inline CSS using Twig?


Unsure of why approach to evaluation limit is incorrect

Question: I have the function
$$
f(x) =
\begin{cases}
x\sin\left(\frac1x\right) & x\text{ is rational}\\
x^2 & x\text{ is irrational}
\end{cases}
$$
I found the limit as x approaches 0 to be 0 by considering a sequence of rational and irrational numbers. This was a past exam question but the answer hasn't been published and the feedback states that:
"some students considered two different sequences
converging to 0 (one of rational numbers and another one of irrational numbers), they studied the
limit of the sequences given by the image through the function f of these two sequences, showed
that the limit of these sequences was zero, and deduced incorrectly that the limit of the function
at the point 0 was 0."
So I'm unsure of why this argument would be incorrect as questions regarding similar functions include the same sequence based method
Comment: It's better if you say why you think this argument is *correct* - are you applying some theorem? Which one?  That way you'll get a more helpful explanation.
Comment: Not "a sequence...", but "any sequence...".
Comment: What level of rigor are you working at? Is this a calculus class? Real analysis? Are you expected to construct a $\delta$-$\varepsilon$ proof?
Answer: I'm not entirely sure of the level of detail your instructor wants, but by definition, for some real number $L$,
$\lim_{x\to0}f(x) = L$ precisely when, for all sequences $(x_n)_{n=1}^\infty$ with $\lim_{n\to\infty}x_n=0$, we have that $\lim_{n\to\infty}f(x_n)=L$.
It seems like your instructor suggests that there were student solutions which looked at two sequences (one of rational numbers and one of irrational numbers) tending towards $0$, rather than all possible sequences. Notice the difference between the following statements:

For every sequence $x_n\to0$, we have that $\lim_{n\to\infty}f(x_n)=L$.
For every sequence of rational numbers $x_n\to0$, we have that $\lim_{n\to\infty}f(x_n)=L$, and for every sequence of irrational numbers $x_n\to0$, we have that $\lim_{n\to\infty}f(x_n)=L$.
For a particular sequence of rational numbers $x_n\to0$, say $\left(\frac1n\right)_n$, we have that $\lim_{n\to\infty}f(x_n)=L$, and a particular sequence of irrational numbers, say $\left(\frac{1}{\pi n}\right)_n$, we have $\lim_{n\to\infty}f(x_n)=L$.

Your professor is likely not satisfied by answers which do not exhibit a student's understanding of the distinction between these; only the first of these bullets is the definition of convergence to $L$, so if you want to check a different condition, you should probably apply a theorem, otherwise it will not be convincing.
Answer: Here's a counterexample, where your method does not work. Consider the function $f:\mathbb{R}\to\mathbb{R}$ given by:
\begin{align*}
f(x)=\begin{cases}
0& \text{if } x=\frac{a}{2^n}\text{ for some $a>0$ odd and }n\in\mathbb{Z^{+}}\\
1& \text{if } x=\frac{a}{2^n}\text{ for some $a<0$ odd and }n\in\mathbb{Z^{+}}\\
0& \text{otherwise}
\end{cases}
\end{align*}
Then considering some sequence of irrational numbers tending to 0, and the sequence of rational numbers $\frac{1}{2^n}$ tending to 0, we might incorrectly conclude that the limit of the function at 0 is 0. However, if we consider the sequence $\frac{-1}{2^n}$, the function tends to 1 as $n$ tends to $\infty$.
However, if you could show that for ALL sequences converging to 0 that are either entirely rational or entirely irrational, that $f$ converges to 0 on each sequence, then it would be true that the limit of $f$ at 0 is indeed 0. You can prove this by contradiction (assume not, then some sequence exists s.t. $|f|$ is always $>\epsilon$, then extract a subsequence that is entirely rational or irrational).


What is the X matrix supposed to look like for a regression model that uses cell means coding?

Question: A study wants to test the effectiveness of three types of drug on a person's weight. The regression model uses cell means coding with no intercept, and one categorical independent variable with 0-1 indicator dummy variable for each category. What should the X matrix look like? I'm guessing its dimension is n x 3, where n is the number of participants for the study.
Answer: Yes, the dimension of the X matrix will be $ n \times 3$. It will look like:
<code>| 1 0 0 |
| 1 0 0 |
...
| 1 0 0 |
| 0 1 0 |
| 0 1 0 |
...
| 0 1 0 |
| 0 0 1 |
| 0 0 1 |
...
| 0 0 1 |
</code>


Meteor: calling function from Meteor.methods

Question: At first I would like to notice that I'm beginner in Meteor. I don't know why this code:
Meteor.methods =
  fun: ->
    "This is message."

if Meteor.isClient
  Template.hello.greeting = ->
    "Welcome to FirstApp."

  Template.hello.events =
    "click input": ->
       console.log "You pressed the button."

when this line typed in browser console:
Meteor.call("fun", function(err, res) { if(err) alert(err); else alert(res); });

allerts: Error: Method not found [404] instead of "This is message.".
Why fun is undefined?
Answer: Did you put this file in the client directory? Meteor.methods has to define fun on the server in order for the callback to be triggered properly.
The client version of Meteor.methods only defines a local stub.
Answer: because Meteor.methods should not be assigned to a function. if you do it like that, you will ever have only one function.
Try this instead:
if Meteor.isServer
   Meteor.methods({
      fun: ->
         "This is message."
   })

I am not aware that coffeescript can be used on the client. But your definition is wrong as the events is an object with multiple functions
this is correct (provided coffeescript works on the client):
Template.hello.events({
   "click input": ->
      console.log "You pressed the button."
})

have fun with Meteor and read the documentation


Connecting to a remote mysql database using its private IP Address

Question: My database server has only a private IP address. I am able to ssh into the database server from my application server. I have created an user with the app server's IP address.
Can anyone tell me how to access mysql databases from the app server using the db server's private IP address on ubuntu 16.04?
Answer: It's likely that the mysql server is bound to the loopback address, either 127.0.0.1 or the ipv6 equivalent, and so you would have to open that up to the LAN network. You can check that with the following command on the mysql server;
# netstat -lntp | grep 3306
tcp        0      0 127.0.0.1:3306     0.0.0.0:*    LISTEN   20080/mysqld

That option for binding to an ip is configured in my.cnf, or where ever the mysql config file is on your system, and can be changed to bind to all ips;
[mysqld]
bind-address                   = 127.0.0.1

change to
[mysqld]
bind-address                   = 0.0.0.0

and restart the mysql server. Obviously it's important to ensure permissions have been set correctly on the mysql server.
Where the config file lives depends on which version of mysql you are using, I see it at;
/etc/mysql/mysql.conf.d/mysqld.cnf on Ubuntu 16.04.3 running mysql-server-core-5.7  but it's at /etc/my.cnf on another CentOS box... so you might have to be more specific about that environment you are in...
You can test whether it's working by connecting to the private ip of the db server from the app server with the mysql-client
# echo "show databases;"  | mysql -uroot -psomepass -h localhost

Database
information_schema
wp_is_annoying_db
mysql
performance_schema
sys

if that's not working you should start with the basics
ping the db server private ip address;
$ ping 192.168.x.x
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.051 ms

use telnet or netcat to test the port
$ telnet localhost 3306
Trying 127.0.0.1...
Connected to localhost.

or use netcat, if telnet is not installed;
nc -v localhost 3306
Connection to localhost 3306 port [tcp/mysql] succeeded!

Comment: Thank you for your prompt reply! But, I have set my bind address to the private IP of my database server so that it listens to all connections within the network. It is not only that I want to access the instance from the app server but also that my php application should access the database as well. So SSH wouldn't be the right option. Any other solution to this issue?
Comment: The port forwarding is an alternative. If you have set the bind address, and checked `netstat -lntp | grep 3306` you should be able to connect with php
Comment: are you getting an error?
Comment: Can port forwarding be used from the application? netstat on the server give's the IP of the server. I get this error ERROR 2003 (HY000): Can't connect to MySQL server on '10.0.3.41' (110)
Comment: 100% packet loss while pinging, telnet and nc does keeps trying but does not connect(done from app server with db server's IP)!
Comment: so you can ssh to the server, i.e. `ssh firstname.lastname@example.com`, but pinging it, and trying to telnet fails? (from the same console?)
Comment: If so, that suggests a firewall problem. try `iptables --list -v` on the dbserver and paste that out
Comment: I am able to ssh to the server! I am not able to paste my iptables here. So, these are my ufw rules To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
443 ALLOW Anywhere
3306 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
443 (v6) ALLOW Anywhere (v6)
3306 (v6) ALLOW Anywhere (v6)
Answer: Try to ping/telnet/nc to the db server from the app server.
If this does not connect you to the db server. Disable the firewall(should be a firewall block and it was for me!)


How to loop over all folders in a given directory and create shortcuts for them in vbs?

Question: I have a batch file that creates a temporary vbs script to create a shortcut but I am getting stuck when trying to insert it in to a for loop that will create a shortcut in a given directory for all folders in that directory.
Here is the vbs script that I am using to make a shortcut:
@echo off
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%HOMEDRIVE%%HOMEPATH%\Desktop\Hello.lnk" >>
CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "C:\Windows\notepad.exe" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs

And here is my attempt to insert it into a for loop:
FOR /D %r in (dir) do(
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%cd%\%%r.ink" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "%cd%\%%r" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs)

Comment: Do you have any errors? Have you checked that the created vbs is correct?
Comment: Why would you place a shortcut to every directory within the same container as those directories themselves? It would greatly improve your chances of receiving help if you were to tell us what your real task is, the genuine shortcut you're wanting to create, with the proper file path and name, _(not made up to protect NOTHING AT ALL)_. That's not `For /D` syntax either.
Answer: With regards to Loop
FOR /D %%r (dir) do (
...
)

Comment: Incorrect, `%%r` would always hold the value `dir`, perhaps the OP was looking for `For /D %%r In ("dir\*") Do (`


How to migrate content using a web service with multiple calls?

Question: I need to migrate content from a web service to which I have to call several URLs. A call to receive a list of nodes and then a call for each node to receive information from the fields.
Something like this:
Calling domain.test/webservice/
<results>
  <count>10</count>
  <list>
    <id>100</id>
    <id>101</id>
    <id>102</id>
    ...
  </list>
</results>

Calling domain.test/webservice/101
<results>
  <id>101</id>
  <name>Name</name>
  <field1>Field example</field1>
    ...
</results>

So, in my migration yml file I have something like:
source:
  plugin: url
  data_fetcher_plugin: http
  headers:
    Accept: application/xml
  data_parser_plugin: simple_xml
  urls: https://domain.test/webservice/

How can I specified the migrate process to retrieve each content info from a URL like https://domain.test/webservice/[ID]?
Answer: There is an issue with the UrlPerRow plugin above.
The source data isn't populated until after the check for whether the source data has changed. Because of that fact, it's always looking at previous data, which means the hash will never change, so "rowChanged()" never returns true. It will import new data but not update if the data changes.
A fixed version is below:
<?php

namespace Drupal\fad_migration\Plugin\migrate\source;

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate_plus\Plugin\migrate\source\Url;
use Drupal\migrate\Row;

/**
 *
 * @MigrateSource(
 *   id = "url_per_row"
 * )
 */
class UrlPerRow extends Url {

  protected $dataNewParserPlugin;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $prepare_row = parent::prepareRow($row);

    $item_info_settings = $row->getSourceProperty('item_info');
    if (!empty($item_info_settings)) {
      $this->getItemData($row, $item_info_settings);
    }

    if (!$row->getIdMap() || $row->needsUpdate() || $this->aboveHighwater($row) || $this->rowChanged($row)) {
      return $prepare_row;
    }
    else {
      return false;
    }

  }

  protected function getItemData(Row &$row, $settings) {

    $new_url = str_replace($settings['token'], $row->getSourceProperty($settings['token_replace']), $settings['url']);
    $this->getNewDataParserPlugin($new_url, $settings['item_selector'], $row->getSource());
    $this->dataNewParserPlugin->rewind();
    $xml_data = $this->dataNewParserPlugin->current();
    if (!empty($xml_data)) {
      $fields = $row->getSourceProperty('fields');
      foreach ($fields as $field) {
        if (!empty($field['item_info']) && !empty($xml_data[$field['name']])) {
          $row->setSourceProperty($field['name'], $xml_data[$field['name']]);
        }
      }
    }
  }

  protected function getNewDataParserPlugin($url, $item_selector, $settings) {
    $settings['urls']          = [$url];
    $settings['item_selector'] = $item_selector;

    $this->dataNewParserPlugin = \Drupal::service('plugin.manager.migrate_plus.data_parser')
                                        ->createInstance($settings['data_parser_plugin'], $settings);

    return $this->dataNewParserPlugin;
  }

}

Answer: To solve this I had to create a source plugin that for each row calls a new data parse plugin with the URL for this row.
Here is the plugin:
/**
*
* @MigrateSource(
*   id = "url_per_row"
* )
*/
class UrlPerRow extends Url {

protected $dataNewParserPlugin;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $prepare_row = parent::prepareRow($row);

    if (!$row->getIdMap() || $row->needsUpdate() || $this->aboveHighwater($row) || $this->rowChanged($row)) {
      $item_info_settings = $row->getSourceProperty('item_info');
      if (!empty($item_info_settings)) {
        $this->getItemData($row, $item_info_settings);
      }
    }

    return $prepare_row;
  }

  protected function getItemData(Row &$row, $settings) {
    $new_url = str_replace($settings['token'], $row->getSourceProperty($settings['token_replace']), $settings['url']);

    $this->getNewDataParserPlugin($new_url, $settings['item_selector'],     $row->getSource());
    $this->dataNewParserPlugin->rewind();
    $xml_data = $this->dataNewParserPlugin->current();
    if (!empty($xml_data)) {
      $fields = $row->getSourceProperty('fields');
      foreach ($fields as $field) {
        if (!empty($field['item_info']) && !empty($xml_data[$field['name']])) {
          $row->setSourceProperty($field['name'], $xml_data[$field['name']]);
        }
      }
    }
  }

  protected function getNewDataParserPlugin($url, $item_selector, $settings) {
    $settings['urls'] = [$url];
    $settings['item_selector'] = $item_selector;

    $this->dataNewParserPlugin = \Drupal::service('plugin.manager.migrate_plus.data_parser')
      ->createInstance($settings['data_parser_plugin'], $settings);

    return $this->dataNewParserPlugin;
  }

}

Then I put some info in the migration .yml definition:
source:
  plugin: url_per_row
  data_fetcher_plugin: http
  headers:
    Accept: application/xml
  data_parser_plugin: simple_xml
  urls: https://myws.com
  item_selector: /ResultWeb/data
  item_info:
    url: https://myws.com/[id]
    token: '[id]'
    token_replace: id
    item_selector: /ResultWeb/data

Notice that the id from token_replace is a field with name id. You can use other field.
Also, for every field where is needt to rereive information from the specified URL I put a item_info: true element.
-
  name: myfield
  label: 'My Field'
  selector: fields/field/my
  item_info: true


Some examples of sequence with cluster points

Question: Provide the following examples, assuming that $(X, d)$ is infinite.

A sequence without cluster points.
A sequence that has exactly 5 cluster points.
A sequence $(x_n)_n$ such that every $x \in X$ is a cluster point of $(x_n)_n$.

I have to do these exercises for my math class.
I thought that in step 1: $x_n = n$ has no cluster point.
For the remaining two points I'm stuck. Can you help me by providing some examples with an explanation?
Answer: A cluster point can be thought of as the limit of a subsequence. Here is a trick to make sequence with exactly two cluster points (in the space $X = \mathbb{R}$). It will help you with question 2. Question 3 is trickier.
We start with a sequence with a limit. For instance: $1, 1/2, 1/3, 1/4, \ldots $ which has limit 0.
Then we take a second series that also has a limit, but a different limit. For instance the sequence $1, 3/2, 7/4, 15/8, \ldots$ which has limit 2.
Now to make your sequence $x_n$ we just 'interweave' them:
$$1, 1, 1/2, 3/2, 1/3, 7/4, 1/4, 15/8, 1/5, 31/16, \ldots$$
This has two cluster points: 0 and 2 because for each clusterpoints there is an infinite subsequence that has it as its limit.
What the example also illustrates is that sequences need not be monotonic: they can jump up and down according to a pattern that need not be clear at first glance.
For question 3 you want to get arbitrarily close to every number. My tip is to first think of a set of numbers that achieves that and then about if it is possible to put them in some order, hence making them into a sequence.
Answer: A cluster point of a sequence $(x_n)_n$ is the limit of some subsequence $(x_{n_k})_{n_k}$. Hence the simplest example I can think for 2. are 5 different constant sequences $(x^i)_n$ in $(X, d)$ put together like this: $x^1,\ldots,x^5, x^1,\ldots,x^5,\ldots$. Of course, the sequences don't need to be constant, you can use, for example, $x^1_n := a^1 + 1/n,\ldots, x^5_n:= a^5 +1/n$ for fixed $a^i$'s. The key idea is to intercalate different convergent sequences.
For 3., think of the metric space $\mathbb{R}$ with the euclidean distance. Since $\mathbb{Q}$ is dense in $\mathbb{R}$, if you could find a way to enumerate all the rationals you will have a properly defined sequence where any $x\in\mathbb{R}$ is the limit of some subsequence. The problem now reduces to finding an explicit bijection from $\mathbb{N}$ to $\mathbb{Q}$.


How to avoid redrawing evey objects at each frame in paper.js

Question: How to avoid redrawing eveything at each frame in paper.js?
I suppose I have to detach the frame event from the view view.detach('frame');, and then call draw manually every time I want to update something ?
This is very usefull to make drawing applications.

EDIT
Here is an example of what I want to avoid (click to toggle copies visibility):
the framerate decreases drastically when I show many other shapes (since everything is redrawn at each frame) but the copies could be drawn only on click and then let untouched (the framerate would be always high).
Just in case:
Symbols are not a solutions here, this is maybe a better example of what I want to achieve. The trails are fading away since the canvas is not cleared at each frame, just darkened.
I found some infos about here, it seems redraw optimizations are not implemented yet.
Answer: Ok, I implemented the persistence request here, but I didn't pull it yet.
You can check two examples: the tail effect and the performance benchmark (click to toggle visibility of modified clones, press 'space' to toggle persistence).
You can find the example code here, under drawings.
Comment: Well, it's available here: https://github.com/arthursw/paper.js and you can have more details about the implementation on this thread: https://groups.google.com/forum/#!msg/paperjs/oTg73NhNUcM/EkY57pE2ZRAJ
Comment: So if I just copy your paper.js file into my app it just works with persistence out of the box?
Comment: Not a good fit for the type of app I am working with, although it sounded extremely promising..sigh..
Comment: What is your problem?


Piano or violin for a guitarist?

Question: I have been playing guitar for several years now and I feel that I'm ready to start another instrument a bit more classic, but I'm not able to decide between piano and violin. I know that I will learn both but I can't decide which one I should begin with. I've been trying to hear melodies with violin alone and piano too but sometimes I prefer one, sometimes the other. I'm torn between them.
Is one a better choice then the other to start with? What should I be thinking about to choose?
Comment: Learning piano will help you understand music better and in that sense can help with learning violin (and anything else). Learning violin will not help you learn piano.
Comment: @JacobSwanson: it's not a duplicate, because that question says _"I have no musical background or whatsoever"_. That's quite a crucial difference here.
Comment: @JacobSwanson it was actually that question that made me want to ask mine, but i didn't find there the answer i was looking for .
Comment: Do you have access to a teacher? Will you be able to get one for which ever instrument you pick?
Comment: @people voting to reopen, mind explaining what's different between the two questions?  The answers seem to be VERY similar.
Comment: @JacobSwanson: well, it's not necessarily the question's fault if the answers are similar. But are they, even? Most answers to the linked question (including yours) are mainly general advice on how to start doing music without a teacher without getting discouraged, and so on. That's not relevant to somebody who's already learned an instrument. Neither is it relevant that piano is a more useful tool for understanding music theory, because guitar already does that job too.
Comment: I'm 15 and I've been playing the piano for 10 years now, and I highly recommend playing the piano, especially after the guitar. The thing about the violin is you can only play one or two notes at a time, never a full chord. As a guitarist, you are used to playing full chords, and I feel like you'd want to play a chord so badly, but you can't because you're on a violin.
Answer: The answer is to learn both.  They are not exclusive of each other, and as you say, you're going to learn both eventually anyway.  Both require development of your music reading skills.  Spending time on the one will not detract from the study of the other.  Virtually all advanced, university-level music programs require the student to have fundamental basic piano skills, regardless of principal instrument.  There's a reason for that!
The violin will require more time before you reach a state of basic proficiency, i.e. the point where you will be able to play with other players in an ensemble.
You'll find that one or the other instrument will begin to emerge as a preference, and that's a far better selection process than making an arbitrary flip of the coin today.
Comment: I agree that learning both is the right answer – however, I'd take a different conclusion: because piano is practically inevitable anyway for any western musician, but violin is not, one should make a deliberate commitment to learn violin ASAP. Otherwise, the "will learn both" is likely to not be fulfilled, because violin is so hard (and it doesn't get easier to start with it later).
Answer: You could think about how you use the guitar most, if you mostly play to accompany yourself singing, the piano may be a better choice. If you treat the guitar as a solo (melodic) instrument, or regularly have other musicians to play with, the violin may be a better choice.
For what it's worth, playing the piano develops and uses a lot more transferable skills. Ways of looking at music theory and chordal harmonies etc which you probably use while playing guitar are a lot more prominent in piano playing. If you learn to play piano you will get keyboard skills, which can then be used for organs, accordions and synthesisers.
You may find that having some form of keyboard synthesiser handy when you're playing guitar becomes a useful tool, if you know both it's fairly easy to switch instruments. The idea of having a violin as an instrument for part of a song and guitar for others would be a lot more difficult, practically.
If you really want to try something completely different, which doesn't combine with your guitar playing at all, the violin may be a better choice. It's got a lot more to think about in terms of expression, detailed technique, although it is likely to tie you down to a fairly limited number of musical contexts, classical or folk, mostly. (Obviously, it can be part of any music, but is less often).
Basically, think about why you want to learn another instrument, and what you hope to achieve with it.
Comment: this answer seems to utterly ignore a vast swath of musical cultures.  Violin figures prominently in every eastern/middle-eastern culture;  it figures prominently in western classical repertoire;  it figures prominently in all american and european folk/indigenous musics:  country&western irish;appalachian; klezmer; turkish/persian; indian; gypsy; on and on.

The piano does as well.
Comment: 'Keyboards utterly useless...' ? Several of mine have a little gismo on the left hand side, that changes all sorts of parameters, making them as expressive as - just about any instrument! And I've a swell pedal! Your bias is showing! However, it's a great answer!  +1.
Comment: Firstly, yes, it is an over-simplification, I stated that myself. Secondly: all of the styles you've listed could be described as folk, or classical styles. I'm very sorry if I've offended some sensibility here, I'm merely trying to suggest things to think about when choosing one of these two instruments.
Comment: when you say "...a fairly limited number of musical contexts..." in describing an instrument that is prominent in MOST musical contexts, it naturally gives pause...
Comment: Agree with @dwoz, violin fits easily in as many genres as piano. In fact, I couldn't name a style where you could not use violin, but there are many styles where piano quite fundamentally doesn't work (to name two: most indian music, due to microtonality, as well as most metal styles, due to lack of ability to "chunk" rythms). Piano is more common in past-1950 western popular music, but that's about it.
Answer: Well, don't fool yourself: violin is difficult. But...

Personal experience: I was (at the age of 15) in a similar situation as you are now. Knew guitar, wanted to learn something more classical. I tried violin. And tried. And failed.
Actually I didn't try that long, nor did I take professional lessons. But I really couldn't see it going anywhere. The thing with violin is, not only is is hard to play good, it's in fact hard to produce any sound that's not plain painful. And even worse, after an hour of practising, that horrible scratchy mess kept following me around in my head all day long...
I sometimes regret not having had the willpower to learn violin. But well... I ended up learning cello instead, which turned out to be rather closer to guitar in many a sense, yet still can do many of the things that are nice about violin. Something you should consider, too! I'm very happy being a string player:

Violin/cello are orchestral instruments. Don't know if you had that in mind, but playing in an orchestra can be an amazing experience. It's a way to be part of a truely, well – great sound, without necessarily having to be extremely skilled. (You may get a similar experience with electric guitar in a rock band, but that never has the kind of "part of something huge" feeling.)

Since an orchestra needs quite a large number of string instruments (unlike winds), it's relatively easy to get into one – provided of course that you can play decently, which as I said sure isn't easy. In that regard, the best choice would however be viola or double bass, which tend to be most sought for (because so rare).
Keyboards are of course also used in orchestral settings, but unless you're really good and can play piano concerts, you'll end up mostly with somewhat silly (but often crazy convoluted) celesta rings, or kitschy fairytale clichees.

String instruments can be used in a remarkably wide range of different ways. The typical silky orchestral violin section is only the tip of the iceberg; you can also do fiery dramatic soloes or rumbling rythms or spooky effects or breathtaking innocent folky tunes. Of course, piano is also versatile (at least keyboards in general), and guitar can achieve a lot through FX processing. But IMO there's no class of instrument which offers such a wide, immediate and emotional response as strings do.

And they manage to fit in pretty much any musical context, if played accordingly; you're not at all bound to orchestra playing.

Especially violin is nicely compact. You can take it everywhere, practise anywhere, and join any session. OTOH, piano... let's not start.
The bowed string instruments, together with guitar skills, readily open up many other instruments. Mandolin is really pretty much just strummed violin with frets, electric bass is exactly the same as cello, and the intonation wisdom can be translated to all kinds of instruments, as well as singing. With piano? Well, you get the other keyboards almost (but not quite) for free, but keyboards are utterly useless for many dimensions of musical expression.

So: definitely try a string instrument, if you're willing to go through some efford!
To disclaim: I'm frankly a bit of a piano hater. Of course piano has undeniable qualities, and sometimes nothing is as fitting as a piano accompaniment. But I find piano is way overused, in part surely because it's so much easier to become decent (which doesn't mean it's easy to become good!), and IMO it also doesn't have any benefits over guitar as a harmony / theory device, in fact I consider the 12-toneism that piano induces rather harmful to composition.
You can (and should) always also learn a bit of keyboard in addition to other instruments. But if you want to become a classical pianist, it requires no less efford as for violin, and honestly I'd consider this is wasted lifetime in your position.
Comment: +1 for orchestra!  Also, please don't forget about viola!  Several of the biggie composers were violists -- you'll understand harmonies from the inside.
Answer: As someone who first learned the piano and then learned guitar, I would say it would be best if you now learn piano. The reason for this is that once you understand the piano keyboard, music theory will become much more easy for you to understand because each note on the piano only has one place and the piano is designed to play all chord inversion easily. Knowing music theory that you can use in a performance setting really ups your game.

Piano or violin for a guitarist?


Prove proposition on real numbers and uniqueness.

Question: How would I go about proving the following proposition. Do I have to prove uniqueness, or that if $x^2 = r$, then $x = \sqrt r$?

Prove given any $r \in \mathbb R\gt 0$, the number $\sqrt r$ is unique in the sense that, if $x$ is a positive real number such that $x^2 = r$, then $ x = \sqrt r$.
Answer: If $0 < x < y$ then $x^2 < y^2$. Consequently, if $x^2 = y^2 = r$ and $x,y > 0$, then you must have $x=y$.
Answer: Suppose $x > 0, x^2 = r$ and we have $y > 0, y^2 = r$. Then $0 = r - r = x^2-y^2 = (x - y)(x+y)$. But since $x > 0$ and $y > 0$ then $x+y > 0$ so it implies that $x - y = 0$.


Using multiple TelephonyManagers with multi-sim device

Question: I am trying to establish whenever a multisim Android device (running Android 7.0+) has any working/enabled sim cards.
For this I am following Google's documentation regarding attaching multiple TelephonyManagers to the  default TelephonyManager instance, as per : https://developer.android.com/reference/android/telephony/TelephonyManager.html#SIM_STATE_READY

The returned TelephonyManager will use the default subscription for
  all calls. To call an API for a specific subscription, use
  createForSubscriptionId(int). e.g. telephonyManager =
  defaultSubTelephonyManager.createForSubscriptionId(subId);

In my specific case something like this :
<code> telephonyManager = (TelephonyManager) mContext
                   .getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_SERVICE_STATE);

List subList = mSubManager.getActiveSubscriptionInfoList();
        SubscriptionInfo firstSub = (SubscriptionInfo) subList.get(0);
    mSim0TelephonyManager = telephonyManager.createForSubscriptionId(firstSub.getSubscriptionId());
    mSim0TelephonyManager.listen(new Sim0PhoneStateListener(), PhoneStateListener.LISTEN_SERVICE_STATE);
    int test = mSim0TelephonyManager.getSimState();

SubscriptionInfo secondSub = (SubscriptionInfo) subList.get(1);
 mSim1TelephonyManager = telephonyManager.createForSubscriptionId(secondSub.getSubscriptionId());
mSim1TelephonyManager.listen(new Sim1PhoneStateListener(), PhoneStateListener.LISTEN_SERVICE_STATE);
 int testw = mSim1TelephonyManager.getSimState();
</code>
So first I get all active subscriptions ,which was already a pain because in reality those are not active subscriptions as in subscriptions who have state in service, those are simply the SIM cards inserted into the SIM slots.
Which means that even if you deactivate a SIM card using the Android Settings Menu you will still receive that SIM card as being an active subscription !!!!
The next problem is that even on deactivated (No service!!!) SIM cards I am getting a value 5 (https://developer.android.com/reference/android/telephony/TelephonyManager.html#SIM_STATE_READY). For me this is incomprehensible, the SIM state is ready whilst the whole SIM is deactivated. This means those API calls are not reliable at all...
Also after adding the PhoneStateListeners to the individual new TelephonyManagers I am not getting any calls to the implementations of those PhoneStateListeners when the SIM cards are activates/deactivated through the Android Settings Menu...
Now I am wondering if something is broke within Android, or maybe with the device manufacturers implementations (testing on a Samsung A5 2017 Duo and a Huawei P9 Lite). Unfortunately the emulator does not support multi-sim so I cannot test the plain vanilla Android Nougat version on that :(
UPDATE :
In the meantime I found this topic : How to get a PhoneStateListener when using Dual SIM functionality
It would seem there is actually a bug within Google's implementation within listen(PhoneStateListener listener, int events) which results in a PhoneStateListener being instantiated only for the default SubscriptionId independently from the parameter which is being passed in the constructor....
Comment: If you are getting the same results across multiple disparate manufacturers (Samsung and Huawei), then most likely the problem is with Android. It's possible the problem would be with the chipset manufacturer, if those devices happen to share a common chipset manufacturer. Unfortunately, there is no multi-SIM Google device (Nexus or Pixel) to use as a reference point.
Answer: I didn't try but it might work for you
<code>subids[] = SubscriptionManager.getSubscriptionId()
if (SubscriptionManager.isActiveSubscriptionId(subids[0])){
    mSim0TelephonyManager = telephonyManager.createForSubscriptionId(firstSub.getSubscriptionId());
}
</code>
this will work