问:
Why queue worker is terribly slow while running with supervisord?
I have a beanstalkd queue implementation. I have created a benchmark tool to test the time of my queue processing. When I open my PHP worker in a terminal tab like this:

```<code>php artisan queue:work --daemon --sleep=0
</code>```

It takes around 8 seconds to finish all my jobs. If I open total 4 terminal tabs and run the above line then test again with same load, it takes around 2 seconds. Which is great.

However when I run my workers using supervisord it takes around 7-8 seconds to process the same load, with 4 workers. Even if I increase my workers to 20, I don't see any impact. Sometimes I see increasing worker has a negative impact (11 seconds). I am sure all 20 workers are running.

So what's the issue here? How can I speed up my processing? In a real server I can't keep workers running in terminal tabs.
I will highly appreciate your help :)

Here's my supervisor config:

```<code>[program:app-worker]
process_name=%(program_name)s_%(process_num)02d
command=php artisan queue:work --daemon --sleep=0
directory=/home/vagrant/Code/app
autostart=true
autorestart=true
user=vagrant
redirect_stderr=true
numprocs=4
stdout_logfile=/home/vagrant/Code/app/storage/logs/worker.log
</code>```

答:
Even though this ticket is 2 years old, I think it's worth an answer.

My guess is this would have been caused by the explicit log file you're setting and the redirection of stderr, in addition, based on your config, looks like you're running this locally, and in a non-isolated environment, meaning your host OS operations and apps would be interfering with your benchmarks.

Either way, I'm sure you've solved this long ago :D

Body:
I have a beanstalkd queue implementation. I have created a benchmark tool to test the time of my queue processing. When I open my PHP worker in a terminal tab like this:

php artisan queue:work --daemon --sleep=0

It takes around 8 seconds to finish all my jobs. If I open total 4 terminal tabs and run the above line then test again with same load, it takes around 2 seconds. Which is great.

However when I run my workers using supervisord it takes around 7-8 seconds to process the same load, with 4 workers. Even if I increase my workers to 20, I don't see any impact. Sometimes I see increasing worker has a negative impact (11 seconds). I am sure all 20 workers are running.

So what's the issue here? How can I speed up my processing? In a real server I can't keep workers running in terminal tabs.
I will highly appreciate your help :)

Here's my supervisor config:

[program:app-worker]
process_name=%(program_name)s_%(process_num)02d
command=php artisan queue:work --daemon --sleep=0
directory=/home/vagrant/Code/app
autostart=true
autorestart=true
user=vagrant
redirect_stderr=true
numprocs=4
stdout_logfile=/home/vagrant/Code/app/storage/logs/worker.log


来源: stackexchange

问:
Using component from another module in Angular 4
I have RoomsComponent in the AppModule, its route is /rooms.
Also i have a lazy-loaded module CompaniesModule with component CompaniesComponent with the route /companies.

I'm trying to build a route like /companies/{company_id}/rooms/ when RoomsComponent is reused from AppModule.

I can't do it a long RoomsComponent is not declared in the CompaniesModule, but this throws me an error, because a component cannot be declared in multiple modules.

答:
Declare the RoomsComponent in a Shared module and then import that shared module into the modules that need it. Here is an example of one of my Shared Modules:

```<code>import { NgModule }  from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { StarComponent } from './star.component';

@NgModule({
  imports: [ CommonModule],
  exports : [
    CommonModule,
    FormsModule,
    StarComponent
  ],
  declarations: [ StarComponent ],
})
export class SharedModule { }
</code>```

Notice that my StarComponent is declared AND exported here. It can then be used in any component that is declared in a module that imports this shared module.

ContentLicense: CC BY-SA 3.0

Body:
Declare the RoomsComponent in a Shared module and then import that shared module into the modules that need it. Here is an example of one of my Shared Modules:

import { NgModule }  from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { StarComponent } from './star.component';

@NgModule({
  imports: [ CommonModule],
  exports : [
    CommonModule,
    FormsModule,
    StarComponent
  ],
  declarations: [ StarComponent ],
})
export class SharedModule { }

Notice that my StarComponent is declared AND exported here. It can then be used in any component that is declared in a module that imports this shared module.


问:
How to handle nulls in ASP.NET MVC
I have user registration form. It has field Date of birth. It is not compulsory in database also not on UI. But while create when i am goiing to assign it to objects property, i have to convert it in to date format. But if i have not selected it, it will become null in the FormCollection object. like

User.DOB=Convert.ToDateTime(collection["DOB"]);

Now issue is if it collection["DOB"]is null then it throws exception. I can not assign default value here. So how can i handle this situation?

答:
You'll probably be better off using DateTime.TryParse for this.

This way you can check whether you're working with a valid date or not.

```<code>DateTime dateOfBirth;

bool isValidDateOfBirth = DateTime.TryParse(collection["DOB"], out dateOfBirth);

if(isValidDateOfBirth)
{
 // do stuff
}
else
{
 // do some other stuff
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to handle nulls in ASP.NET MVC

Body:
You'll probably be better off using DateTime.TryParse for this.

This way you can check whether you're working with a valid date or not.

DateTime dateOfBirth;

bool isValidDateOfBirth = DateTime.TryParse(collection["DOB"], out dateOfBirth);

if(isValidDateOfBirth)
{
 // do stuff
}
else
{
 // do some other stuff
}


问:
Why If isset match with syntax is not working
I want if isset $_POST["items"] text match with reject1 text and then echo. My code is not working why?

```<code>if(isset($_POST["items"])==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}
</code>```

答:
You should use an inner if for the string comparision </p>

```<code>if(isset($_POST["items"])){
  if ($_POST["items"] ==='reject1'){
    echo 'text match :)';
  } else {
   echo 'not match :(';
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want if isset $_POST["items"] text match with reject1 text and then echo. My code is not working why?

if(isset($_POST["items"])==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}

Body:
You should use an inner if for the string comparision

if(isset($_POST["items"])){
  if ($_POST["items"] ==='reject1'){
    echo 'text match :)';
  } else {
   echo 'not match :(';
  }
}


问:
How to use if else in macro(define)?
I should separate Live and Dev URL.
So, I write this code

```<code>#define _APP_MODE @"real"

#if APP_MODE == dev
#define _BASE_URL @"http://devmall.aaa.com/m/app/"
#define _URL_FROM_SAFARI @"http://devmall.safari.com"
#else
#define _BASE_URL @"http://m.aaa.com/m/app/"
#define _URL_FROM_SAFARI @"http://m.safari.com"
</code>```

but it always return dev_url

What is the best way to make sure that the URL is separated by APP_MODE?

答:
strings dont work in objC preprocessor AFAIK

... see also how to compare string in C conditional preprocessor-directives

what I'd do (and is common) is using integers

```<code>#import <Foundation/Foundation.h>

#define DEV 0
#define REAL 1

#define APP_MODE REAL

#if APP_MODE == DEV
#define BASE_URL @"http://devmall.aaa.com/m/app/"
#define URL_FROM_SAFARI @"http://devmall.safari.com"
#else
#define BASE_URL @"http://m.aaa.com/m/app/"
#define URL_FROM_SAFARI @"http://m.safari.com"
#endif

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSLog(BASE_URL);
    }
}
</code>```

note: loose all the weird underscores :)) [if you can]

Title: How to use if else in macro(define)?

Body:
I should separate Live and Dev URL.
So, I write this code

#define _APP_MODE @"real"

#if APP_MODE == dev
#define _BASE_URL @"http://devmall.aaa.com/m/app/"
#define _URL_FROM_SAFARI @"http://devmall.safari.com"
#else
#define _BASE_URL @"http://m.aaa.com/m/app/"
#define _URL_FROM_SAFARI @"http://m.safari.com"

but it always return dev_url

What is the best way to make sure that the URL is separated by APP_MODE?

Body:
strings dont work in objC preprocessor AFAIK

... see also how to compare string in C conditional preprocessor-directives

what I'd do (and is common) is using integers

#import <Foundation/Foundation.h>

#define DEV 0
#define REAL 1

#define APP_MODE REAL

#if APP_MODE == DEV
#define BASE_URL @"http://devmall.aaa.com/m/app/"
#define URL_FROM_SAFARI @"http://devmall.safari.com"
#else
#define BASE_URL @"http://m.aaa.com/m/app/"
#define URL_FROM_SAFARI @"http://m.safari.com"
#endif

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSLog(BASE_URL);
    }
}

note: loose all the weird underscores :)) [if you can]


问:
How to turn on the Security boot for MS Win10
I need to turn on this mode for test of my new drivers.

My operations:

In bios I set a support of UEFI

Enable the option Security boot.

Reboot PC

Load msinfo32 and see

BIOS is in UEFI

Security boot is in off. Why?????

My OS is MS Win 10 x64 1703,
Videocard is Gigabyte Geforce GTX 650, the utility GPU-Z shows that card supports UEFI.

Ideas?

答: Check the system summary, look for "BIOS MODE". It might be in legacy mode. (BIOS MODE)</p>


问:
Why does the delegate of an UIAlertView not work?
When I use my class AlertView for displaying an UIAlertView, I set the delegate to this class object and expect alertView:clickedButtonAt to run, but when I click abutton on the UIAlertView, it doesn't work. Why? Thanks!

```<code>import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow()
        window!.rootViewController = UIViewController()
        window!.rootViewController!.view.backgroundColor = .blue
        window!.makeKeyAndVisible()
        let a = AlertView()
        a.show()
        return true
    }

}
class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    func show(){
        var createAccountErrorAlert: UIAlertView = UIAlertView()

        createAccountErrorAlert.delegate = self

        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")

        createAccountErrorAlert.show()

    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
            print("Why delegate of alert view does not work?")
    }
}
</code>```

答:
I assume that it is related to memory management issue. createAccountErrorAlert has been declared as local variable into show() method, which leads to let the lifetime of the variable is dependent to the lifetime of executing the method.

The solution is to declare createAccountErrorAlert as an instance variable, as follows:

