问:
Parent Content appear in child sub_routes
I'm quite confused of routes children ,

I have 'About' route which have 'me' as a sub-route

```<code> {
    path: '/about',
    name: 'About',
    component: About,
    children: [
      {
        name: 'Me',
        path: '/about/me',
        component: Me,
      },
    ],
  },
</code>```

in App.vue ,

```<code><template>
  <div id="app">
    <div id="nav">
      <ul>
        <router-link to="/about" tag="li" replace>About</router-link>
        <router-link to="/Test" tag="li">Test</router-link>
        <router-link to="/Blog" tag="li">Blog</router-link>
      </ul>
    </div>
    <div id="nav" v-if="inArray(this.$router.currentRoute.name,pathes)">
      <ul>
        <router-link to="/about/me" tag="li">Me</router-link>
      </ul>
    </div>
    <router-view/>
  </div>
</template>
</code>```

I've read a lot of answers related to the subject but still can't figure out why Parent content is showing on navigating to /me

答:
try to do it as below:

const Index = {
  template: `<div>Index</div>`
}
const About = {
  template: `

      About
      <router-view></router-view>

  `
}
const Test = {
  template: `<div>Test</div>`
}
const Blog = {
  template: `<div>Blog</div>`
}
const Me = {
  template: `<div>Me</div>`
}

const router = new VueRouter({
  routes: [
    {
      path: '/',
      name: 'index',
      component: Index
    },
    {
      path: '/test',
      name: 'test',
      component: Test,
    },
    {
      path: '/blog',
      name: 'blog',
      component: Blog,
    },
    {
      path: '/about',
      name: 'about',
      component: About,
      children: [
        {
          path: 'me',
          name: 'aboutMe',
          component: Me,
        }
      ]
    }
  ]
});

