问:
Faulty avltree implementation c++
this is my current avltree implementation, avltree.h:

```<code>#pragma once
#include <math.h>
#include <algorithm>
#include <iostream>
namespace avltree {

    template <class T>
    struct node {
        static node * null_node;
        node *left = null_node;
        node *right = null_node;
        node *parent = null_node;
        int height = 0;
        T value;
        node(T value) :value(value) {}
        node(T value, int height) :height(height), value(value) {}
    };
    template <class T>
    node<T>* node<T>::null_node = new node(0, -1);

    template <class T>
    struct avltree {
    public:
        node<T> *root;
        avltree(T value);
        node<T> *insert(T value);
        void print(void);
        void print_with_height(void);
    private:
        node<T> *insert(T value, node<T> *x);
        node<T> *left_rotate(node<T> *x);
        node<T> *right_rotate(node<T> *x);
        void retrace(node<T> *n);
        void update_root();
        void print(node<T> *n);
        void print(node<T> *n, int depth);
        void update_height(node<T> *n);
    };
    template <class T>
    avltree<T>::avltree(T value) :root(new node<T>(value)) { }

    template <class T>
    node<T> *avltree<T>::insert(T value) {
        auto n = insert(value, root);
        update_root();
        return n;
    }
    template <class T>
    void avltree<T>::retrace(node<T> *n) {
        while (n != node<T>::null_node) {
            update_height(n);
            if (n->left->height - n->right->height > 1) {
                if (n->left->left->height >= n->left->right->height) {
                    right_rotate(n);
                }
                else {
                    left_rotate(n);
                    right_rotate(n);
                }
            }
            else
                if (n->right->height - n->left->height > 1) {
                    if (n->right->right->height >= n->right->left->height) {
                        left_rotate(n);
                    }
                    else {
                        right_rotate(n);
                        left_rotate(n);
                    }
            }
            n = n->parent;
        }
    }
    template <class T>
    node<T> *avltree<T>::insert(T value, node<T> *n) {
        if (n->value > value) {
            if (n->left != node<T>::null_node) {
                n->left->height++;
                insert(value, n->left);
            }
            else {
                auto new_node = new node<T>(value);
                n->left = new_node;
                new_node->parent = n;
                retrace(n);
                return new_node;
            }
        }
        if (n->value < value) {
            if (n->right != node<T>::null_node) {
                n->right->height++;
                insert(value, n->right);
            }
            else {
                auto new_node = new node<T>(value);
                n->right = new_node;
                new_node->parent = n;
                retrace(n);
                return new_node;
            }
        }
        update_height(n);
        return n;
    }
    template <class T>
    node<T> *avltree<T>::left_rotate(node<T> *x) {
        node<T> *y = x->right;
        if (y == node<T>::null_node) {
            return node<T>::null_node;
        }
        y->parent = x->parent;
        if (x->parent->right == x) {
            x->parent->right = y;
        }
        else {
            x->parent->left = y;
        }

        y->left = x;
        x->parent = y;

        x->right = y->left;
        x->right->parent = x;

        update_height(x);
        update_height(y);

        return x;
    }
    template <class T>
    node<T> *avltree<T>::right_rotate(node<T> *x) {
        node<T> *y = x->left;
        if (y == node<T>::null_node) {
            return node<T>::null_node;
        }
        y->parent = x->parent;
        if (x->parent->right == x) {
            x->parent->right = y;
        }
        else {
            x->parent->left = y;
        }

        y->right = x;
        x->parent = y;

        x->left = y->right;
        x->left->parent = x;

        update_height(x);
        update_height(y);

        return x;
    }
    template <class T>
    void avltree<T>::update_root() {
        auto n = root, last = root;
        while (n != node<T>::null_node) {
            last = n;
            n = n->parent;
        }
        root = last;
    }
    template <class T>
    void avltree<T>::print(void) {
        print(root);
        cout << endl;
    }
    template <class T>
    void avltree<T>::print(node<T> *n) {
        if (n->left != node<T>::null_node) {
            print(n->left);
        }
        cout << n->value << " ";
        if (n->right != node<T>::null_node) {
            print(n->right);
        }
    }
    template <class T>
    void avltree<T>::print(node<T> *n, int height) {
        if (n->left != node<T>::null_node) {
            print(n->left, height);
        }
        if (n->height == height) {
            std::cout << n->value << ", ";
        }
        if (n->right != node<T>::null_node) {
            print(n->right, height);
        }
    }
    template <class T>
    void avltree<T>::print_with_height(void) {
        int height = root->height;
        for (int height = root->height; height >= 0; height--) {
            std::cout << "height = " << height << "\t:";
            print(root, height);
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    template <class T>
    void avltree<T>::update_height(node<T> *n) {
        n->height = std::max(n->left->height, n->right->height) + 1;
    }
}
</code>```

And the following is main file:

```<code>#include "stdafx.h"
#include "avltree.h"

int main()
{
    avltree::avltree<int> tree(1);
    for (int i = 2; i < 128; i++) {
        tree.insert(i);
    }
    tree.print_with_height();

    return 0;
}
</code>```

The problem with above code is that at iteration 124 it will generate an infinite loop inside retrace call in insert. Basically, the nodes will keep being rotated in such a way that root node cannot be reached (resulting in an infinite loop). I have checked the trivial examples (for a few nodes) and they work. Everything for a run is provided, I would appreciate if someone with experience in avltrees could take their time and run this program, perhaps finding out what goes wrong inside retrace/rotations.

答:
Getting an infinite loop like that indicates a likely problem with your rotate functions.  A quick look at left_rotate shows

```<code>    y->left = x;
    x->parent = y;

    x->right = y->left;
</code>```

What is y->left in that last assignment?  x, so what you're really is x->right = x.  This is clearly a problem that needs to be fixed.

A similar problem exists in right_rotate.

Title: Faulty avltree implementation c++

Body:
this is my current avltree implementation, avltree.h:

#pragma once
#include <math.h>
#include <algorithm>
#include <iostream>
namespace avltree {

    template <class T>
    struct node {
        static node * null_node;
        node *left = null_node;
        node *right = null_node;
        node *parent = null_node;
        int height = 0;
        T value;
        node(T value) :value(value) {}
        node(T value, int height) :height(height), value(value) {}
    };
    template <class T>
    node<T>* node<T>::null_node = new node(0, -1);

    template <class T>
    struct avltree {
    public:
        node<T> *root;
        avltree(T value);
        node<T> *insert(T value);
        void print(void);
        void print_with_height(void);
    private:
        node<T> *insert(T value, node<T> *x);
        node<T> *left_rotate(node<T> *x);
        node<T> *right_rotate(node<T> *x);
        void retrace(node<T> *n);
        void update_root();
        void print(node<T> *n);
        void print(node<T> *n, int depth);
        void update_height(node<T> *n);
    };
    template <class T>
    avltree<T>::avltree(T value) :root(new node<T>(value)) { }