```<code>class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    var createAccountErrorAlert: UIAlertView = UIAlertView()

    func show(){
        createAccountErrorAlert.delegate = self

        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")

        createAccountErrorAlert.show()

    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
        print("Why delegate of alert view does not work?")
    }
}
</code>```

Remark: I would highly recommend to use UIAlertController instead of UIAlertView:

UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is
  also deprecated.) To create and manage alerts in iOS 8 and later,
  instead use  UIAlertController with a preferredStyle of alert.

Body:
When I use my class AlertView for displaying an UIAlertView, I set the delegate to this class object and expect alertView:clickedButtonAt to run, but when I click abutton on the UIAlertView, it doesn't work. Why? Thanks!

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow()
        window!.rootViewController = UIViewController()
        window!.rootViewController!.view.backgroundColor = .blue
        window!.makeKeyAndVisible()
        let a = AlertView()
        a.show()
        return true
    }

}
class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    func show(){
        var createAccountErrorAlert: UIAlertView = UIAlertView()

        createAccountErrorAlert.delegate = self

        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")

        createAccountErrorAlert.show()

    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
            print("Why delegate of alert view does not work?")
    }
}

Body:
I assume that it is related to memory management issue. createAccountErrorAlert has been declared as local variable into show() method, which leads to let the lifetime of the variable is dependent to the lifetime of executing the method.

The solution is to declare createAccountErrorAlert as an instance variable, as follows:

class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    var createAccountErrorAlert: UIAlertView = UIAlertView()

    func show(){
        createAccountErrorAlert.delegate = self

        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")

        createAccountErrorAlert.show()

    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
        print("Why delegate of alert view does not work?")
    }
}

Remark: I would highly recommend to use UIAlertController instead of UIAlertView:

UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is
  also deprecated.) To create and manage alerts in iOS 8 and later,
  instead use  UIAlertController with a preferredStyle of alert.


问:
Linking external javascript and css files into Vue component?
I created a functional chess board using javascript and CSS. I want to use it in a Vue app but I can't figure out how to link the javascript and CSS files to the component. Is there a way to load them in webpack, or what is the correct way of going about this?</p>

答:
Just follow this tutorial and configure webpack for your project.

http://todarman.com/configuring-webpack-es6-sass/

After configuring the webpack.config.js file, open terminal in your project directory, and run the command npm run dev. I will build the js and css files in their respective directories. You can link the files into your index.html file.

```<code><html>
<head>
<title>Webpack index page</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
  <h2>webpack configuration</h2>

  <script src="js/bundle.js"></script>
</body>
</html>
</code>```

Hope this helps.

Body:
Just follow this tutorial and configure webpack for your project.

http://todarman.com/configuring-webpack-es6-sass/

After configuring the webpack.config.js file, open terminal in your project directory, and run the command npm run dev. I will build the js and css files in their respective directories. You can link the files into your index.html file.

<html>
<head>
<title>Webpack index page</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
  <h2>webpack configuration</h2>

  <script src="js/bundle.js"></script>
</body>
</html>

Hope this helps.


问:
Loading SketchUp Models in SceneKit for ARKit App
I have a scene.scn file which contains a car.dae model. Here is the image:

I have the following code to load the scene.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        // Set the view's delegate
        sceneView.delegate = self

        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true

        // Create a new scene

        let scene = SCNScene(named: "art.scnassets/scene.scn")!

        // Set the scene to the view
        sceneView.scene = scene
    }
</code>```

I do not see the car being loading in the scene. Any ideas?

答: There's a flag in Xcode's scnassets inspector to set which axis is "up". In SceneKit, Y is up. IIRC SketchUp uses Z up by default. </p>

Body:
I have a scene.scn file which contains a car.dae model. Here is the image:

I have the following code to load the scene.

override func viewDidLoad() {
        super.viewDidLoad()

        // Set the view's delegate
        sceneView.delegate = self

        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true

        // Create a new scene

        let scene = SCNScene(named: "art.scnassets/scene.scn")!

        // Set the scene to the view
        sceneView.scene = scene
    }

I do not see the car being loading in the scene. Any ideas?


问:
Internet permission
I have app gradle like that

```<code>apply plugin: 'com.android.application'

android {

    compileSdkVersion 24
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.ahmed.bigovenrecipes"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {

        release {

            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.squareup.picasso:picasso:2.3.3'
    testCompile 'junit:junit:4.12'
}
</code>```

and I want to put Internet permission put I don't know in which part.

答:
If you want to use internet permission, Open Androidmanifest.xml

put this <uses-permission android:name="android.permission.INTERNET" /> at the top inside of manifest file.

Just for your info, you don't need the permission to access internet. Because, all of your internet related tasks are handed over to other applications.

If your application needs network sockets, then your application needs internet permission to use them. Simple as that.

Title: Internet permission

Body:
I have app gradle like that

apply plugin: 'com.android.application'

android {

    compileSdkVersion 24
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.ahmed.bigovenrecipes"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {

        release {

            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.squareup.picasso:picasso:2.3.3'
    testCompile 'junit:junit:4.12'
}

and I want to put Internet permission put I don't know in which part.


答:
php isset() returns true or false, so it can't match 'reject1'. If you want to match you should do:

```<code>if($_POST["items"]==='reject1') {}
</code>```

or if you want to check if the variable exists you can do:

```<code>if(isset($_POST["items"]) && $_POST["items"]==="reject1") {
echo "text match";} else { echo "not match"; }
</code>```

Title: Why If isset match with syntax is not working

Body:
php isset() returns true or false, so it can't match 'reject1'. If you want to match you should do:

if($_POST["items"]==='reject1') {}

or if you want to check if the variable exists you can do:

if(isset($_POST["items"]) && $_POST["items"]==="reject1") {
echo "text match";} else { echo "not match"; }


问:
I want to give monthly subscription to my android application
I have an application in in which initially for a month its free and after 30 days its paid.. n every month the user needs to subscribe for the services. How to do that?</p>

答:
You write code which does that..
There is nothing in the Android API that can do this for you (afaik).
You need to implement some kind of mechanism which communicates with a service and askes if the subscription is still valid or not.</p>


答:
isset returns TRUE if a variable is set, or FALSE if it isn't. Neither TRUE nor FALSE are equal to 'reject1', so the if will never be entered.

You could perform a two phase check - first check if the key is set, and then evaluate its value:

```<code>if(array_key_exists('items', $_POST) && $_POST['items'] === 'reject1') {
   echo 'text match :)';
} else {
   echo 'not match :(';
}
</code>```

Body:
isset returns TRUE if a variable is set, or FALSE if it isn't. Neither TRUE nor FALSE are equal to 'reject1', so the if will never be entered.

You could perform a two phase check - first check if the key is set, and then evaluate its value:

if(array_key_exists('items', $_POST) && $_POST['items'] === 'reject1') {
   echo 'text match :)';
} else {
   echo 'not match :(';
}


问:
Git convert between tabs and spaces but only sometimes
First, I'm a newbie to git.  Like, I could barely tell a cache from an index if it hit me in the staging area.  Or something like that.  With that out of the way, my problem is this:

Suppose I want to work on a project whose coding style mandates spaces for indentation, but I like tabs.  It seems that I can use the clean and smudge features, but there's a catch.  The coding style is not followed consistently, and there some files that mix tabs and spaces on the same line.  Thus a naïve approach would result in me making a one line change, but accidentally creating a massive commit which brings the project into full compliance with its own standards.  This would be great except that the diffs would be less useful so I end up with new enemies.

So the question is: is there a way to get this magic working in such a way that if I don't touch a file, it stays out of the picture?  (I'm willing to take full responsibility for the whitespace of files I do touch, even if I change only a single character.)

EDIT: Okay, I just in-accepted the answer I accepted yesterday.  I'm pretty sure this is very rude of me.  My excuse is that I only got around to testing it today.  Since apparently two people misunderstood me already, let me be clear on what I actually did, so maybe someone can tell me if I'm being confused and/or confusing.

```<code>$ ls -a
.  ..  t.txt
$ hd t.txt # file contains 3 bytes: a tab, a capital A, and a newline
00000000  09 41 0a                                          |.A.|
00000003
$ git init
Initialized empty Git repository in /home/marvy/test/.git/
$ git config --local git config --local user.name me
$ git config --local user.email me@example.com
$ git add t.txt
$ git commit
[master (root-commit) 959bf99] testing cleverness of git status
 1 file changed, 1 insertion(+)
 create mode 100644 t.txt
$ echo '*.txt filter=tabspace' > .git/info/attributes
$ cat .git/info/attributes
*.txt filter=tabspace
$ git config --local filter.tabspace.smudge unexpand
$ git config --local filter.tabspace.clean expand
$ rm t.txt
$ git checkout t.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   t.txt

no changes added to commit (use "git add" and/or "git commit -a")
$ git help --stackoverflow
</code>```

As we can see here, git status reports that t.txt is modified, even though I just checked it out.  If you run git diff, it will claim I want to convert tabs to spaces.  Am I doing something wrong?

答:
The best way to do it is to use script with smudge-clean.

smudge-clean

Smudge/Clean are filters which runs wherever a file is passed through the stage area and those filters will modify the file by executing the given script.

Using smudge and clean will touch only the files you pass through the staging area.

For example (unix sample):
If you are unfamiliar with uexpand/unuexpand read about it
here

~/.gitconfig

```<code># filters to convert between tabs to spaces
[filter "tabspace"]
    smudge = unexpand --tabs=2 --first-only
    clean = expand --tabs=2 --initial
</code>```

~/.gitattributes

```<code>*.txt  filter=tabspace
</code>```

Now any time you add/checkout files they will be converted based upon your configuration.

You can also take a look on this project in github

Body:
First, I'm a newbie to git.  Like, I could barely tell a cache from an index if it hit me in the staging area.  Or something like that.  With that out of the way, my problem is this:

Suppose I want to work on a project whose coding style mandates spaces for indentation, but I like tabs.  It seems that I can use the clean and smudge features, but there's a catch.  The coding style is not followed consistently, and there some files that mix tabs and spaces on the same line.  Thus a naïve approach would result in me making a one line change, but accidentally creating a massive commit which brings the project into full compliance with its own standards.  This would be great except that the diffs would be less useful so I end up with new enemies.

So the question is: is there a way to get this magic working in such a way that if I don't touch a file, it stays out of the picture?  (I'm willing to take full responsibility for the whitespace of files I do touch, even if I change only a single character.)

EDIT: Okay, I just in-accepted the answer I accepted yesterday.  I'm pretty sure this is very rude of me.  My excuse is that I only got around to testing it today.  Since apparently two people misunderstood me already, let me be clear on what I actually did, so maybe someone can tell me if I'm being confused and/or confusing.

$ ls -a
.  ..  t.txt
$ hd t.txt # file contains 3 bytes: a tab, a capital A, and a newline
00000000  09 41 0a                                          |.A.|
00000003
$ git init
Initialized empty Git repository in /home/marvy/test/.git/
$ git config --local git config --local user.name me
$ git config --local user.email me@example.com
$ git add t.txt
$ git commit
[master (root-commit) 959bf99] testing cleverness of git status
 1 file changed, 1 insertion(+)
 create mode 100644 t.txt
$ echo '*.txt filter=tabspace' > .git/info/attributes
$ cat .git/info/attributes
*.txt filter=tabspace
$ git config --local filter.tabspace.smudge unexpand
$ git config --local filter.tabspace.clean expand
$ rm t.txt
$ git checkout t.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   t.txt

no changes added to commit (use "git add" and/or "git commit -a")
$ git help --stackoverflow

As we can see here, git status reports that t.txt is modified, even though I just checked it out.  If you run git diff, it will claim I want to convert tabs to spaces.  Am I doing something wrong?

Body:
The best way to do it is to use script with smudge-clean.

smudge-clean

Smudge/Clean are filters which runs wherever a file is passed through the stage area and those filters will modify the file by executing the given script.

Using smudge and clean will touch only the files you pass through the staging area.

For example (unix sample):
If you are unfamiliar with uexpand/unuexpand read about it
here

~/.gitconfig

# filters to convert between tabs to spaces
[filter "tabspace"]
    smudge = unexpand --tabs=2 --first-only
    clean = expand --tabs=2 --initial

~/.gitattributes

*.txt  filter=tabspace

Now any time you add/checkout files they will be converted based upon your configuration.

You can also take a look on this project in github


问:
Filter matrix by count of odd numbers per row
Having a matrix A like:

```<code>       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]   11   14   17   21   23   25
  [2,]   12   15   18   24   26   28
  [3,]   13   15   19   21   25   29
