问:
Get hardware information from /proc filesytem in Linux
I use execv to run lshw command to get the CPU, disk, and memory in C code. But I would like to search another solution to get these information from /proc or any other existed data. Have any suggestion? Here is my code:

```<code>char *params[9]  = {"/usr/bin/lshw", "-short", "-c", "disk",
                  "-c", "memory", "-c", "processor", 0}; //cmd params filled
execv(params[0], params);
</code>```

Linux command: $ sudo lshw -short -c disk -c processor -c memory

```<code>$ sudo lshw -short -c disk -c processor -c memory
H/W path         Device     Class          Description
======================================================
/0/0                        memory         64KiB BIOS
/0/22                       memory         16GiB System Memory
/0/22/0                     memory         DIMM Synchronous [empty]
/0/22/1                     memory         DIMM Synchronous [empty]
/0/22/2                     memory         8GiB DIMM Synchronous 2133 MHz (0.5 ns)
/0/22/3                     memory         8GiB DIMM Synchronous 2133 MHz (0.5 ns)
/0/2a                       memory         256KiB L1 cache
/0/2b                       memory         1MiB L2 cache
/0/2c                       memory         6MiB L3 cache
/0/2d                       processor      Intel(R) Xeon(R) CPU D-1521 @ 2.40GHz
/0/1/0.0.0       /dev/sda   disk           16GB SATADOM-SH 3IE3
/0/2/0.0.0       /dev/sdb   disk           120GB Patriot Blaze
</code>```

I have two questions:

Where to find a guide to parse the files in /proc to get
these hardware information?

Do I need to trace the source code of lshw to find what does lshw do?

Edit:

Chapter 7 of Advanced Linux Programming is a guide to parse the /proc filesystem.

答:
1: To get the CPU  load use this command :

```<code>top -bn1 | grep load
</code>```

this will give you output like :

```<code>top - 12:26:20 up 35 min,  2 users,  load average: 0.02, 0.01, 0.00
</code>```

now parse the load average from above string.
2: To get memory info use this command :

```<code>free -m
</code>```

This will give you:

```<code>total       used       free     shared    buffers     cached
Mem:         15926        308      15617          6         15        122
-/+ buffers/cache:        171      15755
Swap:            0          0          0
</code>```

To get the disk info , use this :

```<code>df -H /home/test
</code>```

This will give you :

```<code>Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       102G  5.4G   91G   6% /
</code>```

Now from above result parse the content what you want.

Body:
I use execv to run lshw command to get the CPU, disk, and memory in C code. But I would like to search another solution to get these information from /proc or any other existed data. Have any suggestion? Here is my code:

char *params[9]  = {"/usr/bin/lshw", "-short", "-c", "disk",
                  "-c", "memory", "-c", "processor", 0}; //cmd params filled
execv(params[0], params);

Linux command: $ sudo lshw -short -c disk -c processor -c memory

$ sudo lshw -short -c disk -c processor -c memory
H/W path         Device     Class          Description
======================================================
/0/0                        memory         64KiB BIOS
/0/22                       memory         16GiB System Memory
/0/22/0                     memory         DIMM Synchronous [empty]
/0/22/1                     memory         DIMM Synchronous [empty]
/0/22/2                     memory         8GiB DIMM Synchronous 2133 MHz (0.5 ns)
/0/22/3                     memory         8GiB DIMM Synchronous 2133 MHz (0.5 ns)
/0/2a                       memory         256KiB L1 cache
/0/2b                       memory         1MiB L2 cache
/0/2c                       memory         6MiB L3 cache
/0/2d                       processor      Intel(R) Xeon(R) CPU D-1521 @ 2.40GHz
/0/1/0.0.0       /dev/sda   disk           16GB SATADOM-SH 3IE3
/0/2/0.0.0       /dev/sdb   disk           120GB Patriot Blaze

I have two questions:

Where to find a guide to parse the files in /proc to get
these hardware information?

Do I need to trace the source code of lshw to find what does lshw do?

Edit:

Chapter 7 of Advanced Linux Programming is a guide to parse the /proc filesystem.

Body:
1: To get the CPU  load use this command :

top -bn1 | grep load

this will give you output like :

top - 12:26:20 up 35 min,  2 users,  load average: 0.02, 0.01, 0.00

now parse the load average from above string.
2: To get memory info use this command :

free -m

This will give you:

total       used       free     shared    buffers     cached
Mem:         15926        308      15617          6         15        122
-/+ buffers/cache:        171      15755
Swap:            0          0          0

To get the disk info , use this :

df -H /home/test

This will give you :

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       102G  5.4G   91G   6% /

Now from above result parse the content what you want.


来源: stackexchange

问:
How do I read my input from text area in react?
I am trying to read input from text area once I finish typing. I read somewhere that you need onBlur event handler to achieve this functionality instead of onChange. However when I use onBlur, I am not able to enter my input. Where am I going wrong?</p>

```<code>import React from 'react'
import ReactDOM from 'react-dom'
class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }
    handleChange(event) {
        this.setState({value: event.target.value})
        console.log(this.state.value)
    }
    render(){
        return(
            <div>
                <h1>Hello World Restaurant</h1>
                <textarea placeholder="Enter name of guest:" onBlur={this.handleChange.bind(this)} value={this.state.value}></textarea>
            </div>
        )
    }
}
ReactDOM.render(<HelloWorld/>,document.getElementById('root'))
</code>```

答:
You are mixing the concept of controlled component and uncontrolled component.

If you are using value property then you need to use onChange method to update the state value, otherwise it will become read-only (you are controlling the value of textarea by state, so if state will not update whatever you type in textarea will get reset by state value).

If you don't want the onChange method then remove the value property of textarea, it will allow you to type then inside onBlur get the value by event.target.value.

Check this example (Uncontrolled Component):

class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }

    handleChange(event) {
        this.setState({value: event.target.value})
    }

    render(){
        return(

Hello World Restaurant

                value: {this.state.value}

                <textarea placeholder="Enter name of guest:" onBlur={this.handleChange.bind(this)}></textarea>

        )
    }
}

ReactDOM.render(<HelloWorld/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to read input from text area once I finish typing. I read somewhere that you need onBlur event handler to achieve this functionality instead of onChange. However when I use onBlur, I am not able to enter my input. Where am I going wrong?

import React from 'react'
import ReactDOM from 'react-dom'
class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }
    handleChange(event) {
        this.setState({value: event.target.value})
        console.log(this.state.value)
    }
    render(){
        return(

Hello World Restaurant

                <textarea placeholder="Enter name of guest:" onBlur={this.handleChange.bind(this)} value={this.state.value}></textarea>

        )
    }
}
ReactDOM.render(<HelloWorld/>,document.getElementById('root'))

Body:
You are mixing the concept of controlled component and uncontrolled component.

If you are using value property then you need to use onChange method to update the state value, otherwise it will become read-only (you are controlling the value of textarea by state, so if state will not update whatever you type in textarea will get reset by state value).

If you don't want the onChange method then remove the value property of textarea, it will allow you to type then inside onBlur get the value by event.target.value.

Check this example (Uncontrolled Component):

class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }

    handleChange(event) {
        this.setState({value: event.target.value})
    }

    render(){
        return(
            <div>
                <h1>Hello World Restaurant</h1>
                value: {this.state.value}
                <br/>
                <textarea placeholder="Enter name of guest:" onBlur={this.handleChange.bind(this)}></textarea>
            </div>
        )
    }
}

