How do I update a field in a room database using a repository & viewmodel

Question: I created a room database following this guide from code labs It makes use of a repository to:

A Repository manages query threads and allows you to use multiple backends. In the most common example, the Repository implements the logic for deciding whether to fetch data from a network or use results cached in a local database.

I followed the guide and i'm now able to create the entity's & retrieve the data. I even went further and created another whole entity outside the scope of the guide.
However I can't find many resources that use this MVVM(?) style so am struggling as to really under stand the repository.  For now I want to update a field. Just one, as if I am able to manage that the rest should be similar.
I want to update a field called dartshit and I have the dao method created for this:
@Query("UPDATE AtcUserStats SET dartsHit = :amount WHERE userName = :userName")
    void UpdateHitAmount(int amount, String userName);
I have one repository which I assumed I use for all entities:
public class UsersRepository {

private UsersDao mUsersDao;
private AtcDao mAtcDao;
private LiveData<List<Users>> mAllUsers;
private LiveData<List<AtcUserStats>> mAllAtc;
private AtcUserStats mAtcUser;

UsersRepository(Application application) {
    AppDatabase db = AppDatabase.getDatabase(application);
    mUsersDao = db.usersDao();
    mAtcDao = db.atcDao();
    mAllUsers = mUsersDao.fetchAllUsers();
    mAllAtc = mAtcDao.getAllAtcStats();
}

LiveData<List<Users>> getAllUsers() {
    return mAllUsers;
}

LiveData<List<AtcUserStats>> getAllAtcStats() {
    return mAllAtc;
}

LiveData<AtcUserStats> getAtcUser(String username) {

    return mAtcDao.findByName(username);
}

public void insert (Users user) {
    new insertAsyncTask(mUsersDao).execute(user);
}

public void insertAtc (AtcUserStats atc) {
    new insertAsyncAtcTask(mAtcDao).execute(atc);
}

private static class insertAsyncTask extends AsyncTask<Users, Void, Void> {

    private UsersDao mAsyncTaskDao;

    insertAsyncTask(UsersDao dao) {
        mAsyncTaskDao = dao;
    }

    @Override
    protected Void doInBackground(final Users... params) {
        mAsyncTaskDao.insertNewUser(params[0]);
        return null;
    }
}

private static class insertAsyncAtcTask extends AsyncTask<AtcUserStats, Void, Void> {

    private AtcDao mAsyncTaskDao;

    insertAsyncAtcTask(AtcDao dao) {
        mAsyncTaskDao = dao;
    }

    @Override
    protected Void doInBackground(final AtcUserStats... params) {
        mAsyncTaskDao.insertNewAtcUser(params[0]);
        return null;
    }
}
}

My question is how do I create a AsyncTask for the update query I am trying to run in this repository?
Here is what I have so far by broadly copying the insert repository methods:
private class updateHitAsyncTask {

    private AtcDao mAsyncTaskDao;

    public updateHitAsyncTask(AtcDao mAtcDao) {

        mAsyncTaskDao = mAtcDao;
    }

    protected Void doInBackground(int amount, String name) {
        mAsyncTaskDao.UpdateHitAmount(amount, name);
        return null;
    }
}

Which is incorrect is that I'm getting a llegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. error. But i thought this AsyncTask is suppose to take care of this?
Here is my update method in my view model, which is reporting 0 errors:
  void updateHitAmount (int amount, String name) {
    mRepository.updateAtcHits(amount, name);
}

