问:
How to arrange many UIView in a pattern targeting different sized displays
Aim:

Targeting different iPhone and iPad sized displays, I’m wanting to arrange many small square UIView in a pattern. Once arranged in place, I want to be able to control each UIView so that I can manipulate each one, for example, move and scale each individually.

One approach would be to place many small UIView manually on the Storyboard (Image 1), making sure to have enough small UIView to arrange in a pattern on the largest iPad screen, and then connect them all up in code. For example

```<code>@IBOutlet weak var myView001: UIView!
@IBOutlet weak var myView002: UIView!
...
...
@IBOutlet weak var myView144: UIView!
</code>```

But, the above approach seems very complex and not elegant.

Question:

How can I dynamically (and elegantly) create many small UIView, that
  can be arranged in a pattern to fit the smallest iPhone screen and the
  largest iPad screen, that can be manipulated in Swift code?

Image 1:

答:
Here is a way to create a subview and add it to your current view:

```<code>let subview = UIView()
subview.backgroundColor = .black
subview.frame = CGRect(x: 10, y: 10, width: 30, height: 30)
self.view.addSubview(subview)
</code>```

Another way to init multiple subviews, e.g., 10:

```<code>let subviews = (0 ..< 10).map { _ in UIView() }
for i in 0..<10 {
    subviews[i].frame = CGRect(x: 10 * i, y: 10, width: 30, height: 30)
}
</code>```

You need to identify the frame, calculate the distance and views' size, and add them to your current view.

Body:
Aim:

Targeting different iPhone and iPad sized displays, I’m wanting to arrange many small square UIView in a pattern. Once arranged in place, I want to be able to control each UIView so that I can manipulate each one, for example, move and scale each individually.

One approach would be to place many small UIView manually on the Storyboard (Image 1), making sure to have enough small UIView to arrange in a pattern on the largest iPad screen, and then connect them all up in code. For example

@IBOutlet weak var myView001: UIView!
@IBOutlet weak var myView002: UIView!
...
...
@IBOutlet weak var myView144: UIView!

But, the above approach seems very complex and not elegant.

Question:

How can I dynamically (and elegantly) create many small UIView, that
  can be arranged in a pattern to fit the smallest iPhone screen and the
  largest iPad screen, that can be manipulated in Swift code?

Image 1:

Body:
Here is a way to create a subview and add it to your current view:

let subview = UIView()
subview.backgroundColor = .black
subview.frame = CGRect(x: 10, y: 10, width: 30, height: 30)
self.view.addSubview(subview)

Another way to init multiple subviews, e.g., 10:

let subviews = (0 ..< 10).map { _ in UIView() }
for i in 0..<10 {
    subviews[i].frame = CGRect(x: 10 * i, y: 10, width: 30, height: 30)
}

You need to identify the frame, calculate the distance and views' size, and add them to your current view.


来源: stackexchange

问:
How to get respected column data with count(*)
I have a table which gives count of rows on selected condtion from database table in view
like this.

The table data 3 in bellow are count of rows on condition of 'a' and 'e'.

Like bellow query

```<code>    select count(*) from table1 where col1="a" and col2="e";
</code>```

When I click on 3 I want to get all 3 id's and count as 3 with out put as single row

Bellow, I want id's 1,5,7 on click table data 3

```<code>                 #  | a | b | c | d |
                ----|---|---|---|---|---
                 e  | 3 |   |   |   |
                ----|---|---|---|---|---
                 f  |   | 0 | 1 |   |
                ----|---|---|---|---|---
                 g  |   |   |   |   |
                ----|---|---|---|---|---
</code>```

My database table is

```<code>                id |col1 |col2|
                 1 |  a  | e  |
                 2 |  b  | g  |
                 3 |  a  | f  |
                 4 |  c  | f  |
                 5 |  a  | e  |
                 6 |  b  | f  |
                 7 |  a  | e  |
</code>```

I want id's with count

答:
I am not sure if i got your problem correctly.   I think your looking for something like :

SELECT GROUP_CONCAT(id) FROM table1 WHERE col1 = 'a' and col2 = 'e';

ContentLicense: CC BY-SA 3.0

Body:
I have a table which gives count of rows on selected condtion from database table in view
like this.

The table data 3 in bellow are count of rows on condition of 'a' and 'e'.

Like bellow query

    select count(*) from table1 where col1="a" and col2="e";

When I click on 3 I want to get all 3 id's and count as 3 with out put as single row

Bellow, I want id's 1,5,7 on click table data 3

                 #  | a | b | c | d |
                ----|---|---|---|---|---
                 e  | 3 |   |   |   |
                ----|---|---|---|---|---
                 f  |   | 0 | 1 |   |
                ----|---|---|---|---|---
                 g  |   |   |   |   |
                ----|---|---|---|---|---

My database table is

                id |col1 |col2|
                 1 |  a  | e  |
                 2 |  b  | g  |
                 3 |  a  | f  |
                 4 |  c  | f  |
                 5 |  a  | e  |
                 6 |  b  | f  |
                 7 |  a  | e  |

I want id's with count


问:
How this line is working in this C++ code snippet?
In main function there is a line

```<code>vector<bookStatusEnum> booksStatus(numbooks, available);
</code>```

can you please explain how this line is executing? i see there is no booksStatus function in the code snippet. so what is it actually.

```<code>#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

struct book
{
    string title, author;

    inline bool operator<(const book& other) const
    {
        if (author != other.author)
            return author < other.author;

        return title < other.title;
    }
};

void ReadInBooks(vector<book> & allBooks)
{
    string temp;

    book currentBook;

    while (cin >> temp, temp != "END")
    {
        currentBook.title = "";

        bool first = true;

        while (*(temp.end() - 1) != '"')
        {
            if (!first)
                currentBook.title += ' ';

            first = false;
            currentBook.title += temp;

            cin >> temp;
        }

        if (!first)
            currentBook.title += ' ';

        currentBook.title += temp;

        // Ignore 'by'
        cin >> temp;
        // ignore the space after the by
        cin.ignore();

        getline(cin, currentBook.author);
        allBooks.push_back(currentBook);
    }
}

enum bookStatusEnum { available, borrowed, returned };

int main()
{
    vector<book> allBooks;
    ReadInBooks(allBooks);
    int numBooks = allBooks.size();
    std::sort(allBooks.begin(), allBooks.end());

    vector<bookStatusEnum> booksStatus(numBooks, available);

    map<string, int> positionInAllBooks;
    for (int i = 0; i < numBooks; ++i)
        positionInAllBooks[allBooks[i].title] = i;

    vector<bool> borrowed(allBooks.size(), false);
    vector<bool> returned(allBooks.size(), false);

    string command;
    string bookName;
    while (cin >> command, command != "END")
    {
        if (command == "BORROW")
        {
            cin.ignore();
            getline(cin, bookName);
            int pos = positionInAllBooks[bookName];
            borrowed[pos] = true;
            returned[pos] = false;
        }

        else if (command == "RETURN")
        {
            cin.ignore();
            getline(cin, bookName);
            returned[positionInAllBooks[bookName]] = true;
        }

        else // SHELVE
        {
            int previous = -1;
            for (int i = 0; i < numBooks; ++i)
            {
                if (!borrowed[i])
                    previous = i;
                else if (returned[i])
                {
                    if (previous == -1)
                        cout << "Put " << allBooks[i].title << " first\n";
                    else
                        cout << "Put " << allBooks[i].title << " after " << allBooks[previous].title << '\n';

                    returned[i] = false;
                    borrowed[i] = false;
                    previous = i;
                }
            }

            cout << "END\n";
        }
    }
}
</code>```

P.S: I didn't find a suitable title for it. please feel free to suggest.

答:
Short explanation:  it constructs a std::vector<bookStatusEnum> named booksStatus with numbooks elements, each initialised to available.    (Assuming numbooks is in the range of values that a std:vector<bookStatusEnum>::size_type can represent).  If it fails to do this, the program will abort.

Long explanation follows .....

Since

there is a preceding using namespace std  (and no other using directives)

there are preceding variables in scope - numbooks which is of type int and available which is of type bookStatusEnum

the effect of

```<code>vector<bookStatusEnum> booksStatus(numbooks, available);
</code>```

is a definition of a variable named booksStatus which is of type std::vector<bookStatusEnum> which is initialised using a constructor that can accept two arguments, one of integral type and the other of type bookStatusEnum.

Reading the documentation for std::vector, we find it is a templated class with a constructor declared as something like;

```<code>vector(size_type count, const T& value, const Allocator& alloc = Allocator());
</code>```

where

size_type (which is actually named std::vector<bookStatusEnum>::size_type) is an implementation defined unsigned integral type;

T is the template parameter (i.e. the type bookStatusEnum if our vector is a std::vector<bookStatusEnum>) and;

The third parameter is given a default value, so this constructor can
accept two arguments.

To call this constructor, the variable numbooks is converted from int to size_type using modulo arithmetic (i.e. the converted value between 0 and the maximum value a size_type can represent), and available is passed by const reference.

The allocator (supplied by default) is an object that the vector will use to allocate memory.

The net effect of the statement is that bookStatus is of type std::vector<bookStatusEnum>.   The number of elements in that vector is numbooks  (as converted to size_type using modulo arithmetic) and each element has the value available.

If the construction fails (e.g. the allocator fails to allocate memory to hold the elements) an exception will be thrown.   Since there is no try/catch block, this will cause program termination (by calling abort()).

If construction succeeds, the object will exist until its containing scope ends.  In this case, that is when main() returns, so the vector's destructor is called as the program ends.   The effect of that destructor is releasing all memory used by the vector (i.e. the set of elements ceases to exist).

Simple!

Body:
In main function there is a line

vector<bookStatusEnum> booksStatus(numbooks, available);

can you please explain how this line is executing? i see there is no booksStatus function in the code snippet. so what is it actually.

#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

struct book
{
    string title, author;

    inline bool operator<(const book& other) const
    {
        if (author != other.author)
            return author < other.author;

        return title < other.title;
    }
};