ReactDOM.render(<HelloWorld/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
Force Shuffle NSMutableArray
I have a NSMutableArray called putNumberUsed. It contains the following objects @"blah1,@"blah2",@"blah3",@"blah4". I want to shuffle these objects randomly so for example if I chose:

```<code> [putNumberUsed objectAtIndex:0]
</code>```

it would give me anything but "blah1". How would I go about doing this? The following is the code I used thus far:

```<code>NSMutableArray *putNumbersUsed = [[NSMutableArray alloc] arrayWithObjects:@"blah1",@"blah2",@"blah3",@"blah4",nil];
</code>```

答:
From iOS 10.x++ new concept of shuffle array is given by Apple,

You need to import the framework :

ObjeC

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

NSArray *shuffledArray = [yourArray shuffledArray];
</code>```

Swift

```<code>import GameplayKit

let shuffledArray = yourArray.shuffled()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Force Shuffle NSMutableArray

Body:
I have a NSMutableArray called putNumberUsed. It contains the following objects @"blah1,@"blah2",@"blah3",@"blah4". I want to shuffle these objects randomly so for example if I chose:

 [putNumberUsed objectAtIndex:0]

it would give me anything but "blah1". How would I go about doing this? The following is the code I used thus far:

NSMutableArray *putNumbersUsed = [[NSMutableArray alloc] arrayWithObjects:@"blah1",@"blah2",@"blah3",@"blah4",nil];

Body:
From iOS 10.x++ new concept of shuffle array is given by Apple,

You need to import the framework :

ObjeC

#import <GameplayKit/GameplayKit.h>

NSArray *shuffledArray = [yourArray shuffledArray];

Swift

import GameplayKit

let shuffledArray = yourArray.shuffled()


问:
.htaccess help, replacing URI segment
I have a URL that looks like this...

```<code>http://www.domain/a/var
</code>```

I am hoping it would be possible to rewrite the URL using .htaccess so that /a/ would be replaced by /b/.

Is that possible, and if so, how?

答:
This should do that you need

```<code>RewriteEngine on
RewriteRule ^/a/(.*) /b/$1
</code>```

Note: You'll need to add [PT] or similar if you need mod_alias or mod_index or similar to work using the new path.

ContentLicense: CC BY-SA 2.5

Title: .htaccess help, replacing URI segment

Body:
I have a URL that looks like this...

http://www.domain/a/var

I am hoping it would be possible to rewrite the URL using .htaccess so that /a/ would be replaced by /b/.

Is that possible, and if so, how?

Body:
This should do that you need

RewriteEngine on
RewriteRule ^/a/(.*) /b/$1

Note: You'll need to add [PT] or similar if you need mod_alias or mod_index or similar to work using the new path.


问:
How to debug a C program with signal handler in gdb?
I wrote a simple program to understand the control flow transfer of a signal handler. The following program will let the child to repetitively write to .text region and trigger the handler.

```<code>#include "csapp.h" // just include standard headers

extern char etext;

void handler() {
  printf("pid = %d, in handler\n", getpid());
  return;
}

int main(int argc, char **argv) {
  if (signal(SIGSEGV, handler) == SIG_ERR) {
    perror("signal error");
  }

  if (fork() == 0) {
    printf("from Child before\n");
    etext = 'a';
    printf("from Child after\n");
  }

  return EXIT_SUCCESS;
}
</code>```

However, I want to verify this using gdb. Disassembling the main gives the assembly below. I created a break point using command below so gdb can break at the point right before it write to the .text region.

(gdb) b *0x00000000004006fb

Then I run the program in gdb. But the gdb wont stop and keeps executing the signal handler.

```<code>   0x00000000004006ba <+0>: push   %rbp
   0x00000000004006bb <+1>: mov    %rsp,%rbp
   0x00000000004006be <+4>: sub    $0x10,%rsp
   0x00000000004006c2 <+8>: mov    %edi,-0x4(%rbp)
   0x00000000004006c5 <+11>:    mov    %rsi,-0x10(%rbp)
   0x00000000004006c9 <+15>:    mov    $0x40069d,%esi
   0x00000000004006ce <+20>:    mov    $0xb,%edi
   0x00000000004006d3 <+25>:    callq  0x400570 <signal@plt>
   0x00000000004006d8 <+30>:    cmp    $0xffffffffffffffff,%rax
   0x00000000004006dc <+34>:    jne    0x4006e8 <main+46>
   0x00000000004006de <+36>:    mov    $0x4007ba,%edi
   0x00000000004006e3 <+41>:    callq  0x400590 <perror@plt>
   0x00000000004006e8 <+46>:    callq  0x4005a0 <fork@plt>
   0x00000000004006ed <+51>:    test   %eax,%eax
   0x00000000004006ef <+53>:    jne    0x40070c <main+82>
   0x00000000004006f1 <+55>:    mov    $0x4007c7,%edi
   0x00000000004006f6 <+60>:    callq  0x400530 <puts@plt>
   0x00000000004006fb <+65>:    movb   $0x61,0x9b(%rip)        # 0x40079d
   0x0000000000400702 <+72>:    mov    $0x4007d9,%edi
   0x0000000000400707 <+77>:    callq  0x400530 <puts@plt>
   0x000000000040070c <+82>:    mov    $0x0,%eax
   0x0000000000400711 <+87>:    leaveq
   0x0000000000400712 <+88>:    retq
</code>```

Questions:
1.Why gdb wont break at the address I specify?

2.How can I use gdb so that I know the exact address the instruction pointer points to when it returns from the signal handler?

答:
Why gdb wont break at the address I specify?

Because you are debugging the wrong (parent) process.

The instruction you want to stop on is only executed in the child, and you aren't debugging the child.

To debug the child, use set follow-fork-mode child.

How can I use gdb so that I know the exact address the instruction pointer points to when it returns from the signal handler?

Put a breakpoint on the ret instruction in the signal handler, and do x/a $rsp when that breakpoint is hit.

Body:
I wrote a simple program to understand the control flow transfer of a signal handler. The following program will let the child to repetitively write to .text region and trigger the handler.

#include "csapp.h" // just include standard headers

extern char etext;

void handler() {
  printf("pid = %d, in handler\n", getpid());
  return;
}

int main(int argc, char **argv) {
  if (signal(SIGSEGV, handler) == SIG_ERR) {
    perror("signal error");
  }

  if (fork() == 0) {
    printf("from Child before\n");
    etext = 'a';
    printf("from Child after\n");
  }

  return EXIT_SUCCESS;
}

However, I want to verify this using gdb. Disassembling the main gives the assembly below. I created a break point using command below so gdb can break at the point right before it write to the .text region.

(gdb) b *0x00000000004006fb

Then I run the program in gdb. But the gdb wont stop and keeps executing the signal handler.

   0x00000000004006ba <+0>: push   %rbp
   0x00000000004006bb <+1>: mov    %rsp,%rbp
   0x00000000004006be <+4>: sub    $0x10,%rsp
   0x00000000004006c2 <+8>: mov    %edi,-0x4(%rbp)
   0x00000000004006c5 <+11>:    mov    %rsi,-0x10(%rbp)
   0x00000000004006c9 <+15>:    mov    $0x40069d,%esi
   0x00000000004006ce <+20>:    mov    $0xb,%edi
   0x00000000004006d3 <+25>:    callq  0x400570 <signal@plt>
   0x00000000004006d8 <+30>:    cmp    $0xffffffffffffffff,%rax
   0x00000000004006dc <+34>:    jne    0x4006e8
   0x00000000004006de <+36>:    mov    $0x4007ba,%edi
   0x00000000004006e3 <+41>:    callq  0x400590 <perror@plt>
   0x00000000004006e8 <+46>:    callq  0x4005a0 <fork@plt>
   0x00000000004006ed <+51>:    test   %eax,%eax
   0x00000000004006ef <+53>:    jne    0x40070c
   0x00000000004006f1 <+55>:    mov    $0x4007c7,%edi
   0x00000000004006f6 <+60>:    callq  0x400530 <puts@plt>
   0x00000000004006fb <+65>:    movb   $0x61,0x9b(%rip)        # 0x40079d
   0x0000000000400702 <+72>:    mov    $0x4007d9,%edi
   0x0000000000400707 <+77>:    callq  0x400530 <puts@plt>
   0x000000000040070c <+82>:    mov    $0x0,%eax
   0x0000000000400711 <+87>:    leaveq
   0x0000000000400712 <+88>:    retq

Questions:
1.Why gdb wont break at the address I specify?

2.How can I use gdb so that I know the exact address the instruction pointer points to when it returns from the signal handler?


问:
SQL Query in Oracle where clause
I have table Groups with 3 rows, ID, GROUP_NAME and PARENT_GROUP_ID, the table itself presents a basic group-subgroup functionality. Example is: if my Group name is - "First Group" with ID = 1, and it has a subgroup named "Sub Group" with ID = 2, and PARENT_GROUP_ID = 1; this means that Sub Group is the subgroup of the group with ID = 1. My problem is that I have a procedure, which loads the data according to parameters(pn_parent_group_id is a number)

```<code>CURSOR c1 IS
SELECT * FROM GROUPS WHERE PARENT_GROUP_ID = pn_parent_group_id;
</code>```

This query works fine when I send any pn_parent_group_id into the procedure, and it finds all the necessary subgroups, however when I send NULL to the pn_parent_group_id it works wrong, because it should return those without parent_group_id(meaning only parent groups). I know my explanation is lacking, but I hope you got the idea, any help would be appreciated!

答:
You may be interested in the SYS_OP_MAP_NONNULL function, which allows the comparison NULL = NULL to be TRUE.

```<code>CURSOR c1 IS
   SELECT * FROM GROUPS
   WHERE SYS_OP_MAP_NONNULL(parent_group_id) = SYS_OP_MAP_NONNULL(pn_parent_group_id);
</code>```

This function is not directly documented in Oracle documentation, but does appear in topic documentation - as it has been around for a long while, I think it unlikely that it will be removed.  As always with these things, use at your own discretion.

Title: SQL Query in Oracle where clause

Body:
I have table Groups with 3 rows, ID, GROUP_NAME and PARENT_GROUP_ID, the table itself presents a basic group-subgroup functionality. Example is: if my Group name is - "First Group" with ID = 1, and it has a subgroup named "Sub Group" with ID = 2, and PARENT_GROUP_ID = 1; this means that Sub Group is the subgroup of the group with ID = 1. My problem is that I have a procedure, which loads the data according to parameters(pn_parent_group_id is a number)

CURSOR c1 IS
SELECT * FROM GROUPS WHERE PARENT_GROUP_ID = pn_parent_group_id;

This query works fine when I send any pn_parent_group_id into the procedure, and it finds all the necessary subgroups, however when I send NULL to the pn_parent_group_id it works wrong, because it should return those without parent_group_id(meaning only parent groups). I know my explanation is lacking, but I hope you got the idea, any help would be appreciated!

Body:
You may be interested in the SYS_OP_MAP_NONNULL function, which allows the comparison NULL = NULL to be TRUE.

CURSOR c1 IS
   SELECT * FROM GROUPS
   WHERE SYS_OP_MAP_NONNULL(parent_group_id) = SYS_OP_MAP_NONNULL(pn_parent_group_id);

This function is not directly documented in Oracle documentation, but does appear in topic documentation - as it has been around for a long while, I think it unlikely that it will be removed.  As always with these things, use at your own discretion.


问:
Looking for Google Map API
I am looking for Google location API where I can get user's location. I know I can get user location from Geolocation API. But my requirement is little bit different.

For example, I am writing a access control policy which give my client/consumer access to some resource based on my location not based on client's location. I can get client's location by Geolocation API but how my web app can get my location ?

Is there any Google Map API to delegate my location information from google maps to my developed web app ?

Any suggestion will be highly appreciable.

Thanks,
Jabed

答:
You can check this one

Google Map Geolocation API

P.S or do you really need the source code for a geolocation web based?

Title: Looking for Google Map API


问:
Including Angular-tree-component in project throws: (SystemJS) ctorParameters.map is not a function error in Console
I refered this to include the angular-tree-component plugin. I followed the exact steps and get following error while running the application:

Error: (SystemJS) ctorParameters.map is not a function(…)

My package.json file:

```<code>          {
            "name": "template2",
            "version": "1.0.0",
            "scripts": {},
            "license": "ISC",
            "dependencies": {
              "@angular/common": "~2.0.1",
              "@angular/compiler": "~2.0.1",
              "@angular/core": "~2.0.1",
              "@angular/forms": "~2.0.1",
              "@angular/http": "~2.0.1",
              "@angular/platform-browser": "~2.0.1",
              "@angular/platform-browser-dynamic": "~2.0.1",
              "@angular/router": "~3.0.1",
              "@angular/upgrade": "~2.0.1",
              "angular-tree-component": "3.6.0",
              "angular2-modal": "^2.0.3",
              "bootstrap": "^3.3.7",
              "core-js": "^2.4.1",
              "ng-lightning": "^1.3.0",
              "ng2-bs3-modal": "^0.10.4",
              "ng2-dragula": "^1.3.1",
              "ng2-modal-dialog": "^1.0.1",
              "ngx-modal": "0.0.29",
              "reflect-metadata": "^0.1.8",
              "rxjs": "5.0.0-beta.12",
              "systemjs": "0.19.39",
              "zone.js": "^0.6.25"
            },
            "devDependencies": {
              "@types/core-js": "^0.9.34",
              "typescript": "^2.0.3",
              "typings": "^1.4.0"
            }
          }
</code>```

My Systemjs.config.js

```<code>            /**
             * System configuration for Angular samples
             * Adjust as necessary for your application needs.
             */
            (function (global) {
                System.config({
                    paths: {
                        // paths serve as alias
                        'npm:': '/node_modules/',
                    },
                    // map tells the System loader where to look for things

                    //defaultJSExtensions: true,  // This is included for Model Popup
                    map: {
                        // our app is within the app folder
                        app: '/Scripts',
                        // angular bundles
                        '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
                        '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
                        '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
                        '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
                        '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
                        '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
                        '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
                        '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

                        /*The following is required by dragula */
                        'dragula': 'node_modules/dragula',
                        'ng2-dragula': 'node_modules/ng2-dragula',
                        'contra': 'node_modules/contra',
                        'atoa': 'node_modules/atoa',
                        'ticky': 'node_modules/ticky',
                        'crossvent': 'node_modules/crossvent/src',
                        'custom-event': 'node_modules/custom-event',
                        /*The following is required by dragula ^*/

                        'angular-tree-component': 'node_modules/angular-tree-component/dist/angular-tree-component.umd.js',

                        //The following is required by PopUp Model
                        "ngx-modal": "node_modules/ngx-modal",
                        // other libraries
                        'rxjs': 'npm:rxjs'
                    },
                    // packages tells the System loader how to load when no filename and/or no extension
                    packages: {
                        app: {
                            main: './main.js',
                            defaultExtension: 'js'
                        },
                        /*The following is required by dragula */
                        'dragula': { main: 'dragula.js', defaultExtension: 'js' },
                        'ng2-dragula': { defaultExtension: 'js' },
                        'contra': { main: 'contra.js', defaultExtension: 'js' },
                        'atoa': { main: 'atoa.js', defaultExtension: 'js' },
                        'ticky': { main: 'ticky.js', defaultExtension: 'js' },
                        'crossvent': { main: 'crossvent.js', defaultExtension: 'js' },
                        'custom-event': { main: 'index.js', defaultExtension: 'js' },
                        /*The following is required by dragula ^*/

                        'angular2-modal': {
                            main: 'bundles/angular2-modal.umd',
                            defaultExtension: 'js'
                        },

                        "angular2-modal/plugins/bootstrap": {
                            main: 'angular2-modal.bootstrap.umd',
                            defaultExtension: 'js'
                        },

                        "ngx-modal": { "main": "index.js", "defaultExtension": "js" },
                        rxjs: {
                            defaultExtension: 'js'
                        }
                    }
                });
            })(this);
</code>```

I tried other plugins like Dragula and ngx-modal which seems to work fine. Is it something to do with the Angular-tree-component or is it just some build error?

答:
update your Package.json file to latest stable version like I have used angular version 2.4.10 but you may use latest angular version 4.1.3 and its dependent compatible package version

```<code>"dependencies": {
"@angular/animations": "2.4.10",
"@angular/common": "2.4.10",
"@angular/compiler": "2.4.10",
"@angular/core": "2.4.10",
"@angular/forms": "2.4.10",
"@angular/http": "2.4.10",
"@angular/platform-browser": "2.4.10",
"@angular/platform-browser-dynamic": "2.4.10",
"@angular/platform-server": "2.4.10",
"@angular/router": "3.0.1",
"@types/lodash": "^4.14.63",
"angular-tree-component": "3.4.0",
"core-js": "^2.4.1",
"debug": "~2.6.3",
"ejs": "^2.3.3",
"express": "~4.15.2",
"rxjs": "^5.0.0",
"serve-favicon": "~2.4.2",
"twilio": "^2.11.1",
"zone.js": "^0.8.4"
}
</code>```

Body:
I refered this to include the angular-tree-component plugin. I followed the exact steps and get following error while running the application:

Error: (SystemJS) ctorParameters.map is not a function(…)

My package.json file:

          {
            "name": "template2",
            "version": "1.0.0",
            "scripts": {},
            "license": "ISC",
            "dependencies": {
              "@angular/common": "~2.0.1",
              "@angular/compiler": "~2.0.1",
              "@angular/core": "~2.0.1",
              "@angular/forms": "~2.0.1",
              "@angular/http": "~2.0.1",
              "@angular/platform-browser": "~2.0.1",
              "@angular/platform-browser-dynamic": "~2.0.1",
              "@angular/router": "~3.0.1",
              "@angular/upgrade": "~2.0.1",
              "angular-tree-component": "3.6.0",
              "angular2-modal": "^2.0.3",
              "bootstrap": "^3.3.7",
              "core-js": "^2.4.1",
              "ng-lightning": "^1.3.0",
              "ng2-bs3-modal": "^0.10.4",
              "ng2-dragula": "^1.3.1",
              "ng2-modal-dialog": "^1.0.1",
              "ngx-modal": "0.0.29",
              "reflect-metadata": "^0.1.8",
              "rxjs": "5.0.0-beta.12",
              "systemjs": "0.19.39",
              "zone.js": "^0.6.25"
            },
            "devDependencies": {
              "@types/core-js": "^0.9.34",
              "typescript": "^2.0.3",
              "typings": "^1.4.0"
            }
          }

My Systemjs.config.js

            /**
             * System configuration for Angular samples
             * Adjust as necessary for your application needs.
             */
            (function (global) {
                System.config({
                    paths: {
                        // paths serve as alias
                        'npm:': '/node_modules/',
                    },
                    // map tells the System loader where to look for things

                    //defaultJSExtensions: true,  // This is included for Model Popup
                    map: {
                        // our app is within the app folder
                        app: '/Scripts',
                        // angular bundles
                        '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
                        '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
                        '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
                        '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
                        '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
                        '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
                        '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
                        '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

                        /*The following is required by dragula */
                        'dragula': 'node_modules/dragula',
                        'ng2-dragula': 'node_modules/ng2-dragula',
                        'contra': 'node_modules/contra',
                        'atoa': 'node_modules/atoa',
                        'ticky': 'node_modules/ticky',
                        'crossvent': 'node_modules/crossvent/src',
                        'custom-event': 'node_modules/custom-event',
                        /*The following is required by dragula ^*/

                        'angular-tree-component': 'node_modules/angular-tree-component/dist/angular-tree-component.umd.js',

                        //The following is required by PopUp Model
                        "ngx-modal": "node_modules/ngx-modal",
                        // other libraries
                        'rxjs': 'npm:rxjs'
                    },
                    // packages tells the System loader how to load when no filename and/or no extension
                    packages: {
                        app: {
                            main: './main.js',
                            defaultExtension: 'js'
                        },
                        /*The following is required by dragula */
                        'dragula': { main: 'dragula.js', defaultExtension: 'js' },
                        'ng2-dragula': { defaultExtension: 'js' },
                        'contra': { main: 'contra.js', defaultExtension: 'js' },
                        'atoa': { main: 'atoa.js', defaultExtension: 'js' },
                        'ticky': { main: 'ticky.js', defaultExtension: 'js' },
                        'crossvent': { main: 'crossvent.js', defaultExtension: 'js' },
                        'custom-event': { main: 'index.js', defaultExtension: 'js' },
                        /*The following is required by dragula ^*/

                        'angular2-modal': {
                            main: 'bundles/angular2-modal.umd',
                            defaultExtension: 'js'
                        },

                        "angular2-modal/plugins/bootstrap": {
                            main: 'angular2-modal.bootstrap.umd',
                            defaultExtension: 'js'
                        },

                        "ngx-modal": { "main": "index.js", "defaultExtension": "js" },
                        rxjs: {
                            defaultExtension: 'js'
                        }
                    }
                });
            })(this);

I tried other plugins like Dragula and ngx-modal which seems to work fine. Is it something to do with the Angular-tree-component or is it just some build error?

Body:
update your Package.json file to latest stable version like I have used angular version 2.4.10 but you may use latest angular version 4.1.3 and its dependent compatible package version

"dependencies": {
"@angular/animations": "2.4.10",
"@angular/common": "2.4.10",
"@angular/compiler": "2.4.10",
"@angular/core": "2.4.10",
"@angular/forms": "2.4.10",
"@angular/http": "2.4.10",
"@angular/platform-browser": "2.4.10",
"@angular/platform-browser-dynamic": "2.4.10",
"@angular/platform-server": "2.4.10",
"@angular/router": "3.0.1",
"@types/lodash": "^4.14.63",
"angular-tree-component": "3.4.0",
"core-js": "^2.4.1",
"debug": "~2.6.3",
"ejs": "^2.3.3",
"express": "~4.15.2",
"rxjs": "^5.0.0",
"serve-favicon": "~2.4.2",
"twilio": "^2.11.1",
"zone.js": "^0.8.4"
}


问:
replacing a menu for new one from another method on tkinter
First sorry if the title is not the best to explain my problem.
I am trying to do a kind of login where you click on a 'new account' button and then disappear the login buttons made on init method and appear stuffs from createaccount method.

I did this. I tried doing grid_forget() pack_forget() and I am not able to do it yet.
I am working with python 3.
Thanks

```<code>from tkinter import *
class Login:
    def __init__(self, ventana):
        ventana.title("Login - Python")
        ventana.geometry("800x600")
        Label(ventana, text="name: ").grid(column=0, row=0)
        Label(ventana, text="Password: ").grid(column=0, row=1)
        Button(ventana, text="Login").grid(column=0, row=2)
        Button(ventana, text="Create Account", command=self.createaccount).grid(column=0, row=3)
        Button(ventana, text="Exit").grid(column=0, row=4)
    def createaccount(self):
        print("createaccount method executed")
        Label(ventana, text="Name: ").grid(column=2, row=0)
        Label(ventana, text="Password: ").grid(column=2, row=1)
        Label(ventana, text="Repeat Password: ").grid(column=2, row=2)
        Label(ventana, text="Email: ").grid(column=2, row=3)
        Label(ventana, text="Repeat E-mail: ").grid(column=2, row=4)

ventana = Tk()
objeto=Login(ventana)
ventana.mainloop()
</code>```

答:
If you want to use your widgets later in your program you need to store them in a variable.

```<code>def __init__(self, ventana):
    ventana.title("Login - Python")
    ventana.geometry("800x600")
    self.lblName = Label(ventana, text="name: ")
    self.lblPass = Label(ventana, text="Password: ")
    .....
    .....
    self.lblName.grid(column=0, row=0)
    self.lblPass.grid(column=0, row=1)
    .....
    .....
</code>```

Now you can use those widgets any place in your code.

```<code> def createaccount(self):
    self.lblName.grid_forget()
    self.lblPass.grid_forget()
    #and so on...
</code>```

Note that, creation of a widget and placing them with grid are on seperate lines.

Body:
First sorry if the title is not the best to explain my problem.
I am trying to do a kind of login where you click on a 'new account' button and then disappear the login buttons made on init method and appear stuffs from createaccount method.

I did this. I tried doing grid_forget() pack_forget() and I am not able to do it yet.
I am working with python 3.
Thanks

from tkinter import *
class Login:
    def __init__(self, ventana):
        ventana.title("Login - Python")
        ventana.geometry("800x600")
        Label(ventana, text="name: ").grid(column=0, row=0)
        Label(ventana, text="Password: ").grid(column=0, row=1)
        Button(ventana, text="Login").grid(column=0, row=2)
        Button(ventana, text="Create Account", command=self.createaccount).grid(column=0, row=3)
        Button(ventana, text="Exit").grid(column=0, row=4)
    def createaccount(self):
        print("createaccount method executed")
        Label(ventana, text="Name: ").grid(column=2, row=0)
        Label(ventana, text="Password: ").grid(column=2, row=1)
        Label(ventana, text="Repeat Password: ").grid(column=2, row=2)
        Label(ventana, text="Email: ").grid(column=2, row=3)
        Label(ventana, text="Repeat E-mail: ").grid(column=2, row=4)

ventana = Tk()
objeto=Login(ventana)
ventana.mainloop()

Body:
If you want to use your widgets later in your program you need to store them in a variable.

def __init__(self, ventana):
    ventana.title("Login - Python")
    ventana.geometry("800x600")
    self.lblName = Label(ventana, text="name: ")
    self.lblPass = Label(ventana, text="Password: ")
    .....
    .....
    self.lblName.grid(column=0, row=0)
    self.lblPass.grid(column=0, row=1)
    .....
    .....

Now you can use those widgets any place in your code.

 def createaccount(self):
    self.lblName.grid_forget()
    self.lblPass.grid_forget()
    #and so on...

Note that, creation of a widget and placing them with grid are on seperate lines.


问:
Can I deploy an app to Google Assistant without using Google's AI platform (Api.ai)
I'd like to deploy an app to Google Assistant. But, I'd like to use a different AI backend instead of api.ai.

Does anyone know if it's even possible? And how?

Or am I stuck with api.ai if I want to work with Google Assistant?

Thanks

答:
You can actually use anything in the backend, from a simple string-matching approach to another NLU (wit.ai, luis.ai, Amazon Lex, Rasa, etc.).

However, if you're not using any of the ones supported by Google, you'll have to write the software that bridges between the Google Actions SDK and your other conversation platform.

Like Prisoner said, you'll pretty much have to make your own action package detailed here: https://developers.google.com/actions/sdk/

If you're doing a simplistic string-matching approach, the ActionsSDK can do really basic intent matching and entity recognition by itself without additional processing, but for more complicated things, you'll need a proper NLU.

If you're forwarding the input text to another service, you can simply use the TEXT standard intent (actions.intent.TEXT), grab the raw text and forward it along to your fulfillment server. From there, you can process the text with your NLU, and build a response to send back to the ActionsSDK. You can pretty much ignore everything else about the ActionsSDK.

One last thing: if your backend is already using Node.js, you can take a slight shortcut and build a wrapper around your backend with the Node.js Client Library, otherwise, you'll have to implement the interface from scratch.

Good luck!


问:
Performance issues while DELETE operation
I have a simple delete statement like this:

```<code>DELETE FROM MY_TABLE WHERE ID='Something'
</code>```

This deletes only one record for that ID, which is taking more than a minute since MY_TABLE is referenced by a Foreign Key created on another table that has around 40 millions records and the DELETE operation checks existence of this ID in that large table.

One way is to drop/re-create this Foreign Key, but this DELETE operation gets performed by the application users and I can not just drop/re-create this FK on the fly unless it could have been an off-hours operation.

Can anyone help?

答:
So there's an excellent SO question that you can refer
SQL delete performance.

Apart from the suggestions on the question like

Possible causes:

1) cascading delete operations