</code>```

I want to filter all rows that have per row count of odd numbers < 2

So the matrix (result) should contain only row 2 of matrix A.

Body:
Having a matrix A like:

       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]   11   14   17   21   23   25
  [2,]   12   15   18   24   26   28
  [3,]   13   15   19   21   25   29

I want to filter all rows that have per row count of odd numbers < 2

So the matrix (result) should contain only row 2 of matrix A.

Body:
We can loop through the rows with apply specifying MARGIN =1, create a logical vector to subset the matrix 'm1'

m1[apply(m1, 1, FUN = function(x) sum(x %% 2) < 2),, drop = FALSE]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   12   15   18   24   26   28

Or with rowSums

m1[rowSums((m1 %%2)) <2, , drop = FALSE]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   12   15   18   24   26   28

EDIT: Based on @lmo's comments

data

m1 <- structure(c(11, 12, 13, 14, 15, 15, 17, 18, 19, 21, 24, 21, 23,
     26, 25, 25, 28, 29), .Dim = c(3L, 6L))


问:
Mosquitto certificate SSL23_GET_CLIENT_HELLO:unknown protocol
I'm been desperately trying to get my MQTT clients to connect to a MQTT broker which is set up with a certificate from a CA. (Letsencrypt: https://pypi.python.org/pypi/letsencrypt/0.4.1) I'm using the same certificate for my https site, and that seems to work fine. I'm not sure if that holds any connection, though.

I've used this guide to set-up the certificates for the broker (http://mosquitto.org/2015/12/using-lets-encrypt-certificates-with-mosquitto/)

The broker, v1.4.8 seems to work fine with the following config:

```<code>cafile chain.pem
certfile cert.pem
keyfile privkey.pem

[ ok ] mosquitto is running.
</code>```

Clients attempting to connect to this broker with debug message yields:

```<code>Client mosqsub/42074-titan sending CONNECT
</code>```

On my broker's side log I recieve this error message:

```<code>1457358950: New connection from NOT.TELLING.YOU.OBVIOUSLY on port 8883.
1457358950: OpenSSL Error: error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol
1457358950: Socket error on client <unknown>, disconnecting.
</code>```

I've searched high and wide for a solution to this, sadly there is little to nothing out there.

Any help would be greatly appreciated! Thank you!

答:
I ran into this problem with the paho.mqtt.c MQTT client library when I was using tcp as a protocol instead of ssl.

So I had to use

```<code>ssl://1.2.3.4:56789
</code>```

instead of

```<code>tcp://1.2.3.4:56789
</code>```

Also when using paho.mqtt.c make sure you are linking against the libs with SSL support and that the libs with SSL support are actually built with SSL support! There used to be a bug in a CMake file in which a define was missing (OPENSSL) and thus the SSL libraries did not offer SSL support...

Body:
I'm been desperately trying to get my MQTT clients to connect to a MQTT broker which is set up with a certificate from a CA. (Letsencrypt: https://pypi.python.org/pypi/letsencrypt/0.4.1) I'm using the same certificate for my https site, and that seems to work fine. I'm not sure if that holds any connection, though.

I've used this guide to set-up the certificates for the broker (http://mosquitto.org/2015/12/using-lets-encrypt-certificates-with-mosquitto/)

The broker, v1.4.8 seems to work fine with the following config:

cafile chain.pem
certfile cert.pem
keyfile privkey.pem

[ ok ] mosquitto is running.

Clients attempting to connect to this broker with debug message yields:

Client mosqsub/42074-titan sending CONNECT

On my broker's side log I recieve this error message:

1457358950: New connection from NOT.TELLING.YOU.OBVIOUSLY on port 8883.
1457358950: OpenSSL Error: error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol
1457358950: Socket error on client <unknown>, disconnecting.

I've searched high and wide for a solution to this, sadly there is little to nothing out there.

Any help would be greatly appreciated! Thank you!

Body:
I ran into this problem with the paho.mqtt.c MQTT client library when I was using tcp as a protocol instead of ssl.

So I had to use

ssl://1.2.3.4:56789

instead of

tcp://1.2.3.4:56789

Also when using paho.mqtt.c make sure you are linking against the libs with SSL support and that the libs with SSL support are actually built with SSL support! There used to be a bug in a CMake file in which a define was missing (OPENSSL) and thus the SSL libraries did not offer SSL support...


问:
Which characters are valid in CSS class names/selectors?
What characters/symbols are allowed within the CSS class selectors?

I know that the following characters are invalid, but what characters are valid?

~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
```

答:
Read the W3C spec. (this is CSS 2.1; find the appropriate version for your assumption of browsers)

relevant paragraph:

In CSS, identifiers  (including
element names, classes, and IDs in
selectors) can contain only the
characters [a-z0-9] and ISO 10646
characters U+00A1 and higher, plus the
hyphen (-) and the underscore (_);
they cannot start with a digit, or a
hyphen followed by a digit.
Identifiers can also contain escaped
characters and any ISO 10646 character
as a numeric code (see next item). For
instance, the identifier "B&W?" may be
written as "B&W?" or "B\26 W\3F".

As @mipadi points out in Kenan Banks's answer, there's this caveat, also in the same webpage:

In CSS, identifiers may begin with '-'
(dash) or '_' (underscore). Keywords
and property names beginning with '-'
or '_' are reserved for
vendor-specific extensions. Such
vendor-specific extensions should have
one of the following formats:

'-' + vendor identifier + '-' + meaningful name
'_' + vendor identifier + '-' + meaningful name
```
<p>Example(s):</p>
<p>For example, if XYZ organization added
a property to describe the color of
the border on the East side of the
display, they might call it
-xyz-border-east-color.</p>
<p>Other known examples:</p>
<pre class="lang-none prettyprint-override"><code>-moz-box-sizing
-moz-border-radius
-wap-accesskey
</code>```

An initial dash or underscore is
guaranteed never to be used in a
property or keyword by any current or
future level of CSS. Thus typical CSS
implementations may not recognize such
properties and may ignore them
according to the rules for handling
parsing errors. However, because the
initial dash or underscore is part of
the grammar, CSS 2.1 implementers
should always be able to use a
CSS-conforming parser, whether or not
they support any vendor-specific
extensions.

Authors should avoid vendor-specific
extensions

OwnerDisplayName: Darryl Hein

Body:
Read the W3C spec. (this is CSS 2.1; find the appropriate version for your assumption of browsers)

relevant paragraph:

In CSS, identifiers  (including
element names, classes, and IDs in
selectors) can contain only the
characters [a-z0-9] and ISO 10646
characters U+00A1 and higher, plus the
hyphen (-) and the underscore (_);
they cannot start with a digit, or a
hyphen followed by a digit.
Identifiers can also contain escaped
characters and any ISO 10646 character
as a numeric code (see next item). For
instance, the identifier "B&W?" may be
written as "B&W?" or "B\26 W\3F".

As @mipadi points out in Kenan Banks's answer, there's this caveat, also in the same webpage:

In CSS, identifiers may begin with '-'
(dash) or '_' (underscore). Keywords
and property names beginning with '-'
or '_' are reserved for
vendor-specific extensions. Such
vendor-specific extensions should have
one of the following formats:

'-' + vendor identifier + '-' + meaningful name
'_' + vendor identifier + '-' + meaningful name