and here is the UI code where im actually trying to tie all these together, I suspect there must be a better way that using onChanged for simply updating a field but again I am struggling to come across any advice on google with the repository approach:
   private void callOnChanged() {

    mAtcViewModel = ViewModelProviders.of(this).get(AtcViewModel.class);

    mAtcViewModel.getAllUsers().observe(this, new Observer<List<AtcUserStats>>() {
        @Override
        public void onChanged(@Nullable final List<AtcUserStats> atc) {
            // Update the cached copy of the users in the adapter.

            for (int i = 0; i < atc.size(); i++) {
                if (atc.get(i).getUserName().equals(mUser)) {
                    mAtcViewModel.updateHitAmount(55, mUser);
                    //atc.get(i).setDartsHit(55);
                    Log.d("id", String.valueOf(userSelected.getId()));
                }
            }
        }
    });

How can I update fields using this approach on the background thread?
Answer: Figured it out due to this answer here. It was mostly because of my lack of understanding of AsyncTask. Essentially I needed to create an object and pass the data that way and then execute in the background:
 private static class MyTaskParams {
    int amount;
    String name;

    MyTaskParams(int amount, String name) {
        this.amount = amount;
        this.name = name;
    }
}

public void updateAtcHits (int amount, String name) {

    MyTaskParams params = new MyTaskParams(amount,name);
    new updateHitAsyncTask(mAtcDao).execute(params);
}

private class updateHitAsyncTask extends AsyncTask<MyTaskParams,Void,Void>{

    private AtcDao mAsyncTaskDao;

    public updateHitAsyncTask(AtcDao mAtcDao) {

        mAsyncTaskDao = mAtcDao;
    }

    @Override
    protected Void doInBackground(MyTaskParams... myTaskParams) {
        int amount =myTaskParams[0].amount;
        String name = myTaskParams[0].name;
        mAsyncTaskDao.UpdateHitAmount(amount, name);
        return null;
    }
}


Firewall predefined rule property cannot be modified

Question: Using a stand alone Windows Server 2012 Standard edition (no Active Directory),
I Tried to establish a simple remote desktop with a custom port number, but could not modify the port number in the Firewall inbound rule,
when I open the inbound property I get the next message: "This is a predefined rule and some of its properties cannot be modified"
I have tried to set it up like this: New rule -> predifined drop down list -> Remote Desktop -> check mark rules -> Allow the connection.
but still get "This is a predefined rule and some of its properties cannot be modified"
Thank you in advance.
Answer: It looks like you're trying to "redefine" a rule for a predefined service when I think you need to make a custom rule for the port you want RDP to listen on. Then you'll need to change thr port that RDP is listening on. Here's an article that explains how to do it in Windows Server 2008 R2. I imagine it's going to be the same in Windows Server 2012.
http://www.techrepublic.com/blog/datacenter/changing-the-rdp-listening-port-on-windows-server/1939
Comment: thank you for the link, I'll check it soon and give my feed back.
Comment: I have previously changed the port number in the registry, but when I go to the firewall rules I found it unchanged, and no way to change it there.
Comment: Right, because you're trying to change a rule that uses predefined parameters. Try creating a new port based rule for the port you changed RDP to.
Comment: and disable the predefined rule ? there are many in Windows server 2012 that have relation with RDP and its services. I will check now...
Comment: I have created a new port based rule for the port I changed RDP to and it worked. Previously there was 4 rules using 3389 port RDP TCP, RDP UDP, RDP services TCP, and RDP services UDP, do I have to disable them all?
Comment: I don't think that's neccessary because RDP is now listening on a different port so those rules shouldn't have any bearing on anything.
Comment: Ok, thank you very much for your help, I'll post in a while a wew question on Windows Server RDP Licencing in case you're interested.
Comment: Glad to help...


LilyPond - how to write a basic makefile

Question: During the last years I tought myself to write scores using LilyPond and furthermore to make file handling easier by using Bash scripts.
Recently I started a project a little bigger than only one or two pages and once again I came across the article about Makefiles in the LilyPond Documentary.
Even though reading this article it was kinda hard for me to grasp the actual technique behind the template Makefile also because the article does not supply the file repository it is working with.
So I though to take the time to make up an example project to ask, how a Makefile in this scenario could look like. How I would build it step by step and how I actually run the Makefile. (Edit: referring to a make man page I got my understanding as far as being able to say that one uses make as interpreter like bash on a shell-script.sh. The command then simply looks like make -f Makefile run in the root directory of the project.)

The Project has a file-structure like this:
├── Book.ly
├── Book.pdf
├── global-files
│   ├── copyright.ily
│   ├── Frontpage.ily
│   ├── header.ily
│   └── paper.ily
├── input-files-voiceI
│   ├── Nr_01-voiceI.ily
│   ├── Nr_02-voiceI.ily
│   └── Nr_03-voiceI.ily
├── input-files-voiceII
│   ├── Nr_01-voiceII.ily
│   ├── Nr_02-voiceII.ily
│   └── Nr_03-voiceII.ily
├── README.md
├── single-pages-voiceI
│   ├── MIDI
│   │   ├── Score-Nr_01-voiceI.midi
│   │   ├── Score-Nr_02-voiceI.midi
│   │   └── Score-Nr_03-voiceI.midi
│   ├── PDF
│   │   ├── Score-Nr_01-voiceI.pdf
│   │   ├── Score-Nr_02-voiceI.pdf
│   │   └── Score-Nr_03-voiceI.pdf
│   ├── Score-Nr_01-voiceI.ly
│   ├── Score-Nr_02-voiceI.ly
│   └── Score-Nr_03-voiceI.ly
├── single-pages-voiceI_a_II
│   ├── MIDI
│   │   ├── Score-I_u_II_Nr_01.midi
│   │   ├── Score-I_u_II_Nr_02.midi
│   │   └── Score-I_u_II_Nr_03.midi
│   ├── PDF
│   │   ├── Score-I_u_II_Nr_01.pdf
│   │   ├── Score-I_u_II_Nr_02.pdf
│   │   └── Score-I_u_II_Nr_03.pdf
│   ├── Score-I_u_II_Nr_01.ly
│   ├── Score-I_u_II_Nr_02.ly
│   └── Score-I_u_II_Nr_03.ly
└── single-pages-voiceII
    ├── MIDI
    │   ├── Score-Nr_01-voiceII.midi
    │   ├── Score-Nr_02-voiceII.midi
    │   └── Score-Nr_03-voiceII.midi
    ├── PDF
    │   ├── Score-Nr_01-voiceII.pdf
    │   ├── Score-Nr_02-voiceII.pdf
    │   └── Score-Nr_03-voiceII.pdf
    ├── Score-Nr_01-voiceII.ly
    ├── Score-Nr_02-voiceII.ly
    └── Score-Nr_03-voiceII.ly

The input-files of both voices have a format like this:
\relative c {
  \clef bass
  \time 3/4
  \key c major

  c4( d e f      | %01
  g1) \bar "|."  | %02
}

The Score files have the purpose to be compiled for output of PDF and MIDI. and simply look like this (despite the fact that the Scores for two systems contain another Staff):
\version "2.18.2"

#(set-default-paper-size "a4")
#(set-global-staff-size 22)

\include "../global-files/header.ily"

\score {
  \new StaffGroup = "" \with {
    instrumentName = \markup { \bold \huge { \larger "1." }}
  }
  <<
    \new Staff = "celloI" \with { midiInstrument = #"cello" }

    \include "../input-files-voiceI/Nr_01-voiceI.ily"
  >>
  \layout {}
  \midi {}
}

The Book part is the part I'm still pretty unhappy with. I would prefer this pretty simple with just using the Score*.ly files as \includes, but I get problems with the \includes that are already in the Score.ly files, since they do not only contain the \score block to be compileable by them selfs.
Well I could use a \book with setting a book output name like \bookOutputSuffix "OutputName", but then my Book.ly would become a massive file, taking quite a long time to be compiled, even for a small change on a single piece.
So right now my Book.ly file has the following format and the only purpose to compile the whole book with two voices in two staffs, but with all pieces, here 01-03:
\version "2.18.2"

#(set-default-paper-size "a4")
#(set-global-staff-size 22)

\include "./global-files/paper.ily"

\book {

  \include "./global-files/Frontpage.ily"

  %%%% Score Number: 1 ==================================%%%%

  \score {
    \new StaffGroup = "" \with {
      instrumentName = \markup { \bold \huge { \larger "1." }}}
    <<
      \new Staff = "voiceI" \with { midiInstrument = #"voice" }
      \include "./input-files-voiceI//Nr_01-voiceI.ily"
      \new Staff = "voiceII" \with { midiInstrument = #"voice" }
      \include "./input-files-voiceII//Nr_01-voiceII.ily"
    >>
    \layout {
      \printTupletBow
    }
  }

  %%%% Score Number: 2 ==================================%%%%

  \score {
    \new StaffGroup = "" \with {
      instrumentName = \markup { \bold \huge { \larger "2." }}}
    <<
      \new Staff = "voiceI" \with { midiInstrument = #"voice" }
      \include "./input-files-voiceI//Nr_02-voiceI.ily"
      \new Staff = "voiceII" \with { midiInstrument = #"voice" }
      \include "./input-files-voiceII//Nr_02-voiceII.ily"
    >>
    \layout {}
  }

  %%%% Score Number: 3 ==================================%%%%

  \score {
    \new StaffGroup = "" \with {
      instrumentName = \markup { \bold \huge { \larger "3." }}}
    <<
      \new Staff = "voiceI" \with { midiInstrument = #"voice" }
      \include "./input-files-voiceI//Nr_03-voiceI.ily"
      \new Staff = "voiceII" \with { midiInstrument = #"voice" }
      \include "./input-files-voiceII//Nr_03-voiceII.ily"
    >>
    \layout {}
  }
}

My workflow is the following:

I write the input files: input-file.ily
I run a bash-script.sh that creates the compileable Score.ly files from the input-files/*.ily
I run a bash-script.sh that creates the compileable Book.ly file
from the input-files/*.ily
I compile the Score.ly files one by one or run a simple for file in *.ly; do lilypond "$file"; done loop, but in each of the three Score directories. I use a script to move the PDF and MIDI files into their corresponding folders.
I simply run lilypond to compile the Book.ly file.

DONE

The actual project this question is asked for can be found here on GitHub

Update 1:
My system:
    Operating System: Debian GNU/Linux bullseye/sid
              Kernel: Linux 5.3.0-2-686-pae
        Architecture: x86
        GNU LilyPond: 2.18.2
My Editor - GNU Nano: 4.5
      Guake Terminal: 3.6.3
            GNU Make: 4.2.1

I added my shell-scripts to a separate Git-Repository

Update 2:
This is a very simplified chart of the dependencies. Assuming there was only one voice:
./infiles/
  infile{01..03}.ily -------------> ./Book.ly ===> Book.pdf
     |                                 ^ ^ ^
     *---------> Scores{01..03}.ly === | | |=====> Score{01..03}.pdf
                      ^  ^         === | | |=====> Score{01..03}.midi
                      |  |             | | |
./global-files/       |  |             | | |
  header.ily    ------*  |             | | |
  copyright.ily ---------+-------------* | |
  Frontpage.ily -------------------------* |
  paper.ily     ---------------------------*

Comment: Also do inform abt OS and your editor of choice
Comment: Do you have the bash-script.sh files available anywhere? I'm having some difficulty grokking the whole procedure.
Comment: FYI: I updated my answer to provide some more context and a brief technical description of the mechanics.
Comment: This question was being discussed in [the meta](https://music.meta.stackexchange.com/questions/3437/is-this-question-on-topic?cb=1).
Answer: Invocation
make will search the current directory for a file named Makefile or makefile, so it's often simplest to name it one of these two choices and then invoke with the simple command:
$ make

If you use the uppercase 'M' then the file will usually be listed at the top according to alphabetical or collation order.
Rules
make operates by using rules for how to create an output from an input. The format for a rule is the target followed by a colon, then a space delimited list of dependencies, followed by commands indented with TAB.
target: dependencies
    commands

The target or dependencies can be filenames or symbols that correspond to other rules.
If you don't specify a target on the command line, it will invoke the first rule it encounters. So a common technique is to make the first rule a "dummy" rule which doesn't produce a file but simply collects all the steps or outputs together. Eg.
all: output1

Invoking make with this makefile will try to create output1 if it doesn't exist. If there's a rule for creating output1 later in the makefile it will use that.
For your case, I suggest making a top level rule to create Score.ly and Book.ly
all: Score.ly Book.ly

Pattern rules
To replace your shell loop, you can use a pattern rule.
%.pdf: %.ly
    lilypond $^

This rule says: To make a .pdf file, run lilypond on the corresponding .ly file.
Note that the command to execute must start with a literal TAB character. The %^ variable refers to the input file mentioned above. Other useful variables are $@ for the target, and $< for the first input if there are more than one.
This handles just part of your shell loop, defining the transformation from an input file to an output file. For the other task of generating a list of files, there are some special variables available in GNU make for this.
inputs= $(notdir $(wildcard ./*.ly))
bases= $(basename $(inputs))
outputs= $(patsubst %,%.pdf,$(bases))

After these definitions, you can use $(outputs) as a dependency in a rule, like:
pdfs: $(outputs)
    mkdir -p PDF
    mv *.pdf PDF
    mkdir -p MIDI
    mv *.midi MIDI

This example from the LilyPond docs shows that you can put multiple targets to the left of the colon, so you can account for both types of files produced by LilyPond which my example here doesn't do. Again, each of these commands must be indented with a bona fide ASCII TAB character.
For very simple cases
You can use a makefile just to collect one or more shell scripts together, ignoring much of the complexity of rules and dependencies if your situation is very simple.
For one project where I made a bunch of .abc files in a single directory, the whole thing is handled by a single rule:
all:
    for f in `ls *.abc` ;               \
    do ../abcm2ps -O $${f%.abc}.ps $$f ; \
       ps2pdf $${f%.abc}.ps ;           \
    done ;
    zip -r evildead.zip *.pdf

Comment: Works now. However a semantically loaded initial tab is so unnatural, not just to humans but even well-meaning editors that a stronger caveat may be in order??
Comment: True. That's how `make` has always worked. But I'll try to flag it more loudly and more often as I fill out the answer.
Comment: [I found this](https://paste.debian.net/1119187/) in the [LilyPond Docs](http://lilypond.org/doc/v2.18/Documentation/usage/make-and-makefiles.en.html) looks like the way to handle both formats **PDF** *and* **MIDI**, as far as I can tell from my `bash` knowledge it also looks like they use an `if statement` to find out weather the files exist or not and then run the `mv` command on it.
Comment: That didn't work. Trying .
Comment: Instead of `lilypond $^`, I would use `lilypond $<`. This lets you use `\include` and specify the dependencies in the makefile.
Comment: @Rusi The lore (tm) has it that the issue with the tabs was noticed just weeks after the utility was first released (in the 1970s) and wasn't changed because there were already more than a dozen users who would have been inconvenienced by the change.
Comment: @luserdroog I added a chart :-)
Answer: luser droog's answer gives a good overview of make itself. Here's an
example of how to apply that to a real-world Lilypond project with the
following characteristics:

Multiple parts: piano, bassoon, etc.
Multiple movements.
Multiple desired outputs: a single "master" (conductor) score, a
master score for each movement, and a part score for each
instrument.
Both PDF and MIDI outputs.
Common definitions (macros) for both music and presentation.

For instance, if your Book.ly file includes your Nr_01-voiceI.ily
file, which in turn includes your macros.ily shared definitions file,
then if macros.ily is changed, your Makefile needs to know that it
needs to recompile Book.ly to update Book.pdf.
On the othre hand, if you change just one part, it is very convenient to
be able to write make parts and have Make only recompile the part
that was changed, rather than wasting time recompiling all the others.
And, if you just want to listen to a segment, you should be able to
make midi to skip the slow typesetting and only re-do the necessary
sequencing.
I've written a shell script to generate a Makefile that has all these
properties. In particular, it automatically traverses the \include
graph of your project to figure out which Lilypond files depend on
which others, and will incur the minimal set of recompilations for any
particular change. You just tell it what "main files" you have, and
which ones you want in PDF and/or MIDI form, and it will do the rest.
Here's the script:
https://github.com/MutopiaProject/MutopiaProject/blob/918971593735f2dbf4864f289767b8d59a7d950e/ftp/MozartWA/KV488/Mozart-KV488/Mozart-KV488-lys/create_makefile.sh
Here's an example of the output Makefile:
https://github.com/MutopiaProject/MutopiaProject/blob/918971593735f2dbf4864f289767b8d59a7d950e/ftp/MozartWA/KV488/Mozart-KV488/Mozart-KV488-lys/Makefile
The core mechanism is to create a secondary target for each Lilypond
file, which I've called its "lydep" ("Lilypond dependencies") file, such
that a file's lydep is dirty if and only if any of the file's transitive
sources is dirty. In practical terms, this means that each lydep target
needs to depend on its source file plus all the lydep targets on which
it has direct \include dependencies. Then, Make's automatic resolution
takes care of the rest.
The script is tailored to a particular project, but you should be able
to keep the core infrastructure in place and customize the makefile
function at the bottom to substitute in your project structure.
I've written this script for GNU/Linux, and it might need some minor
adjustments for macOS/BSD (e.g., swapping out readlink -f), but it's
pretty straightforward overall. It does require bash and GNU make
(for secondary targets). I see that you're on Debian, so it should run
just fine as is.
This is all released under the MIT License. Please feel free to take
whatever you find helpful.
Comment: Sure thing. I'll see if I can explain/summarize the gist of it when I get a chance later today.
Comment: yuhu man, this is quite a couple of lines to read through. Thanks for the answer, and for sharing your work! <3


Disable the cache for a specific view

Question: I'm showing my users a random number ({{ random() }}) in a twig which is being rendered in a view. But when I refresh a page it just shows me the same number.
I tried several things but they all failed:

Disabled caching in admin/config/development/performance
Disabled cache in views advanced settings
tried to use cacheexclude module
I even disabled twig cache!

How can I completely disable cache for specefic twig or specefic view?
Update:
By the way in response header there is a header called x-drupal-cache:HIT. (It's MISS for the first time and then HIT after first load) Why?
Update 2:
I uninstalled Internal Page Cache too. the x-drupal-cache is gone now but the page is still being cached! I literally disabled everything but still no luck to show a random number in twig in a view..
This is my response header if it helps:
cache-control:must-revalidate, no-cache, private
content-encoding:gzip
content-type:text/html; charset=UTF-8
date:Wed, 28 Feb 2018 14:26:47 GMT
expires:Sun, 19 Nov 1978 05:00:00 GMT
server:nginx
status:200
strict-transport-security:max-age=15768000
vary:Accept-Encoding
x-content-type-options:nosniff
x-drupal-dynamic-cache:UNCACHEABLE
x-frame-options:SAMEORIGIN
x-generator:Drupal 8 (https://www.drupal.org)
x-ua-compatible:IE=edge

Solution:
I uninstalled Internal Cache module and ALSI big pipe module too.
Comment: 1 and 2 should be enough ... maybe your server is running some kind of cache ? its been know with some very popular hosts to run cache for an account automatically and you have to actually go in the panel to disable it.
Comment: @GiorgosK I'm just using Nginx and php-fpm and nothing else... In response header there is a tag called `x-drupal-cache:HIT`
Answer: Unfortunately point 1 doesn't work for anonymous traffic.
You have to uninstall the Internal Page Cache module.
Or trigger
\Drupal::service('page_cache_kill_switch')->trigger();

in a view hook.
When the View is placed on most or all pages then uninstall the Internal Page Cache, because the page cache kill switch also disables the dynamic page cache and you don't want to disable both caches, unless this is only for a few pages which don't have too much traffic.
Additionally you need point 2 (disabled cache in views advanced settings) in any case.
Update:

By the way in response header there is a header called
  x-drupal-cache:HIT. (It's MISS for the first time and then HIT after
  first load) Why?

This header is generated by the Internal Page Cache, a HIT means it is served from this cache.
Comment: @4x4 are you sure ?  I have at least a view on Drupal 3.7 currently that serves random content from a view (even for anonymous) with internal Page Cache enabled as I described in my answer.
Comment: Thank you for your answer. Where should I add `\Drupal::service('page_cache_kill_switch')->trigger();`? `mytheme_views`?
Comment: @GiorgosK, yes, see this issue https://www.drupal.org/project/drupal/issues/2352009. Sky, you can use any view hook, but I would prefer `hook_views_pre_render`, because this also works in themes.
Comment: @4k4 I disabled Internal Page Cache Module. Also added `\Drupal::service('page_cache_kill_switch')->trigger();` too. The `x-drupal-cache` header is gone but the page is still being cached :( I just did everything!
Comment: @Sky, to be sure you can add `$variables['#cache'] = ['max-age' => 0];` to hook_preprocess_views_view, although this should be done already by point 2 in Views UI. I don't know what you can else do, at least not with the information you've provided so far.
Comment: ... for example if `{{ random() }}` was inside of an entity template, then you would need to add cache max-age = 0 to the preprocess hook of that entity, for example hook_preprocess_node
Comment: Thank you so much. I had to uninstal big pipe module too
Answer: In Drupal 8 in order to disable cache for a specific view
your view > ADVANCED > Caching > None

For your case twig caching is probably at play but it better be left untouched.
services.yml > twig.config:  cache: false

You might want to consider creating a random number in view using
https://www.drupal.org/project/views_random_seed
NOTE: If you Drupal cache is enabled in admin/config/development/performance than the no cache setting of any view will not be respected by default and all views will be cached instead.  Installing cache_control_override will help resolve this and allow views configured with no cache to work as such.  Read more on this problem in the module's page.
Above problem is resolved assuming there is no other caching mechanisms between the drupal site and the browser.
Comment: Thank you but I disabled twig cache too but it loads the same number after the first page load (After clear cache)
Comment: Try rebuilding cache https://drupal.stackexchange.com/questions/203184/turn-off-twig-cache.  Also just realized that there is a report that the clearing of twig cache is not that reliable https://www.drupal.org/project/drupal/issues/2752961

Disable the cache for a specific view


Show the following 3 spaces are homeomorphic.

Question: I want to show the following 3 spaces are homeomorphic to one another.

$\{0,1\}^{\omega}$, i.e., $\{0,1\}^{\mathbb{N}}$, the set of infinite sequences of 0's and 1's, in the dictionary order topology.
$\{0,1\}^{\omega}$, the same set, in the product (cylinder) topology.
The Cantor Set $C$.

I've been stuck in this question for quite a while. Sincerely appreciate any help! Thanks a lot.
Answer: This answer of mine sets out the basics for the Cantor set definition and outlines the homeomorphism with $\{0,1\}^\omega$ as well.
It remains to notice that the lexicographic order is just the usual order that $C$ inherits from $[0,1]$, under this homeomorphism. So we get an order isomorphism that way.
There is also Brouwer's theorem that all spaces $X$ that are compact, Hausdorff, have a countable base of clopen sets and do not have isolated points are homeomorphic to the Cantor set. But this is not commonly taught (only as a matter of course in descriptive set theory, where it's used extensively).


How can I add field information to an standard image?

Question: How can I automate this. I am having some sort op coupon like website. But I want the coupon code to be placed into an image. With the nessecary information from the rest of the fields, like date and other conditions, company name, etc.
How can I accomplish this?
Comment: What exactly do you mean? `` over ``? Text as a graphic? fields into EXIF?
Answer: I assume you already have image installed and a content type set up that you have an image field attached to.

You will need to install the following modules image cache actions and token
 also the following will need to be enabled "Image Effects Text" (this is part of image cahce actions)
Add an image style by going to example.com/admin/config/media/image-styles and clicking add style.
Using the select list under Effect select text and then click add
You will now be in a page where you can set all the txt setting including the actual text to overlay the image with. You can select the type of text using the select list labelled "text source" if you have token installed you can select token and browse tokens for your replacement text.


Is fibonacci sequence a member of more broad family of sequences?

Question: Yesterday, I was pondering on the Fibonacci sequence and  I started to discover some features of it that were previously unknown to me.
Such as,
1, 1, 2, 3, 5, 8, 13, 21, 34 ....
1 ) The nth element of the sequence is the sum-1 of first n-2 elements.
2) If you multiply the first number with one and the second one with the two and sum them, you would get the fibonacci number, after the next element of the sequence.
For example, 1x1 + 1x2 =  3.
3x1 + 5x2 = 13.
5x1 + 8x2 = 21.
and so on.
What is more, if I do this for another subsequent (5, 8 or 2, 3) fibonacci numbers I would get another Fibonacci number but in this case, I would not skip one element, instead, I would skip 'x' times where 'x' is equal to the index of the first occurence of the subsequent numbers.
For example,
3x5 + 5x8 = 55, normally we would get the next element, if the second operands would be one but in this case we get the 4th element after the next fibonacci number.
It amazed me and I asked to myself, if there was any other such sequence.
Then I realized that, any sequence generated by random two number has the same property.
For example,
suppose that the first two numbers in my sequence are 3 and 4.
I will generate the next element of the sequence by multiplying the previous one with 3, the current one with 4 and summing those two results.
Following happens,
3, 4, 25, 112, 523 ...
And this series also satisfies the second property mentioned above.
So, my question is, Do all this sort of sequences have another name which refers to that abstraction?
OR is this property trivial?
Comment: $x_n\cdot 1 + x_{n+1}\cdot 2 = (x_n+x_{n+1}) + x_{n+1}=x_{n+2}+x_{n+1}=x_{n+3}$
Answer: I think you should take a look at recurrence relations - wikipedia has a nice article on them.
The Fibbonacci sequence is given by such a relation:
$$f_{n+2}=f_{n+1}+f_{n},\quad f_0=f_1=1.$$
This definition directly yields you second property: $f_{n+3}=f_{n+2}+f_{n+1} = 2f_{n+1}+f_{n}$.
This a particular case of linear recurrence relation of second order (an element is a linear combination of two its predecessors).
In general case the second order linear homogenous relation writes $$x_{n+2} = ax_{n+1}+bx_n$$ with some sort of initial data. These relations are useful, for example, for finding the determninants of tridiagonal matrices (if the determinant is non-zero then we have nonzero eigenvalues), which in turn arise quite often in numerical methods (recall the matrix of discretised second order derivative).
The homogenous first order recurrence relations yield geometric progressions: $x_{n+1}=ax_n$.
Answer: As @TZakrevskiy points out, what you describe is
$$
x_{n}=x_{1}x_{n-1}+x_{0}x_{n-2}\text{ for }n>1.
$$
Let
$$
\mu_{\pm}=x_{1}\pm\sqrt{x_{1}^{2}+4x_{0}}.
$$
This recurrence can be solved to yield
$$
x_{n}=\frac{1}{2^{n+1}}\left[\frac{x_{1}\left(x_{0}-2\right)}{\sqrt{x_{1}^{2}+4x_{0}}}\left(\mu_{-}^{n}-\mu_{+}^{n}\right)+x_{0}\left(\mu_{-}^{n}+\mu_{+}^{n}\right)\right]
$$
Comment: You can verify that for $x_0=3,x_1=4$, the first terms are $3,4,25,112,523,2428,11281,52408,\ldots$


can't jump from one activity to the next

Question: Hey everyone,
I cannot jump from my launch-activity to my second activity and i don't know why. this is the error i get:
02-22 11:43:04.858: ERROR/AndroidRuntime(18335): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.Database/android.Database.projects}: android.database.sqlite.SQLiteException: no such column: _id: , while compiling: SELECT  _id, Name, Comment, projects

this is my launch-activity:
package android.Database;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class projectsDatabase extends Activity {
    /** Called when the activity is first created. */

    SQLiteDatabase myDB = null;
    final static String MY_DB_NAME ="projectsDatabase";
    final static String MY_DB_TABLE = "projects";

    static final int MENU_PROJECTS = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onCreateDBAndDBTabled();
        setContentView(R.layout.main);
    }

    private void onCreateDBAndDBTabled(){

        myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
        myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
                + " ( _id integer primary key autoincrement,"+
                "Name varchar(100),"+
                "Comment varchar(128),"+
                "BookingDetails varchar(255),"+
                "ProjectKind integer(3))"
                +";");
         }

    public boolean onCreateOptionsMenu(Menu menu) {
          super.onCreateOptionsMenu(menu);

            menu.add(0, MENU_PROJECTS, 0, R.string.menuProjects)
            .setShortcut('1', 'f')
            .setIcon(R.drawable.icon);
             return true;

          }

    public boolean onOptionsItemSelected(MenuItem item){
          switch (item.getItemId()) {
          case MENU_PROJECTS:
            Intent iProjects= new Intent(this, projects.class);
            startActivity(iProjects);
            return true;
          }
          return false;
        }

}

and this is the actiity i want to start when the menu-button is clicked:
package android.Database;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

public class projects extends ListActivity {

        SQLiteDatabase myDB = null;

        static final int MENU_NEW_PROJECT = 0;

        public void onCreate(Bundle icicle){
            super.onCreate(icicle);

            myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);

            Cursor c = myDB.rawQuery("SELECT  _id, ColumnName, ColumnComment, " + projectsDatabase.MY_DB_TABLE + ";", null);
            startManagingCursor(c);

                SimpleCursorAdapter adapter = new SimpleCursorAdapter (this,
                        android.R.layout.simple_list_item_1,
                        c,
                        new String[] {"_id"},
                        new int []{android.R.id.text1});

                adapter.setViewBinder (new ViewBinder (){

                    @Override
                    public boolean setViewValue(View view, Cursor theCursor, int column){

                        String ColumnName = theCursor.getString(1);//Name
                        String ColumnComment = theCursor.getString(2);//Comment

                        ((TextView)view).setText(ColumnName + "," + ColumnComment);

                        return true;
                    }

                });
                this.setListAdapter(adapter);

        }

        @Override
                protected void onListItemClick(ListView l, View v, int position, long _id){
                            super.onListItemClick(l, v, position, _id);

                            Intent i = new Intent(this, projects_New.class);
                            i.putExtra("_id", _id);
                this.startActivity(i);
            }

        public boolean onCreateOptionsMenu(Menu menu){
            super.onCreateOptionsMenu(menu);
                    menu.add(0, MENU_NEW_PROJECT, 0, R.string.menuNewProject)
                .setShortcut('1', 'n')
                .setIcon(android.R.drawable.ic_menu_add);
            return true;
            }

        public boolean onOptionsItemSelected(MenuItem item){
            switch (item.getItemId()){
            case MENU_NEW_PROJECT:
                Intent iProjects_New = new Intent (this, projects_New.class);
                    startActivity (iProjects_New);
                    return true;
            }
            return false;

        }

}

I really hope you can help me out again ;)
--------------------------------------------Edit-------------------------------------------
now i can save data but can't select anything from my listview... here is the code for my projects_new.class :
package android.Database;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class projects_New extends Activity{
    SQLiteDatabase myDB = null;
    static final int MENU_INSERT_PROJECT = 0;
    static final int MENU_UPDATE_PROJECT = 0;

    @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.projects_new);

            Spinner s1 = (Spinner) findViewById(R.id.cb_ProjectKind);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this,
            R.array.ProjectKind,
            android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(adapter);

        if(getIntent().hasExtra("_id") == true){
                long l = getIntent().getExtras().getLong("_id");
                myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);

                Cursor myCursor = myDB.rawQuery("SELECT _id, ColumnName, ColumnComment, ColumnBookingDetails, ColumnProjectKind FROM"
                                                + projectsDatabase.MY_DB_TABLE + "WHERE _id = " +l+ "", null);
                startManagingCursor(myCursor);

                int ColumnName = myCursor.getColumnIndex("ColumnName");
                int ColumnComment = myCursor.getColumnIndex("ColumnComment");
                int ColumnBookingDetails = myCursor.getColumnIndex("ColumnBookingDetails");
                int ColumnProjectKind = myCursor.getColumnIndex("ColumnProjectKind");

                myCursor.moveToFirst();

                if (myCursor != null) {
                    if(myCursor.isFirst()){
                        EditText eName = (EditText)findViewById(R.id.ed_Name);
                        eName.setText(myCursor.getString(ColumnName));

                        EditText eComment = (EditText)findViewById(R.id.ed_Comment);
                        eComment.setText(myCursor.getString(ColumnComment));

                        EditText eBookingDetails = (EditText)findViewById(R.id.ed_BookingDetails);
                        eBookingDetails.setText (myCursor.getString(ColumnBookingDetails));

                        Spinner sProjectKind = (Spinner)findViewById(R.id.cb_ProjectKind);
                        sProjectKind.setSelection(myCursor.getInt(ColumnProjectKind), true);
                    }
                }
            }
        }

    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);

        if(getIntent().hasExtra("_id")== true)
        {
            menu.add(0,MENU_UPDATE_PROJECT, 0, R.string.menuUpdate)
            .setShortcut('1', 's')
            .setIcon(android.R.drawable.ic_menu_save);
        }
        else
        {
            menu.add(0, MENU_INSERT_PROJECT, 0, R.string.menuInsert)
            .setShortcut('1', 's')
            .setIcon(android.R.drawable.ic_menu_save);
        }
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
        case MENU_INSERT_PROJECT:
            EditText Name = (EditText)findViewById(R.id.ed_Name);
            EditText Comment = (EditText)findViewById(R.id.ed_Comment);
            EditText BookingDetails = (EditText)findViewById(R.id.ed_BookingDetails);
            Spinner ProjectKind = (Spinner)findViewById(R.id.cb_ProjectKind);

            int i = ProjectKind.getSelectedItemPosition();

            if(Name.length()!= 0)
            {
                myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);

                        if(getIntent().hasExtra("id")== true)//update
                        {
                            long l = getIntent().getExtras().getLong("_id");
                            myDB.execSQL("UPDATE "+ projectsDatabase.MY_DB_TABLE+" SET "+
                                    "name = '"+Name.getText().toString()+"', "+
                                    "Comment = '"+Comment.getText().toString()+"', "+
                                    "BookingDetails ='"+BookingDetails.getText().toString()+"', "+
                                    "ProjectKind ='"+i+"', "+
                                    "WHERE _id = "+l+";");

                        }
                        else //insert
                        {
                            myDB.execSQL("INSERT INTO "+ projectsDatabase.MY_DB_TABLE +"(Name, Comment, BookingDetails, ProjectKind)"
                                                                                +"VALUES ('"+Name.getText().toString()+"', "+
                                                                                "'"+Comment.getText().toString()+"', "+
                                                                                "'"+BookingDetails.getText().toString()+"', "+
                                                                                "'"+i+"')");
                        }
                        finish();
                        return true;
            }
            else
            {
                Toast toast = Toast.makeText(this, "Please enter a name for this Project!" , Toast.LENGTH_SHORT);
                toast.show();
            }
        }

        return false;
    }

}

