问:
Firebase Storage keeps replacing image when uploading
I am trying to upload 2 images at once and get the DownloadURL to go to the Firebase Database but the second Image function keeps replacing the first one so when I click on the downloadURL for either the first or second it will only grab the second Image. This is my code.</p>

```<code>@IBAction func upload(_ sender: Any) {

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!){
    storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

        let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
        if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!){
        storageRef2.putData(uploadData2, metadata: nil, completion: { (metadata, error) in

                if error != nil {
                        print("error")
                        return

                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadata?.downloadURL()?.absoluteString

                        self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "PostSize": self.postSize.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

            }
</code>```

答:
As shown above you just need to include differnt URL for each and every image.
Eg

` // Create a timestamp as filename
    const filename = Math.floor(Date.now() / 1000);

```<code>// Create a reference to 'images/todays-date.jpg'
this.storRef=firebase.storage().ref();
const imageRef = this.storRef.child(`images/${filename}.jpg`);`
</code>```

Here cause of the filename it will change every time you uploading.try this kind of thing.problem is in the same URL providing.

Body:
I am trying to upload 2 images at once and get the DownloadURL to go to the Firebase Database but the second Image function keeps replacing the first one so when I click on the downloadURL for either the first or second it will only grab the second Image. This is my code.

@IBAction func upload(_ sender: Any) {

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!){
    storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

        let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
        if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!){
        storageRef2.putData(uploadData2, metadata: nil, completion: { (metadata, error) in

                if error != nil {
                        print("error")
                        return

                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadata?.downloadURL()?.absoluteString

                        self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "PostSize": self.postSize.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

            }

Body:
As shown above you just need to include differnt URL for each and every image.
Eg

` // Create a timestamp as filename
    const filename = Math.floor(Date.now() / 1000);

// Create a reference to 'images/todays-date.jpg'
this.storRef=firebase.storage().ref();
const imageRef = this.storRef.child(`images/${filename}.jpg`);`

Here cause of the filename it will change every time you uploading.try this kind of thing.problem is in the same URL providing.


来源: stackexchange

问:
unable to get react app started when starting node.js
I'm following a tutorial on react, and the final step is to start node, but when I do "npm start" as indicated by this tutorial. I get this error.

here's the error cmd line is giving me on starting node "npm start"

```<code>C:\Users\George\Desktop\reactapp>npm start
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\nodejs\\node.exe" "C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! file C:\Users\George\Desktop\reactapp\package.json
npm ERR! code EJSONPARSE

npm ERR! Failed to parse json
npm ERR! Unexpected token '"' at 11:3
npm ERR!   "keywords": [
npm ERR!   ^
npm ERR! File: C:\Users\George\Desktop\reactapp\package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\George\Desktop\reactapp\npm-debug.log
</code>```

and finally here's my package.json file

```<code>{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "test react application",
  "main": "index.js",
  "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node server.js"
    }
}
  "keywords": [
    "test",
    "react",
    "application"
  ],
  "author": "George Louis",
  "license": "ISC",
  "dependencies": {
    "webpack": "^3.0.0"
  }
}
</code>```

答:
If you read the trace, npm is telling you the answer

```<code>npm ERR! Unexpected token '"' at 11:3
npm ERR!   "keywords": [
npm ERR!   ^
npm ERR! File: C:\Users\George\Desktop\reactapp\package.json
</code>```

It tells you whats' wrong (the comma), at which line (11) and which row (3) of which file (C:\Users\George\Desktop\reactapp\package.json).

So, you are missing a comma:

```<code>      "start": "node server.js"
    }
  },
  "keywords": [
    "test",
    "react",
    "application"
  ],
</code>```

Notice the comma before "keywords", that is missing in your JSON, hence it is invalid.

ContentLicense: CC BY-SA 3.0

Body:
I'm following a tutorial on react, and the final step is to start node, but when I do "npm start" as indicated by this tutorial. I get this error.

here's the error cmd line is giving me on starting node "npm start"

C:\Users\George\Desktop\reactapp>npm start
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\nodejs\\node.exe" "C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! file C:\Users\George\Desktop\reactapp\package.json
npm ERR! code EJSONPARSE

npm ERR! Failed to parse json
npm ERR! Unexpected token '"' at 11:3
npm ERR!   "keywords": [
npm ERR!   ^
npm ERR! File: C:\Users\George\Desktop\reactapp\package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\George\Desktop\reactapp\npm-debug.log

and finally here's my package.json file

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "test react application",
  "main": "index.js",
  "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node server.js"
    }
}
  "keywords": [
    "test",
    "react",
    "application"
  ],
  "author": "George Louis",
  "license": "ISC",
  "dependencies": {
    "webpack": "^3.0.0"
  }
}

Body:
If you read the trace, npm is telling you the answer

npm ERR! Unexpected token '"' at 11:3
npm ERR!   "keywords": [
npm ERR!   ^
npm ERR! File: C:\Users\George\Desktop\reactapp\package.json

It tells you whats' wrong (the comma), at which line (11) and which row (3) of which file (C:\Users\George\Desktop\reactapp\package.json).

So, you are missing a comma:

      "start": "node server.js"
    }
  },
  "keywords": [
    "test",
    "react",
    "application"
  ],

Notice the comma before "keywords", that is missing in your JSON, hence it is invalid.


问:
Angular Material 2 - changing md-select placeholder color
Couldn't find any proper way to overwrite the defaults.

Simply this:

```<code><md-select class="selector"
      color="primary"
      placeholder="Date Format" --> change this color
      [(ngModel)]="dateType" name="dateType">
        <md-option value="1">Option 1</md-option>
        <md-option value="2">Option 2</md-option>
</md-select>
</code>```

Trying to overwrite any of the placeholder classes didn't do it:

```<code>md-select, .mat-select-placeholder, .mat-select-trigger {
  color:white !important;
}
</code>```

Anyone got a solution for this?

答:
The quick way to override CSS is to add your CSS block in styles.css (or .scss or .sass) file in ./src.

```<code>md-select, .mat-select-placeholder, .mat-select-trigger {
  color:white !important;
}
</code>```

Summary: You cannot apply CSS on any "Angular Material generated HTML elements" in your.component.css file because Angular adds [_ngcontent-cXX] attribute selectors to all rules defined in it on compilation to keep your CSS rules in scope of only your component.

Edit: As pointed out by @RoddyoftheFrozenPeas (thanks!), we can use /deep/ to apply styles across components. However, Angular is deprecating deep. So, we do not seem to have a long-term-supported way of doing this.

Body:
Couldn't find any proper way to overwrite the defaults.

Simply this:

<md-select class="selector"
      color="primary"
      placeholder="Date Format" --> change this color
      [(ngModel)]="dateType" name="dateType">
        <md-option value="1">Option 1</md-option>
        <md-option value="2">Option 2</md-option>
</md-select>

Trying to overwrite any of the placeholder classes didn't do it:

md-select, .mat-select-placeholder, .mat-select-trigger {
  color:white !important;
}

Anyone got a solution for this?

Body:
The quick way to override CSS is to add your CSS block in styles.css (or .scss or .sass) file in ./src.

md-select, .mat-select-placeholder, .mat-select-trigger {
  color:white !important;
}

Summary: You cannot apply CSS on any "Angular Material generated HTML elements" in your.component.css file because Angular adds [_ngcontent-cXX] attribute selectors to all rules defined in it on compilation to keep your CSS rules in scope of only your component.

Edit: As pointed out by @RoddyoftheFrozenPeas (thanks!), we can use /deep/ to apply styles across components. However, Angular is deprecating deep. So, we do not seem to have a long-term-supported way of doing this.


问:
How to remove rows with multiple occurrences of a specific column in pandas dataframe
I have a data frame containing 3 columns and a large number of rows

```<code>     A     B     C     D     E
aa   hi    43    21    22    45
ab   helo  44    65    86    94
ac   hola  42    71    91    44
ad   hi    12    79    45    12
ae   hey   81    14    34    42
af   hi    21    45    12    02
ag   hola  04    12    39    65
</code>```

I want to remove all multiple occurrences in column A, keeping the first row and eliminate the rest, so I expect a data frame as follows

```<code>     A     B     C     D     E
aa   hi    43    21    22    45
ab   helo  44    65    86    94
ac   hola  42    71    91    44
ae   hey   81    14    34    42
</code>```

答:
Use drop_duplicates with parameter subset for columns for check dupes:

```<code>df = df.drop_duplicates(subset=['A'])
#same as keep='first', because default value can be omited
# df = df.drop_duplicates(subset=['A'], keep='first')
print (df)
       A   B   C   D   E
aa    hi  43  21  22  45
ab  helo  44  65  86  94
ac  hola  42  71  91  44
ae   hey  81  14  34  42
</code>```

Also is possible keep only last rows:

```<code>df = df.drop_duplicates('A', keep='last')
print (df)
       A   B   C   D   E
ab  helo  44  65  86  94
ae   hey  81  14  34  42
af    hi  21  45  12   2
ag  hola   4  12  39  65
</code>```

Body:
I have a data frame containing 3 columns and a large number of rows

     A     B     C     D     E
aa   hi    43    21    22    45
ab   helo  44    65    86    94
ac   hola  42    71    91    44
ad   hi    12    79    45    12
ae   hey   81    14    34    42
af   hi    21    45    12    02
ag   hola  04    12    39    65

I want to remove all multiple occurrences in column A, keeping the first row and eliminate the rest, so I expect a data frame as follows

     A     B     C     D     E
aa   hi    43    21    22    45
ab   helo  44    65    86    94
ac   hola  42    71    91    44
ae   hey   81    14    34    42

Body:
Use drop_duplicates with parameter subset for columns for check dupes:

df = df.drop_duplicates(subset=['A'])
#same as keep='first', because default value can be omited
# df = df.drop_duplicates(subset=['A'], keep='first')
print (df)
       A   B   C   D   E