Example(s):

For example, if XYZ organization added
a property to describe the color of
the border on the East side of the
display, they might call it
-xyz-border-east-color.

Other known examples:

-moz-box-sizing
-moz-border-radius
-wap-accesskey

An initial dash or underscore is
guaranteed never to be used in a
property or keyword by any current or
future level of CSS. Thus typical CSS
implementations may not recognize such
properties and may ignore them
according to the rules for handling
parsing errors. However, because the
initial dash or underscore is part of
the grammar, CSS 2.1 implementers
should always be able to use a
CSS-conforming parser, whether or not
they support any vendor-specific
extensions.

Authors should avoid vendor-specific
extensions

OwnerDisplayName: Jason S

LastEditorDisplayName: Jason S


问:
I'm trying to get a count of records from a related entity that match a criteria
I have an entity matches which has a related to-many entity sets. I want to get a count of how many sets have the attribute 'set_finished' set to YES for a particular match. I'm trying to do this with:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY set_finished == YES"];
 NSUInteger numberOfFinishedSets = [[[match valueForKeyPath:@"sets"] filteredArrayUsingPredicate:predicate ] count];

The second line crashes with this error, which I don't understand. Can anyone shed some light on this for me? Thanks.

2010-12-20 13:17:13.814
  DartScorer[2154:207] * Terminating
  app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_NSFaultingMutableSet
  filteredArrayUsingPredicate:]:
  unrecognized selector sent to instance
  0x617fb20'

答:
Try wrapping the string YES in single quotes  "... 'YES' "  </p>

<p>(assuming the field contains the strings 'YES' and 'NO' and not 1 | 0)</p>

Body:
Try wrapping the string YES in single quotes  "... 'YES' "

(assuming the field contains the strings 'YES' and 'NO' and not 1 | 0)


问:
Angular Component doesn't render
Here's my code:

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['../assets/css/app.component.css']
})
export class MainVisualComponent {
  main_visual_img:string = "";
  main_visual_desc:string = "";
  main_visual_title:string = "";
  constructor(main_visual_img:string, main_visual_desc:string, main_visual_title:string){
    this.main_visual_img = main_visual_img;
    this.main_visual_desc = main_visual_desc;
    this.main_visual_title = main_visual_title;
  }
}
</code>```

HTML:

```<code><section style="text-align:center">
  <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
    <visual-item></visual-item>
    <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
    </a>
    <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
    </a>
  </div>
</section>
</code>```

答:
the selector of the component is app-root.

just replace the <visual-item></visual-item> with <app-root></app-root>.

so your code will be:

```<code><section style="text-align:center">
  <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
    <app-root></app-root>
    <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
    </a>
    <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
    </a>
  </div>
</section>
</code>```

Title: Angular Component doesn't render

Body:
Here's my code:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['../assets/css/app.component.css']
})
export class MainVisualComponent {
  main_visual_img:string = "";
  main_visual_desc:string = "";
  main_visual_title:string = "";
  constructor(main_visual_img:string, main_visual_desc:string, main_visual_title:string){
    this.main_visual_img = main_visual_img;
    this.main_visual_desc = main_visual_desc;
    this.main_visual_title = main_visual_title;
  }
}

HTML:

    <visual-item></visual-item>

Body:
the selector of the component is app-root.

just replace the <visual-item></visual-item> with <app-root></app-root>.

so your code will be:

<section style="text-align:center">
  <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
    <app-root></app-root>
    <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
    </a>
    <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
    </a>
  </div>
</section>


答:
or do a one liner:

```<code>echo (isset($_POST["items"]) && $_POST["items"]==='reject1')? 'text match :)' : 'not match :(';
</code>```

Refs: http://php.net/manual/ro/function.isset.php

Returns TRUE if var exists and has value other than NULL. FALSE otherwise.

Body:
I want if isset $_POST["items"] text match with reject1 text and then echo. My code is not working why?

if(isset($_POST["items"])==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}

Body:
or do a one liner:

echo (isset($_POST["items"]) && $_POST["items"]==='reject1')? 'text match :)' : 'not match :(';

Refs: http://php.net/manual/ro/function.isset.php

Returns TRUE if var exists and has value other than NULL. FALSE otherwise.


问:
Connecting to local MySQL server with RMySQL
I'm successfully able to connect to a local MySQL server with the following R script:

```<code>library(RMySQL)

drv <- dbDriver("MySQL")
con <- dbConnect(drv, user="root", pass="myrootpass")
rs <- dbSendQuery(con, statement = "SHOW DATABASES;")
fetch(rs)
</code>```

However, I don't want my password to be in the script since it will be saved in a file! I'm using Ubuntu 13.10, MySQL 5.5.35, MySQL Workbench 6.0 and R 3.0.1.

At work, I use Windows, and I'm able to connect to a SQL Server to which I have access without a password with the following lines:

```<code>library(RODBC)
dbhandle<-odbcDriverConnect('driver={SQL Server};server=SomeServer;database=SomeDatabase;trusted_connection=true')
</code>```

In this case, it seems as if it is sufficient that I have logged in as an employee who has access to the server.

I would like to accomplish something similar to this - how can I connect to a local MySQL Server with my Ubuntu computer?

答:
First, create the following .csv and name it "database_credentials.csv"

```<code>user,password,dbname,host
your_user_name_here,your_password_here,your_database_address_aka_database_name_here,your_hostname_here
</code>```

If this is a local connection, then in the host field in the .csv file above enter "localhost"

Then do this

```<code># R Script for
# CONNECTING TO DATABASE
  library(RMySQL)
  dbCredentialsFile <- read.csv("database_credentials.csv", stringsAsFactors = FALSE, header = TRUE)
  con <- dbConnect(MySQL(),
  user = dbCredentialsFile$user[1],
  password = dbCredentialsFile$password[1],
  host = dbCredentialsFile$host[1],
  dbname = dbCredentialsFile$dbname[1])
  rm(dbCredentialsFile)
  gc()

# FUNCTION FOR QUERYING DATABASE
  query <- function(...) dbGetQuery(con, ...)

# EXAMPLE FOR QUERYING DATABASE
  testDF <- query("SELECT * FROM name_of_table_in_database_to_retrive")
</code>```

Body:
I'm successfully able to connect to a local MySQL server with the following R script:

library(RMySQL)

drv <- dbDriver("MySQL")
con <- dbConnect(drv, user="root", pass="myrootpass")
rs <- dbSendQuery(con, statement = "SHOW DATABASES;")
fetch(rs)

However, I don't want my password to be in the script since it will be saved in a file! I'm using Ubuntu 13.10, MySQL 5.5.35, MySQL Workbench 6.0 and R 3.0.1.

At work, I use Windows, and I'm able to connect to a SQL Server to which I have access without a password with the following lines:

library(RODBC)
dbhandle<-odbcDriverConnect('driver={SQL Server};server=SomeServer;database=SomeDatabase;trusted_connection=true')

In this case, it seems as if it is sufficient that I have logged in as an employee who has access to the server.

I would like to accomplish something similar to this - how can I connect to a local MySQL Server with my Ubuntu computer?

Body:
First, create the following .csv and name it "database_credentials.csv"

user,password,dbname,host
your_user_name_here,your_password_here,your_database_address_aka_database_name_here,your_hostname_here

If this is a local connection, then in the host field in the .csv file above enter "localhost"

Then do this

# R Script for
# CONNECTING TO DATABASE
  library(RMySQL)
  dbCredentialsFile <- read.csv("database_credentials.csv", stringsAsFactors = FALSE, header = TRUE)
  con <- dbConnect(MySQL(),
  user = dbCredentialsFile$user[1],
  password = dbCredentialsFile$password[1],
  host = dbCredentialsFile$host[1],
  dbname = dbCredentialsFile$dbname[1])
  rm(dbCredentialsFile)
  gc()

# FUNCTION FOR QUERYING DATABASE
  query <- function(...) dbGetQuery(con, ...)

# EXAMPLE FOR QUERYING DATABASE
  testDF <- query("SELECT * FROM name_of_table_in_database_to_retrive")


问:
Capturing audio in a non exclusive mode with JavaSound API
I wrote some code to capture sound with JavaSound API.

It starts like this:

```<code>        DataLine.Info info = new DataLine.Info(TargetDataLine.class,
            audioFormat);

        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open();
</code>```

However, once getLine() gets called, other applications cannot start capturing sound any-more.

The other way round, getLine() will fail if some other sound-capturing-applications are running.

Generally I can use the sound recorder during a Skype session, that means that capturing sound doesn't have to be exclusive.

I would like my application to be non exclusive as well. I don't want to limit the user on what he can do with it.

In the JavaSound API tutorial it reads:

Commonly, only one input port can be open at a time, but an audio-input mixer that mixes audio from multiple ports is also possible.

Does it mean that JavaSound can only capture in an exclusive mode or that JavaSound itself can handle only one input port?

If the former is true, does any-one know how to work around this issue in Java?

答:
I think, this is a linux/ubuntu related problem. I found a few site on the web that mention and/or solve this issue, here is two of them:

http://ubuntuforums.org/archive/index.php/t-342473.html

https://bugs.launchpad.net/ubuntu/+source/sun-java6/+bug/404313

Body:
I wrote some code to capture sound with JavaSound API.

It starts like this:

        DataLine.Info info = new DataLine.Info(TargetDataLine.class,
            audioFormat);

        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open();

However, once getLine() gets called, other applications cannot start capturing sound any-more.

The other way round, getLine() will fail if some other sound-capturing-applications are running.

Generally I can use the sound recorder during a Skype session, that means that capturing sound doesn't have to be exclusive.

I would like my application to be non exclusive as well. I don't want to limit the user on what he can do with it.

In the JavaSound API tutorial it reads:

Commonly, only one input port can be open at a time, but an audio-input mixer that mixes audio from multiple ports is also possible.

Does it mean that JavaSound can only capture in an exclusive mode or that JavaSound itself can handle only one input port?

If the former is true, does any-one know how to work around this issue in Java?


问:
Language code detection of spoken language in Google Speech API
Is there an option to automatically detect the spoken language using Google Cloud Platform Machine Learning's Speech API?

https://cloud.google.com/speech/docs/languages indicates the list of the languages supported. However, the user needs to manually set this parameter to perform speech-to-text. I'd like to do this automatically.

答: No, I believe you (at least currently) have to specify the input language. (Unlike the Translation API where you can let it auto-detect, for example.)


问:
Is there some way to add the Node JS Tools for Visual Studio (NTVS) test adapter to a VSTS hosted agent?
Is there some way to add the Node JS Tools for Visual Studio (NTVS) test adapter to a VSTS hosted agent?

The Visual Studio docs on hosted agent mention "Node.js Tools 1.0 for Visual Studio 2015" in the list for the "Hosted" agent, but the "Hosted VS2017" has no mention of any Node.js Tools

So how can you use the test adapter?

答:
refer to these steps to run test on Hosted VS 2017 agent.

Modify project file (njsproj)

:

```<code><!--<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>-->
    <VSToolsPath>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0</VSToolsPath>