2) trigger(s)

3) the type of your primary key column is something other than an
  integer, thereby forcing a type conversion on each pk value to do the
  comparison. this requires a full table scan.

4) does your query really end in a dot like you posted it in the
  question? if so, the number may considered to be a floating point
  number instead of an integer, thereby causing a type conversion
  similar to 3)

5) your delete query is waiting for some other slow query to release a
  lock

Importantly:

We should definitely look into triggers. You should try to do away with triggers if there are any.

Also try to see if there are index on the FK in the other large table.

See if you can convert your query to a CASCADE delete to deleting from large table and then deleting from the MY_TABLE like in query below

DELETE FROM LARGE_TABLE WHERE LT.FK IN (SELECT PK FROM MY_TABLE WHERE ID='Something')
GO
DELETE FROM MY_TABLE WHERE ID='Something'

Also see the performance plan for first query on LARGE_TABLE.

You should try to replace WHERE ID='Something' with an INT key operation like WHERE anotherID=34. Basically instead of using a string in WHERE try to use integers for deletion. It is hard to believe that ID column in varchar. You should have a Primary KEY clustered indexed column in MY_Table, and use this key in WHERE clause.

Another way to improve performance is to drop the FK contraint between tables. You can always periodically do garbage deletion from LARGE_TABLE followed by Index rebuilding.