    template <class T>
    node<T> *avltree<T>::insert(T value) {
        auto n = insert(value, root);
        update_root();
        return n;
    }
    template <class T>
    void avltree<T>::retrace(node<T> *n) {
        while (n != node<T>::null_node) {
            update_height(n);
            if (n->left->height - n->right->height > 1) {
                if (n->left->left->height >= n->left->right->height) {
                    right_rotate(n);
                }
                else {
                    left_rotate(n);
                    right_rotate(n);
                }
            }
            else
                if (n->right->height - n->left->height > 1) {
                    if (n->right->right->height >= n->right->left->height) {
                        left_rotate(n);
                    }
                    else {
                        right_rotate(n);
                        left_rotate(n);
                    }
            }
            n = n->parent;
        }
    }
    template <class T>
    node<T> *avltree<T>::insert(T value, node<T> *n) {
        if (n->value > value) {
            if (n->left != node<T>::null_node) {
                n->left->height++;
                insert(value, n->left);
            }
            else {
                auto new_node = new node<T>(value);
                n->left = new_node;
                new_node->parent = n;
                retrace(n);
                return new_node;
            }
        }
        if (n->value < value) {
            if (n->right != node<T>::null_node) {
                n->right->height++;
                insert(value, n->right);
            }
            else {
                auto new_node = new node<T>(value);
                n->right = new_node;
                new_node->parent = n;
                retrace(n);
                return new_node;
            }
        }
        update_height(n);
        return n;
    }
    template <class T>
    node<T> *avltree<T>::left_rotate(node<T> *x) {
        node<T> *y = x->right;
        if (y == node<T>::null_node) {
            return node<T>::null_node;
        }
        y->parent = x->parent;
        if (x->parent->right == x) {
            x->parent->right = y;
        }
        else {
            x->parent->left = y;
        }

        y->left = x;
        x->parent = y;

        x->right = y->left;
        x->right->parent = x;

        update_height(x);
        update_height(y);

        return x;
    }
    template <class T>
    node<T> *avltree<T>::right_rotate(node<T> *x) {
        node<T> *y = x->left;
        if (y == node<T>::null_node) {
            return node<T>::null_node;
        }
        y->parent = x->parent;
        if (x->parent->right == x) {
            x->parent->right = y;
        }
        else {
            x->parent->left = y;
        }

        y->right = x;
        x->parent = y;

        x->left = y->right;
        x->left->parent = x;

        update_height(x);
        update_height(y);

        return x;
    }
    template <class T>
    void avltree<T>::update_root() {
        auto n = root, last = root;
        while (n != node<T>::null_node) {
            last = n;
            n = n->parent;
        }
        root = last;
    }
    template <class T>
    void avltree<T>::print(void) {
        print(root);
        cout << endl;
    }
    template <class T>
    void avltree<T>::print(node<T> *n) {
        if (n->left != node<T>::null_node) {
            print(n->left);
        }
        cout << n->value << " ";
        if (n->right != node<T>::null_node) {
            print(n->right);
        }
    }
    template <class T>
    void avltree<T>::print(node<T> *n, int height) {
        if (n->left != node<T>::null_node) {
            print(n->left, height);
        }
        if (n->height == height) {
            std::cout << n->value << ", ";
        }
        if (n->right != node<T>::null_node) {
            print(n->right, height);
        }
    }
    template <class T>
    void avltree<T>::print_with_height(void) {
        int height = root->height;
        for (int height = root->height; height >= 0; height--) {
            std::cout << "height = " << height << "\t:";
            print(root, height);
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    template <class T>
    void avltree<T>::update_height(node<T> *n) {
        n->height = std::max(n->left->height, n->right->height) + 1;
    }
}

And the following is main file:

#include "stdafx.h"
#include "avltree.h"

int main()
{
    avltree::avltree<int> tree(1);
    for (int i = 2; i < 128; i++) {
        tree.insert(i);
    }
    tree.print_with_height();

    return 0;
}

The problem with above code is that at iteration 124 it will generate an infinite loop inside retrace call in insert. Basically, the nodes will keep being rotated in such a way that root node cannot be reached (resulting in an infinite loop). I have checked the trivial examples (for a few nodes) and they work. Everything for a run is provided, I would appreciate if someone with experience in avltrees could take their time and run this program, perhaps finding out what goes wrong inside retrace/rotations.

Body:
Getting an infinite loop like that indicates a likely problem with your rotate functions.  A quick look at left_rotate shows

    y->left = x;
    x->parent = y;

    x->right = y->left;

What is y->left in that last assignment?  x, so what you're really is x->right = x.  This is clearly a problem that needs to be fixed.

A similar problem exists in right_rotate.


来源: stackexchange

问:
Ruby on Rails: Get nested modules?
In my Rails project I want to get all modules that are nested inside the module A.

The file lib/assets/a/b.rb, consists of:

```<code>module A
  module B
  end
end
</code>```

In the Rails console:

```<code>A.constants
  => []
A::B.class
  => Module
A.constants
  => [:B]
</code>```

Why is the first line returning an empty array, and how do I get round the problem?

答:
That's because how Rails autoloading works.

When you call A.constants Rails find A in the a.rb file and get you the constants defined there. As it seems you didn't define any constant there, it is the empty array.

When you call A::B.class Rails autoloading looks for A::B and load a/b.rb. So, next time you call A.constants it returns the constants defined in both a.rb and a/b.rb, as both files are now loaded. And that's why it returns B the second time.

So, you can not solve the problem. This is expected as it is caused by how the Rails autoloading works.

Also, you say that your models are in lib/assets/, but this makes no difference, as it would be the same if they were in models/.

ContentLicense: CC BY-SA 3.0

Title: Ruby on Rails: Get nested modules?

Body:
In my Rails project I want to get all modules that are nested inside the module A.

The file lib/assets/a/b.rb, consists of:

module A
  module B
  end
end

In the Rails console:

A.constants
  => []
A::B.class
  => Module
A.constants
  => [:B]

Why is the first line returning an empty array, and how do I get round the problem?


问:
How to solve SyntaxError on autogenerated manage.py?
I'm following the Django tutorial https://docs.djangoproject.com/es/1.10/intro/tutorial01/

I've created a "mysite" dummy project (my very first one) and try to test it without altering it.

```<code>django-admin startproject mysite
cd mysite
python manage.py runserver

File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax
</code>```

I'm getting a SyntaxError on a file that was generated by the system itself. And I seem unable to find anyone else who has gone through the same issue.

I'll add some data of my setup in case it may be of use

```<code>$ vpython --version
Python 2.7.12
$ pip --version
pip 9.0.1 from /home/frank/.local/lib/python2.7/site-packages (python 2.7)
$ python -m django --version
1.10.6
</code>```

Adding contents of autogenerated manage.py

```<code>cat manage.py
#!/usr/bin/env python3
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)
</code>```

答:
Also, the tutorial recommends that a virtual environment is used (see Django documentation: https://docs.djangoproject.com/en/2.0/topics/install/#installing-official-release"). You can do this with pipenv --three. Once you've installed django with pipenv install django and activated your virtual environment with pipenv shell, python will refer to python3 when executing python manage.py runserver.

Pipenv documentation:
https://pipenv.kennethreitz.org/

ContentLicense: CC BY-SA 4.0

Body:
I'm following the Django tutorial https://docs.djangoproject.com/es/1.10/intro/tutorial01/

I've created a "mysite" dummy project (my very first one) and try to test it without altering it.

django-admin startproject mysite
cd mysite
python manage.py runserver

File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

I'm getting a SyntaxError on a file that was generated by the system itself. And I seem unable to find anyone else who has gone through the same issue.

I'll add some data of my setup in case it may be of use

$ vpython --version
Python 2.7.12
$ pip --version
pip 9.0.1 from /home/frank/.local/lib/python2.7/site-packages (python 2.7)
$ python -m django --version
1.10.6

Adding contents of autogenerated manage.py

cat manage.py
#!/usr/bin/env python3
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


问:
Git LFS file not shown
While, submitting my pull request on github I saw some of the images are displaying the message Git LFS file is not shown and I'm having all the images in my working branch.What does that mean?</p>

答:
I suspect this problem maybe related your github settings for Git LFS.
Could you double check that it's enabled?
How to check Git Large File Storage Configuration

These are the actual instructions on the link.

Sign in to your GitHub Enterprise instance at http(s)://[hostname]/login.

Rocketship icon for accessing site admin settingsIn the upper-right corner of any page, click the Rocketship icon.

Site admin settings search fieldIn the search field, type the name of the repository and click Search.

Site admin settings search optionsIn the search results, click the name of the repository.

Admin ToolsIn the upper-right corner of the page, click  Admin.

Admin ToolsIn the left sidebar, click Admin.

Disable buttonIn the Git LFS section, click Enable or Disable.

Title: Git LFS file not shown


问:
always execute the last statement in java
when i run the code, its always execute the last statement (admin) although if i enter correct/incorrect userid or password for different role position, only open the admin.java , can't open others statement</p>

```<code>Scanner input1 = new Scanner(System.in);
System.out.println("User ID : ");
String salesid = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Password : ");
String salespass = input2.next();

String smposition = "SM";
String pmposition = "PM";
String adposition = "AD";
{
    try
    {
        String line;
        File f = new File("UserDetails.txt");
        input1 = new Scanner(f);
        while(input1.hasNextLine())
        {
            String Line = input1.nextLine();
            String[] Seperator = Line.split(",");

            if(salesid.equals(Seperator[0]) && salespass.equals(Seperator[3]) && smposition.equals(Seperator[2]) || pmposition.equals(Seperator[2]) || adposition.equals(Seperator[2]))
            {
                if (smposition.equals(Seperator[2]))
                {
                    System.out.println("login successfull");
                    salesmanager ss = new salesmanager();
                    ss.sale();
                }
                else if(pmposition.equals(Seperator[2]))
                {
                    System.out.println("login successfull");
                    purchasemanager pm = new purchasemanager();
                    pm.purchase();
                }
                else if(adposition.equals(Seperator[2]))
                {
                    System.out.println("login successfull");
                    admin ad = new admin();
                    ad.adm();
                }
            }
        }
    }
    catch(IOException e)
    {
    }
}
</code>```

答:
Change your if condition to

```<code>if(salesid.equals(Seperator[0]) && salespass.equals(Seperator[3]) && (smposition.equals(Seperator[2]) || pmposition.equals(Seperator[2]) || adposition.equals(Seperator[2])))
</code>```

Note the extra parentheses around the || conditions.

Body:
when i run the code, its always execute the last statement (admin) although if i enter correct/incorrect userid or password for different role position, only open the admin.java , can't open others statement

Scanner input1 = new Scanner(System.in);
System.out.println("User ID : ");
String salesid = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Password : ");
String salespass = input2.next();

String smposition = "SM";
String pmposition = "PM";
String adposition = "AD";
{
    try
    {
        String line;
        File f = new File("UserDetails.txt");
        input1 = new Scanner(f);
        while(input1.hasNextLine())
        {
            String Line = input1.nextLine();
            String[] Seperator = Line.split(",");

            if(salesid.equals(Seperator[0]) && salespass.equals(Seperator[3]) && smposition.equals(Seperator[2]) || pmposition.equals(Seperator[2]) || adposition.equals(Seperator[2]))
            {
                if (smposition.equals(Seperator[2]))
                {
                    System.out.println("login successfull");
                    salesmanager ss = new salesmanager();
                    ss.sale();
                }
                else if(pmposition.equals(Seperator[2]))
                {
                    System.out.println("login successfull");
                    purchasemanager pm = new purchasemanager();
                    pm.purchase();
                }
                else if(adposition.equals(Seperator[2]))
                {
                    System.out.println("login successfull");
                    admin ad = new admin();
                    ad.adm();
                }
            }
        }
    }
    catch(IOException e)
    {
    }
}

Body:
Change your if condition to

if(salesid.equals(Seperator[0]) && salespass.equals(Seperator[3]) && (smposition.equals(Seperator[2]) || pmposition.equals(Seperator[2]) || adposition.equals(Seperator[2])))

Note the extra parentheses around the || conditions.


问:
Verify that clicks are coming from own website
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code

```<code>if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])) {
    header("Location: http:// www .site.com");
    die();
}
</code>```

but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?

EDIT: I formatted the code, but I left the spaces near http:// and www. -gore

答: If you want to try a different route than $_SERVER['HTTP_REFERER'] or setting cookie/session, you could write a script on the landing pages that will check the Apache access log to see if the requesting IP address was just previously visiting one of your linking pages... this should work even if they have cookies turned off or try to forge the referrer, and there's no visible url token</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code

if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])) {
    header("Location: http:// www .site.com");
    die();
}