</code>```

Copy NodeJsTools folder in C:\Program Files (x86)\Microsoft Visual Studio\2017\[Community, professional or enterprise]\Common7\IDE\Extensions\Microsoft to your ntvs folder

Add these files to source control and check in changes

Queue build with Hosted VS 2017 agent.

Build definition steps:

NPM install (Working folder: $(Build.SourcesDirectory)\NodejsConsoleApp1)

Visual Studio Test task (Test assemblies: NodejsConsoleApp1\NodejsConsoleApp1.njsproj; Search folder: $(System.DefaultWorkingDirectory); Test platform version: Visual Studio 2017; Path to Custom test adapters: NodejsConsoleApp1\ntvs

Body:
refer to these steps to run test on Hosted VS 2017 agent.

Modify project file (njsproj)

:

<!--<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>-->
    <VSToolsPath>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0</VSToolsPath>

Copy NodeJsTools folder in C:\Program Files (x86)\Microsoft Visual Studio\2017\[Community, professional or enterprise]\Common7\IDE\Extensions\Microsoft to your ntvs folder

Add these files to source control and check in changes

Queue build with Hosted VS 2017 agent.

Build definition steps:

NPM install (Working folder: $(Build.SourcesDirectory)\NodejsConsoleApp1)

Visual Studio Test task (Test assemblies: NodejsConsoleApp1\NodejsConsoleApp1.njsproj; Search folder: $(System.DefaultWorkingDirectory); Test platform version: Visual Studio 2017; Path to Custom test adapters: NodejsConsoleApp1\ntvs


问:
Sitemap.xml or Sitemap.html
I am working on one web application. I want to submit site to web crawlers using a site-map file.

There are many ways to do so

Use sitemap.xml

Use sitemap.html

Use urllist.txt

Use compressed sitemap files

All we need to do is add one of these files in root directory of applications.

My question is which option out of these is good to use ?

答:
I'd go with an xml sitemap as defined here http://sitemaps.org/

Html sitemaps are more geared towards user navigation and urllist.txt seems to be an old method of providing links to yahoo.

XML sitemaps in the format defined on the above site were created by Google, Yahoo! and Microsoft and are recognised by all three.

The others wont do any harm but I believe the biggest benefit will come from an xml sitemap.

As for compression, that's up to you, if you want to conserve your bandwidth then gzip it however keep in mind it must be no larger than 10mb when uncompressed.

Title: Sitemap.xml or Sitemap.html


问:
Ruby split does not working on string?
I'm trying to split a string to capitalize each word.

Code:

```<code>def titleize(a)
little_words = %w(a an the)
#a = %w(a quick brown fox jumps) --> works if an array is specifically used.
a.split(" ")
a.each do |i|
    if !little_words.include? "#{i}"
    i.capitalize!
    end
end
g = a.join(" ")
return g
end

print titleize("a quick brown fox jump")
</code>```

Error:

```<code>  `titleize': undefined method `each' for "a quick brown fox jump":String (NoMethodError)
</code>```

However, I am running into this error. From what I understand, the error is saying that my variable 'a' is a string which does not contain the method 'each'. I have already applied 'split(" ")' to convert the string to an array. Why does it not work?

答:
Because you are ignoring what the method returns

```<code>a = a.split(" ")
</code>```

And " " is the default for split so you can write simply

```<code>a = a.split
</code>```

Title: Ruby split does not working on string?

Body:
I'm trying to split a string to capitalize each word.

Code:

def titleize(a)
little_words = %w(a an the)
#a = %w(a quick brown fox jumps) --> works if an array is specifically used.
a.split(" ")
a.each do |i|
    if !little_words.include? "#{i}"
    i.capitalize!
    end
end
g = a.join(" ")
return g
end

print titleize("a quick brown fox jump")

Error:

  `titleize': undefined method `each' for "a quick brown fox jump":String (NoMethodError)

However, I am running into this error. From what I understand, the error is saying that my variable 'a' is a string which does not contain the method 'each'. I have already applied 'split(" ")' to convert the string to an array. Why does it not work?

Body:
Because you are ignoring what the method returns

a = a.split(" ")

And " " is the default for split so you can write simply

a = a.split


问:
Background Image not displaying on iPhone
How do I make the background image display on iPhone as it displays on Android?

HTML

```<code><div class="bgimg-1">
    <div class="hometoptext ">
        <h1 class="text-center">
            Africa's First Online Business Lender
        </h1>
        <div>
            <h3 class="thin">Grow faster with South Africa's most innovative online funder</h3>
        </div>
        <div class="text-center">
            <button class="btn btn-primary" (click)="applyNow()">APPLY NOW</button>
        </div>
    </div>
    <div class="bottom-arrow text-center">

    </div>
</div>
</code>```

Background Image not  displaying on iPhone

CSS

```<code>.bgimg-1 {
    background-image: url("img/main_pic2.png");
    color: white;
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-color: #999;
    position:relative;
    width:100%;
    min-height: 100vh;
    top: 0;
}
</code>```

Image on Android:

Image on iPhone:

答:
iOS Safari has buggy behavior with background-size: cover; +
background-attachment: fixed;

Safari (OS X and iOS) and Chrome do not support background-size: 100%
px; in combination with SVG images, it leaves them at the
original size while other browsers stretch the vector image correctly
while leaving the height at the specified number of pixels.

iOS Safari has buggy behavior with background-size: cover; on a
page's body.

macOS Safari 10 is having frame rate issue with background-size.

Android 4.3 browser and below are reported to not support percentages
in background-size

Ref : Link

Body:
How do I make the background image display on iPhone as it displays on Android?

HTML

            Africa's First Online Business Lender

Grow faster with South Africa's most innovative online funder

            <button class="btn btn-primary" (click)="applyNow()">APPLY NOW</button>

Background Image not  displaying on iPhone

CSS

.bgimg-1 {
    background-image: url("img/main_pic2.png");
    color: white;
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-color: #999;
    position:relative;
    width:100%;
    min-height: 100vh;
    top: 0;
}

Image on Android:

Image on iPhone:


问:
Python Basemap does not show the proper plot
I need to plot some data over a map of the city of Amsterdam, but I can't get Basemap to display the proper plot.  With the code below, all I get is an empty plot and I don't know how to get the map to display.

My code is below:

```<code>from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
%matplotlib inline

#Create a map around Amsterdam
#http://www.latlong.net/
#Upper Right Corner 52.4268763,5.2415393
#Lower Left Corner 52.3303609,4.6992733

#fig, ax = plt.subplots()
m = Basemap(projection='merc',
        llcrnrlat=52.3303609,urcrnrlat=52.4268763,
        llcrnrlon=4.6992733, urcrnrlon=5.2415393,
        resolution='c')

m.fillcontinents()
m.drawcoastlines()
m.drawmapboundary()
plt.show()
</code>```

What am I missing in my code?

答:
The resolution you chose for the basemap, resolution='c' is "coarse", meaning that detailed coastlines will not be shown. You can use any of the other possible resolutions

```<code>l (low), i (intermediate), h (high), f (full)
</code>```

Example:

resolution="l":

resolution="i":

resolution="h":

resolution="f":

Code to reproduce:

```<code>from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

m = Basemap(projection='merc',
        llcrnrlat=52.3303609,urcrnrlat=52.4268763,
        llcrnrlon=4.6992733, urcrnrlon=5.2415393,
        resolution="f")

m.fillcontinents(color='bisque')
m.drawcoastlines()
m.drawmapboundary(fill_color='lightcyan')

plt.show()
</code>```

Body:
I need to plot some data over a map of the city of Amsterdam, but I can't get Basemap to display the proper plot.  With the code below, all I get is an empty plot and I don't know how to get the map to display.

My code is below:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
%matplotlib inline

#Create a map around Amsterdam
#http://www.latlong.net/
#Upper Right Corner 52.4268763,5.2415393
#Lower Left Corner 52.3303609,4.6992733

#fig, ax = plt.subplots()
m = Basemap(projection='merc',
        llcrnrlat=52.3303609,urcrnrlat=52.4268763,
        llcrnrlon=4.6992733, urcrnrlon=5.2415393,
        resolution='c')

m.fillcontinents()
m.drawcoastlines()
m.drawmapboundary()
plt.show()

What am I missing in my code?

Body:
The resolution you chose for the basemap, resolution='c' is "coarse", meaning that detailed coastlines will not be shown. You can use any of the other possible resolutions

l (low), i (intermediate), h (high), f (full)

Example:

resolution="l":

resolution="i":

resolution="h":

resolution="f":

Code to reproduce:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

m = Basemap(projection='merc',
        llcrnrlat=52.3303609,urcrnrlat=52.4268763,
        llcrnrlon=4.6992733, urcrnrlon=5.2415393,
        resolution="f")