Another simpler way is to introduce mapping table between these tables. Where say a table named Map_My_Table_Large_Table exists which keeps following columns (FK column from My_Table, FK column from Large_Table). You can shift your CASCADE delete to this table.

Body:
I have a simple delete statement like this:

DELETE FROM MY_TABLE WHERE ID='Something'

This deletes only one record for that ID, which is taking more than a minute since MY_TABLE is referenced by a Foreign Key created on another table that has around 40 millions records and the DELETE operation checks existence of this ID in that large table.

One way is to drop/re-create this Foreign Key, but this DELETE operation gets performed by the application users and I can not just drop/re-create this FK on the fly unless it could have been an off-hours operation.

Can anyone help?


问:
sed command with -i option failing on Mac, but works on Linux
I've successfully used the following sed command to search/replace text in Linux:

```<code>sed -i 's/old_link/new_link/g' *
</code>```

However, when I try it on my Mac OS X, I get:

"command c expects \ followed by text"

I thought my Mac runs a normal BASH shell.  What's up?

EDIT:

According to @High Performance, this is due to Mac sed being of a different (BSD) flavor, so my question would therefore be how do I replicate this command in BSD sed?

EDIT:

Here is an actual example that causes this:

```<code>sed -i 's/hello/gbye/g' *
</code>```

答:
Here's how to apply environment variables to template file (no backup need).

1. Create template with {{FOO}} for later replace.

```<code>echo "Hello {{FOO}}" > foo.conf.tmpl
</code>```

2. Replace {{FOO}} with FOO variable and output to new foo.conf file

```<code>FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf
</code>```

Working both macOS 10.12.4 and Ubuntu 14.04.5

Body:
I've successfully used the following sed command to search/replace text in Linux:

sed -i 's/old_link/new_link/g' *

However, when I try it on my Mac OS X, I get:

"command c expects \ followed by text"

I thought my Mac runs a normal BASH shell.  What's up?

EDIT:

According to @High Performance, this is due to Mac sed being of a different (BSD) flavor, so my question would therefore be how do I replicate this command in BSD sed?

EDIT:

Here is an actual example that causes this:

sed -i 's/hello/gbye/g' *

Body:
Here's how to apply environment variables to template file (no backup need).

1. Create template with {{FOO}} for later replace.

echo "Hello {{FOO}}" > foo.conf.tmpl

2. Replace {{FOO}} with FOO variable and output to new foo.conf file

FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf

Working both macOS 10.12.4 and Ubuntu 14.04.5


问:
How to calculate the sentence similarity using word2vec model of gensim with python
According to the Gensim Word2Vec, I can use the word2vec model in gensim package to calculate the similarity between 2 words.

e.g.

```<code>trained_model.similarity('woman', 'man')
0.73723527
</code>```

However, the word2vec model fails to predict the sentence similarity. I find out the LSI model with sentence similarity in gensim, but, which doesn't seem that can be combined with word2vec model. The length of corpus of each sentence I have is not very long (shorter than 10 words).  So, are there any simple ways to achieve the goal?

答:
I would like to update the existing solution to help the people who are going to calculate the semantic similarity of sentences.

Step 1:

Load the suitable model using gensim and calculate the word vectors for words in the sentence and store them as a word list

Step 2 :
Computing the sentence vector

The calculation of semantic similarity between sentences was difficult before but recently a paper named "A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SENTENCE
EMBEDDINGS" was proposed which suggests a simple approach by computing the weighted average of word vectors in the sentence and then remove the projections of the average vectors on their first principal component.Here the weight of a word w is a/(a + p(w)) with a being a parameter and p(w) the (estimated) word frequency called smooth inverse frequency.this method performing significantly better.

A simple code to calculate the sentence vector using SIF(smooth inverse frequency) the method proposed in the paper has been given here

Step 3:
using sklearn cosine_similarity load two vectors for the sentences and compute the similarity.

This is the most simple and efficient method to compute the sentence similarity.

Body:
According to the Gensim Word2Vec, I can use the word2vec model in gensim package to calculate the similarity between 2 words.

e.g.

trained_model.similarity('woman', 'man')
0.73723527

However, the word2vec model fails to predict the sentence similarity. I find out the LSI model with sentence similarity in gensim, but, which doesn't seem that can be combined with word2vec model. The length of corpus of each sentence I have is not very long (shorter than 10 words).  So, are there any simple ways to achieve the goal?


问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答: You can open Xcode Help -> Run and debug -> Network debugging for more info. Hope it helps.</p>


问:
use distinct with multiple columns in laravel
my table structure is as below

```<code>date        seller  unit    price   total
05-06-17    abc     14      700     9800
05-06-17    pqr     12      600     7200
05-06-17    abc     10      520     5200
06-06-17    abc     10      600     6000
06-06-17    pqr     15      520     7800
06-06-17    pqr     16      520     8320
</code>```

I need to fetch record like

```<code>1) 'date' = '05-06-2017', 'seller' = 'abc', 'total' = '15000'
2) 'date' = '05-06-2017', 'seller' = 'pqr', 'total' = '7200'
3) 'date' = '06-06-2017', 'seller' = 'abc', 'total' = '6000'
4) 'date' = '06-06-2017', 'seller' = 'pqr', 'total' = '16120'
</code>```

I need data from database in date wise. seller abc has two entry in a table for date 05-06-2017 so I need total of that day for seller abc as well pqr same things for the second date for all seller

答:
Whenever we have multiple rows with same data that needs to be merged together in final output, we use group by functionality of mySQL.

so in your case you can use laravel query builder to do it in this way.

```<code> DB::table('orders')->select('date', 'seller', DB::raw('SUM(total) as total'))
    ->groupBy('seller')
    ->groupBy('date')
    ->get();
</code>```

Explanation

DB::table('orders')->select('date', 'seller', DB::raw('SUM(total) as total'))
will query our orders table in our database & then fetch our provided columns i.e. date, seller and sum of total column as total

 ->groupBy('seller')->groupBy('date') It will merge the multiple records of same seller in same date.

 ->get(); we are get getting our data from the query.

Body:
my table structure is as below

date        seller  unit    price   total
05-06-17    abc     14      700     9800
05-06-17    pqr     12      600     7200
05-06-17    abc     10      520     5200
06-06-17    abc     10      600     6000
06-06-17    pqr     15      520     7800
06-06-17    pqr     16      520     8320

I need to fetch record like

1) 'date' = '05-06-2017', 'seller' = 'abc', 'total' = '15000'
2) 'date' = '05-06-2017', 'seller' = 'pqr', 'total' = '7200'
3) 'date' = '06-06-2017', 'seller' = 'abc', 'total' = '6000'
4) 'date' = '06-06-2017', 'seller' = 'pqr', 'total' = '16120'

I need data from database in date wise. seller abc has two entry in a table for date 05-06-2017 so I need total of that day for seller abc as well pqr same things for the second date for all seller

Body:
Whenever we have multiple rows with same data that needs to be merged together in final output, we use group by functionality of mySQL.

so in your case you can use laravel query builder to do it in this way.

 DB::table('orders')->select('date', 'seller', DB::raw('SUM(total) as total'))
    ->groupBy('seller')
    ->groupBy('date')
    ->get();

Explanation

DB::table('orders')->select('date', 'seller', DB::raw('SUM(total) as total'))
will query our orders table in our database & then fetch our provided columns i.e. date, seller and sum of total column as total

 ->groupBy('seller')->groupBy('date') It will merge the multiple records of same seller in same date.

 ->get(); we are get getting our data from the query.


问:
Sharing settings on Visual Studio Code installations
I casually use VS Code at both work and home. Is there any easy way to share settings, themes, shortcuts, snippets, extensions, etc. between multiple installations?</p>

答:
I use the Settings Sync extension to sync my settings.

If you don't want an extension, you can manually copy the settings files from ...AppData\Roaming\Code\User\


问:
Querying a nested array in Elasticsearch
I have the following data index in Elasticsearch with the following syntax:

```<code>PUT /try1
{
"mappings" : {
  "product" : {
   "properties" : {
     "name": { "type" : "text" },
     "categories": {
       "type": "nested",
       "properties": {
         "range":{"type":"text"}
       }
     }
   }
  }
 }
}
</code>```

The range type has an array of words:["high","medium","low"]
I need to access the range element inside the nested category. I tried using the following syntax:

```<code>GET /try1/product/_search
{
    "query": {
        "nested" : {
            "path" : "categories",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"categories.range": "low"} }
                    ]
                }
            }
        }
    }

}
</code>```

However, I am getting an error with the message:
 "reason": """failed to create query:...

Can someone please offer a solution to this?

答:
```<code>{
    "query": {
        "nested" : {
            "path" : "categories",
            "query" : {
                "bool" : {
                    "must" : [
                    { categories.range": "low"}
                    ]
                }
            }
        }
    }
}
</code>```

<p>This worked perfectly </p>

Body:
I have the following data index in Elasticsearch with the following syntax:

PUT /try1
{
"mappings" : {
  "product" : {
   "properties" : {
     "name": { "type" : "text" },
     "categories": {
       "type": "nested",
       "properties": {
         "range":{"type":"text"}
       }
     }
   }
  }
 }
}

The range type has an array of words:["high","medium","low"]
I need to access the range element inside the nested category. I tried using the following syntax:

GET /try1/product/_search
{
    "query": {
        "nested" : {
            "path" : "categories",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"categories.range": "low"} }
                    ]
                }
            }
        }
    }

}

However, I am getting an error with the message:
 "reason": """failed to create query:...

Can someone please offer a solution to this?