void ReadInBooks(vector<book> & allBooks)
{
    string temp;

    book currentBook;

    while (cin >> temp, temp != "END")
    {
        currentBook.title = "";

        bool first = true;

        while (*(temp.end() - 1) != '"')
        {
            if (!first)
                currentBook.title += ' ';

            first = false;
            currentBook.title += temp;

            cin >> temp;
        }

        if (!first)
            currentBook.title += ' ';

        currentBook.title += temp;

        // Ignore 'by'
        cin >> temp;
        // ignore the space after the by
        cin.ignore();

        getline(cin, currentBook.author);
        allBooks.push_back(currentBook);
    }
}

enum bookStatusEnum { available, borrowed, returned };

int main()
{
    vector<book> allBooks;
    ReadInBooks(allBooks);
    int numBooks = allBooks.size();
    std::sort(allBooks.begin(), allBooks.end());

    vector<bookStatusEnum> booksStatus(numBooks, available);

    map<string, int> positionInAllBooks;
    for (int i = 0; i < numBooks; ++i)
        positionInAllBooks[allBooks[i].title] = i;

    vector<bool> borrowed(allBooks.size(), false);
    vector<bool> returned(allBooks.size(), false);

    string command;
    string bookName;
    while (cin >> command, command != "END")
    {
        if (command == "BORROW")
        {
            cin.ignore();
            getline(cin, bookName);
            int pos = positionInAllBooks[bookName];
            borrowed[pos] = true;
            returned[pos] = false;
        }

        else if (command == "RETURN")
        {
            cin.ignore();
            getline(cin, bookName);
            returned[positionInAllBooks[bookName]] = true;
        }

        else // SHELVE
        {
            int previous = -1;
            for (int i = 0; i < numBooks; ++i)
            {
                if (!borrowed[i])
                    previous = i;
                else if (returned[i])
                {
                    if (previous == -1)
                        cout << "Put " << allBooks[i].title << " first\n";
                    else
                        cout << "Put " << allBooks[i].title << " after " << allBooks[previous].title << '\n';

                    returned[i] = false;
                    borrowed[i] = false;
                    previous = i;
                }
            }

            cout << "END\n";
        }
    }
}

P.S: I didn't find a suitable title for it. please feel free to suggest.

Body:
Short explanation:  it constructs a std::vector<bookStatusEnum> named booksStatus with numbooks elements, each initialised to available.    (Assuming numbooks is in the range of values that a std:vector<bookStatusEnum>::size_type can represent).  If it fails to do this, the program will abort.

Long explanation follows .....

Since

there is a preceding using namespace std  (and no other using directives)

there are preceding variables in scope - numbooks which is of type int and available which is of type bookStatusEnum

the effect of

vector<bookStatusEnum> booksStatus(numbooks, available);

is a definition of a variable named booksStatus which is of type std::vector<bookStatusEnum> which is initialised using a constructor that can accept two arguments, one of integral type and the other of type bookStatusEnum.

Reading the documentation for std::vector, we find it is a templated class with a constructor declared as something like;

vector(size_type count, const T& value, const Allocator& alloc = Allocator());

where

size_type (which is actually named std::vector<bookStatusEnum>::size_type) is an implementation defined unsigned integral type;

T is the template parameter (i.e. the type bookStatusEnum if our vector is a std::vector<bookStatusEnum>) and;

The third parameter is given a default value, so this constructor can
accept two arguments.

To call this constructor, the variable numbooks is converted from int to size_type using modulo arithmetic (i.e. the converted value between 0 and the maximum value a size_type can represent), and available is passed by const reference.

The allocator (supplied by default) is an object that the vector will use to allocate memory.

The net effect of the statement is that bookStatus is of type std::vector<bookStatusEnum>.   The number of elements in that vector is numbooks  (as converted to size_type using modulo arithmetic) and each element has the value available.

If the construction fails (e.g. the allocator fails to allocate memory to hold the elements) an exception will be thrown.   Since there is no try/catch block, this will cause program termination (by calling abort()).

If construction succeeds, the object will exist until its containing scope ends.  In this case, that is when main() returns, so the vector's destructor is called as the program ends.   The effect of that destructor is releasing all memory used by the vector (i.e. the set of elements ceases to exist).

Simple!


问:
Mongodb : Aggregate data and apply function on each element
I want to get a catalog with all discounted product in it.

2 documents :

```<code>/* Catalog schema */
{
  Catalog: {
    products: [{
      type: ObjectId,
      ref: 'Product'
    }],
  discount: {
    global: { type: Number, default: 0 },
    categories: [{
      codeCategory: String,
      discount: Number
  }]
 }
}

/* Product schema */
{
  reference: {
    type: String,
    index: true,
    unique: true
  },
  url_photo: {
    type: String,
    default: 'http://localhost:3001/app/img/no-picture.jpg'
  },
  category: {
    type: ObjectId,
    ref: 'Category'
  },
  short_description: String,
  long_description: String,
  price: Number,
  information: String
}
</code>```

The discount is apply on each product from a catalog, how can i make a query in mongo to get in the catalog all product with the applied discount ?

Can i query directly to have this result ?

i already check with aggregate but i'm new with it and i can't see how can i make this.

thanks

答:
You can use below aggregation in 3.4 pipeline.

$lookup to pull products data for category at catalog.products path and use $map to apply discount to each product's price and include all the product fields similar to as shown for information field. $addFields overwrites the products array with discounted price.

Add category level discount if the matching product category is found in catalog. Use $indexOfArray to find the index of matching category, if found, use $arrayElemAt to find the category at that index followed by projecting discount amount else 0.

```<code>[
  {
    "$lookup": {
      "from": "products",
      "localField": "catalog.products",
      "foreignField": "_id",
      "as": "catalog.products"
    }
  },
  {
    "$addFields": {
      "catalog.products": {
        "$map": {
          "input": "$catalog.products",
          "as": "product",
          "in": {
            "price": {
              "$multiply": [
                "$$product.price",
                {
                  "$add": [
                    "$catalog.discount.global",
                    {
                      "$let": {
                        "vars": {
                          "index": {
                            "$indexOfArray": [
                              "$catalog.discount.categories.codeCategory",
                              "$$product.category"
                            ]
                          }
                        },
                        "in": {
                          "$cond": [
                            {
                              "$eq": [
                                "$$index",
                                -1
                              ]
                            },
                            0,
                            {
                              "$let": {
                                "vars": {
                                  "categorydisc": {
                                    "$arrayElemAt": [
                                      "$catalog.discount.categories",
                                      "$$index"
                                    ]
                                  }
                                },
                                "in": "$$categorydisc.discount"
                              }
                            }
                          ]
                        }
                      }
                    }
                  ]
                }
              ]
            },
            "information": "$$product.information"
          }
        }
      }
    }
  }
]
</code>```

Body:
I want to get a catalog with all discounted product in it.

2 documents :