Thank you so much for all your effort and help :)
Answer: In your Projects class you defined the following line
    Cursor c = myDB.rawQuery("SELECT  _id, ColumnName,
ColumnComment, " + projectsDatabase.MY_DB_TABLE + ";", null);

because it' says, there's no colunm _id in your table, so pls check that _id is a column in your table.
Pls ensure a clolun _id exists or not
Comment: @Sankar yes it did ;) just working on the insert statement now :D thank you!
Comment: @Sam: can you post your create table query and select query
Comment: @Sam: Show the Colunms of your table
Comment: @Sankar I can save data now, just can't select sth from the listView then to update... will post that statement.


Amazon Web Services EFS doesn't seem to be saving files

Question: So I'm trying to use AWS EFS with EC2 to have persistent storage between multiple instances.
I'm mounting the drive using,
sudo mount -t nfs4 -o nfsvers=4.1 $(curl -s http://IPADDRESSHERE/latest/meta-data/placement/availability-zone).FILESYSTEMIDHERE.ZONEHERE.amazonaws.com:/ /mydir. I have replaced some of the key information with placeholders for security reasons.
After running that nothing happens it just goes right back to the terminal no success message and no error message so I assume it worked.
I create a folder or file inside /mydir and ls /mydir and everything shows up fine.
Then I unmount the drive using sudo umount /mydir. Once again after running that no error but no success message so I assume it worked. All the files stay in the folder and nothing changes after running that.
Then I create a new directory and mount the drive to that new directory and none of the files or folders I created show up in that new folder.
So it looks like it's not even saving to the EFS drive if when mounting to a new folder it doesn't even sync down the files. Any ideas on how to get this working? Thanks so much in advance.
Comment: Are you inside of /mydir when mounting? Any interesting logs in "dmesg"?
Comment: @EEAA Yes I am inside of /mydir when mounting. I have uploaded the result of "dmesg" here, http://pastebin.com/ZtauTKKe
Comment: That is likely the problem. Try staying in the parent of /mydir to mount, then cd into /mydir.
Comment: @EEAA Oh wow looks like that worked. One last question that is totally unrelated. Does mounting an EFS drive take up the local storage on EBS? And if so does un-mounting that EFS drive free that storage? Also feel free to submit that as an answer if you would like and I will accept it and up vote it. Thanks so much for your help!!
Answer: To your original question: if you mount a filesystem "on top" of your current working directory, you will not see the contents of the mounted fs, nor will you be able to save content to that fs until you cd back to the parent directory and then enter the mounted fs again.
When you write data, it consumes space on whatever filesystem it is written to. In the case of EFS, data saved there will not affect usage of your EBS volumes.


Correct way to render an custom entity and its custom field?

Question: In my module, I have a custom entity LocationEntity and it uses a custom field type CoordinateItem which has 2 sub fields X, Y.
So what is the correct way of Drupal 8 to:
1) Render this LocationEntity in a twig template?