aa    hi  43  21  22  45
ab  helo  44  65  86  94
ac  hola  42  71  91  44
ae   hey  81  14  34  42

Also is possible keep only last rows:

df = df.drop_duplicates('A', keep='last')
print (df)
       A   B   C   D   E
ab  helo  44  65  86  94
ae   hey  81  14  34  42
af    hi  21  45  12   2
ag  hola   4  12  39  65


问:
Using Create-React-App with ExpressJs
Ok so I have a very simple app with create-react-app. Now I'm using ExpressJS to handle API calls that I am making with the $.ajax() method inside of my react app within the componentWillMount() method.

So all the React front end has is a simple form with 1 input field and  submit like so:

```<code>import React, { Component } from 'react';
import $ from 'jquery';
import './App.css';

class App extends Component {

  componentDidMount(){

      $('form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
          url: '/api',
          type: 'post',
          data: $('form').serialize(),
          dataType: 'json',
          success: function(data) {
            console.log('successful ajax request made!');
          }
        });

      });
  }

  render() {
    return (
      <div className="App">
        <form method="POST">
          <input type="text" name="title" />
          <input id="submit" type="submit" />
        </form>
      </div>
      );
  }
}

export default App;
</code>```

Now my express route look like this:

```<code>var express = require("express");
var router = express.Router();

router.post("/api", function(req, res, next){
    console.log(req.body);
});

module.exports = router;
</code>```

THE PROBLEM

When running create-react-app with npm start it goes to localhost:3000 do to the Webpack local dev server and when I fire off my app.js in my server directory with node server/app.js is goes to localhost:3001 because they cannot run in the same port.

Because of this I cannot make proper API calls without getting an error showing that the POST request has failed.

So now the golden question is how can I make API calls from a local server on 2 different ports?

If you need any more info about my code i'd be more than happy to post it. Help is greatly appreciated, thank you!

答:
You have to set up in your package.json this line:

```<code>"proxy": "http://localhost:PORT"
</code>```

being PORT the port number you set up in your Express server.

Thus, Webpack local dev server knows which URL has to call to in order to reach your API run by Express.

Title: Using Create-React-App with ExpressJs

Body:
Ok so I have a very simple app with create-react-app. Now I'm using ExpressJS to handle API calls that I am making with the $.ajax() method inside of my react app within the componentWillMount() method.

So all the React front end has is a simple form with 1 input field and  submit like so:

import React, { Component } from 'react';
import $ from 'jquery';
import './App.css';

class App extends Component {

  componentDidMount(){

      $('form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
          url: '/api',
          type: 'post',
          data: $('form').serialize(),
          dataType: 'json',
          success: function(data) {
            console.log('successful ajax request made!');
          }
        });

      });
  }

  render() {
    return (

        <form method="POST">
          <input type="text" name="title" />
          <input id="submit" type="submit" />
        </form>

      );
  }
}

export default App;

Now my express route look like this:

var express = require("express");
var router = express.Router();

router.post("/api", function(req, res, next){
    console.log(req.body);
});

module.exports = router;

THE PROBLEM

When running create-react-app with npm start it goes to localhost:3000 do to the Webpack local dev server and when I fire off my app.js in my server directory with node server/app.js is goes to localhost:3001 because they cannot run in the same port.

Because of this I cannot make proper API calls without getting an error showing that the POST request has failed.

So now the golden question is how can I make API calls from a local server on 2 different ports?

If you need any more info about my code i'd be more than happy to post it. Help is greatly appreciated, thank you!

Body:
You have to set up in your package.json this line:

"proxy": "http://localhost:PORT"

being PORT the port number you set up in your Express server.

Thus, Webpack local dev server knows which URL has to call to in order to reach your API run by Express.


问:
HTTP GET request to server only occasionally works
I am using jQuery Ajax to make a GET request. Sometimes It works perfectly, but other times I get a 403 forbidden when I look at the chrome dev tools console. Is this a server issue or my code?

When I sign in, I get the encrypted password, username and ID back from the server. I then store that in LocalStorage since the request I am trying to get working is on another page. I am also required to make a client token from those fields using AES encryption. For that, I am using CryptoJS. For my request, I am required to send in the password, username, ID and client token that has been retrieved from LocalStorage. I realize that may not be a good way to go about it, but I do not have control of the server side.

Edit: Here is my Ajax call to the service:

```<code> $("#system-form").submit(function (e) {
    $.ajax({
        type: "GET",
        url: "myurl",
        data: "User.Username=" + localStorage.getItem("guid") + "&User.Password=" + localStorage.getItem("password") + "&User.SecUser=" + localStorage.getItem("secUser") + "&ClientAppID=" + localStorage.getItem("ClientAppId") +"&"+ $(this).serialize(),
    })
    .done(function(data) {
        //parse data
    })
    .fail(function (xhr, textStatus, error) {
        console.log(JSON.stringify(xhr.responseText));
    });
    e.preventDefault();
});
</code>```

答: I realized my issue was that I need to URL encode my auth parameters. I fixed this by using encodeURIComponent.

Body:
I am using jQuery Ajax to make a GET request. Sometimes It works perfectly, but other times I get a 403 forbidden when I look at the chrome dev tools console. Is this a server issue or my code?

When I sign in, I get the encrypted password, username and ID back from the server. I then store that in LocalStorage since the request I am trying to get working is on another page. I am also required to make a client token from those fields using AES encryption. For that, I am using CryptoJS. For my request, I am required to send in the password, username, ID and client token that has been retrieved from LocalStorage. I realize that may not be a good way to go about it, but I do not have control of the server side.

Edit: Here is my Ajax call to the service:

 $("#system-form").submit(function (e) {
    $.ajax({
        type: "GET",
        url: "myurl",
        data: "User.Username=" + localStorage.getItem("guid") + "&User.Password=" + localStorage.getItem("password") + "&User.SecUser=" + localStorage.getItem("secUser") + "&ClientAppID=" + localStorage.getItem("ClientAppId") +"&"+ $(this).serialize(),
    })
    .done(function(data) {
        //parse data
    })
    .fail(function (xhr, textStatus, error) {
        console.log(JSON.stringify(xhr.responseText));
    });
    e.preventDefault();
});


问:
Why don't Scala Lists have an Ordering?
Is there a reason why there is no implicit Ordering for Lists in Scala?

```<code>val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]
</code>```

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

答: The only really sensible total order over the class of List[Int] would be lexicographic (i.e, compare the first elements of the list, then the second if they are equal, the third if the seconds are equal, etc.).  This isn't provided by the standard library, probably because there aren't that many cases where it's actually needed.   It would be easy enough to create an implicit conversion from List[X] to Ordering[List[X]] that would implement that, and then you could simply import that conversion wherever you needed it.   </p>

ContentLicense: CC BY-SA 2.5

Title: Why don't Scala Lists have an Ordering?

Body:
Is there a reason why there is no implicit Ordering for Lists in Scala?

val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.


问:
jquery/javascript: $(document).trigger vs normal function call?
I just saw two javascript files:

first one had called following line after some success ajax call:

```<code>$(document).trigger("locationloaded");
</code>```

The second js had:

```<code>$(document).on('locationloaded', function () {
   //few lines of code here
});
</code>```

Bit new to JS, just curious to know, could there be any valid reason for calling locationloaded through trigger? Why can't we have simple function as locationloaded() which would be called from first js? If both do the same work, which one should be used?

答:
Event declaration

on registers an event; in this case the locationloaded. And since the locationloaded is a custom event and the only way to fire the event is through the trigger method.

Registers an Event customevent and attach the function locationloaded

```<code>$(document).on('customevent', locationloaded);

function locationloaded() {
    console.log('The custom event is triggered inside the "locationlaoded" function');
}
</code>```

Fires the Event: customevent

```<code>$(document).trigger("customevent");
</code>```

In turn, logs the message The custom event is triggered inside the "locationlaoded" function

Using trigger vs calling the function directly; i.e. locationloaded()

Using trigger broadcast a message to the DOM that an event is fired. So any separate javascript file that listens to an event immediately notified

```<code>$(document).trigger('subscribe');
</code>```

On the same file as $(document).trigger('subscribe')

```<code>$(document).on('subscribe', function() {
   // Send email
});
</code>```

On the other javascript file

```<code>$(document).on('subscribe', function() {
   // Save data
});
</code>```

Whereas calling a declared function directly only allows any other performing tasks within the same context of the method called.

That's why the $(document).trigger('locationloaded)` is declared in a separate file, at the same time if the event is triggered and broadcast, then, the other file can perform its tasks.

Body:
I just saw two javascript files:

first one had called following line after some success ajax call:

$(document).trigger("locationloaded");

The second js had:

$(document).on('locationloaded', function () {
   //few lines of code here
});

Bit new to JS, just curious to know, could there be any valid reason for calling locationloaded through trigger? Why can't we have simple function as locationloaded() which would be called from first js? If both do the same work, which one should be used?

Body:
Event declaration

on registers an event; in this case the locationloaded. And since the locationloaded is a custom event and the only way to fire the event is through the trigger method.

Registers an Event customevent and attach the function locationloaded

$(document).on('customevent', locationloaded);

function locationloaded() {
    console.log('The custom event is triggered inside the "locationlaoded" function');
}

Fires the Event: customevent

$(document).trigger("customevent");

In turn, logs the message The custom event is triggered inside the "locationlaoded" function

Using trigger vs calling the function directly; i.e. locationloaded()

Using trigger broadcast a message to the DOM that an event is fired. So any separate javascript file that listens to an event immediately notified

$(document).trigger('subscribe');

On the same file as $(document).trigger('subscribe')

$(document).on('subscribe', function() {
   // Send email
});

On the other javascript file

$(document).on('subscribe', function() {
   // Save data
});

Whereas calling a declared function directly only allows any other performing tasks within the same context of the method called.

That's why the $(document).trigger('locationloaded)` is declared in a separate file, at the same time if the event is triggered and broadcast, then, the other file can perform its tasks.