/* Catalog schema */
{
  Catalog: {
    products: [{
      type: ObjectId,
      ref: 'Product'
    }],
  discount: {
    global: { type: Number, default: 0 },
    categories: [{
      codeCategory: String,
      discount: Number
  }]
 }
}

/* Product schema */
{
  reference: {
    type: String,
    index: true,
    unique: true
  },
  url_photo: {
    type: String,
    default: 'http://localhost:3001/app/img/no-picture.jpg'
  },
  category: {
    type: ObjectId,
    ref: 'Category'
  },
  short_description: String,
  long_description: String,
  price: Number,
  information: String
}

The discount is apply on each product from a catalog, how can i make a query in mongo to get in the catalog all product with the applied discount ?

Can i query directly to have this result ?

i already check with aggregate but i'm new with it and i can't see how can i make this.

thanks

Body:
You can use below aggregation in 3.4 pipeline.

$lookup to pull products data for category at catalog.products path and use $map to apply discount to each product's price and include all the product fields similar to as shown for information field. $addFields overwrites the products array with discounted price.

Add category level discount if the matching product category is found in catalog. Use $indexOfArray to find the index of matching category, if found, use $arrayElemAt to find the category at that index followed by projecting discount amount else 0.

[
  {
    "$lookup": {
      "from": "products",
      "localField": "catalog.products",
      "foreignField": "_id",
      "as": "catalog.products"
    }
  },
  {
    "$addFields": {
      "catalog.products": {
        "$map": {
          "input": "$catalog.products",
          "as": "product",
          "in": {
            "price": {
              "$multiply": [
                "$$product.price",
                {
                  "$add": [
                    "$catalog.discount.global",
                    {
                      "$let": {
                        "vars": {
                          "index": {
                            "$indexOfArray": [
                              "$catalog.discount.categories.codeCategory",
                              "$$product.category"
                            ]
                          }
                        },
                        "in": {
                          "$cond": [
                            {
                              "$eq": [
                                "$$index",
                                -1
                              ]
                            },
                            0,
                            {
                              "$let": {
                                "vars": {
                                  "categorydisc": {
                                    "$arrayElemAt": [
                                      "$catalog.discount.categories",
                                      "$$index"
                                    ]
                                  }
                                },
                                "in": "$$categorydisc.discount"
                              }
                            }
                          ]
                        }
                      }
                    }
                  ]
                }
              ]
            },
            "information": "$$product.information"
          }
        }
      }
    }
  }
]


问:
GIF transparent background turned yellow
I tried several solutions, but nothing work.

```<code>$srcImage = imagecreatefromgif($_FILES['img']['tmp_name']);
$bg = imagecolorallocatealpha($srcImage, 0, 0, 0, 127);
imagecolortransparent($srcImage, $bg);
imagealphablending($srcImage, false);
imagesavealpha($srcImage, true);

imagegif($srcImage, 't.gif');
</code>```

Result:

答:
GIF images don't support alpha-channel transparency.

Since you're trying to set an existing image colour to transparent you need to find it in the palette.  You can do that with imagecolorexact:

```<code>$srcImage = imagecreatefromgif($_FILES['img']['tmp_name']);
$bg = imagecolorexact($srcImage, 204, 168, 46); // RGB here matches the yellowish colour in your image.
imagecolortransparent($srcImage, $bg);

imagegif($srcImage, 't.gif');
</code>```

Result:

Body:
I tried several solutions, but nothing work.

$srcImage = imagecreatefromgif($_FILES['img']['tmp_name']);
$bg = imagecolorallocatealpha($srcImage, 0, 0, 0, 127);
imagecolortransparent($srcImage, $bg);
imagealphablending($srcImage, false);
imagesavealpha($srcImage, true);

imagegif($srcImage, 't.gif');

Result:

Body:
GIF images don't support alpha-channel transparency.

Since you're trying to set an existing image colour to transparent you need to find it in the palette.  You can do that with imagecolorexact:

$srcImage = imagecreatefromgif($_FILES['img']['tmp_name']);
$bg = imagecolorexact($srcImage, 204, 168, 46); // RGB here matches the yellowish colour in your image.
imagecolortransparent($srcImage, $bg);

imagegif($srcImage, 't.gif');

Result:


问:
Access view inside view controller programmatically using a string tag
I'm retrieving a bunch of ViewControllers programmatically. The source of those ViewController is in my StoryBoard and I'm creating them using

```<code>let page = storyboard?.instantiateViewController(withIdentifier: "features_view_controller")
</code>```

What I want to do is, to access a UILabel I have inside that ViewController in my StoryBoard programmatically using preferably a string tag. Something like this maybe?

```<code>var label = page?.view("identifer")
</code>```

How can I do this?

答:
You should add @IBOutlet property to your UIViewController class.

```<code>class YourViewController: UIViewController {
    @IBOutlet weak var label: UILabel! // link it with UILabel in the storyborad.
}
</code>```

Then you will able to have an access to UILabel:

```<code>    if let page = UIStoryboard().instantiateViewController(withIdentifier: "features_view_controller") as? YourViewController {
        page.label //your label, which is currently nil, because the view controller still does not draw view.
    }
</code>```

But if you need update, for example, the label text, then you should prepare "data transfer object" and pass it to your view controller. After view did load, you can update UILabel. Example below:

```<code>class YourViewController: UIViewController {
    @IBOutlet weak var label: UILabel!
    var text: String? //text for label.

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = text
    }
}

if let page = UIStoryboard().instantiateViewController(withIdentifier: "features_view_controller") as? YourViewController {
    page.text = "Test"
    //show page (present or push view controller) or manually send command for drawing view (page.view)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm retrieving a bunch of ViewControllers programmatically. The source of those ViewController is in my StoryBoard and I'm creating them using

let page = storyboard?.instantiateViewController(withIdentifier: "features_view_controller")

What I want to do is, to access a UILabel I have inside that ViewController in my StoryBoard programmatically using preferably a string tag. Something like this maybe?

var label = page?.view("identifer")

How can I do this?

Body:
You should add @IBOutlet property to your UIViewController class.

class YourViewController: UIViewController {
    @IBOutlet weak var label: UILabel! // link it with UILabel in the storyborad.
}

Then you will able to have an access to UILabel:

    if let page = UIStoryboard().instantiateViewController(withIdentifier: "features_view_controller") as? YourViewController {
        page.label //your label, which is currently nil, because the view controller still does not draw view.
    }

But if you need update, for example, the label text, then you should prepare "data transfer object" and pass it to your view controller. After view did load, you can update UILabel. Example below:

class YourViewController: UIViewController {
    @IBOutlet weak var label: UILabel!
    var text: String? //text for label.

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = text
    }
}

if let page = UIStoryboard().instantiateViewController(withIdentifier: "features_view_controller") as? YourViewController {
    page.text = "Test"
    //show page (present or push view controller) or manually send command for drawing view (page.view)
}


问:
Why would you set `null: false, default: ""` on a required DB column?
I'm building a Rails app with Devise for authentication, and its default DB migration sets the following columns:

```<code>## Database authenticatable
t.string :email,              null: false, default: ""
t.string :encrypted_password, null: false, default: ""
</code>```

What is the purpose of setting null: false and default: "" at the same time?

My understanding is that null: false effectively makes a value required: i.e., trying to save a record with a NULL value in that column will fail on the database level, without depending any validations on the model.

But then default: "" basically undoes that by simply converting NULL values to empty strings before saving.

I understand that for an optional column, you want to reject NULL values just to make sure that all data within that column is of the same type. However, in this case, email and password are decidedly not optional attributes on a user authentication model. I'm sure there are validations in the model to make sure you can't create a user with an empty email address, but why would you set default: "" here in the first place? Does it serve some benefit or prevent some edge case that I haven't considered?

答:
Broadly speaking:

To make a column required, you must set null: false on it. This is true whether you are creating a new table or updating an existing one.

And in the event that you're updating an existing table, the DB engine will try to populate that new column with NULL in each row. In such cases, you must override this behavior with default: "", or else it will conflict with null: false and the migraiton will fail.

With respect to Devise:

Devise uses two separate templates for building migrations: migration.rb, for creating new tables, and migration_existing.rb, for updating existing tables (see source on GitHub). Both templates call the same migration_data method to generate the lines in question (i.e., the ones that specify null: false, default: ""), but as mentioned above, default: "" is only really relevant in the latter case (see O. Jones’ answer for more).

So the short answer to your question, specifically in the case of Devise migrations, is “because the generator uses borrowed code which doesn’t always apply, but still doesn’t break anything.”

A consideration for UNIQUE columns:

Note that in most popular SQL engines, uniquely indexed columns can still contain multiple rows of NULL values, as long as they are not required (naturally). But the effect of making a new column both required and unique (i.e., null: false, default: "", and unique: true) is that it cannot be added: the DB engine tries to populate the new column with an empty string in each row, which conflicts with the unique constraint and causes the migration to fail.

(The only scenario in which this mechanism fails is if you have exactly one row in your table — it gets a blank string value for the new column, which naturally passes the uniqueness constraint because it's the only record.)

So another way to look at it might be that these options are a safety mechanism preventing you from running migrations that you shouldn't (i.e., retroactively adding required columns to an already-populated table).

Body:
I'm building a Rails app with Devise for authentication, and its default DB migration sets the following columns:

## Database authenticatable
t.string :email,              null: false, default: ""
t.string :encrypted_password, null: false, default: ""

What is the purpose of setting null: false and default: "" at the same time?

My understanding is that null: false effectively makes a value required: i.e., trying to save a record with a NULL value in that column will fail on the database level, without depending any validations on the model.

But then default: "" basically undoes that by simply converting NULL values to empty strings before saving.

I understand that for an optional column, you want to reject NULL values just to make sure that all data within that column is of the same type. However, in this case, email and password are decidedly not optional attributes on a user authentication model. I'm sure there are validations in the model to make sure you can't create a user with an empty email address, but why would you set default: "" here in the first place? Does it serve some benefit or prevent some edge case that I haven't considered?


问:
django template / File name too long error/ when getting models objects
I am getting an error which lokks like this:

```<code>IOError at /url/
[Errno 36] File name too long: "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/

    <user_prefs: user_prefs object>,<user_prefs: user_prefs object>,<user_prefs: user_prefs object> etc..
</code>```

my views.py look like this

```<code>def show_interests(request):
    current_user = request.user.id
    output = user_prefs()
    output.save()
    outputs = user_prefs.objects.all().filter(userID=current_user)
    return render('showme.html',{'outputs':outputs})
</code>```

and my template( i use a very basic html form just to test things as for now.)

```<code><!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Hi, it's a test</title>
    {% for outputs in output %}
    {{ outputs.Cuisine }}
    {{ outputs.Cuisine1 }}
    {{ outputs.LunchPref }}
    {{ outputs.DinnerPref }}
    {{ outputs.Friday }}
    {{ outputs.Sunday }}
    {% endfor %}
<body>

</body>
</html>
</code>```

Never ever seen an error like this, and my other models that i have work just fine.

答:
Couple of mistakes in your view,

As @Exprator pointed out, missed the request parameter.

Your context variable is named as outputs, but in your template, you have written {% for outputs in output %} (may be just a typo).

Every time you access this page an object is created. Probably, you don't want that.

Body:
I am getting an error which lokks like this:

IOError at /url/
[Errno 36] File name too long: "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/

    <user_prefs: user_prefs object>,<user_prefs: user_prefs object>,<user_prefs: user_prefs object> etc..

my views.py look like this

def show_interests(request):
    current_user = request.user.id
    output = user_prefs()
    output.save()
    outputs = user_prefs.objects.all().filter(userID=current_user)
    return render('showme.html',{'outputs':outputs})

and my template( i use a very basic html form just to test things as for now.)

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hi, it's a test</title>
    {% for outputs in output %}
    {{ outputs.Cuisine }}
    {{ outputs.Cuisine1 }}
    {{ outputs.LunchPref }}
    {{ outputs.DinnerPref }}
    {{ outputs.Friday }}
    {{ outputs.Sunday }}
    {% endfor %}

Never ever seen an error like this, and my other models that i have work just fine.


问:
nested loops avoiding self and reciprocal comparisons
Since this must be quite a common scenario I'm wondering whether there are any pre-existing solutions to the following.

Lets say I have a set of N strings, and I am computing distances the distances between them. In this case it's a Hamming distance, but that's not really important.

If I wanted to make this as quick as possible, I would avoid self comparisons like so:

```<code> def hamming_distance(string1, string2):
     """Return the Hamming distance between equal-length sequences"""
     if len(string1) != len(string2):
         raise ValueError("Undefined for sequences of unequal length")
     return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

ratios=[]
 for a, i in enumerate(string_list):
     for b, j in enumerate(string_list):
         if a == b: # Avoid self comparisons for speed
             break
     ratios.append(hamming_distance(string_list[i], string_list[j]))
 return ratios
</code>```

But since this is 'symmetric', I could also throw away any reciprocal comparisons which would increase the speed if the strings were numerous and/or large.

Is there a generally accepted/elegant way of doing this in the above set up?

I'm also aware that in general it's advised to avoid nested loops as they can be slow - so if there is a better way of achieving this pairwise iteration over lists (maybe something in collections?) and incorporating the avoidance of self and reciprocal comparisons, I'm all ears.

答:
You can limit the nested for to start from the next item to the current item in the outer loop. In that way, you only run through each unique once:

```<code>for i, s1 in enumerate(string_list):
   for s2 in string_list[i+1:]:
      ratios.append(hamming_distance(s1, s2))
return ratios
</code>```

You could put this in a list comp.:

```<code>ratios = [(s1, s2, hamming_distance(s1, s2)) for i, s1 in enumerate(string_list)
                                                     for s2 in string_list[i+1:]]
</code>```

You could put the strings in a tuple as part of the result like I've done in the list comp.

Body:
Since this must be quite a common scenario I'm wondering whether there are any pre-existing solutions to the following.

Lets say I have a set of N strings, and I am computing distances the distances between them. In this case it's a Hamming distance, but that's not really important.

If I wanted to make this as quick as possible, I would avoid self comparisons like so:

 def hamming_distance(string1, string2):
     """Return the Hamming distance between equal-length sequences"""
     if len(string1) != len(string2):
         raise ValueError("Undefined for sequences of unequal length")
     return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

ratios=[]
 for a, i in enumerate(string_list):
     for b, j in enumerate(string_list):
         if a == b: # Avoid self comparisons for speed
             break
     ratios.append(hamming_distance(string_list[i], string_list[j]))
 return ratios

But since this is 'symmetric', I could also throw away any reciprocal comparisons which would increase the speed if the strings were numerous and/or large.

Is there a generally accepted/elegant way of doing this in the above set up?

I'm also aware that in general it's advised to avoid nested loops as they can be slow - so if there is a better way of achieving this pairwise iteration over lists (maybe something in collections?) and incorporating the avoidance of self and reciprocal comparisons, I'm all ears.

Body:
You can limit the nested for to start from the next item to the current item in the outer loop. In that way, you only run through each unique once:

for i, s1 in enumerate(string_list):
   for s2 in string_list[i+1:]:
      ratios.append(hamming_distance(s1, s2))
return ratios

You could put this in a list comp.:

ratios = [(s1, s2, hamming_distance(s1, s2)) for i, s1 in enumerate(string_list)
                                                     for s2 in string_list[i+1:]]

You could put the strings in a tuple as part of the result like I've done in the list comp.


问:
Mongoose creating a regular expression and searching in model for blog
I want to implement searching in my blog so far what I have done is created a blog having search form which takes a string as input and make get request.

Now in that request I have a function which gets called for searching the string in my blog head or body.

So if a user types "foo bar" I get my results that have "foo bar"

But what I want is that this function searches for each space separated word and AND the result. i.e. search for "foo", search for "bar" and intersect the results to get
posts having "bar foo", "foo hello bar", "bar hello foo"

```<code>function(searchQuery, callback){
    var query = {
        $or:[
                { head: {$regex: searchQuery, $options: "i"} },
                { body: {$regex: searchQuery, $options: "i"} }
            ]
    };
    Post.find(query, {sort: { date: -1 }, page: i, limit: 5 }, callback);
}
</code>```

the url of get requests is as follows

```<code>localhost:5000/blog/?searchQuery=FOO+BAR
</code>```

If there is some other way around of doing this I am open to suggestions.

答:
Found the answer!
needed to create my head and body a textindex
https://docs.mongodb.com/manual/core/index-text/

and the use this code inside the function

```<code>function(searchQuery, callback){

    var queryString = '\"' + searchQuery.split(' ').join('\" \"') + '\"';
    var query = { $text: { $search: queryString } };
    Post.find(query, {sort: { date: -1 }, page: i, limit: 5 }, callback);

}
</code>```

no need of regular expression!

Body:
I want to implement searching in my blog so far what I have done is created a blog having search form which takes a string as input and make get request.

Now in that request I have a function which gets called for searching the string in my blog head or body.

So if a user types "foo bar" I get my results that have "foo bar"

But what I want is that this function searches for each space separated word and AND the result. i.e. search for "foo", search for "bar" and intersect the results to get
posts having "bar foo", "foo hello bar", "bar hello foo"

function(searchQuery, callback){
    var query = {
        $or:[
                { head: {$regex: searchQuery, $options: "i"} },
                { body: {$regex: searchQuery, $options: "i"} }
            ]
    };
    Post.find(query, {sort: { date: -1 }, page: i, limit: 5 }, callback);
}

the url of get requests is as follows

localhost:5000/blog/?searchQuery=FOO+BAR

If there is some other way around of doing this I am open to suggestions.

Body:
Found the answer!
needed to create my head and body a textindex
https://docs.mongodb.com/manual/core/index-text/

and the use this code inside the function

function(searchQuery, callback){

    var queryString = '\"' + searchQuery.split(' ').join('\" \"') + '\"';
    var query = { $text: { $search: queryString } };
    Post.find(query, {sort: { date: -1 }, page: i, limit: 5 }, callback);

}

no need of regular expression!


问:
difference in setProperty and ActiveProfiles annotation for junit testing
I have config files for my different environmnets: prod.properties, dev.propertites, and test.properties.

Properties file is loaded via application-context.xml file using

${spring.profiles.active}.properties

and passing in -Dspring.profiles.active flag. This works file for my 3 environments.

For Junit testing I'm trying to use

@ActiveProfiles("test")

in my test class but $(spring.profiles.active) is not resolving. But when I use

System.getProperties().setProperty("spring.profiles.active",
  "test");

it resolved fine.

I know @ActiveProfiles is only for test classes but why doesn't it set the spring.profiles.active property? Does it only affect which beans to use?

This also doesn't clarify who best to handle profiles and property files.
Spring profiles and Testing

Update:
I have so far resorted to using the following in my application context file:

```<code><beans profile="dev,prod">
<context:property-placeholder
      location="classpath:META-INF/properties/generic.properties,
        classpath:META-INF/properties/${spring.profiles.active}/${spring.profiles.active}.properties"/>
        <context:component-scan base-package="com.my.package.to.scan"/>
 </beans>

<beans profile="test">
    <context:property-placeholder
      location="classpath:META-INF/properties/generic.properties,
        classpath:META-INF/properties/test/test.properties"/>
<context:component-scan base-package="com.my.package.to.scan"/>
</beans>
</code>```

答:
As the name suggest @ActiveProfiles, this is array of profiles.

```<code>/**
 * The bean definition profiles to activate.
 * <p>This attribute may <strong>not</strong> be used in conjunction with
 * {@link #value}, but it may be used <em>instead</em> of {@link #value}.
 */
@AliasFor("value")
String[] profiles() default {};
</code>```

Try with @ActiveProfiles({"test"}).

Body:
I have config files for my different environmnets: prod.properties, dev.propertites, and test.properties.

Properties file is loaded via application-context.xml file using

${spring.profiles.active}.properties

and passing in -Dspring.profiles.active flag. This works file for my 3 environments.

For Junit testing I'm trying to use

@ActiveProfiles("test")

in my test class but $(spring.profiles.active) is not resolving. But when I use

System.getProperties().setProperty("spring.profiles.active",
  "test");

it resolved fine.

I know @ActiveProfiles is only for test classes but why doesn't it set the spring.profiles.active property? Does it only affect which beans to use?

This also doesn't clarify who best to handle profiles and property files.
Spring profiles and Testing

Update:
I have so far resorted to using the following in my application context file:

<beans profile="dev,prod">
<context:property-placeholder
      location="classpath:META-INF/properties/generic.properties,
        classpath:META-INF/properties/${spring.profiles.active}/${spring.profiles.active}.properties"/>
        <context:component-scan base-package="com.my.package.to.scan"/>
 </beans>

<beans profile="test">
    <context:property-placeholder
      location="classpath:META-INF/properties/generic.properties,
        classpath:META-INF/properties/test/test.properties"/>
<context:component-scan base-package="com.my.package.to.scan"/>
</beans>

Body:
As the name suggest @ActiveProfiles, this is array of profiles.

/**
 * The bean definition profiles to activate.
 * <p>This attribute may <strong>not</strong> be used in conjunction with
 * {@link #value}, but it may be used <em>instead</em> of {@link #value}.
 */
@AliasFor("value")
String[] profiles() default {};

Try with @ActiveProfiles({"test"}).


问:
PostgreSQL: ERROR: syntax error at or near "clear"
I use psql to connect to the PostgreSQL database on terminal. If I run a simple select query,

```<code>select count(*) from my_schema.my_table;
</code>```

I get the error:
ERROR:  syntax error at or near "clear"
LINE 1: clear

UPDATE:

I cannot even execute a simple select query like select * from my_schema.my_table; or select * from my_table;. It gives me the error:

```<code>ERROR:  relation "my_table" does not exist
LINE 1: select * from my_table;
</code>```

答:
Did you login into right database.

The error 'relation "my_table" does not exist' seems cause by wrong database selection.

For example:
psql -h localhost -p 5435 -U myuser -W <>

Body:
I use psql to connect to the PostgreSQL database on terminal. If I run a simple select query,

select count(*) from my_schema.my_table;

I get the error:
ERROR:  syntax error at or near "clear"
LINE 1: clear

UPDATE:

I cannot even execute a simple select query like select * from my_schema.my_table; or select * from my_table;. It gives me the error:

ERROR:  relation "my_table" does not exist
LINE 1: select * from my_table;


问:
SQL: Consider datatype when multiplying columns
I'm writing on a little c# tool that will change columns of databases. It should also multiply a column by a certain factor according to user input.
Of course it works with

UPDATE table SET column = column * factor

however this doesn't consider the data type of the column, so in case of a wrong user input a column with data type "TEXT" will also be multiplied without any error message resulting in zeros.

I'm aware I could get the type of the column into my c# program and test for it  before updating, however in my case this would be slow and impractical since I'm working only with the information from the sql's I get from

```<code>SELECT * FROM sqlite_master
</code>```

Is there a way to the needed feedback directly within sqlite?

答:
You shoudl use typeof() to filter out non-numeric values as shown in
  this question, eg where typeof(column)= 'integer'

This answer by Panagiotis Kanavos is correct, I actually tried that before but I used capitals (INTEGER vs. integer) for the types which didn't work.

Thx for the answer!

Body:
I'm writing on a little c# tool that will change columns of databases. It should also multiply a column by a certain factor according to user input.
Of course it works with

UPDATE table SET column = column * factor

however this doesn't consider the data type of the column, so in case of a wrong user input a column with data type "TEXT" will also be multiplied without any error message resulting in zeros.

I'm aware I could get the type of the column into my c# program and test for it  before updating, however in my case this would be slow and impractical since I'm working only with the information from the sql's I get from

SELECT * FROM sqlite_master

Is there a way to the needed feedback directly within sqlite?


问:
JavaScript replace all ignoring case sensitivity
I am trying to replace all the occurences of a value in a string and with another value

what I have so far is

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
   result = result.replace(new RegExp(item, 'g'), "" + item + "");
});

console.log(result)```
</div>
</div>
</p>

<p>The result I am after should look like</p>

```result = "Cooker Wors";
```

I am having problems handling the case, Is there any way I can ignore this and still get the result I am after

答:
This will solve your problem

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
     result = result.replace(new RegExp(item, 'ig'), "" + result.match(new RegExp(item, 'ig')) + "");
});