What I'm doing is just send the entity to twig template '#loc1' and manually render its each field value using getter method {{ loc1.getName() }}. It works but I'm sure this is not the correct way to do.

2) If question 1 has another correct way then how to have more than one templates for rendering the entity?

For example, one simple layout with less fields and one detail layout with all fields.

3) In the entity, I defined to use the custom field CoordinateItem. But now what to do with its getter and setter, because it's not a single sub field inside?

Getter if $this->get('coord') -> a FieldItemList object.
Getter if $this->get('coord')->value -> null.
Setter? What type is the parameter?

4) I wrote a formatter for CoordinateItem to show its sub fields. But again I don't know how to use this formatter to render this custom field in the main (entity) template?

Maybe this is related to question 1 and 2?
Answer: View Builder

Set the view_builder in ContentEntityType annotation to EntityViewBuilder to inherit some default behavior (or write your own).

Set your canonical router to something like what content_entity_example does in the examples module.

Berdir suggests using DefaultHtmlRouteProvider though that class is marked as @internal so it may not be stable to use long term.

content_entity_example.routing.yml
entity.content_entity_example_contact.canonical:
  path: '/content_entity_example_contact/{content_entity_example_contact}'
  defaults:
    _entity_view: 'content_entity_example_contact'
    _title: 'Contact Content'
  requirements:
    _entity_access: 'content_entity_example_contact.view'

Change your entity theme to something like what node module does, and have it display as a render element.

Use your entity or bundle's field display page to change what field formatters a given field will use.

Then you can print out {{ elements }} in the template for it to go through the entire render array for a given view mode. Again, you can follow something similar to node module.
Comment: Instead of 2. use the DefaultHtmlRouteProvider, that generates standard routes automatically based on the link templates.
Comment: Not sure why it is @internal, it's IMHO definitely the recommended way to do this these days. I think It's just internal because we keep adding more features to it in minor releases, but we recently agreed that we can do that to all interfaces/classes.


Why is commutativity optional in multiplication for rings?

Question: More precisely, why is it that all rings are required by the axioms to have commutativity in addition, but are not held to the same axiom regarding multiplication? I know that we have commutative and non-commutative rings depending on whether or not they are commutative in multiplication, but I am wondering why it is that the axioms were defined that way, providing us with this option.
I am using this list of axioms, from David Sharpe's Rings and factorization:

Definition 1.3.1. A ring is a non-empty set $R$ which satisfies the following axioms:
(1) $R$ has a binary operation denoted by $+$ defined on it;
(2) addition is associative, i.e.
  \begin{align}
a + \left(b+c\right) = \left(a+b\right) + c \text{ for all } a, b, c \in R
\end{align}
  (so that we can write $a+b+c$ without brackets);
(3) addition is commutative, i.e.
  \begin{align}
a + b = b + a \text{ for all } a, b \in R;
\end{align}
(4) there is an element denoted by $0$ in $R$ such that
  \begin{align}
0 + a = a \text{ for all } a \in R
\end{align}
  (there is only one such element because, if $0_1$ and $0_2$ are two such, then $0_1 = 0_1 + 0_2 = 0_2$ and they are the same -- we call $0$ the zero element of $R$);
