问:
Proper return type for Redux action
This typing sort of works, but for some reason the promise that dispatch() is supposed to return is not defined:

So instead of using ThunkAction<any,any,any,any> is there a better type I can use perhaps? Or maybe ThunkAction is the wrong type altogether?

Here is all my code:

```<code>import {ThunkAction, ThunkDispatch} from 'redux-thunk';
const {setLanguage} = require('redux-polyglot');
import {CMError} from '../shared/cm-error';
import {receiveCurrentUser} from './login';

export const signup = (
  email: string,
  pwd: string,
  fullName: string
): ThunkAction<any, any, any, any> => {

  return (dispatch) => {

    return fetchFromApi(`/cp/users`, {
      method: 'POST',
      body: {
        email: email,
        password: pwd,
        name: fullName
      }
    }).then(
      ([resp, json]) => {

        if (resp.status === 200) {
          return dispatch(receiveCurrentUser(json));
        }
      })
    );
  };
};
</code>```

I don't see a mention of this in the react-redux TS docs:
https://react-redux.js.org/using-react-redux/static-typing

答:
That's because thunks are not part of React-Redux - they're a separate middleware that's added to the Redux core.

We cover typing thunks in the Redux core docs "Usage with TypeScript" page, and in the Redux Toolkit "Advanced Tutorial" page.

Specifically for your case, the first generic argument to ThunkAction is the expected return type of the thunk.  So, it should look something like:

```<code>ThunkAction<Promise<SomeValue>, RootState, unknown, Action<String>>
</code>```

and that should be applied to the definition of getCurrentUser().

Title: Proper return type for Redux action

Body:
This typing sort of works, but for some reason the promise that dispatch() is supposed to return is not defined:

So instead of using ThunkAction<any,any,any,any> is there a better type I can use perhaps? Or maybe ThunkAction is the wrong type altogether?

Here is all my code:

import {ThunkAction, ThunkDispatch} from 'redux-thunk';
const {setLanguage} = require('redux-polyglot');
import {CMError} from '../shared/cm-error';
import {receiveCurrentUser} from './login';

export const signup = (
  email: string,
  pwd: string,
  fullName: string
): ThunkAction<any, any, any, any> => {

  return (dispatch) => {

    return fetchFromApi(`/cp/users`, {
      method: 'POST',
      body: {
        email: email,
        password: pwd,
        name: fullName
      }
    }).then(
      ([resp, json]) => {

        if (resp.status === 200) {
          return dispatch(receiveCurrentUser(json));
        }
      })
    );
  };
};

I don't see a mention of this in the react-redux TS docs:
https://react-redux.js.org/using-react-redux/static-typing

Body:
That's because thunks are not part of React-Redux - they're a separate middleware that's added to the Redux core.

We cover typing thunks in the Redux core docs "Usage with TypeScript" page, and in the Redux Toolkit "Advanced Tutorial" page.

Specifically for your case, the first generic argument to ThunkAction is the expected return type of the thunk.  So, it should look something like:

ThunkAction<Promise<SomeValue>, RootState, unknown, Action<String>>

and that should be applied to the definition of getCurrentUser().


来源: stackexchange

问:
using lstm to predict and have only one answer
I have implemented an emotion analysis using lstm form https://www.kaggle.com/eray1yildiz/using-lstms-with-attention-for-emotion-recognition/comments

I am having wrong predictions as well as I am having a list of results as shown below:

```<code>['enjoy', 'lovely', 'moment']
{'joy': 0.18797465, 'satisfied': 0.19864388, 'happy': 0.18680806, 'sad': 0.20265724, 'disappointment': 0.22391614}
</code>```

Below is the part of codes I am using for prediction:

```<code>
      # Padding
      encoded_samples = keras.preprocessing.sequence.pad_sequences(encoded_samples, maxlen=max_words)

      # Make predictions
      label_probs, attentions = model_with_attentions.predict(encoded_samples)
      label_probs = {id2label[_id]: prob for (label, _id), prob in zip(label2id.items(), label_probs[0])}
</code>```

I want my output to be like this:

```<code>Input: ['enjoy', 'lovely', 'moment']
Output: 'joy'
</code>```

Is it possible to do this? please help me guys..