m.fillcontinents(color='bisque')
m.drawcoastlines()
m.drawmapboundary(fill_color='lightcyan')

plt.show()


问:
How to check more gently that some part of the code running 4 times a day
I have the script running by crontab and I want some part of the code being executed 4 times a day.

I have the snippet of code which

```<code>from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time == time(10,00) or now_time == time(16,00) or now_time == time(22,00) or now_time == time (4,00):
    func()
</code>```

The minus of this solution is that this part of the code may be executed on 10.01, 10.02 and will be skipped this way.

Is there more gentle and shorter way to write down this part of code?

Thanks!

答:
What you could do is modify your script to accept an (extra) argument that will trigger the execution of that specific part of the code. You can then modify the crontab listing so that at the required times the script is called with that extra argument.

So, if you want to run the script every whole and half hour, and do the extra stuff at 4, 10, 16, and 22 o'clock, you can put the following three lines in your crontab file:

```<code>30 * * * * <script> # Thirty minutes after each hour
0 1-3,5-9,11-15,17-21,23 * * * <script> # Every whole hour, except the four designated hours
0 4,10,16,22 * * * <script with extra argument> # Script with extra argument at designated hours.
</code>```

In this way, the script runs every 30 minutes, but at the designated hours the script runs with the extra argument.

Body:
I have the script running by crontab and I want some part of the code being executed 4 times a day.

I have the snippet of code which

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time == time(10,00) or now_time == time(16,00) or now_time == time(22,00) or now_time == time (4,00):
    func()

The minus of this solution is that this part of the code may be executed on 10.01, 10.02 and will be skipped this way.

Is there more gentle and shorter way to write down this part of code?

Thanks!

Body:
What you could do is modify your script to accept an (extra) argument that will trigger the execution of that specific part of the code. You can then modify the crontab listing so that at the required times the script is called with that extra argument.

So, if you want to run the script every whole and half hour, and do the extra stuff at 4, 10, 16, and 22 o'clock, you can put the following three lines in your crontab file:

30 * * * * <script> # Thirty minutes after each hour
0 1-3,5-9,11-15,17-21,23 * * * <script> # Every whole hour, except the four designated hours
0 4,10,16,22 * * * <script with extra argument> # Script with extra argument at designated hours.

In this way, the script runs every 30 minutes, but at the designated hours the script runs with the extra argument.


问:
How to get people interests from Google +?
I am trying to get user profile information such as people in circles, interest, feeds, plusoners and reshares.

I tried during a lot of time and it was imposible to me getting interest and people in circles.

In Google Domains API there is a way to get all people from circles but even with OAuth shows this error:

```<code>"error": {
    "errors": [
        {
            "domain": "global",
            "reason": "forbidden",
            "message": "Forbidden"
        }
    ],
        "code": 403,
            "message": "Forbidden"
}
</code>```

I think that the poblem is that Google only provides this information if you are a G Suite user, not a Google 'normal' user.

About the interest, I have no idea.

Anyone knows how to get this info (interests and people in circles) from Google Plus API?

Sorry for my english :(

答:
Google domains api is not the Google+ api.

The Domains API is for use with a GSuite account. Google+ API.

```<code>"error": {
    "errors": [
        {
            "domain": "global",
            "reason": "forbidden",
            "message": "Forbidden"
        }
    ],
        "code": 403,
            "message": "Forbidden"
}
</code>```

Means that you are trying to use the domains api but do not have access to a gsuite account.

You can try and use the people api which will give you a list of who the user has emailed and who they have in their contacts.  I dont think it has anything to do with who they have in their circles to my knowledge there is no way to retrieve that information.

Body:
I am trying to get user profile information such as people in circles, interest, feeds, plusoners and reshares.

I tried during a lot of time and it was imposible to me getting interest and people in circles.

In Google Domains API there is a way to get all people from circles but even with OAuth shows this error:

"error": {
    "errors": [
        {
            "domain": "global",
            "reason": "forbidden",
            "message": "Forbidden"
        }
    ],
        "code": 403,
            "message": "Forbidden"
}

I think that the poblem is that Google only provides this information if you are a G Suite user, not a Google 'normal' user.

About the interest, I have no idea.

Anyone knows how to get this info (interests and people in circles) from Google Plus API?

Sorry for my english :(

Body:
Google domains api is not the Google+ api.

The Domains API is for use with a GSuite account. Google+ API.

"error": {
    "errors": [
        {
            "domain": "global",
            "reason": "forbidden",
            "message": "Forbidden"
        }
    ],
        "code": 403,
            "message": "Forbidden"
}

Means that you are trying to use the domains api but do not have access to a gsuite account.

You can try and use the people api which will give you a list of who the user has emailed and who they have in their contacts.  I dont think it has anything to do with who they have in their circles to my knowledge there is no way to retrieve that information.


问:
overwhelmed by UIDatePicker. trying to preset .hour and .minute for func in viewDidLoad()
i spend 2.5 hours searching google, i think i have never been on google search page number 10 in my entire life. untill today.

im a newbie with swift and i want the app to open the new viewcontroller with a UIDatePicker (datepickermode: time) preset to the time the user choose the last time he set a time with the datepicker. basically like the iphone alarm if that helps?

the struct 'Time' that contains .hour and .minute (integers) has its own class.

i want to have a tiny function that is executed with viewDidLoad() and sets the timepicker.

```<code>   @IBAction func timePicker(_ sender: UIDatePicker) {
    let picker = timePicker.date
    getTime(date: picker)
    print(globalTime.savedTime)
}

func oldTime(withTime: TimeStruct.Time) {

    var newTime = DateComponents()
    newTime.hour = withTime.hour
    newTime.minute = withTime.minute

    var newDate = Date()

    timePicker.calendar.

    //blabliblub i've lost it here. the code makes no sense anymore

}

func getTime(date: Date) {

let components = Calendar.current.dateComponents([.hour, .minute], from: date)
globalTime.savedTime.hour = components.hour!
globalTime.savedTime.minute = components.minute!

}
</code>```

getTime saves the time once set. oldTime gives the previously set time to the picker when viewed again to change again.

the user sets a time and clicks a save button that saves the current hour and minute to a variable of type 'Time'

oh and if possible, please help me with the use of Date(), not NSDate().

thank you so much for your time!

Felix ✌

答:
hope this helps anyone. thanks for any further help :)

```<code>import UIKit

var globalTime = TimeStruct()

class Time_Setting: UIViewController {

func oldTime(withTime: TimeStruct.Time) {

    let newHour = withTime.hour
    let newMinute = withTime.minute
    let someDate = Date()

    let newTimePicker = timePicker.calendar.date(bySettingHour: newHour, minute: newMinute, second: 0, of: someDate)

    timePicker.date = newTimePicker!

    }
}
</code>```

another file:

```<code>import UIKit

class TimeStruct {

struct Time {
    var hour: Int
    var minute: Int
}

var savedTime = Time(hour: 07, minute: 00)
}
</code>```

Body:
i spend 2.5 hours searching google, i think i have never been on google search page number 10 in my entire life. untill today.

im a newbie with swift and i want the app to open the new viewcontroller with a UIDatePicker (datepickermode: time) preset to the time the user choose the last time he set a time with the datepicker. basically like the iphone alarm if that helps?

the struct 'Time' that contains .hour and .minute (integers) has its own class.

i want to have a tiny function that is executed with viewDidLoad() and sets the timepicker.

   @IBAction func timePicker(_ sender: UIDatePicker) {
    let picker = timePicker.date
    getTime(date: picker)
    print(globalTime.savedTime)
}

func oldTime(withTime: TimeStruct.Time) {

    var newTime = DateComponents()
    newTime.hour = withTime.hour
    newTime.minute = withTime.minute

    var newDate = Date()

    timePicker.calendar.

    //blabliblub i've lost it here. the code makes no sense anymore

}

func getTime(date: Date) {

let components = Calendar.current.dateComponents([.hour, .minute], from: date)
globalTime.savedTime.hour = components.hour!
globalTime.savedTime.minute = components.minute!

}

getTime saves the time once set. oldTime gives the previously set time to the picker when viewed again to change again.

the user sets a time and clicks a save button that saves the current hour and minute to a variable of type 'Time'

oh and if possible, please help me with the use of Date(), not NSDate().

thank you so much for your time!

Felix ✌

Body:
hope this helps anyone. thanks for any further help :)

import UIKit

var globalTime = TimeStruct()

class Time_Setting: UIViewController {

func oldTime(withTime: TimeStruct.Time) {

    let newHour = withTime.hour
    let newMinute = withTime.minute
    let someDate = Date()

    let newTimePicker = timePicker.calendar.date(bySettingHour: newHour, minute: newMinute, second: 0, of: someDate)

    timePicker.date = newTimePicker!

    }
}

another file:

import UIKit

class TimeStruct {

struct Time {
    var hour: Int
    var minute: Int
}

var savedTime = Time(hour: 07, minute: 00)
}


问:
R - Comparing strings that are similar but not identical
I have a data set that contains the sender's name and/or sender's email address.

```<code>sender_info = c('Kelvin [mailto:kelvin0354@gmail.com]','Kelvin','Sheryl [mailto:sheryl@hotmail.com]','Sheryl <sheryl@hotmail.com>','Oscar',)
</code>```

I want to check for the number of unique senders. As you can tell from sender_info, there are 3 unique senders - Kelvin, Sheryl and Oscar.

I tried implementing a couple of methods but they don't work. One of it involves the use of the levenshteinSim() function from the R RecordLinkage library to check for how similar each of the elements are. However, this method fails when the elements are too different (eg. 'Kelvin [mailto:kelvin0354@gmail.com]' and 'Kelvin').

I would really appreciate if anyone can give me a hint or two on how to solve this problem. Thank you!

答:
The alternative to strsplit is str_split from stringr.

```<code>library(stringr)
unique(str_split(sender_info, pattern = " ", simplify = TRUE)[,1])
# [1] "Kelvin" "Sheryl" "Oscar"
</code>```