but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?

EDIT: I formatted the code, but I left the spaces near http:// and www. -gore


问:
Oozie java action and spark action in same workflow error
I have a workflow whicha has two actions - java and spark.
In the lib directory If I keep the both Jars, then the Java action completes but the spark action throws error as

```<code>2017-12-01 03:50:02,612 ERROR [main] org.apache.hadoop.mapreduce.v2.app.MRAppMaster: Error starting MRAppMaster
java.lang.NoSuchMethodError: org.apache.hadoop.mapred.TaskLog.createLogSyncer()
</code>```

Having two lib paths results to java action not triggering.
How to keep java jar and spark jar in same workflow.

答:
You should first try to resolve this issue by using the lib version that spark is using. What is happening is your java and spark actions are using a common lib but with different versions. Java is able to run as "most likely" the lib jar version that java action requires is coming before in the class path.

If you want to go for the dirty solution, shade your java action jar and relocate the conflicting package name. (relocate package using shaded plugin)

Body:
I have a workflow whicha has two actions - java and spark.
In the lib directory If I keep the both Jars, then the Java action completes but the spark action throws error as

2017-12-01 03:50:02,612 ERROR [main] org.apache.hadoop.mapreduce.v2.app.MRAppMaster: Error starting MRAppMaster
java.lang.NoSuchMethodError: org.apache.hadoop.mapred.TaskLog.createLogSyncer()

Having two lib paths results to java action not triggering.
How to keep java jar and spark jar in same workflow.


问:
DBeaver on OSX - null connection returned
I can't connect to a postgreSQL database with DBeaver on osx (latest) and get this cryptic null connection returned

I can however connect with teamSQL without a problem.

I checked a ton of resources but I have no idea of the cause of this problem so my connection infos are the right ones.

For information I have java installed :

```<code>java -version
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
</code>```

答:
I'll provide a proper answer in case anyone runs into the same problem :

I am on osx and my team mates are on windows, we provided the same credentials but they were able to log in and I wasn't.

The problems comes from DBeaver on osx that will not strip the http:// from the beginning of urls and will not accept .com/:1244 as a valid port but will accept those without a problem on windows.

The correct way to input a url would then be mywebsite.com:1244

Hope that helps.

Body:
I can't connect to a postgreSQL database with DBeaver on osx (latest) and get this cryptic null connection returned

I can however connect with teamSQL without a problem.

I checked a ton of resources but I have no idea of the cause of this problem so my connection infos are the right ones.

For information I have java installed :

java -version
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)


问:
ASP secure user login in different access level and restricted access pages
Im building an ASP website with user login. Does any one knows what is the best and must secure way to make login page and make pages restricted access? I know some ways and used them for some website but sometimes they were not that secure. There is couple access level for this website. Admin, User, Sales Team, and couple more. Thanks.</p>

答: Add an include file at the top of your ASP pages which is executed before any of the page's code.  This way you can write your security code once, and apply it to all of your pages.</p>


问:
Matlab: How to link each note to a key if all keys are called to one function
In an exercise, we create piano keys which, when pressed, plays the required note.

Normally we call each key to its distinct function, as shown below.

```<code>function keysound
f=figure('Visible','off')
c_key = uicontrol('Style','pushbutton','String','C','Position',[140,80 40 160],'Callback',@c_keybutton)
%Pushbutton, @ 140,80, Size 40x160, labeled 'C', calls the keySound function
d_key = uicontrol('Style','pushbutton','String','D','Position',[180 80 40 160],'Callback',@d_keybutton)
%Pushbutton, @ 180,80, Size 40x160, labeled 'D', calls the keySound function
e_key = uicontrol('Style','pushbutton','String','E','Position',[220 80 40 160],'Callback',@e_keybutton)
%Pushbutton, @ 220,80, Size 40x160, labeled 'E', calls the keySound function
f_key =  uicontrol('Style','pushbutton','String','F','Position',[260 80 40 160],'Callback',@f_keybutton)
%Pushbutton, @ 260,80, Size 40x160, labeled 'F', calls the keySound function
g_key =  uicontrol('Style','pushbutton','String','G','Position',[300 80 40 160],'Callback',@g_keybutton)
%Pushbutton, @ 380,80, Size 40x160, labeled 'B', calls the keySound function
c_sharp =  uicontrol('Style','pushbutton','String','C#','Position',...
    [160 180 40 100],'Background','black','ForeGround','white','Callback',@c_sharpbutton)
%Pushbutton, @ 160,80, Size 40x100, labeled 'C#', background is black, foregrou, calls the keySound function
e_flat =  uicontrol('Style','pushbutton','String','Eb','Position',...
    [200 180 40 100],'Background','black','ForeGround','white','Callback',@e_flatbutton)
%Pushbutton, @ 300,80, Size 40x160, labeled 'G', calls the keySound function
a_key =  uicontrol('Style','pushbutton','String','A','Position',[340 80 40 160],'Callback',@a_keybutton)
%Pushbutton, @ 340,80, Size 40x160, labeled 'A', calls the keySound function
b_key =  uicontrol('Style','pushbutton','String','B','Position',[380 80 40 160],'Callback',@b_keybutton)
%Pushbutton, @ 200,80, Size 40x100, labeled 'Eb', background is black, foreground is white, calls the keySound function
f_sharp =  uicontrol('Style','pushbutton','String','F#','Position',[280 180 40 100],...
    'Background','black','ForeGround','white','Callback',@f_sharpbutton)
%Pushbutton, @ 280,80, Size 40x100, labeled 'F#', background is black, foreground is white, calls the keySound function
g_sharp =  uicontrol('Style','pushbutton','String','G#','Position',...
    [320 180 40 100],'Background','black','ForeGround','white','Callback',@g_sharpbutton)
%Pushbutton, @ 320,80, Size 40x100, labeled 'G#', background is black, foreground is white, calls the keySound function
b_flat =  uicontrol('Style','pushbutton','String','Bb','Position',...
    [360 180 40 100],'Background','black','ForeGround','white','Callback',@b_flatbutton)
%Pushbutton, @ 360,80, Size 40x100, labeled 'Bb', background is black, foreground is white, calls the keySound function

f.Visible='on'

freq = [261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, ...
    391.995, 415.305, 440.000, 466.164, 493.883]; %Provided frequencies of each note
sample = 8192;%Default sampling rate of the sound() command
% HINT: Begin by getting the 'String' property from the pressed button, you'll need it to determine which frequency
% you'll use.
% Begin your code after this line
dur = 0.6 %Set this to .6, which will be your duration
vals = 0:(1/sample):dur %This will be an array of values, from 0 to dur, in steps of the inverse of the sample rate

     function c_keybutton(c_key,event)
     R1=10*sin(2*pi*freq(1)*vals)
     sound(R1)
    end

     function d_keybutton(d_key,event)
     R2=10*sin(2*pi*freq(3)*vals)
     sound(R2)
     end

     function e_keybutton(e_key,event)
     R3=10*sin(2*pi*freq(5)*vals)
     sound(R3)
     end

      function f_keybutton(f_key,event)
      R4=10*sin(2*pi*freq(6)*vals)
      sound(R4)
      end
      function g_keybutton(g_key,event)
      R5=10*sin(2*pi*freq(8)*vals)
      sound(R5)
     end

      function a_keybutton(a_key,event)
      R6=10*sin(2*pi*freq(10)*vals)
      sound(R6)
      end
     function b_keybutton(b_key,event)
         R7=10*sin(2*pi*freq(12)*vals)
         sound(R7)
     end

     function c_sharpbutton(c_sharp,event)
         R8=10*sin(2*pi*freq(2)*vals)
        sound(R8)
     end

     function e_flatbutton(e_flat,event)
         R9=10*sin(2*pi*freq(4)*vals)
        sound(R9)
    end
     function f_sharpbutton(f_sharp,event)
         R10=10*sin(2*pi*freq(7)*vals)
         sound(R10)
     end
    function g_sharpbutton(g_sharp,event)
        R11=10*sin(2*pi*freq(9)*vals)
        sound(R11)
    end
    function b_flatbutton(b_flat,event)
        R12=10*sin(2*pi*freq(11)*vals)
         sound(R12)
     end

end
</code>```