console.log(result)```

Body:
I am trying to replace all the occurences of a value in a string and with another value

what I have so far is

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
   result = result.replace(new RegExp(item, 'g'), "" + item + "");
});

console.log(result)

The result I am after should look like

result = "Cooker Wors";

I am having problems handling the case, Is there any way I can ignore this and still get the result I am after

Body:
This will solve your problem

var result = "Cooker Works"
var searchterm = "cooker wor";

searchterm.split(" ").forEach(function (item) {
     result = result.replace(new RegExp(item, 'ig'), "<strong>" + result.match(new RegExp(item, 'ig')) + "</strong>");
});

console.log(result)


问:
angularJs shift table item index to up or down
I have a table where I would like to change the order or rows by moving an item Up or Down. The element select here(T17180054) with index 3 should move up and have a new index of 2 and keep the selection preferably.

This is my HTML:

```<code><table st-safe-src="flow3.dataSet" st-table="flow3.displayed" class="table table-striped">
    <thead>
        <tr>
            <th st-sort="method">Method</th>
            <th st-sort="sample">Sample</th>
            <th st-sort="parameters">Parameters</th>
        </tr>
    </thead>
    <tbody ui-sortable ng-model="flow3.displayed">
        <tr ng-repeat="row in flow3.displayed track by $index" style="cursor: move;"
            ng-click="row.selected = !row.selected; flow3.selectRow($event, row, index)"
            ng-class="{success: row.selected}">>
            <td>{{row.method.name}}</td>
            <td>{{row.sample}}</td>
            <td>
                <span ng-repeat="parameter in row.parameters">
                    {{parameter.methodInputParameter.name}} : {{parameter.value}}<br/></span>
            </td>
            <td>
                <button type="button" ng-click="flow3.removeItem(row)"
                    class="btn btn-danger btn-sm btn-round pull-right"
                    ng-disabled="flow3.confirmDisabled">
                        <i class="glyphicon glyphicon-trash"></i>
                </button>
            </td>
        </tr>
    </tbody>