Body:
I have a data set that contains the sender's name and/or sender's email address.

sender_info = c('Kelvin [mailto:kelvin0354@gmail.com]','Kelvin','Sheryl [mailto:sheryl@hotmail.com]','Sheryl <sheryl@hotmail.com>','Oscar',)

I want to check for the number of unique senders. As you can tell from sender_info, there are 3 unique senders - Kelvin, Sheryl and Oscar.

I tried implementing a couple of methods but they don't work. One of it involves the use of the levenshteinSim() function from the R RecordLinkage library to check for how similar each of the elements are. However, this method fails when the elements are too different (eg. 'Kelvin [mailto:kelvin0354@gmail.com]' and 'Kelvin').

I would really appreciate if anyone can give me a hint or two on how to solve this problem. Thank you!

Body:
The alternative to strsplit is str_split from stringr.

library(stringr)
unique(str_split(sender_info, pattern = " ", simplify = TRUE)[,1])
# [1] "Kelvin" "Sheryl" "Oscar"


问:
Creating a tar stream of arbitrary data and size
I need to create an arbitrarily large tarfile for testing but don't want it to hit the disk.

What's the easiest way to do this?

答:
You can use tar with -O option tar -O, like this tar -xOzf foo.tgz bigfile | process

https://www.gnu.org/software/tar/manual/html_node/Writing-to-Standard-Output.html

PS: However, it could be, that you will not get the benefits you intend to gain as tar starts writing stdout only after it has read through the entire compressed file. You can demonstrate this behavior by starting a large file extraction and following the file size over time; it should be zero most of the processing time and start growing at very late stage. On the other hand I haven't researched this extensively, there might be some work around, or I might be just plain wrong with my first hand out-of-memory experience.


问:
Google App Engine, define a Preprocessing class

I am trying to define a base request handling class so that the webapp pages may inherit some basic methods and variable which otherwise would be required to be repeatedly be defined for each page of the application. A sort of similar functionality like django preprocessors.  This is my base class from which other pages inherit:

```<code>class BasePage(webapp.RequestHandler):
    def __init__(self):
        self.user = users.get_current_user()
        self.template_values = {
                'user': self.user,
                'environ': self,   #I don't like the idea of passing the whole environ object to a template

                ##The below three functions cannot be executed during _init_ because of absence of self.request
                #'openid_providers': self.openid_providers(),
                #'logout_url': self.get_logout_url(),
                #'request': self.get_request(),
            }

    ##A sort of similar functionality like render_to_response in django
    def render_template(self, template_name, values = None, *args, **kwargs):
        #PATH is the directory containing the templates
        if values:
            for value in values:  self.template_values[value] = values[value]
        self.response.out.write(template.render(PATH+template_name, self.template_values, *args, **kwargs))

    ##Returns request as the name suggests
    def logout_url(self):
        return users.create_logout_url(self.request.url)

    ##Returns request as the name suggests
    def request(self):
        return request

    ##Returns openid login urls
    def openid_providers(self):
        #OPENID_POVIDERS  is a list of dictionary
        for p in OPENID_PROVIDERS:
             p['login_url'] = users.create_login_url(self.request.get('next', '/') , p['name'], p['url'])
        return OPENID_PROVIDERS
</code>```

Everything is working fine except that I cannot pass some variables during initialization as self.request is not available. So for a workaround what I did is pass on whole self variable as a template variable.

Is there some other way to provide the template variables (request, logout_url etc) to the templates?

答:
I've solved that problem in my AppEngine code by using the Template Method Pattern

Basically, the base class looks like:

```<code>class MyBasePage(webapp.RequestHandler):
    def __init__(self):
        # common setup/init stuff here,
        # omitted for this discussion

    def Setup(self):
        # request handling setup code needed in both GET/POST methods, like
        # checking for user login, getting session cookies, etc.
        # omitted for this discussion

    def get(self, *args):
        self.Setup()
        # call the derived class' 'DoGet' method that actually has
        # the logic inside it
        self.DoGet(*args)

    def post(self, *args):
        self.Setup()
        # call the derived class' 'DoPost' method
        self.DoPost(*args)

    def DoGet(self, *args):
        ''' derived classes override this method and
            put all of their GET logic inside. Base class does nothing.'''
        pass

    def DoPost(self, *args):
        ''' derived classes override this method and
            put all of their POST logic inside. Base class does nothing.'''
        pass
</code>```

...your derived classes then mostly just need to worry about the guts of those DoGet() and DoPost() methods.

Body:
I am trying to define a base request handling class so that the webapp pages may inherit some basic methods and variable which otherwise would be required to be repeatedly be defined for each page of the application. A sort of similar functionality like django preprocessors.  This is my base class from which other pages inherit:

class BasePage(webapp.RequestHandler):
    def __init__(self):
        self.user = users.get_current_user()
        self.template_values = {
                'user': self.user,
                'environ': self,   #I don't like the idea of passing the whole environ object to a template

                ##The below three functions cannot be executed during _init_ because of absence of self.request
                #'openid_providers': self.openid_providers(),
                #'logout_url': self.get_logout_url(),
                #'request': self.get_request(),
            }

    ##A sort of similar functionality like render_to_response in django
    def render_template(self, template_name, values = None, *args, **kwargs):
        #PATH is the directory containing the templates
        if values:
            for value in values:  self.template_values[value] = values[value]
        self.response.out.write(template.render(PATH+template_name, self.template_values, *args, **kwargs))

    ##Returns request as the name suggests
    def logout_url(self):
        return users.create_logout_url(self.request.url)

    ##Returns request as the name suggests
    def request(self):
        return request

    ##Returns openid login urls
    def openid_providers(self):
        #OPENID_POVIDERS  is a list of dictionary
        for p in OPENID_PROVIDERS:
             p['login_url'] = users.create_login_url(self.request.get('next', '/') , p['name'], p['url'])
        return OPENID_PROVIDERS

Everything is working fine except that I cannot pass some variables during initialization as self.request is not available. So for a workaround what I did is pass on whole self variable as a template variable.

Is there some other way to provide the template variables (request, logout_url etc) to the templates?

Body:
I've solved that problem in my AppEngine code by using the Template Method Pattern

Basically, the base class looks like:

class MyBasePage(webapp.RequestHandler):
    def __init__(self):
        # common setup/init stuff here,
        # omitted for this discussion

    def Setup(self):
        # request handling setup code needed in both GET/POST methods, like
        # checking for user login, getting session cookies, etc.
        # omitted for this discussion

    def get(self, *args):
        self.Setup()
        # call the derived class' 'DoGet' method that actually has
        # the logic inside it
        self.DoGet(*args)

    def post(self, *args):
        self.Setup()
        # call the derived class' 'DoPost' method
        self.DoPost(*args)

    def DoGet(self, *args):
        ''' derived classes override this method and
            put all of their GET logic inside. Base class does nothing.'''
        pass

    def DoPost(self, *args):
        ''' derived classes override this method and
            put all of their POST logic inside. Base class does nothing.'''
        pass

...your derived classes then mostly just need to worry about the guts of those DoGet() and DoPost() methods.


问:
Android Facebook 4.0: Check permissions
Many things been changed in Facebook 4.0.

How to check if user have permission in Facebook 4.x api?

答:
After Successfull Login Call this method

```<code>    new GraphRequest(
        AccessToken.getCurrentAccessToken(),
        "/{user-id}/permissions",
        null,
        HttpMethod.GET,
        new GraphRequest.Callback() {
            public void onCompleted(GraphResponse response) {
                /* handle the result */
            }
        }
    ).executeAsync();

================================================================
 new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/744511125731315/permissions",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        CommonMethod.showAlert("PERMISSION_GRANTED Fb ---> " + response, MainActivity.this);
                    }
                }
        ).executeAsync();
============================================
</code>```

Title: Android Facebook 4.0: Check permissions

Body:
After Successfull Login Call this method

    new GraphRequest(
        AccessToken.getCurrentAccessToken(),
        "/{user-id}/permissions",
        null,
        HttpMethod.GET,
        new GraphRequest.Callback() {
            public void onCompleted(GraphResponse response) {
                /* handle the result */
            }
        }
    ).executeAsync();

================================================================
 new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/744511125731315/permissions",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        CommonMethod.showAlert("PERMISSION_GRANTED Fb ---> " + response, MainActivity.this);
                    }
                }
        ).executeAsync();
============================================


问:
How to process frames of an existing video in Swift
Currently I am trying to process the frames of an existing video with OpenCV. Are there any AV reader libraries that contain delegate methods that process frames while playing back videos? I know how to process frames during a live AVCaptureSession through the use of the AVCaptureVideoDataOutput and the captureOutput delegate method. Is there something similar for playing back videos?

Any help would be appreiciated.

答:
You can use AVVideoComposition

If You want to process frames with CoreImage you can create an instance by calling init(asset:applyingCIFiltersWithHandler:) method.

Or you can create custom comopsitor

You can implement your own custom video compositor by implementing the
  AVVideoCompositing  protocol; a custom video compositor is provided
  with pixel buffers for each of its video sources during playback and
  other operations and can perform arbitrary graphical operations on
  them in order to produce visual output.

See docs for more info.
Here you can find an example (but example is in Objective-C).


问:
Getting return type of Task (not Task<T>)
I use ASP.NET Identity 2.2.1.

I implement the interface IIdentityMessageService like this:

```<code>public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        Mail mailService = new Mail(message.Destination, message.Subject, body);
        string succes = mailService.send();
        return Task.FromResult(succes);
    }
}
</code>```

Below is (a part) of my Mail class:

```<code>public class Mail
{
    public MailMessage message { get; set; }
    public string send(string host, int port, string username, string wachtwoord, int timeout)
    {
        SmtpClient ss = new SmtpClient(host, port);
        ss.EnableSsl = true;
        ss.Timeout = timeout;
        ss.DeliveryMethod = SmtpDeliveryMethod.Network;
        ss.UseDefaultCredentials = false;
        ss.Credentials = new System.Net.NetworkCredential(username, wachtwoord);
        try
        {
            ss.Send(message);
            message.Dispose();
            return "succes";
        }
        catch (Exception ex)
        {
            return "no succes: " + ex.ToString();
        }
    }
}
</code>```