答:
The wrong predictions are associated to the model training, however you can get a unique result by using the argmax() method to your predict result (as described here https://github.com/keras-team/keras/issues/5910). Without knowing the shape of encoded_sample I would guess that you need something like this:

```<code>label_probs = model_with_attentions.predict(encoded_samples)
label_pred= label_probs.argmax(axis=-1)
</code>```

Note that here it will predict disappointment in your example.

ContentLicense: CC BY-SA 4.0

Body:
I have implemented an emotion analysis using lstm form https://www.kaggle.com/eray1yildiz/using-lstms-with-attention-for-emotion-recognition/comments

I am having wrong predictions as well as I am having a list of results as shown below:

['enjoy', 'lovely', 'moment']
{'joy': 0.18797465, 'satisfied': 0.19864388, 'happy': 0.18680806, 'sad': 0.20265724, 'disappointment': 0.22391614}

Below is the part of codes I am using for prediction:

      # Padding
      encoded_samples = keras.preprocessing.sequence.pad_sequences(encoded_samples, maxlen=max_words)

      # Make predictions
      label_probs, attentions = model_with_attentions.predict(encoded_samples)
      label_probs = {id2label[_id]: prob for (label, _id), prob in zip(label2id.items(), label_probs[0])}

I want my output to be like this:

Input: ['enjoy', 'lovely', 'moment']
Output: 'joy'

Is it possible to do this? please help me guys..

Body:
The wrong predictions are associated to the model training, however you can get a unique result by using the argmax() method to your predict result (as described here https://github.com/keras-team/keras/issues/5910). Without knowing the shape of encoded_sample I would guess that you need something like this:

label_probs = model_with_attentions.predict(encoded_samples)
label_pred= label_probs.argmax(axis=-1)

Note that here it will predict disappointment in your example.


问:
Why the Debug.Assert show the error message even if the Length is 1 all the time?
```<code>private GameObject GetDoorShaderPrefab()
    {
        string[] shieldPrefab = AssetDatabase.FindAssets(c_doorShieldFxLocked);
        Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");
        string shieldGuid = shieldPrefab[0];
        string prefabPath = AssetDatabase.GUIDToAssetPath(shieldGuid);
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
        Debug.Assert(prefab != null, "Expected prefab to load");
        return prefab;
    }
</code>```

I used a break point on the line :

```<code>Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");
</code>```

The Length of shieldPrefab is all the time 1 but it's still showing the error message "Expected exactly 1 shield like this..."

The method GetDoorShaderPrefab is being called many times in other place in the script. But each time the Length is 1 and it keep showing the error message.

答:
I think your condition should be == 1
so:

```<code>Debug.Assert(shieldPrefab.Length == 1, "Expected exactly 1 shield like this...");
</code>```

The message is displayed when the condition is false. From the docs:

Assert(Boolean, String)

Checks for a condition; if the condition is false, outputs a specified message and displays a message box that shows the call stack.

The idea is that the asserts checks some conditions and it will only complain is your assertion is wrong.

To remember it easily, the condition and text should tell you the same, not the opposite.

Body:
private GameObject GetDoorShaderPrefab()
    {
        string[] shieldPrefab = AssetDatabase.FindAssets(c_doorShieldFxLocked);
        Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");
        string shieldGuid = shieldPrefab[0];
        string prefabPath = AssetDatabase.GUIDToAssetPath(shieldGuid);
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
        Debug.Assert(prefab != null, "Expected prefab to load");
        return prefab;
    }

I used a break point on the line :

Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");

The Length of shieldPrefab is all the time 1 but it's still showing the error message "Expected exactly 1 shield like this..."

The method GetDoorShaderPrefab is being called many times in other place in the script. But each time the Length is 1 and it keep showing the error message.

Body:
I think your condition should be == 1
so:

Debug.Assert(shieldPrefab.Length == 1, "Expected exactly 1 shield like this...");

The message is displayed when the condition is false. From the docs:

Assert(Boolean, String)

Checks for a condition; if the condition is false, outputs a specified message and displays a message box that shows the call stack.

The idea is that the asserts checks some conditions and it will only complain is your assertion is wrong.

To remember it easily, the condition and text should tell you the same, not the opposite.


问:
ISFORMULA function conditional formatting, exclude formulas that contain specific phrase
I have a spreadsheet where I would like to highlight cells when a user enters a formula in a cell.

The issue I have is there are other cells that contain formulas in the same range. The Formula in particular is this one =SUMIFS(B13:B99,AB13:AB99,TRUE) The cell ranges can change, but the rest will not.

I would like to set up conditional formatting that says, If the cell contains the SUMIF string, then do not apply the conditional formatting.

The user will just be entering simple formulas. Ex =10,000*1.34, or =5,733+2,000+1,000. They could be putting in addition, subtraction, multiplication, division and parentheses. I don't think they would need any more functionality. So we could also use those variables as well.

The reason I cannot just manually do this, is because the sheet is dynamic and imports data. The locations of the cells I do not want to highlight are always changing.

I am open to using VBA or just regular old Excel formulas.

My current formula is simply =ISFORMULA(B11:B99) and it returns a value of true or false. How can I write a condition to say, if there is a formula that does not contain SUMIF, return true, else false?

答:
You can use FORMULATEXT in your condition:

```<code>=NOT(ISNUMBER(SEARCH("SUMIFS",FORMULATEXT(G6))))
</code>```

This will basically look for "SUMIFS" in the text of the formula, if it is found, ISNUMBER will return true, since you want the opposite, the whole thing is wrapped in a NOT

Body:
You can use FORMULATEXT in your condition:

=NOT(ISNUMBER(SEARCH("SUMIFS",FORMULATEXT(G6))))

This will basically look for "SUMIFS" in the text of the formula, if it is found, ISNUMBER will return true, since you want the opposite, the whole thing is wrapped in a NOT


问:
Inverting a binary tree with javascript
I'm trying to invert a binary tree in javascript, but i can't figure out why I'm not getting it to print my tree. It seems like i can create my tree in the example code in the bottom, but i cant get it to save the data.

// A node contains the value, left and right pointers
class Node {
  constructor(item) {
    this.data = item;
    this.left = this.right = null;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  invert() {
    this.root = this.invert(this.root);
  }

  invert(node) {
    if (node == null)
      return node;

    /* recursive calls */
    let left = this.invert(node.left);
    let right = this.invert(node.right);

    /* swap the left and right pointers */
    node.left = right;
    node.right = left;

    return node;
  }

  printTree() {
    this.printTree(this.root);
  }

  // print InOrder binary tree traversal.
  printTree(node) {
    if (node == null)
      return;

    this.printTree(node.left);
    console.log(node.data + " ");
    this.printTree(node.right);
  }
}

/* testing for example nodes */
const tree = new BinaryTree();
tree.root = new Node(2);
tree.root.left = new Node(11);
tree.root.right = new Node(4);
tree.root.right.left = new Node(13);
tree.root.right.right = new Node(5);

/* log inorder traversal of the input tree */
console.log("Inorder traversal of input tree is :");
tree.printTree();
console.log("");

/* invert tree */
tree.invert();

/* log inorder traversal of the minor tree */
console.log("Inorder traversal of binary tree is : ");
tree.printTree();```

What am i doing wrong here to not get it to print the tree, and then invert it.

答:
You can't overload functions in javascript, it will always call the same function regardless of which one "matches".

class Demo {
    overload(a) {
        console.log('hi');
    }
    overload() {
        console.log('bye');
    }
    overload(a, b) {
        console.log('wow');
    }
}

const d = new Demo();
d.overload();
d.overload(1);
d.overload(1, 2);```
</div>
</div>
</p>

<p>Because you start with <code>tree.printTree();</code>, and it's actually calling:</p>

```printTree(node) {
  if (node == null)
    return;

  this.printTree(node.left);
  console.log(node.data + " ");
  this.printTree(node.right);
}
```

<p>AND you used <code>==</code> instead of <code>===</code>, you are essentially calling:</p>

```printTree() {
    if (true) {
        return;
    }
}
```

Title: Inverting a binary tree with javascript

Body:
I'm trying to invert a binary tree in javascript, but i can't figure out why I'm not getting it to print my tree. It seems like i can create my tree in the example code in the bottom, but i cant get it to save the data.

// A node contains the value, left and right pointers
class Node {
  constructor(item) {
    this.data = item;
    this.left = this.right = null;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  invert() {
    this.root = this.invert(this.root);
  }

  invert(node) {
    if (node == null)
      return node;

    /* recursive calls */
    let left = this.invert(node.left);
    let right = this.invert(node.right);

    /* swap the left and right pointers */
    node.left = right;
    node.right = left;

    return node;
  }

  printTree() {
    this.printTree(this.root);
  }

  // print InOrder binary tree traversal.
  printTree(node) {
    if (node == null)
      return;

    this.printTree(node.left);
    console.log(node.data + " ");
    this.printTree(node.right);
  }
}

/* testing for example nodes */
const tree = new BinaryTree();
tree.root = new Node(2);
tree.root.left = new Node(11);
tree.root.right = new Node(4);
tree.root.right.left = new Node(13);
tree.root.right.right = new Node(5);

/* log inorder traversal of the input tree */
console.log("Inorder traversal of input tree is :");
tree.printTree();
console.log("");

/* invert tree */
tree.invert();

/* log inorder traversal of the minor tree */
console.log("Inorder traversal of binary tree is : ");
tree.printTree();

What am i doing wrong here to not get it to print the tree, and then invert it.

Body:
You can't overload functions in javascript, it will always call the same function regardless of which one "matches".

class Demo {
    overload(a) {
        console.log('hi');
    }
    overload() {
        console.log('bye');
    }
    overload(a, b) {
        console.log('wow');
    }
}

const d = new Demo();
d.overload();
d.overload(1);
d.overload(1, 2);

Because you start with tree.printTree();, and it's actually calling:

printTree(node) {
  if (node == null)
    return;

  this.printTree(node.left);
  console.log(node.data + " ");
  this.printTree(node.right);
}

AND you used == instead of ===, you are essentially calling:

printTree() {
    if (true) {
        return;
    }
}


问:
How to make folders into isolated spaces that cannot access anything else outside of them (PHP)
I'm trying to make a website where users have their own creative spaces where anyone can see said spaces. The problem is that those users might hack my website by accessing the parent folders. I was wondering if there was a way to ensure the exclusivity of those folders.

the following is the structure I mentioned:

```<code>parent/
  child1/
     file1
     file2
     folder/
     image
  child2/
     file
</code>```

I just want to make sure files from child1 will only be able to access others within child1 only. meaning that file1 can access folder/image, but not ../child2/file or ../../other_file

Also, I use PHP.

答:
Briefly;

Use a database to control authentication.

Use mod_Rewrite to hide PHP file locations.

Store user data files off the public area of your server account.

ABSOLUTELY CLEAN UPLOADED USER FILES FIRST!!

Use PHP Headers and file_get_contents() to present files as if they are native.

The below is only an example of one way to approach this broad topic

For example; let's look at Instagram; they use a complex version of the above system.

This is an instagram image:

https://instagram.flhr1-2.fna.fbcdn.net/v/t51.2885-15/e35/20987296_218244025372607_4512699619393667072_n.jpg?_nc_ht=instagram.flhr1-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=LwKoP3yHB_AAX-QA9yR&oh=d6d19ba6381de558e7260f44897f6010&oe=5E8FE8D7

You see all the stuff after the image file?

_nc_ht

_nc_cat

_nc_ohc

oh

These are trackers and definitions. These are used to ensure the image loaded is correct; if you load the URL without these you get:

https://instagram.flhr1-2.fna.fbcdn.net/v/t51.2885-15/e35/20987296_218244025372607_4512699619393667072_n.jpg

Which gives you:

```<code>"Bad URL Timestamp"
</code>```

Because the .jpg file is NOT A JPEG. It is a PHP file which is pretending to be a core file, the file name also does not exist but is used to generate a .htaccess mod_rewrite,

so, applying this example to your scenario:

Request: /myfolder/mark/20987296_218244025372607_4512699619393667072_n.jpg

is

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/myfolder/(*.[^/]+)/([0-9]+)_([0-9]+)_([0-9]+)_n.jpg$ /imageProcessor.php?folder=$1&image=$2&var3=$3&var4=$4 [NC,L,QSA]
</code>```

The PHP file imageProcessor.php will look something like:

```<code><?php
// headers
// PHP tells the browser it is a JPEG file type.
Header("content-type: image/jpeg");

// validate $_GET data and
if(is_numeric($_GET['image']) && $_GET['oh'] > (time() - 3600) ){

// check database of values; such as if this image is visible
$imageData = $DatabaseObject->getImage((int)$_GET['image']);

// Load the result file path from the database,
// check it fits the database value
if($_GET['folder'] === $imageData['user_folder'] && file_exists($imageData['user_folder'])){

// load the file with file_get_contents
$image = file_get_contents($imageData['image_path']);

}

print $image;
</code>```

Therefore you can build a complete system whereby what the user and browser sees at the front end is entirely different from what actually happens on the server; you can contain users in certain spaces defined by their database attributes according to their account values.

the above is AN EXTREMELY SIMPLE EXAMPLE but the core concepts should be enough to get you started, how you authenticate your users based on folder could be:

The user login hash can be any string of a fixed length that is generated when that user logs in and is unique in the database. This string can be uses in filenames or in Query Strings to identify the user, however $_SESSION data is far more reliable and can be more secret.

So $_SESSION['login_hash'] = "randomGeneratedCodeX";

MySQL:

```<code>user_id | user_name | user_folder | user_login_hash
------------------------------------------------------------
  1     |   userA   |   mark      | randomGeneratedCodeX
  2     |   userB   |  jason      | randomCodeGeneratedZ
</code>```

Therefore when the user accessses /myfolder/mark/234_464_7681.jpg the Mod_rewrite would actually access /imageProcessor.php?image=234....

Then your code can look in the database and find if the $_SESSION hashes compare; and find the folder:

```<code>SELECT user_folder FROM `users_table` WHERE user_login_hash = :sessionString
</code>```

Where $_SESSION['login_hash'] === :sessionString = randomGeneratedCodeX.
Then you can check if the image exists:

```<code>$imagePath = "/path/to/data/folders/".$imageData['user_folder']./".$_GET['image'].".jpg";
if(file_exists($imagePath) && $imageData['user_folder'] === $_GET['folder']){
    //File exists so load it into PHP and outpout the image to the browser!
    print file_get_contents($imagePath);
}
</code>```

PLEASE NOTE that you should use a basic .htaccess to stop direct access to the data file by the browser, or store the file outside of the public_html directory so it is never accessible from the browser:

For example:

FILE: /yourServerAccount/path/to/data/folders/mark/234.jpg

URL: /yourServerAccount/public_html/imageProcessor.php

So this can give each of your users their own pseudo space and as they're logged in as one user they'd be hardcoded not to be able to load data from another users directory.

THE ABOVE IS AN EXTREMELY SIMPLE AND IMPERFECT EXAMPLE ONLY.

You need to read up on the concepts and ballparks presented above.

Bibilography:

Apache - rewrite images to php file with .htaccess

PHP, display image with Header()

Prevent direct access to a php include file

PHP: How to sanitize uploaded filenames?

... and many, many other links and useful informations ...

Body:
I'm trying to make a website where users have their own creative spaces where anyone can see said spaces. The problem is that those users might hack my website by accessing the parent folders. I was wondering if there was a way to ensure the exclusivity of those folders.

the following is the structure I mentioned:

parent/
  child1/
     file1
     file2
     folder/
     image
  child2/
     file

I just want to make sure files from child1 will only be able to access others within child1 only. meaning that file1 can access folder/image, but not ../child2/file or ../../other_file

Also, I use PHP.

Body:
Briefly;

Use a database to control authentication.

Use mod_Rewrite to hide PHP file locations.

Store user data files off the public area of your server account.

ABSOLUTELY CLEAN UPLOADED USER FILES FIRST!!

Use PHP Headers and file_get_contents() to present files as if they are native.

The below is only an example of one way to approach this broad topic

For example; let's look at Instagram; they use a complex version of the above system.

This is an instagram image:

https://instagram.flhr1-2.fna.fbcdn.net/v/t51.2885-15/e35/20987296_218244025372607_4512699619393667072_n.jpg?_nc_ht=instagram.flhr1-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=LwKoP3yHB_AAX-QA9yR&oh=d6d19ba6381de558e7260f44897f6010&oe=5E8FE8D7

You see all the stuff after the image file?

_nc_ht

_nc_cat

_nc_ohc

oh

These are trackers and definitions. These are used to ensure the image loaded is correct; if you load the URL without these you get:

https://instagram.flhr1-2.fna.fbcdn.net/v/t51.2885-15/e35/20987296_218244025372607_4512699619393667072_n.jpg

Which gives you:

"Bad URL Timestamp"

Because the .jpg file is NOT A JPEG. It is a PHP file which is pretending to be a core file, the file name also does not exist but is used to generate a .htaccess mod_rewrite,

so, applying this example to your scenario:

Request: /myfolder/mark/20987296_218244025372607_4512699619393667072_n.jpg

is

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/myfolder/(*.[^/]+)/([0-9]+)_([0-9]+)_([0-9]+)_n.jpg$ /imageProcessor.php?folder=$1&image=$2&var3=$3&var4=$4 [NC,L,QSA]

The PHP file imageProcessor.php will look something like:

<?php
// headers
// PHP tells the browser it is a JPEG file type.
Header("content-type: image/jpeg");

// validate $_GET data and
if(is_numeric($_GET['image']) && $_GET['oh'] > (time() - 3600) ){

// check database of values; such as if this image is visible
$imageData = $DatabaseObject->getImage((int)$_GET['image']);

// Load the result file path from the database,
// check it fits the database value
if($_GET['folder'] === $imageData['user_folder'] && file_exists($imageData['user_folder'])){

// load the file with file_get_contents
$image = file_get_contents($imageData['image_path']);

}

print $image;

Therefore you can build a complete system whereby what the user and browser sees at the front end is entirely different from what actually happens on the server; you can contain users in certain spaces defined by their database attributes according to their account values.

the above is AN EXTREMELY SIMPLE EXAMPLE but the core concepts should be enough to get you started, how you authenticate your users based on folder could be:

The user login hash can be any string of a fixed length that is generated when that user logs in and is unique in the database. This string can be uses in filenames or in Query Strings to identify the user, however $_SESSION data is far more reliable and can be more secret.

So $_SESSION['login_hash'] = "randomGeneratedCodeX";

MySQL:

user_id | user_name | user_folder | user_login_hash
------------------------------------------------------------
  1     |   userA   |   mark      | randomGeneratedCodeX
  2     |   userB   |  jason      | randomCodeGeneratedZ

Therefore when the user accessses /myfolder/mark/234_464_7681.jpg the Mod_rewrite would actually access /imageProcessor.php?image=234....

Then your code can look in the database and find if the $_SESSION hashes compare; and find the folder:

SELECT user_folder FROM `users_table` WHERE user_login_hash = :sessionString

Where $_SESSION['login_hash'] === :sessionString = randomGeneratedCodeX.
Then you can check if the image exists:

$imagePath = "/path/to/data/folders/".$imageData['user_folder']./".$_GET['image'].".jpg";
if(file_exists($imagePath) && $imageData['user_folder'] === $_GET['folder']){
    //File exists so load it into PHP and outpout the image to the browser!
    print file_get_contents($imagePath);
}

PLEASE NOTE that you should use a basic .htaccess to stop direct access to the data file by the browser, or store the file outside of the public_html directory so it is never accessible from the browser:

For example:

FILE: /yourServerAccount/path/to/data/folders/mark/234.jpg

URL: /yourServerAccount/public_html/imageProcessor.php

So this can give each of your users their own pseudo space and as they're logged in as one user they'd be hardcoded not to be able to load data from another users directory.

THE ABOVE IS AN EXTREMELY SIMPLE AND IMPERFECT EXAMPLE ONLY.

You need to read up on the concepts and ballparks presented above.

Bibilography:

Apache - rewrite images to php file with .htaccess

PHP, display image with Header()

Prevent direct access to a php include file

PHP: How to sanitize uploaded filenames?

... and many, many other links and useful informations ...


问:
Age verification based on birthdate and current date
So, I need to calculate age by subtracting "todays" date from the converted date of an input field, entered by the user. Although it needs cleaned up, the below code works, I had to get creative as RN uses a different JS execution environment... see here.

My question, without adding the "+1" to this snippet "b.getMonth() + 1", the math on the date subtraction comes back 1 month off every time. When I add the "+1" it works like a charm, why? If it's a logical fix, I don't mind keeping the "+1," but I would surely like to know why the "+1" is necessary.

Also, totally open to improved solutions to this problem, keep in mind I had a much simpler function that worked great while debugger was open, once closed, it did not work, see the link above.

```<code>getVerifyBirthday(birthday) {
    const b = new Date();
    var verify = birthday.length;

    const utc2 = Date.UTC(b.getFullYear(), b.getMonth() + 1, b.getDate());

    if (verify === 10) {
      const splitBirth = birthday.split('-');
      var mydate = new Date(splitBirth[2], splitBirth[0], splitBirth[1]);

      const a = mydate;
      const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());

      const diffTime = Math.abs(utc2 - utc1);
      const diffYears = (diffTime / (3.15576e+10));

      this.setState({ diffYears: diffYears});

      return diffYears >= 13;
    } else {}
  }
</code>```

Update

I ended up refactoring my original function, leaving the (+1) on months due to months starting at 0, as mentioned below. I still had to split both dates, when I didn't split both, my age came back NaN/Undefined; not sure if this goes back to the RN execution environment vs browser, but I digress.

答:
I'd make a few of my own suggestions over here:

there's no need to hussle with UTC dates (to make sure whether the user in his timezone has already reached the age of 13, assuming along the way that he or she was born in that same timezone ;)

there's no need to split mm-dd-yyyy date string to convert into Date, it may be parsed by new Date()

counting years as 365.25 days has certain error margin depending on the exact leap years quantity that passed since the user's birth year, instead whole years may be compared together with dates

To me, it makes more sense to decompose date strings into days, months and years and make decision based on full years difference minus 1 year (if the person didn't yet celebrate his/her birthday this year):

const today = new Date().toISOString().slice(0,10), // yyyy-mm-dd
      birthday = '1982-06-21',
      [bYear, bMonth, bDay] = birthday.split('-'),
      [tYear, tMonth, tDay] = today.split('-'),
      diffYears = tYear - bYear - (bMonth > tMonth || bDay > tDay ? 1 : 0)

console.log(diffYears)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

Body:
So, I need to calculate age by subtracting "todays" date from the converted date of an input field, entered by the user. Although it needs cleaned up, the below code works, I had to get creative as RN uses a different JS execution environment... see here.

My question, without adding the "+1" to this snippet "b.getMonth() + 1", the math on the date subtraction comes back 1 month off every time. When I add the "+1" it works like a charm, why? If it's a logical fix, I don't mind keeping the "+1," but I would surely like to know why the "+1" is necessary.

Also, totally open to improved solutions to this problem, keep in mind I had a much simpler function that worked great while debugger was open, once closed, it did not work, see the link above.

getVerifyBirthday(birthday) {
    const b = new Date();
    var verify = birthday.length;

    const utc2 = Date.UTC(b.getFullYear(), b.getMonth() + 1, b.getDate());

    if (verify === 10) {
      const splitBirth = birthday.split('-');
      var mydate = new Date(splitBirth[2], splitBirth[0], splitBirth[1]);

      const a = mydate;
      const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());

      const diffTime = Math.abs(utc2 - utc1);
      const diffYears = (diffTime / (3.15576e+10));

      this.setState({ diffYears: diffYears});

      return diffYears >= 13;
    } else {}
  }

Update

I ended up refactoring my original function, leaving the (+1) on months due to months starting at 0, as mentioned below. I still had to split both dates, when I didn't split both, my age came back NaN/Undefined; not sure if this goes back to the RN execution environment vs browser, but I digress.

Body:
I'd make a few of my own suggestions over here:

there's no need to hussle with UTC dates (to make sure whether the user in his timezone has already reached the age of 13, assuming along the way that he or she was born in that same timezone ;)

there's no need to split mm-dd-yyyy date string to convert into Date, it may be parsed by new Date()

counting years as 365.25 days has certain error margin depending on the exact leap years quantity that passed since the user's birth year, instead whole years may be compared together with dates

To me, it makes more sense to decompose date strings into days, months and years and make decision based on full years difference minus 1 year (if the person didn't yet celebrate his/her birthday this year):

const today = new Date().toISOString().slice(0,10), // yyyy-mm-dd
      birthday = '1982-06-21',
      [bYear, bMonth, bDay] = birthday.split('-'),
      [tYear, tMonth, tDay] = today.split('-'),
      diffYears = tYear - bYear - (bMonth > tMonth || bDay > tDay ? 1 : 0)

console.log(diffYears)

.as-console-wrapper{min-height:100%;}


问:
How do I fix this error on unity: Cannot implicitly convert type float to UnityEngine.transform
I am trying to do something, and I get this error:

```<code>Cannot implicitly convert type float to UnityEngine.transform
</code>```

code:

```<code>private Transform EndPos;
EndPos = transform.position.x + 40f;
transform.position = Vector3.MoveTowards(transform.position, EndPos, moveSpeed * Time.deltaTime);
</code>```

Thank you for your help

答:
EndPos is type Transform. You are trying to set it to transform.position.x which is type float.

I think what you are trying to do is:

```<code>EndPos.position = transform.position + (Vector3.right * 40f);
</code>```

This sets EndPos 40 units to the right of transform's current position.

Body:
I am trying to do something, and I get this error:

Cannot implicitly convert type float to UnityEngine.transform

code:

private Transform EndPos;
EndPos = transform.position.x + 40f;
transform.position = Vector3.MoveTowards(transform.position, EndPos, moveSpeed * Time.deltaTime);

Thank you for your help

Body:
EndPos is type Transform. You are trying to set it to transform.position.x which is type float.

I think what you are trying to do is:

EndPos.position = transform.position + (Vector3.right * 40f);

This sets EndPos 40 units to the right of transform's current position.


问:
Building GCC-Ada, Syntax error compiling s-excmac.adb with very old gnatmake
I'm trying to update our 20-year old Ada compiler, however you need an Ada-compiler to build some parts of GCC+Ada (9.2.0).

The gnatmake is circa 2000, and it's possibly sub-calling GCC 2.8.1.  Sigh.

I have already successfully built several Ada parts of GCC, but this libgnat/ file eludes me:

Compiling libgnat/s-excmac.adb:

```<code>$ gnatmake s-excmac.adb
gcc -c -gnatpg s-excmac.adb
s-excmac.ads:134:44: identifier expected
gnatmake: "s-excmac.adb" compilation error
</code>```

So the problematic line in s-excmac.ads is:

```<code>   type GCC_Exception_Access is access all Unwind_Exception;
   --  Pointer to a GCC exception

   procedure Unwind_DeleteException (Excp : not null GCC_Exception_Access );  -- <-- THIS ONE!

   pragma Import (C, Unwind_DeleteException, "_Unwind_DeleteException");

   --  Procedure to free any GCC exception
</code>```

I don't understand what is wrong with this code.  Is there some turn-of-the-century Ada syntax replacement I can use to get this part of GCC-Ada compiled?

I'm a bit of an Ada NOOB, so please be gentle.

EDIT: Seems like trying to "repair" the s-excmac.adb / s-excmac.ads is a fool's errand.  The path of lesser resistance is to download a pre-built compiler, and start building the later GCC from that.

答:
If the compiler is older than 2005, compiling the Ada-2005 not null access declaration is going to be a problem.

To move forward, you could delete the words "not null" and that line will compile and work, but you won't get the desired behaviour (abort with an exception) if you ever pass in a null access type. A better fix would be a wrapper procedure that explicitly checked, and either raised an exception or called the underlying C procoughvoid function as appropriate.

Additionally, there may be other Ada-2005 features which will also fail to compile, so a better choice would be a compiler upgrade.

Body:
I'm trying to update our 20-year old Ada compiler, however you need an Ada-compiler to build some parts of GCC+Ada (9.2.0).

The gnatmake is circa 2000, and it's possibly sub-calling GCC 2.8.1.  Sigh.

I have already successfully built several Ada parts of GCC, but this libgnat/ file eludes me:

Compiling libgnat/s-excmac.adb:

$ gnatmake s-excmac.adb
gcc -c -gnatpg s-excmac.adb
s-excmac.ads:134:44: identifier expected
gnatmake: "s-excmac.adb" compilation error

So the problematic line in s-excmac.ads is:

   type GCC_Exception_Access is access all Unwind_Exception;
   --  Pointer to a GCC exception

   procedure Unwind_DeleteException (Excp : not null GCC_Exception_Access );  -- <-- THIS ONE!

   pragma Import (C, Unwind_DeleteException, "_Unwind_DeleteException");

   --  Procedure to free any GCC exception

I don't understand what is wrong with this code.  Is there some turn-of-the-century Ada syntax replacement I can use to get this part of GCC-Ada compiled?

I'm a bit of an Ada NOOB, so please be gentle.

EDIT: Seems like trying to "repair" the s-excmac.adb / s-excmac.ads is a fool's errand.  The path of lesser resistance is to download a pre-built compiler, and start building the later GCC from that.


问:
Find the shortest cycle in a directed weighted graph
Where are the edge lengths are positive and it has to run in O(V^3) time. I'm having a bit of trouble trying to wrap my head around this problem, but this is what I have right now:

Set a shortest cycle variable, make it really large. Loop through every vertex in the graph, then loop through every vertex in the graph for that for loop, then inside the double for loop, I compute the distance from the first vertex to the second, then the second to the first, then compare this distance with my shortest cycle variable and update if it is smaller.

With this implementation then, since I go through every vertex for every vertex in a double for loop it's O(V^3) but I use Djisktra's algorithm twice inside each iteration of the double for loop so that's O(ElogV). I'm not exactly sure how this would be O(V^3) so I think my implementation may need more work.

答:
For an O(V³) implementation, you could check if every 3 vertices make a cycle and return those with a minimal total weight:

int minimalCycleWeight = POSITIVE_INFINITY;
// declare nodes to be returned if needed

for (int i = 0; i < verticesCount; i++) {
    for (int j = 0; j < verticesCount; j++) {
        for (int k = 0; k < verticesCount; k++) {
            if (graph[i].hasEdgeTo(graph[j])
                && graph[j].hasEdgeTo(graph[k])
                && graph[k].hasEdgeTo(graph[i])) {

                int totalCycleWeight = graph[i].weightTo(graph[j])
                                        + graph[j].weightTo(graph[k])
                                        + graph[k].weightTo(graph[i]);

                if (totalCycleWeight < minimalCycleWeight) {
                    minimalCycleWeight = totalCycleWeight;
                    // save nodes to return later if needed
                }
            }
        }
    }
}
```

With Dijkstra's algorithm you could only do better than O(V³).

Body:
For an O(V³) implementation, you could check if every 3 vertices make a cycle and return those with a minimal total weight:

int minimalCycleWeight = POSITIVE_INFINITY;
// declare nodes to be returned if needed

for (int i = 0; i < verticesCount; i++) {
    for (int j = 0; j < verticesCount; j++) {
        for (int k = 0; k < verticesCount; k++) {
            if (graph[i].hasEdgeTo(graph[j])
                && graph[j].hasEdgeTo(graph[k])
                && graph[k].hasEdgeTo(graph[i])) {

                int totalCycleWeight = graph[i].weightTo(graph[j])
                                        + graph[j].weightTo(graph[k])
                                        + graph[k].weightTo(graph[i]);

                if (totalCycleWeight < minimalCycleWeight) {
                    minimalCycleWeight = totalCycleWeight;
                    // save nodes to return later if needed
                }
            }
        }
    }
}

With Dijkstra's algorithm you could only do better than O(V³).


问:
Microsoft Graph API token validation failure
I would use Microsoft Graph API in my Angular Web application.

First I make connexion using msal library
When I try log in  with my profil I get this error

I have configured my app as the mentionned in the official git sample

```<code>MsalModule.forRoot({
  clientID: "Tenant ID",
  authority: "https://login.microsoftonline.com/common/",
  redirectUri: "http://localhost:4200/",
  validateAuthority : true,
  popUp: true
}),
</code>```

Authetification is working and I get the token.

Then when I'm in home page I make a second request to Microsoft Graph API to get user information using that token.

```<code>getProfile() {
  let header= new Headers();
  let tokenid= sessionStorage.getItem('msal.idtoken');
  header.set('Authorization', 'Bearer ' + tokenid)
  let url ="https://graph.microsoft.com/v1.0/me/"
  return this.http.get(url,{headers:header});
}
</code>```

}

I get an 401 Unauthorized error with a response :

```<code>{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure.",
    "innerError": {
      "request-id": "xxxxxx",
      "date": "2018-10-09T22:58:41"
    }
  }
}
</code>```

I don't know why MG API is not accepting my token, Am I using wrong authority url ?

UPDATE: I have understood that actually I get id_token which is different from access token. How can I get Access token from MSAL library to make MS GRAPH API calls ?:

答:
Make sure you add your endpoint to Resource Map configuration. See this link: https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp</p>

```<code>export const protectedResourceMap:[string, string[]][]=[ ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];
</code>```

Body:
I would use Microsoft Graph API in my Angular Web application.

First I make connexion using msal library
When I try log in  with my profil I get this error

I have configured my app as the mentionned in the official git sample

MsalModule.forRoot({
  clientID: "Tenant ID",
  authority: "https://login.microsoftonline.com/common/",
  redirectUri: "http://localhost:4200/",
  validateAuthority : true,
  popUp: true
}),

Authetification is working and I get the token.

Then when I'm in home page I make a second request to Microsoft Graph API to get user information using that token.

getProfile() {
  let header= new Headers();
  let tokenid= sessionStorage.getItem('msal.idtoken');
  header.set('Authorization', 'Bearer ' + tokenid)
  let url ="https://graph.microsoft.com/v1.0/me/"
  return this.http.get(url,{headers:header});
}

}

I get an 401 Unauthorized error with a response :

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure.",
    "innerError": {
      "request-id": "xxxxxx",
      "date": "2018-10-09T22:58:41"
    }
  }
}