However, the exercise demands this is split into two parts.

In the first part, we create a script which outlines the keys of the piano. We call only the "keySound" function.

```<code>c_key = uicontrol('Style','pushbutton','String','C','Position',[140 80 40 160],'Callback',@keySound)
%Pushbutton, @ 140,80, Size 40x160, labeled 'C', calls the keySound function
d_key = uicontrol('Style','pushbutton','String','D','Position',[180 80 40 160],'Callback',@keySound)
%Pushbutton, @ 180,80, Size 40x160, labeled 'D', calls the keySound function
e_key = uicontrol('Style','pushbutton','String','E','Position',[220 80 40 160],'Callback',@keySound)
%Pushbutton, @ 220,80, Size 40x160, labeled 'E', calls the keySound function
f_key = uicontrol('Style','pushbutton','String','F','Position',[260 80 40 160],'Callback',@keySound)
%Pushbutton, @ 260,80, Size 40x160, labeled 'F', calls the keySound function
g_key = uicontrol('Style','pushbutton','String','G','Position',[300 80 40 160],'Callback',@keySound)
%Pushbutton, @ 300,80, Size 40x160, labeled 'G', calls the keySound function
a_key = uicontrol('Style','pushbutton','String','A','Position',[340 80 40 160],'Callback',@keySound)
%Pushbutton, @ 340,80, Size 40x160, labeled 'A', calls the keySound function
b_key = uicontrol('Style','pushbutton','String','B','Position',[380 80 40 160],'Callback',@keySound)
%Pushbutton, @ 380,80, Size 40x160, labeled 'B', calls the keySound function
c_sharp = uicontrol('Style','pushbutton','String','C#','Position',[160 180 40 100],'BackgroundColor','black'...
    ,'Foreground','white','Callback',@keySound)
%Pushbutton, @ 160,180, Size 40x100, labeled 'C#', background is black, foreground is white, calls the keySound function
e_flat = uicontrol('Style','pushbutton','String','Eb','Position',[200 180 40 100],'BackgroundColor','black',...
    'ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 200,180, Size 40x100, labeled 'Eb', background is black, foreground is white, calls the keySound function
f_sharp = uicontrol('Style','pushbutton','String','F#','Position',[280 180 40 100],...,
    'BackgroundColor','black','ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 280,180, Size 40x100, labeled 'F#', background is black, foreground is white, calls the keySound function
g_sharp = uicontrol('Style','pushbutton','String','G#','Position',[320 180 40 100],...
    'BackgroundColor','black','ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 320,180, Size 40x100, labeled 'G#', background is black, foreground is white, calls the keySound function
b_flat = uicontrol('Style','pushbutton','String','Bb','Position',[360 180 40 100],...
    'BackgroundColor','black','ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 360,180, Size 40x100, labeled 'Bb', background is black, foreground is white, calls the keySound function
</code>```

In the second part, the following (quoted below) is required.

"The second part of this problem will be devoted to designing the callback function for the piano keys. When a key is pressed, it will call this function, which will play the note associated with that key. This function will play sound (using the sound() command)."

"Once you complete this, try copy/pasting both parts into matlab (as seperate files), and running the GUI script. Your GUI should pop up, and you should hear notes when you press the buttons!"

They give hints in the form of a code.

```<code>    function wave = keySound(hObject, Data)
%%Problem 10.1.2 is designed by Benjamin Szafarz for MATLAB 2017a
% function keySound(hObject, Data) is called when pressed by ANY of the keys in your piano GUI
% The aim of this function is to play the note of the pressed key, which you will do by first creating the note
% then playing it using the sound() command. Note that the sound() command takes an input of wave data.
% The wave data is a sin wave, created by you, in the form: A * sin(2*pi*<frequency>*<values array>), where
% A is 10, the frequency is the frequency of the note being played, and the values array is the array of values
% which you will create. The frequencies of the notes (in ascending order) are provided, as well as the default
% sampling rate for the sound() command.
% OUTPUT: wave, an array containing the wave data (your input for sound() ).
freq = [261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, ...
    391.995, 415.305, 440.000, 466.164, 493.883]; %Provided frequencies of each note
sample = 8192;%Default sampling rate of the sound() command
% HINT: Begin by getting the 'String' property from the pressed button, you'll need it to determine which frequency
% you'll use.
% Begin your code after this line
dur = .6; %Set this to .6, which will be your duration
vals = 0:(1/sample):1; %This will be an array of values, from 0 to dur, in steps of the inverse of the sample rate
end
</code>```

However, I'm unsure how to link each key to its note if all the keys call the same function.

答:
Hint:

```<code>b_flat = uicontrol('Style','pushbutton','String','Bb','Position',[360 180 40 100],...
'BackgroundColor','black','ForegroundColor','white','Callback',{@keySound,1})
</code>```

The function call should is similar to this:

```<code>function keySound(~,~,Id)
%Execution when button is pressed
switch Id

case 1
    %....

otherwise

end

return;
</code>```

Body:
In an exercise, we create piano keys which, when pressed, plays the required note.

Normally we call each key to its distinct function, as shown below.

function keysound
f=figure('Visible','off')
c_key = uicontrol('Style','pushbutton','String','C','Position',[140,80 40 160],'Callback',@c_keybutton)
%Pushbutton, @ 140,80, Size 40x160, labeled 'C', calls the keySound function
d_key = uicontrol('Style','pushbutton','String','D','Position',[180 80 40 160],'Callback',@d_keybutton)
%Pushbutton, @ 180,80, Size 40x160, labeled 'D', calls the keySound function
e_key = uicontrol('Style','pushbutton','String','E','Position',[220 80 40 160],'Callback',@e_keybutton)
%Pushbutton, @ 220,80, Size 40x160, labeled 'E', calls the keySound function
f_key =  uicontrol('Style','pushbutton','String','F','Position',[260 80 40 160],'Callback',@f_keybutton)
%Pushbutton, @ 260,80, Size 40x160, labeled 'F', calls the keySound function
g_key =  uicontrol('Style','pushbutton','String','G','Position',[300 80 40 160],'Callback',@g_keybutton)
%Pushbutton, @ 380,80, Size 40x160, labeled 'B', calls the keySound function
c_sharp =  uicontrol('Style','pushbutton','String','C#','Position',...
    [160 180 40 100],'Background','black','ForeGround','white','Callback',@c_sharpbutton)
%Pushbutton, @ 160,80, Size 40x100, labeled 'C#', background is black, foregrou, calls the keySound function
e_flat =  uicontrol('Style','pushbutton','String','Eb','Position',...
    [200 180 40 100],'Background','black','ForeGround','white','Callback',@e_flatbutton)