new Vue({
  el: '#app',
  router
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.1.3/vue-router.min.js"></script>

<div id="app">
  <div id="nav">
    <ul>
      <router-link to="/about" tag="li" replace>About</router-link>
      <router-link to="/Test" tag="li">Test</router-link>
      <router-link to="/Blog" tag="li">Blog</router-link>
    </ul>
  </div>
  <div>
    <ul>
      <router-link to="/about/me" tag="li">Me</router-link>
    </ul>
  </div>
  <router-view></router-view>
</div></code>```

Body:
I'm quite confused of routes children ,

I have 'About' route which have 'me' as a sub-route

 {
    path: '/about',
    name: 'About',
    component: About,
    children: [
      {
        name: 'Me',
        path: '/about/me',
        component: Me,
      },
    ],
  },

in App.vue ,

<template>

        <router-link to="/about" tag="li" replace>About</router-link>
        <router-link to="/Test" tag="li">Test</router-link>
        <router-link to="/Blog" tag="li">Blog</router-link>

        <router-link to="/about/me" tag="li">Me</router-link>

    <router-view/>

</template>

I've read a lot of answers related to the subject but still can't figure out why Parent content is showing on navigating to /me

Body:
try to do it as below:

const Index = {
  template: `<div>Index</div>`
}
const About = {
  template: `
    <div>
      About
      <router-view></router-view>
    </div>
  `
}
const Test = {
  template: `<div>Test</div>`
}
const Blog = {
  template: `<div>Blog</div>`
}
const Me = {
  template: `<div>Me</div>`
}

const router = new VueRouter({
  routes: [
    {
      path: '/',
      name: 'index',
      component: Index
    },
    {
      path: '/test',
      name: 'test',
      component: Test,
    },
    {
      path: '/blog',
      name: 'blog',
      component: Blog,
    },
    {
      path: '/about',
      name: 'about',
      component: About,
      children: [
        {
          path: 'me',
          name: 'aboutMe',
          component: Me,
        }
      ]
    }
  ]
});

new Vue({
  el: '#app',
  router
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.1.3/vue-router.min.js"></script>

<div id="app">
  <div id="nav">
    <ul>
      <router-link to="/about" tag="li" replace>About</router-link>
      <router-link to="/Test" tag="li">Test</router-link>
      <router-link to="/Blog" tag="li">Blog</router-link>
    </ul>
  </div>
  <div>
    <ul>
      <router-link to="/about/me" tag="li">Me</router-link>
    </ul>
  </div>
  <router-view></router-view>
</div>


来源: stackexchange

问:
Pass required argument plus variable length arguments to function
I have a function that has one required parameter and a variable number of parameters.  I'm passing an array of blobs to the functions.  A simplified version of the function looks like this:

```<code>function test(directory, blob0, blob1) {
  for (var argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) {
    var bytes = arguments[argumentIndex].getBytes();
    //do some things
  }
}
</code>```

I'm using the rhino runtime so I can't use the spread operator.  The closest I've come to making it work is by using the apply function, but I'm not sure how to also pass the required parameter (directory) in the test function above.

```<code>var blobs = [];
blobs[0] = getBlob();
blobs[1] = getBlob();
blobs[2] = getBlob();

test.apply(null,blobs)  //doesn't set required parameter (directory)
</code>```

答:
You want to use an array of blobs as the expanded values of blob0, blob1, blob2 at test(directory, blob0, blob1, blob2).

You want to use directory at test(directory, blob0, blob1, blob2) by adding directory.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

In this answer, bind is used.

Modified script:

```<code>// sample getBlob(). This returns a blob.
function getBlob() {return Utilities.newBlob("sample", MimeType.PLAIN_TEXT)}

function test(directory, blob0, blob1, blob2) {
  Logger.log("%s, %s, %s, %s", directory, blob0, blob1, blob2) // <--- directory, Blob, Blob, Blob

  for (var argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) {
    var bytes = arguments[argumentIndex].getBytes();
    //do some things
  }
}

// Please run this function.
function myFunction() {
  var directory = "directory";

  var blobs = [];
  blobs[0] = getBlob();
  blobs[1] = getBlob();
  blobs[2] = getBlob();

  test.bind(this, directory).apply(null, blobs);
}
</code>```

In this modified script, directory is added using bind.

When myFunction() is run, you can see directory, Blob, Blob, Blob at Logger.log("%s, %s, %s, %s", directory, blob0, blob1, blob2) in the function test(directory, blob0, blob1, blob2).

References:

Function.prototype.bind()

Is JavaScript function.bind() supported in google sheets?

I thought that this thread might be useful.

If I misunderstood your question and this was not the direction you want, I apologize.

ContentLicense: CC BY-SA 4.0

Body:
I have a function that has one required parameter and a variable number of parameters.  I'm passing an array of blobs to the functions.  A simplified version of the function looks like this:

function test(directory, blob0, blob1) {
  for (var argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) {
    var bytes = arguments[argumentIndex].getBytes();
    //do some things
  }
}

I'm using the rhino runtime so I can't use the spread operator.  The closest I've come to making it work is by using the apply function, but I'm not sure how to also pass the required parameter (directory) in the test function above.

var blobs = [];
blobs[0] = getBlob();
blobs[1] = getBlob();
blobs[2] = getBlob();

test.apply(null,blobs)  //doesn't set required parameter (directory)

Body:
You want to use an array of blobs as the expanded values of blob0, blob1, blob2 at test(directory, blob0, blob1, blob2).

You want to use directory at test(directory, blob0, blob1, blob2) by adding directory.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

In this answer, bind is used.

Modified script:

// sample getBlob(). This returns a blob.
function getBlob() {return Utilities.newBlob("sample", MimeType.PLAIN_TEXT)}

function test(directory, blob0, blob1, blob2) {
  Logger.log("%s, %s, %s, %s", directory, blob0, blob1, blob2) // <--- directory, Blob, Blob, Blob

  for (var argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) {
    var bytes = arguments[argumentIndex].getBytes();
    //do some things
  }
}

// Please run this function.
function myFunction() {
  var directory = "directory";

  var blobs = [];
  blobs[0] = getBlob();
  blobs[1] = getBlob();
  blobs[2] = getBlob();

  test.bind(this, directory).apply(null, blobs);
}

In this modified script, directory is added using bind.

When myFunction() is run, you can see directory, Blob, Blob, Blob at Logger.log("%s, %s, %s, %s", directory, blob0, blob1, blob2) in the function test(directory, blob0, blob1, blob2).

References:

Function.prototype.bind()

Is JavaScript function.bind() supported in google sheets?

I thought that this thread might be useful.

If I misunderstood your question and this was not the direction you want, I apologize.


问:
How to Pass JSON Data into Express REST API
I am creating a REST API using Node/Express and had a question regarding setting up the API and how to incorporate a JSON file into it. I have the following as an example of the JSON data I would like to look up and it includes an ID number, model and color:

{
    "1": {
        "car_model": "Ferrari",
        "color": "Silver"
    },
    "2": {
        "car_model": "Porsche",
        "color": "Green"
    },
    "3": {
        "car_model": "Camry",
        "color": "Blue"
    }
}

Now, I'd like to have the GET route return all the cars in the JSON list and return the ID, color and model. I'm not sure how to incorporate the JSON data into the requests (say it is located on my hard-drive at path/JSON)

I have the following code set up as the basics for the API:

```<code>// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/endpoint_get', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

router.post('/endpoint_post', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /endpoint.com
app.use('/endpoint.com/', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
</code>```

Not necessarily using this code, I would like some guidance or help from anyone or an example of how one would incorporate the JSON data (from some random file) into the HTTP requests. Thank you

答:
One option would be to use node fs (filesystem).

One option is to convert your endpoint to an async function.

On each request open the file with fs.open(). Depending on your requirements, either read the entire file or provide an offset to read from.

Then parse the data with JSON.parse(), format and return.

Another option would be to do all the above steps on startup, saving the contents of the file to some sort of store. Then you can bypass the slow reading from disk in the request handling.

Here is some example code from node docs. I would recommend having a look at the different options.

I would also recommend using the methods that return a promise, (or promisify the callbacks). That way you code that accesses it can have a clean ordering to it.

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.fstat(fd, (err, stat) => {
    if (err) throw err;
    // use stat

    // always close the file descriptor!
    fs.close(fd, (err) => {
      if (err) throw err;
    });
  });
});
```

Body:
I am creating a REST API using Node/Express and had a question regarding setting up the API and how to incorporate a JSON file into it. I have the following as an example of the JSON data I would like to look up and it includes an ID number, model and color:

{
    "1": {
        "car_model": "Ferrari",
        "color": "Silver"
    },
    "2": {
        "car_model": "Porsche",
        "color": "Green"
    },
    "3": {
        "car_model": "Camry",
        "color": "Blue"
    }
}

Now, I'd like to have the GET route return all the cars in the JSON list and return the ID, color and model. I'm not sure how to incorporate the JSON data into the requests (say it is located on my hard-drive at path/JSON)

I have the following code set up as the basics for the API:

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/endpoint_get', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

router.post('/endpoint_post', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /endpoint.com
app.use('/endpoint.com/', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

Not necessarily using this code, I would like some guidance or help from anyone or an example of how one would incorporate the JSON data (from some random file) into the HTTP requests. Thank you


问:
WPF - How to detect when new Visual child elements are added?
Based on some custom security settings, I alter window child controls to readonly and disabled. To accomplish this, I loop through child controls when the window loads.

This works just fine. 99% perfect.

In my window I have an ItemsControl whose content is based on a ComboBox. Change the ComboBox, the child controls in the ItemsControl are databound again. But, then security (readonly/disabled) is no longer true.

Before you jump to the solution, I know I could handle the ComboBox changed event; but, I have many such boxes and wnt a generic solution to can apply at the window-level (think: base) no matter what my developers add to the window/form.

My question (sorry for the long lead in) is, how can I detect when a new child is added to the window because of some dynamic activity like databinding? Is there a NewChildAdded event? Is there a DataBindingJustChangedThings event?

There's gotta be something.

If your solution includes a timer, you need not reply. My forms are too complex to handle that extra load - and the delay between ticks is too real of a security issue.

You might be thinking, just make the outer-container readonly or disabled. But this has a negative effect on things like expanders, multi-line textboxes and listboxes. Such an approach is not grainular enough. Of course, it is where we started iterations ago.

If your solution includes a style, you need to include how I can override your approach on a per-control basis. Some controls (like a checkbox) cannot be disabled as they have a purpose in the UI layout.

Sorry for the constraints, but I plan to use the solution in production.

Thank you.

答:
Have you tried OnVisualChildrenChanged?</p>

```<code>    /// <summary>
    /// Handle visual children being added or removed
    /// </summary>
    /// <param name="visualAdded">Visual child added</param>
    /// <param name="visualRemoved">Visual child removed</param>
    protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
    {
        // Track when objects are added and removed
        if (visualAdded != null)
        {
            // Do stuff with the added object
        }
        if (visualRemoved != null)
        {
            // Do stuff with the removed object
        }

        // Call base function
        base.OnVisualChildrenChanged(visualAdded, visualRemoved);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Have you tried OnVisualChildrenChanged?

    /// <summary>
    /// Handle visual children being added or removed
    /// </summary>
    /// <param name="visualAdded">Visual child added</param>
    /// <param name="visualRemoved">Visual child removed</param>
    protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
    {
        // Track when objects are added and removed
        if (visualAdded != null)
        {
            // Do stuff with the added object
        }
        if (visualRemoved != null)
        {
            // Do stuff with the removed object
        }

        // Call base function
        base.OnVisualChildrenChanged(visualAdded, visualRemoved);
    }


问:
Speed up linq query perfomance
I'm running this linq query which is a little big.

```<code>var events = _context.Event.OrderByDescending(e => e.StartDate).Where(e => e.IsPresentation == true).Where(e => e.IsCanceled == false).Where(e => e.StartDate > new DateTime());
</code>```

And the page outputing the data from this query is taking too much time to load. Maybe because I'm using too many wheres.

I had the same issue using includes, and then includes, in a different query, but I divided the query, to improve the performance. But I'm trying to figure it out how to do the same thing in that situation, because I'm not using any include.

答:
You should store the value to one variable like var now = new DateTime()

Combine all of the conditions into one Where clause

Just OrderByDescending after Where clause, It means We just order based on actual data instead of all.

```<code>var now = new DateTime();
var events = _context.Event
                         .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate > now)
                         .OrderByDescending(e => e.StartDate);
</code>```

Tips

You should re-arrange your condition based on actual data. For example:

```<code>.Where(e => 1 == 2 && 2 == 2 && 3 == 3)
</code>```

As you can see, We no need to manipulate the rest of conditions from && 2 == 2 && 3 == 3 because of and condition.

Title: Speed up linq query perfomance

Body:
I'm running this linq query which is a little big.

var events = _context.Event.OrderByDescending(e => e.StartDate).Where(e => e.IsPresentation == true).Where(e => e.IsCanceled == false).Where(e => e.StartDate > new DateTime());

And the page outputing the data from this query is taking too much time to load. Maybe because I'm using too many wheres.

I had the same issue using includes, and then includes, in a different query, but I divided the query, to improve the performance. But I'm trying to figure it out how to do the same thing in that situation, because I'm not using any include.

Body:
You should store the value to one variable like var now = new DateTime()

Combine all of the conditions into one Where clause

Just OrderByDescending after Where clause, It means We just order based on actual data instead of all.

var now = new DateTime();
var events = _context.Event
                         .Where(e => e.IsPresentation && !e.IsCanceled && e.StartDate > now)
                         .OrderByDescending(e => e.StartDate);

Tips

You should re-arrange your condition based on actual data. For example:

.Where(e => 1 == 2 && 2 == 2 && 3 == 3)

As you can see, We no need to manipulate the rest of conditions from && 2 == 2 && 3 == 3 because of and condition.


问:
VS Code debug python script configuration ignores args attribute
I am trying to debug a python3 script I wrote that requires command line arguments without success.  I found VSCode: How debug Python script with arguments when searching stackoverflow and it points out that the attribute args should be set to a list of arguments.  However when I run the debug config that I created to debug a script under ./scripts I get back the argparse error the following arguments are required: database, media_url, images.  And I am not sure what I am overlooking

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Populate Database Script Debug",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/populate_sqlite.py",
            "console": "integratedTerminal",
            "args": ["db.sqlite3", "../tarot_juicer/static/img", "~/slipsnip/automation/tarot/out"],
            "cwd": "${workspaceFolder}/scripts/"
        }
    ]
}
</code>```

on the same subject of debuging python with vscode I also noted that when my populate_sqlite.py script attempts to read a file data.csv which exists in the same directory as the script, I get the FileNotFoundError: [Errno 2] File data.csv does not exist: 'data.csv' however if in the terminal I navigate into the script directory before running the debug config, that problem is solved though I am still left with the subject problem of this question, why is args being ignored?

If someone can explain how to fix the problem of my arguments not being passed to the script upon debug execution that would be greatly appreciated.  If someone could also lead me in the right direction as to how can I have files in the cwd exist without having to cd into the script directory that would also be greatly appreciated.  Thank you.

答: It seems to have corrected itself, having returned to the project today after a reboot.  Perhaps vscode needed to be restarted, the problem has gone away and args are now being passed.</p>

Body:
I am trying to debug a python3 script I wrote that requires command line arguments without success.  I found VSCode: How debug Python script with arguments when searching stackoverflow and it points out that the attribute args should be set to a list of arguments.  However when I run the debug config that I created to debug a script under ./scripts I get back the argparse error the following arguments are required: database, media_url, images.  And I am not sure what I am overlooking

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Populate Database Script Debug",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/scripts/populate_sqlite.py",
            "console": "integratedTerminal",
            "args": ["db.sqlite3", "../tarot_juicer/static/img", "~/slipsnip/automation/tarot/out"],
            "cwd": "${workspaceFolder}/scripts/"
        }
    ]
}

on the same subject of debuging python with vscode I also noted that when my populate_sqlite.py script attempts to read a file data.csv which exists in the same directory as the script, I get the FileNotFoundError: [Errno 2] File data.csv does not exist: 'data.csv' however if in the terminal I navigate into the script directory before running the debug config, that problem is solved though I am still left with the subject problem of this question, why is args being ignored?

If someone can explain how to fix the problem of my arguments not being passed to the script upon debug execution that would be greatly appreciated.  If someone could also lead me in the right direction as to how can I have files in the cwd exist without having to cd into the script directory that would also be greatly appreciated.  Thank you.


问:
Getting an error of "Client does not support authentication protocol requested by server" using MySQL Connector in Python
Hello Dear StackOverflow friends,

I'm receiving an strange error when connecting to a managed MySQL instance (DigitalOcean). The connection works on my Dev computer (Windows 8.1 machine), but not on the Prod server (CentOS 8, SELinux in permissive mode). The connection also works with MySQL Workbench.

I've done pip freeze on both mentioned environments and both results are mysql-connector-python==8.0.19 which I find very strange. I've made sure to run my tests with the venv activated.

The managed MySQL 8.x instance is set up to allow connections from both my droplet and my Dev IP address. I've also tried this without the firewall enabled. The managed instance requires the usage of an SSL enabled connection, so a CA Certificate is provided (I've applied chmod 777 over it for now to make sure that's not the cause of the problem).

I've checked the documentation of the library I'm using and it's compatible with MySQL 8.

It is also worth noting I've also tried the solution in this question about it.

The code is the following. Works as expected in Windows.

```<code>import datetime

import mysql.connector
from mysql.connector.constants import ClientFlag

dbconn_host = '<sanitized>'
dbconn_port = '<sanitized>'
dbconn_user = '<sanitized>'
dbconn_passwd = '<sanitized>'
dbconn_database = '<sanitized>'

cnx = mysql.connector.connect(
    host=dbconn_host,
    port=dbconn_port,
    user=dbconn_user,
    passwd=dbconn_passwd,
    database=dbconn_database,
    client_flags=ClientFlag.SSL,
    ssl_ca='.\\ca_certificate.crt', # When running on prod server I change it to a proper Linux path
    # auth_plugin='caching_sha2_password' # Trying another solution I had it changed to mysql_native_password
)

cur_a = cnx.cursor(buffered=True)

query_sel = (
    "SELECT * FROM datasources"
)

cur_a.execute(query_sel)

for w in cur_a:
    print(w[0])

</code>```

This is the stack trace I receive in Linux.

```<code>(venv) [root@<sanitized> <sanitized>]# python -i conn-test.py
Traceback (most recent call last):
  File "conn-test.py", line 12, in <module>
    cnx = mysql.connector.connect(
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/__init__.py", line 219, in connect
    return MySQLConnection(*args, **kwargs)
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 104, in __init__
    self.connect(**kwargs)
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/abstracts.py", line 960, in connect
    self._open_connection()
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 290, in _open_connection
    self._do_auth(self._user, self._password,
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 212, in _do_auth
    self._auth_switch_request(username, password)
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 256, in _auth_switch_request
    raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 1251: Client does not support authentication protocol requested by server; consider upgrading MySQL client
>>>
</code>```

What do you think could be the issue here?

答:
The magic of StackOverflow, is when you post a question that you find the solution in a few minutes. Two things happened:

Half the time I didn't have network connectivity to the MySQL database.

So I ran all kinds of tests before I could even ping the server, then I realized I should run all tests again, but I didn't start with the basics (I did all tests with patches applied, instead of trying a "vanilla" connection first, so to speak).

The solution is I commented out client_flags=ClientFlag.SSL, but left the CA Certificate enabled and the connection worked as expected in the Prod server.

Body:
Hello Dear StackOverflow friends,

I'm receiving an strange error when connecting to a managed MySQL instance (DigitalOcean). The connection works on my Dev computer (Windows 8.1 machine), but not on the Prod server (CentOS 8, SELinux in permissive mode). The connection also works with MySQL Workbench.

I've done pip freeze on both mentioned environments and both results are mysql-connector-python==8.0.19 which I find very strange. I've made sure to run my tests with the venv activated.

The managed MySQL 8.x instance is set up to allow connections from both my droplet and my Dev IP address. I've also tried this without the firewall enabled. The managed instance requires the usage of an SSL enabled connection, so a CA Certificate is provided (I've applied chmod 777 over it for now to make sure that's not the cause of the problem).

I've checked the documentation of the library I'm using and it's compatible with MySQL 8.

It is also worth noting I've also tried the solution in this question about it.

The code is the following. Works as expected in Windows.

import datetime

import mysql.connector
from mysql.connector.constants import ClientFlag

dbconn_host = '<sanitized>'
dbconn_port = '<sanitized>'
dbconn_user = '<sanitized>'
dbconn_passwd = '<sanitized>'
dbconn_database = '<sanitized>'

cnx = mysql.connector.connect(
    host=dbconn_host,
    port=dbconn_port,
    user=dbconn_user,
    passwd=dbconn_passwd,
    database=dbconn_database,
    client_flags=ClientFlag.SSL,
    ssl_ca='.\\ca_certificate.crt', # When running on prod server I change it to a proper Linux path
    # auth_plugin='caching_sha2_password' # Trying another solution I had it changed to mysql_native_password
)

cur_a = cnx.cursor(buffered=True)

query_sel = (
    "SELECT * FROM datasources"
)

cur_a.execute(query_sel)

for w in cur_a:
    print(w[0])

This is the stack trace I receive in Linux.

(venv) [root@<sanitized> <sanitized>]# python -i conn-test.py
Traceback (most recent call last):
  File "conn-test.py", line 12, in <module>
    cnx = mysql.connector.connect(
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/__init__.py", line 219, in connect
    return MySQLConnection(*args, **kwargs)
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 104, in __init__
    self.connect(**kwargs)
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/abstracts.py", line 960, in connect
    self._open_connection()
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 290, in _open_connection
    self._do_auth(self._user, self._password,
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 212, in _do_auth
    self._auth_switch_request(username, password)
  File "/var/<sanitized>/venv/lib/python3.8/site-packages/mysql/connector/connection.py", line 256, in _auth_switch_request
    raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 1251: Client does not support authentication protocol requested by server; consider upgrading MySQL client
>>>

What do you think could be the issue here?


问:
Decompose 3x3 Matrix
I have a 3x3 matrix I'm using to track movement in 2D. I need to extract from that the translation, rotation and scale matrices. Can anyone suggest how I would do this? I've had no luck searching online so far (possibly I'm using the wrong terms).</p>

答:
For a column major matrix, given:

X vector of < Xx, Xy >;

Y vector of < Yx, Yy > and

Translation/position of < Tx, Ty >,

The corresponding column major transformation matrix is:

```<code>The translation is:
</code>```

```<code>For the Scaling, the scale factors for the X and Y vectors are:
</code>```

The scaling transformation is then:

```<code>For Rotation, the normalized vectors are:
</code>```

X Vector: < Xx/Sx, Xy/Sx >

Y Vector: < Yx/Sy, Yy/Sy >

And the rotation transformation "R" is:

```<code>RECOMPOSITION:
</code>```

Given translation "T", rotation "R", and scaling "S" transformation in column major order, the original matrix/transform can be recreated with:

```<code>            T * R * S
</code>```

Assumption, the original transformation has X and Y vectors that are:

Not parallel;

Not a length of zero;

Not mirrored; and

Not skewed/sheared.

The rotation can be further decomposed into an angle as described by 3Dave (which is row major, and needs to be transposed to be column major).

Title: Decompose 3x3 Matrix

Body:
For a column major matrix, given:

X vector of < Xx, Xy >;

Y vector of < Yx, Yy > and

Translation/position of < Tx, Ty >,

The corresponding column major transformation matrix is:

The translation is:

For the Scaling, the scale factors for the X and Y vectors are:

The scaling transformation is then:

For Rotation, the normalized vectors are:

X Vector: < Xx/Sx, Xy/Sx >

Y Vector: < Yx/Sy, Yy/Sy >

And the rotation transformation "R" is:

RECOMPOSITION:

Given translation "T", rotation "R", and scaling "S" transformation in column major order, the original matrix/transform can be recreated with:

            T * R * S

Assumption, the original transformation has X and Y vectors that are:

Not parallel;

Not a length of zero;

Not mirrored; and

Not skewed/sheared.

The rotation can be further decomposed into an angle as described by 3Dave (which is row major, and needs to be transposed to be column major).


问:
Multiple conditional statements with groupby in pandas
I have a dataset similar to the following.

```<code>date,score
3/1/16,0.6369
5/1/16,-0.2023
6/1/16,0.04
7/1/16,0.0772
9/1/16,-0.4215
12/1/16,0.2960
15/1/16,0.25
15/1/16,0.7684
</code>```

I want to apply the following conditions on the score.

```<code>Con1: if the score is >.05, count that as positive for that date
Con2: if the score is  -0.05<=score <=.05, count that as neutral for that date
Con3: Else, count that as negative for that date
And add a new_column to the DataFrame alongside the score to put the 'negative'/'positive'/'neutral' result
</code>```

Expected Output:

```<code>date, score, mood
3/1/16,0.6369, positive
5/1/16,-.2023, negative
6/1/16,0.04, neutral
</code>```

And I have multiple scores on the same date. So, I thought of using groupby with multiple columns ('date'and 'score')  and pass through the if conditions and add a new column ['mood'] to the DataFrame.

What I have tried:

```<code>df =pd.read_csv('file.csv')
def SortMood(df)
df['mood']=[] #empty column as a list in the df to store the mood
 for score in df['score']:
      if score>(0.05):
            df['mood'].append('positive')
      elif -0.05<=score <=.05:
            df['mood'].append('neutral')
      else:
          df['mood'].append('negative')
</code>```

I am aware that this function is wrong (I get a ValueError). So, any help is appreciated. Thank you.

答:
Use apply:

```<code>def determine_mood(row, thresh=.05):
    if row.score < -thresh:
        return "negative"
    elif row.score > thresh:
        return "positive"
    else:
        return "neutral"

df["mood"] = df.apply(determine_mood, axis=1)

df
      date   score      mood
0   3/1/16  0.6369  positive
1   5/1/16 -0.2023  negative
2   6/1/16  0.0400   neutral
3   7/1/16  0.0772  positive
4   9/1/16 -0.4215  negative
5  12/1/16  0.2960  positive
6  15/1/16  0.2500  positive
7  15/1/16  0.7684  positive
</code>```

Body:
I have a dataset similar to the following.

date,score
3/1/16,0.6369
5/1/16,-0.2023
6/1/16,0.04
7/1/16,0.0772
9/1/16,-0.4215
12/1/16,0.2960
15/1/16,0.25
15/1/16,0.7684

I want to apply the following conditions on the score.

Con1: if the score is >.05, count that as positive for that date
Con2: if the score is  -0.05<=score <=.05, count that as neutral for that date
Con3: Else, count that as negative for that date
And add a new_column to the DataFrame alongside the score to put the 'negative'/'positive'/'neutral' result

Expected Output:

date, score, mood
3/1/16,0.6369, positive
5/1/16,-.2023, negative
6/1/16,0.04, neutral

And I have multiple scores on the same date. So, I thought of using groupby with multiple columns ('date'and 'score')  and pass through the if conditions and add a new column ['mood'] to the DataFrame.

What I have tried:

df =pd.read_csv('file.csv')
def SortMood(df)
df['mood']=[] #empty column as a list in the df to store the mood
 for score in df['score']:
      if score>(0.05):
            df['mood'].append('positive')
      elif -0.05<=score <=.05:
            df['mood'].append('neutral')
      else:
          df['mood'].append('negative')

I am aware that this function is wrong (I get a ValueError). So, any help is appreciated. Thank you.

Body:
Use apply:

def determine_mood(row, thresh=.05):
    if row.score < -thresh:
        return "negative"
    elif row.score > thresh:
        return "positive"
    else:
        return "neutral"

df["mood"] = df.apply(determine_mood, axis=1)

df
      date   score      mood
0   3/1/16  0.6369  positive
1   5/1/16 -0.2023  negative
2   6/1/16  0.0400   neutral
3   7/1/16  0.0772  positive
4   9/1/16 -0.4215  negative
5  12/1/16  0.2960  positive
6  15/1/16  0.2500  positive
7  15/1/16  0.7684  positive


问:
How to make XTemplate work with TabPanel in Sencha Touch
I've got my TabPanels generating as expected, however, if I try and inject an XTemplate into one of the panels, and then call content.update(myArray);, the result is that the panels don't move, the buttons don't work, and the template doesn't render.

Can anyone tell me what I'm doing wrong?

```<code><script type="text/javascript">
    Ext.setup({
        onReady: function () {
            var rootPanel,
                videoPanel,
                aboutPanel,
                videoTpl,
                bergman,
                gray,
                videosToShow

            bergman = { id: "23657322" };
            gray = { id: "23694183" };
            videosToShow = [bergman, gray];

            videoTpl = new Ext.XTemplate(
                '<tpl for=".">',
                '<iframe src="http://player.vimeo.com/video/{id}?title=0&byline=0&portrait=0&color=80ceff" ',
                'width="400" ',
                'height="225" ',
                'frameborder="0">',
                '</iframe>',
                '</tpl>'
            );

            videoPanel = {
                title: "Videos",
                tpl: videoTpl,
                iconCls: "tv",
                badgeText: "1",
                dockedItems: [{ xtype: "toolbar", title: "Videos"}],
                scroll: "vertical"
            };

            aboutPanel = {
                title: "About",
                html: "About RockPointe Church.",
                iconCls: "more",
                dockedItems: [{ xtype: "toolbar", title: "About"}],
                scroll: "vertical"
            };

            rootPanel = new Ext.TabPanel({
                fullscreen: true,
                layout: 'card',
                items: [videoPanel, aboutPanel],
                tabBar: { dock: 'bottom' }
            });

            content.update(videosToShow);
        }
    });
</script>
</code>```

答:
I figured it out

I needed to videoPanel.update(videosToShow);

I also had to change

videoPanel = {

to

videoPanel = new Panel({


问:
SQL DataReader giving "string or binary data will be truncated"
I'm trying to read a table where under normal circumstances zero rows will be returned. If any rows are returned an error message is shown. I've tested the SQL statement in on SQL Server and it works. However, I'm getting an error in the DataReader. My code is as follows:

```<code>Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString)
     Dim sSQLc As String = "SELECT * FROM UnitHistory " _
                            + "WHERE Unit=" + iUnitID.ToString + " " _
                            + "AND StartDate<='" + returnSQLDateString(dAdmissionDateTime) + "' " _
                            + "AND (EndDate IS NULL OR " _
                            + "EndDate>'" + returnSQLDateString(dAdmissionDateTime) + "') " _
                            + "AND IsAmended IS NULL AND IsReversed IS NULL"
     Using sqlCMD As SqlCommand = New SqlCommand(sSQLc, sqlConn)
         Using sqlR As SqlDataReader = sqlCMD.ExecuteReader ' <--- (The error is raised at this line)
             If sqlR.HasRows Then
                 ' if rows were returned then there was someone in the unit
                 ' we're trying to admit to.
                 MsgBox("There is an admission already in this unit for this admission date")
                 Exit Sub
             End If
         End Using
     End Using
End Using
</code>```

A sample SQL Statement which this generates is:

```<code>SELECT *
FROM UnitHistory
WHERE Unit=1
AND StartDate<='2019-07-14 20:55'
AND (EndDate IS NULL OR EndDate>'2019-07-14 20:55')
AND IsAmended IS NULL
AND IsReversed IS NULL
</code>```

The columns in question (as in the SQL Statement) are int/DateTime/DateTime/Bit/Bit

I can't see why this is causing the error to be raised.

答:
I went to SQL Management studio and tried a similar query on one of my tables and it quickly pointed out the problem.  It wanted additional parentheses.</p>

```<code>    Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString)
     Dim sSQLc As String = "SELECT * FROM UnitHistory " _
                            + "WHERE (Unit=" + iUnitID.ToString + ") " _
                            + "AND (StartDate<='" + returnSQLDateString(dAdmissionDateTime) + "') " _
                            + "AND ((EndDate IS NULL) OR " _
                            + "(EndDate>'" + returnSQLDateString(dAdmissionDateTime) + "')) " _
                            + "AND (IsAmended IS NULL) AND (IsReversed IS NULL)"
     Using sqlCMD As SqlCommand = New SqlCommand(sSQLc, sqlConn)
         Using sqlR As SqlDataReader = sqlCMD.ExecuteReader ' <--- (The error is raised at this line)
             If sqlR.HasRows Then
                 ' if rows were returned then there was someone in the unit
                 ' we're trying to admit to.
                 MsgBox("There is an admission already in this unit for this admission date")
                 Exit Sub
             End If
         End Using
     End Using
End Using
</code>```

Body:
I'm trying to read a table where under normal circumstances zero rows will be returned. If any rows are returned an error message is shown. I've tested the SQL statement in on SQL Server and it works. However, I'm getting an error in the DataReader. My code is as follows:

Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString)
     Dim sSQLc As String = "SELECT * FROM UnitHistory " _
                            + "WHERE Unit=" + iUnitID.ToString + " " _
                            + "AND StartDate<='" + returnSQLDateString(dAdmissionDateTime) + "' " _
                            + "AND (EndDate IS NULL OR " _
                            + "EndDate>'" + returnSQLDateString(dAdmissionDateTime) + "') " _
                            + "AND IsAmended IS NULL AND IsReversed IS NULL"
     Using sqlCMD As SqlCommand = New SqlCommand(sSQLc, sqlConn)
         Using sqlR As SqlDataReader = sqlCMD.ExecuteReader ' <--- (The error is raised at this line)
             If sqlR.HasRows Then
                 ' if rows were returned then there was someone in the unit
                 ' we're trying to admit to.
                 MsgBox("There is an admission already in this unit for this admission date")
                 Exit Sub
             End If
         End Using
     End Using
End Using

A sample SQL Statement which this generates is:

SELECT *
FROM UnitHistory
WHERE Unit=1
AND StartDate<='2019-07-14 20:55'
AND (EndDate IS NULL OR EndDate>'2019-07-14 20:55')
AND IsAmended IS NULL
AND IsReversed IS NULL

The columns in question (as in the SQL Statement) are int/DateTime/DateTime/Bit/Bit

I can't see why this is causing the error to be raised.

Body:
I went to SQL Management studio and tried a similar query on one of my tables and it quickly pointed out the problem.  It wanted additional parentheses.

    Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString)
     Dim sSQLc As String = "SELECT * FROM UnitHistory " _
                            + "WHERE (Unit=" + iUnitID.ToString + ") " _
                            + "AND (StartDate<='" + returnSQLDateString(dAdmissionDateTime) + "') " _
                            + "AND ((EndDate IS NULL) OR " _
                            + "(EndDate>'" + returnSQLDateString(dAdmissionDateTime) + "')) " _
                            + "AND (IsAmended IS NULL) AND (IsReversed IS NULL)"
     Using sqlCMD As SqlCommand = New SqlCommand(sSQLc, sqlConn)
         Using sqlR As SqlDataReader = sqlCMD.ExecuteReader ' <--- (The error is raised at this line)
             If sqlR.HasRows Then
                 ' if rows were returned then there was someone in the unit
                 ' we're trying to admit to.
                 MsgBox("There is an admission already in this unit for this admission date")
                 Exit Sub
             End If
         End Using
     End Using
End Using


问:
Django - run a function every x seconds
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is -

```<code>def shut_down(request):
  # Do some stuff
  while True:
    result = some_fn()
    if result:
      break
    time.sleep(2)

  return True
</code>```

While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it.

This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True)

EDIT -

Reading Oz123's response gave me an idea which seems to work. Here's what I did -

```<code>def shut_down(params):
    # Do some stuff
    # Offload the blocking job to a new thread

    t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
    t.setDaemon(True)
    t.start()

    return True

def some_fn(id):
    while True:
        # Do the job, get result in res
        # If the job is done, return. Or sleep the thread for 2 seconds before trying again.

        if res:
            return
        else:
            time.sleep(2)
</code>```

This does the job for me. It's simple but I don't know how efficient multithreading is in conjunction with Django.

If anyone can point out pitfalls of this, criticism is appreciated.

答:
This answer expands on Oz123's answer a little bit.

In order to get things working, I created a file called mainapp/jobs.py to contain my scheduled jobs. Then, in my apps.py module, I put from . import jobs in the ready method. Here's my entire apps.py file:

```<code>from django.apps import AppConfig
import os

class MainappConfig(AppConfig):
    name = 'mainapp'

    def ready(self):
        from . import jobs

        if os.environ.get('RUN_MAIN', None) != 'true':
            jobs.start_scheduler()
</code>```

(The RUN_MAIN check is because python manage.py runserver runs the ready method twice—once in each of two processes—but we only want to run it once.)

Now, here's what I put in my jobs.py file. First, the imports. You'll need to import Scheduler, threading and time as below. The F and UserHolding imports are just for what my job does; you won't import these.

```<code>from django.db.models import F
from schedule import Scheduler
import threading
import time

from .models import UserHolding
</code>```

Next, write the function you want to schedule. The following is purely an example; your function won't look anything like this.

```<code>def give_admin_gold():
    admin_gold_holding = (UserHolding.objects
        .filter(inventory__user__username='admin', commodity__name='gold'))

    admin_gold_holding.update(amount=F('amount') + 1)
</code>```

Next, monkey-patch the schedule module by adding a run_continuously method to its Scheduler class. Do this by using the below code, which is copied verbatim from Oz123's answer.

```<code>def run_continuously(self, interval=1):
    """Continuously run, while executing pending jobs at each elapsed
    time interval.
    @return cease_continuous_run: threading.Event which can be set to
    cease continuous run.
    Please note that it is *intended behavior that run_continuously()
    does not run missed jobs*. For example, if you've registered a job
    that should run every minute and you set a continuous run interval
    of one hour then your job won't be run 60 times at each interval but
    only once.
    """

    cease_continuous_run = threading.Event()

    class ScheduleThread(threading.Thread):

        @classmethod
        def run(cls):
            while not cease_continuous_run.is_set():
                self.run_pending()
                time.sleep(interval)

    continuous_thread = ScheduleThread()
    continuous_thread.setDaemon(True)
    continuous_thread.start()
    return cease_continuous_run

Scheduler.run_continuously = run_continuously
</code>```

Finally, define a function to create a Scheduler object, wire up your job, and call the scheduler's run_continuously method.

```<code>def start_scheduler():
    scheduler = Scheduler()
    scheduler.every().second.do(give_admin_gold)
    scheduler.run_continuously()
</code>```

Title: Django - run a function every x seconds

Body:
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is -

def shut_down(request):
  # Do some stuff
  while True:
    result = some_fn()
    if result:
      break
    time.sleep(2)

  return True

While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it.

This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True)

EDIT -

Reading Oz123's response gave me an idea which seems to work. Here's what I did -

def shut_down(params):
    # Do some stuff
    # Offload the blocking job to a new thread

    t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
    t.setDaemon(True)
    t.start()

    return True

def some_fn(id):
    while True:
        # Do the job, get result in res
        # If the job is done, return. Or sleep the thread for 2 seconds before trying again.

        if res:
            return
        else:
            time.sleep(2)

This does the job for me. It's simple but I don't know how efficient multithreading is in conjunction with Django.

If anyone can point out pitfalls of this, criticism is appreciated.

Body:
This answer expands on Oz123's answer a little bit.

In order to get things working, I created a file called mainapp/jobs.py to contain my scheduled jobs. Then, in my apps.py module, I put from . import jobs in the ready method. Here's my entire apps.py file:

from django.apps import AppConfig
import os

class MainappConfig(AppConfig):
    name = 'mainapp'

    def ready(self):
        from . import jobs

        if os.environ.get('RUN_MAIN', None) != 'true':
            jobs.start_scheduler()

(The RUN_MAIN check is because python manage.py runserver runs the ready method twice—once in each of two processes—but we only want to run it once.)

Now, here's what I put in my jobs.py file. First, the imports. You'll need to import Scheduler, threading and time as below. The F and UserHolding imports are just for what my job does; you won't import these.

from django.db.models import F
from schedule import Scheduler
import threading
import time

from .models import UserHolding

Next, write the function you want to schedule. The following is purely an example; your function won't look anything like this.

def give_admin_gold():
    admin_gold_holding = (UserHolding.objects
        .filter(inventory__user__username='admin', commodity__name='gold'))

    admin_gold_holding.update(amount=F('amount') + 1)

Next, monkey-patch the schedule module by adding a run_continuously method to its Scheduler class. Do this by using the below code, which is copied verbatim from Oz123's answer.

def run_continuously(self, interval=1):
    """Continuously run, while executing pending jobs at each elapsed
    time interval.
    @return cease_continuous_run: threading.Event which can be set to
    cease continuous run.
    Please note that it is *intended behavior that run_continuously()
    does not run missed jobs*. For example, if you've registered a job
    that should run every minute and you set a continuous run interval
    of one hour then your job won't be run 60 times at each interval but
    only once.
    """

    cease_continuous_run = threading.Event()

    class ScheduleThread(threading.Thread):

        @classmethod
        def run(cls):
            while not cease_continuous_run.is_set():
                self.run_pending()
                time.sleep(interval)

    continuous_thread = ScheduleThread()
    continuous_thread.setDaemon(True)
    continuous_thread.start()
    return cease_continuous_run

Scheduler.run_continuously = run_continuously

Finally, define a function to create a Scheduler object, wire up your job, and call the scheduler's run_continuously method.

def start_scheduler():
    scheduler = Scheduler()
    scheduler.every().second.do(give_admin_gold)
    scheduler.run_continuously()


问:
How to add dividers and spaces between items in RecyclerView
This is an example of how it could have been done previously in the ListView class, using the divider and dividerHeight parameters:

```<code><ListView
    android:id="@+id/activity_home_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="8dp"/>
</code>```

However, I don't see such possibility in the RecyclerView class.

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/activity_home_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"/>
</code>```

In that case, is it ok to define margins and/or add a custom divider view directly into a list item's layout or is there a better way to achieve my goal?

答:
Here's how I would do it in Kotlin, for a simple space between Items with a default size of 10 dp:

```<code>class SimpleItemDecoration(context: Context, space: Int = 10) : RecyclerView.ItemDecoration() {

    private val spaceInDp = ConvertUtil.dpToPx(context, space)

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {

        outRect.left = spaceInDp
        outRect.right = spaceInDp
        outRect.bottom = spaceInDp
        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top = spaceInDp
        }
    }
}
</code>```

And here is the dpToPx method:

```<code>fun dpToPx(context: Context, dp: Int): Int {
        return (dp * context.resources.displayMetrics.density).toInt()
    }
</code>```

and then add it to the RecyclerView like this: (thanks @MSpeed)

```<code>recyclerView.addItemDecoration(SimpleItemDecoration(context))
</code>```

Body:
This is an example of how it could have been done previously in the ListView class, using the divider and dividerHeight parameters:

<ListView
    android:id="@+id/activity_home_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="8dp"/>

However, I don't see such possibility in the RecyclerView class.

<android.support.v7.widget.RecyclerView
    android:id="@+id/activity_home_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"/>

In that case, is it ok to define margins and/or add a custom divider view directly into a list item's layout or is there a better way to achieve my goal?

Body:
Here's how I would do it in Kotlin, for a simple space between Items with a default size of 10 dp:

class SimpleItemDecoration(context: Context, space: Int = 10) : RecyclerView.ItemDecoration() {

    private val spaceInDp = ConvertUtil.dpToPx(context, space)

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {

        outRect.left = spaceInDp
        outRect.right = spaceInDp
        outRect.bottom = spaceInDp
        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top = spaceInDp
        }
    }
}

And here is the dpToPx method:

fun dpToPx(context: Context, dp: Int): Int {
        return (dp * context.resources.displayMetrics.density).toInt()
    }

and then add it to the RecyclerView like this: (thanks @MSpeed)

recyclerView.addItemDecoration(SimpleItemDecoration(context))


问:
CSS won't dynamically change with .addClass() or .css()
I have a table that has rows with different classes depending on what color it should be.  On the click of a button I want the background color of the row to change instantly.  I tried both .addClass() and .css() but they both fail. On click, I have a function that checks whether the row is colored or not, that works fine.

Here are the pieces of code I'm using and the css classes that go along with the rows.

If a row is white:

$("#"+table+"_row_"+id).addClass("table-1").removeClass("table-0");

or

$("#"+table+"_row_"+id).css("background-color","orange");

If a row is orange:

$("#"+table+"_row_"+id).addClass("table-0").removeClass("table-1");

or

$("#"+table+"_row_"+id).css("background-color","white");

css:

```<code>table.tablesorter .table-1{
background-color:orange;
}
table.tablesorter .table-0{
background-color:white;
}
</code>```

答:
Have you checked the CSS cascading order, perhaps with Firebug or WebKit's Web inspector?

When updating a CSS class, you'll need to take care the cascading order. Otherwise, it may not turn out to be the effect you are after.

Body:
I have a table that has rows with different classes depending on what color it should be.  On the click of a button I want the background color of the row to change instantly.  I tried both .addClass() and .css() but they both fail. On click, I have a function that checks whether the row is colored or not, that works fine.

Here are the pieces of code I'm using and the css classes that go along with the rows.

If a row is white:

$("#"+table+"_row_"+id).addClass("table-1").removeClass("table-0");

or

$("#"+table+"_row_"+id).css("background-color","orange");

If a row is orange:

$("#"+table+"_row_"+id).addClass("table-0").removeClass("table-1");

or

$("#"+table+"_row_"+id).css("background-color","white");

css:

table.tablesorter .table-1{
background-color:orange;
}
table.tablesorter .table-0{
background-color:white;
}


问:
Sign in with Facebook error code: 1349195 [ IONIC ]
I'm having a problem a few days ago with Ionic and the login with Facebook.

I have everything included, install the respective Ionic plugin and I put the APP_ID and the APP_NAME.

When I'm in the APP, and I want to log in with Facebook, Pop-up appears normally. When I give to accept for facebook to access my personal data and my e-mail this happens:

"Facebook error: SERVER_ERROR: [code] 1349195 [message]: The hash of
  the key does not match any of the stored key hashes. Go to
  https://developers.facebook.com/docs/facebook-login/android for get
  more information. [extra]: "

I did not find any way to solve it.

答:
I have the same problem, and I noticed that I put the wrong password when creating the hash code.
the correct password is: android


问:
How is SHA unique?
I am trying to understand SHA uniqueness in simple terms.
For example let us assume there are only messages with maximum length of 4 bits (binery) in whole world. Number of possible messages with different lengths is

2 for single bit length

2^2 for double bit length

2^3 for 3 bit length

2^4 for 4 bit length

that would be 2+4+8+16 = 30 (31 if we consider empty message 2^0 = 1)

Lets us consider SHA3(for example) with output length of 3bits (binery), so maximum possible number of digest are 8.
How can a digest be unique if we need to map 30 messages to 8, or why is it hard to find digest collision for 2 unique messages

答:
"SHA3 which has digest length of 3bits"

I think this question is based on one bit misunderstanding. SHA-3 is a family of hashes that has the same output bit size as SHA-2. SHA-2 has bit sizes 224, 256, 384 or 512 for SHA-224, SHA-256, SHA-384 and SHA-512 respectively.

Of course, SHA-2 already took those identifiers, so SHA-3 will have SHA3-224, SHA3-256, SHA3-384 and SHA3-512. There were some proposals to use a different acronym, but those failed.

Still, SHA-3 hashes have near infinite input, so there will be many hashes that map to the same value. However, since it is not possible reverse any SHA-3 algorithm, it should be impossible to find a collision. That is, unless SHA-3 is broken, as it is not provably secure.

Title: How is SHA unique?


问:
Django always connects to localhost mongodb
I have followed the guide of db connection config:
https://nesdis.github.io/djongo/database-configuration/

However, it always connects to localhost one, not my setting's one.

Does anyone have any idea on this issue?

my packages versions:

```<code>Django  2.0
django-cors-headers 2.4.0
django-rest-auth    0.9.3
djangorestframework 3.9.0
djongo  1.1
mongoengine 0.16.3
pip 10.0.1
pymongo 3.7.2
urllib3 1.24.1
</code>```

my settings

```<code>DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test_db',
        'HOST': 'somewhere.com',
        'PORT': 27017
    }
}
</code>```

答:
Is seems that somewhere along the way, djongo changed the structure of the database settings. After wasting days trying to find the solution, I came across a page that had the updated structure, Try setting your DATABASE structure to this:</p>

```<code>DATABASES = {
  'default': {
    'ENGINE':   'djongo',
    'NAME':     'yourmongodb',
    'CLIENT': {
      'host': 'some-host.or.ip',
      'port': 27017,
      'username': 'youruser',
      'password': 'yourdbpass',
      'authSource': 'yourcollection',
    }
  },
}
</code>```

Body:
I have followed the guide of db connection config:
https://nesdis.github.io/djongo/database-configuration/

However, it always connects to localhost one, not my setting's one.

Does anyone have any idea on this issue?

my packages versions:

Django  2.0
django-cors-headers 2.4.0
django-rest-auth    0.9.3
djangorestframework 3.9.0
djongo  1.1
mongoengine 0.16.3
pip 10.0.1
pymongo 3.7.2
urllib3 1.24.1

my settings

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test_db',
        'HOST': 'somewhere.com',
        'PORT': 27017
    }
}

Body:
Is seems that somewhere along the way, djongo changed the structure of the database settings. After wasting days trying to find the solution, I came across a page that had the updated structure, Try setting your DATABASE structure to this:

DATABASES = {
  'default': {
    'ENGINE':   'djongo',
    'NAME':     'yourmongodb',
    'CLIENT': {
      'host': 'some-host.or.ip',
      'port': 27017,
      'username': 'youruser',
      'password': 'yourdbpass',
      'authSource': 'yourcollection',
    }
  },
}


问:
global optimum for non convex optimization
I have a question about non-convex models. I deal with a Mixed Integer Quadratic problem (non-convex quadratic objective function with linear constraints- product of two continuous variables in the objective function makes it non-convex). I want to know about the exact methods for solving this type of problem to obtain the global optimum?</p>

答:
You cannot solve this problem in general like any NP-hard problems. You can solve the problem with a handful of variables by checking every case. However, you cannot solve it in general, i.e., it is not tractable to solve, for large number of variables.

However, there are methods that can be used for obtaining the suboptimal solution to these problems, e.g., Algorithms for Mixed Integer Problems.


问:
Bazel cc_library with no srcs doesn't compile on its own
I have a cc_library that is header-only. Whenever I try to compile such library by itself, it won't actually compile anything. I purposely put some errors to try to get such errors on compilation, but bazel doesn't actually compile anything. Here's a small example.

// test.h

This should not compile fdsafdsafdsa
int foo() { return 1; }
```

<pre class="lang-py prettyprint-override"><code># BUILD

cc_library(
  name = 'test',
  hdrs = ['test.h']
)
</code>```

```<code>// bazel build :test
INFO: Analyzed target //:test (2 packages loaded, 3 targets configured).
INFO: Found 1 target...
Target //:test up-to-date (nothing to build)
INFO: Elapsed time: 0.083s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
</code>```

Is this behavior intended?

I also ran the same experiment but splitting the .h and .cc files, and in that case, I got the error when I compiled.

答: A header only library means that you don't need to build anything. Simply include the headers you need in your program and use them.</p>

Body:
I have a cc_library that is header-only. Whenever I try to compile such library by itself, it won't actually compile anything. I purposely put some errors to try to get such errors on compilation, but bazel doesn't actually compile anything. Here's a small example.

// test.h

This should not compile fdsafdsafdsa
int foo() { return 1; }

# BUILD

cc_library(
  name = 'test',
  hdrs = ['test.h']
)

// bazel build :test
INFO: Analyzed target //:test (2 packages loaded, 3 targets configured).
INFO: Found 1 target...
Target //:test up-to-date (nothing to build)
INFO: Elapsed time: 0.083s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action

Is this behavior intended?

I also ran the same experiment but splitting the .h and .cc files, and in that case, I got the error when I compiled.


答:
Use pd.cut to bin your data to categorical:

```<code>df['mood'] = pd.cut(df['score'],
                    bins=[-np.inf, -.05, .05, np.inf],
                    labels=['negative', 'neutral', 'positive'])

      date   score      mood
0   3/1/16  0.6369  positive
1   5/1/16 -0.2023  negative
2   6/1/16  0.0400   neutral
3   7/1/16  0.0772  positive
4   9/1/16 -0.4215  negative
5  12/1/16  0.2960  positive
6  15/1/16  0.2500  positive
7  15/1/16  0.7684  positive
</code>```

Or use numpy.select for vectorized multiple conditional column:

```<code>conditions = [
    df['score'].lt(-.05),
    df['score'].between(-.05, 0.05)
]

df['mood'] = np.select(conditions, ['negative', 'neutral'], default='positive')

      date   score      mood
0   3/1/16  0.6369  positive
1   5/1/16 -0.2023  negative
2   6/1/16  0.0400   neutral
3   7/1/16  0.0772  positive
4   9/1/16 -0.4215  negative
5  12/1/16  0.2960  positive
6  15/1/16  0.2500  positive
7  15/1/16  0.7684  positive
</code>```

Title: Multiple conditional statements with groupby in pandas

Body:
Use pd.cut to bin your data to categorical:

df['mood'] = pd.cut(df['score'],
                    bins=[-np.inf, -.05, .05, np.inf],
                    labels=['negative', 'neutral', 'positive'])

      date   score      mood
0   3/1/16  0.6369  positive
1   5/1/16 -0.2023  negative
2   6/1/16  0.0400   neutral
3   7/1/16  0.0772  positive
4   9/1/16 -0.4215  negative
5  12/1/16  0.2960  positive
6  15/1/16  0.2500  positive
7  15/1/16  0.7684  positive

Or use numpy.select for vectorized multiple conditional column:

conditions = [
    df['score'].lt(-.05),
    df['score'].between(-.05, 0.05)
]

df['mood'] = np.select(conditions, ['negative', 'neutral'], default='positive')

      date   score      mood
0   3/1/16  0.6369  positive
1   5/1/16 -0.2023  negative
2   6/1/16  0.0400   neutral
3   7/1/16  0.0772  positive
4   9/1/16 -0.4215  negative
5  12/1/16  0.2960  positive
6  15/1/16  0.2500  positive
7  15/1/16  0.7684  positive


问:
C# WinForms: Identify type of drag-drop action event
The use case: users need the ability to drag & drop email items from Outlook onto a form in my WinForms (.Net 4) application. The application saves these items in .msg format and stores them in a predetermined location.

The problem: my code is not robust against drag-drop from other sources (e.g. dragging a jpeg from IE onto the form triggers the same event). This is because I cannot determine whether the dragged item is an Outlook object, or what source the dragged item(s) came from.

Is there a workaround such that I can only accept drag-drop items of a particular type? Here is my code in the DragDrop event handler:

```<code>Outlook.Application outlook = new Outlook.Application();
Outlook.Selection sel = outlook.ActiveExplorer().Selection;

try
{
    foreach (object item in sel)
    {
        if (item is Outlook.MailItem)
        {
            var mail = item as Outlook.MailItem;

            CopyMailItemToLocalTempDir(mail);

            txtComment.Text = "Email from " + mail.SenderName + " Regarding " + mail.Subject;
        }
    }
}
finally
{
    // This is hokey but it prevents Outlook from remembering previously selected items
    // - refer http://stackoverflow.com/questions/14090420/interop-outlook-doesnt-clear-selected-mails-at-drag-and-drop
    var folder = outlook.ActiveExplorer().CurrentFolder;
    outlook.ActiveExplorer().CurrentFolder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
    Thread.Sleep(50);
    outlook.ActiveExplorer().CurrentFolder = folder;

    Marshal.ReleaseComObject(sel);
    Marshal.ReleaseComObject(outlook);
    sel = null;
    outlook = null;
}
</code>```

Some details on the DragEventArgs object (e) when dragging from Outlook:

```<code>e.Data.GetFormats() returns:
{string[15]}
    [0]: "RenPrivateSourceFolder"
    [1]: "RenPrivateLatestMessages"
    [2]: "RenPrivateMessages"
    [3]: "RenPrivateItem"
    [4]: "FileGroupDescriptor"
    [5]: "FileGroupDescriptorW"
    [6]: "FileDrop"
    [7]: "FileNameW"
    [8]: "FileName"
    [9]: "FileContents"
    [10]: "Object Descriptor"
    [11]: "System.String"
    [12]: "UnicodeText"
    [13]: "Text"
    [14]: "CSV"

e.Data.GetData("Text") returns:
"From\tSubject\tReceived\tSize\tCategories\t\r\nJoe Sender\tThis is the email subject\t10:51 AM\t3 KB\t\t"
</code>```

答:
Is there a workaround such that I can only accept drag-drop items of a
particular type?

Yes, there is 2 way

(When working with single files):

```<code>if (e.Data.GetData(typeof(...)) is ...)
    //process it
</code>```

and

```<code>if (e.Data.GetDataPresent(typeof(...)))
    //process it
</code>```

About robustness

Since you have not specified the type to be Outlook.MailItem (or maybe Image) but the source: I assume your program fails on other parts of the code (due to bad design). E.g. ActiveExplorer().Selection in 2nd line or in the finally {} part. This is easily manageable by prefiltering/try-catching in place (before involving outlook) or in the DragEnter event (better when the type is strictly some type of outlook).

To master drag & drop stuff, check out this.

For multiple file handling

or for special types like outlook messages, you already have a good solution with plenty of explanations in the article you mentioned.

I also found an answer to your non-general (outlook only) use case (wrote in 2012) that exhibits OutlookDataObject class and probably based on the article you mentioned (wrote in 2008).

Body:
The use case: users need the ability to drag & drop email items from Outlook onto a form in my WinForms (.Net 4) application. The application saves these items in .msg format and stores them in a predetermined location.

The problem: my code is not robust against drag-drop from other sources (e.g. dragging a jpeg from IE onto the form triggers the same event). This is because I cannot determine whether the dragged item is an Outlook object, or what source the dragged item(s) came from.

Is there a workaround such that I can only accept drag-drop items of a particular type? Here is my code in the DragDrop event handler:

Outlook.Application outlook = new Outlook.Application();
Outlook.Selection sel = outlook.ActiveExplorer().Selection;

try
{
    foreach (object item in sel)
    {
        if (item is Outlook.MailItem)
        {
            var mail = item as Outlook.MailItem;

            CopyMailItemToLocalTempDir(mail);

            txtComment.Text = "Email from " + mail.SenderName + " Regarding " + mail.Subject;
        }
    }
}
finally
{
    // This is hokey but it prevents Outlook from remembering previously selected items
    // - refer http://stackoverflow.com/questions/14090420/interop-outlook-doesnt-clear-selected-mails-at-drag-and-drop
    var folder = outlook.ActiveExplorer().CurrentFolder;
    outlook.ActiveExplorer().CurrentFolder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
    Thread.Sleep(50);
    outlook.ActiveExplorer().CurrentFolder = folder;

    Marshal.ReleaseComObject(sel);
    Marshal.ReleaseComObject(outlook);
    sel = null;
    outlook = null;
}

Some details on the DragEventArgs object (e) when dragging from Outlook:

e.Data.GetFormats() returns:
{string[15]}
    [0]: "RenPrivateSourceFolder"
    [1]: "RenPrivateLatestMessages"
    [2]: "RenPrivateMessages"
    [3]: "RenPrivateItem"
    [4]: "FileGroupDescriptor"
    [5]: "FileGroupDescriptorW"
    [6]: "FileDrop"
    [7]: "FileNameW"
    [8]: "FileName"
    [9]: "FileContents"
    [10]: "Object Descriptor"
    [11]: "System.String"
    [12]: "UnicodeText"
    [13]: "Text"
    [14]: "CSV"

e.Data.GetData("Text") returns:
"From\tSubject\tReceived\tSize\tCategories\t\r\nJoe Sender\tThis is the email subject\t10:51 AM\t3 KB\t\t"

Body:
Is there a workaround such that I can only accept drag-drop items of a
particular type?

Yes, there is 2 way

(When working with single files):

if (e.Data.GetData(typeof(...)) is ...)
    //process it

and

if (e.Data.GetDataPresent(typeof(...)))
    //process it

About robustness

Since you have not specified the type to be Outlook.MailItem (or maybe Image) but the source: I assume your program fails on other parts of the code (due to bad design). E.g. ActiveExplorer().Selection in 2nd line or in the finally {} part. This is easily manageable by prefiltering/try-catching in place (before involving outlook) or in the DragEnter event (better when the type is strictly some type of outlook).

To master drag & drop stuff, check out this.

For multiple file handling

or for special types like outlook messages, you already have a good solution with plenty of explanations in the article you mentioned.

I also found an answer to your non-general (outlook only) use case (wrote in 2012) that exhibits OutlookDataObject class and probably based on the article you mentioned (wrote in 2008).


问:
Determining Filetype with PHP. What is Magic Database?
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.

What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?

Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?

```<code><?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>
</code>```

答:
Most file formats have a header that helps identify what kind of file it is. For example, GIF files always begin with GIF87

The magic number database is a list of all headers and allows finfo() to id the files.

Windows doesn't have this database installed by default. You would need to bring it along for windows.  In fact you should use the same database no matter where you deploy to improve cross platform compatibility. Imagine if you deployed to an old system that doesn't know about filetypes your dev platform understands.

Body:
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.

What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?

Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>


问:
Is there a LINQ-oriented method to quicky evaluate nested lists in dictionaries
I have a dictionary constructed like this:

```<code>Dictionary<string, List<MyObject>>
</code>```

And my object has an integer value as one of its properties:

```<code>public class MyObject
{
  public int number {get; set;}
}
</code>```

How would I construct a LINQ-oriented query to evaluate the average number for each Key in the dictionary?

答:
Because dictionaries are enumerables, your request can be accomplished in a straightforward and natural manner</p>

```<code> var averages = dictionary
     .ToDictionary(pair => pair.Key, pair => pair.Value.Average(e => e.number));
</code>```

Body:
I have a dictionary constructed like this:

Dictionary<string, List<MyObject>>

And my object has an integer value as one of its properties:

public class MyObject
{
  public int number {get; set;}
}

How would I construct a LINQ-oriented query to evaluate the average number for each Key in the dictionary?

Body:
Because dictionaries are enumerables, your request can be accomplished in a straightforward and natural manner

 var averages = dictionary
     .ToDictionary(pair => pair.Key, pair => pair.Value.Average(e => e.number));


问:
What is the following Java/Android syntax actually doing?
I came across the following syntax, which is alien to me. I know String[] is a String array, but what are the curly braces doing

new String[]{Manifest.permission.ACCESS_FINE_LOCATION}

in the following code snippet:

```<code>if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    }
</code>```

答:
Calling this Android method displays a dialog box that prompts the app to grant permission and invokes onRequestPermissionsResult when the choice is made. Once this permission has been granted to the system, startAcquisition, stopAcquisition, and acquireGeoPosition are granted access to the location services.

```<code>new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
</code>```

For this syntax it an inline initializing for a list of string.

Body:
I came across the following syntax, which is alien to me. I know String[] is a String array, but what are the curly braces doing

new String[]{Manifest.permission.ACCESS_FINE_LOCATION}

in the following code snippet:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    }

Body:
Calling this Android method displays a dialog box that prompts the app to grant permission and invokes onRequestPermissionsResult when the choice is made. Once this permission has been granted to the system, startAcquisition, stopAcquisition, and acquireGeoPosition are granted access to the location services.

new String[]{Manifest.permission.ACCESS_FINE_LOCATION}

For this syntax it an inline initializing for a list of string.


问:
How do you access application-specific constants in vba from a macro in a different application?
It's often a requirement to use VBA in one MS Office application to perform actions in another, for example, having an excel macro that performs calculations and then renders a table in powerpoint.

VBA provides useful aliases for constants in VBA, such as ppBorderRight= 4.  You can style a table in a powerpoint VBA macro by referring to the constant name instead of needing to keep track of which integer value corresponds to what.

This works fine within a powerpoint macro (pptm file), but fails when called from excel (xlsm file)

How can you refer to these constants from another application?  I have an excel VBA macro that creates a ppt application with Set pp = CreateObject("PowerPoint.Application")

I have tried the following approaches within my excel macro:

```<code>Set pp = CreateObject("PowerPoint.Application")
Set activeSlide = pp.ActivePresentation.Slides(pp.ActivePresentation.Slides.Count)
Set myTable = activeSlide.Shapes.AddTable(8, 2, , , 600, 500).Table