I don't know why MG API is not accepting my token, Am I using wrong authority url ?

UPDATE: I have understood that actually I get id_token which is different from access token. How can I get Access token from MSAL library to make MS GRAPH API calls ?:

Body:
Make sure you add your endpoint to Resource Map configuration. See this link: https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp

export const protectedResourceMap:[string, string[]][]=[ ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];


问:
Converting to C++ from C#
I have done pretty much all my programming using C# and very much a newbie to C++. However now I have to convert to C++ and is finding it a bit difficult. For example, I wrote a pretty simple program using C# to acquire a RegistryKey, then using a recursive function I iterate through my registry key to find a specific key and then get the values I want. No problem, I can write that program in 10 minutes using C#. Here is the code.

My primary function. It gets Bluetooth Registry Key and then call the recursive function.

```<code>private static void CheckOpenComPorts()
{
            RegistryKey blueToothPorts = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\Bluetooth");

            List<string> foundPorts = new List<string>();
            AddFoundPortsToList(blueToothPorts, ref foundPorts);

            //Rest of the program; not relevant here.
}
</code>```

Recursive Function. Iterates the passed Key to find out necessary values.

```<code>private static void AddFoundPortsToList(RegistryKey regKey, ref List<string> ports)
        {
            try
            {
                string[] subKeys = regKey.GetSubKeyNames();

                if (subKeys != null)
                {
                    foreach (string subKey in subKeys)
                    {
                        AddFoundPortsToList(regKey.OpenSubKey(subKey), ref ports);
                    }
                }

                if (regKey.Name.EndsWith("Device Parameters"))
                {
                    string str = System.Convert.ToString(regKey.GetValue("PortName"));
                    if (String.IsNullOrEmpty(str) == false)
                    {
                        ports.Add(str);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                ;
            }
        }
</code>```