(5) for every $a \in R$, there exists an element $-a \in R$ such that
  \begin{align}
\left(-a\right) + a = 0
\end{align}
  (there is only one such element for each $a$, because if $b + a = 0$ and $c + a = 0$, then
  \begin{align}
b = 0 + b = \left(c + a\right) + b = c + \left(a + b\right) = c + 0 = c;
\end{align}
  we call $-a$ the negative of $a$);
(6) $R$ has a binary operation denoted by multiplication defined on it;
(7) multiplication is associative, i.e.
  \begin{align}
a\left(bc\right) = \left(ab\right)c \text{ for all } a, b, c \in R;
\end{align}
(8) multiplication is left and right distributive over addition, i.e.
  \begin{align}
a\left(b+c\right) = ab + ac,\ \left(a+b\right)c = ac + bc
\text{ for all } a, b, c \in R;
\end{align}
(9) there is an element denoted by $1$ in $R$ such that $1 \neq 0$ and
  \begin{align}
1 \cdot a = a \cdot 1 = a \text{ for all } a \in R
\end{align}
  (as for the zero element, there is only one such element, and it is called the identity element of $R$).
Comment: The first rings that were considered were generally commutative, but it soon became apparent that rings with noncommutative multiplication were far too common, starting with matrices and, more generally, endomorphism rings of abelian groups. On the other hand, if you take the definition of ring with unity, but omit the condition that addition is commutative, it turns out that you can *prove* that the other conditions *force* commutativity of addition.
Comment: For what it's worth, we also have the notion of a "commutative ring," one in which multiplication *does* commute. (https://en.wikipedia.org/wiki/Commutative_ring) Of course I get you're trying to get at *why* we don't require this, and I don't know how to answer you on that, but I figured it's a point worth bringing up.
Comment: Note that matrices are an example where addition is commutative but multiplication is not necessarily
Comment: @EeveeTrainer Thank you! I dunno if you missed it, but I did express my awareness of that.
Comment: Oh, I did miss it, sorry about that Kusa. xD
Comment: @ArturoMagidin Oh cool! There is in fact a remark on the next page stating that Axioms 1-5 may be summarized by saying that R is an abelian group under addition, but I didn't fully register it until I read your comment. Regarding everything else, since I am pretty new here and your comment seems like a pretty good answer, is there a reason you opted to comment rather than answer?
Comment: @Kusa: working on it...
Comment: @ArturoMagidin oh whoops, I see how that works now!
Comment: Some authors do define rings to be commutative in certain contexts. It's merely a convention which one deserves the shorter name "ring". Same for whether or not rings have $1$ (and whether it must be preserved by ring maps).
Comment: Here's the real question: Why in the seven hells does the author require $1 \neq 0$ ?
Comment: @darijgrinberg on the next page he discusses how some authors do not consider 9 an axiom, but he wishes to insist that our rings have an identity element.
Answer: The first rings that were considered were generally commutative; polynomial rings, then from work of Dedekind in number fields. The properties were then abstracted by Fraenkel and Noether, who still dealt mostly with commutative rings.
However, it soon became apparent that there were too many instances where commutativity of multiplication did not hold. You had famously the quaternions, of course, but you also had matrices and, more generally, the endomorphism ring of an abelian group (where "multiplication" is composition of functions). So that we have two different, related, notions: commutative rings and noncommutative rings, just like we have noncommutative groups and commutative/abelian groups.
Now, why do this with multiplication and not with addition? Well, if you take your definition of ring above, which includes a unity, but you drop condition (3) (that is, you require everything except you do not require that addition be commutative), it turns out that the other eight axioms force commutativity of addition.
Indeed, suppose you have a structure $(R,+,\cdot,0,1)$ that satisfies axioms (1), (2), and (4)-(9) above. I claim that one can deduce (3). Indeed, let $a,b\in R$. Then using distributivity on the left first, and distributivity on the right second, we have
$$\begin{align*}
(1+1)(a+b) &= 1(a+b) + 1(a+b) = a+b+a+b\\
(1+1)(a+b) &= (1+1)a + (1+1)b = a+a+b+b.
\end{align*}$$
From this we get that $a+b+a+b = a+a+b+b$. Now add the inverse of $a$ on the left and the inverse of $b$ on the right on both sides to get
$$\begin{align*}
(-a) + a + b  + a + b + (-b) &= 0+b+a+0 = b+a\\
(-a) + a + a + b + b + (-b) &= 0+a+b+0 = a+b
\end{align*}$$
Thus, we conclude that $a+b=b+a$. That is, commutativity of addition is a consequence of the other eight axioms.
The reason we include it is two-fold: one, is that it is much nicer to say that the first few axioms force $(R,+)$ to be a commutative/abelian group. The second is that it is also common to consider rings without unity, and if we do that, then it is no longer true that addition is forced to be commutative. To see this, note that if $(G,\cdot)$ is any group with identity element $e_G$, and we define a multiplication on $G$ by letting $a*b=e_G$ for all $a,b\in G$, then $(G,\cdot,*)$ satisfies axioms (1)-(8) given above. But if the original group is not commutative, then the "addition" in this ring is not commutative. So if we want to consider rings without unity, we do want to explicitly require addition to be commutative.
Comment: @darijgrinberg: No... if you assume that your (possibly nonabelian) group has a left neutral element and left inverses, then you can deduce they are both two-sided. Problems only arise if you require the neutral and inverses to be on opposite sides.
Comment: There is an entire thread on the 4th paragragh, see [Why is ring addition commuattive?](https://math.stackexchange.com/q/609364/242)
Comment: Nitpick: The way the author of the quote defines $0$ and $-a$, your argument may not work. You are relying on the "sane" definitions on $0$ and $-a$, which require $0$ to be a two-sided neutral element and $-a$ to be a two-sided inverse of $a$.
Comment: @ArturoMagidin: Ah, I see! That's a neat exercise in itself.
Answer: I don't know about the history, but I think the right way to motivate rings is via their linear action on some set. Even the semi-ring of natural numbers $\def\nn{\mathbb{N}}$$\nn$ should be motivated by the action of counting numbers on objects, where you want the following for any $a,b ∈ \nn$ and object collections $X,Y$:

$a·X+a·Y = a·(X+Y)$   [$a$ copies of $X$ plus $a$ copies of $Y$ is $a$ copies of ( $X$ plus $Y$ )]
$a·X+b·X = (a+b)·X$   [$a$ copies of $X$ plus $b$ copies of $X$ is $(a+b)$ copies of $X$]
$a·(b·X) = (a·b)·X$   [$a$ copies of $b$ copies of $X$ is $(a·b)$ copies of $X$]
$1·X = X$   [$1$ copy of $X$ is just $X$]
$0·X + Y = Y$   [$0$ copies of $X$ plus $Y$ is just $Y$]
$X + Y = Y + X$   [Combining collections is symmetric]

Here $\nn$ acts via $·$ on the commutative semi-group $C$ of collections of things under combining, and the point is that we can abstract out the counting numbers $\nn$ by simply dropping the semi-group $C$ that $\nn$ acts on.
Note that associativity and commutativity of $+$ for $\nn$ immediately follows from associativity and commutativity for $C$.
Now observe that for any $a,b,c ∈ \nn$ and object collection $X$ we have:

$(a·(b+c))·X = a·((b+c)·X)$ $= a·(b·X+c·X)$ $= a·(b·X)+a·(c·X)$ $= (a·b)·X+(a·c)·X$.
$((a+b)·c)·X = (a+b)·(c·X)$ $= a·(c·X)+b·(c·X)$ $= (a·c)·X+(b·c)·X$.

So we have obtained distributivity for $\nn$!
But what about commutativity of $·$ for $\nn$? That corresponds to:

$a·(b·X) = b·(a·X)$   [$a$ copies of $b$ copies of $X$ is $b$ copies of $a$ copies of $X$]

Is it obviously true? For "copies" in the real world, sure, and hence we get the familiar semi-ring properties of $\nn$. Similar motivation involving scalings gives us semi-ring properties of $\mathbb{R}_{≥0}$.
If we move to the more abstract notion of collections of assets owned/owed, we can easily get the ring $\mathbb{Z}$, and likewise once we consider inverse scalings we get the ring $\mathbb{R}$.
In general, if a ring $R$ acts on a group $G$, then $R$ will automatically acquire associativity, and also naturally acquire commutative addition if $G$ is commutative.

But commutative multiplication is different. For copying and scaling, indeed the action is commutative. But it should be obvious that in general actions are not commutative!
For example, the collection $T$ of rigid transformations acts on set $S$ of locations (vectors), and certainly $A·(B·X)$ may not be $B·(A·X)$ for general $A,B ∈ T$ and location $X$ (rotations and translations do not generally commute). So if $T$ is viewed as a ring, with addition being pointwise addition and multiplication being composition, then this ring has commutative addition (since vector addition is commutative) but has non-commutative multiplication. And of course $T$ is a subset of linear operators on the vector space of locations, which can be represented by matrices. After all, matrix multiplication is defined so that it is the same as composition.
Comment: @Kusa The "linear action" view of rings is that they are isomorphic to a subring of the ring of linear maps on their underlying abelian group  (this can be viewed as a ring theoretic analog of Cayley's theorem that a group may be represented as a subgroup of the group of bijections (permutations) acting on it. See the [links here](https://math.stackexchange.com/a/95208/242) for more on such representation theory (including category-theoretic generalizations).
Comment: it is safe to say I've learned a great deal from this comment, thank you sincerely!
Comment: @Kusa: You're very welcome! Also see [this](https://math.stackexchange.com/a/1847519/21820) and other posts linked from my profile under "Rigour with intuition".
Answer: Matrix rings are the same as set of linear transformations ('endomorphisms') after writing them in a fixed basis. These linear transformations are functions of special kind (satisfying linearity conditions).
The functions taking values in vector space can be added and so make a vector space. As the domain and codomain are the same vector spaces, they can be composed.
The function addition and compositions  satisfy distributive law.
Unfortunately function compositions are rarely commutative.
For example in the nicest situation of functions from real numbers to real numbers  namely $f(x)= \sin x,\ g(x)= x^2$. Clearly $\sin (x^2)\neq \sin^2 (x)$.
(Or much simpler $(x+5)^2\neq x^2 +5$.)
Functions and their compositions being mainstream operations in all branches of mathematics (not just algebra) we need a study of these operations and so we have to accommodate non-commutative rings.
In a different set-up, where there is no ring just a group: Galois group of a normal separable finite extension of fields consists of field automorphisms. Automorphisms are first of all functions from a field onto themselves.
Their compositions make them into a group. Again as function compositions are rarely commutative, one needs to single out the case where these Galois groups turn out to be abelian and find out what is special about them.
There is a whole subfield (pun intended) of Algebraic Number Theory called Class Field Theory that deals with cases of abelian Galois groups (and much more). The simplest cases of rational numbers as base field there is a celebrated theorem of Kronecker-Weber describing how to obtain all algebraic number fields that are abelian Galois extensions.
Comment: Right, and I hope that my answer succeeds in giving a layman-level motivation of ring action corresponding to the first half of your answer. =)
Answer: Commutativity is optional in the definition of a ring (or even a field) because one can already prove tons of propositions about rings (and even fields and modules and vector spaces) without assuming commutativity. The fewer assumptions one makes, the better are one's axioms.
It is more convenient to define a ring in general and to assume commutativity only when it is needed.
Comment: French authors (and those who follow Bourbaki) do not assume that "field" implies commutativity. However, pretty much everyone else uses "division ring" for a ring (commutative or not) in which every nonzero element has a multiplicative inverse, and reserves "field" for the commutative case.
Comment: Your claim that axiomatizations are better when they make fewer assumptions is **absolutely wrong**, and demonstrably so. For example, groups may be axiomatized by only requiring the existence of left-identity and left-inverses. One can recover the existence of right-identity and right-inverses, but it would be ridiculous to use the former axiomatization. Another example, propositional logic can be reduced to the [Sheffer stroke with just modus ponens plus a single short axiom schema](https://en.wikipedia.org/wiki/Minimal_axioms_for_Boolean_algebra), but it is obviously practically useless.
Comment: Furthermore, one can prove the translation (via suitable encoding) of a lot of results in real analysis in very weak systems of arithmetic such as ACA. Does that mean that ACA is better than some set theory that actually can construct the real numbers (like Z) for real analysis? Of course not. It isn't important whether fewer assumptions are made. What's important is how **meaningful** those assumptions are. You are right that we can prove lots of facts about rings and modules, but it is the general applicability of those facts that make rings and modules important in the first place.
Comment: If a property (eg existence of right identity and right inverse) can be deduced from other axioms, it is not an **assumption**.

Of course, axiomatizing groups stating only the existence of left identity and left inverse would be pedantic and unpractical.
Comment: I had difficulties finding good material about non commutative linear algebra (I recommand van der Waerden Algebra btw), just to discover that the results I needed could have been included almost for free  in any algebra book!


What's the theory behind Chim Chim Cher-ee?

Question: Chim Chim Cher-ee has a fantastic chord structure:
i, IIIaug, III, IV, iv, i, II7, V
Most of those transitions make sense to me.  However, there are three transitions that I don't quite understand:
the i to IIIaug, IIIaug to III, and IV to iv.
All of these make the moving baseline nice and smooth  (down a half step every measure).  That said, I can't just make a song that has a the same baseline, and just choose any chord on top of it, and have it sound nice.
Why do those transitions work?  Is the IIIaug not really a chord, and simply a moving note?   Why is going from Major to minor fine here, and are there other spots that this transition is fine?
Comment: I never knew the song had that as its title!
Comment: Google "line cliché"
Answer: This is an example of using chromaticism and common tones to color a chord progression.
If you look at the three chords you listed, there is one note difference between all of them. They have two common tones and the other note is approached by half step. In fact if you follow that chromatic note, you'll see it's what's driving that progression as that note continues to descend stepwise.
Another thing to note in your analysis is II7 is not correct. This is a common mistake for people stating to learn Roman Numeral Analysis.  This chord is not functioning in the original key, but tonizing V by acting like a dominant. So the Roman Numeral for this would be V7/V.
Comment: Until  I read the OP's roman numeral analysis, it never occurred to me to think about this song in terms of "chords". The most important thing after the tune is the counter-melody which is just a chromatic scale - in C, it's C B Bb A Ab G F# G. But then I play more Bach than Sherman & Sherman...
Comment: @coconochao it's not. It's a functional chord to the dominant, so writing in terms the tonic makes no sense. People understand what you mean, but it doesn't show the proper relationship. The whole point of Roman Numeral analysis is to show the function of the harmony which II7 does not function as any type of II. It's acting like a V. An example of this is using "too" when you meant "two". People can figure it out, but it doesn't make the use of it correct.
Comment: Again it doesn't show proper relationship. They are secondary chords so for the analysis to be complete it needs to show that function. ii/ii V7/ii ii givens more information than iii VI7 ii ever can.  It's easier for _transcription_ the way you are writing it, but that's not the point of Roman Numeral analysis. It's a functional analysis. I can garuntee you that if you showed iii VI7 ii to someone just learning the subject they would have no idea what it relates or that it's a ii V7 i progression to the supertonic.
Comment: So, in an effort to generalize, could I take most chords, and simply move a single note down or up (in a progression, perhaps)?
Comment: II7 is not incorrect, I've seen many discussions about this on this website, and most of the times it's agreed that II7 or V7/V are both correct.
Comment: For example, I have never seen Dm G Em A7 Dm G7 C written as ii V ii/II V7/II ii V7 I ??? iii VI7 is much more common right? Even though iii and IV work as a ii V of II.
Comment: Generally "Sherman and Sherman" are referrred to as "the Sherman Brothers" :)


Form API + Module: Nested default value variable_get doesnt behave the same as unnested variable_get

Question: Heres the example code:
function mymodule_form($form, &$form_state){
    $form['nest'] = array(
        '#type' => 'fieldset',
        '#title' => t('Nested settings'),
        '#tree' => TRUE,
    );

    $form['nest']['nested_example_item'] = array(
        '#type' => 'textfield',
        '#title' => t('Nested Example Item'),
        '#default_value' => variable_get('nested_example_item', 'example value 1'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description' => t('Nested Example Item'),
    );

    $form['unnested_example_item'] = array(
        '#type' => 'textfield',
        '#title' => t('Unnested Example Item'),
        '#default_value' => variable_get('unnested_example_item', 'example value 2'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description' => t('Unnested Example Item'),
    );

    return system_settings_form($form);    }

Now what happens when i change both values and submit the form is the following:

The unnested field behaves like expected - it reflects the changes.
The nested field item, does not show this behaviour, does not reflect the changes

I am confused, should I treat the nested variable_get differently?
Answer: I'm pretty sure system_settings_form() only looks for variables defined at the root of the $form_state['values'] array.
Since you have '#tree' => TRUE on your fieldset element this will not be the case. If you remove the '#tree' => TRUE' line, the value of your nested element will be saved in a variable called 'unnested_example_item' as you expect.


Remove focus when user presses ESC

Question: I'm using a select2 dropbox. One odd thing I notice, if it's open and the user presses ESC, the dropbox closes but stays in focus?
Ho to change that, such that it closes and loses focus when pressing ESC?
Answer: You can listen to select2-close event. When this event is fire you can remove "active" class.
$('.YOURCLASS').removeClass('select2-container-active');

Demo
Answer: If you don't mess with the controls behaviour you trust that the browser implementation got usability right.
This is the best advice to give, because based on platform (gnome/kde on linux, safari, mac, windows and so on) those rules may have slight differences. So best is, you don't be picky about how the default behaviour handles these cases and let it "do its thing", which is probably what users expect.
That said, what you can do to un-focus the drop-down list is one of these:
1) catch the ESC key and invoke blur() on the drop-down list;
-or-
2) catch the ESC key and invoke focus() on an element of your choice.

Remove focus when user presses ESC


create category and subcategory menu on the left sidebar

Question:
I need a category, subcategory and subbactegory based solution for
  example

<code>Project
    Web project
        Project 1
        Project 2
    Desktop project
        Project 1
        Project 2
</code>
Project 1 (when i click this then content appear on right side)
Project 2 (when i click this then content appear on right side)

Basically, when i click on the li page wouldn't be refresh. 1) i click
  on web project then menu expanded Project 1, project 2 appear and if i
  click on project 1 then content related to project 1 appear on the
  right side. Similarly for Project 2 and the subcategory for desktop
  project will be same means i can create subcategory related to desktop
  project.. Like in any category and product relation we need to select
  the category and add the product detail similarly in this
Answer:
Views Tree would be worth trying.
Toggling of leaf terms can be handled by javascript.
To show content, you can declare ajaxified menu callbacks, which simply takes tid as argument and replace a certain section of DOM with the server reponse.


como faço para puxar o resultado de uma coluna dentro de uma string no mysql

Question: exemplo :
select
    case
        when campo = 1 then 'existe o resultado='aqui eu colocaria o nome da coluna da tabela 'fim da string'
        else 0
    end
from banco.tabela;

como faria isso tem uma forma de concatenar?
Answer: Para concatenar no MySQL tem que usar a função CONCAT, ficaria assim:
SELECT
    CASE
        WHEN campo = 1 THEN CONCAT('existe o resultado=', banco.tabela.coluna, 'fim da string')
        ELSE 0
    END
FROM banco.tabela;

Veja mais sobre a função CONCAT aqui.


Morphism $f\colon X\to S$ is proper iff $f^{-1}(V_j)\to V_j$ is proper for some open cover $\{V_j\}$ of $S$? (Lemma 28.42.3 of Stacks Project)

Question: I was browsing the Stacks Project, and Lemma 28.42.3 says that a morphism $f\colon X\to S$ is a proper morphism if and only if there exists an open covering $S=\bigcup V_j$ such that $f^{-1}(V_j)\to V_j$ is proper for all $j$. However, the proof there is omitted.
Can anyone fill in this gap, or have a resource which explains it? Thanks.
Comment: Do you know how to prove this kind of thing for the properties of separated and finite type? Given that I think this statement really boils down to the property of being a closed set being local: you can check it on an open cover of the ambient space.
Answer: Let $\{V_j\to S\}$ be a Zariski cover of $S$.
If $f:X\to S$ is proper, then the base-change $f_j=f|_{f^{-1}V_j} : f^{-1} V_j = X \times_S V_j \to V_j$ is proper.
Conversely, assume that $f_j: f^{-1}V_j \to V_j$ is proper for all $j$. Then $f_j$ is finite type and separated. In particular, since finite type and separated are local in the Zariski topology, we conclude that $f$ is finite type separated. (This is what Hoot is advising you to look up how to prove.) Therefore, it remains to show that $f$ is universally closed. If $T\to S$ is a morphism, then $\{T\times_S V_j\to T\}$ is a Zariski cover and the pull-back of $f$ to $T\times_S V_j$ is proper by base-change. Thus, to show that $f$ is universally closed, it suffices to show that $f$ is closed. (The same argument will then apply to $f:X\times_S T \to T$.
So let us show that $f:X\to S$ is closed. Let $Z$ be a closed subset of $X$. Let $f(Z)$ be the image of $Z$ in $S$. To conclude, it suffices to show that $f(Z)$ is closed.
Note that $f(Z)\cap V_j$ is closed for all $j$. Therefore, by a small lemma in topology, we conclude that $f(Z)$ is closed in $S$. QED
Comment: This is a very pedagogical answer, Ariyan: bravo! (and +1, of course)
Comment: Dear @GeorgesElencwajg , thank you very much for your kind words. I have to say that I truly enjoy your many answers and questions on MSE and MO.  Best, Ariyan
Comment: Dear Ariyan, I have two questions:
1) When you say "and the pull-back of $f$ to $T\times_{S} V_{j}$ is proper by base-change", what cartesian square do you have in mind?
2) Could you clarify why in order to show that $f$ is universally-closed, it suffices to show that $f$ is closed?
I am basically having trouble to see this reduction step. The rest of your answer is perfectly clear to me. Thank you!