myTable.Columns(4).Cells.Borders(ppBorderRight).Weight = 0 'ppBorderRight evaluates to Empty
myTable.Columns(4).Cells.Borders(pp.ppBorderRight).Weight = 0 'Error: Application object has no property 'ppBorderRight'
</code>```

What's the right way to accomplish this?

答:
Thanks @Mark for the answer.

The answer is to go to Tools -> References in the vba application (Excel in my case), and to add a reference to the target application's object library (Microsoft PowerPoint 16.0 Object Library in my case).

Body:
It's often a requirement to use VBA in one MS Office application to perform actions in another, for example, having an excel macro that performs calculations and then renders a table in powerpoint.

VBA provides useful aliases for constants in VBA, such as ppBorderRight= 4.  You can style a table in a powerpoint VBA macro by referring to the constant name instead of needing to keep track of which integer value corresponds to what.

This works fine within a powerpoint macro (pptm file), but fails when called from excel (xlsm file)

How can you refer to these constants from another application?  I have an excel VBA macro that creates a ppt application with Set pp = CreateObject("PowerPoint.Application")

I have tried the following approaches within my excel macro:

Set pp = CreateObject("PowerPoint.Application")
Set activeSlide = pp.ActivePresentation.Slides(pp.ActivePresentation.Slides.Count)
Set myTable = activeSlide.Shapes.AddTable(8, 2, , , 600, 500).Table

myTable.Columns(4).Cells.Borders(ppBorderRight).Weight = 0 'ppBorderRight evaluates to Empty
myTable.Columns(4).Cells.Borders(pp.ppBorderRight).Weight = 0 'Error: Application object has no property 'ppBorderRight'

What's the right way to accomplish this?


答:
Demo on dotnet fiddle

You can use Average to achieve it.

```<code>var data = new Dictionary<string, List<MyObject>>();
data.Add("1", new List<MyObject> { new MyObject { number = 1 }, new MyObject { number = 2 }, new MyObject { number = 3 }});
data.Add("2", new List<MyObject> { new MyObject { number = 4 }, new MyObject { number = 5 }, new MyObject { number = 6 }});