Body:
{
    "query": {
        "nested" : {
            "path" : "categories",
            "query" : {
                "bool" : {
                    "must" : [
                    { categories.range": "low"}
                    ]
                }
            }
        }
    }
}

This worked perfectly


问:
Race condition on Pod restart
We have a smaller issue when restarting pods when other pods connect there through a service (with ClusterIP). When the pod goes down there is a small timespan (~200ms) where some client requests fail, because they still try to connect to the pod which just went down. This results in some "Connection Refused" errors. We can avoid it by adding a preStop hook which sleeps a second. Unfortunately, it's ugly to do this for every deployment.

Is this maybe a known issue? Any idea how to solve this in general?

To me it looks like some kind of race condition (aka the pod is gone before it's properly deregistered from its endpoint)

We're using Kubernetes v1.5.3.

This is what the workaround looks like (simplified):

```<code>apiVersion: apps/v1beta1
kind: StatefulSet

spec:
  template:
    spec:
      containers:
      - name: solr
        lifecycle:
          preStop:
            exec:
              command:
              - /bin/sleep
              - "1"
</code>```

The example in the docs actually shows the issue. It begins to shutdown the process and removing the endpoint at the same time. So it probably already shutdown the before the endpoint is registered.

答:
I found a post saying a common pitfall that could be your case:

Let’s say your Dockerfile ends with a CMD in the shell form:

CMD myapp

The shell form runs the command with /bin/sh -c myapp, so the process
  that will get the SIGTERM is actually /bin/sh and not its child myapp.
  Depending on the actual shell you’re running, it could or could not
  pass the signal to its children.

It probably being your app was killed violently causing the ~200ms connection fail. Maybe try the options suggest in the article?

Title: Race condition on Pod restart

Body:
We have a smaller issue when restarting pods when other pods connect there through a service (with ClusterIP). When the pod goes down there is a small timespan (~200ms) where some client requests fail, because they still try to connect to the pod which just went down. This results in some "Connection Refused" errors. We can avoid it by adding a preStop hook which sleeps a second. Unfortunately, it's ugly to do this for every deployment.

Is this maybe a known issue? Any idea how to solve this in general?

To me it looks like some kind of race condition (aka the pod is gone before it's properly deregistered from its endpoint)

We're using Kubernetes v1.5.3.

This is what the workaround looks like (simplified):

apiVersion: apps/v1beta1
kind: StatefulSet

spec:
  template:
    spec:
      containers:
      - name: solr
        lifecycle:
          preStop:
            exec:
              command:
              - /bin/sleep
              - "1"

The example in the docs actually shows the issue. It begins to shutdown the process and removing the endpoint at the same time. So it probably already shutdown the before the endpoint is registered.


问:
Converting a formatted date to another in PHP
I've a date in this format: Tuesday 11th October, 2016
stored in a php varaible $pastdate

I want to convert this to:
2016-10-11 23:59:59

I'm using this line of code:

```<code>$newDate = date("Y-m-d", strtotime($pastDate)).' 23:59:59';
</code>```

However, the output of $newDate is:
2017-10-17 23:59:59

Can anyone explain why this is happening and how I should better format my code?
Thanks in advance.

答:
use the date function and pass the parameters for hour, minute and second to get the complete date and time</p>

```<code>$newDate = date("Y-m-d H:i:s", strtotime($pastDate));
</code>```

Body:
I've a date in this format: Tuesday 11th October, 2016
stored in a php varaible $pastdate

I want to convert this to:
2016-10-11 23:59:59

I'm using this line of code:

$newDate = date("Y-m-d", strtotime($pastDate)).' 23:59:59';

However, the output of $newDate is:
2017-10-17 23:59:59

Can anyone explain why this is happening and how I should better format my code?
Thanks in advance.

Body:
use the date function and pass the parameters for hour, minute and second to get the complete date and time

$newDate = date("Y-m-d H:i:s", strtotime($pastDate));


问:
Changing selected TabBarItem font iOS
I have a TabBar. I am trying to style it so that the titles on the TabBarItems have different fonts for the normal state and the selected state. For normal state I want Helvetica Neue Light and for the selected state I want Helvetica Neue Medium. No matter what I do, I can't seem to get the fonts to be different for these two states. The color changing works fine. Here is what I currently have:

```<code>  // Set the tab bar title appearance for normal state.
  [[UITabBarItem appearance] setTitleTextAttributes:@{
     NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light"
                                          size:16],
     NSForegroundColorAttributeName: [CMK8Colors grayColor]
   }
                                           forState:UIControlStateNormal];

  // Set the tab bar title appearance for selected state.
  [[UITabBarItem appearance] setTitleTextAttributes:@{
     NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Medium"
                                          size:16],
     NSForegroundColorAttributeName: [CMK8Colors blueColor]
   }
                                           forState:UIControlStateSelected];
</code>```

Please help.

答:
@Acey´s answer in Swift 3:</p>

```<code>    override var selectedViewController: UIViewController? {
    didSet {

        guard let viewControllers = viewControllers else {
            return
        }

        for viewController in viewControllers {

            if viewController == selectedViewController {

                let selected: [String: AnyObject] =
                    [NSFontAttributeName: UIFont.systemFont(ofSize: 11, weight: UIFontWeightHeavy),
                     NSForegroundColorAttributeName: UIColor.red]

                viewController.tabBarItem.setTitleTextAttributes(selected, for: .normal)

            } else {

                let normal: [String: AnyObject] =
                    [NSFontAttributeName: UIFont.systemFont(ofSize: 11),
                     NSForegroundColorAttributeName: UIColor.blue]

                viewController.tabBarItem.setTitleTextAttributes(normal, for: .normal)

            }
        }
    }
}
</code>```

Title: Changing selected TabBarItem font iOS

Body:
I have a TabBar. I am trying to style it so that the titles on the TabBarItems have different fonts for the normal state and the selected state. For normal state I want Helvetica Neue Light and for the selected state I want Helvetica Neue Medium. No matter what I do, I can't seem to get the fonts to be different for these two states. The color changing works fine. Here is what I currently have:

  // Set the tab bar title appearance for normal state.
  [[UITabBarItem appearance] setTitleTextAttributes:@{
     NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light"
                                          size:16],
     NSForegroundColorAttributeName: [CMK8Colors grayColor]
   }
                                           forState:UIControlStateNormal];

  // Set the tab bar title appearance for selected state.
  [[UITabBarItem appearance] setTitleTextAttributes:@{
     NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Medium"
                                          size:16],
     NSForegroundColorAttributeName: [CMK8Colors blueColor]
   }
                                           forState:UIControlStateSelected];

Please help.

Body:
@Acey´s answer in Swift 3:

    override var selectedViewController: UIViewController? {
    didSet {

        guard let viewControllers = viewControllers else {
            return
        }

        for viewController in viewControllers {

            if viewController == selectedViewController {

                let selected: [String: AnyObject] =
                    [NSFontAttributeName: UIFont.systemFont(ofSize: 11, weight: UIFontWeightHeavy),
                     NSForegroundColorAttributeName: UIColor.red]

                viewController.tabBarItem.setTitleTextAttributes(selected, for: .normal)

            } else {

                let normal: [String: AnyObject] =
                    [NSFontAttributeName: UIFont.systemFont(ofSize: 11),
                     NSForegroundColorAttributeName: UIColor.blue]

                viewController.tabBarItem.setTitleTextAttributes(normal, for: .normal)

            }
        }
    }
}


问:
Transparent background appears for the dynamic columns in grid
I am developing a grid structure using div layout in my application. The columns and rows are not fixed, they are dynamic, being fetched from the json data in AngularJS.

So, it should scroll both horizontally as well as vertically, if the columns or rows or both extend beyond the available width.

I have handled it using following CSS:

```<code>.wrapper {
  white-space: nowrap;
  overflow-x: auto;
}
</code>```

The issue is that, it doesn't applies the background to the columns and rows which are beyond the grid's width.

Expectation: Both the header i.e. column and data-list i.e. rows, should be able to inherit their respective background colors.

Demo

答:
Change your CSS

```<code>.header .display-data {
  background: lightblue;
}

.data-list .display-data {
  background: white;
}
</code>```

See updated DEMO

Body:
I am developing a grid structure using div layout in my application. The columns and rows are not fixed, they are dynamic, being fetched from the json data in AngularJS.

So, it should scroll both horizontally as well as vertically, if the columns or rows or both extend beyond the available width.

I have handled it using following CSS:

.wrapper {
  white-space: nowrap;
  overflow-x: auto;
}

The issue is that, it doesn't applies the background to the columns and rows which are beyond the grid's width.

Expectation: Both the header i.e. column and data-list i.e. rows, should be able to inherit their respective background colors.

Demo

Body:
Change your CSS

.header .display-data {
  background: lightblue;
}

.data-list .display-data {
  background: white;
}

See updated DEMO


问:
How to dynamically choose the configurations based on the environment in JAVA?
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

```<code>package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}
</code>```

In my code I'm manually commenting out the configuration!

答:
You should lookup the system dependend values from a properties store (e.g. a properties file which is handled by Javas Properties class).

But you should not provide all systems information in the same file.

You should have separate files (with the same name) an have your deployment process copying the file for the target system to the expected location.

This way you enable operations team to manipulate (or preconfigue) a properties file with data you (as a developer) should not know, eg. passwords for high security systems...

Body:
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}

In my code I'm manually commenting out the configuration!


问:
The term 'Invoke-WebRequest' is not recognized as the name of a cmdlet
I've got problem with executing Invoke-WebRequest cmdlet. I read that ~100% case of that scenario is PS version lower than 3, but it's not my case:

```<code>Name                           Value
----                           -----
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
CLRVersion                     4.0.30319.34011
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.10208.0
PSVersion                      5.0.10208.0
SerializationVersion           1.1.0.1
</code>```

I can add that I'm using Windows 10 IoT Core version of OS. In fact my main purpose is execution of simple web request, but I am interested why this cmdlet is not working, especially if more of them won't be ;/ I suppose it can be some windows feature like switch to turn on, but its just my guess.

Update

As far as I compared available cmdlets for certain modules, and preloaded assemblies between my regular system and an IoT version, it looks like the latter version is cut somehow, but I still didn't see any docs for that.

答:
Using -UseBasicParsing option in the command works. The following is part of the command's documentation

-UseBasicParsing

Indicates that the cmdlet uses the response object for HTML content without Document Object Model (DOM) parsing.

This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

Body:
I've got problem with executing Invoke-WebRequest cmdlet. I read that ~100% case of that scenario is PS version lower than 3, but it's not my case:

Name                           Value
----                           -----
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
CLRVersion                     4.0.30319.34011
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.10208.0
PSVersion                      5.0.10208.0
SerializationVersion           1.1.0.1

I can add that I'm using Windows 10 IoT Core version of OS. In fact my main purpose is execution of simple web request, but I am interested why this cmdlet is not working, especially if more of them won't be ;/ I suppose it can be some windows feature like switch to turn on, but its just my guess.

Update

As far as I compared available cmdlets for certain modules, and preloaded assemblies between my regular system and an IoT version, it looks like the latter version is cut somehow, but I still didn't see any docs for that.


问:
Lucene not indexing String field with value "this"
I am adding the document to lucene index as follows:

```<code>Document doc = new Document();
String stringObj = (String)field.get(obj);
doc.add(new TextField(fieldName, stringObj.toLowerCase(), org.apache.lucene.document.Field.Store.YES));
indexWriter.addDocument(doc);
</code>```

I am doing a wild card search as follows:

```<code>searchTerm = "*" + searchTerm + "*";
term = new Term(field, sTerm.toLowerCase());
Query query = new WildcardQuery(term);
TotalHitCountCollector collector = new TotalHitCountCollector();
indexSearcher.search(query, collector);
if(collector.getTotalHits() > 0){
    TopDocs hits = indexSearcher.search(query, collector.getTotalHits());
}
</code>```