Como colocar a data e hora atual num campo do tipo datetime?

Question: Eu tenho um campo date em uma tabela que é do tipo datetime e quero lá colocar a data atual do meu servidor.

Já tentei de tudo, com NOW() no SQL de inserção, mas depois vi que não funciona. Já tentei alterar o DEFAULT do campo date para CURRENT_TIMESTAMP e nada.
No PHP já tentei com a função date, e gmdate,
date("Y-m-d H:i:s");
gmdate("Y-m-d H:i:s");

e continuo a ter 0000-00-00 00:00:00 na base de dados, isto quado tento inserir um registo na tabela.
Comment: @psantos tens razão foi só uma experiência. E já descobri o problema, estou a usar `mysqli_` e estava a usar o 'i' como tipo de parâmetro e tem de ser 's'.
Comment: Eu encontrei esse post: http://optimize-this.blogspot.com.br/2012/04/datetime-default-now-finally-available.html. O que fazemos geralmente é deixar o campo tipo `timestamp` e aí sim usar o `current_timestamp` ou `now()` como **default**.
Comment: @Zoom é `MySQL 5.1.73`. Pois mas eu queria que fosse `datetime`.
Comment: e se antes você setar date_default_timezone_set('America/Sao_Paulo'); o que acontece?
Comment: Já tentou definir seu campo assim? `date datetime NOT NULL DEFAULT NOW(),`
Comment: Qual a versão do seu MySQL ? Tente usar `Current_Date`.
Comment: @MarconcilioSouza `ERROR 1067: Invalid default value for 'date'`
Comment: @JorgeB. mostra a estrutura da sua tabela
Comment: @psantos está feito.
Comment: @JorgeB. primeira dica: mude o nome do campo `date` para `data` ou `my_date`. `date` é um tipo para MySQL logo haverá confusão
Answer: Bem, não sei se é exactamente isso isso que eu entendi. Suponhamos que tens a seguinte tabela:
CREATE TABLE `test`.`tasks` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `created_at` DATETIME NULL,
    PRIMARY KEY (`id`)
);