var result = data.Select(p => new { p.Key, Average = p.Value.Average(n => n.number) });
</code>```

Title: Is there a LINQ-oriented method to quicky evaluate nested lists in dictionaries

Body:
Demo on dotnet fiddle

You can use Average to achieve it.

var data = new Dictionary<string, List<MyObject>>();
data.Add("1", new List<MyObject> { new MyObject { number = 1 }, new MyObject { number = 2 }, new MyObject { number = 3 }});
data.Add("2", new List<MyObject> { new MyObject { number = 4 }, new MyObject { number = 5 }, new MyObject { number = 6 }});

var result = data.Select(p => new { p.Key, Average = p.Value.Average(n => n.number) });


问:
Best way to send notification if new message is received while app is killed or in background
So, I have a chat app that is using Firebase Realtime database. Everything is working as expected, the problem is, whenever the user kills or sends the app to background, new messages received don't send notifications to the user. I've searched StackOverflow for a solution to this problem but I couldn't find a working solution.

My first thought was to create a Service that would check if a new message was received, and if so, send a notification. This is the code I currently have (not finished):

```<code>class NotificationsService : Service(){

    private lateinit var mHandler: Handler
    private lateinit var mRunnable: Runnable

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mHandler = Handler()
        mRunnable = Runnable { getNewMessage()
             }
             mHandler.postDelayed(mRunnable, 20000)

        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacks(mRunnable)
    }

    override fun onBind(intent: Intent?): IBinder? {
        throw UnsupportedOperationException("Not yet implemented")
    }

    private fun getNewMessage(){
        // Random code just to test
        val rand = Random()
        val number = rand.nextInt(100)
        mHandler.postDelayed(mRunnable, 20000)
    }

}
</code>```

My doubt is, is this the best solution for this problem? Or the most optimized in terms of data consuming and power efficiency?

答:
It's not possible to force your app process to stay alive.  Android will kill it when the user isn't using it any more, and your database listeners will stop.  The best chance you have of keeping it alive is establishing a foreground service, but even that isn't a guarantee, as Android will still kill it if it needs the memory.  You should simply expect that you can't keep your app alive, in order to allow other apps and services to run normally.

What you should be doing instead is also using Firebase Cloud Messaging to deliver messages to your app from a backend you control.  These message will wake the app, if necessary, when Android says it's OK.  You can then present the user a notification if you want, or schedule further background work with WorkManager.

If you absolutely can't have a backend for whatever reason, you will have to schedule your app to wake periodically using AlarmManager or WorkManager.

Body:
So, I have a chat app that is using Firebase Realtime database. Everything is working as expected, the problem is, whenever the user kills or sends the app to background, new messages received don't send notifications to the user. I've searched StackOverflow for a solution to this problem but I couldn't find a working solution.

My first thought was to create a Service that would check if a new message was received, and if so, send a notification. This is the code I currently have (not finished):

class NotificationsService : Service(){

    private lateinit var mHandler: Handler
    private lateinit var mRunnable: Runnable

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mHandler = Handler()
        mRunnable = Runnable { getNewMessage()
             }
             mHandler.postDelayed(mRunnable, 20000)

        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacks(mRunnable)
    }

    override fun onBind(intent: Intent?): IBinder? {
        throw UnsupportedOperationException("Not yet implemented")
    }

    private fun getNewMessage(){
        // Random code just to test
        val rand = Random()
        val number = rand.nextInt(100)
        mHandler.postDelayed(mRunnable, 20000)
    }

}

My doubt is, is this the best solution for this problem? Or the most optimized in terms of data consuming and power efficiency?


问:
CrudRepository cannot be resolved to a type
I'm working on a Spring Boot project (generated by Spring Initializr), using Maven. I want to create a CrudRepository, but I'm getting the error "CrudRepository cannot be resolved to a type" and the package org.springframework.data.repository does not contain the CrudRepository class. I tried to follow a bunch of tutorials to understand what is wrong and I didn't find anything. My POM looks right to me, I don't have any build failure when I run maven clean and package goals, I tried to update the project and download sources, but nothing works. Eclipse can't find the CrudRepository class.

Here is my POM file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myquickstart</groupId>
    <artifactId>SpringQuickstart</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringQuickstart</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

And my repository:

```<code>package com.myquickstart.repositories;