When I have a string with a "this" value, it is not getting added to the index, hence i do not get the result on searching by "this". I am using a StandardAnalyzer.

答: Common terms of English language like prepositions, pronouns etc are marked as stop words and omitted before indexing. You can define a custom analyzer or custom stop word list for your analyzer. That way you will be able to omit words that you don't want to be indexed and keep the stop words that you need. </p>

Body:
I am adding the document to lucene index as follows:

Document doc = new Document();
String stringObj = (String)field.get(obj);
doc.add(new TextField(fieldName, stringObj.toLowerCase(), org.apache.lucene.document.Field.Store.YES));
indexWriter.addDocument(doc);

I am doing a wild card search as follows:

searchTerm = "*" + searchTerm + "*";
term = new Term(field, sTerm.toLowerCase());
Query query = new WildcardQuery(term);
TotalHitCountCollector collector = new TotalHitCountCollector();
indexSearcher.search(query, collector);
if(collector.getTotalHits() > 0){
    TopDocs hits = indexSearcher.search(query, collector.getTotalHits());
}

When I have a string with a "this" value, it is not getting added to the index, hence i do not get the result on searching by "this". I am using a StandardAnalyzer.


问:
Load script javascript
I'm using 3 html, 1 with the header, 1 with footer, and another with the base of everything.
I am loading the header and footer with the following code

```<code>jQuery(document).ready(function ($) {
    $('#header-load').load('/app/templates/header.html', function () {
        console.log('header loaded')
    });
    $('#footer-load').load('/app/templates/footer.html', function () {
        console.log('footer loaded')
    });
    $('.dropdown').on('show.bs.dropdown', function (e) {
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
    });

    $('.dropdown').on('hide.bs.dropdown', function (e) {
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
    });

})
</code>```

In the base html, this is the following

```<code><!DOCTYPE html>
<html class="no-focus" lang="en">
<head>
    <meta charset="utf-8">
    <title>Home</title>
    <link rel="stylesheet" id="css-main" href="/public/css/app.css">
    <!-- END Stylesheets -->
</head>
<body>
    <!-- Page Container -->
    <div id="page-container" class="">
        <!-- Header -->
        <div id="header-load"></div>
        <!-- END Header -->

        <!-- Main Container -->
        <main id="main-container">

        </main>
        <!-- END Main Container -->

        <!-- Footer -->
        <div id="footer-load"></div>
        <!-- END Footer -->
    </div>
    <!-- END Page Container -->

    <!-- JS-->
    <script src="/public/library/jquery/dist/jquery.min.js"></script>
    <script src="/public/library/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="/public/js/app.js"></script>
</body>

</html>
</code>```

I have a function in app.js to load into the header.html, but it does not work..

Load the header and footer but the other function does not

答:
.load work async like ajax, you must wait for request complete then find elements and define events.

```<code>jQuery(document).ready(function ($) {
$('#header-load').load('/app/templates/header.html', function () {
    console.log('header loaded')
    $('#footer-load').load('/app/templates/footer.html', function () {
        console.log('footer loaded')
        $('.dropdown').on('show.bs.dropdown', function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
        });

        $('.dropdown').on('hide.bs.dropdown', function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
        });
    });
})
});
</code>```

Title: Load script javascript

Body:
I'm using 3 html, 1 with the header, 1 with footer, and another with the base of everything.
I am loading the header and footer with the following code

jQuery(document).ready(function ($) {
    $('#header-load').load('/app/templates/header.html', function () {
        console.log('header loaded')
    });
    $('#footer-load').load('/app/templates/footer.html', function () {
        console.log('footer loaded')
    });
    $('.dropdown').on('show.bs.dropdown', function (e) {
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
    });

    $('.dropdown').on('hide.bs.dropdown', function (e) {
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
    });

})

In the base html, this is the following

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Home</title>
    <link rel="stylesheet" id="css-main" href="/public/css/app.css">

I have a function in app.js to load into the header.html, but it does not work..

Load the header and footer but the other function does not

Body:
.load work async like ajax, you must wait for request complete then find elements and define events.

jQuery(document).ready(function ($) {
$('#header-load').load('/app/templates/header.html', function () {
    console.log('header loaded')
    $('#footer-load').load('/app/templates/footer.html', function () {
        console.log('footer loaded')
        $('.dropdown').on('show.bs.dropdown', function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
        });

        $('.dropdown').on('hide.bs.dropdown', function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
        });
    });
})
});


问:
How to find direction of a vector path
I have a vector path (made up from lineto, curveTo points) and I want to determine its direction (clockwise, anticlockwise).

Is there any algorithm which can be used for the same?

The reason I want to do this is that I am getting two paths from different functions; one is always clockwise but the other function returns anticlockwise paths sometimes; when I combine these two paths and fill the resultant path then the non-zero winding fill rule creates a hole in the regions where the path overlaps.

So I am trying to solve the problem by converting all paths to clockwise direction before combining them.

答:
Pick any point in the interior of the path component, then use the fill rule to determine whether its winding number is +1 or −1:

Draw a ray from the point out to infinity

Start with a count of zero

Add 1 every time a path segment crosses the ray from left to right

Subtract 1 every time a path segment crosses the ray from right to left

(If the path component is simple there will only be one crossing. If the path is not simple, i.e. it crosses itself, then it does not mean anything to say if it is clockwise or not.)

Then, since you want clockwise components you should expect a count of +1. A count of −1 indicates that the component is inside out.

Title: How to find direction of a vector path


问:
python manage.py startapp is not creating migrations directory
python manage.py startapp polls. I tried this command but it creates only python files and it does not create the migrations directory. And the django version that i am using is 1.6.11
here is the directory structure of polls directory created by above command

```<code>__init__.py
admin.py
models.py
test.py
urls.py
views.py
</code>```

答:
Built-in support for migrations was added in Django 1.7.

https://docs.djangoproject.com/en/1.11/releases/1.7/#schema-migrations

For Django < 1.7, use south.

South documentation: http://south.readthedocs.io/en/latest/index.html

Hope this helps.

Body:
python manage.py startapp polls. I tried this command but it creates only python files and it does not create the migrations directory. And the django version that i am using is 1.6.11
here is the directory structure of polls directory created by above command

__init__.py
admin.py
models.py
test.py
urls.py
views.py


答:
Add the following into your application.properties file:

```<code>from.email.id = xx12@xyz.com
from.name = xyz

...
</code>```

e.t.c

You define those properties before you start your application (depending on your evn in your case).
Of course you need to inject them into your class as follows:

```<code>@Value("${from.email.id}")
private String fromEmailId;
</code>```

So now the fromEmailId will have the value given into the application.properties file.

Good luck.

EDIT:

If you want a little bit higher level of security you can use jasypt to cript your passwords into your applicaiton.properties file. At the end the password will look something like this:

```<code>smtp.password = ENC(5KZL2q+Ute21FzCsJy/h0aIp75TZgHBHx8L11R+jTJs0=)
</code>```

Title: How to dynamically choose the configurations based on the environment in JAVA?

Body:
Add the following into your application.properties file:

from.email.id = xx12@xyz.com
from.name = xyz

...

e.t.c

You define those properties before you start your application (depending on your evn in your case).
Of course you need to inject them into your class as follows:

@Value("${from.email.id}")
private String fromEmailId;

So now the fromEmailId will have the value given into the application.properties file.

Good luck.

EDIT:

If you want a little bit higher level of security you can use jasypt to cript your passwords into your applicaiton.properties file. At the end the password will look something like this:

smtp.password = ENC(5KZL2q+Ute21FzCsJy/h0aIp75TZgHBHx8L11R+jTJs0=)


问:
Sharing a local image on Google+
Has anyone tried to use the code here:
https://developers.google.com/+/mobile/ios/share/basic-share

My impression is that it makes it possible to share a URL publicly available on the net, but not a URL to a local image (that I would like to share). I hope someone will tell me I am wrong and show me why.

When I try it in order to share an image on Google+, it complains with a message saying:
"That link is invalid"