%Pushbutton, @ 300,80, Size 40x160, labeled 'G', calls the keySound function
a_key =  uicontrol('Style','pushbutton','String','A','Position',[340 80 40 160],'Callback',@a_keybutton)
%Pushbutton, @ 340,80, Size 40x160, labeled 'A', calls the keySound function
b_key =  uicontrol('Style','pushbutton','String','B','Position',[380 80 40 160],'Callback',@b_keybutton)
%Pushbutton, @ 200,80, Size 40x100, labeled 'Eb', background is black, foreground is white, calls the keySound function
f_sharp =  uicontrol('Style','pushbutton','String','F#','Position',[280 180 40 100],...
    'Background','black','ForeGround','white','Callback',@f_sharpbutton)
%Pushbutton, @ 280,80, Size 40x100, labeled 'F#', background is black, foreground is white, calls the keySound function
g_sharp =  uicontrol('Style','pushbutton','String','G#','Position',...
    [320 180 40 100],'Background','black','ForeGround','white','Callback',@g_sharpbutton)
%Pushbutton, @ 320,80, Size 40x100, labeled 'G#', background is black, foreground is white, calls the keySound function
b_flat =  uicontrol('Style','pushbutton','String','Bb','Position',...
    [360 180 40 100],'Background','black','ForeGround','white','Callback',@b_flatbutton)
%Pushbutton, @ 360,80, Size 40x100, labeled 'Bb', background is black, foreground is white, calls the keySound function

f.Visible='on'

freq = [261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, ...
    391.995, 415.305, 440.000, 466.164, 493.883]; %Provided frequencies of each note
sample = 8192;%Default sampling rate of the sound() command
% HINT: Begin by getting the 'String' property from the pressed button, you'll need it to determine which frequency
% you'll use.
% Begin your code after this line
dur = 0.6 %Set this to .6, which will be your duration
vals = 0:(1/sample):dur %This will be an array of values, from 0 to dur, in steps of the inverse of the sample rate

     function c_keybutton(c_key,event)
     R1=10*sin(2*pi*freq(1)*vals)
     sound(R1)
    end

     function d_keybutton(d_key,event)
     R2=10*sin(2*pi*freq(3)*vals)
     sound(R2)
     end

     function e_keybutton(e_key,event)
     R3=10*sin(2*pi*freq(5)*vals)
     sound(R3)
     end

      function f_keybutton(f_key,event)
      R4=10*sin(2*pi*freq(6)*vals)
      sound(R4)
      end
      function g_keybutton(g_key,event)
      R5=10*sin(2*pi*freq(8)*vals)
      sound(R5)
     end

      function a_keybutton(a_key,event)
      R6=10*sin(2*pi*freq(10)*vals)
      sound(R6)
      end
     function b_keybutton(b_key,event)
         R7=10*sin(2*pi*freq(12)*vals)
         sound(R7)
     end

     function c_sharpbutton(c_sharp,event)
         R8=10*sin(2*pi*freq(2)*vals)
        sound(R8)
     end

     function e_flatbutton(e_flat,event)
         R9=10*sin(2*pi*freq(4)*vals)
        sound(R9)
    end
     function f_sharpbutton(f_sharp,event)
         R10=10*sin(2*pi*freq(7)*vals)
         sound(R10)
     end
    function g_sharpbutton(g_sharp,event)
        R11=10*sin(2*pi*freq(9)*vals)
        sound(R11)
    end
    function b_flatbutton(b_flat,event)
        R12=10*sin(2*pi*freq(11)*vals)
         sound(R12)
     end

end

However, the exercise demands this is split into two parts.

In the first part, we create a script which outlines the keys of the piano. We call only the "keySound" function.

c_key = uicontrol('Style','pushbutton','String','C','Position',[140 80 40 160],'Callback',@keySound)
%Pushbutton, @ 140,80, Size 40x160, labeled 'C', calls the keySound function
d_key = uicontrol('Style','pushbutton','String','D','Position',[180 80 40 160],'Callback',@keySound)
%Pushbutton, @ 180,80, Size 40x160, labeled 'D', calls the keySound function
e_key = uicontrol('Style','pushbutton','String','E','Position',[220 80 40 160],'Callback',@keySound)
%Pushbutton, @ 220,80, Size 40x160, labeled 'E', calls the keySound function
f_key = uicontrol('Style','pushbutton','String','F','Position',[260 80 40 160],'Callback',@keySound)
%Pushbutton, @ 260,80, Size 40x160, labeled 'F', calls the keySound function
g_key = uicontrol('Style','pushbutton','String','G','Position',[300 80 40 160],'Callback',@keySound)
%Pushbutton, @ 300,80, Size 40x160, labeled 'G', calls the keySound function
a_key = uicontrol('Style','pushbutton','String','A','Position',[340 80 40 160],'Callback',@keySound)
%Pushbutton, @ 340,80, Size 40x160, labeled 'A', calls the keySound function
b_key = uicontrol('Style','pushbutton','String','B','Position',[380 80 40 160],'Callback',@keySound)
%Pushbutton, @ 380,80, Size 40x160, labeled 'B', calls the keySound function
c_sharp = uicontrol('Style','pushbutton','String','C#','Position',[160 180 40 100],'BackgroundColor','black'...
    ,'Foreground','white','Callback',@keySound)