The above code works fine, but when I tried to convert it to C++, I'm pretty lost.
Note : I'm using a Win32 Console C++ Program.

I figured out that I can do something like the following to get the Bluetooth Registry Key.

```<code>RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\Bluetooth", 0, KEY_READ, &hKey)
</code>```

But after that, I'm pretty lost about the recursive function. Specially, how do I get the available subkeys of the passed registry key when I do NOT know the subkey names?. Or in short, what is the equivalent behavior of RegistryKey.GetSubKeyNames() in C++?

As I am only beginning this thing a code sample with some explanations would be great.

答:
I'm assuming you want to transition from .NET to native C++ programming.  (i.e. no CLI and no .NET framework, which you could still use if you enabled managed C++ compilation).

If you spent a ton of time in C# land, you are probably very used to a ton of very convenient classes for just about everything imaginable and all you have to do is hit "." and let the Intellisense list the methods.  Well.... you can forget all those conveniences :)

There is no such (at least not complete) framework in C++ so often you have to turn to Win32 API. MSDN Library is YOUR FRIEND.  If you want to get good at C++, learn how to read it and learn how to look things up (not just by name, but learn where different categories are).  In this case, if you search for the function you found, you will find a whole set of functions that work on registry.  So now, looking at other methods in the same category in MSDN library, you can find RegEnumKeyEx. (hint: make sure to switch MSDN library UI to classical view, that makes it much easier to navigate between topics.  I don't know what MS was thinking with their "new" look and feel)

As you start using Win32 API you will realize what a pain it is, especially coming from C#.  But you don't have to use it directly (or at least not every time).  You can use other libraries, for example ATL provides you with CRegKey class which makes working with registry much simpler.  If you can't find the class, do what C++ does best, write your own class.  Constantly working directly with windows functions will make your code very, very long and a pain to read.

Another 2 libraries worth knowing as you get into C++ are STL (a must) and Boost (strong should).  Boost especially has a lot of OS abstraction so you don't have to go directly to windows DLLs every time.

ContentLicense: CC BY-SA 3.0

Title: Converting to C++ from C#

Body:
I have done pretty much all my programming using C# and very much a newbie to C++. However now I have to convert to C++ and is finding it a bit difficult. For example, I wrote a pretty simple program using C# to acquire a RegistryKey, then using a recursive function I iterate through my registry key to find a specific key and then get the values I want. No problem, I can write that program in 10 minutes using C#. Here is the code.

My primary function. It gets Bluetooth Registry Key and then call the recursive function.

private static void CheckOpenComPorts()
{
            RegistryKey blueToothPorts = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\Bluetooth");

            List<string> foundPorts = new List<string>();
            AddFoundPortsToList(blueToothPorts, ref foundPorts);

            //Rest of the program; not relevant here.
}

Recursive Function. Iterates the passed Key to find out necessary values.

private static void AddFoundPortsToList(RegistryKey regKey, ref List<string> ports)
        {
            try
            {
                string[] subKeys = regKey.GetSubKeyNames();

                if (subKeys != null)
                {
                    foreach (string subKey in subKeys)
                    {
                        AddFoundPortsToList(regKey.OpenSubKey(subKey), ref ports);
                    }
                }

                if (regKey.Name.EndsWith("Device Parameters"))
                {
                    string str = System.Convert.ToString(regKey.GetValue("PortName"));
                    if (String.IsNullOrEmpty(str) == false)
                    {
                        ports.Add(str);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                ;
            }
        }

The above code works fine, but when I tried to convert it to C++, I'm pretty lost.
Note : I'm using a Win32 Console C++ Program.

I figured out that I can do something like the following to get the Bluetooth Registry Key.

RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\Bluetooth", 0, KEY_READ, &hKey)

But after that, I'm pretty lost about the recursive function. Specially, how do I get the available subkeys of the passed registry key when I do NOT know the subkey names?. Or in short, what is the equivalent behavior of RegistryKey.GetSubKeyNames() in C++?

As I am only beginning this thing a code sample with some explanations would be great.


问:
Running as PS as Admin but receive error -that operation requires elevation
Due to various new security policies, we need to be able to run various tasks as an assigned uid. To assist in this, a common menu system was developed. One of the functions in the script is:

```<code>$credential = user_credential
$cmd = "C:\windows\system32\mmc.exe"
$args = "C:\Windows\System32\compmgmt.msc"
Start-Process -FilePath $cmd -ArgumentList $args  -Credential $credential
</code>```

Error received:

```<code>Start-Process : This command cannot be run due to the error: The requested operation requires elevation.
t C:\webeng\webeng.ps1:131 char:5
     Start-Process -FilePath $cmd -ArgumentList $args  -Credential $credential
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
   + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
</code>```

The error seems to indicate that the PS script requires elevated privs but I am already running as Administrator.

What could I possibly be missing here?

答:
```<code># variables
$mmc = "$($env:SystemDrive)\Windows\System32\mmc.exe"
$msc = "$($env:SystemDrive)\Windows\System32\compmgmt.msc"

# credentials
$username   = "DOMAIN\USERNAME"
$securePass = ConvertTo-SecureString "PASSWORD" -AsPlainText –Force
$cred       = New-Object System.Management.Automation.PSCredential $username, $securePass

# call MSC
Start-Process powershell.exe -Credential $cred -ArgumentList "Start-Process -FilePath $mmc -ArgumentList $msc -Verb runAs"
</code>```

Body:
Due to various new security policies, we need to be able to run various tasks as an assigned uid. To assist in this, a common menu system was developed. One of the functions in the script is:

$credential = user_credential
$cmd = "C:\windows\system32\mmc.exe"
$args = "C:\Windows\System32\compmgmt.msc"
Start-Process -FilePath $cmd -ArgumentList $args  -Credential $credential

Error received:

Start-Process : This command cannot be run due to the error: The requested operation requires elevation.
t C:\webeng\webeng.ps1:131 char:5
     Start-Process -FilePath $cmd -ArgumentList $args  -Credential $credential
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
   + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

The error seems to indicate that the PS script requires elevated privs but I am already running as Administrator.

What could I possibly be missing here?


问:
Python's sum not returning same result as NumPy's numpy.sum
Numpy's sum function is returning the correct expected result, but the default python's sum is not (at least not for uint8 datatype, which makes it even more confusing):</p>

```<code>In [1]: import numpy as np

In [2]: x = np.random.randint(2, size = (1000,100))

In [3]: x
Out[3]:
array([[1, 1, 0, ..., 0, 1, 1],
       [1, 1, 1, ..., 0, 0, 0],
       [1, 1, 0, ..., 1, 0, 1],
       ...,
       [1, 0, 0, ..., 1, 0, 1],
       [0, 0, 1, ..., 0, 1, 1],
       [1, 1, 0, ..., 1, 1, 1]])

In [4]: np.sum(x)
Out[4]: 50318

In [5]: sum(sum(x))
Out[5]: 50318

In [6]: x = x.astype('uint8')

In [7]: np.sum(x)
Out[7]: 50318

In [8]: sum(sum(x))
Out[8]: 16014
</code>```

答:
By specifying uint8 you are telling numpy to use 8 bits per element. The maximum number that can be stored in 8 bits is 255. So when you sum, you get an overflow.

Practical example:

```<code>>>> arr = np.array([[255],[1]],dtype=np.uint8)
>>> arr
array([[255],
       [1]], dtype=uint8)
>>> sum(arr)
array([0], dtype=uint8)
>> arr[0]+arr[1]
array([0], dtype=uint8)
</code>```

Note that sum(arr) corresponds to arr[0] + arr[1] in this case.  As stated in the docs:

Arithmetic is modular when using integer types, and no error is raised on overflow.

Body:
Numpy's sum function is returning the correct expected result, but the default python's sum is not (at least not for uint8 datatype, which makes it even more confusing):

In [1]: import numpy as np

In [2]: x = np.random.randint(2, size = (1000,100))

In [3]: x
Out[3]:
array([[1, 1, 0, ..., 0, 1, 1],
       [1, 1, 1, ..., 0, 0, 0],
       [1, 1, 0, ..., 1, 0, 1],
       ...,
       [1, 0, 0, ..., 1, 0, 1],
       [0, 0, 1, ..., 0, 1, 1],
       [1, 1, 0, ..., 1, 1, 1]])

In [4]: np.sum(x)
Out[4]: 50318

In [5]: sum(sum(x))
Out[5]: 50318

In [6]: x = x.astype('uint8')

In [7]: np.sum(x)
Out[7]: 50318

In [8]: sum(sum(x))
Out[8]: 16014

Body:
By specifying uint8 you are telling numpy to use 8 bits per element. The maximum number that can be stored in 8 bits is 255. So when you sum, you get an overflow.

Practical example:

>>> arr = np.array([[255],[1]],dtype=np.uint8)
>>> arr
array([[255],
       [1]], dtype=uint8)
>>> sum(arr)
array([0], dtype=uint8)
>> arr[0]+arr[1]
array([0], dtype=uint8)

Note that sum(arr) corresponds to arr[0] + arr[1] in this case.  As stated in the docs:

Arithmetic is modular when using integer types, and no error is raised on overflow.


问:
Specifying vocabulary input in LDA
I am trying to understand how to use LDA in my case. I have a corpus of many documents and I want to see how a very specific set of words and ngrams are distributed across topics. Is there a way to specify a list of specific words as a vocabulary for topic modeling?

I have been working with the gensim implementation and I believe the argument id2word handles this, but the documentation is not clear to me. Is my understanding correct?

答:
LDA’s approach to topic modelling is it considers each document as a collection of topics in a certain proportion. And each topic as a collection of keywords, again, in a certain proportion.

Once you provide the algorithm with the number of topics, all it does it to rearrange the topics distribution within the documents and keywords distribution within the topics to obtain a good composition of topic-keywords distribution.

The two main inputs to the LDA topic model are the dictionary or vocabulary(id2word) and the corpus.

You can use something like this to achieve this:

```<code>import gensim.corpora as corpora

# Create Dictionary/Vocabulary
id2word = corpora.Dictionary(data_lemmatized)

# Create Corpus
texts = data_lemmatized

# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]
</code>```

Title: Specifying vocabulary input in LDA

Body:
LDA’s approach to topic modelling is it considers each document as a collection of topics in a certain proportion. And each topic as a collection of keywords, again, in a certain proportion.

Once you provide the algorithm with the number of topics, all it does it to rearrange the topics distribution within the documents and keywords distribution within the topics to obtain a good composition of topic-keywords distribution.

The two main inputs to the LDA topic model are the dictionary or vocabulary(id2word) and the corpus.

You can use something like this to achieve this:

import gensim.corpora as corpora

# Create Dictionary/Vocabulary
id2word = corpora.Dictionary(data_lemmatized)

# Create Corpus
texts = data_lemmatized

# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]


问:
How do I parameterize this jsonb array contains query?
I have the following sql:

```<code>WITH
ni AS (SELECT DISTINCT ON(issuercik) issuercik FROM new_insiders
WHERE date_filed > (CURRENT_DATE - INTERVAL '360 day')::date AND ( tickers @> '["MSFT"]'::jsonb ) ORDER BY issuercik, date_filed DESC),
t AS (SELECT cik FROM companies WHERE data->'tickers' @> '["MSFT"]'::jsonb )
SELECT ni.issuercik AS first, t.cik AS second FROM ni FULL OUTER JOIN t ON ni.issuercik = t.cik;
</code>```

Which gives me (as expected):

789019 | 789019

Now, I need to parameterize the query but am unable to:

```<code>DEALLOCATE stmt;
PREPARE stmt AS WITH
ni AS (SELECT DISTINCT ON(issuercik) issuercik FROM new_insiders
WHERE date_filed > (CURRENT_DATE - INTERVAL '360 day')::date AND ( tickers @> '["$1"]'::jsonb ) ORDER BY issuercik, date_filed DESC),
t AS (SELECT cik FROM companies WHERE data->'tickers' @> '["$1"]'::jsonb )
SELECT ni.issuercik AS first, t.cik AS second FROM ni FULL OUTER JOIN t ON ni.issuercik = t.cik;

EXECUTE stmt('MSFT');
</code>```

I get an empty row and that's because it is literally searching for "$1". I try to remove the double quotes then it complains

```<code>ERROR:  invalid input syntax for type json
LINE 4: ...DATE - INTERVAL '360 day')::date AND ( tickers @> '[$1]'::js...
                                                             ^
DETAIL:  Token "$" is invalid.
</code>```

I'm not sure how to resolve this one.

答:
If you just want to check if an array contains a given value, you can use ? instead of @>.

That would look like:

```<code>DEALLOCATE stmt;

PREPARE stmt AS
WITH
    ni AS (
        SELECT DISTINCT ON(issuercik) issuercik
        FROM new_insiders
        WHERE
            date_filed > (CURRENT_DATE - INTERVAL '360 day')::date
            AND tickers ? $1
        ORDER BY issuercik, date_filed DESC
    ),
    t AS (
        SELECT cik
        FROM companies
        WHERE data->'tickers' ? $1
    )
SELECT ni.issuercik AS first, t.cik AS second
FROM ni
FULL OUTER JOIN t ON ni.issuercik = t.cik;

EXECUTE stmt('MSFT');
</code>```

Body:
I have the following sql:

WITH
ni AS (SELECT DISTINCT ON(issuercik) issuercik FROM new_insiders
WHERE date_filed > (CURRENT_DATE - INTERVAL '360 day')::date AND ( tickers @> '["MSFT"]'::jsonb ) ORDER BY issuercik, date_filed DESC),
t AS (SELECT cik FROM companies WHERE data->'tickers' @> '["MSFT"]'::jsonb )
SELECT ni.issuercik AS first, t.cik AS second FROM ni FULL OUTER JOIN t ON ni.issuercik = t.cik;

Which gives me (as expected):

789019 | 789019

Now, I need to parameterize the query but am unable to:

DEALLOCATE stmt;
PREPARE stmt AS WITH
ni AS (SELECT DISTINCT ON(issuercik) issuercik FROM new_insiders
WHERE date_filed > (CURRENT_DATE - INTERVAL '360 day')::date AND ( tickers @> '["$1"]'::jsonb ) ORDER BY issuercik, date_filed DESC),
t AS (SELECT cik FROM companies WHERE data->'tickers' @> '["$1"]'::jsonb )
SELECT ni.issuercik AS first, t.cik AS second FROM ni FULL OUTER JOIN t ON ni.issuercik = t.cik;

EXECUTE stmt('MSFT');

I get an empty row and that's because it is literally searching for "$1". I try to remove the double quotes then it complains

ERROR:  invalid input syntax for type json
LINE 4: ...DATE - INTERVAL '360 day')::date AND ( tickers @> '[$1]'::js...
                                                             ^
DETAIL:  Token "$" is invalid.

I'm not sure how to resolve this one.

Body:
If you just want to check if an array contains a given value, you can use ? instead of @>.

That would look like:

DEALLOCATE stmt;

PREPARE stmt AS
WITH
    ni AS (
        SELECT DISTINCT ON(issuercik) issuercik
        FROM new_insiders
        WHERE
            date_filed > (CURRENT_DATE - INTERVAL '360 day')::date
            AND tickers ? $1
        ORDER BY issuercik, date_filed DESC
    ),
    t AS (
        SELECT cik
        FROM companies
        WHERE data->'tickers' ? $1
    )
SELECT ni.issuercik AS first, t.cik AS second
FROM ni
FULL OUTER JOIN t ON ni.issuercik = t.cik;

EXECUTE stmt('MSFT');


问:
Is Logging using FileHandler a bottleneck?
I am considering logging business events in a J2EE web application by using Java logging and FileHandler.

I am wondering whether that could cause a performance bottleneck, since many log records will be written to one file.

What are your experiences and opinions?

Is logging a busy web application to one file with Java logging and FileHandler likely to become performance bottleneck?

答:
In order to avoid generalities like "it depends" or "a little" etc. you should measure the performance of your application with and without the logging overhead. Apache JMeter can help you generate the load for the test.

The information you can collect through logging is usually so essential for the integrity of the application, that you can not operate blindly. There is also a slight overhead if you use Google Analytics, but the benefits prevail.

In order to keep your log files within reasonable sizes, you can always use rotating log files.


问:
Javascript code hiding a div doesn't work (CSS @media rule doesn't work either)- 'cannot read property style of null'
So, I've got a button that display toggles a div on a click event. It works properly. However, I can't hide the same div using nearly the same code (however, I want to toggle this div after my screen becomes too big, not after clicking), because I get the problem like in the title- 'cannot read property style of null'

The part that doesn't work (hiding a div after screen becomes too big:

```<code>if (screen.width > 900) {
  document.getElementById('klik').style.display = 'none';
}
</code>```

And the part that works (button toggles a div using a click event):

```<code>function showDiv() {
  if (document.getElementById('klik').style.display == 'block'){
    document.getElementById('klik').style.display = 'none';
  }
  else{
    document.getElementById('klik').style.display = 'block';
  }
}
</code>```

I wrote this code because I want to do a scalable menu, displaying a div with list items inside after clicking on it. The menu button is visible only  when screen-width <= 900px, if screen-width > 900px I've got a normal navigation bar and the button disappears.

Am I forgetting something? I'm new to Javascript. Also one more thing- it also doesn't work using @media rule, however I can change the background-color with @media. I hope it might help. Also thanks in advance.

答:
Note Two Problems:

Ensure that the element you want to change it's display has the id="klik"

The below code will execute only once.

if (screen.width > 900) { document.getElementById('klik').style.display = 'none'; }

But why?
The answer is because you didn't set an event to run it every time when your resize the screen. Also, screen.width will always return the width of the display. What you are looking for is the window.innerWidth

So a possible solution:

    window.addEventListener('resize', function(){
      document.getElementById("screen").innerHTML = window.innerWidth.toString() + "px";
      if(window.innerWidth < 900)
      {
        //Perform your desired Executions Here
      }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="screen"></div></code>```

This will run the code every time a window.onresize is triggered. And that's exactly what @media in CSS does. It works on window.onresize behind the scene in javascript sense.

Note: I have added a simple illustration on how to work with screen.resize which you can use as the basis for modifying element properties based on a certain range. All you need to do, is to ensure that you do your styling within that block and it will work.

Body:
So, I've got a button that display toggles a div on a click event. It works properly. However, I can't hide the same div using nearly the same code (however, I want to toggle this div after my screen becomes too big, not after clicking), because I get the problem like in the title- 'cannot read property style of null'

The part that doesn't work (hiding a div after screen becomes too big:

if (screen.width > 900) {
  document.getElementById('klik').style.display = 'none';
}

And the part that works (button toggles a div using a click event):

function showDiv() {
  if (document.getElementById('klik').style.display == 'block'){
    document.getElementById('klik').style.display = 'none';
  }
  else{
    document.getElementById('klik').style.display = 'block';
  }
}

I wrote this code because I want to do a scalable menu, displaying a div with list items inside after clicking on it. The menu button is visible only  when screen-width <= 900px, if screen-width > 900px I've got a normal navigation bar and the button disappears.

Am I forgetting something? I'm new to Javascript. Also one more thing- it also doesn't work using @media rule, however I can change the background-color with @media. I hope it might help. Also thanks in advance.

Body:
Note Two Problems:

Ensure that the element you want to change it's display has the id="klik"

The below code will execute only once.

if (screen.width > 900) { document.getElementById('klik').style.display = 'none'; }

But why?
The answer is because you didn't set an event to run it every time when your resize the screen. Also, screen.width will always return the width of the display. What you are looking for is the window.innerWidth

So a possible solution:

    window.addEventListener('resize', function(){
      document.getElementById("screen").innerHTML = window.innerWidth.toString() + "px";
      if(window.innerWidth < 900)
      {
        //Perform your desired Executions Here
      }
    });

<div id="screen"></div>

This will run the code every time a window.onresize is triggered. And that's exactly what @media in CSS does. It works on window.onresize behind the scene in javascript sense.

Note: I have added a simple illustration on how to work with screen.resize which you can use as the basis for modifying element properties based on a certain range. All you need to do, is to ensure that you do your styling within that block and it will work.


答:
According to the documentation Debug.Assert shows the message if the condition is false....

Therefore when you say "shieldPrefab.Length != 1" this is always false because the Length is always 1.

If you want to check if the Length is not 1 you need to apply the opposite:

```<code>Debug.Assert(shieldPrefab.Length == 1, "Expected exactly 1 shield like this...");
</code>```

Title: Why the Debug.Assert show the error message even if the Length is 1 all the time?

Body:
private GameObject GetDoorShaderPrefab()
    {
        string[] shieldPrefab = AssetDatabase.FindAssets(c_doorShieldFxLocked);
        Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");
        string shieldGuid = shieldPrefab[0];
        string prefabPath = AssetDatabase.GUIDToAssetPath(shieldGuid);
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
        Debug.Assert(prefab != null, "Expected prefab to load");
        return prefab;
    }

I used a break point on the line :

Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");

The Length of shieldPrefab is all the time 1 but it's still showing the error message "Expected exactly 1 shield like this..."

The method GetDoorShaderPrefab is being called many times in other place in the script. But each time the Length is 1 and it keep showing the error message.

Body:
According to the documentation Debug.Assert shows the message if the condition is false....

Therefore when you say "shieldPrefab.Length != 1" this is always false because the Length is always 1.

If you want to check if the Length is not 1 you need to apply the opposite:

Debug.Assert(shieldPrefab.Length == 1, "Expected exactly 1 shield like this...");


问:
Django Pillow Install Works for Migrate, But Not Run
When running mange makemigrations, I got an error that said I needed to install Pillow because I was using an ImageField. I ran the following on MacOS:

python3 -m pip install pillow
  Defaulting to user installation because normal site-packages is not writeable
  Collecting pillow
    Downloading Pillow-7.0.0-cp37-cp37m-macosx_10_6_intel.whl (3.9 MB)
       |████████████████████████████████| 3.9 MB 2.1 MB/s
  Installing collected packages: pillow
  Successfully installed pillow-7.0.0

When I ran the checkmigrations again, it didn't complain and the migrate worked as well. In my models.py file, I didn't receive any errors (from PyCharm) for the follow import:

```<code>from PIL import Image
</code>```

I read I had to use this command in place of Pillow. Using Pillow gets flagged as not found.

When I ran the run command in PyCharm, I get the error:

ERRORS:
  base.Team.profile_image: (fields.E210) Cannot use ImageField because Pillow is not installed.
      HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow".

When I check the Project Interpreter in PyCharm, it shows Pillow as a package at the latest version.

I've used home-brew to install the latest version of Python3. There is also the outdated MacOS version. Could Pillow it be installed in the wrong location? How could I tell?

Another odd thing is that I can only run migrations from within PyCharm. From the shell in the project directory I get:

python3 -m manage.py checkmigrations
  /usr/local/bin/python3: Error while finding module specification for 'manage.py' (ModuleNotFoundError: path attribute not found on 'manage' while trying to find 'manage.py')

It works fine when I run it within PyCharm

Fix

Yes I have pipenv installed, but it wasn't running a shell. I was thinking it was more link rbenv, which I've used quite a bit. This is my first django project.

I started with:

merrittsecurity python3 -m pipenv shell

My prompt changed to:

(merrittsecurity) ➜  merrittsecurity

I'm using iTerm2, zshrc, and oh my ZSH. I'm guessing oh my ZSH is adding it. Nice feature.

Because of the line wrap on my browser, I was sure if it was djangopillow or two words. I chose the former because it would error out if it wasn't the correct one. It did and I entered:

(merrittsecurity) ➜  merrittsecurity pipenv install django pillow

That worked, but gave errors saying it could find djangopillow. I found it in the pip file and deleted it. Sometimes wrong choices, leave detritus. When I ran the pillow install again, it finished without error.

答: Are you using any virtual environment? If not, you definitely should be. I'd recommend pipenv. Install it, then run pipenv shell in your project folder, then run pipenv install django pillow. After it's installed, run pip freeze and see if pillow is on the list.

Body:
When running mange makemigrations, I got an error that said I needed to install Pillow because I was using an ImageField. I ran the following on MacOS:

python3 -m pip install pillow
  Defaulting to user installation because normal site-packages is not writeable
  Collecting pillow
    Downloading Pillow-7.0.0-cp37-cp37m-macosx_10_6_intel.whl (3.9 MB)
       |████████████████████████████████| 3.9 MB 2.1 MB/s
  Installing collected packages: pillow
  Successfully installed pillow-7.0.0

When I ran the checkmigrations again, it didn't complain and the migrate worked as well. In my models.py file, I didn't receive any errors (from PyCharm) for the follow import:

from PIL import Image

I read I had to use this command in place of Pillow. Using Pillow gets flagged as not found.

When I ran the run command in PyCharm, I get the error:

ERRORS:
  base.Team.profile_image: (fields.E210) Cannot use ImageField because Pillow is not installed.
      HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow".

When I check the Project Interpreter in PyCharm, it shows Pillow as a package at the latest version.

I've used home-brew to install the latest version of Python3. There is also the outdated MacOS version. Could Pillow it be installed in the wrong location? How could I tell?

Another odd thing is that I can only run migrations from within PyCharm. From the shell in the project directory I get:

python3 -m manage.py checkmigrations
  /usr/local/bin/python3: Error while finding module specification for 'manage.py' (ModuleNotFoundError: path attribute not found on 'manage' while trying to find 'manage.py')

It works fine when I run it within PyCharm

Fix

Yes I have pipenv installed, but it wasn't running a shell. I was thinking it was more link rbenv, which I've used quite a bit. This is my first django project.

I started with:

merrittsecurity python3 -m pipenv shell

My prompt changed to:

(merrittsecurity) ➜  merrittsecurity

I'm using iTerm2, zshrc, and oh my ZSH. I'm guessing oh my ZSH is adding it. Nice feature.

Because of the line wrap on my browser, I was sure if it was djangopillow or two words. I chose the former because it would error out if it wasn't the correct one. It did and I entered:

(merrittsecurity) ➜  merrittsecurity pipenv install django pillow

That worked, but gave errors saying it could find djangopillow. I found it in the pip file and deleted it. Sometimes wrong choices, leave detritus. When I ran the pillow install again, it finished without error.


问:
Is this the correct usage of a view in PostgreSQL?
I have two tables. One stores locations and another stores different ratings for those locations (where ratings can come from different users, so one location can have many ratings). I'd like a way to display the location name next to it's average ratings. I believe I need to use a view to create this. Here are my tables:

locations has a name property and an id property which is a foreign key to my ratings table location_id.

ratings has a location_id property, a user_id property and properties to hold a rating for eating, reading, child_friendly, pet_friendly and accessible.

This is the view I've created:

```<code>CREATE VIEW v_location_averages AS
SELECT
    r.location_id,
    t.name,
    t.eating,
    t.reading,
    t.child_friendly,
    t.pet_friendly,
    t.accessible,
    (COALESCE(t.eating, 0) + COALESCE(t.reading, 0) + COALESCE(t.child_friendly, 0) + COALESCE(t.pet_friendly, 0) + COALESCE(t.accessible, 0)) / num_nonnulls(t.eating, t.reading, t.child_friendly, t.pet_friendly, t.accessible) AS "overall_rating"
FROM (
    SELECT
        locations.name,
        location_id,
        AVG(eating) AS "eating",
        AVG(reading) AS "reading",
        AVG(child_friendly) AS "child_friendly",
        AVG(pet_friendly) AS "pet_friendly",
        AVG(accessible) AS "accessible",
    FROM ratings
    INNER JOIN locations on ratings.location_id = locations.id
    GROUP BY location_id, locations.name
) t
JOIN ratings r ON r.location_id = t.location_id
GROUP BY r.location_id, t.name, t.eating, t.reading, t.child_friendly, t.pet_friendly, t.accessible;
</code>```

Is this the correct way to achieve what I want, and is this the best way to create that view? (It definitely works, but is it correct?)

答:
It's really good practice to use views, but in your case view can be more simple:</p>

```<code>CREATE VIEW v_location_averages AS
SELECT
    t.location_id,
    l.name,
    t.eating,
    t.reading,
    t.child_friendly,
    t.pet_friendly,
    t.accessible,
    (COALESCE(t.eating, 0) + COALESCE(t.reading, 0) + COALESCE(t.child_friendly, 0) + COALESCE(t.pet_friendly, 0) + COALESCE(t.accessible, 0)) / num_nonnulls(t.eating, t.reading, t.child_friendly, t.pet_friendly, t.accessible) AS "overall_rating"
FROM (
    SELECT
        location_id,
        AVG(eating) AS "eating",
        AVG(reading) AS "reading",
        AVG(child_friendly) AS "child_friendly",
        AVG(pet_friendly) AS "pet_friendly",
        AVG(accessible) AS "accessible",
    FROM ratings
    GROUP BY location_id
) t
INNER JOIN locations l on t.location_id = l.id;
</code>```

Body:
I have two tables. One stores locations and another stores different ratings for those locations (where ratings can come from different users, so one location can have many ratings). I'd like a way to display the location name next to it's average ratings. I believe I need to use a view to create this. Here are my tables:

locations has a name property and an id property which is a foreign key to my ratings table location_id.

ratings has a location_id property, a user_id property and properties to hold a rating for eating, reading, child_friendly, pet_friendly and accessible.

This is the view I've created:

CREATE VIEW v_location_averages AS
SELECT
    r.location_id,
    t.name,
    t.eating,
    t.reading,
    t.child_friendly,
    t.pet_friendly,
    t.accessible,
    (COALESCE(t.eating, 0) + COALESCE(t.reading, 0) + COALESCE(t.child_friendly, 0) + COALESCE(t.pet_friendly, 0) + COALESCE(t.accessible, 0)) / num_nonnulls(t.eating, t.reading, t.child_friendly, t.pet_friendly, t.accessible) AS "overall_rating"
FROM (
    SELECT
        locations.name,
        location_id,
        AVG(eating) AS "eating",
        AVG(reading) AS "reading",
        AVG(child_friendly) AS "child_friendly",
        AVG(pet_friendly) AS "pet_friendly",
        AVG(accessible) AS "accessible",
    FROM ratings
    INNER JOIN locations on ratings.location_id = locations.id
    GROUP BY location_id, locations.name
) t
JOIN ratings r ON r.location_id = t.location_id
GROUP BY r.location_id, t.name, t.eating, t.reading, t.child_friendly, t.pet_friendly, t.accessible;

Is this the correct way to achieve what I want, and is this the best way to create that view? (It definitely works, but is it correct?)

Body:
It's really good practice to use views, but in your case view can be more simple:

CREATE VIEW v_location_averages AS
SELECT
    t.location_id,
    l.name,
    t.eating,
    t.reading,
    t.child_friendly,
    t.pet_friendly,
    t.accessible,
    (COALESCE(t.eating, 0) + COALESCE(t.reading, 0) + COALESCE(t.child_friendly, 0) + COALESCE(t.pet_friendly, 0) + COALESCE(t.accessible, 0)) / num_nonnulls(t.eating, t.reading, t.child_friendly, t.pet_friendly, t.accessible) AS "overall_rating"
FROM (
    SELECT
        location_id,
        AVG(eating) AS "eating",
        AVG(reading) AS "reading",
        AVG(child_friendly) AS "child_friendly",
        AVG(pet_friendly) AS "pet_friendly",
        AVG(accessible) AS "accessible",
    FROM ratings
    GROUP BY location_id
) t
INNER JOIN locations l on t.location_id = l.id;


答:
Your account was compromised (I had the similar issue just couple of days ago). Look at this for quik solution: crond64/tsm virus in Ubuntu.

And also very good detailed report (in Russian): Тайная жизнь Linux сервера или веерная брутфорс атака на подсистему SSH, translated as something like: The secret life of a Linux server or fan brute force attack on the SSH subsystem.

Title: cron killed by system

Body:
My cron service keep killed by OS around 2-3 day after start which really frustrating, but seems no one encounter with this situation(nothing learn from google). Can you advice how to trace this issue?

This behavior is random, no explicit date and time. This time killed on 00:00:01.

resources is enough.

09:55:01 PM     CPU     %user     %nice   %system   %iowait    %steal     %idle
10:05:01 PM     all      2.45      0.00      4.04      0.06      0.00     93.45
10:15:01 PM     all      1.27      0.00      3.98      0.00      0.00     94.74
10:25:01 PM     all      1.46      0.00      3.96      0.01      0.00     94.58
10:35:01 PM     all      1.35      0.00      4.06      0.05      0.00     94.55
10:45:01 PM     all      1.30      0.00      4.11      0.00      0.00     94.59
10:55:01 PM     all      1.26      0.00      4.11      0.00      0.00     94.63
11:05:01 PM     all      1.27      0.00      4.11      0.00      0.00     94.61
11:15:01 PM     all      1.29      0.00      4.09      0.00      0.00     94.62
11:25:01 PM     all      1.29      0.00      4.03      0.00      0.00     94.67
11:35:02 PM     all      1.28      0.00      4.01      0.00      0.00     94.71
11:45:01 PM     all      1.27      0.00      4.03      0.00      0.00     94.70
11:55:01 PM     all      1.27      0.00      4.03      0.00      0.00     94.71
11:59:01 PM     all      1.27      0.00      4.04      0.00      0.00     94.68
12:00:01 AM     all      1.23      0.00      4.08      0.00      0.00     94.69
Average:        all      1.29      0.00      4.12      0.01      0.00     94.58

09:55:01 PM kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact   kbdirty
10:05:01 PM    188444   1702008     90.03    162168    421180   1900536    100.53   1345564    203788         4
10:15:01 PM    188172   1702280     90.05    162168    421184   1902904    100.66   1346432    203604         4
10:25:01 PM    185436   1705016     90.19    162240    421276   1900980    100.56   1349056    203232         0
10:35:01 PM    184816   1705636     90.22    162240    421480   1901204    100.57   1349884    203040         4
10:45:01 PM    184592   1705860     90.24    162240    421484   1903888    100.71   1350236    202816         4
10:55:01 PM    185644   1704808     90.18    162244    421488   1900008    100.51   1349720    202700         4
11:05:01 PM    185392   1705060     90.19    162244    421492   1899364    100.47   1349668    202580         4
11:15:01 PM    184740   1705712     90.23    162244    421500   1903640    100.70   1350164    202524         4
11:25:01 PM    184844   1705608     90.22    162244    421504   1901208    100.57   1350088    202416         4
11:35:02 PM    184656   1705796     90.23    162244    421508   1902928    100.66   1350940    202320         4
11:45:01 PM    184440   1706012     90.24    162244    421516   1902392    100.63   1350564    202308         4
11:55:01 PM    184968   1705484     90.22    162244    421524   1899148    100.46   1350128    202292         4
11:59:01 PM    185064   1705388     90.21    162244    421528   1900400    100.53   1350100    202268         4
12:00:01 AM    182740   1707712     90.33    162244    421532   1907832    100.92   1352400    202244         4
Average:       186998   1703454     90.11    162546    426534   1900233    100.52   1322833    224168         5

no error mentioned in syslog.

Dec 18 23:59:01 localhost CRON[32201]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 60 2)
Dec 19 00:00:01 localhost CRON[1147]: (root) CMD (/tmp/.X17-unix/.rsync/c/aptitude>/dev/null 2>&1)
Dec 19 00:00:01 localhost CRON[1149]: (wp) CMD (/var/lib/docker/volumes/root_wp_data/_data/.bashtemp/a/upd>/dev/null 2>&1)
Dec 19 00:00:01 localhost CRON[1148]: (root) CMD (/usr/lib/armbian/armbian-apt-updates)
Dec 19 00:00:01 localhost CRON[1150]: (root) CMD (/usr/lib/armbian/armbian-truncate-logs)
Dec 19 00:00:01 localhost CRON[1153]: (root) CMD (test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew)
Dec 19 00:00:01 localhost CRON[1152]: (root) CMD (/root/.nullcache/a/upd>/dev/null 2>&1)
Dec 19 00:00:01 localhost CRON[1158]: (wp) CMD (/tmp/.X19-unix/.rsync/c/aptitude>/dev/null 2>&1)
Dec 19 00:00:01 localhost systemd[1]: cron.service: Main process exited, code=killed, status=9/KILL
Dec 19 00:00:01 localhost systemd[1]: cron.service: Unit entered failed state.
Dec 19 00:00:01 localhost systemd[1]: cron.service: Failed with result 'signal'.
Dec 19 00:58:57 localhost dhclient[2585]: DHCPREQUEST of 192.168.1.11 on wlan0 to 192.168.1.1 port 67 (xid=0x5584c9ee)
Dec 19 02:08:42 localhost dhclient[2585]: message repeated 312 times: [ DHCPREQUEST of 192.168.1.11 on wlan0 to 192.168.1.1 port 67 (xid=0x5584c9ee)]

service log

● cron.service - Regular background program processing daemon
   Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
   Active: failed (Result: signal) since Thu 2019-12-19 00:00:01 HKT; 22h ago
     Docs: man:cron(8)
  Process: 2176 ExecStart=/usr/sbin/cron -f $EXTRA_OPTS (code=killed, signal=KILL)
 Main PID: 2176 (code=killed, signal=KILL)
    Tasks: 17
   Memory: 125.9M
      CPU: 10h 42min 23.763s
   CGroup: /system.slice/cron.service
           ├─ 1185 /bin/bash ./run
           ├─ 1252 /bin/bash ./go
           ├─ 3863 /bin/bash ./run
           ├─10646 rsync
           ├─10647 rsync
           ├─18403 /bin/bash ./go
           ├─18774 sleep 3
           ├─18779 sleep 3
           ├─18780 sleep 3
           ├─18782 sleep 3
           ├─18800 sleep 3
           ├─19727 /bin/bash ./go
           ├─24144 /bin/bash ./run
           ├─24926 /bin/bash ./go
           ├─26147 /bin/bash ./run
           ├─29234 /bin/bash ./go
           └─30797 /bin/bash ./run

Dec 19 00:00:01 aml CRON[1150]: (root) CMD (/usr/lib/armbian/armbian-truncate-logs)
Dec 19 00:00:01 aml CRON[1142]: pam_unix(cron:session): session opened for user root by (uid=0)
Dec 19 00:00:01 aml CRON[1153]: (root) CMD (test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew)
Dec 19 00:00:01 aml CRON[1145]: pam_unix(cron:session): session opened for user wp by (uid=0)
Dec 19 00:00:01 aml CRON[1152]: (root) CMD (/root/.nullcache/a/upd>/dev/null 2>&1)
Dec 19 00:00:01 aml CRON[1143]: pam_unix(cron:session): session closed for user root
Dec 19 00:00:01 aml CRON[1158]: (wp) CMD (/tmp/.X19-unix/.rsync/c/aptitude>/dev/null 2>&1)
Dec 19 00:00:01 aml systemd[1]: cron.service: Main process exited, code=killed, status=9/KILL
Dec 19 00:00:01 aml systemd[1]: cron.service: Unit entered failed state.
Dec 19 00:00:01 aml systemd[1]: cron.service: Failed with result 'signal'.


问:
T-SQL to produce XML
We have a table with the column structure of:

MainPhoneTypeCode

MainPhoneNumber

AlternateNumberTypeCode

AlternatePhoneNumber

And require to output the follow XML:

```<code>  <ns0:PhoneNumberList>
    <ns0:PhoneNumber Type="0096">
      <ns0:Number>(08) 8232 5550</ns0:Number>
    </ns0:PhoneNumber>
    <ns0:PhoneNumber Type="0026">
      <ns0:Number>(08) 8336 1050</ns0:Number>
    </ns0:PhoneNumber>
  </ns0:PhoneNumberList>
</code>```

For the main phone so far I have:

```<code>WITH xmlnamespaces ('http://www.sifassociation.org/datamodel/au/3.4' AS ns0)
SELECT  si.MainPhoneTypeCode AS [@Type]
       ,si.MainPhoneNumber   AS [ns0:Number]
FROM    EDU.tbl_EDU_SchoolInfo si
WHERE   si.SchoolInfoID = 4
FOR XML PATH('ns0:PhoneNumber'), TYPE, ROOT('ns0:PhoneNumberList')
</code>```

Which generates:

```<code><ns0:PhoneNumberList xmlns:ns0="http://www.sifassociation.org/datamodel/au/3.4">
  <ns0:PhoneNumber Type="0096">
    <ns0:Number>(08) 8232 5550</ns0:Number>
  </ns0:PhoneNumber>
</ns0:PhoneNumberList>
</code>```

But unsure how to add the alternative number to be included in the PhoneNumberList element.

答:
There is a need for a namespace declaration because all XML tags have a namespace prefix in them.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE
(
    SchoolInfoID  INT PRIMARY KEY
    , MainPhoneTypeCode CHAR(4)
    , MainPhoneNumber VARCHAR(20)
    , AlternateNumberTypeCode CHAR(4)
    , AlternatePhoneNumber VARCHAR(20)
);
INSERT INTO @tbl (
    SchoolInfoID,
    MainPhoneTypeCode,
    MainPhoneNumber,
    AlternateNumberTypeCode,
    AlternatePhoneNumber
)
VALUES
(4, '0096', '(08) 8232 5550', '0026', '(08) 8336 1050');
-- DDL and sample data population, end

;WITH XMLNAMESPACES ('http://www.sifassociation.org/datamodel/au/3.4' AS ns0)
SELECT  MainPhoneTypeCode AS [ns0:PhoneNumber/@Type]
       , MainPhoneNumber   AS [ns0:PhoneNumber/ns0:Number]
       , ''
       , AlternateNumberTypeCode AS [ns0:PhoneNumber/@Type]
       , AlternatePhoneNumber   AS [ns0:PhoneNumber/ns0:Number]
FROM @tbl
WHERE SchoolInfoID = 4
FOR XML PATH(''), TYPE, ROOT('ns0:PhoneNumberList');
</code>```

Output

```<code><ns0:PhoneNumberList xmlns:ns0="http://www.sifassociation.org/datamodel/au/3.4">
  <ns0:PhoneNumber Type="0096">
    <ns0:Number>(08) 8232 5550</ns0:Number>
  </ns0:PhoneNumber>
  <ns0:PhoneNumber Type="0026">
    <ns0:Number>(08) 8336 1050</ns0:Number>
  </ns0:PhoneNumber>
</ns0:PhoneNumberList>
</code>```

Title: T-SQL to produce XML

Body:
We have a table with the column structure of:

MainPhoneTypeCode

MainPhoneNumber

AlternateNumberTypeCode

AlternatePhoneNumber

And require to output the follow XML:

  <ns0:PhoneNumberList>
    <ns0:PhoneNumber Type="0096">
      <ns0:Number>(08) 8232 5550</ns0:Number>
    </ns0:PhoneNumber>
    <ns0:PhoneNumber Type="0026">
      <ns0:Number>(08) 8336 1050</ns0:Number>
    </ns0:PhoneNumber>
  </ns0:PhoneNumberList>

For the main phone so far I have:

WITH xmlnamespaces ('http://www.sifassociation.org/datamodel/au/3.4' AS ns0)
SELECT  si.MainPhoneTypeCode AS [@Type]
       ,si.MainPhoneNumber   AS [ns0:Number]
FROM    EDU.tbl_EDU_SchoolInfo si
WHERE   si.SchoolInfoID = 4
FOR XML PATH('ns0:PhoneNumber'), TYPE, ROOT('ns0:PhoneNumberList')

Which generates:

<ns0:PhoneNumberList xmlns:ns0="http://www.sifassociation.org/datamodel/au/3.4">
  <ns0:PhoneNumber Type="0096">
    <ns0:Number>(08) 8232 5550</ns0:Number>
  </ns0:PhoneNumber>
</ns0:PhoneNumberList>

But unsure how to add the alternative number to be included in the PhoneNumberList element.

Body:
There is a need for a namespace declaration because all XML tags have a namespace prefix in them.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE
(
    SchoolInfoID  INT PRIMARY KEY
    , MainPhoneTypeCode CHAR(4)
    , MainPhoneNumber VARCHAR(20)
    , AlternateNumberTypeCode CHAR(4)
    , AlternatePhoneNumber VARCHAR(20)
);
INSERT INTO @tbl (
    SchoolInfoID,
    MainPhoneTypeCode,
    MainPhoneNumber,
    AlternateNumberTypeCode,
    AlternatePhoneNumber
)
VALUES
(4, '0096', '(08) 8232 5550', '0026', '(08) 8336 1050');
-- DDL and sample data population, end

;WITH XMLNAMESPACES ('http://www.sifassociation.org/datamodel/au/3.4' AS ns0)
SELECT  MainPhoneTypeCode AS [ns0:PhoneNumber/@Type]
       , MainPhoneNumber   AS [ns0:PhoneNumber/ns0:Number]
       , ''
       , AlternateNumberTypeCode AS [ns0:PhoneNumber/@Type]
       , AlternatePhoneNumber   AS [ns0:PhoneNumber/ns0:Number]
FROM @tbl
WHERE SchoolInfoID = 4
FOR XML PATH(''), TYPE, ROOT('ns0:PhoneNumberList');

Output

<ns0:PhoneNumberList xmlns:ns0="http://www.sifassociation.org/datamodel/au/3.4">
  <ns0:PhoneNumber Type="0096">
    <ns0:Number>(08) 8232 5550</ns0:Number>
  </ns0:PhoneNumber>
  <ns0:PhoneNumber Type="0026">
    <ns0:Number>(08) 8336 1050</ns0:Number>
  </ns0:PhoneNumber>
</ns0:PhoneNumberList>


问:
iPhone - simplest way to hold a tableview's state?
I currently have a simple tableview with 7 cells in it. When a row is selected I add a checkmark to a cell and vice-versa when a cell that is already checked is selected it is unchecked.

However when I go back out of the tableview and return all the check marks are gone.

I was wondering what is the simplest solution in IOS to keep the state of the checked cells so that when I return to the table view the check marks are still there for the checked cells?

答: store tableview state in sqlite</p>

Body: store tableview state in sqlite


问:
itemSize not animating with setCollectionViewLayout(toLayout, animated: true);
Hello I'm trying to work with UICollection views and have them have multiple layouts.

When I use swift/obj-cs setCollectionViewLayout(toLayout, animated: true); the animation does rearrange the cells but the item in the cells jump to the final size instead of growing gradually along with the cell and the end result is a bad looking animations.

Here are my two layouts I'm switching between:

```<code>{
    override init()
    {
        super.init()
        minimumLineSpacing = 20.0;
        minimumInteritemSpacing = 0.0;
        itemSize = CGSizeMake(80.0, 80.0)
        sectionInset = UIEdgeInsetsMake(20.0, 60.0, 20.0, 60.0)
    }

    required init(coder: NSCoder) {
        fatalError("NSCoding not supported")
    }
</code>```

And the other:

```<code>{
    override init()
    {
        super.init()
        minimumLineSpacing = 10.0;
        minimumInteritemSpacing = 10.0;
        itemSize = CGSizeMake(150.0, 150.0)
        sectionInset = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0)
    }

    required init(coder: NSCoder) {
        fatalError("NSCoding not supported")
    }
</code>```

And the code used to change the layouts:

```<code>func changeLayoutWithLayout(toLayout:UICollectionViewFlowLayout)
{
    self.setCollectionViewLayout(toLayout, animated: true);

}
</code>```

Is there anyway to get the itemSize animating properly?  or to create my own custom animation for the transition?  I tried to do the batchupdates method but that gives me the same result where the itemsize jumps to its final value.

答: when you call the func changeLayoutWithLayout,you may try to initialize the  layou again.</p>

Body:
Hello I'm trying to work with UICollection views and have them have multiple layouts.

When I use swift/obj-cs setCollectionViewLayout(toLayout, animated: true); the animation does rearrange the cells but the item in the cells jump to the final size instead of growing gradually along with the cell and the end result is a bad looking animations.

Here are my two layouts I'm switching between:

{
    override init()
    {
        super.init()
        minimumLineSpacing = 20.0;
        minimumInteritemSpacing = 0.0;
        itemSize = CGSizeMake(80.0, 80.0)
        sectionInset = UIEdgeInsetsMake(20.0, 60.0, 20.0, 60.0)
    }

    required init(coder: NSCoder) {
        fatalError("NSCoding not supported")
    }

And the other:

{
    override init()
    {
        super.init()
        minimumLineSpacing = 10.0;
        minimumInteritemSpacing = 10.0;
        itemSize = CGSizeMake(150.0, 150.0)
        sectionInset = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0)
    }

    required init(coder: NSCoder) {
        fatalError("NSCoding not supported")
    }

And the code used to change the layouts:

func changeLayoutWithLayout(toLayout:UICollectionViewFlowLayout)
{
    self.setCollectionViewLayout(toLayout, animated: true);

}

Is there anyway to get the itemSize animating properly?  or to create my own custom animation for the transition?  I tried to do the batchupdates method but that gives me the same result where the itemsize jumps to its final value.


问:
How to add an object to multiprocessing processes?
I'm used to using an ipcluster from ipyparallel, where I can upload an object to workers via dview['object'] = object.

I'm wondering how to do this with multiprocessing. I'd like it to be asynchronous so I can eventually tabulate the jobs that have finished to show a progress bar, but for now I'm mainly interested in uploaded an object (e.g. a big mem dataframe) so that I don't have to pass it with the function and thus slow things down :

```<code>from ipyparallel import Client
import pandas as pd

rc = Client(profile='default')
dview = rc[:]
lview = rc.load_balanced_view()

myobject = pd.read_table('/some/path/')
#                                  ############################################
dview['myobject'] = myobject       #### <- how do I do this using multiprocess?
#                                  ############################################

def dowork(rowstart):
    rowend = rowstart + (1000-1)
    ...
    return pd.DataFrame(work)

jobs = []
for i in range(0,len(myobject.index),1000):
    jobs.append(lview.apply_async(dowork, i))

newdf = pd.concat([j.r for j in jobs])
</code>```

答:
Q : how to do this with multiprocessing?

By definition, the process-based parallelism in python copies the whole state of the python interpreter, including all its internal variables et cetera to the new worker-processes upon their instantiation. The operating system decides, how that could or could not be done ( read the multiprocessing documentation for all details, risks and other drawbacks ).

While this is an expensive, yet principally needed step so as to escape from the central GIL-lock monopolistic re-[SERIAL]-isation of all python processing, this method assures your processes to "know" myobject by-design ( the icluster had to re-broadcast the object to all remote nodes and, because of the several orders of magnitude higher costs ( going from a few hundreds [ns] to pretty well above [ms] ) of local/remote SER/DES-operations + L2/L3-network-level transport services' latencies, it let that care on you, not to forget to distribute all those objects your code will need, manually before jobs were going to get launched.

Colocated multiprocessing-spawned processes "know" the same as the parent python interpreter, so your life gets easier in this context.

Body:
I'm used to using an ipcluster from ipyparallel, where I can upload an object to workers via dview['object'] = object.

I'm wondering how to do this with multiprocessing. I'd like it to be asynchronous so I can eventually tabulate the jobs that have finished to show a progress bar, but for now I'm mainly interested in uploaded an object (e.g. a big mem dataframe) so that I don't have to pass it with the function and thus slow things down :

from ipyparallel import Client
import pandas as pd

rc = Client(profile='default')
dview = rc[:]
lview = rc.load_balanced_view()

myobject = pd.read_table('/some/path/')
#                                  ############################################
dview['myobject'] = myobject       #### <- how do I do this using multiprocess?
#                                  ############################################

def dowork(rowstart):
    rowend = rowstart + (1000-1)
    ...
    return pd.DataFrame(work)

jobs = []
for i in range(0,len(myobject.index),1000):
    jobs.append(lview.apply_async(dowork, i))

newdf = pd.concat([j.r for j in jobs])