I use this kind of code to make the local URL (as I always do):
    let imageURL = NSURL(string: “MY_LOCAL_URL”

答:
As per documentation there are only 2 params available URL and Language Code.

So for displaying image, it will require to upload image on server, then use that URL.

I wanted to put some text also along with URL, but no documented param available. "text" param is working, but can stop work anytime.

Title: Sharing a local image on Google+


问:
how many times does the user want to play a game c language
I am learning how to write a game I have been given the following rules for the game.

Rule 1: Players must define a minimum number to stop the turn this has to be greater than 10

Rule 2: all point from round are added to the total

Rule 3: If the dice lands on 1 then all points for that round are forfeited

Rule 4: First player to get to 101 points WINS!

I am trying to get the number of games to be inputted in after the user enters how many players there are.

My problem is it ask the user every time I enter the players names depending on how many players I have inputted

Example

How many Players: 3

How many games: 15

Enter Players name: John

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Mary

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Barry

How many games: 15 (I input this number again) I dont need this line here

This is my code for the problem:

```<code>//user inputs value of player_num, here, as you have now//

printf_s("Please type in the number of players: ");
scanf_s("%d", &player_num, sizeof(int));
for (i = 0; i < player_num; i++) {
    //user inputs value of num_game, here, as you have now//
    printf_s("Please type in the number of games: ");
    scanf_s("%d", &num_games, sizeof(int));
    num_games = (j = 1, num_games);

    printf_s("Enter the player's first name: ");
    scanf_s("%s", names[i], 25);
    getchar();
}
printf_s("\n");
for (i = 0; i < player_num; i++)
    printf_s("\n%s", names[i]);
</code>```

答:
your loop has 2 scanf, while you need only one. Put this

printf_s("Please type in the number of games: ");
scanf_s("%d", &num_games, sizeof(int));
num_games = (j = 1, num_games);

in front of your loop, instead of inside it.

```<code>for (i = 0; i < player_num; i++) {

  //user inputs value of num_game, here, as you have now//
  printf_s("Please type in the number of games: ");  // no need for this in the loop
  scanf_s("%d", &num_games, sizeof(int));            // no need for this in the loop
  num_games = (j = 1, num_games);                    // no need for this in the loop

  printf_s("Enter the player's first name: ");
  scanf_s("%s", names[i], 25);
  getchar();
}
</code>```

Body:
I am learning how to write a game I have been given the following rules for the game.

Rule 1: Players must define a minimum number to stop the turn this has to be greater than 10

Rule 2: all point from round are added to the total

Rule 3: If the dice lands on 1 then all points for that round are forfeited

Rule 4: First player to get to 101 points WINS!

I am trying to get the number of games to be inputted in after the user enters how many players there are.

My problem is it ask the user every time I enter the players names depending on how many players I have inputted

Example

How many Players: 3

How many games: 15

Enter Players name: John

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Mary

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Barry

How many games: 15 (I input this number again) I dont need this line here

This is my code for the problem:

//user inputs value of player_num, here, as you have now//

printf_s("Please type in the number of players: ");
scanf_s("%d", &player_num, sizeof(int));
for (i = 0; i < player_num; i++) {
    //user inputs value of num_game, here, as you have now//
    printf_s("Please type in the number of games: ");
    scanf_s("%d", &num_games, sizeof(int));
    num_games = (j = 1, num_games);

    printf_s("Enter the player's first name: ");
    scanf_s("%s", names[i], 25);
    getchar();
}
printf_s("\n");
for (i = 0; i < player_num; i++)
    printf_s("\n%s", names[i]);

Body:
your loop has 2 scanf, while you need only one. Put this

printf_s("Please type in the number of games: ");
scanf_s("%d", &num_games, sizeof(int));
num_games = (j = 1, num_games);

in front of your loop, instead of inside it.

for (i = 0; i < player_num; i++) {

  //user inputs value of num_game, here, as you have now//
  printf_s("Please type in the number of games: ");  // no need for this in the loop
  scanf_s("%d", &num_games, sizeof(int));            // no need for this in the loop
  num_games = (j = 1, num_games);                    // no need for this in the loop

  printf_s("Enter the player's first name: ");
  scanf_s("%s", names[i], 25);
  getchar();
}


问:
How to set a default value for MvxSpinner

I am trying to modify the MvxSpinner to set a default value saying
"Select a Value".

I referred this solution to override the methods, but I am
not able to override the methods.

How to achieve this in a elegant way

XML

```<code><Mvx.MvxSpinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:background="@drawable/dropdown"
        local:MvxBind="ItemsSource Cruise; SelectedItem CruiseLineSelected; Visible CruiseAndShipSelectionVisibility"
        local:MvxItemTemplate="@layout/spinner_cruise_list"
        local:MvxDropDownItemTemplate="@layout/spinner_cruise_list"
        android:text="Select a cruise"
        android:layout_marginBottom="20dp"
        android:id="@+id/mvxSpinnerCruise" />
</code>```

答:
I find a simple solution to set a default text for Spinner and it works fine, I think you can use Mvvm to implement this function by yourself, here is the
code :

```<code> public class MySpinnerAdapter<T> : ArrayAdapter<T>
 {
    private Context mContext;
    private int mTextResourceId;

    public MySpinnerAdapter(Context context, int textViewResourceId):base(context,textViewResourceId)
    {
        mContext = Context;
        mTextResourceId = textViewResourceId;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View view = base.GetView(position, convertView, parent);
        if (position == Count)
        {
            TextView a = (view.FindViewById<TextView>(Android.Resource.Id.Text1));
            a.Text = "";

            TextView b = (view.FindViewById<TextView>(Android.Resource.Id.Text1));
            b.Hint = GetItem(Count).ToString(); //"Hint to be displayed"
        }
        return view;
    }

    public override int Count => (base.Count - 1);
 }
</code>```

When use the it :

```<code>spinner = FindViewById<Spinner>(Resource.Id.spinner);
var adapter = new MySpinnerAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem);

adapter.Add("php");
adapter.Add("java");
adapter.Add("C++");
adapter.Add("C");
adapter.Add("Select a cruise");

spinner.Adapter = adapter;
spinner.SetSelection(adapter.Count); //display hint
</code>```

Here is the Spinner.

Body:
I am trying to modify the MvxSpinner to set a default value saying
"Select a Value".

I referred this solution to override the methods, but I am
not able to override the methods.

How to achieve this in a elegant way

XML

<Mvx.MvxSpinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:background="@drawable/dropdown"
        local:MvxBind="ItemsSource Cruise; SelectedItem CruiseLineSelected; Visible CruiseAndShipSelectionVisibility"
        local:MvxItemTemplate="@layout/spinner_cruise_list"
        local:MvxDropDownItemTemplate="@layout/spinner_cruise_list"
        android:text="Select a cruise"
        android:layout_marginBottom="20dp"
        android:id="@+id/mvxSpinnerCruise" />

Body:
I find a simple solution to set a default text for Spinner and it works fine, I think you can use Mvvm to implement this function by yourself, here is the
code :

 public class MySpinnerAdapter<T> : ArrayAdapter<T>
 {
    private Context mContext;
    private int mTextResourceId;

    public MySpinnerAdapter(Context context, int textViewResourceId):base(context,textViewResourceId)
    {
        mContext = Context;
        mTextResourceId = textViewResourceId;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View view = base.GetView(position, convertView, parent);
        if (position == Count)
        {
            TextView a = (view.FindViewById<TextView>(Android.Resource.Id.Text1));
            a.Text = "";

            TextView b = (view.FindViewById<TextView>(Android.Resource.Id.Text1));
            b.Hint = GetItem(Count).ToString(); //"Hint to be displayed"
        }
        return view;
    }

    public override int Count => (base.Count - 1);
 }

When use the it :

spinner = FindViewById<Spinner>(Resource.Id.spinner);
var adapter = new MySpinnerAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem);

adapter.Add("php");
adapter.Add("java");
adapter.Add("C++");
adapter.Add("C");
adapter.Add("Select a cruise");

spinner.Adapter = adapter;
spinner.SetSelection(adapter.Count); //display hint

Here is the Spinner.


问:
How to get current DB connection name in Cakephp 2.x
I have two(default and test) db connections in my database.php:

```<code>public function __construct() {
        $this->default = array(
            'datasource' => 'Database/Mysql',
            'driver' => 'mysql',
                'persistent' => false,
                'encoding' => 'utf8',
                'prefix' => 'shaufel_',
                'host' => 'localhost',
                'database' => 'db',
                'login' => 'root', /*** replace this ***/
                'password' => 'root', /*** replace this ***/
        );

        //test db
        $this->test = $this->default;
        $this->test['database'] = $this->test['database'].'_test';
    }
</code>```

How can I get the current DB connection NAME in my Model ? That means for example : if(current_db is testDB) do something. I use Cakephp 2.9.7.

答: I found it by myself: $this->getDataSource()->config['database']

Body:
I have two(default and test) db connections in my database.php:

public function __construct() {
        $this->default = array(
            'datasource' => 'Database/Mysql',
            'driver' => 'mysql',
                'persistent' => false,
                'encoding' => 'utf8',
                'prefix' => 'shaufel_',
                'host' => 'localhost',
                'database' => 'db',
                'login' => 'root', /*** replace this ***/
                'password' => 'root', /*** replace this ***/
        );

        //test db
        $this->test = $this->default;
        $this->test['database'] = $this->test['database'].'_test';
    }

How can I get the current DB connection NAME in my Model ? That means for example : if(current_db is testDB) do something. I use Cakephp 2.9.7.


问:
How to release Outlook objects correctly?
I just can't release my Outlook MailItems. After opening 200 Mails the Exchange Sever  returns the maximum open Emails is reached.

I'm remove my UserProperty from all selected Mail.

My Code:

```<code>
foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------

  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}</code>```

Any idea what's wrong?

答:
Try to replace foreach with a for loop and do the following

```<code>GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
</code>```

Also remove all the reference to any outlook COM object that you might be using.

Body:
I just can't release my Outlook MailItems. After opening 200 Mails the Exchange Sever  returns the maximum open Emails is reached.

I'm remove my UserProperty from all selected Mail.

My Code:

foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------

  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}

Any idea what's wrong?

Body:
Try to replace foreach with a for loop and do the following

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Also remove all the reference to any outlook COM object that you might be using.


问:
Looping over a huge list, check string equal to true
I have a requirement as below:

```<code>List<User> userList = listOfUsers(); // Morethan 50,000 users
</code>```

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

答:
You may use Collections ArrayDeque. ArrayDeques will use half of the iteration  to find the active user. In your case </p>

```<code>ArrayDeque sample = new ArrayDeque(userList);

    for(int i=0;i<sample.size();i++){
                if(sample.pollFirst().status.equalsIgnoreCase("A")) {
                    break;
                }

                if(sample.pollLast().status.equalsIgnoreCase("A")) {
                    break;
                }
                if(sample.size()==0) break;

            }
</code>```

Body:
I have a requirement as below:

List<User> userList = listOfUsers(); // Morethan 50,000 users

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

Body:
You may use Collections ArrayDeque. ArrayDeques will use half of the iteration  to find the active user. In your case

ArrayDeque sample = new ArrayDeque(userList);

    for(int i=0;i<sample.size();i++){
                if(sample.pollFirst().status.equalsIgnoreCase("A")) {
                    break;
                }

                if(sample.pollLast().status.equalsIgnoreCase("A")) {
                    break;
                }
                if(sample.size()==0) break;

            }