</table>
</code>```

This is my two Up and Down buttons

```<code><div class="row">
    <div class="col-xs-6">
        <div class="btn btn-info btn-lg btn-full-width">
            <span class="glyphicon glyphicon-menu-up" ng-click="flow3.moveItemUp();"></span> Up
        </div>
    </div>
    <div class="col-xs-6">
        <div class="btn btn-info btn-lg btn-full-width">
            <span class="glyphicon glyphicon-menu-down" ng-click="flow3.moveItemDown();"></span> Down
        </div>
    </div>
</div>
</code>```

This is my JS :
I have tried to use the splice method by I had wrong results each time.
Is there a better alternative?

```<code>flow3.moveItemDown = function moveItemDown() {
    var index = flow3.dataSet.indexOf(flow3.selectedItem);

    if(index == 0) {
        return;
    } else {
        flow3.dataSet.splice(?, ?, ? , ?)
    }
}
</code>```

答:
You don't need use splice(). you can do it with using array swapping logic

Just use this as a key answer, I don't know it's exactly correct with your code :). I hope this logic will resolve your problem

```<code>//TopToBottom
flow3.moveItemDown = function moveItemDown()
    {
            var fromIndex = flow3.displayed.indexOf(flow3.selectedItem);
            if (fromIndex + 1 > flow3.displayed.length) {
                return false
            }
            var toindexObject = flow3.displayed[fromIndex + 1]
            flow3.displayed[fromIndex + 1] = flow3.selectedItem;
            flow3.displayed[fromIndex] = toindexObject;
    }

//BottomToTop
flow3.moveItemUp = function  moveItemUp() {
            var fromIndex = flow3.displayed.indexOf(flow3.selectedItem);
            if (fromIndex - 1 < flow3.displayed.length) {
                return false
            }
            var toindexObject = flow3.displayed[fromIndex - 1]
            flow3.displayed[fromIndex - 1] = flow3.selectedItem;
            flow3.displayed[fromIndex] = toindexObject;
    }
</code>```

Body:
I have a table where I would like to change the order or rows by moving an item Up or Down. The element select here(T17180054) with index 3 should move up and have a new index of 2 and keep the selection preferably.

This is my HTML:

            Method
            Sample
            Parameters

>
            {{row.method.name}}
            {{row.sample}}

                    {{parameter.methodInputParameter.name}} : {{parameter.value}}

                <button type="button" ng-click="flow3.removeItem(row)"
                    class="btn btn-danger btn-sm btn-round pull-right"
                    ng-disabled="flow3.confirmDisabled">

                </button>

This is my two Up and Down buttons

             Up

             Down

This is my JS :
I have tried to use the splice method by I had wrong results each time.
Is there a better alternative?

flow3.moveItemDown = function moveItemDown() {
    var index = flow3.dataSet.indexOf(flow3.selectedItem);

    if(index == 0) {
        return;
    } else {
        flow3.dataSet.splice(?, ?, ? , ?)
    }
}

Body:
You don't need use splice(). you can do it with using array swapping logic

Just use this as a key answer, I don't know it's exactly correct with your code :). I hope this logic will resolve your problem

//TopToBottom
flow3.moveItemDown = function moveItemDown()
    {
            var fromIndex = flow3.displayed.indexOf(flow3.selectedItem);
            if (fromIndex + 1 > flow3.displayed.length) {
                return false
            }
            var toindexObject = flow3.displayed[fromIndex + 1]
            flow3.displayed[fromIndex + 1] = flow3.selectedItem;
            flow3.displayed[fromIndex] = toindexObject;
    }

//BottomToTop
flow3.moveItemUp = function  moveItemUp() {
            var fromIndex = flow3.displayed.indexOf(flow3.selectedItem);
            if (fromIndex - 1 < flow3.displayed.length) {
                return false
            }
            var toindexObject = flow3.displayed[fromIndex - 1]
            flow3.displayed[fromIndex - 1] = flow3.selectedItem;
            flow3.displayed[fromIndex] = toindexObject;
    }


问:
f-String interpolation not just when run
Is there a way to make it so that the content of a string always depend on an environment variable (and not just interpolated when the line that defines the string is run) ?

I'm probably not clear, so here's an example of what I want

```<code>my_variable = "foo"
my_string = f"The variable is {my_variable}"
print(my_string)

# Output :
</code>```

The answer is foo

```<code>my_variable = "bar"
# Note I'm not doing "my_string = ..." again
print(my_string)

# The desired output :
</code>```

The variable is bar

```<code># The actual output :
</code>```

The variable is foo

答:
Do you mean like this?

```<code>my_variable="foo"
my_string = "a string containing {somevar}".format(somevar=my_variable)
print(my_string)
my_variable="bar"
my_string = "a string containing {somevar}".format(somevar=my_variable)
print(my_string)
</code>```

Returns:

```
a string containing foo
a string containing bar
```

[edit] ahh I see, you want to remove the second explicit re-evaluation of my_string and print out the result as if it had been evaluated?

You could pretend not to re-evaluate the string by defining my_string as a function and feeding it a my_variable parameter. It'll look the way you want, but will be doing the same in the background.

```<code>def my_string(somevar):
    return "a string containing {somevar}".format(somevar=somevar)

my_variable="foo"
print(my_string(my_variable))
my_variable="bar"
#my_string = "a string containing {somevar}".format(somevar=my_variable)
print(my_string(my_variable))
</code>```

Returns:

```
a string containing foo
a string containing bar
```

Body:
Is there a way to make it so that the content of a string always depend on an environment variable (and not just interpolated when the line that defines the string is run) ?

I'm probably not clear, so here's an example of what I want

my_variable = "foo"
my_string = f"The variable is {my_variable}"
print(my_string)

# Output :

The answer is foo

my_variable = "bar"
# Note I'm not doing "my_string = ..." again
print(my_string)

# The desired output :

The variable is bar

# The actual output :

The variable is foo

Body:
Do you mean like this?

my_variable="foo"
my_string = "a string containing {somevar}".format(somevar=my_variable)
print(my_string)
my_variable="bar"
my_string = "a string containing {somevar}".format(somevar=my_variable)
print(my_string)

Returns:

a string containing foo
a string containing bar

[edit] ahh I see, you want to remove the second explicit re-evaluation of my_string and print out the result as if it had been evaluated?

You could pretend not to re-evaluate the string by defining my_string as a function and feeding it a my_variable parameter. It'll look the way you want, but will be doing the same in the background.

def my_string(somevar):
    return "a string containing {somevar}".format(somevar=somevar)

my_variable="foo"
print(my_string(my_variable))
my_variable="bar"
#my_string = "a string containing {somevar}".format(somevar=my_variable)
print(my_string(my_variable))

Returns:

a string containing foo
a string containing bar


问:
Analyzing multiple Json with Tableau
I'm beginning to use Tableau and I have a project involving multiple website logs stored as JSON. I have one log for each day for about a month, each weighting about 500-600 Mb.

Is it possible to open (and join) multiple JSON files in Tableau? If yes, how ? I can load them in parallel, but not join them.
EDIT : I can load multiple JSON files and define their relationship, so this is OK. I still have the memory issue:

I'm am worried that by joining them all, I will not have enough memory to make it work. Are the loaded files stored in RAM of in an internal DB ?

What would be the best way to do this ? Should I merge all the JSON first, or load them in a database and use a connector to Tableau? If so, what could be a good choice of DB?

I'm aware some of these questions are opinion-based, but I have no clue about this and I really need some guideline to get started.

答:
I believe we can join 2 JSON tables in Tableau.

First extract the column names from the JSON data as below--

```<code>select
   get_json_object(JSON_column, '$.Attribute1') as Attribute1,
   get_json_object(line, '$.Attribute2') as Attribute2
   from table_name;