Para inserir um registo com a data actual do servidor, basta o seguinte comando:
INSERT INTO tasks (created_at) VALUES (now());

mysql> select * from tasks;
  +----+---------------------+
  | id | created_at          |
  +----+---------------------+
  |  1 | 2016-01-19 11:49:58 |
  +----+---------------------+
  1 row in set (0.00 sec)

Usando o PHP (com PDO), basta fazer o seguinte:
<?php

// algo mais ou menos como: 2016-01-19 11:56:30
$data_actual = date('Y-m-d H:i:s');

$sql = "INSET INTO tasks(created_at) VALUES (:created_at)";
$stmt = $pdo->prepare($sql);

$stmt->bindParam(':created_at', $data_actual);
$stmt->execute();

UPDATE:
Nota: Pelo erro, estás a tentar adicionar um valor do tipo datetime num campo do tipo date
UPDATE 2:
Pela estrutura da tabela, o campo no nome date está ou poderá causar problemas.
Mude o nome deste campo. Pois date é usado como um tipo de dados do MySQL (http://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html).
Depois de fazeres esta actualização, podes fazer o insert desta forma:
INSERT INTO tasks (created_at) VALUES (now());


Space of Non-Surjective maps between Spheres

Question: Let $\text{Map}_{ns}(S^n,S^n)$ denote the space of all continuous, non-surjective maps from $S^n$ to $S^n$ carrying the compact-open topology. There is the following fibration:$$
\text{Map}_{ns}((S^n,N),(S^n,N))\to \text{Map}_{ns}(S^n,S^n)\to S^n
$$
where the last map is evaluation at the north pole $N$ and $\text{Map}_{ns}((S^n,N),(S^n,N))$ is the subspace of pointed non-surjective maps.
My question is wether evaluation at the north pole is a (weak) homotopy equivalence or in other words wether $\text{Map}_{ns}((S^n,N),(S^n,N))$ is (weakly) contractible. It might also be interesting wether it makes a difference if one restricts to smooth maps (I'm a bit hesistant to just cite smooth approximation in this case).
Comment: @Tyrone There are surjective maps that are nullhomotopic. For example project the sphere onto a disk and map the disk surjectively to the sphere
Comment: An element of $\pi_k$ consists of a map $S^{k+n}\to S^n$ for which none of the "equators" $S^n\to S^{k+n}\to S^n$ is surjective, up to homotopy(with a nonsurjectivity condition too); so you're looking at something related to $\pi_{n+k}(S^n)$ : the question might be difficult. Of course, any nonsurjective map is contractible so $\pi_0$ is trivial, but as soon as you start looking at $\pi_1$, you have stuff like $S^3\to S^2$, where there is the Hopf fibration (which does not, itself, satisfy the nonsurjectivity condition)
Comment: Is it obvious this is actually a fibration?
Comment: You can use the action of $O(n) $ on both spaces to show that it is a fiber bundle I think.
Comment: Is it true that $S^n\rightarrow S^n$ is null-homotopic if and only if it is non-surjective? (One direction is clear). if so then $Map_{ns}(S^n,S^n)$ is simply the path-component of the constant map in $Map(S^n,S^n)$. The pointed version of this is the path-component of the constant map in the loop space $Map_*(S^n,S^n)=\Omega^nS^n$. Note that all path components of $\Omega^nS^n$ have the same homotopy type, and in particular are non-trivial when $n>1$.
Answer: Smooth approximation does indeed show that the homotopy type doesn't depend on smoothness. The point is that the set of surjective maps is closed by compactness, and so given any compact family $f: X \times S^n \to S^n$ of non-surjective maps, the infimum $$D = \inf_x d(f_x, \text{Map}_{\text{surj}})$$ is strictly positive. Here distance is measured in $C^0$.
Because you can apply smooth approximation to any compact family while changing the $C^0$ norm by an arbitrarily small amount, you can in fact smoothly approximate while moving the whole family by $C^0$ norm less than $D$, so that you can't reach a surjective map by such a small perturbation.
The actual question you ask strikes me as hard but I bet it is false for $n > 1$. It strikes me that it is probably equivalent to whether or not there is a continuous map $r: \text{Map}^*_{ns}(S^n, S^n) \to S^n$ (the domain being pointed non-surj maps) with $$r(f) \not \in \text{Im}(f).$$ I do not have an idea for constructing that map.
Comment: It's not clear to me that the original question is equivalent to the existence of $r$ (but I agree having $r$ answers the question affirmatively.)  On the other hand, here is a sketch of a proof that there is no such $r$.  Start with a non-surjective $f$ defined as follows.  Surjectively map $S^n$ onto a rectangle, then wrap the rectangle around the equator in such a way that the image is $S^n$ without the two poles, $n$ and $s$.  Then $r(f)=n$ without loss of generality.  Now, create a homotopy $F$ of $f$ for which $F(\cdot, t)$ surjects onto $S^n\setminus\{s\}$ for all $t > 0$.  Then ....
Comment: $r(F(\cdot, t)) = \begin{cases} n & t = 0\\ s & t > 0\end{cases}$.  This is clearly not continuous.


Ramified primes, as defined by Neukirch

Question: In ch. I, §8, p. 49 of the English translation of $\textit{Algebraic Number Theory}$, Neukirch states the following (I paraphrase, but retain his notation):
Let $L/K$ be an extension of number fields, and let $\mathcal{O}$ and $\mathcal{o}$ be their respective rings of integers.
Then every prime ideal $\mathfrak{p} \subset \mathcal{o}$ possesses a unique factorisation
$$\mathfrak{p} = \mathfrak{P}_1^{e_1}...\mathfrak{P}_1^{e_1}$$
where the $\mathfrak{P}_i$ are prime ideals in $\mathcal{O}$.
He then says that the prime ideal $\mathfrak{P}_i$ in the above factorisation is said to be $\textbf{unramified}$ over $K$ if $e_i = 1$ ($\textit{i.e.}$ if the prime only appears once in the factorisation) $\underline{\textit{and}}$ the residue field extension $(\mathcal{O}/\mathfrak{P}_i)/(\mathcal{o}/\mathfrak{p})$ is separable.
But $(\mathcal{O}/\mathfrak{P}_i)/(\mathcal{o}/\mathfrak{p})$ is a finite extension of finite fields, so will it not always be separable? Why is this included in the definition?
Below I have included the excerpt from the book I am referring to.

Thank you for your attention.
$\textbf{Addendum:}$ In response to the comments below, include two more excerpts from ch. I, §9, p. 58 and p. 59 respectively.
From p. 58:

From p. 59:

I should explain that his notation is $\kappa(\mathfrak{P}) := \mathcal{O}/\mathfrak{P}$ and $\kappa(\mathfrak{p}) := \mathcal{o}/\mathfrak{p}$.
Now if the assumption was only included for formal reasons (because he did not want to assume that finite fields are perfect), then why would he repeatedly refer to the separability of the residue field extension as a "special case"?
Comment: It's also possible he wrote it out of habit, and kind of momentarily forgot it was automatic for number fields.
Comment: There are examples of (things also called) ramification in some other contexts for which separability is nontrivial, but it is automatic for the case here. Maybe Neukirch didn't want to assume the result that finite fields are perfect? (I don't have my copy at hand to check, but it would seem like he uses enough Galois theory to prove or assume that, though.)
Comment: @anomaly That sounds plausible, but then why would he repeatedly refer to it as a "special case"? See the bit added above.
Answer: I took a look at the corresponding section in the book. Although the end goal is of course to apply all this to number fields, this is actually not the assumption in that section. Neukirch works at the level of generality of Dedekind domain, not rings of integers of number fields. And in that more general case, the residue fields don't have to be finite, and the inertia extension does not have to be separable.
Answer: Given your interest in L-functions you should look at the finite extensions of the $p$-adic integers $\Bbb{Z}_p$. The main point is Hensel lemma: if $f\in \Bbb{Z}_p[x]$ and $f(a)=0\bmod p,f'(a)\ne 0\bmod p$ then there is $b\in \Bbb{Z}_p$ such that $b=a\bmod p, f(b)=0$. This is what makes $p$-adic fields much simpler than $\Bbb{Q}$, because we can use this to classify all the extensions and connect some apparently very different fields. In the general setting we replace $\Bbb{Z}_p$ by $\varprojlim O/\mathfrak{p}^n$ where $\mathfrak{p}$ is a non-zero invertible prime ideal of $O$ (corresponding to a discrete valuation). The unramified condition is what we need to ensure the extension is generated by the lift of some roots of separable polynomials $\bmod \mathfrak{p}$. And we can understand $O$ by looking at $\varprojlim O/\mathfrak{p}^n$ for each prime ideal.
Answer: In number fields there is a basic theorem that the ramified primes are the prime factors of the discriminant (prime ideal factors if the base field is bigger than $\mathbf Q$).  If you extend this result to a finite extension of fraction fields of Dedekind domains, where residue fields are no longer automatically finite (really, no longer automatically perfect) then you discover that the prime factors of the discriminant ideal are the primes downstairs whose prime factorization upstairs has all exponents equal to $1$ and where the residue field extensions at all primes upstairs are separable. That is the simplest reason to define unramified primes in a general setting (not just number fields) to include the peculiar extra property of separable residue field extensions.

Ramified primes, as defined by Neukirch


Sorting a file manager array by file type

Question: I am creating a file manager for my users, it's pretty basic right now and lists every folder and file within their directory.
<?PHP
  function getFileList($dir)
  {
    // array to hold return value
    $retval = array();

    // add trailing slash if missing
    if(substr($dir, -1) != "/") $dir .= "/";

    // open pointer to directory and read list of files
    $d = @dir($dir) or die("getFileList: Failed opening directory $dir for reading");
    while(false !== ($entry = $d->read())) {
      // skip hidden files
      if($entry[0] == ".") continue;
      if(is_dir("$dir$entry")) {
        $retval[] = array(
          "name" => "$dir$entry/",
          "type" => filetype("$dir$entry"),
          "size" => 0,
          "lastmod" => filemtime("$dir$entry")
        );
      } elseif(is_readable("$dir$entry")) {
        $retval[] = array(
          "name" => "$dir$entry",
          "type" => mime_content_type("$dir$entry"),
          "size" => filesize("$dir$entry"),
          "lastmod" => filemtime("$dir$entry")
        );
      }
    }
    $d->close();

    return $retval;
  }
?>

It then echos this information in to a responsive table:

                                            Select
                                            Filename
                                            Type
                                            Last Modified
                                            Size
                                            Actions

                                    <?
 $dirlist = getFileList("../test/".$ref."");
  // output file list in HTML TABLE format
  foreach($dirlist as $file) {
      $files = $file['name'];
      $tmp = explode('../test/'.$ref.'/', $files);
      $filename = end($tmp);
      $filenames = rtrim($filename, '/');
  ?>

                                            <input type="checkbox" name="test" value="test">
                                            <a href="<? if($file['type'] == 'dir'){ echo 'user_filemanager.php?ref='.$ref.'/'.$filenames.''; } else { echo 'http://mysite.co.uk/test/'.$ref.'/'.$filenames.''; } ?>"><? echo $filenames; ?>
                                            <? echo $file['type']; ?>
                                            <? echo date('r', $file['lastmod']) ?>
                                            <? echo $file['size']; ?>
                                            X

  <?
  }
  ?>

The issue I have is it outputs the data at random. I would like for it to display all Directories FIRST. Before listing files. So all directories are on top. Is this possible? Directories currently display as dir from $file['type'];
Comment: So sort result array before output. With `usort` for example.
Comment: I've looked it up but not found an example of how I would use it for this type of thing ?
Answer: Simple example of usort in your case is:
function getFileList($dir)
{
    // code here

    // sort by `type` key:
    usort($retval, function($a, $b) { return $a['type'] == 'dir'? -1 : 1; });

    return $retval;
}


What is the rank of matrix $A\in \mathbb{R}^m\times \mathbb{R}^n$ with entries $a_{i,j} = i + j$?

Question: I've been sitting on this practice question for a while but haven't been able to make any progress. Thanks in advance for any help.
Below is an $n \times m$ matrix over $\mathbb{R}$:
$$A= \begin{bmatrix}a_{1,1}& \dots &a_{1,n}\\
\vdots & \ddots & \vdots \\
a_{m,1}&...&a_{m,n}\end{bmatrix} \text{with} \ a_{i,j} = i + j  \ \text{for all} \ i \in {1,..m}, \  j\in{1,...n}.$$
Determine the row and column rank of the matrix $A$ for any $n,m > 0$.
How do I go about this question?
I know the rank of a matrix is the number of linearly independent rows or columns, but I don't really know how to apply that to this matrix.
P.S: please excuse my poor formatting.
Comment: Hint: the matrix does have number entries: $i$ and $j$ are always numbers. Write down the matrix for some small values of $n,m$ and compute their ranks explicitly.
Comment: Not sure what you mean when you say that the matrix has "non-number entries".  For instance, in the $3 \times 3$ case, we have
$$
A =  \pmatrix{2&3&4\\3&4&5\\4&5&6}
$$
Comment: I think I am to determine the rank for any matrix of the form, not for specific entries..That's what I mean.
Comment: Suppose that $V_i$ denote the $i$th row of matrix $A$, then
all the rows of matrix $A$ are spanned by vectors
$V_1=\langle2,3,4,\ldots,n+1\rangle$
and
$
U=\langle1,1,1\ldots,1\rangle.
$
because we have $V_i=V_1+iU$.

It is clear that $\dim (V_1,U)=2$, so the rank of matrix $A$ is $2$. This is the nice answer of user @Jyrki to [my question](https://math.stackexchange.com/questions/2317712/the-vectors-langle-1i-2i-dots-n-1i-ni-rangle-for-0-leq-i-leq-n-1-are/2317757#2317757)
Answer: Hint: Subtracting any two consecutive rows gives you the vector $(1,1,\dots,1)$. Conclude that the rank of the matrix is at most $2$.


Estimating a linear function mapping from n-dim to 1-dim

Question: I'm coming from a computer science domain with an estimation problem that I'm trying to address. My background isn't statistics, so I apologize if the terminology is bad.
I've been reading various topics related to model estimation, but the area seems enormous. So, I'll describe the problem below, and it would be extremely helpful to get pointers to specific areas that are relevant to avoid wading through dozens more wikipedia pages :).

Consider a $d$-dimensional space $S$ with dimensions $N_1 \times N_2 \times \dots \times N_d$. Any point $s \in S$ is specified by a tuple $(n_1, n_2, \dots, n_d)$ with $d$ zero-based indices $n_k \in [0, N_k-1]$.
There exists a 1-1 function $f: S \rightarrow \mathbb{N}$ that maps a multi-dimensional point in $S$ to a single natural number.
The problem I am trying to approach is related to estimating $f$, that is: given $S$, the range of $f(S)$, and $p \in f(S)$, estimate the point $s \in S$ such that $f(s)=p$.
(edit): I forgot to mention: The space can be probed to construct a training set. That is, training data can be acquired by evaluating $f(s)$. However, computing $f(s)$ is very expensive, so the goal is to estimate $f$ with as few evaluations as possible.

So, in the end the goal is to estimate the inverse of $f$. There are some assumptions about $f$, perhaps the most important is that it is linear. There are other properties, too, if they might be relevant please ask.
Thanks!
Noah
Comment: I think there may be some typos here as well as some ambiguous terminology: (1) you use "dimension" in two different senses within the very same statement (#1).  (2) In statement 3 it looks like you want to estimate $f^{-1}$, not $f$.  As far as properties of $f$ go, is there any possibility that $f(s)$ can be *incorrectly* evaluated?  If not, this is not a statistical problem and it has a mathematical answer that is trivial to obtain.  If so, what can you tell us about the nature of these errors?
Comment: might be helpful: http://www.models.kvl.dk/~pih/parafac/chap2parafac.htm
Answer: One relevant area is principal components analysis.  It only applies if $f$ is linear, but from what you say this is the case.  The first principal component might be just what you want.
@whuber asks good questions in his comments.  You need to think through at some point what statistical variation there is in $S$ and how to incorporate that into your model when you look at different candidates for $f$, but I suspect something along the lines of PCA and the literature around it will get you in the right direction.


JavaScript to check if PHP session exists

Question:

it doesn't work  why ?
Comment: Javascript is not PHP ?
Answer: You can use a mix of JavaScript and PHP:

PHP pre-proccesses HTML meaning it runs before anything else. PHP will replace anything in <?php ?> with what it prints.
I'm using isset because you need that to check if a variables exists/is defined.
Comment: @Devin You can use vihan1086's method, but you have to remove session_start() from its code and place it in the first row of your file. You can not start a session after printing headers and body in stdout with a standard PHP configuration. Sessions have to be started before sending headers.
Comment: i have tried the top 2 suggestions and neither works :(
Comment: You started `session` after `character  echo`  it's not TRUE.
Comment: i have php file that creates the session and another php file that shows that the session was created however i cant check if that session exist
Answer: You can just use the variable contain like this:
if (!<?php echo $_SESSION['kool']; ?>) {
  alert("session")
} else {
  alert('work')
  location.href = 'lol.html';
}

Comment: Can help me more??? What is the error?
Comment: i have tried the top 2 suggestions and neither works :(


É possivel restringir acesso a informações de variáveis com AngularJs?

Question: Olá,
Sou novo em desenvolvimento e gostaria de saber se existe alguma maneira de ocultar informações de variáveis no AngularJs  , estou usando uma API do MongoLab e não queria deixar minha apiKey visível para qualquer pessoa que debugar o código no navegador, estou rodando a aplicação com NodeJs e ExpressJs , o codigo do server foi gerado através do ExpressJS CLI dessa maneira: npm install express-generator -g e logo em seguida express meuApp.
Segue código do controller:
app.controller("RBScontroller", function ($scope, $http) {

$scope.enviar = function enviar(){

    var ApiMongo = 'https://api.mongolab.com/api/1/databases/db_test/collections/users?apiKey=Chave_da_APi';  //Gostaria de esconder essa informação
    $scope.users = [];
    $scope.loading = true;

    $http.get(ApiMongo).success(function(data) {
        console.log(data);
        $scope.users = data;
        $scope.loading = false;

    }).error(function(msg) {

        angular.element($(function(){alert("Fail")}));
        $scope.loading = false;
    });
 }
});

Answer: A resposta simples é não, não há maneira de ocultar do lado do cliente. E, ainda que existisse, a URL chamada poderia ser interceptada (via debug tools).
Entretanto, você pode utilizar uma abordagem diferente. Ao invés de realizar a chamada via Angular, utilize uma função via http.request no NodeJS, e retorne o resultado para a sua aplicação.
Comment: Valeu cara , vou pesquisar então como faz isso no NodeJS! ;)
Comment: Ah, você já tinha respondido isso aí. A leitura dinâmica me impossibilitou de ver o trecho do `http.request`. +1
Answer: Amigo, não existe maneira de fazer isso através do javascript.
A única coisa que pode ser feita - e é o que eu faria se tivesse que esconder essa informação - é fazer um proxying.
Traduzindo, você vai mandar a informação para o seu servidor, e seu servidor por sua vez fará a requisição que você precisa - ao invés de fazer diretamente.
Exemplificando com PHP
#requisicao.php

$conteudo = file_get_contents('https://api.mongolab.com/api/1/databases/db_test/collections/users?apiKey=Chave_da_APi');

return Response::json($conteudo);

Javascript:
$scope.enviar = function enviar(){

    var ApiMongo = 'requisicao.php'; // A informação só é vista pelo programador que acessar requisicao.php
    $scope.users = [];
    $scope.loading = true;

    $http.get(ApiMongo).success(function(data) {
        console.log(data);
        $scope.users = data;
        $scope.loading = false;

    }).error(function(msg) {

        angular.element($(function(){alert("Fail")}));
        $scope.loading = false;
    });
 }
});

No caso, como você está usando node.js do lado do servidor, creio que você poderia fazer isso.
Comment: +1, descrição mais elaborada. =)
Comment: Valeu Wallace, com node não sei como faz , acho que vou ter que usar alguma outra linguagem então, esse exemplo que você mostrou me parece simples de fazer , vou tentar! ;)
Comment: Que isso, rapaz? como não sabe? O @OnoSendai deu a dica: use `http.request` para capturar as informações