%Pushbutton, @ 160,180, Size 40x100, labeled 'C#', background is black, foreground is white, calls the keySound function
e_flat = uicontrol('Style','pushbutton','String','Eb','Position',[200 180 40 100],'BackgroundColor','black',...
    'ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 200,180, Size 40x100, labeled 'Eb', background is black, foreground is white, calls the keySound function
f_sharp = uicontrol('Style','pushbutton','String','F#','Position',[280 180 40 100],...,
    'BackgroundColor','black','ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 280,180, Size 40x100, labeled 'F#', background is black, foreground is white, calls the keySound function
g_sharp = uicontrol('Style','pushbutton','String','G#','Position',[320 180 40 100],...
    'BackgroundColor','black','ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 320,180, Size 40x100, labeled 'G#', background is black, foreground is white, calls the keySound function
b_flat = uicontrol('Style','pushbutton','String','Bb','Position',[360 180 40 100],...
    'BackgroundColor','black','ForegroundColor','white','Callback',@keySound)
%Pushbutton, @ 360,180, Size 40x100, labeled 'Bb', background is black, foreground is white, calls the keySound function

In the second part, the following (quoted below) is required.

"The second part of this problem will be devoted to designing the callback function for the piano keys. When a key is pressed, it will call this function, which will play the note associated with that key. This function will play sound (using the sound() command)."

"Once you complete this, try copy/pasting both parts into matlab (as seperate files), and running the GUI script. Your GUI should pop up, and you should hear notes when you press the buttons!"

They give hints in the form of a code.

    function wave = keySound(hObject, Data)
%%Problem 10.1.2 is designed by Benjamin Szafarz for MATLAB 2017a
% function keySound(hObject, Data) is called when pressed by ANY of the keys in your piano GUI
% The aim of this function is to play the note of the pressed key, which you will do by first creating the note
% then playing it using the sound() command. Note that the sound() command takes an input of wave data.
% The wave data is a sin wave, created by you, in the form: A * sin(2*pi*<frequency>*<values array>), where
% A is 10, the frequency is the frequency of the note being played, and the values array is the array of values
% which you will create. The frequencies of the notes (in ascending order) are provided, as well as the default
% sampling rate for the sound() command.
% OUTPUT: wave, an array containing the wave data (your input for sound() ).
freq = [261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, ...
    391.995, 415.305, 440.000, 466.164, 493.883]; %Provided frequencies of each note
sample = 8192;%Default sampling rate of the sound() command
% HINT: Begin by getting the 'String' property from the pressed button, you'll need it to determine which frequency
% you'll use.
% Begin your code after this line
dur = .6; %Set this to .6, which will be your duration
vals = 0:(1/sample):1; %This will be an array of values, from 0 to dur, in steps of the inverse of the sample rate
end

However, I'm unsure how to link each key to its note if all the keys call the same function.

Body:
Hint:

b_flat = uicontrol('Style','pushbutton','String','Bb','Position',[360 180 40 100],...
'BackgroundColor','black','ForegroundColor','white','Callback',{@keySound,1})

The function call should is similar to this:

function keySound(~,~,Id)
%Execution when button is pressed
switch Id

case 1
    %....

otherwise

end

return;


问:
One row per group with multiple column sorting
Would like to return one row per group, where the one is selected by multiple sort columns. Treading lightly here in the land of greatest-n-per-group to avoid a duplicate question.

SCHEMA:

```<code>CREATE TABLE logs (
  id INT NOT NULL,
  ip_address INT NOT NULL,
  status INT NOT NULL,
  PRIMARY KEY id
);
</code>```

DATA:

```<code>INSERT INTO logs (id, ip_address, status)
VALUES ('1', 19216800, 1),
       ('2', 19216801, 2),
       ('3', 19216800, 2),
       ('4', 19216803, 0),
       ('5', 19216804, 0),
       ('6', 19216803, 0),
       ('7', 19216804, 1);
</code>```

CURRENT QUERY:

```<code>SELECT *
  FROM logs
 ORDER BY ip_address, status=1 DESC, id DESC
</code>```

Note: sorting by status=1 effectively turns the status column into a boolean. The tie breaker after status=1 is id. This query currently returns the correct row for each ip_address first and then a bunch of other rows I don't want for that ip_address.

CURRENT OUTPUT:

```<code>1, 19216800, 1
3, 19216800, 2
2, 19216801, 2
6, 19216803, 0
4, 19216803, 0
7, 19216804, 1
5, 19216804, 0
</code>```

WANTED OUTPUT:

```<code>1, 19216800, 1
2, 19216801, 2
6, 19216803, 0
7, 19216804, 1
</code>```

Today my workaround is to filter in PHP with if ($lastIP == $row['ip_address']) continue;. But I would like to move this logic to MySQL.

答:
Try this - </p>

```<code>SELECT MIN(id), ip_address, status
FROM logs
GROUP BY ip_address, status
</code>```

Body:
Would like to return one row per group, where the one is selected by multiple sort columns. Treading lightly here in the land of greatest-n-per-group to avoid a duplicate question.

SCHEMA:

CREATE TABLE logs (
  id INT NOT NULL,
  ip_address INT NOT NULL,
  status INT NOT NULL,
  PRIMARY KEY id
);

DATA:

INSERT INTO logs (id, ip_address, status)
VALUES ('1', 19216800, 1),
       ('2', 19216801, 2),
       ('3', 19216800, 2),
       ('4', 19216803, 0),
       ('5', 19216804, 0),
       ('6', 19216803, 0),
       ('7', 19216804, 1);

CURRENT QUERY:

SELECT *
  FROM logs
 ORDER BY ip_address, status=1 DESC, id DESC

Note: sorting by status=1 effectively turns the status column into a boolean. The tie breaker after status=1 is id. This query currently returns the correct row for each ip_address first and then a bunch of other rows I don't want for that ip_address.

CURRENT OUTPUT:

1, 19216800, 1
3, 19216800, 2
2, 19216801, 2
6, 19216803, 0
4, 19216803, 0
7, 19216804, 1
5, 19216804, 0

WANTED OUTPUT:

1, 19216800, 1
2, 19216801, 2
6, 19216803, 0
7, 19216804, 1

Today my workaround is to filter in PHP with if ($lastIP == $row['ip_address']) continue;. But I would like to move this logic to MySQL.

Body:
Try this -

SELECT MIN(id), ip_address, status
FROM logs
GROUP BY ip_address, status


问:
What is the equivalent of JSTL <c:forTokens> in JSF or PrimeFaces?
Assume we have the following JSP code:

```<code><c:forTokens items="${someBean.aStringOfIntNumbersSeparatedBySemicolons}"
             delims=";"
             var="item"
             varStatus="stat">
  ${item}
  <c:if test="${!stat.last}">;</c:if>
  <c:if test="${stat.count %5 == 0}">
    <br/>
  </c:if>
</c:forTokens>
</code>```

Of which the output is rendered in rows with 5 columns each, like so:

How can I possibly do this with the JSF or Primefaces tags?

答:
The only working solution I've found

For now, the only working solution I've found lies partly in the JSF and partly in the back-end code:

Edit the back-end code so that it adds a
 after every fifth element of that String field aStringOfIntNumbersSeparatedBySemicolons.

Add escape="false" to the <h:outputText> tag that holds the data on the front end. (The default value is escape="true", which renders
 as
)

Body:
Assume we have the following JSP code:

<c:forTokens items="${someBean.aStringOfIntNumbersSeparatedBySemicolons}"
             delims=";"
             var="item"
             varStatus="stat">
  ${item}
  <c:if test="${!stat.last}">;</c:if>
  <c:if test="${stat.count %5 == 0}">

  </c:if>
</c:forTokens>

Of which the output is rendered in rows with 5 columns each, like so:

How can I possibly do this with the JSF or Primefaces tags?

Body:
The only working solution I've found

For now, the only working solution I've found lies partly in the JSF and partly in the back-end code:

Edit the back-end code so that it adds a <br/> after every fifth element of that String field aStringOfIntNumbersSeparatedBySemicolons.

Add escape="false" to the <h:outputText> tag that holds the data on the front end. (The default value is escape="true", which renders <br/> as &lt;br/&gt;)


问:
How to read a text file with special characters in python
I am trying to read txt file with special characters like:
الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ

I'm using:

```<code>import fileinput
fileToSearch = "test_encoding.txt"
with open(fileToSearch, 'r', encoding='utf-8') as file:
    counter = 0;
    for line in file:
        print(line)
</code>```

But Python crashes with this message:

```<code>Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print(line)
  File "C:\Users\atheelm\AppData\Local\Programs\Python\Python35-
32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1:
character maps to <undefined>
</code>```

I have Python 3.5.1 and I'm using Windows.

I'm running this command:

```<code>py test.py > out.txt
</code>```

答:
use 2 diff files and use io:</p>

```<code>lines=["Init"]
with io.open(fileToSearch,'r',encoding='utf-8') as file:
    counter = 1;
    for line in file:
        lines.insert(counter,str(line))
        counter = counter+1
with io.open(out_file,'w',encoding='utf-8') as file:
    for item in lines:
        file.write("%s\n" % item)
</code>```

Body:
I am trying to read txt file with special characters like:
الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ

I'm using:

import fileinput
fileToSearch = "test_encoding.txt"
with open(fileToSearch, 'r', encoding='utf-8') as file:
    counter = 0;
    for line in file:
        print(line)

But Python crashes with this message:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print(line)
  File "C:\Users\atheelm\AppData\Local\Programs\Python\Python35-
32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1:
character maps to <undefined>

I have Python 3.5.1 and I'm using Windows.

I'm running this command:

py test.py > out.txt

Body:
use 2 diff files and use io:

lines=["Init"]
with io.open(fileToSearch,'r',encoding='utf-8') as file:
    counter = 1;
    for line in file:
        lines.insert(counter,str(line))
        counter = counter+1
with io.open(out_file,'w',encoding='utf-8') as file:
    for item in lines:
        file.write("%s\n" % item)


问:
Reactjs react-router Authenticate failling
I am new to ReactJS and sorry if this question was asked before, I don't know where to start.

I followed the Auth guidelines in:
https://reacttraining.com/react-router/web/example/auth-workflow

I am using react-router to handle navigation with ReactJS, I have an index.js file that handles the navigation and includes:

```<code>import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.authenticate((auth) => {
      if (auth) {
        (<Component {...props}/>)
      }
      else {
        (<Redirect to={{
          pathname: '/',
          state: { from: props.location }
        }}/>)
      }
    })
  )}/>
)

const App = () => (<BrowserRouter>
  <div>
    {/* PUBLIC */}
      <Route path={'/'} exact component={Inicio}/>
      <Route path={'/login'} component={Login}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

  </div>
</BrowserRouter>);

ReactDOM.render(<App/>, document.getElementById('root'));
</code>```

Navigates fine, but the Authentication in Auth.authenticate((auth).. isn't working properly and throws an error.

It refers to a file that has the following:

```<code>import React from 'react';
import http from '../services/http';

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

export default Auth;
</code>```

http.aunthenticate is a method with a callback, that works fine.

Yet I get the following error message in the console:

```<code>> The above error occurred in the <Route> component:
>     in Route (created by PrivateRoute)
>     in PrivateRoute (created by App)
>     in MuiThemeProvider (created by App)
>     in div (created by App)
>     in Router (created by BrowserRouter)
>     in BrowserRouter (created by App)
>     in App
>
> Consider adding an error boundary to your tree to customize error
> handling behavior. Visit https://reactjs.org/docs/error-boundaries.html to learn
> more about error boundaries. react-dom.development.js:9747 Error:
> Route(...): Nothing was returned from render. This usually means a
> return statement is missing. Or, to render nothing, return null.
</code>```

Any ideas? Thanks!

答:
Your PrivateRoute component never returns anything. Auth.authenticate((auth) =>... this is asynchronous therefore it's the same as if your method was empty in terms of render response. You should avoid doing that and simply have a property to detect whether or not the account is logged in or not. Per example this is how I wrote my PrivateRoute component using Facebook's Flux store.

```<code>const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      AccountStore.loggedIn ? (
        <Component {...props} />
      ) : (
          <Redirect to={{
            pathname: '/signin',
            state: { from: props.location }
          }} />
        )
    )} />
  )
</code>```

Here my component will always return something based off the account state being calculated prior to the rendering.

EDIT: Adding my AccountStore below for a bit more clarity on the specifics, Here I use a jwt token received after authenticatingn through a remote api and use whether or not it's set to determine if the user is logged in or not. However, it can be any property/value you pick. Could even be a class not connecting to anything and just flipping the user login status through a couple methods.

```<code>import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import AccountActionTypes from './AccountActionTypes';
import CoreDispatcher from '../CoreDispatcher';

import LocalStorage from '../../io/LocalStorage';

class AccountStore extends ReduceStore {
  constructor() {
    super(CoreDispatcher);

    this._jwt = LocalStorage.getItem('jwt');
  }

  getInitialState() {
    return Immutable.OrderedMap({
      jwt: this._jwt,
    });
  }

  reduce(state, action) {
    switch (action.type) {
      case AccountActionTypes.USER_DETAILS_IN:
        console.log('user details in');
        this._user = action.user;
        return state.set('user', this._user);

      case AccountActionTypes.USER_LOGGED_IN:
        this._jwt = action.jwt;
        return state.set('jwt', this._jwt);

      case AccountActionTypes.USER_LOGGED_OUT:
        this._jwt = null;
        return state.set('jwt', this._jwt);

      default:
        return state;
    }
  }

  get jwt() {
    return this._jwt;
  }

  get loggedIn() {
    return !!this._jwt;
  }
}

export default new AccountStore();
</code>```

More details to use Flux Stores and Dispatcher there: https://facebook.github.io/flux/

Body:
I am new to ReactJS and sorry if this question was asked before, I don't know where to start.

I followed the Auth guidelines in:
https://reacttraining.com/react-router/web/example/auth-workflow

I am using react-router to handle navigation with ReactJS, I have an index.js file that handles the navigation and includes:

import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.authenticate((auth) => {
      if (auth) {
        (<Component {...props}/>)
      }
      else {
        (<Redirect to={{
          pathname: '/',
          state: { from: props.location }
        }}/>)
      }
    })
  )}/>
)

const App = () => (<BrowserRouter>

    {/* PUBLIC */}
      <Route path={'/'} exact component={Inicio}/>
      <Route path={'/login'} component={Login}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

</BrowserRouter>);

ReactDOM.render(<App/>, document.getElementById('root'));

Navigates fine, but the Authentication in Auth.authenticate((auth).. isn't working properly and throws an error.

It refers to a file that has the following:

import React from 'react';
import http from '../services/http';

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

export default Auth;

http.aunthenticate is a method with a callback, that works fine.

Yet I get the following error message in the console:

> The above error occurred in the <Route> component:
>     in Route (created by PrivateRoute)
>     in PrivateRoute (created by App)
>     in MuiThemeProvider (created by App)
>     in div (created by App)
>     in Router (created by BrowserRouter)
>     in BrowserRouter (created by App)
>     in App
>
> Consider adding an error boundary to your tree to customize error
> handling behavior. Visit https://reactjs.org/docs/error-boundaries.html to learn
> more about error boundaries. react-dom.development.js:9747 Error:
> Route(...): Nothing was returned from render. This usually means a
> return statement is missing. Or, to render nothing, return null.

Any ideas? Thanks!

Body:
Your PrivateRoute component never returns anything. Auth.authenticate((auth) =>... this is asynchronous therefore it's the same as if your method was empty in terms of render response. You should avoid doing that and simply have a property to detect whether or not the account is logged in or not. Per example this is how I wrote my PrivateRoute component using Facebook's Flux store.

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      AccountStore.loggedIn ? (
        <Component {...props} />
      ) : (
          <Redirect to={{
            pathname: '/signin',
            state: { from: props.location }
          }} />
        )
    )} />
  )

Here my component will always return something based off the account state being calculated prior to the rendering.

EDIT: Adding my AccountStore below for a bit more clarity on the specifics, Here I use a jwt token received after authenticatingn through a remote api and use whether or not it's set to determine if the user is logged in or not. However, it can be any property/value you pick. Could even be a class not connecting to anything and just flipping the user login status through a couple methods.

import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import AccountActionTypes from './AccountActionTypes';
import CoreDispatcher from '../CoreDispatcher';

import LocalStorage from '../../io/LocalStorage';

class AccountStore extends ReduceStore {
  constructor() {
    super(CoreDispatcher);

    this._jwt = LocalStorage.getItem('jwt');
  }

  getInitialState() {
    return Immutable.OrderedMap({
      jwt: this._jwt,
    });
  }

  reduce(state, action) {
    switch (action.type) {
      case AccountActionTypes.USER_DETAILS_IN:
        console.log('user details in');
        this._user = action.user;
        return state.set('user', this._user);

      case AccountActionTypes.USER_LOGGED_IN:
        this._jwt = action.jwt;
        return state.set('jwt', this._jwt);

      case AccountActionTypes.USER_LOGGED_OUT:
        this._jwt = null;
        return state.set('jwt', this._jwt);

      default:
        return state;
    }
  }

  get jwt() {
    return this._jwt;
  }

  get loggedIn() {
    return !!this._jwt;
  }
}

export default new AccountStore();

More details to use Flux Stores and Dispatcher there: https://facebook.github.io/flux/


问:
Java Script error "Cannot read property 'clientWidth' of null" with modal
I'm having issues with Java Script with this code Not Answered.

Got it working in https://jsfiddle.net/p3kdbquh/2/ but not locally

```<code>  $('#myModal').modal('show');

var particleCount = 300;
var particleMax   = 1000;
var sky           = document.querySelector('.modal');
var canvas        = document.createElement('canvas');
var ctx           = canvas.getContext('2d');
var width         = sky.clientWidth; //THIS LINE
var height        = sky.clientHeight;
var i             = 0;
var active        = false;
var snowflakes    = [];
var snowflake;
canvas.style.position = 'absolute';
canvas.style.left = canvas.style.top = '0';

var Snowflake = function () {
  this.x = 0;
  this.y = 0;
  this.vy = 0;
  this.vx = 0;
  this.r = 0;

  this.reset();
};

Snowflake.prototype.reset = function() {
  this.x = Math.random() * width;
  this.y = Math.random() * -height;
  this.vy = 1 + Math.random() * 3;
  this.vx = 0.5 - Math.random();
  this.r = 1 + Math.random() * 2;
  this.o = 0.5 + Math.random() * 0.5;
};

function generateSnowFlakes() {
  snowflakes = [];
  for (i = 0; i < particleMax; i++) {
    snowflake = new Snowflake();
    snowflake.reset();
    snowflakes.push(snowflake);
  }
}

generateSnowFlakes();

function update() {
  ctx.clearRect(0, 0, width, height);

  if (!active) {
    return;
  }

  for (i = 0; i < particleCount; i++) {
    snowflake = snowflakes[i];
    snowflake.y += snowflake.vy;
    snowflake.x += snowflake.vx;

    ctx.globalAlpha = snowflake.o;
    ctx.beginPath();
    ctx.arc(snowflake.x, snowflake.y, snowflake.r, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.fill();

    if (snowflake.y > height) {
      snowflake.reset();
    }
  }

  requestAnimFrame(update);
}

function onResize() {
  width = sky.clientWidth;
  height = sky.clientHeight;
  canvas.width = width;
  canvas.height = height;
  ctx.fillStyle = '#FFF';

  var wasActive = active;
  active = width > 600;

  if (!wasActive && active) {
    requestAnimFrame(update);
  }
}

// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

onResize();
window.addEventListener('resize', onResize, false);

sky.appendChild(canvas);

var gui = new dat.GUI();
gui.add(window, 'particleCount').min(1).max(particleMax).step(1).name('Particles count').onFinishChange(function() {
  requestAnimFrame(update);
});
</code>```

I've read about this and seen that it has to do with the document.querySelector('.modal'); the class defined but my aspx code has the same name so it shouldn't return null.

this is the code in the client side with the modal properly defined

```<code><head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
<%--        <link rel="stylesheet" href="Content/bootstrap.min.css" />--%>
      <link rel="stylesheet" type="text/css" href="Style/Site.css" />
    <link rel="stylesheet" href="Style/animate.min.css" />

     <script src="Scripts/jquery-1.9.1.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
            <script src="Script/query.js"></script>

</head>
<body>
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <div class="top-image">
              <img src="https://tutsplus.github.io/merry-christmas-web-app-build/images/xmas-tree.png" alt="" />
            </div>
            <h1 class="modal-title">I wish you</h4>
          </div>
          <div class="modal-body">
            <p>Merry Christmas and Happy Holidays!</p>
            <hr />
            <p>Its time to say "<span>Thank You!</span>"</p>
          </div>
          <div class="modal-footer">
            <div class="img-footer">
            </div>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    </body>
</code>```

I got the code from this page "https://codepen.io/nunofidalgo/pen/zrYoVr"

Can anyone help please

Error i get from the consola

答:
I don't get that error

https://jsfiddle.net/p3kdbquh/

```<code>console.log(sky)
</code>```

div class="modal fade" id="myModal" tabindex="-1" role="dialog"

Can you make your own codepen with a recreation of the issue? If document.querySelector(query) doesn't find any elements it will return null so I'm assuming you have some issue in your configuration. Make sure your JS and is loading properly with your HTML, and you have spelled your class names correctly etc.

Also I feel like I should note that .modal() is not a part of jQuery stdlib. .modal() is, I believe, found in bootstrap's JS

Body:
I'm having issues with Java Script with this code Not Answered.

Got it working in https://jsfiddle.net/p3kdbquh/2/ but not locally

  $('#myModal').modal('show');

var particleCount = 300;
var particleMax   = 1000;
var sky           = document.querySelector('.modal');
var canvas        = document.createElement('canvas');
var ctx           = canvas.getContext('2d');
var width         = sky.clientWidth; //THIS LINE
var height        = sky.clientHeight;
var i             = 0;
var active        = false;
var snowflakes    = [];
var snowflake;
canvas.style.position = 'absolute';
canvas.style.left = canvas.style.top = '0';

var Snowflake = function () {
  this.x = 0;
  this.y = 0;
  this.vy = 0;
  this.vx = 0;
  this.r = 0;

  this.reset();
};

Snowflake.prototype.reset = function() {
  this.x = Math.random() * width;
  this.y = Math.random() * -height;
  this.vy = 1 + Math.random() * 3;
  this.vx = 0.5 - Math.random();
  this.r = 1 + Math.random() * 2;
  this.o = 0.5 + Math.random() * 0.5;
};

function generateSnowFlakes() {
  snowflakes = [];
  for (i = 0; i < particleMax; i++) {
    snowflake = new Snowflake();
    snowflake.reset();
    snowflakes.push(snowflake);
  }
}

generateSnowFlakes();

function update() {
  ctx.clearRect(0, 0, width, height);

  if (!active) {
    return;
  }

  for (i = 0; i < particleCount; i++) {
    snowflake = snowflakes[i];
    snowflake.y += snowflake.vy;
    snowflake.x += snowflake.vx;

    ctx.globalAlpha = snowflake.o;
    ctx.beginPath();
    ctx.arc(snowflake.x, snowflake.y, snowflake.r, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.fill();

    if (snowflake.y > height) {
      snowflake.reset();
    }
  }

  requestAnimFrame(update);
}

function onResize() {
  width = sky.clientWidth;
  height = sky.clientHeight;
  canvas.width = width;
  canvas.height = height;
  ctx.fillStyle = '#FFF';

  var wasActive = active;
  active = width > 600;

  if (!wasActive && active) {
    requestAnimFrame(update);
  }
}

// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

onResize();
window.addEventListener('resize', onResize, false);

sky.appendChild(canvas);

var gui = new dat.GUI();
gui.add(window, 'particleCount').min(1).max(particleMax).step(1).name('Particles count').onFinishChange(function() {
  requestAnimFrame(update);
});

I've read about this and seen that it has to do with the document.querySelector('.modal'); the class defined but my aspx code has the same name so it shouldn't return null.

this is the code in the client side with the modal properly defined

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
<%--        <link rel="stylesheet" href="Content/bootstrap.min.css" />--%>
      <link rel="stylesheet" type="text/css" href="Style/Site.css" />
    <link rel="stylesheet" href="Style/animate.min.css" />

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

I wish you

Merry Christmas and Happy Holidays!

Its time to say "Thank You!"

I got the code from this page "https://codepen.io/nunofidalgo/pen/zrYoVr"

Can anyone help please

Error i get from the consola

Body:
I don't get that error

https://jsfiddle.net/p3kdbquh/

console.log(sky)

div class="modal fade" id="myModal" tabindex="-1" role="dialog"

Can you make your own codepen with a recreation of the issue? If document.querySelector(query) doesn't find any elements it will return null so I'm assuming you have some issue in your configuration. Make sure your JS and is loading properly with your HTML, and you have spelled your class names correctly etc.

Also I feel like I should note that .modal() is not a part of jQuery stdlib. .modal() is, I believe, found in bootstrap's JS


问:
C# string manipulation, why this doesn't work?
```<code>int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}
</code>```

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

答:
My guess is you want something like this:

```<code>for(int i=1;i<=10;i++)
    Console.WriteLine(String.Format("test{0}",i);
</code>```

You can put any number of things in brackets, separate each input with a comma.

```<code>string Month = "Jan";
int day = 21;
string temp = String.Format("Today is:{0} - {1}/{2}",Month,day,2011);
</code>```

temp gets the value "Today is:Jan - 21/2011"

In the future the desired output would be helpful.

Edit: spelling

Body:
int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

Body:
My guess is you want something like this:

for(int i=1;i<=10;i++)
    Console.WriteLine(String.Format("test{0}",i);

You can put any number of things in brackets, separate each input with a comma.

string Month = "Jan";
int day = 21;
string temp = String.Format("Today is:{0} - {1}/{2}",Month,day,2011);

temp gets the value "Today is:Jan - 21/2011"

In the future the desired output would be helpful.

Edit: spelling


问:
How to prevent users from going back to the previous page?
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

```<code>[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}
</code>```

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code>```

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

答:
You can add a line of javascript to every page for a client-side solution:

history.forward();

See docs on MDN. When there is a page to go forward to (which is when the used pressed the BACK button), this will force the user to that page. When the user already is at the most recent page, this does nothing (no error).

Body:
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.


问:
getPackageManager and MockPackageManager
I wanted to get a list of installed apps on a device by using getInstalledApplications() method from MockPackageManager class (Yes it is deprecated). I used the following code (in my activity):

```<code>MockPackageManager mpm = new MockPackageManager();
List<ApplicationInfo> appInfoList = mpm.getInstalledApplications(0);
</code>```

But it gave me this error:

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Landroid/test/mock/MockPackageManager;
</code>```

then found this way (which worked):

```<code> List<ApplicationInfo> appInfoList = getPackageManager().getInstalledApplications(0);
</code>```

I looked at Android docs but only found these:

Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager(). [PackageManager docs]

Return PackageManager instance to find global package information.[Context docs about getPackageManager()]

I really didn't understand why the first way is wrong and why I should first use getPackageManager() (what does it do?).

Tnx in advance.

P.S: Sorry if it is a simple(stupid!) question :)

答:
As described in the official documentation here, MockPackageManager is a (deprecated) test class for mocking the package manager behaviours.

In the description there is stated:

All methods are non-functional and throw
  UnsupportedOperationException. Override it to provide the operations
  that you need.

Which is usefull only if you want to test some of your code involving the package manager.

To access the real implementation you have to use the real PackageManager class using

```<code>PackageManager pManager = getPackageManager(); //in a context environment
</code>```

or

```<code>PackageManager pManager = context.getPackageManager(); //in a non-context environment
</code>```

Body:
I wanted to get a list of installed apps on a device by using getInstalledApplications() method from MockPackageManager class (Yes it is deprecated). I used the following code (in my activity):

MockPackageManager mpm = new MockPackageManager();
List<ApplicationInfo> appInfoList = mpm.getInstalledApplications(0);

But it gave me this error:

java.lang.NoClassDefFoundError: Failed resolution of: Landroid/test/mock/MockPackageManager;

then found this way (which worked):

 List<ApplicationInfo> appInfoList = getPackageManager().getInstalledApplications(0);

I looked at Android docs but only found these:

Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager(). [PackageManager docs]

Return PackageManager instance to find global package information.[Context docs about getPackageManager()]

I really didn't understand why the first way is wrong and why I should first use getPackageManager() (what does it do?).

Tnx in advance.

P.S: Sorry if it is a simple(stupid!) question :)

Body:
As described in the official documentation here, MockPackageManager is a (deprecated) test class for mocking the package manager behaviours.

In the description there is stated:

All methods are non-functional and throw
  UnsupportedOperationException. Override it to provide the operations
  that you need.

Which is usefull only if you want to test some of your code involving the package manager.

To access the real implementation you have to use the real PackageManager class using

PackageManager pManager = getPackageManager(); //in a context environment

or

PackageManager pManager = context.getPackageManager(); //in a non-context environment