问:
How to ignore certain files in Git
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

答:
I have tried the --assume-unchanged and also the .gitignore but neither worked well. They make it hard to switch branches and hard to merge changes from others. This is my solution:

When I commit, I manually remove the files from the list of changes

Before I pull, I stash the changed files. And after pull, I do a stash pop.

git stash

git pull

git stash pop

Step 3 sometimes will trigger a merge and may result in conflict that you need to resolve, which is a good thing.

This allows me to keep local changes that are not shared with others on the team.

ContentLicense: CC BY-SA 4.0

Title: How to ignore certain files in Git


问:
Cannot load module 'fireBaseDatabase' as 'FirebaseDatabase'
So i am new to Firebase and I was following this guys tutorial on how to connect your Swift app to Firebase and this completely works out for him fine. But when I try to import 'FirebaseDatabase' it gives me this error;

cannot load module 'fireBaseDatabase' as 'FirebaseDatabase

I was wondering how i can solve this problem. Thank you.

Here is my podfile;

```<code># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'FIRBaseQuickStart' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for FIRBaseQuickStart

    pod ‘Firebase’
    pod ‘Firebase/Database’

end
</code>```

Now it says "Thread 1: signal SIGABRT" when i try to run the app.

```<code>import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}
</code>```

It gives me error on the class declaration line. This is sooo frustrating.

答: It turns out that it was because of the project name. I had it as 'fireBaseDatabase' and turns out that complicates things. I just created another project with another name and now it's fine!</p>

Body:
So i am new to Firebase and I was following this guys tutorial on how to connect your Swift app to Firebase and this completely works out for him fine. But when I try to import 'FirebaseDatabase' it gives me this error;

cannot load module 'fireBaseDatabase' as 'FirebaseDatabase

I was wondering how i can solve this problem. Thank you.

Here is my podfile;

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'FIRBaseQuickStart' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for FIRBaseQuickStart

    pod ‘Firebase’
    pod ‘Firebase/Database’

end

Now it says "Thread 1: signal SIGABRT" when i try to run the app.

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

It gives me error on the class declaration line. This is sooo frustrating.


问:
How to check of a column in a data frame equals a certain data type in Pandas?
I need to convert all my columns that are of the data type objects into strings.

For simplicity, here is the column headers:

```<code>keys= [Name, Age, Passport, Date, Location, Height]
</code>```

'Name' and 'Location' are of type object. I need to identify these columns are of type object, and convert the columns into strings.

My loop that I attempted to write:

```<code>while variable_1 < len(keys):
  if df[variable_1].dtypes == object:
    df[variable_1] = df[variable_1].astype(str)
    variable_1 = variable_1 + 1
</code>```

This is throwing an obvious error, I am sort of stuck on the syntax.

答:
I am not sure why you would want to do this, but here's how:

```<code>object_columns = (df.dtypes == numpy.object)
df.loc[:, object_columns] = df.loc[:, object_columns].astype(str)
</code>```

If you ever use a loop in Pandas, you are 99% surely doing it wrong.

Body:
I need to convert all my columns that are of the data type objects into strings.

For simplicity, here is the column headers:

keys= [Name, Age, Passport, Date, Location, Height]

'Name' and 'Location' are of type object. I need to identify these columns are of type object, and convert the columns into strings.

My loop that I attempted to write:

while variable_1 < len(keys):
  if df[variable_1].dtypes == object:
    df[variable_1] = df[variable_1].astype(str)
    variable_1 = variable_1 + 1

This is throwing an obvious error, I am sort of stuck on the syntax.

Body:
I am not sure why you would want to do this, but here's how:

object_columns = (df.dtypes == numpy.object)
df.loc[:, object_columns] = df.loc[:, object_columns].astype(str)

If you ever use a loop in Pandas, you are 99% surely doing it wrong.


问:
TSQL - Extract LastName and first initial of FirstName from FullName field that may or may not have a title
I have a requirement to extract from a full name column the last name and the first initial of the first name regardless if they have a title or not. Here are some samples of the data:

FullName Examples:

ALLAN MD,BEER

SIG DO,JEFFREY CAR

Passion, Fruit

Expected Output:

ALLAN_B

SIG_J

Passion_F

答:
So, you want everything before the first space/comma and then the first non-space character after the first comma.  If so:</p>

```<code>select (left(fullname, patindex('%[, ]%', fullname) - 1) + '_' +
        left(ltrim(stuff(fullname, 1, charindex(',', fullname), '')), 1)
       )
</code>```

Body:
So, you want everything before the first space/comma and then the first non-space character after the first comma.  If so:

select (left(fullname, patindex('%[, ]%', fullname) - 1) + '_' +
        left(ltrim(stuff(fullname, 1, charindex(',', fullname), '')), 1)
       )


问:
How do I query the GitHub v4 API for directory contents at a certain tag?
How do I query the GitHub API v4 for the contents of a certain directory of a repository at a certain tag?

This is the best I've come up with so far:

```<code>query {
  repository(owner:"example", name:"example") {
    refs(refPrefix: "tags") {
    }
  }
}
</code>```

答:
From this post, you can get the GitObject with object to filter on branch:/path/folder and print the Tree. The following will get the tree from gson folder from tag gson-2.4 and print name, type and mode :

```<code>query {
  repository(owner:"google", name:"gson") {
      object(expression: "gson-2.4:gson") {
      ... on Tree{
        entries{
          name
          type
          mode
        }
      }
    }
  }
}
</code>```

Body:
How do I query the GitHub API v4 for the contents of a certain directory of a repository at a certain tag?

This is the best I've come up with so far:

query {
  repository(owner:"example", name:"example") {
    refs(refPrefix: "tags") {
    }
  }
}

Body:
From this post, you can get the GitObject with object to filter on branch:/path/folder and print the Tree. The following will get the tree from gson folder from tag gson-2.4 and print name, type and mode :

query {
  repository(owner:"google", name:"gson") {
      object(expression: "gson-2.4:gson") {
      ... on Tree{
        entries{
          name
          type
          mode
        }
      }
    }
  }
}


问:
Cannot get ElasticSearch to map all fields as text
I am trying to map all fields as text. Based on the docs, this should work, but it doesn't:

```<code>PUT my_type
{
  "mappings": {
    "my_type": {
      "dynamic_templates": [
        {
          "longs_as_strings": {
            "match_mapping_type": "*",
            "match":   "*",
            "mapping": {
              "type": "text"
            }
          }
        }
      ]
    }
  }
}

PUT my_type/my_type/1
{
  "intfield": 5
}

GET my_type/_search
</code>```

Results in:

```<code>{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "my_type",
        "_type": "my_type",
        "_id": "1",
        "_score": 1,
        "_source": {
          "intfield": 5
        }
      }
    ]
  }
}
</code>```

答:
I think ES index your data correctly. Try to get mapping of your index, after document was added. Execute this:

```<code>GET my_type
</code>```

I think you will get something like this:

```<code>{
    "my_type": {
        ...
        "mappings": {
            "my_type": {
                ...
                "properties": {
                    "intfield": {
                        "type": "text"
                    }
                }
            }
        },
        ...
    }
}
</code>```

As you see, ES index you intfield like text. And you could work with this field, like with text field.

When you try to get back your data, ES return data "as is". But in index, it store data like text

Body:
I am trying to map all fields as text. Based on the docs, this should work, but it doesn't:

PUT my_type
{
  "mappings": {
    "my_type": {
      "dynamic_templates": [
        {
          "longs_as_strings": {
            "match_mapping_type": "*",
            "match":   "*",
            "mapping": {
              "type": "text"
            }
          }
        }
      ]
    }
  }
}

PUT my_type/my_type/1
{
  "intfield": 5
}

GET my_type/_search

Results in:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "my_type",
        "_type": "my_type",
        "_id": "1",
        "_score": 1,
        "_source": {
          "intfield": 5
        }
      }
    ]
  }
}

Body:
I think ES index your data correctly. Try to get mapping of your index, after document was added. Execute this:

GET my_type

I think you will get something like this:

{
    "my_type": {
        ...
        "mappings": {
            "my_type": {
                ...
                "properties": {
                    "intfield": {
                        "type": "text"
                    }
                }
            }
        },
        ...
    }
}

As you see, ES index you intfield like text. And you could work with this field, like with text field.

When you try to get back your data, ES return data "as is". But in index, it store data like text


问:
Generate a repeating sequence
I need to generate a vector of the following format using R:

```<code>1:10, 1:10, 11:20, 11:20, ... 121:130, 121:130
</code>```

Is there an easier way than creating 12 vectors and then repeating each one twice?

答:
A method using split is

```<code>unlist(rep(split(seq_len(130), rep(1:13, each=10)), each=2), use.names=FALSE)
</code>```

Title: Generate a repeating sequence

Body:
I need to generate a vector of the following format using R:

1:10, 1:10, 11:20, 11:20, ... 121:130, 121:130

Is there an easier way than creating 12 vectors and then repeating each one twice?

Body:
A method using split is

unlist(rep(split(seq_len(130), rep(1:13, each=10)), each=2), use.names=FALSE)


问:
Compiling with font resource
I'm on windows 8.1, visual studio 2017.

I'm using this pricedown font in a directx project I'm working on.

I load it with AddFontResourceEx and create a font for it with D3DXCreateFont.

When I hit "Local Windows Debugger" everything is fine, font renders. Be it in release or in debug mode.
Problem arises when I go through any executable, it never renders said font, be it release or debug.

So I went reading, I read the articles on msdn, this one and others whenever needed.

I don't think I'm doing anything wrong, my Resource View looks like this:

, and IDR_FONT1 looks like this:

The file is automatically loaded into the solution explorer (I didn't add it, VS did from the Resource.rc file), as you can see here:

With these proprieties:

I add it like so:

```<code>AddFontResourceEx("pricedown.ttf", FR_PRIVATE, 0);
this->createFont("Pricedown", 60, true, false);
</code>```

Where createfont is my function to add the font (stripped down, it has arrays):

```<code>bool    D3D9Render::createFont(char *name, int size, bool bold, bool italic)
{
    D3DXCreateFont(m_pD3dDev, size, 0, (bold) ? FW_BOLD : FW_NORMAL, 0, (italic) ? 1 : 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH, name, &m_pFont);
    return true;
}
</code>```

I'm compiling it as x64 release.

As I've said, it works and renders the font when I press "Local Windows Debugger" (in any mode including x64 release), but when I go to project/x64/Release, it just won't render the font. Even the executable size is adequate.

GetLastError on the AddFontResource is 2 (ERROR_FILE_NOT_FOUND)

What am I doing wrong?

答:
(Read the answer until the end, or you'll waste a lot of time.)

I got it. I had read over this blog post.

Here is an example on how to use AddFontMemResourceEx on a font file embedded in the resource.

```<code>HINSTANCE hResInstance = AfxGetResourceHandle( ); //Read the edit

HRSRC res = FindResource(
    hResInstance,
    MAKEINTRESOURCE(IDR_MYFONT),
    L"BINARY"  //Read The Edit
);
if (res)
{
    HGLOBAL mem = LoadResource(hResInstance, res);
    void *data = LockResource(mem);
    size_t len = SizeofResource(hResInstance, res);

    DWORD nFonts;
    m_fonthandle = AddFontMemResourceEx(
        data,       // font resource
        len,       // number of bytes in font resource
        NULL,          // Reserved. Must be 0.
        &nFonts      // number of fonts installed
        );

    if(m_fonthandle==0)
    {
        MessageBox(L"Font add fails", L"Error");
    }
}
</code>```

<s>Though you need afxwin.h</s>, and from here:

afxwin.h is MFC and MFC is not included in the free version of VC++
  (Express Edition)

EDIT:

You do not need to use AfxGetResourceHandle (why you would need afxwin.h), you can simply do:

```<code>HINSTANCE hResInstance = (HINSTANCE)GetModuleHandle(NULL);
</code>```

And in FindResource, the 3rd parameter should be RT_FONT, and so you'd get:

```<code>HRSRC res = FindResource(hResInstance, MAKEINTRESOURCE(IDR_FONT1), RT_FONT);
</code>```

Title: Compiling with font resource

Body:
I'm on windows 8.1, visual studio 2017.

I'm using this pricedown font in a directx project I'm working on.

I load it with AddFontResourceEx and create a font for it with D3DXCreateFont.

When I hit "Local Windows Debugger" everything is fine, font renders. Be it in release or in debug mode.
Problem arises when I go through any executable, it never renders said font, be it release or debug.

So I went reading, I read the articles on msdn, this one and others whenever needed.

I don't think I'm doing anything wrong, my Resource View looks like this:

, and IDR_FONT1 looks like this:

The file is automatically loaded into the solution explorer (I didn't add it, VS did from the Resource.rc file), as you can see here:

With these proprieties:

I add it like so:

AddFontResourceEx("pricedown.ttf", FR_PRIVATE, 0);
this->createFont("Pricedown", 60, true, false);

Where createfont is my function to add the font (stripped down, it has arrays):

bool    D3D9Render::createFont(char *name, int size, bool bold, bool italic)
{
    D3DXCreateFont(m_pD3dDev, size, 0, (bold) ? FW_BOLD : FW_NORMAL, 0, (italic) ? 1 : 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH, name, &m_pFont);
    return true;
}

I'm compiling it as x64 release.

As I've said, it works and renders the font when I press "Local Windows Debugger" (in any mode including x64 release), but when I go to project/x64/Release, it just won't render the font. Even the executable size is adequate.

GetLastError on the AddFontResource is 2 (ERROR_FILE_NOT_FOUND)

What am I doing wrong?

Body:
(Read the answer until the end, or you'll waste a lot of time.)

I got it. I had read over this blog post.

Here is an example on how to use AddFontMemResourceEx on a font file embedded in the resource.

HINSTANCE hResInstance = AfxGetResourceHandle( ); //Read the edit

HRSRC res = FindResource(
    hResInstance,
    MAKEINTRESOURCE(IDR_MYFONT),
    L"BINARY"  //Read The Edit
);
if (res)
{
    HGLOBAL mem = LoadResource(hResInstance, res);
    void *data = LockResource(mem);
    size_t len = SizeofResource(hResInstance, res);

    DWORD nFonts;
    m_fonthandle = AddFontMemResourceEx(
        data,       // font resource
        len,       // number of bytes in font resource
        NULL,          // Reserved. Must be 0.
        &nFonts      // number of fonts installed
        );

    if(m_fonthandle==0)
    {
        MessageBox(L"Font add fails", L"Error");
    }
}

<s>Though you need afxwin.h</s>, and from here:

afxwin.h is MFC and MFC is not included in the free version of VC++
  (Express Edition)

EDIT:

You do not need to use AfxGetResourceHandle (why you would need afxwin.h), you can simply do:

HINSTANCE hResInstance = (HINSTANCE)GetModuleHandle(NULL);

And in FindResource, the 3rd parameter should be RT_FONT, and so you'd get:

HRSRC res = FindResource(hResInstance, MAKEINTRESOURCE(IDR_FONT1), RT_FONT);


问:
count the number of items in a shell variable
I have a shell variable sampleDir:

```<code>sampleDir=/home/sample*
echo $sampleDir
</code>```

will give:

```<code>/home/sample_001 /home/sample_002 /home/sample_003
</code>```

(note there are sub-directories under the sample_*** ones)

If I would like to count how much of these items are in this $sampleDir variable, what would be a best way please? (Expect to return 3)

答:
sampleDir=/home/sample* assigns a literal '/home/sample*' into sampleDir

```<code>$ echo "$sampleDir"
/home/sample*
</code>```

but if you don't double-quote the variable expansion, it will undergo glob expansion (unless set -f is on)
and splitting on $IFS characters (characters in the IFS variable— normally space, tab, and newline).

You can count the number of items after the expansion by passing the unquoted $sampleDir to a function that
counts its arguments.

```<code>argc() { argc=$#; }
argc $sampleDir
echo $argc      #will print the number of items $sampleDir expanded to
</code>```

This would be how you can do it portably, on any POSIX shell (solutions based on things like arrays are limited to shells that have them).

( I recommend returning stuff from shell functions by assigning it to a global variable of the same name as the function.
It's portable, namespace-clean, and very fast (unlike echoing and then using captures to get the echoed string, which is common, but rather expensive))

Body:
I have a shell variable sampleDir:

sampleDir=/home/sample*
echo $sampleDir

will give:

/home/sample_001 /home/sample_002 /home/sample_003

(note there are sub-directories under the sample_*** ones)

If I would like to count how much of these items are in this $sampleDir variable, what would be a best way please? (Expect to return 3)

Body:
sampleDir=/home/sample* assigns a literal '/home/sample*' into sampleDir

$ echo "$sampleDir"
/home/sample*

but if you don't double-quote the variable expansion, it will undergo glob expansion (unless set -f is on)
and splitting on $IFS characters (characters in the IFS variable— normally space, tab, and newline).

You can count the number of items after the expansion by passing the unquoted $sampleDir to a function that
counts its arguments.

argc() { argc=$#; }
argc $sampleDir
echo $argc      #will print the number of items $sampleDir expanded to

This would be how you can do it portably, on any POSIX shell (solutions based on things like arrays are limited to shells that have them).

( I recommend returning stuff from shell functions by assigning it to a global variable of the same name as the function.
It's portable, namespace-clean, and very fast (unlike echoing and then using captures to get the echoed string, which is common, but rather expensive))


问:
How to check if a number is a power of 2
Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

Simple

Correct for any ulong value.

I came up with this simple algorithm:

```<code>private bool IsPowerOfTwo(ulong number)
{
    if (number == 0)
        return false;

    for (ulong power = 1; power > 0; power = power << 1)
    {
        // This for loop used shifting for powers of 2, meaning
        // that the value will become 0 after the last shift
        // (from binary 1000...0000 to 0000...0000) then, the 'for'
        // loop will break out.

        if (power == number)
            return true;
        if (power > number)
            return false;
    }
    return false;
}
</code>```

But then I thought: How about checking if log2 x is an exactly a round number? When I checked for 2^63+1, Math.Log() returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number and it is, because the calculation is done in doubles and not in exact numbers.

```<code>private bool IsPowerOfTwo_2(ulong number)
{
    double log = Math.Log(number, 2);
    double pow = Math.Pow(2, Math.Round(log));
    return pow == number;
}
</code>```

This returned true for the given wrong value: 9223372036854775809.

Is there a better algorithm?

答:
Improving the answer of @user134548, without bits arithmetic:

```<code>public static bool IsPowerOfTwo(ulong n)
{
    if (n % 2 != 0) return false;  // is odd (can't be power of 2)

    double exp = Math.Log(n, 2);
    if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power
    return Math.Pow(2, exp) == n;
}
</code>```

This works fine for:

```<code>IsPowerOfTwo(9223372036854775809)
</code>```

OwnerDisplayName: configurator

Body:
Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

Simple

Correct for any ulong value.

I came up with this simple algorithm:

private bool IsPowerOfTwo(ulong number)
{
    if (number == 0)
        return false;

    for (ulong power = 1; power > 0; power = power << 1)
    {
        // This for loop used shifting for powers of 2, meaning
        // that the value will become 0 after the last shift
        // (from binary 1000...0000 to 0000...0000) then, the 'for'
        // loop will break out.

        if (power == number)
            return true;
        if (power > number)
            return false;
    }
    return false;
}

But then I thought: How about checking if log2 x is an exactly a round number? When I checked for 2^63+1, Math.Log() returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number and it is, because the calculation is done in doubles and not in exact numbers.

private bool IsPowerOfTwo_2(ulong number)
{
    double log = Math.Log(number, 2);
    double pow = Math.Pow(2, Math.Round(log));
    return pow == number;
}

This returned true for the given wrong value: 9223372036854775809.

Is there a better algorithm?

Body:
Improving the answer of @user134548, without bits arithmetic:

public static bool IsPowerOfTwo(ulong n)
{
    if (n % 2 != 0) return false;  // is odd (can't be power of 2)

    double exp = Math.Log(n, 2);
    if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power
    return Math.Pow(2, exp) == n;
}

This works fine for:

IsPowerOfTwo(9223372036854775809)


问:
MySQL Date comparison advice
I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks</p>

```<code>        // If num of months provided is a year, make calculation based on exact year
        if ($age_in_months % 12 == 0)
        {
            // Using 365 days here (60 * 60 * 24 * 365 = 3153600)
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
        }
        else
        {
            // Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
        }
</code>```

答:
I'd just use the MySQL date logic. You can be sneaky and use the fact that the DOB column is stored as text this lie this:

```<code>SELECT whatever FROM users WHERE dob LIKE DATE_FORMAT(CURDATE(), '%d/%m/%%');
</code>```

This will take the current date, format it like a UK date (the %% turns into a single %). So for today (as I post), that would be '20/12/%'. It uses that for a LIKE on dob, giving you everyone with a birthday of '20/12/(something)'.

It's a little weird, but it actually takes advantage of having the DOB stored in a text format. I'm assuming an index on DOB, although you could get away without it if you don't have too many people.

For the second query, it looks like you're trying to do a 'People who were born 6 months ago' type thing. Is that right? You could so something like this:

```<code>SELECT whatever FROM users WHERE DATE_ADD(CURDATE(), INTERVAL -6 MONTH) = STR_TO_DATE(dob, '%d/%m/%Y');
</code>```

It's not a pretty, and if you want people who were born 6, 18, 30... months ago it won't work. In that case, I'd actually go with something like what you have. It's not ideal, but it would more-or-less work and the results may be close enough for you.

Title: MySQL Date comparison advice

Body:
I'm setting up a script to run daily and check for members who meet a certain age - automated emails can be set up in a CMS and assigned to be sent at any age, either in months or years. To handle this via PHP and MySQL, the number of months is passed as a parameter to a method, which I deal with as below. However, I'm not sure I'm going about this in the easiest way! Partly because of the formatting of the UK date format, I'm converting from string to datetime to unix timestamp to make the comparison.
Can anyone find a better way of going about this? Thanks

        // If num of months provided is a year, make calculation based on exact year
        if ($age_in_months % 12 == 0)
        {
            // Using 365 days here (60 * 60 * 24 * 365 = 3153600)
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 31536000) = ' . $age_in_months;
        }
        else
        {
            // Using 30 days as avg month length (60 * 60 * 24 = 86400) - convert months to days
            $clause = 'WHERE ROUND((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(STR_TO_DATE(dob, "%d/%m/%Y"))) / 86400) = ' . $age_in_months * 30;
        }

Body:
I'd just use the MySQL date logic. You can be sneaky and use the fact that the DOB column is stored as text this lie this:

SELECT whatever FROM users WHERE dob LIKE DATE_FORMAT(CURDATE(), '%d/%m/%%');

This will take the current date, format it like a UK date (the %% turns into a single %). So for today (as I post), that would be '20/12/%'. It uses that for a LIKE on dob, giving you everyone with a birthday of '20/12/(something)'.

It's a little weird, but it actually takes advantage of having the DOB stored in a text format. I'm assuming an index on DOB, although you could get away without it if you don't have too many people.

For the second query, it looks like you're trying to do a 'People who were born 6 months ago' type thing. Is that right? You could so something like this:

SELECT whatever FROM users WHERE DATE_ADD(CURDATE(), INTERVAL -6 MONTH) = STR_TO_DATE(dob, '%d/%m/%Y');

It's not a pretty, and if you want people who were born 6, 18, 30... months ago it won't work. In that case, I'd actually go with something like what you have. It's not ideal, but it would more-or-less work and the results may be close enough for you.


问:
Filter data frame based on paired combinations of variables
I have a data frame, ex_data in the example below, that lists participant id, a group identifier, and some value. I then have a second data frame that indicates particular observations that need to be removed (remove_data in the below example). Is there a way to use dplyr or other tidyverse functions to filter out these combinations? In my efforts below, I end up filtering out all record for the indicated participants, rather than just the data for when the participant was in that specific group. I'm able to get the desired output using a for loop, which I've also included for reference.

library(tidyverse)
#> Loading tidyverse: ggplot2
#> Loading tidyverse: tibble
#> Loading tidyverse: tidyr
#> Loading tidyverse: readr
#> Loading tidyverse: purrr
#> Loading tidyverse: dplyr
#> Conflicts with tidy packages ----------------------------------------------
#> filter(): dplyr, stats
#> lag():    dplyr, stats

set.seed(1234)
ex_data <- data_frame(
  id = rep(sample(1:100, 10), 2),
  group = rep(c("a", "b"), each = 10),
  score = rnorm(20)
)
ex_data
#> # A tibble: 20 x 3
#>       id group       score
#>    <int> <chr>       <dbl>
#>  1    12     a  0.50605589
#>  2    62     a -0.57473996
#>  3    60     a -0.54663186
#>  4    61     a -0.56445200
#>  5    83     a -0.89003783
#>  6    97     a -0.47719270
#>  7     1     a -0.99838644
#>  8    22     a -0.77625389
#>  9    99     a  0.06445882
#> 10    47     a  0.95949406
#> 11    12     b -0.11028549
#> 12    62     b -0.51100951
#> 13    60     b -0.91119542
#> 14    61     b -0.83717168
#> 15    83     b  2.41583518
#> 16    97     b  0.13408822
#> 17     1     b -0.49068590
#> 18    22     b -0.44054787
#> 19    99     b  0.45958944
#> 20    47     b -0.69372025

remove_data <- data_frame(
  id = sample(ex_data$id, 3),
  group = sample(c("a", "b"), 3, replace = TRUE)
)
remove_data
#> # A tibble: 3 x 2
#>      id group
#>   <int> <chr>
#> 1    62     b
#> 2    97     a
#> 3    60     b

# Current efforts
ex_data %>%
  filter(!(id %in% remove_data$id & group %in% remove_data$group))
#> # A tibble: 14 x 3
#>       id group       score
#>    <int> <chr>       <dbl>
#>  1    12     a  0.50605589
#>  2    61     a -0.56445200
#>  3    83     a -0.89003783
#>  4     1     a -0.99838644
#>  5    22     a -0.77625389
#>  6    99     a  0.06445882
#>  7    47     a  0.95949406
#>  8    12     b -0.11028549
#>  9    61     b -0.83717168
#> 10    83     b  2.41583518
#> 11     1     b -0.49068590
#> 12    22     b -0.44054787
#> 13    99     b  0.45958944
#> 14    47     b -0.69372025

# Desired output
for (i in 1:nrow(remove_data)) {
  ex_data <- ex_data %>%
    filter(!(id == remove_data$id[i] & group == remove_data$group[i]))
}
ex_data
#> # A tibble: 17 x 3
#>       id group       score
#>    <int> <chr>       <dbl>
#>  1    12     a  0.50605589
#>  2    62     a -0.57473996
#>  3    60     a -0.54663186
#>  4    61     a -0.56445200
#>  5    83     a -0.89003783
#>  6     1     a -0.99838644
#>  7    22     a -0.77625389
#>  8    99     a  0.06445882
#>  9    47     a  0.95949406
#> 10    12     b -0.11028549
#> 11    61     b -0.83717168
#> 12    83     b  2.41583518
#> 13    97     b  0.13408822
#> 14     1     b -0.49068590
#> 15    22     b -0.44054787
#> 16    99     b  0.45958944
#> 17    47     b -0.69372025
```

Body:
why not use anti_join instead of filter?

dplyr::anti_join(ex_data, remove_data)

Joining, by = c("id", "group")
# A tibble: 17 x 3
      id group       score
   <int> <chr>       <dbl>
 1    47     b -0.69372025
 2    99     b  0.45958944
 3    22     b -0.44054787
 4     1     b -0.49068590
 5    97     b  0.13408822
 6    83     b  2.41583518
 7    61     b -0.83717168
 8    12     b -0.11028549
 9    47     a  0.95949406
10    99     a  0.06445882
11    22     a -0.77625389
12     1     a -0.99838644
13    83     a -0.89003783
14    61     a -0.56445200
15    60     a -0.54663186
16    62     a -0.57473996
17    12     a  0.50605589


问:
How to run thousands of queries in Ms Access?
I've discovered the SQL VIEW in Ms Access to execute some queries, but I need to execute about 20.000 UPDATE queries I have in a .sql file.

When I paste in the SQL VIEW it says the "Text is too long to modify".

How can I run those UPDATE's ?

答:
The limit to the number of characters in an Access SQL query is "about 64000" - see here https://support.office.com/en-us/article/Access-2010-specifications-HA010341462.aspx. And unfortunately you cannot execute multiple statements in a query. I think this will mean quite a bit of work for you in VBA. Here is an example approach (pseudocode):-

```<code>open file
read line into variable
while not EOF
currentdb.execute variable, dbfailonerror
read next line
wend
close file
</code>```

Probably a nasty surprise for you if you are used to executing huge batches of statements using other RDBMS!

An alternative suggestion: we don't know exactly what your file looks like or where it comes from, but if it is generated from another RDBMS which you have access to, then I would very strongly recommend that you set up an ODBC connection to it, and query out the data you need (either by linking the tables or writing a pass through query), then inserting into your local Access tables. This will be many orders of magnitude faster than executing thousands of individual statements.

If your only source of the data is the SQL statements then you may still be better of if you can parse the SQL text into relevant columns (for example PK, and value to be updated, or if inserting, then all column values), then save as a csv file, import into Access, add keys as necessary, and then run a single update statement as an updateable query against the imported data and the existing tables. Dumping the file into Excel and using the various string functions may enable you to parse the data quite quickly.

Body:
The limit to the number of characters in an Access SQL query is "about 64000" - see here https://support.office.com/en-us/article/Access-2010-specifications-HA010341462.aspx. And unfortunately you cannot execute multiple statements in a query. I think this will mean quite a bit of work for you in VBA. Here is an example approach (pseudocode):-

open file
read line into variable
while not EOF
currentdb.execute variable, dbfailonerror
read next line
wend
close file

Probably a nasty surprise for you if you are used to executing huge batches of statements using other RDBMS!

An alternative suggestion: we don't know exactly what your file looks like or where it comes from, but if it is generated from another RDBMS which you have access to, then I would very strongly recommend that you set up an ODBC connection to it, and query out the data you need (either by linking the tables or writing a pass through query), then inserting into your local Access tables. This will be many orders of magnitude faster than executing thousands of individual statements.

If your only source of the data is the SQL statements then you may still be better of if you can parse the SQL text into relevant columns (for example PK, and value to be updated, or if inserting, then all column values), then save as a csv file, import into Access, add keys as necessary, and then run a single update statement as an updateable query against the imported data and the existing tables. Dumping the file into Excel and using the various string functions may enable you to parse the data quite quickly.


答:
I think what you're looking for is

```<code>awk 'int($1)==57581' file
</code>```

regex checks will give you false positives if not checked for decimal point in the right place (eg. 575810000 will satisfy "starting with" condition).

In your notation, this is equivalent to

```<code>awk -v lowerInc=57581 -v upperExc=57582 'lowerInc<=$1 && $1<upperExc' file
</code>```

Title: how to use awk for extract a column with a determinate range

Body:
i have a file like this:

57580.87499999965802999   -2.01319509921268036e+00>

57580.91666666632227134   -2.00037110698185661e+00>

57580.95833333298651269    -1.98754711475190549e+00>

57580.99999999965075403    -1.97472312252219151e+00>

57581.04166666631499538    -1.95440667936783941e+00>

57581.08333333297923673    -1.94158268713747040e+00>

57581.12499999964347808    -1.92875869490721019e+00>

57581.16666666630771942    -1.91593470267662269e+00>

57581.20833333297196077    -1.89561825952250729e+00>

and i would like to use awk to print only the columns that start wit 57581

the code i wrote is

DATA=57581
DATA2=57582

awk '{ if ($1 >= $DATA'.00000000000000000' && $1 < $DATA2'.00000000000000000') print $1, $2 >> "file.txt"}' $filename

any idea?

thank you

Body:
I think what you're looking for is

awk 'int($1)==57581' file

regex checks will give you false positives if not checked for decimal point in the right place (eg. 575810000 will satisfy "starting with" condition).

In your notation, this is equivalent to

awk -v lowerInc=57581 -v upperExc=57582 'lowerInc<=$1 && $1<upperExc' file


问:
How to correctly write this "simple" T-SQL query
I took a test with a bunch T-SQL exercises. I did well in all but one of them. I took a picture of it to find out later the correct answer. I don't consider myself an expert but I know my way around SQL. Yet, I cannot write what should be a not so hard query to come up with.

Here is the exercise:

I probably need to group by Name and Sum the price but I am still kinda lost. Help with this one! Thank you

答:
This is a pretty simple GROUP BY with a COUNT() and SUM(). The two tables will need to be joined as well:</p>

```<code>SELECT name, count(*) as total_sales, sum(price) as total_amount
FROM people INNER JOIN sales ON people.id = sales.fk_people
GROUP BY name;
</code>```

Body:
This is a pretty simple GROUP BY with a COUNT() and SUM(). The two tables will need to be joined as well:

SELECT name, count(*) as total_sales, sum(price) as total_amount
FROM people INNER JOIN sales ON people.id = sales.fk_people
GROUP BY name;


问:
Emacs Neotree open file in split window
Is there a way to open a file from Neotree in a new split window?

I want to achive same functionality as Vim NERDTree shortcuts "i" and "s"

Or is that the wrong approach?

答: You can use | for veritcal split and - for horizontal split.</p>

Title: Emacs Neotree open file in split window


问:
In Drools, what does it mean to compare IDs
I understand the basics of writing drools rules now but i can't seem to understand in the examples that i've seen (optaplanner), there are comparisons of IDs. Is this necessary? Why is it there?

```<code>// RoomOccupancy: Two lectures in the same room at the same period.
// Any extra lecture in the same period and room counts as one more violation.
rule "roomOccupancy"
    when
        Lecture($leftId : id, period != null, $period : period, room != null, $room : room)
        // $leftLecture has lowest id of the period+room combo
        not Lecture(period == $period, room == $room, id < $leftId)
        // rightLecture has the same period
        Lecture(period == $period, room == $room, id > $leftId, $rightId : id)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end
</code>```

From my understanding deleting the line with not Lecture(.. and leaving Lecture(period == $period, room == $room) should do the trick. Is my understanding correct or am I missing some use cases here?

答:
You should understand that a pattern such as

```<code>$a: Lecture()
$b: Lecture()
</code>```

with two Lecture facts A an B in the system will produce the following matches and firings:

```<code>$a-A, $b-B   (1)
$a-B, $b-A   (2)
$a-A, $b-A
$a-B, $b-B
</code>```

Therefore, to reduce the unwanted combinations you need have a way to ascertain to have not identical facts matching (bound to) $a and $b:

```<code>$a: Lecture( $ida: id )
$b: Lecture( $idb: id != $ida )
</code>```

However, using not equal still produces combinations (1) and (2).

Body:
I understand the basics of writing drools rules now but i can't seem to understand in the examples that i've seen (optaplanner), there are comparisons of IDs. Is this necessary? Why is it there?

// RoomOccupancy: Two lectures in the same room at the same period.
// Any extra lecture in the same period and room counts as one more violation.
rule "roomOccupancy"
    when
        Lecture($leftId : id, period != null, $period : period, room != null, $room : room)
        // $leftLecture has lowest id of the period+room combo
        not Lecture(period == $period, room == $room, id < $leftId)
        // rightLecture has the same period
        Lecture(period == $period, room == $room, id > $leftId, $rightId : id)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

From my understanding deleting the line with not Lecture(.. and leaving Lecture(period == $period, room == $room) should do the trick. Is my understanding correct or am I missing some use cases here?

Body:
You should understand that a pattern such as

$a: Lecture()
$b: Lecture()

with two Lecture facts A an B in the system will produce the following matches and firings:

$a-A, $b-B   (1)
$a-B, $b-A   (2)
$a-A, $b-A
$a-B, $b-B

Therefore, to reduce the unwanted combinations you need have a way to ascertain to have not identical facts matching (bound to) $a and $b:

$a: Lecture( $ida: id )
$b: Lecture( $idb: id != $ida )

However, using not equal still produces combinations (1) and (2).


问:
Python: wifi subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlp4s0']' returned non-zero exit status 1
I am working on a python script to automatically connect to a known Wifi.
I am using the following library https://wifi.readthedocs.io/en/latest/ which seems to work very well. The only problem is that when a try to connect to a chosen Wifi through the scheme.activate() command, it returns the following error:

```<code>    Traceback (most recent call last):
  File "wifi_connection.py", line 100, in <module>
    print Connect('dotbot', 'pass')
  File "wifi_connection.py", line 64, in Connect
    savedcell.activate()
  File "/home/pietro/.local/lib/python2.7/site-packages/wifi/scheme.py", line 172, in activate
    subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 574, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlp4s0']' returned non-zero exit status 1
</code>```

which I really don't understand.

The name of the script is wifi_connection.py and the code is the following:

```<code>import wifi

def Search():
    wifilist = []

    cells = wifi.Cell.all('wlp4s0')

    for cell in cells:
        wifilist.append(cell)

    return wifilist

def FindFromSearchList(ssid):
    wifilist = Search()

    for cell in wifilist:
        if cell.ssid == ssid:
            return cell

    return False

def FindFromSavedList(ssid):
    cell = wifi.Scheme.find('wlp4s0', ssid)

    if cell:
        return cell

    return False

def Add(cell, password=None):
    if not cell:
        return False

    scheme = wifi.Scheme.for_cell('wlp4s0', cell.ssid, cell, password)
    scheme.save()
    return scheme

def Delete(ssid):
    if not ssid:
        return False

    cell = FindFromSavedList(ssid)

    if cell:
        cell.delete()
        return True

    return False

def Connect(ssid, password):
    cell = FindFromSearchList(ssid)

    if cell:
        savedcell = FindFromSavedList(cell.ssid)

        # Already Saved from Setting
        if savedcell:
            savedcell.activate()
            return cell

        # First time to connect
        else:
            if cell.encrypted:
                if password:
                    scheme = Add(cell, password)

                    try:
                        scheme.activate()

                    # Wrong Password
                    except wifi.exceptions.ConnectionError:
                        Delete(ssid)
                        return False

                    return cell
                else:
                    return False
            else:
                scheme = Add(cell)

                try:
                    scheme.activate()
                except wifi.exceptions.ConnectionError:
                    Delete(ssid)
                    return False

                return cell

    return False

print " "
print Search()
print " "
print Connect('dotbot', 'pass')
print " "
</code>```

where wlp4s0 is the name of the wifi interface, "dotbot" and "pass" are respectively the name of the wifi and its password.

Thank you in advance for your help.

The strange thing is that when I run the command "ifconfig", I get:

```<code>wlp4s0    Link encap:Ethernet  IndirizzoHW e0:06:e6:f8:53:29
          indirizzo inet:192.168.0.116  Bcast:192.168.0.255
          Maschera:255.255.255.0
          indirizzo inet6: fe80::525e:7c8d:6f43:9d98/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:222347 errors:0 dropped:0 overruns:0 frame:96541
          TX packets:147762 errors:0 dropped:0 overruns:0 carrier:0
          collisioni:0 txqueuelen:1000
          Byte RX:208449235 (208.4 MB)  Byte TX:17616899 (17.6 MB)
          Interrupt:19
</code>```

but if I try "/sbin/ifdown wlp4s0", then I get:

```<code>Unknown interface wlp4s0
</code>```

答:
make sure your interface is configured in

/etc/network/interfaces

my config, for example:

```<code>auto wlp7s0
iface wlp7s0 inet loopback
</code>```

Body:
I am working on a python script to automatically connect to a known Wifi.
I am using the following library https://wifi.readthedocs.io/en/latest/ which seems to work very well. The only problem is that when a try to connect to a chosen Wifi through the scheme.activate() command, it returns the following error:

    Traceback (most recent call last):
  File "wifi_connection.py", line 100, in <module>
    print Connect('dotbot', 'pass')
  File "wifi_connection.py", line 64, in Connect
    savedcell.activate()
  File "/home/pietro/.local/lib/python2.7/site-packages/wifi/scheme.py", line 172, in activate
    subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 574, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlp4s0']' returned non-zero exit status 1

which I really don't understand.

The name of the script is wifi_connection.py and the code is the following:

import wifi

def Search():
    wifilist = []

    cells = wifi.Cell.all('wlp4s0')

    for cell in cells:
        wifilist.append(cell)

    return wifilist

def FindFromSearchList(ssid):
    wifilist = Search()

    for cell in wifilist:
        if cell.ssid == ssid:
            return cell

    return False

def FindFromSavedList(ssid):
    cell = wifi.Scheme.find('wlp4s0', ssid)

    if cell:
        return cell

    return False

def Add(cell, password=None):
    if not cell:
        return False

    scheme = wifi.Scheme.for_cell('wlp4s0', cell.ssid, cell, password)
    scheme.save()
    return scheme

def Delete(ssid):
    if not ssid:
        return False

    cell = FindFromSavedList(ssid)

    if cell:
        cell.delete()
        return True

    return False

def Connect(ssid, password):
    cell = FindFromSearchList(ssid)

    if cell:
        savedcell = FindFromSavedList(cell.ssid)

        # Already Saved from Setting
        if savedcell:
            savedcell.activate()
            return cell

        # First time to connect
        else:
            if cell.encrypted:
                if password:
                    scheme = Add(cell, password)

                    try:
                        scheme.activate()

                    # Wrong Password
                    except wifi.exceptions.ConnectionError:
                        Delete(ssid)
                        return False

                    return cell
                else:
                    return False
            else:
                scheme = Add(cell)

                try:
                    scheme.activate()
                except wifi.exceptions.ConnectionError:
                    Delete(ssid)
                    return False

                return cell

    return False

print " "
print Search()
print " "
print Connect('dotbot', 'pass')
print " "

where wlp4s0 is the name of the wifi interface, "dotbot" and "pass" are respectively the name of the wifi and its password.

Thank you in advance for your help.

The strange thing is that when I run the command "ifconfig", I get:

wlp4s0    Link encap:Ethernet  IndirizzoHW e0:06:e6:f8:53:29
          indirizzo inet:192.168.0.116  Bcast:192.168.0.255
          Maschera:255.255.255.0
          indirizzo inet6: fe80::525e:7c8d:6f43:9d98/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:222347 errors:0 dropped:0 overruns:0 frame:96541
          TX packets:147762 errors:0 dropped:0 overruns:0 carrier:0
          collisioni:0 txqueuelen:1000
          Byte RX:208449235 (208.4 MB)  Byte TX:17616899 (17.6 MB)
          Interrupt:19

but if I try "/sbin/ifdown wlp4s0", then I get:

Unknown interface wlp4s0

Body:
make sure your interface is configured in

/etc/network/interfaces

my config, for example:

auto wlp7s0
iface wlp7s0 inet loopback


问:
Listening to real variable changes in Javascript
I hope not to bother anyone. I don't have enough reputation points to comment and ask directly in that beautiful suggestion: https://stackoverflow.com/a/37403125/8261024 .

My additional question to that great solution is: what, if I want to detect only real changes? What I mean is: if the value of x.a changes, i will know. What, if the value of x.a was 42 and after the change it is 42 too, but I want only a real change of the value? I only want to know, if it changes to dolphin or fish or sth.

Maybe I am blind right know so I can't see the obvious.

Thanks.

答:
Yes shure, simply compare the new to the stored value:</p>

```<code>var obj = (function(){
  let store = undefined;

  return {
   get value() {
     return store;
   },
   set value(v){
    if(v !== store){
      alert("changed");
      store = v;
    }
   },
  };
})();

obj.value = 10;//changed
obj.value = 10;
</code>```

Body:
Yes shure, simply compare the new to the stored value:

var obj = (function(){
  let store = undefined;

  return {
   get value() {
     return store;
   },
   set value(v){
    if(v !== store){
      alert("changed");
      store = v;
    }
   },
  };
})();

obj.value = 10;//changed
obj.value = 10;


问:
Why is if request.method == 'POST' and 'photo' in request.files
I have this little example script. It gets a file from a HTML an uploads it to the server. That part works just fine. Please see the script below.

I would like to take some action if no file is selected in the form. I thought the following would evaluate to false if no file was selected in the HTML form, but it seams to be always true.

```<code>  if request.method == 'POST' and 'photo' in request.files:
</code>```

Either a file is selected or not 'Text to print' is returned.

What am I missing here?

Any hint is appreciated.

Best regards
Kresten

```<code>from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads, IMAGES

app = Flask(__name__)
photos = UploadSet('photos', IMAGES)

app.config['UPLOADED_PHOTOS_DEST'] = 'static'
configure_uploads(app, photos)

@app.route('/upload', methods=['GET', 'POST'])
def upload():
  if request.method == 'POST' and 'photo' in request.files:
    filename = photos.url(request.files['photo'])
    fil = request.files['photo']
    return 'Text to print'

  return render_template('upload.html')

if __name__ == '__main__':
  app.run(debug=True)
  app.run(host='0.0.0.0')
</code>```

The HTML template:

```<code><html>
<head>
        <title>Upload</title>
</head>
<body>
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}">
    <input type=file name=photo>
    <input type="submit">
</form>
</body>
</html>
</code>```

(Thanks to Danila for saving my day)

答:
In your case photo always will be in request.files, but filename not(can be empty string). Just change condition to:

```<code>@app.route('/upload', methods=['GET', 'POST'])
def upload():
  if request.method == 'POST' and request.files['photo'].filename:
    filename = photos.url(request.files['photo'])
    fil = request.files['photo']
    return 'Text to print'

  return render_template('upload.html')
</code>```

Body:
I have this little example script. It gets a file from a HTML an uploads it to the server. That part works just fine. Please see the script below.

I would like to take some action if no file is selected in the form. I thought the following would evaluate to false if no file was selected in the HTML form, but it seams to be always true.

  if request.method == 'POST' and 'photo' in request.files:

Either a file is selected or not 'Text to print' is returned.

What am I missing here?

Any hint is appreciated.

Best regards
Kresten

from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads, IMAGES

app = Flask(__name__)
photos = UploadSet('photos', IMAGES)

app.config['UPLOADED_PHOTOS_DEST'] = 'static'
configure_uploads(app, photos)

@app.route('/upload', methods=['GET', 'POST'])
def upload():
  if request.method == 'POST' and 'photo' in request.files:
    filename = photos.url(request.files['photo'])
    fil = request.files['photo']
    return 'Text to print'

  return render_template('upload.html')

if __name__ == '__main__':
  app.run(debug=True)
  app.run(host='0.0.0.0')

The HTML template:

        <title>Upload</title>

<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}">
    <input type=file name=photo>
    <input type="submit">
</form>

(Thanks to Danila for saving my day)

Body:
In your case photo always will be in request.files, but filename not(can be empty string). Just change condition to:

@app.route('/upload', methods=['GET', 'POST'])
def upload():
  if request.method == 'POST' and request.files['photo'].filename:
    filename = photos.url(request.files['photo'])
    fil = request.files['photo']
    return 'Text to print'

  return render_template('upload.html')


问:
ERROR in Cannot read property 'getSymbolByModule' of undefined
When I upgrade to Angular 4 and run ng serve, I got the following error:

```<code>ERROR in Cannot read property 'getSymbolByModule' of undefined
</code>```

The dependencies are used as per following

```<code>  "dependencies": {
    "@angular/animations": "^4.0.2",
    "@angular/cli": "^1.0.0",
    "@angular/common": "^4.0.2",
    "@angular/compiler": "^4.0.2",
    "@angular/compiler-cli": "^2.4.10",
    "@angular/core": "^4.0.2",
    "@angular/forms": "^4.0.2",
    "@angular/http": "^4.0.2",
    "@angular/platform-browser": "^4.0.2",
    "@angular/platform-browser-dynamic": "^4.0.2",
    "@angular/platform-server": "^4.0.2",
    "@angular/router": "^4.0.2",
    "@types/jasmine": "^2.5.47",
    "angular2-flash-messages": "^1.0.8",
    "angular2-jwt": "^0.1.28",
    "codelyzer": "^2.1.1",
    "core-js": "^2.4.1",
    "jasmine-spec-reporter": "^2.7.0",
    "karma": "^1.6.0",
    "rxjs": "^5.3.0",
    "ts-helpers": "^1.1.2",
    "ts-node": "^1.7.3",
    "typescript": "^2.0.10",
    "zone.js": "^0.8.5"
  },
</code>```

Is  there something wrong here?

答: I had the same problem, but I also had a version of angular-cli in my devDependencies. I removed that and ng-serve worked.

Body:
When I upgrade to Angular 4 and run ng serve, I got the following error:

ERROR in Cannot read property 'getSymbolByModule' of undefined

The dependencies are used as per following

  "dependencies": {
    "@angular/animations": "^4.0.2",
    "@angular/cli": "^1.0.0",
    "@angular/common": "^4.0.2",
    "@angular/compiler": "^4.0.2",
    "@angular/compiler-cli": "^2.4.10",
    "@angular/core": "^4.0.2",
    "@angular/forms": "^4.0.2",
    "@angular/http": "^4.0.2",
    "@angular/platform-browser": "^4.0.2",
    "@angular/platform-browser-dynamic": "^4.0.2",
    "@angular/platform-server": "^4.0.2",
    "@angular/router": "^4.0.2",
    "@types/jasmine": "^2.5.47",
    "angular2-flash-messages": "^1.0.8",
    "angular2-jwt": "^0.1.28",
    "codelyzer": "^2.1.1",
    "core-js": "^2.4.1",
    "jasmine-spec-reporter": "^2.7.0",
    "karma": "^1.6.0",
    "rxjs": "^5.3.0",
    "ts-helpers": "^1.1.2",
    "ts-node": "^1.7.3",
    "typescript": "^2.0.10",
    "zone.js": "^0.8.5"
  },

Is  there something wrong here?


问:
Mac Mouse Coordinates != Window Frame?
Here's my issue.  Hopefully I can explain it well enough.  My desktop is a 2x2 with monitors of size (2048,1152).

I'm trying to use an ancillary device to generate mouse clicks.  My mouse click is supposed to be on coordinate (1600,1407)-ish (on the "pan button"), assuming (0,0) is the top-left of my entire desktop area.  It moves the mouse to the correct position, but when I perform a CGREctContainsPoint()) it gives me NO as a result.

The rectangle(frame) given by my pop-up window has origin of (1558,-406)?  So the math is correct for CGREctContainsPoint(), but the window's frame should contain the point.  (even more so as I can see the mouse cursor over the window.)

Why?  Is it because it is a child window? (center of my desktop is in center of the image, each window is a different background color.)

I have tried using the following:

```<code>NSRect pFrame = [_popupWindow frame];
NSPoint pOrigin = pFrame.origin;
NSPoint correctedOrigin = [[_popupWindow parentWindow] convertBaseToScreen:pOrigin];
pFrame.origin = correctedOrigin;
</code>```

but that gives me:

... Rect {{1488, -1529}, {439, 306}}, Point {1556.17, 1314.76}, InRect 0

as a result, which still doesn't place the point (which I can see hovering over the pop-up window) in the rect.

Why is the rect for my popup window and the point not even remotely the same?  How can I get them in the same coordinate "space"?

Thanks,

答:
On a mac, (0,0) is in the bottom-left corner. How are you getting the mouse coordinates? The window's frame will be in screen coordinates, so if the point is in it's base coordinates you need to call point = [window convertBaseToScreen:point]; before comparing.

Here are two ways to get the mouse location in cocoa:

```<code>NSPoint location = [NSEvent mouseLocation];
//already in screen coordinates, no need to convert
</code>```

or

```<code>//window is a variable containing your window
NSPoint location = [window mouseLocationOutsideOfEventStream];
//convert to screen coordinates
location = [window convertBaseToScreen:location];
</code>```

Title: Mac Mouse Coordinates != Window Frame?

Body:
Here's my issue.  Hopefully I can explain it well enough.  My desktop is a 2x2 with monitors of size (2048,1152).

I'm trying to use an ancillary device to generate mouse clicks.  My mouse click is supposed to be on coordinate (1600,1407)-ish (on the "pan button"), assuming (0,0) is the top-left of my entire desktop area.  It moves the mouse to the correct position, but when I perform a CGREctContainsPoint()) it gives me NO as a result.

The rectangle(frame) given by my pop-up window has origin of (1558,-406)?  So the math is correct for CGREctContainsPoint(), but the window's frame should contain the point.  (even more so as I can see the mouse cursor over the window.)

Why?  Is it because it is a child window? (center of my desktop is in center of the image, each window is a different background color.)

I have tried using the following:

NSRect pFrame = [_popupWindow frame];
NSPoint pOrigin = pFrame.origin;
NSPoint correctedOrigin = [[_popupWindow parentWindow] convertBaseToScreen:pOrigin];
pFrame.origin = correctedOrigin;

but that gives me:

... Rect {{1488, -1529}, {439, 306}}, Point {1556.17, 1314.76}, InRect 0

as a result, which still doesn't place the point (which I can see hovering over the pop-up window) in the rect.

Why is the rect for my popup window and the point not even remotely the same?  How can I get them in the same coordinate "space"?

Thanks,

Body:
On a mac, (0,0) is in the bottom-left corner. How are you getting the mouse coordinates? The window's frame will be in screen coordinates, so if the point is in it's base coordinates you need to call point = [window convertBaseToScreen:point]; before comparing.

Here are two ways to get the mouse location in cocoa:

NSPoint location = [NSEvent mouseLocation];
//already in screen coordinates, no need to convert

or

//window is a variable containing your window
NSPoint location = [window mouseLocationOutsideOfEventStream];
//convert to screen coordinates
location = [window convertBaseToScreen:location];


问:
iTunes track Played Date
The following AppleScript works as expected, giving me the last played value for the first track in the the specified user playlist.

```<code>tell application "iTunes"
    set theTrack to (item 1 of tracks of user playlist "Named")
    set playedDate to played date of theTrack
    display dialog (playedDate as string)
end tell
</code>```

This AppleScript however, will not compile and instead gives me an error Expected end of line, etc. but found class name.

```<code>tell application "iTunes"
    my testMethod(item 1 of tracks of user playlist "Named")
end tell

on testMethod(theTrack)
    set trackName to (name of theTrack)
    display dialog trackName
    -- set playedDate to played date of theTrack
    -- display dialog playedDate
end testMethod
</code>```

Are these two scripts so different that AppleScript's compiler goes wonky? How do I get played date of theTrack in to playedDate in the second example?

答:
played date is a part of the iTunes application terminology, you need an application tell block

```<code>tell application "iTunes"
    set playedDate to played date of theTrack
end tell
</code>```

or an using terms from application block to help the compiler to resolve the terminology

```<code>using terms from application "iTunes"
    set playedDate to played date of theTrack
end using terms from
</code>```

You might now ask: why does name work? Well, name is a well-known property in many applications and even the AppleScript runner knows it.

Title: iTunes track Played Date

Body:
The following AppleScript works as expected, giving me the last played value for the first track in the the specified user playlist.

tell application "iTunes"
    set theTrack to (item 1 of tracks of user playlist "Named")
    set playedDate to played date of theTrack
    display dialog (playedDate as string)
end tell

This AppleScript however, will not compile and instead gives me an error Expected end of line, etc. but found class name.

tell application "iTunes"
    my testMethod(item 1 of tracks of user playlist "Named")
end tell

on testMethod(theTrack)
    set trackName to (name of theTrack)
    display dialog trackName
    -- set playedDate to played date of theTrack
    -- display dialog playedDate
end testMethod

Are these two scripts so different that AppleScript's compiler goes wonky? How do I get played date of theTrack in to playedDate in the second example?

Body:
played date is a part of the iTunes application terminology, you need an application tell block

tell application "iTunes"
    set playedDate to played date of theTrack
end tell

or an using terms from application block to help the compiler to resolve the terminology

using terms from application "iTunes"
    set playedDate to played date of theTrack
end using terms from

You might now ask: why does name work? Well, name is a well-known property in many applications and even the AppleScript runner knows it.


问:
Excel - How to create a formula to return a cell to the right of the result of another formula
Basically, I have this formula in a cell to return the very first non 0 value in a row:

=INDEX('Financials Cashflow Year'!C30:M30,MATCH(TRUE,INDEX('Financials Cashflow Year'!C30:M30<>0,),0))

I would like a formula to return the value of the cell on the right of the one picked up by this very first formula.

Say we have sheet 1 first row:

```<code>0 0 0 4 3 2
</code>```

Sheet 2 I would like to see with the formulas. Something scalable.

```<code>4 3 2
</code>```

答:
I think you'll want an Array Formula for this. Instead of the match use a SMALL function to get the item you want, something like this:

```<code>={INDEX('Financials Cashflow Year'!$C30:$M30,1,SMALL(IF('Financials Cashflow Year'!$C30:$M30>0,COLUMN('Financials Cashflow Year'!$C30:$M30)),2)-2)}
</code>```

The IF function gets an array of column numbers where the row's value is above zero.

Then the 2 parameter of the Small function, will bring back the value of the cell in the second most left columns whose value isn't zero.

I.e. in your example above it would bring back the 3, similarly if you changed the parameter to 1 it would bring back the 4.

The If statement gets the column numbers for the values in the index above zero.

Note: Hit the combination Ctrl + Shfit + Enter to submit rather than just enter
Note2: I noticed you are working across a row so I think you need the ",1," before the SMALL

Body:
Basically, I have this formula in a cell to return the very first non 0 value in a row:

=INDEX('Financials Cashflow Year'!C30:M30,MATCH(TRUE,INDEX('Financials Cashflow Year'!C30:M30<>0,),0))

I would like a formula to return the value of the cell on the right of the one picked up by this very first formula.

Say we have sheet 1 first row:

0 0 0 4 3 2

Sheet 2 I would like to see with the formulas. Something scalable.

4 3 2

Body:
I think you'll want an Array Formula for this. Instead of the match use a SMALL function to get the item you want, something like this:

={INDEX('Financials Cashflow Year'!$C30:$M30,1,SMALL(IF('Financials Cashflow Year'!$C30:$M30>0,COLUMN('Financials Cashflow Year'!$C30:$M30)),2)-2)}

The IF function gets an array of column numbers where the row's value is above zero.

Then the 2 parameter of the Small function, will bring back the value of the cell in the second most left columns whose value isn't zero.

I.e. in your example above it would bring back the 3, similarly if you changed the parameter to 1 it would bring back the 4.

The If statement gets the column numbers for the values in the index above zero.

Note: Hit the combination Ctrl + Shfit + Enter to submit rather than just enter
Note2: I noticed you are working across a row so I think you need the ",1," before the SMALL