In one of my controller's I have the following line:

```<code>var emailResult = UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);
</code>```

I get a result back of type Task. If I had await a like this I expected to get the string result of succes:

```<code>var emailResult = await UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);
</code>```

But I get the following compile error: "cannot assign void to an implicitly-typed variable". I just want to get the result of success in my controller. How do I accomplish that?

答:
You could hide the interface method and create your own method to use from the outside:</p>

```<code>public class EmailService : IIdentityMessageService
{
    Task IIdentityMessageService.SendAsync(IdentityMessage message)
    {
        return this.SendAsync(message);
    }

    public Task<string> SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        Mail mailService = new Mail(message.Destination, message.Subject, body);
        string succes = mailService.send();
        return Task.FromResult(succes);
    }
}
</code>```

Body:
I use ASP.NET Identity 2.2.1.

I implement the interface IIdentityMessageService like this:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        Mail mailService = new Mail(message.Destination, message.Subject, body);
        string succes = mailService.send();
        return Task.FromResult(succes);
    }
}

Below is (a part) of my Mail class:

public class Mail
{
    public MailMessage message { get; set; }
    public string send(string host, int port, string username, string wachtwoord, int timeout)
    {
        SmtpClient ss = new SmtpClient(host, port);
        ss.EnableSsl = true;
        ss.Timeout = timeout;
        ss.DeliveryMethod = SmtpDeliveryMethod.Network;
        ss.UseDefaultCredentials = false;
        ss.Credentials = new System.Net.NetworkCredential(username, wachtwoord);
        try
        {
            ss.Send(message);
            message.Dispose();
            return "succes";
        }
        catch (Exception ex)
        {
            return "no succes: " + ex.ToString();
        }
    }
}

In one of my controller's I have the following line:

var emailResult = UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);

I get a result back of type Task. If I had await a like this I expected to get the string result of succes:

var emailResult = await UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);

But I get the following compile error: "cannot assign void to an implicitly-typed variable". I just want to get the result of success in my controller. How do I accomplish that?

Body:
You could hide the interface method and create your own method to use from the outside:

public class EmailService : IIdentityMessageService
{
    Task IIdentityMessageService.SendAsync(IdentityMessage message)
    {
        return this.SendAsync(message);
    }

    public Task<string> SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        Mail mailService = new Mail(message.Destination, message.Subject, body);
        string succes = mailService.send();
        return Task.FromResult(succes);
    }
}


问:
User defined Exception doubt
I have this exception class

```<code>class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')
</code>```

and the exception comes as

```<code>Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'
</code>```

------------------------------------update------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot

答:
I think you meant to write val instead of value here:

```<code>def __str__(self):
    return repr(self.val) # <--- not self.value
</code>```

To display multiple values I'd recommend str.format (requires Python 2.6 or newer). Example:

```<code>def __str__(self):
    return "Hello: {0}".format(self.val)
</code>```

Another example:

```<code>def __str__(self):
    return "val1 = {}, val2 = {}".format(self.val1, self.val2)
</code>```

Title: User defined Exception doubt

Body:
I have this exception class

class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')

and the exception comes as

Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'

------------------------------------update------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot

Body:
I think you meant to write val instead of value here:

def __str__(self):
    return repr(self.val) # <--- not self.value

To display multiple values I'd recommend str.format (requires Python 2.6 or newer). Example:

def __str__(self):
    return "Hello: {0}".format(self.val)

Another example:

def __str__(self):
    return "val1 = {}, val2 = {}".format(self.val1, self.val2)


问:
XSL: Get data from referred element in XML (ref, id)
I would like to get the the name of an author-element which is referred by a book-element in a XML file but I haven't figured out yet how to access it.

Down below is my XSL code and a sample of how my XML looks like.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/library">
<html>
  <head>
    <link rel="stylesheet" href="librarytable.css" type="text/css"/>
  </head>
  <body>
    <h2>Bibliothek</h2>
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Jahr</th>
          <th>Autor(en)</th>
        </tr>
      </thead>
      <xsl:for-each select="book">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="year"/></td>
        <td><xsl:value-of select="author-ref"/></td>
        <!-- author-ref just to fill in the blank-->
      </tr>
      </xsl:for-each>
    </table>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>
</code>```

This is how book and author are connected in my XML:

```<code><book>
    <author-ref>T.Pratchett</author-ref>
    <title>The Colour of Magic</title>
    <year>1983</year>
</book>

<author id="T.Pratchett">
    <last-name>Pratchett</last-name>
    <first-name>Terry</first-name>
</author>
</code>```

Here is how it looks like but instead of T.Pratchett I would like to have Terry Pratchett in the table cell for example.

I would be very grateful if anybody knows how to solve this problem.
Thank you.

答:
You can use a key to look up the author elements by their id attribute.

```<code><xsl:key name="authors" match="author" use="@id" />
</code>```

So, to look up the author for a current book you would do this...

```<code><xsl:value-of select="key('authors', author-ref)"/>
</code>```

Try this XSLT:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="authors" match="author" use="@id" />

<xsl:template match="/library">
<html>
  <head>
    <link rel="stylesheet" href="librarytable.css" type="text/css"/>
  </head>
  <body>
    <h2>Bibliothek</h2>
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Jahr</th>
          <th>Autor(en)</th>
        </tr>
      </thead>
      <xsl:for-each select="book">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="year"/></td>
        <td>
          <xsl:value-of select="key('authors', author-ref)/first-name"/>
          <xsl:text> </xsl:text>
          <xsl:value-of select="key('authors', author-ref)/last-name"/>
        </td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>
</code>```

Body:
I would like to get the the name of an author-element which is referred by a book-element in a XML file but I haven't figured out yet how to access it.

Down below is my XSL code and a sample of how my XML looks like.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/library">

    <link rel="stylesheet" href="librarytable.css" type="text/css"/>

Bibliothek

          Titel
          Jahr
          Autor(en)

      <xsl:for-each select="book">

        <xsl:value-of select="title"/>
        <xsl:value-of select="year"/>
        <xsl:value-of select="author-ref"/>

      </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

This is how book and author are connected in my XML:

<book>
    <author-ref>T.Pratchett</author-ref>
    <title>The Colour of Magic</title>
    <year>1983</year>
</book>

<author id="T.Pratchett">
    <last-name>Pratchett</last-name>
    <first-name>Terry</first-name>
</author>

Here is how it looks like but instead of T.Pratchett I would like to have Terry Pratchett in the table cell for example.

I would be very grateful if anybody knows how to solve this problem.
Thank you.

Body:
You can use a key to look up the author elements by their id attribute.

<xsl:key name="authors" match="author" use="@id" />

So, to look up the author for a current book you would do this...

<xsl:value-of select="key('authors', author-ref)"/>

Try this XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="authors" match="author" use="@id" />

<xsl:template match="/library">
<html>
  <head>
    <link rel="stylesheet" href="librarytable.css" type="text/css"/>
  </head>
  <body>
    <h2>Bibliothek</h2>
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Jahr</th>
          <th>Autor(en)</th>
        </tr>
      </thead>
      <xsl:for-each select="book">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="year"/></td>
        <td>
          <xsl:value-of select="key('authors', author-ref)/first-name"/>
          <xsl:text> </xsl:text>
          <xsl:value-of select="key('authors', author-ref)/last-name"/>
        </td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>


问:
IntelliJ cannot resolve taglib for the neighbouring dir in the same module
A jsp file has a line:

```<code><%@ taglib uri="../../WEB-INF/thincore.tld" prefix="TL" %>
</code>```

And the address in it is red and gives a hint: "cannot resolve taglib ../../WEB-INF/thincore.tld".

But the file really lies in the "uncle" directory, in the same module, both jsp file and its uncle lie in the same grandfather, marked as a source dir. So, I don't know about any logical border between them.

It is not a duplicate!

I have read all questions on SO with the same "IntelliJ cannot resolve taglib" in the title, but they all are about seeing some distant libraries, that really must be registered. But registering the module in itself seems senseless to me.

I am not expecting the answer (I would be grateful, though), but at least some hint where to investigate.
It seems that the module is invisible for itself?

答:
I have found the source of the problem.

The fact the grandfather folder is the source folder does not mean that its folders will be considered as library folders, and their files, being libs/jars/tlds and not java files, are simply not seen when they are needed. So, yes, we must set in the Project Structure the appropriate folder as a library, even if it is inside the module.

Body:
A jsp file has a line:

<%@ taglib uri="../../WEB-INF/thincore.tld" prefix="TL" %>

And the address in it is red and gives a hint: "cannot resolve taglib ../../WEB-INF/thincore.tld".

But the file really lies in the "uncle" directory, in the same module, both jsp file and its uncle lie in the same grandfather, marked as a source dir. So, I don't know about any logical border between them.

It is not a duplicate!

I have read all questions on SO with the same "IntelliJ cannot resolve taglib" in the title, but they all are about seeing some distant libraries, that really must be registered. But registering the module in itself seems senseless to me.

I am not expecting the answer (I would be grateful, though), but at least some hint where to investigate.
It seems that the module is invisible for itself?


问:
Creating Java Calendar, basic parameters
I would like to send a Java Calendar object over a web service (soap). I notice that this kind of object is too complex and there should be a better method to send the same information.

What are the basic attributes that should be sended over the web service, so the client can create a Java Calendar out of this attributes?

I'm guessing: TimeZone, Date, and Time?

Also, how can the client recreate the Calendar based on those attributes?

Thanks!

答:
In fact I would go for Timezone tz (timezone the calendar was expressed in), Locale loc (used for data representation purpose) and long time (UTC time) if you want exactly the same object.

In most uses the time is enough though, the receiver will express it with his own timezone and locale.