</code>```

perform the above for the required tableau and join them.

Title: Analyzing multiple Json with Tableau

Body:
I believe we can join 2 JSON tables in Tableau.

First extract the column names from the JSON data as below--

select
   get_json_object(JSON_column, '$.Attribute1') as Attribute1,
   get_json_object(line, '$.Attribute2') as Attribute2
   from table_name;

perform the above for the required tableau and join them.


问:
Deferred that extends Promise
How to implement a Deferred promise that extends Promise? It's important to extend Promise for type-safe usage where a typical Promise is expected.

Following implementation

```<code>export class Deferred<T> extends Promise<T> {
  public _resolveSelf;
  public _rejectSelf;
  constructor() {
    super(
      (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject
      }
    )
  }
  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }
}
</code>```

throws TypeError: _this is undefined.

In this Typescript playground, one can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

答:
```<code>export class Deferred<T> implements Promise<T> {

  private _resolveSelf;
  private _rejectSelf;
  private promise: Promise<T>

  constructor() {
    this.promise = new Promise( (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject

      }
    )
  }

  public then<TResult1 = T, TResult2 = never>(
    onfulfilled?: ((value: T) =>
      TResult1 | PromiseLike<TResult1>) | undefined | null,
    onrejected?: ((reason: any) =>
      TResult2 | PromiseLike<TResult2>) | undefined | null
    ): Promise<TResult1 | TResult2> {
      return this.promise.then(onfulfilled, onrejected)
    }

  public catch<TResult = never>(
    onrejected?: ((reason: any) =>
      TResult | PromiseLike<TResult>) | undefined | null
    ): Promise<T | TResult> {
      return this.promise.catch(onrejected)
    }

  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }

  [Symbol.toStringTag]: 'Promise'

}
</code>```

Method signatures of then and catch copy-pasted from Typescript's Promise interface and cosmetically cleaned up. The [Symbol.toStringTag] line is also necessary for Typescript to consider this a Promise, though you only find that out at compile-time.

Title: Deferred that extends Promise

Body:
How to implement a Deferred promise that extends Promise? It's important to extend Promise for type-safe usage where a typical Promise is expected.

Following implementation

export class Deferred<T> extends Promise<T> {
  public _resolveSelf;
  public _rejectSelf;
  constructor() {
    super(
      (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject
      }
    )
  }
  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }
}

throws TypeError: _this is undefined.

In <a href="https://www.typescriptlang.org/play/#src=class%20Deferred%3CT%3E%20extends%20Promise%3CT%3E%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%20%20public%20_resolveSelf%3B%0D%0A%20%20public%20_rejectSelf%3B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%20%20constructor()%20%7B%0D%0A%20%20%20%20super(%0D%0A%20%20%20%20%20%20(resolve%2C%20reject)%20%3D%3E%0D%0A%20%20%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%20%20this._resolveSelf%20%3D%20resolve%0D%0A%20%20%20%20%20%20%20%20this._rejectSelf%20%3D%20reject%0D%0A%20%20%20%20%20%20%7D%0D%0A%20%20%20%20)%0D%0A%20%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%20%20public%20resolve(val%3AT)%20%7B%20this._resolveSelf(val)%20%7D%0D%0A%20%20public%20reject(reason%3Aany)%20%7B%20this._rejectSelf(reason)%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%7D%0D%0A%0D%0Aconst%20d%20%3D%20new%20Deferred%0D%0A%0D%0Ad.then(console.log)%0D%0A%0D%0Ad.resolve(10)" rel="noreferrer">this Typescript playground, one can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

Body:
export class Deferred<T> implements Promise<T> {

  private _resolveSelf;
  private _rejectSelf;
  private promise: Promise<T>

  constructor() {
    this.promise = new Promise( (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject

      }
    )
  }

  public then<TResult1 = T, TResult2 = never>(
    onfulfilled?: ((value: T) =>
      TResult1 | PromiseLike<TResult1>) | undefined | null,
    onrejected?: ((reason: any) =>
      TResult2 | PromiseLike<TResult2>) | undefined | null
    ): Promise<TResult1 | TResult2> {
      return this.promise.then(onfulfilled, onrejected)
    }

  public catch<TResult = never>(
    onrejected?: ((reason: any) =>
      TResult | PromiseLike<TResult>) | undefined | null
    ): Promise<T | TResult> {
      return this.promise.catch(onrejected)
    }

  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }

  [Symbol.toStringTag]: 'Promise'

}

Method signatures of then and catch copy-pasted from Typescript's Promise interface and cosmetically cleaned up. The [Symbol.toStringTag] line is also necessary for Typescript to consider this a Promise, though you only find that out at compile-time.


问:
Switch from dyadic to monadic interpretation in a J sentence
I am trying to understand composition in J, after struggling to mix and match different phases. I would like help switching between monadic and dyadic phrases in the same sentence.

I just made a simple dice roller in J, which will serve as an example:

```<code>   d=.1+[:?[#]
   4 d 6
2 3 1 1
   8 d 12
10 2 11 11 5 11 1 10
</code>```

This is a chain: "d is one plus the (capped) roll of x occurrences of y"

But what if I wanted to use >: to increment (and skip the cap [: ), such that it "switched" to monadic interpretation after the first fork?
It would read: "d is the incremented roll of x occurrences of y".

Something like this doesn't work, even though it looks to me to have about the right structure:

```<code>   d=.>:&?[#]
   d
>:&? ([ # ])
</code>```

(If this approach is against the grain for J and I should stick to capped forks, that is also useful information.)

答:
To summarize the main simple patterns of verb mixing in J:

```<code>          (f @: g) y    =    f (g y)             NB. (1) monadic "at"
        x (f @: g) y    =    f (x g y)           NB. (2) dyadic "at"
        x (f &: g) y    =    (g x) f (g y)       NB. (3) "appose"
          (f g h)  y    =    (f y) g (h y)       NB. (4) monadic fork
        x (f g h)  y    =  (x f y) g (x h y)     NB. (5) dyadic  fork
            (f g)  y    =       y  f (g y)       NB. (6) monadic hook
          x (f g)  y    =       x  f (g y)       NB. (7) dyadic  hook
</code>```

A nice review of those is here (compositions) and here (trains).

Usually there are many possible forms for a verb. To complicate matters more, you can mix many primitives in different ways to achieve to same result.

Experience, style, performance and other such factors influence the way you'll combine the above to form your verb.

In this particular case, I would use @bob's d1 because I find it clearer to read: increase the roll of x copies of y:

```<code>>: @ ? @ $
</code>```

For the same reason, I am replacing # with $. When I see # in this context, I automatically read "number of elements of", but maybe that's just me.

Body:
I am trying to understand composition in J, after struggling to mix and match different phases. I would like help switching between monadic and dyadic phrases in the same sentence.

I just made a simple dice roller in J, which will serve as an example:

   d=.1+[:?[#]
   4 d 6
2 3 1 1
   8 d 12
10 2 11 11 5 11 1 10

This is a chain: "d is one plus the (capped) roll of x occurrences of y"

But what if I wanted to use >: to increment (and skip the cap [: ), such that it "switched" to monadic interpretation after the first fork?
It would read: "d is the incremented roll of x occurrences of y".

Something like this doesn't work, even though it looks to me to have about the right structure:

   d=.>:&?[#]
   d
>:&? ([ # ])

(If this approach is against the grain for J and I should stick to capped forks, that is also useful information.)

Body:
To summarize the main simple patterns of verb mixing in J:

          (f @: g) y    =    f (g y)             NB. (1) monadic "at"
        x (f @: g) y    =    f (x g y)           NB. (2) dyadic "at"
        x (f &: g) y    =    (g x) f (g y)       NB. (3) "appose"
          (f g h)  y    =    (f y) g (h y)       NB. (4) monadic fork
        x (f g h)  y    =  (x f y) g (x h y)     NB. (5) dyadic  fork
            (f g)  y    =       y  f (g y)       NB. (6) monadic hook
          x (f g)  y    =       x  f (g y)       NB. (7) dyadic  hook

A nice review of those is here (compositions) and here (trains).

Usually there are many possible forms for a verb. To complicate matters more, you can mix many primitives in different ways to achieve to same result.

Experience, style, performance and other such factors influence the way you'll combine the above to form your verb.

In this particular case, I would use @bob's d1 because I find it clearer to read: increase the roll of x copies of y:

>: @ ? @ $

For the same reason, I am replacing # with $. When I see # in this context, I automatically read "number of elements of", but maybe that's just me.


问:
PyQt5 pip installation error 13. Permission denied
I'm trying to install PyQt5 with the command pip install PyQt5

but I get an error instead.

I use Python 3.5, windows 10.

error:

```<code>C:\WINDOWS\system32>pip install PyQt5

Collecting PyQt5
  Using cached PyQt5-5.7-cp35-none-win_amd64.whl
Collecting sip (from PyQt5)
  Using cached sip-4.18.1-cp35-none-win_amd64.whl
Installing collected packages: sip, PyQt5
Exception:
Traceback (most recent call last):
  File "c:\anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\anaconda3\lib\site-packages\pip\commands\install.py", line 317, in run
    prefix=options.prefix_path,
  File "c:\anaconda3\lib\site-packages\pip\req\req_set.py", line 742, in install
    **kwargs
  File "c:\anaconda3\lib\site-packages\pip\req\req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\anaconda3\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "c:\anaconda3\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
    clobber(source, lib_dir, True)
  File "c:\anaconda3\lib\site-packages\pip\wheel.py", line 324, in clobber
    shutil.copyfile(srcfile, destfile)
  File "c:\anaconda3\lib\shutil.py", line 115, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'c:\\anaconda3\\Lib\\site-packages\\sip.pyd'
</code>```

答: Run the cmd window as administrator (https://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx)</p>

Body:
I'm trying to install PyQt5 with the command pip install PyQt5

but I get an error instead.

I use Python 3.5, windows 10.

error:

C:\WINDOWS\system32>pip install PyQt5

Collecting PyQt5
  Using cached PyQt5-5.7-cp35-none-win_amd64.whl
Collecting sip (from PyQt5)
  Using cached sip-4.18.1-cp35-none-win_amd64.whl
Installing collected packages: sip, PyQt5
Exception:
Traceback (most recent call last):
  File "c:\anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\anaconda3\lib\site-packages\pip\commands\install.py", line 317, in run
    prefix=options.prefix_path,
  File "c:\anaconda3\lib\site-packages\pip\req\req_set.py", line 742, in install
    **kwargs
  File "c:\anaconda3\lib\site-packages\pip\req\req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\anaconda3\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "c:\anaconda3\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
    clobber(source, lib_dir, True)
  File "c:\anaconda3\lib\site-packages\pip\wheel.py", line 324, in clobber
    shutil.copyfile(srcfile, destfile)
  File "c:\anaconda3\lib\shutil.py", line 115, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'c:\\anaconda3\\Lib\\site-packages\\sip.pyd'


问:
Why/when is __declspec( dllimport ) not needed?
In a project using a server.dll and a client.exe, I have dllexported a server symbol from the server dll, and not dllimported it into the client exe.

Still, the application links, and starts, without any problem.  Is dllimport not needed, then???

Details:

I have this 'server' dll:

```<code>// server.h
#ifdef SERVER_EXPORTS
  #define SERVER_API __declspec(dllexport)
#else
  #define SERVER_API // =====> not using dllimport!
#endif
class  SERVER_API CServer {
   static long s;
   public:
   CServer();
};

// server.cpp
CServer::CServer(){}

long CServer::s;
</code>```

and this client executable:

```<code>#include <server.h>
int main() {
   CServer s;
}
</code>```

The server command line:

```<code>cl.exe /Od  /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_USRDLL"
 /D "SERVER_EXPORTS" /D "_UNICODE" /D "UNICODE" /D "_WINDLL"
 /Gm /EHsc /RTC1 /MDd /Yu"stdafx.h"
 /Fp"Debug\server.pch" /Fo"Debug\\" /Fd"Debug\vc80.pdb"
 /W3 /nologo /c /Wp64 /ZI /TP /errorReport:prompt

cl.exe /OUT:"U:\libs\Debug\server.dll" /INCREMENTAL:NO /NOLOGO /DLL
/MANIFEST /MANIFESTFILE:"Debug\server.dll.intermediate.manifest"
/DEBUG /PDB:"u:\libs\Debug\server.pdb"
/SUBSYSTEM:WINDOWS /MACHINE:X86 /ERRORREPORT:PROMPT
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib
shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
</code>```

Client command line:

```<code>cl.exe /Od /I "..\server"
 /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE"
 /Gm /EHsc /RTC1 /MDd /Fo"Debug\\" /Fd"Debug\vc80.pdb" /W3 /c /Wp64 /ZI /TP
 .\client.cpp

cl.exe /OUT:"U:\libs\Debug\Debug\client.exe" /INCREMENTAL
/LIBPATH:"U:\libs\Debug"
/MANIFEST /MANIFESTFILE:"Debug\client.exe.intermediate.manifest"
/DEBUG /PDB:"u:\libs\debug\debug\client.pdb"
/SUBSYSTEM:CONSOLE /MACHINE:X86
server.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
</code>```

答:
__declspec(dllimport) is a client-side MSVC attribute that can be specified for imported code and data.

It isn't required for code.  It is an optimization; a client-side compiler hint that a function call isn't direct but imported.  The imported function pointer for a function named foo() will be __imp_foo.  Without the hint, a thunk is created to load the address in __imp_foo and jump to it.  With the hint the thunk is skipped and an indirect call through the IAT1 entry is generated i.e. the thunk is inlined.  It is a time optimization, not space.

It's required for data that's imported from a DLL.

This blog post has the details.

1: Import Address Table of a program

ContentLicense: CC BY-SA 2.5

Body:
In a project using a server.dll and a client.exe, I have dllexported a server symbol from the server dll, and not dllimported it into the client exe.

Still, the application links, and starts, without any problem.  Is dllimport not needed, then???

Details:

I have this 'server' dll:

// server.h
#ifdef SERVER_EXPORTS
  #define SERVER_API __declspec(dllexport)
#else
  #define SERVER_API // =====> not using dllimport!
#endif
class  SERVER_API CServer {
   static long s;
   public:
   CServer();
};

// server.cpp
CServer::CServer(){}

long CServer::s;

and this client executable:

#include <server.h>
int main() {
   CServer s;
}

The server command line:

cl.exe /Od  /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_USRDLL"
 /D "SERVER_EXPORTS" /D "_UNICODE" /D "UNICODE" /D "_WINDLL"
 /Gm /EHsc /RTC1 /MDd /Yu"stdafx.h"
 /Fp"Debug\server.pch" /Fo"Debug\\" /Fd"Debug\vc80.pdb"
 /W3 /nologo /c /Wp64 /ZI /TP /errorReport:prompt

cl.exe /OUT:"U:\libs\Debug\server.dll" /INCREMENTAL:NO /NOLOGO /DLL
/MANIFEST /MANIFESTFILE:"Debug\server.dll.intermediate.manifest"
/DEBUG /PDB:"u:\libs\Debug\server.pdb"
/SUBSYSTEM:WINDOWS /MACHINE:X86 /ERRORREPORT:PROMPT
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib
shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib

Client command line:

cl.exe /Od /I "..\server"
 /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE"
 /Gm /EHsc /RTC1 /MDd /Fo"Debug\\" /Fd"Debug\vc80.pdb" /W3 /c /Wp64 /ZI /TP
 .\client.cpp

cl.exe /OUT:"U:\libs\Debug\Debug\client.exe" /INCREMENTAL
/LIBPATH:"U:\libs\Debug"
/MANIFEST /MANIFESTFILE:"Debug\client.exe.intermediate.manifest"
/DEBUG /PDB:"u:\libs\debug\debug\client.pdb"
/SUBSYSTEM:CONSOLE /MACHINE:X86
server.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib


问:
Reshape 59x16 double into 236x4?
How can I reshape a matrix in MATLAB, preferably using reshape?

A simple matrix setup:

```<code>A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
</code>```

that I want to reshape into

```<code>B = [1 4; 2 5; 3 6; 7 10; 8 11; 9 12]
</code>```

I've tried numerous settings of reshape, but I cannot figure it out.

```<code>1 2 3 4
5 6 7 8
</code>```

reshaped into

```<code>1 2
5 6
3 4
7 8
</code>```

答:
```<code>B = A(:,1:end/2);
B = [B;A(:,end/2+1:end)];

C = B(:,1:end/2);
C = [C;B(:,end/2+1:end)];
</code>```

Maybe it can be done in a simpler way, but seems to work.

Title: Reshape 59x16 double into 236x4?

Body:
How can I reshape a matrix in MATLAB, preferably using reshape?

A simple matrix setup:

A = [1 4 7 10; 2 5 8 11; 3 6 9 12]

that I want to reshape into

B = [1 4; 2 5; 3 6; 7 10; 8 11; 9 12]

I've tried numerous settings of reshape, but I cannot figure it out.

1 2 3 4
5 6 7 8

reshaped into

1 2
5 6
3 4
7 8

Body:
B = A(:,1:end/2);
B = [B;A(:,end/2+1:end)];

C = B(:,1:end/2);
C = [C;B(:,end/2+1:end)];

Maybe it can be done in a simpler way, but seems to work.


问:
JSON.parse() a wrong string
I have a string that I obtain via a user, so it is not guaranteed to be a correct JSON string format.

This problem may cause the rest of the js code to be stop.

Consider the following example:

```<code>var a='==wrong string===';
var b=JSON.parse(a);
alert(1); //will not implemented
</code>```

How to avoid this problem?

答:
You can use try catch block:

var a='==wrong string===';
try{
  var b=JSON.parse(a);
 }catch(e){
  console.log(e.message); /*use e.message to get the exact error */
 }
alert(1)```

Title: JSON.parse() a wrong string

Body:
I have a string that I obtain via a user, so it is not guaranteed to be a correct JSON string format.

This problem may cause the rest of the js code to be stop.

Consider the following example:

var a='==wrong string===';
var b=JSON.parse(a);
alert(1); //will not implemented

How to avoid this problem?


问:
IdentityServer4 client - Refreshing access tokens on CookieAuthenticationEvents
I am trying to use refresh token when the access token expires. A similar so question is answered here. And a sample code to renew token by an action

And i end up with the following code in the startup.cs

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookies",
    //ExpireTimeSpan = TimeSpan.FromSeconds(100),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Events = new CookieAuthenticationEvents()
    {
        OnValidatePrincipal = async x =>
        {
            if (x.Properties?.Items[".Token.expires_at"] == null) return;

            var logger = loggerFactory.CreateLogger(this.GetType());

            var now = DateTimeOffset.UtcNow;
            var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
            var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
            var timeRemaining = tokenExpireTime.Subtract(now.DateTime);

            if (timeElapsed > timeRemaining)
            {
                var httpContextAuthentication = x.HttpContext.Authentication;//Donot use the HttpContext.Authentication to retrieve anything, this cause recursive call to this event
                var oldAccessToken = await httpContextAuthentication.GetTokenAsync("access_token");
                var oldRefreshToken = await httpContextAuthentication.GetTokenAsync("refresh_token");
                logger.LogInformation($"Refresh token :{oldRefreshToken}, old access token:{oldAccessToken}");

                var disco = await DiscoveryClient.GetAsync(AuthorityServer);
                if (disco.IsError) throw new Exception(disco.Error);

                var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
                var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);
                logger.LogInformation("Refresh token requested. " + tokenResult.ErrorDescription);

                if (!tokenResult.IsError)
                {

                    var oldIdToken = await httpContextAuthentication.GetTokenAsync("id_token");
                    var newAccessToken = tokenResult.AccessToken;
                    var newRefreshToken = tokenResult.RefreshToken;

                    var tokens = new List<AuthenticationToken>
                    {
                        new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
                        new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
                        new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
                    };

                    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
                    tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });

                    var info = await httpContextAuthentication.GetAuthenticateInfoAsync("Cookies");
                    info.Properties.StoreTokens(tokens);
                    await httpContextAuthentication.SignInAsync("Cookies", info.Principal, info.Properties);

                }
                x.ShouldRenew = true;
            }
            else
            {
                logger.LogInformation("Not expired");
            }
        }

    }
});
</code>```

The client setup is as follows

```<code>AllowAccessTokensViaBrowser = true,
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
AbsoluteRefreshTokenLifetime = 86400,
AccessTokenLifetime = 10,
AllowOfflineAccess = true,
AccessTokenType = AccessTokenType.Reference
</code>```

After successfully login, i am getting a 401 for every other request. And the log says

[Identity Server]2017-07-04 10:15:58.819 +01:00 [Debug]
  "TjpIkvHQi../cfivu6Nql5ADJJlZRuoJV1QI=" found in database: True

[Identity Server]2017-07-04 10:15:58.820 +01:00 [Debug]
  "reference_token" grant with value:
  "..9e64c1235c6675fcef617914911846fecd72f7b372" found in store, but has
  expired.

[Identity Server]2017-07-04 10:15:58.821 +01:00 [Error] Invalid
  reference token. "{   \"ValidateLifetime\": true,

  \"AccessTokenType\": \"Reference\",   \"TokenHandle\":
  \"..9e64c1235c6675fcef617914911846fecd72f7b372\" }"

[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Token is
  invalid.

[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Creating
  introspection response for inactive token.

[Identity Server]2017-07-04 10:15:58.822 +01:00 [Information] Success
  token introspection. Token status: "inactive", for API name: "api1"

Any help would by highly appreciated

UPDATE:

Basically, when the token expires i get a System.StackOverflowException on the following line

```<code>var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
</code>```

UPDATE 2:
Do not use HttpContext.Authentication to retrieve anything. Check my answer below to find the working implementaion

答:
I was working on this for last two days and could not make this work. Funnily, after posting the question here, within 2 hours I make it working :)

```<code>Events = new CookieAuthenticationEvents()
{
    OnValidatePrincipal = async x =>
    {
        if (x.Properties?.Items[".Token.expires_at"] == null) return;
        var now = DateTimeOffset.UtcNow;

        var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
        var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
        var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
        WriteMessage($"{timeRemaining} and elapsed at {timeElapsed}");
        if (timeElapsed > timeRemaining)
        {
            var oldAccessToken = x.Properties.Items[".Token.access_token"];

            var oldRefreshToken = x.Properties.Items[".Token.refresh_token"];
            WriteMessage($"Refresh token :{oldRefreshToken}, old access token {oldAccessToken}");

            var disco = await DiscoveryClient.GetAsync(AuthorityServer);
            if (disco.IsError) throw new Exception(disco.Error);

            var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
            var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);

            if (!tokenResult.IsError)
            {
                var oldIdToken = x.Properties.Items[".Token.id_token"];//tokenResult.IdentityToken

                var newAccessToken = tokenResult.AccessToken;
                var newRefreshToken = tokenResult.RefreshToken;

                var tokens = new List<AuthenticationToken>
                {
                    new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
                    new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
                    new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
                };

                var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
                tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });

                x.Properties.StoreTokens(tokens);

                WriteMessage($"oldAccessToken: {oldAccessToken}{Environment.NewLine} and new access token {newAccessToken}");

            }
            x.ShouldRenew = true;
        }
    }
}
</code>```

Basically httpContextAuthentication.GetTokenAsync make this recursive, for that reason StackOverflowException occured.

Please let me know if this implementation has any issue

Body:
I am trying to use refresh token when the access token expires. A similar so question is answered here. And a sample code to renew token by an action

And i end up with the following code in the startup.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookies",
    //ExpireTimeSpan = TimeSpan.FromSeconds(100),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Events = new CookieAuthenticationEvents()
    {
        OnValidatePrincipal = async x =>
        {
            if (x.Properties?.Items[".Token.expires_at"] == null) return;

            var logger = loggerFactory.CreateLogger(this.GetType());

            var now = DateTimeOffset.UtcNow;
            var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
            var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
            var timeRemaining = tokenExpireTime.Subtract(now.DateTime);

            if (timeElapsed > timeRemaining)
            {
                var httpContextAuthentication = x.HttpContext.Authentication;//Donot use the HttpContext.Authentication to retrieve anything, this cause recursive call to this event
                var oldAccessToken = await httpContextAuthentication.GetTokenAsync("access_token");
                var oldRefreshToken = await httpContextAuthentication.GetTokenAsync("refresh_token");
                logger.LogInformation($"Refresh token :{oldRefreshToken}, old access token:{oldAccessToken}");

                var disco = await DiscoveryClient.GetAsync(AuthorityServer);
                if (disco.IsError) throw new Exception(disco.Error);

                var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
                var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);
                logger.LogInformation("Refresh token requested. " + tokenResult.ErrorDescription);

                if (!tokenResult.IsError)
                {

                    var oldIdToken = await httpContextAuthentication.GetTokenAsync("id_token");
                    var newAccessToken = tokenResult.AccessToken;
                    var newRefreshToken = tokenResult.RefreshToken;

                    var tokens = new List<AuthenticationToken>
                    {
                        new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
                        new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
                        new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
                    };

                    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
                    tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });

                    var info = await httpContextAuthentication.GetAuthenticateInfoAsync("Cookies");
                    info.Properties.StoreTokens(tokens);
                    await httpContextAuthentication.SignInAsync("Cookies", info.Principal, info.Properties);

                }
                x.ShouldRenew = true;
            }
            else
            {
                logger.LogInformation("Not expired");
            }
        }

    }
});

The client setup is as follows

AllowAccessTokensViaBrowser = true,
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
AbsoluteRefreshTokenLifetime = 86400,
AccessTokenLifetime = 10,
AllowOfflineAccess = true,
AccessTokenType = AccessTokenType.Reference

After successfully login, i am getting a 401 for every other request. And the log says

[Identity Server]2017-07-04 10:15:58.819 +01:00 [Debug]
  "TjpIkvHQi../cfivu6Nql5ADJJlZRuoJV1QI=" found in database: True

[Identity Server]2017-07-04 10:15:58.820 +01:00 [Debug]
  "reference_token" grant with value:
  "..9e64c1235c6675fcef617914911846fecd72f7b372" found in store, but has
  expired.

[Identity Server]2017-07-04 10:15:58.821 +01:00 [Error] Invalid
  reference token. "{   \"ValidateLifetime\": true,

  \"AccessTokenType\": \"Reference\",   \"TokenHandle\":
  \"..9e64c1235c6675fcef617914911846fecd72f7b372\" }"

[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Token is
  invalid.

[Identity Server]2017-07-04 10:15:58.822 +01:00 [Debug] Creating
  introspection response for inactive token.

[Identity Server]2017-07-04 10:15:58.822 +01:00 [Information] Success
  token introspection. Token status: "inactive", for API name: "api1"

Any help would by highly appreciated

UPDATE:

Basically, when the token expires i get a System.StackOverflowException on the following line

var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();

UPDATE 2:
Do not use HttpContext.Authentication to retrieve anything. Check my answer below to find the working implementaion

Body:
I was working on this for last two days and could not make this work. Funnily, after posting the question here, within 2 hours I make it working :)

Events = new CookieAuthenticationEvents()
{
    OnValidatePrincipal = async x =>
    {
        if (x.Properties?.Items[".Token.expires_at"] == null) return;
        var now = DateTimeOffset.UtcNow;

        var tokenExpireTime = DateTime.Parse(x.Properties.Items[".Token.expires_at"]).ToUniversalTime();
        var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
        var timeRemaining = tokenExpireTime.Subtract(now.DateTime);
        WriteMessage($"{timeRemaining} and elapsed at {timeElapsed}");
        if (timeElapsed > timeRemaining)
        {
            var oldAccessToken = x.Properties.Items[".Token.access_token"];

            var oldRefreshToken = x.Properties.Items[".Token.refresh_token"];
            WriteMessage($"Refresh token :{oldRefreshToken}, old access token {oldAccessToken}");

            var disco = await DiscoveryClient.GetAsync(AuthorityServer);
            if (disco.IsError) throw new Exception(disco.Error);

            var tokenClient = new TokenClient(disco.TokenEndpoint, ApplicationId, "secret");
            var tokenResult = await tokenClient.RequestRefreshTokenAsync(oldRefreshToken);

            if (!tokenResult.IsError)
            {
                var oldIdToken = x.Properties.Items[".Token.id_token"];//tokenResult.IdentityToken

                var newAccessToken = tokenResult.AccessToken;
                var newRefreshToken = tokenResult.RefreshToken;

                var tokens = new List<AuthenticationToken>
                {
                    new AuthenticationToken {Name = OpenIdConnectParameterNames.IdToken, Value = oldIdToken},
                    new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken},
                    new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken}
                };

                var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
                tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });

                x.Properties.StoreTokens(tokens);

                WriteMessage($"oldAccessToken: {oldAccessToken}{Environment.NewLine} and new access token {newAccessToken}");

            }
            x.ShouldRenew = true;
        }
    }
}

Basically httpContextAuthentication.GetTokenAsync make this recursive, for that reason StackOverflowException occured.

Please let me know if this implementation has any issue


问:
Binding to collection that exist in other collection
I have ListBox that has binding to the collection (Publishers), every publisher has a name and collection of authors in it, every author has a name. So how can I provide binding to author's name?

```<code><TextBlock Text="{Binding name}" Grid.Column="1" Grid.Row="1"></TextBlock>
<TextBlock Text="{Binding city}" Grid.Column="1" Grid.Row="0"></TextBlock>
</code>```

It is binding to a publisher's name and city.

答:
```<code><ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding name}"></TextBlock>
                <ListBox ItemsSource="{Binding authors}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                             <TextBlock Text="{Binding name}"></TextBlock>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

This will show name of a publisher with a list of all its authors for every publisher. I assumed a publisher has a property named authors that returns IEnumerable<Author>

Body:
I have ListBox that has binding to the collection (Publishers), every publisher has a name and collection of authors in it, every author has a name. So how can I provide binding to author's name?

<TextBlock Text="{Binding name}" Grid.Column="1" Grid.Row="1"></TextBlock>
<TextBlock Text="{Binding city}" Grid.Column="1" Grid.Row="0"></TextBlock>

It is binding to a publisher's name and city.

Body:
<ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding name}"></TextBlock>
                <ListBox ItemsSource="{Binding authors}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                             <TextBlock Text="{Binding name}"></TextBlock>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This will show name of a publisher with a list of all its authors for every publisher. I assumed a publisher has a property named authors that returns IEnumerable<Author>