import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
import com.myquickstart.entities.Movie;

@Repository
public interface MovieRepository extends CrudRepository<Movie, Long> {

}
</code>```

Thanks for your help

Edit:

I've updated the project with the "Maven => Update project" in Eclipse. After that, I got this error in the "Problems" view:

```<code>C:/Users/carrm/.m2/repository/org/hibernate/hibernate-core/5.0.11.Final/hibernate-core-5.0.11.Final.jar' in project 'SpringQuickstart' cannot be read or is not a valid ZIP file
</code>```

I'm not sure to know how to solve this/what is the link with my CrudRepository problem.

答:
If you are having this problem, check if the org.springframework.data.repository.CrudRepository import is working. If it is then this answer probably won't be the solution. If it is not working and the "data" part is highlighted, then check your pom.xml and if you don't have it already, add the following dependency to it:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</code>```

After adding the dependency, delete your local .m2 directory and build from the command-line. You may also want to reimport the maven project to your workspace.

Body:
I'm working on a Spring Boot project (generated by Spring Initializr), using Maven. I want to create a CrudRepository, but I'm getting the error "CrudRepository cannot be resolved to a type" and the package org.springframework.data.repository does not contain the CrudRepository class. I tried to follow a bunch of tutorials to understand what is wrong and I didn't find anything. My POM looks right to me, I don't have any build failure when I run maven clean and package goals, I tried to update the project and download sources, but nothing works. Eclipse can't find the CrudRepository class.

Here is my POM file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myquickstart</groupId>
    <artifactId>SpringQuickstart</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringQuickstart</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

And my repository:

package com.myquickstart.repositories;

import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
import com.myquickstart.entities.Movie;

@Repository
public interface MovieRepository extends CrudRepository<Movie, Long> {

}

Thanks for your help

Edit:

I've updated the project with the "Maven => Update project" in Eclipse. After that, I got this error in the "Problems" view:

C:/Users/carrm/.m2/repository/org/hibernate/hibernate-core/5.0.11.Final/hibernate-core-5.0.11.Final.jar' in project 'SpringQuickstart' cannot be read or is not a valid ZIP file

I'm not sure to know how to solve this/what is the link with my CrudRepository problem.

Body:
If you are having this problem, check if the org.springframework.data.repository.CrudRepository import is working. If it is then this answer probably won't be the solution. If it is not working and the "data" part is highlighted, then check your pom.xml and if you don't have it already, add the following dependency to it:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

After adding the dependency, delete your local .m2 directory and build from the command-line. You may also want to reimport the maven project to your workspace.