问:
don't know why os.system code returns 1
I can't find out why my os.system python code returns 1.</p>

```<code>import os
flist =  getFileList("C:/Users/Owner/Desktop/TM/reports")
a = flist[0].replace('.pdf', '.txt')
os.system("pdf2txt.py -o a flist[0]")
</code>```

答:
I think you meant

```<code>import os
flist =  getFileList("C:/Users/Owner/Desktop/TM/reports")
a = flist[0].replace('.pdf', '.txt')
# 1. os.system("pdf2txt.py -o a flist[0]")
# 2. os.system("pdf2txt.py -o a " + "flist[0]")
os.system("pdf2txt.py -o " + a + " " + '"' + flist[0] + '"')
</code>```

The differences between all 3 options are very subtle. In 1,2 python is executing the command with a string literal flist[0] and the other, uncommented option, with the value contained at  flist[0]

Title: don't know why os.system code returns 1

Body:
I can't find out why my os.system python code returns 1.

import os
flist =  getFileList("C:/Users/Owner/Desktop/TM/reports")
a = flist[0].replace('.pdf', '.txt')
os.system("pdf2txt.py -o a flist[0]")

Body:
I think you meant

import os
flist =  getFileList("C:/Users/Owner/Desktop/TM/reports")
a = flist[0].replace('.pdf', '.txt')
# 1. os.system("pdf2txt.py -o a flist[0]")
# 2. os.system("pdf2txt.py -o a " + "flist[0]")
os.system("pdf2txt.py -o " + a + " " + '"' + flist[0] + '"')

The differences between all 3 options are very subtle. In 1,2 python is executing the command with a string literal flist[0] and the other, uncommented option, with the value contained at  flist[0]


来源: stackexchange

问:
Is it OK return http status 404 in the POST?
I'm developing an API and I always try to use the most correct http status codes for each scenario.

One of this scenarios is the response for POST requests. Per example, a POST method for an endpoint /orders/ receive some informations, like a customer:

```<code>{
  customerDocument: {number: "123.456.789"},
  // other informations for create a order
}
</code>```

So, my questions is: if this number from customerDocument not exists, is it Ok to return a 404 status code error with a nice message telling that the customer was not found?

I normally use 404 only for GET in the specific resources (the most obvious usage), like:

```<code>/customers/{number}/
</code>```

In business validations like "The customer is not active", I normally use the http status code 422 for any http method (POST, PUT, GET, etc). I'm in doubt if I can use 404 or 422 for my POST example.

答:
I think 400 is the appropriate status code in this scenario, given its definition from Wikipedia:

400 Bad Request

The server cannot or will not process the request due to an apparent client error.

According to the description, semantically, 422 is better ("The request was well-formed but was unable to be followed due to semantic errors."). However, 422 is introduced for WebDAV, so it is better to use general purpose status code such as 400.

400 is not the perfect status code, as whether document number exists or valid is not so apparent. However, excludes special-purpose status code such as 422, 400 is the best option.

Why 404 is not appropriate?

From RESTful API point of view, endpoint /orders/ is a resource, no matter it accepts GET or POST or something else. 404 is only appropriate when the resource /orders/ itself does not exist. If /orders/ endpoint exist, but its invocation failed (no matter what reasons), the response status code must be something  other than 404.

ContentLicense: CC BY-SA 3.0

Body:
I'm developing an API and I always try to use the most correct http status codes for each scenario.

One of this scenarios is the response for POST requests. Per example, a POST method for an endpoint /orders/ receive some informations, like a customer:

{
  customerDocument: {number: "123.456.789"},
  // other informations for create a order
}

So, my questions is: if this number from customerDocument not exists, is it Ok to return a 404 status code error with a nice message telling that the customer was not found?

I normally use 404 only for GET in the specific resources (the most obvious usage), like:

/customers/{number}/

In business validations like "The customer is not active", I normally use the http status code 422 for any http method (POST, PUT, GET, etc). I'm in doubt if I can use 404 or 422 for my POST example.


问:
React native, redux, redux ORM, expo ... trying to make it all work. __fbbatchedbridge
In the spirit of 4th July, I want to establish something thus I am not giving up on this. I've been trying to make it work for a while now(not just today) and frankly I am sick of react native and it's habit of breaking every time I pull a package from npm.

package.json

```<code>"dependencies": {
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "expo": "^18.0.4",
    "react": "16.0.0-alpha.12",
    "react-native": "https://github.com/expo/react-native/archive/sdk-18.0.1.tar.gz",
    "react-redux": "^5.0.5",
    "redux": "^3.7.1",
    "redux-orm": "^0.9.4",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "babel-preset-react-native": "^2.0.0",
    "redux-orm-proptypes": "^0.1.0"
  }
</code>```

App.js

```<code>import React from 'react';
import { Provider } from 'react-redux';
import store from './store';

export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Text>asdasdasD</Text>
      </Provider>
    );
  }
}
</code>```

store/index.js

```<code>import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers/';

const configureStore = createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware)
);

export default configureStore;
</code>```

reducers/index.js

```<code>import { combineReducers } from 'redux';
import { createReducer } from 'redux-orm';
import orm from '../models';

const rootReducerCombined = combineReducers({ orm: createReducer(orm) });

export default rootReducerCombined;
</code>```

models/index.js

```<code>import { ORM } from 'redux-orm';
import Job from './JobModel';

const orm = new ORM();
orm.register(Job);

export default orm;
</code>```

The rest of the stuff is pretty basic. Project is blank expo project that I wanted to create for the sake of using ORM in redux.

On a side note, and I much prefer a solution to my question than having the focus on this, I can not help but think what am I missing? Yes I am very new to react and react native but why does everyone love react native? I agreed to use it on a project even though I did not want to and now I spend most my of time looking through github issues to make everything in my package json work. Everytime I go "hey this looks good I want to use it" and run the npm install, everything breaks ... So, honestly, what is the point of working to work? Am I looking at this all wrong?

答:
I tried out your repository and managed to get it running. The first thing I did was just run exp start --ios to see if that would work. It showed me the following error:

So I went to App.js and saw that on line 9, Text was used but it wasn't imported, so I imported it from react-native and the app rendered with some text.

Next, I looked at the logs and saw this warning:

```<code>  [exp] jest-haste-map: @providesModule naming collision:
  [exp]   Duplicate module name: babel-preset-react-native
  [exp]   Paths: /Users/brent/coding/reduxormexposf/node_modules/react-native/babel-preset/package.json collides with /Users/brent/coding/reduxormexposf/node_modules/react-native/node_modules/babel-preset-react-native/package.json
  [exp]
  [exp] This warning is caused by a @providesModule declaration with the same name across two different files.
</code>```

I then checked the package.json and saw that there were a bunch of babel modules, but the babelrc didn't actually use any of those -- it only used babel-preset-expo. So I removed all of those plugins, closed the packager, and ran exp start --ios again and the warning went away.

I'm not sure how you ended up in the state where you had an error about __fbBatchedBridge is undefined as in your post, there are a number of ways that can happen. The error message is not very descriptive at all and it should be improved. It's quite possible that the packager was not running (exp start). Let me know if the problem persists, but the other issues should be resolved. I submitted a pull request with the changes I discussed: https://github.com/ODelibalta/reduxormexposf/pull/1

Body:
In the spirit of 4th July, I want to establish something thus I am not giving up on this. I've been trying to make it work for a while now(not just today) and frankly I am sick of react native and it's habit of breaking every time I pull a package from npm.

package.json

"dependencies": {
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "expo": "^18.0.4",
    "react": "16.0.0-alpha.12",
    "react-native": "https://github.com/expo/react-native/archive/sdk-18.0.1.tar.gz",
    "react-redux": "^5.0.5",
    "redux": "^3.7.1",
    "redux-orm": "^0.9.4",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "babel-preset-react-native": "^2.0.0",
    "redux-orm-proptypes": "^0.1.0"
  }

App.js

import React from 'react';
import { Provider } from 'react-redux';
import store from './store';

export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Text>asdasdasD</Text>
      </Provider>
    );
  }
}

store/index.js

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers/';

const configureStore = createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware)
);

export default configureStore;

reducers/index.js

import { combineReducers } from 'redux';
import { createReducer } from 'redux-orm';
import orm from '../models';

const rootReducerCombined = combineReducers({ orm: createReducer(orm) });

export default rootReducerCombined;

models/index.js

import { ORM } from 'redux-orm';
import Job from './JobModel';

const orm = new ORM();
orm.register(Job);

export default orm;

The rest of the stuff is pretty basic. Project is blank expo project that I wanted to create for the sake of using ORM in redux.

On a side note, and I much prefer a solution to my question than having the focus on this, I can not help but think what am I missing? Yes I am very new to react and react native but why does everyone love react native? I agreed to use it on a project even though I did not want to and now I spend most my of time looking through github issues to make everything in my package json work. Everytime I go "hey this looks good I want to use it" and run the npm install, everything breaks ... So, honestly, what is the point of working to work? Am I looking at this all wrong?

Body:
I tried out your repository and managed to get it running. The first thing I did was just run exp start --ios to see if that would work. It showed me the following error:

So I went to App.js and saw that on line 9, Text was used but it wasn't imported, so I imported it from react-native and the app rendered with some text.

Next, I looked at the logs and saw this warning:

  [exp] jest-haste-map: @providesModule naming collision:
  [exp]   Duplicate module name: babel-preset-react-native
  [exp]   Paths: /Users/brent/coding/reduxormexposf/node_modules/react-native/babel-preset/package.json collides with /Users/brent/coding/reduxormexposf/node_modules/react-native/node_modules/babel-preset-react-native/package.json
  [exp]
  [exp] This warning is caused by a @providesModule declaration with the same name across two different files.

I then checked the package.json and saw that there were a bunch of babel modules, but the babelrc didn't actually use any of those -- it only used babel-preset-expo. So I removed all of those plugins, closed the packager, and ran exp start --ios again and the warning went away.

I'm not sure how you ended up in the state where you had an error about __fbBatchedBridge is undefined as in your post, there are a number of ways that can happen. The error message is not very descriptive at all and it should be improved. It's quite possible that the packager was not running (exp start). Let me know if the problem persists, but the other issues should be resolved. I submitted a pull request with the changes I discussed: https://github.com/ODelibalta/reduxormexposf/pull/1


问:
Replace occurrence of string in another string with Numbers in PHP
I have a html string code which contain some "img" tags. I want to search the string and change each "<img " occurrence with something like "<img onclick=lightbox(XXXX)", so the first one should become "<img onclick=lightbox(0)" then the second occurrence should become "<img onclick=lightbox(1)" and then third one should become "<img onclick=lightbox(2)" and etc,  How can I achieve this in PHP?

答:
Here. Try this

```<code><?php
  $str = "this is xxxx is not equal xxxx, So what xxxx";

  $t = explode('xxxx',$str);
  $i=0;
  $imStr=[];
  foreach($t as $s){
    $s=$s.$i;
    $imStr[$i]=$s;
    $i=$i+1;
  }

  $str = implode($imStr);
  echo $str;
  ?>
</code>```

This can be improved a lot..

Body:
Here. Try this

<?php
  $str = "this is xxxx is not equal xxxx, So what xxxx";

  $t = explode('xxxx',$str);
  $i=0;
  $imStr=[];
  foreach($t as $s){
    $s=$s.$i;
    $imStr[$i]=$s;
    $i=$i+1;
  }

  $str = implode($imStr);
  echo $str;
  ?>

This can be improved a lot..


问:
Tool to measure quality of javadoc with no source at hand
I'm looking for a tool that can rank javadoc for which I only have the bytecode. A tool that would give an interface without javadoc comments a rank of 0, whereas a well doc:ed interface would rank 100. Cheers Niklas</p>

答: Look into the JavadocMiner tool by Ninus Khamis</p>

ContentLicense: CC BY-SA 2.5


问:
How do computers keep track of time?
How is time represented in the the computer? I mean doesn't the computer do all computations as fast as it can? How do you keep track of the passage of time if things run at various speeds on various machines?</p>

答: The electonic clock inside the computer can calculate the passing of time by using an oscillator which vibrates at a constant frequency. The clock then counts the number of vibrations to keep track of time.</p>

Title: How do computers keep track of time?


问:
Why should we typedef a struct so often in C?
I have seen many programs consisting of structures like the one below

```<code>typedef struct
{
    int i;
    char k;
} elem;

elem user;
</code>```

Why is it needed so often? Any specific reason or applicable area?

答:
A>
a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).

B>
a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit

C>
typedef'ing a struct is explained in A above.

D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.

OwnerDisplayName: Manoj Doubts

Body:
I have seen many programs consisting of structures like the one below

typedef struct
{
    int i;
    char k;
} elem;

elem user;

Why is it needed so often? Any specific reason or applicable area?

LastEditorDisplayName: swilliams


问:
Python etree control empty tag format
When creating an XML file with Python's etree, if we write to the file an empty tag using SubElement, I get:

```<code><MyTag />
</code>```

Unfortunately, our XML parser library used in Fortran doesn't handle this even though it's a correct tag. It needs to see:

```<code><MyTag></MyTag>
</code>```

Is there a way to change the formatting rules or something in etree to make this work?

答:
This was directly solved in Python 3.4. From then, the write method of xml.etree.ElementTree.ElementTree has the short_empty_elements parameter which:

controls the formatting of elements that contain no content. If True (the default), they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags.

More details in the xml.etree documentation.

Title: Python etree control empty tag format

Body:
When creating an XML file with Python's etree, if we write to the file an empty tag using SubElement, I get:

<MyTag />

Unfortunately, our XML parser library used in Fortran doesn't handle this even though it's a correct tag. It needs to see:

<MyTag></MyTag>

Is there a way to change the formatting rules or something in etree to make this work?


问:
mysql - LEFT JOIN not returning all rows

What I have

Problem: My LEFT JOIN is not returning all the data from the left table.

Here are my table schemas:

```<code>CREATE TABLE item_to_map
  (
    id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    item_id INT UNSIGNED NOT NULL,
    map_id INT UNSIGNED NOT NULL,
    user_id INT UNSIGNED NOT NULL,
    date DATETIME DEFAULT CURRENT_TIMESTAMP,

    INDEX(item_id),
    INDEX(map_id),
    INDEX(date),

    FOREIGN KEY (item_id)
      REFERENCES item (id)
        ON DELETE CASCADE,
    FOREIGN KEY (user_id)
      REFERENCES user (id)
        ON DELETE CASCADE,
    FOREIGN KEY (map_id)
      REFERENCES map (id)
        ON DELETE CASCADE
  );

CREATE TABLE vote_item
  (
    id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    user_id INT UNSIGNED NOT NULL,
    item_to_map_id INT UNSIGNED NOT NULL,
    date DATETIME DEFAULT CURRENT_TIMESTAMP,
    score ENUM("-1", "1"),

    INDEX(user_id),
    INDEX(item_to_map_id),
    INDEX(date),
    UNIQUE(user_id, item_to_map_id),

    FOREIGN KEY (item_to_map_id)
      REFERENCES item_to_map (id)
        ON DELETE CASCADE,
    FOREIGN KEY (user_id)
      REFERENCES user (id)
        ON DELETE CASCADE
  );
</code>```

Here's the data I have so far in vote_item (ignore the fact that user_id maps to multiple item_to_map_id)

```<code>+----+---------+----------------+---------------------+-------+
| id | user_id | item_to_map_id | date                | score |
+----+---------+----------------+---------------------+-------+
|  1 |      12 |              1 | 2017-07-05 09:41:32 | 1     |
|  2 |      12 |              1 | 2017-07-05 09:41:32 | 1     |
|  3 |      12 |              1 | 2017-07-05 09:41:33 | 1     |
|  4 |      12 |              2 | 2017-07-05 09:45:29 | 1     |
|  5 |      12 |              2 | 2017-07-05 09:45:29 | -1    |
|  6 |      12 |              2 | 2017-07-05 09:45:29 | -1    |
|  7 |      12 |              3 | 2017-07-05 09:56:28 | 1     |
|  8 |      12 |              3 | 2017-07-05 09:56:29 | -1    |
+----+---------+----------------+---------------------+-------+
</code>```

Here's the item_to_map table:

```<code>+----+---------+--------+---------+---------------------+
| id | item_id | map_id | user_id | date                |
+----+---------+--------+---------+---------------------+
|  1 |       1 |     20 |      12 | 2017-07-05 09:38:23 |
|  2 |       1 |     20 |      12 | 2017-07-05 09:38:23 |
|  3 |       1 |     20 |      12 | 2017-07-05 09:38:23 |
|  4 |       2 |     20 |      12 | 2017-07-05 09:38:23 |
|  5 |       2 |     20 |      12 | 2017-07-05 09:38:23 |
|  6 |       2 |     20 |      12 | 2017-07-05 09:38:24 |
+----+---------+--------+---------+---------------------+
</code>```

What I've tried

```<code>SELECT
  i.id,
  i.item_id,
  v.item_to_map_id,
  IFNULL( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i
LEFT JOIN
  vote_item v ON i.id = v.item_to_map_id
GROUP BY v.item_to_map_id;
</code>```

But this returns

```<code>+----+---------+----------------+-------+
| id | item_id | item_to_map_id | score |
+----+---------+----------------+-------+
|  4 |       2 |           NULL |     0 |
|  1 |       1 |              1 |     3 |
|  2 |       1 |              2 |    -1 |
|  3 |       1 |              3 |     0 |
+----+---------+----------------+-------+
</code>```

What I expected

I expected id 5 and 6 to also show up

答:
Aggregate by all the (unaggregated) columns and fix your problem:</p>

```<code>SELECT i.id, i.item_id, v.item_to_map_id,
       COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i LEFT JOIN
     vote_item v
     ON i.id = v.item_to_map_id
GROUP BY i.id, i.item_id, v.item_to_map_id;
</code>```

Body:
What I have

Problem: My LEFT JOIN is not returning all the data from the left table.

Here are my table schemas:

CREATE TABLE item_to_map
  (
    id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    item_id INT UNSIGNED NOT NULL,
    map_id INT UNSIGNED NOT NULL,
    user_id INT UNSIGNED NOT NULL,
    date DATETIME DEFAULT CURRENT_TIMESTAMP,

    INDEX(item_id),
    INDEX(map_id),
    INDEX(date),

    FOREIGN KEY (item_id)
      REFERENCES item (id)
        ON DELETE CASCADE,
    FOREIGN KEY (user_id)
      REFERENCES user (id)
        ON DELETE CASCADE,
    FOREIGN KEY (map_id)
      REFERENCES map (id)
        ON DELETE CASCADE
  );

CREATE TABLE vote_item
  (
    id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    user_id INT UNSIGNED NOT NULL,
    item_to_map_id INT UNSIGNED NOT NULL,
    date DATETIME DEFAULT CURRENT_TIMESTAMP,
    score ENUM("-1", "1"),

    INDEX(user_id),
    INDEX(item_to_map_id),
    INDEX(date),
    UNIQUE(user_id, item_to_map_id),

    FOREIGN KEY (item_to_map_id)
      REFERENCES item_to_map (id)
        ON DELETE CASCADE,
    FOREIGN KEY (user_id)
      REFERENCES user (id)
        ON DELETE CASCADE
  );

Here's the data I have so far in vote_item (ignore the fact that user_id maps to multiple item_to_map_id)

+----+---------+----------------+---------------------+-------+
| id | user_id | item_to_map_id | date                | score |
+----+---------+----------------+---------------------+-------+
|  1 |      12 |              1 | 2017-07-05 09:41:32 | 1     |
|  2 |      12 |              1 | 2017-07-05 09:41:32 | 1     |
|  3 |      12 |              1 | 2017-07-05 09:41:33 | 1     |
|  4 |      12 |              2 | 2017-07-05 09:45:29 | 1     |
|  5 |      12 |              2 | 2017-07-05 09:45:29 | -1    |
|  6 |      12 |              2 | 2017-07-05 09:45:29 | -1    |
|  7 |      12 |              3 | 2017-07-05 09:56:28 | 1     |
|  8 |      12 |              3 | 2017-07-05 09:56:29 | -1    |
+----+---------+----------------+---------------------+-------+

Here's the item_to_map table:

+----+---------+--------+---------+---------------------+
| id | item_id | map_id | user_id | date                |
+----+---------+--------+---------+---------------------+
|  1 |       1 |     20 |      12 | 2017-07-05 09:38:23 |
|  2 |       1 |     20 |      12 | 2017-07-05 09:38:23 |
|  3 |       1 |     20 |      12 | 2017-07-05 09:38:23 |
|  4 |       2 |     20 |      12 | 2017-07-05 09:38:23 |
|  5 |       2 |     20 |      12 | 2017-07-05 09:38:23 |
|  6 |       2 |     20 |      12 | 2017-07-05 09:38:24 |
+----+---------+--------+---------+---------------------+

What I've tried

SELECT
  i.id,
  i.item_id,
  v.item_to_map_id,
  IFNULL( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i
LEFT JOIN
  vote_item v ON i.id = v.item_to_map_id
GROUP BY v.item_to_map_id;

But this returns

+----+---------+----------------+-------+
| id | item_id | item_to_map_id | score |
+----+---------+----------------+-------+
|  4 |       2 |           NULL |     0 |
|  1 |       1 |              1 |     3 |
|  2 |       1 |              2 |    -1 |
|  3 |       1 |              3 |     0 |
+----+---------+----------------+-------+

What I expected

I expected id 5 and 6 to also show up

Body:
Aggregate by all the (unaggregated) columns and fix your problem:

SELECT i.id, i.item_id, v.item_to_map_id,
       COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i LEFT JOIN
     vote_item v
     ON i.id = v.item_to_map_id
GROUP BY i.id, i.item_id, v.item_to_map_id;


问:
Best approach to combine multiple MySQL tables in R
What is the best approach to combine multiple MySQL tables in R? For instance, I need to rbind 14 large `MySQL tables (each >100k rows by 100 columns). I tried the below approach, which consumed most of my memory and got time out from MySQL. I am wondering if there is alternative solution? I do not need to fetch the whole table, just need group the whole table by a couple of variables and calculate some metrics.

```<code>station_tbl_t <- dbSendQuery(my_db, "select * from tbl_r3_300ft
                  union all
                  select * from tbl_r4_350ft
                  union all
                  select * from tbl_r5_400ft
                  union all
                  select * from tbl_r6_500ft
                  union all
                  select * from tbl_r7_600ft
                  union all
                  select * from tbl_r8_700ft
                  union all
                  select * from tbl_r9_800ft
                  union all
                  select * from tbl_r10_900ft
                  union all
                  select * from tbl_r11_1000ft
                  union all
                  select * from tbl_r12_1200ft
                  union all
                  select * from tbl_r13_1400ft
                  union all
                  select * from tbl_r14_1600ft
                  union all
                  select * from tbl_r15_1800ft
                  union all
                  select * from tbl_r16_2000ft
                  ")
</code>```

答:
Consider iteratively importing MySQL table data and then row bind with R. And be sure to select needed columns to save on overhead:</p>

```<code>tbls <- c("tbl_r3_300ft", "tbl_r4_350ft", "tbl_r5_400ft",
          "tbl_r6_500ft", "tbl_r7_600ft", "tbl_r8_700ft",
          "tbl_r9_800ft", "tbl_r10_900ft", "tbl_r11_1000ft",
          "tbl_r12_1200ft", "tbl_r13_1400ft", "tbl_r14_1600ft",
          "tbl_r15_1800ft", "tbl_r16_2000ft")

sql <- "SELECT Col1, Col2, Col3 FROM"

dfList <- lapply(paste(sql, tbls), function(s) {
             tryCatch({ return(dbGetQuery(my_db, s))
                      }, error = function(e) return(as.character(e)))
          })

# ROW BIND VERSIONS ACROSS PACKAGES
master_df <- base::do.call(rbind, dfList)
master_df <- plyr::rbind.fill(dfList)
master_df <- dplyr::bind_rows(dfList)
master_df <- data.table::rbindlist(dfList)
</code>```

Body:
What is the best approach to combine multiple MySQL tables in R? For instance, I need to rbind 14 large `MySQL tables (each >100k rows by 100 columns). I tried the below approach, which consumed most of my memory and got time out from MySQL. I am wondering if there is alternative solution? I do not need to fetch the whole table, just need group the whole table by a couple of variables and calculate some metrics.

station_tbl_t <- dbSendQuery(my_db, "select * from tbl_r3_300ft
                  union all
                  select * from tbl_r4_350ft
                  union all
                  select * from tbl_r5_400ft
                  union all
                  select * from tbl_r6_500ft
                  union all
                  select * from tbl_r7_600ft
                  union all
                  select * from tbl_r8_700ft
                  union all
                  select * from tbl_r9_800ft
                  union all
                  select * from tbl_r10_900ft
                  union all
                  select * from tbl_r11_1000ft
                  union all
                  select * from tbl_r12_1200ft
                  union all
                  select * from tbl_r13_1400ft
                  union all
                  select * from tbl_r14_1600ft
                  union all
                  select * from tbl_r15_1800ft
                  union all
                  select * from tbl_r16_2000ft
                  ")

Body:
Consider iteratively importing MySQL table data and then row bind with R. And be sure to select needed columns to save on overhead:

tbls <- c("tbl_r3_300ft", "tbl_r4_350ft", "tbl_r5_400ft",
          "tbl_r6_500ft", "tbl_r7_600ft", "tbl_r8_700ft",
          "tbl_r9_800ft", "tbl_r10_900ft", "tbl_r11_1000ft",
          "tbl_r12_1200ft", "tbl_r13_1400ft", "tbl_r14_1600ft",
          "tbl_r15_1800ft", "tbl_r16_2000ft")

sql <- "SELECT Col1, Col2, Col3 FROM"

dfList <- lapply(paste(sql, tbls), function(s) {
             tryCatch({ return(dbGetQuery(my_db, s))
                      }, error = function(e) return(as.character(e)))
          })

# ROW BIND VERSIONS ACROSS PACKAGES
master_df <- base::do.call(rbind, dfList)
master_df <- plyr::rbind.fill(dfList)
master_df <- dplyr::bind_rows(dfList)
master_df <- data.table::rbindlist(dfList)


问:
Why is my Angular template throwing this Typescript error?
I'm building an Angular 4 project in Typescript 2.3.4. I can't figure out what's wrong with the code below.

IDialog interface

```<code>export interface IDialog{
    cancellable?: boolean,

    inputs?: Array<{label: string, value?: any, description?: string}|string>
    message: string
    title?: string,
    type?: DialogInputTypes // <- an Enum
}
</code>```

SampleComponent.ts

```<code>  public dialog:IDialog = {
    cancellable:false,
    title:'Dialog Title',
    message:'This is a modal dialog',
    type:DialogInputTypes.button,
    inputs:[
      {label:'OK', value:'OK'},
      {label:'Cancel', value:'Cancel'}
    ]
  };
</code>```

SampleComponent.html

```<code><input *ngFor="let input of dialog.inputs" [value]="input.value">
                                                    ^^^^^^^^^^^^
</code>```

This error is thrown by the compiler:

Angular: Identifier 'value' is not defined. <anonymous> does not contain such a member

I just upgraded from Angular 2 with Typescript 2.0 and this error was not present before.

Why is this error thrown? Perhaps it has to do with the fact that IDialog.inputs is defined as either an array or a string, and at compile time there is no way for the compiler to know which shape inputs has. If I remove |string from the interface, the error goes away.

More importantly, I don't know how to fix my code.

答:
Its definitely your project configuration
Your code works perfectly fine if its like this

@Component({
   template: `
       <input *ngFor="let input of dialog.inputs" [value]="input.value">
   `
})
export class WhateverComponent{
    public dialog:IDialog = {
        inputs:[
            {label:'OK', value:'OK'},
            {label:'Cancel', value:'Cancel'}
        ]
    };
}
export interface IDialog{
    inputs: Array<iSomeControl | string >;
}
export interface iSomeControl{
    label: string;
    value: string;

}```

I am using Angular 4.0.2 Typescript 2.2.2
I modified in order to be more specific

Body:
I'm building an Angular 4 project in Typescript 2.3.4. I can't figure out what's wrong with the code below.

IDialog interface

export interface IDialog{
    cancellable?: boolean,

    inputs?: Array<{label: string, value?: any, description?: string}|string>
    message: string
    title?: string,
    type?: DialogInputTypes // <- an Enum
}

SampleComponent.ts

  public dialog:IDialog = {
    cancellable:false,
    title:'Dialog Title',
    message:'This is a modal dialog',
    type:DialogInputTypes.button,
    inputs:[
      {label:'OK', value:'OK'},
      {label:'Cancel', value:'Cancel'}
    ]
  };

SampleComponent.html

<input *ngFor="let input of dialog.inputs" [value]="input.value">
                                                    ^^^^^^^^^^^^

This error is thrown by the compiler:

Angular: Identifier 'value' is not defined. <anonymous> does not contain such a member

I just upgraded from Angular 2 with Typescript 2.0 and this error was not present before.

Why is this error thrown? Perhaps it has to do with the fact that IDialog.inputs is defined as either an array or a string, and at compile time there is no way for the compiler to know which shape inputs has. If I remove |string from the interface, the error goes away.

More importantly, I don't know how to fix my code.

Body:
Its definitely your project configuration
Your code works perfectly fine if its like this

@Component({
   template: `
       <input *ngFor="let input of dialog.inputs" [value]="input.value">
   `
})
export class WhateverComponent{
    public dialog:IDialog = {
        inputs:[
            {label:'OK', value:'OK'},
            {label:'Cancel', value:'Cancel'}
        ]
    };
}
export interface IDialog{
    inputs: Array<iSomeControl | string >;
}
export interface iSomeControl{
    label: string;
    value: string;

}

I am using Angular 4.0.2 Typescript 2.2.2
I modified in order to be more specific


问:
AssertionError: expected [ true ] to be true
I have faced with the strange assertions problem so even successful assertions are marked as failed, like this:

```<code>this.expect(this.getWidget('contacts').isNamesDisplayed()).to.eventually.be.true.and.notify(next);
</code>```

and in the console I have:

1 scenario (1 passed)
  4 steps (4 passed)
  0m03.618s
  [17:06:38] E/launcher - expected [ true ] to be true
  [17:06:38] E/launcher - AssertionError: expected [ true ] to be true

As you see in this case test marked as successful despite of failed assertion, but in case when after 'failed' assertion there is another one the whole thing will be failed.

I'm using the last versions of protractor and chai.

答:
The accepted answer is great. The accepted answer reiterates the complaint from Protractor, which is frustrating but very clear:

... returning an array value [true]...

Apparently that is the behavior of the OP's function isNamesDisplayed. But there may be other reasons:

In my case, I accidentally used $$, instead of $, and I was expect($$('div.to-test').isDisplayed()).toBe(true). $$ is a "Shorthand function for finding arrays of elements by css" .

So be aware that one character, $, could be the cause of (and solution to) all life's problems: expect($('div.to-test').isDisplayed()).toBe(true),

(or as the accepted answer says, you could just... "change your expectations" :) )

expect($$('div.to-test').isDisplayed()).toBe([true]);

Maybe  makes more sense for something you actually expect to repeat,for example the
 list items in a

expect($$('ul.to-test li').isDisplayed()).toBe([true, true, true]);

Body:
I have faced with the strange assertions problem so even successful assertions are marked as failed, like this:

this.expect(this.getWidget('contacts').isNamesDisplayed()).to.eventually.be.true.and.notify(next);

and in the console I have:

1 scenario (1 passed)
  4 steps (4 passed)
  0m03.618s
  [17:06:38] E/launcher - expected [ true ] to be true
  [17:06:38] E/launcher - AssertionError: expected [ true ] to be true

As you see in this case test marked as successful despite of failed assertion, but in case when after 'failed' assertion there is another one the whole thing will be failed.

I'm using the last versions of protractor and chai.

Body:
The accepted answer is great. The accepted answer reiterates the complaint from Protractor, which is frustrating but very clear:

... returning an array value [true]...

Apparently that is the behavior of the OP's function isNamesDisplayed. But there may be other reasons:

In my case, I accidentally used $$, instead of $, and I was expect($$('div.to-test').isDisplayed()).toBe(true). $$ is a "Shorthand function for finding arrays of elements by css" .

So be aware that one character, $, could be the cause of (and solution to) all life's problems: expect($('div.to-test').isDisplayed()).toBe(true),

(or as the accepted answer says, you could just... "change your expectations" :) )

expect($$('div.to-test').isDisplayed()).toBe([true]);

Maybe  makes more sense for something you actually expect to repeat,for example the <li> list items in a <ul>

expect($$('ul.to-test li').isDisplayed()).toBe([true, true, true]);


问:
Details View in Asp.net, Set it to NEW
I have a grid view on my page, and a hidden details view.
When the user wants to add a new entry, they will click a button, and the gridview will become hidden and the details view will become visible. The only problem is I want my details view to automatically be set empty in the NEW mode, without them having to click the new in the details view form.</p>

答:
On button click change the mode like:</p>

```<code>DetailsView1.ChangeMode(DetailsViewMode.Insert)
</code>```

Title: Details View in Asp.net, Set it to NEW

Body:
On button click change the mode like:

DetailsView1.ChangeMode(DetailsViewMode.Insert)


问:
Cordova/UWP - how to deal with promises sequentially and write a routine to copy a folder recursively
I'm having trouble figuring out the best way to utilise promises. I'm trying to create a routine that will copy a folder and I find myself trying to deal with promises in sequence. The code that I've written isn't very elegant:

```<code>copyFolder = function( source, target ) {
  var deferred = $q.defer();

  var sourceFolder = null;
  var sourcePromise = Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync(sourcePath)

  sourcePromise.then(function(dir) {
    sourceFolder = dir;
  }, function(error) {
    return
  });

  var targetFolder = null;
  var targetPromise = Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync(targetPath)

  targetPromise.then(function(dir) {
    targetFolder = dir;
  }

  $q.all( sourcePromise, targetPromise ).then( function() {
    if ( !targetFolder ) {
      var createPromise = Windows.Storage.KnownFolders.documentsLibrary.createFolderAsync(targetPath)

      createPromise.then(function(dir) {
        targetFolder = dir;
      }
    }

    createPromise.then( function() {
      deferred.resolve( copyFolderRecursively(sourceFolder, targetFolder) );
    });
  });

  return deferred.promise;
}
</code>```

Please note that I'm copying files that are in the Documents folder, so I can't use cordova-plugin-file.

In the case of the targetFolder, I'm checking to see if it exists (targetPromise). If it doesn't, I create it (createPromise). I like the idea of the $q.all() call, unfortunately it can't be used for createPromise.

To top it all off, I'm trying to create a recursive function that will return once all the files are copied. Actually, it would be better if it could return a promise (or build a list of promises).

Can this code be written in a more elegant form? Also, is there an example I can follow with a recursive function that implements a promise?

答:
I realised that I can create a promise that depends on another promise and wait for that:

```<code>var targetFolder = null;
var targetPromise = Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync( target ).then( function() {
  return Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync( target );
}, function(error) {
  return Windows.Storage.KnownFolders.documentsLibrary.createFolderAsync( target );
});

targetPromise.then( function(folder) {
  targetFolder = folder;
});
</code>```

It's not ideal, but I treat the first call to getFolderAsync as an "exists" call. The success callback is then used to return the result of getFolderAsync. If the "exists" fails, then the call to createFolderAsync is made. This means that $q.all( sourcePromise, targetPromise ) will wait until the folder is retrieved (or created). To keep things simple, instead of trapping the fail callback for createFolderAsync I just check to see whether targetFolder is defined.

Though this technically answers the first part of my question. I realised the following is much more concise:

```<code>var replace = Windows.Storage.CreationCollisionOption.replaceExisting;

var targetFolder = null;
var targetPromise = Windows.Storage.KnownFolders.documentsLibrary.createFolderAsync(target, replace);

targetPromise.then( function(folder) {
  targetFolder = folder;
});
</code>```

What I'm not sure about is whether the targetPromise.then is executed sequentially before the $q.all (used at the end of the function). It seems to work, but I'm not sure whether it's supposed to.

I also created a function that will generate promises and wait for each copy operation (before resolving a single deferred promise). This is just the first version that worked. Any advice on how to improve it will be appreciated:

```<code>$scope.copyFolderRecursively = function(sourceFolder, targetFolder) {
  function CopySubFolders(sourcefolder, targetFolder) {
    var deferred = $q.defer();

    if ( !sourceFolder ) return false;

    var promises = [];

    // Copy the files
    var getFilesPromise = sourceFolder.getFilesAsync();
    var copyFilesPromise = getFilesPromise.then(function (files) {
      if ( files ) {
        files.forEach(function (file) {
          console.log("copy file: " + file.displayName);

          var delayed = $q.defer();
          promises.push( delayed.promise );

          file.copyAsync(targetFolder).then( function(copiedfile) {
            delayed.resolve( copiedfile );
          }, function(error) {
            delayed.reject( "Error copying file" + file.path );
          });
        });
      }
    });

    // Recursively copy each subfolder
    var getFoldersPromise = sourceFolder.getFoldersAsync();
    var copyFoldersPromise = getFoldersPromise.then(function (folders) {
      if ( folders ) {
        folders.forEach(function (folder) {
          var replace = Windows.Storage.CreationCollisionOption.replaceExisting;
          console.log("create folder: " + folder.name);

          var delayed = $q.defer();
          promises.push( delayed.promise );

          targetFolder.createFolderAsync(folder.name, replace).then(function (newFolder) {
            CopySubFolders(folder, newFolder).then( function(success) {
              delayed.resolve( newFolder );
            }, function(error) {
              delayed.reject( "Error copying folder " + newFolder.path );
            });
          });
        });
      }
    });

    $q.all( getFilesPromise, copyFilesPromise, getFoldersPromise, copyFoldersPromise, promises ).then( function() {
      return $q.all( promises );
    }).then( function() {
      deferred.resolve( true );
    }, function(error) {
      deferred.resolve( false );
    });

    return deferred.promise;
  }

  return CopySubFolders( sourceFolder, targetFolder );
}
</code>```

One thing worth noting with this solution (another realisation), UWP promises are not Angularjs promises. I basically convert each UWP call into an AngularJS deferred promise - so I can use $q.all().

Body:
I'm having trouble figuring out the best way to utilise promises. I'm trying to create a routine that will copy a folder and I find myself trying to deal with promises in sequence. The code that I've written isn't very elegant:

copyFolder = function( source, target ) {
  var deferred = $q.defer();

  var sourceFolder = null;
  var sourcePromise = Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync(sourcePath)

  sourcePromise.then(function(dir) {
    sourceFolder = dir;
  }, function(error) {
    return
  });

  var targetFolder = null;
  var targetPromise = Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync(targetPath)

  targetPromise.then(function(dir) {
    targetFolder = dir;
  }

  $q.all( sourcePromise, targetPromise ).then( function() {
    if ( !targetFolder ) {
      var createPromise = Windows.Storage.KnownFolders.documentsLibrary.createFolderAsync(targetPath)

      createPromise.then(function(dir) {
        targetFolder = dir;
      }
    }

    createPromise.then( function() {
      deferred.resolve( copyFolderRecursively(sourceFolder, targetFolder) );
    });
  });

  return deferred.promise;
}

Please note that I'm copying files that are in the Documents folder, so I can't use cordova-plugin-file.

In the case of the targetFolder, I'm checking to see if it exists (targetPromise). If it doesn't, I create it (createPromise). I like the idea of the $q.all() call, unfortunately it can't be used for createPromise.

To top it all off, I'm trying to create a recursive function that will return once all the files are copied. Actually, it would be better if it could return a promise (or build a list of promises).

Can this code be written in a more elegant form? Also, is there an example I can follow with a recursive function that implements a promise?

Body:
I realised that I can create a promise that depends on another promise and wait for that:

var targetFolder = null;
var targetPromise = Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync( target ).then( function() {
  return Windows.Storage.KnownFolders.documentsLibrary.getFolderAsync( target );
}, function(error) {
  return Windows.Storage.KnownFolders.documentsLibrary.createFolderAsync( target );
});

targetPromise.then( function(folder) {
  targetFolder = folder;
});

It's not ideal, but I treat the first call to getFolderAsync as an "exists" call. The success callback is then used to return the result of getFolderAsync. If the "exists" fails, then the call to createFolderAsync is made. This means that $q.all( sourcePromise, targetPromise ) will wait until the folder is retrieved (or created). To keep things simple, instead of trapping the fail callback for createFolderAsync I just check to see whether targetFolder is defined.

Though this technically answers the first part of my question. I realised the following is much more concise:

var replace = Windows.Storage.CreationCollisionOption.replaceExisting;

var targetFolder = null;
var targetPromise = Windows.Storage.KnownFolders.documentsLibrary.createFolderAsync(target, replace);

targetPromise.then( function(folder) {
  targetFolder = folder;
});

What I'm not sure about is whether the targetPromise.then is executed sequentially before the $q.all (used at the end of the function). It seems to work, but I'm not sure whether it's supposed to.

I also created a function that will generate promises and wait for each copy operation (before resolving a single deferred promise). This is just the first version that worked. Any advice on how to improve it will be appreciated:

$scope.copyFolderRecursively = function(sourceFolder, targetFolder) {
  function CopySubFolders(sourcefolder, targetFolder) {
    var deferred = $q.defer();

    if ( !sourceFolder ) return false;

    var promises = [];

    // Copy the files
    var getFilesPromise = sourceFolder.getFilesAsync();
    var copyFilesPromise = getFilesPromise.then(function (files) {
      if ( files ) {
        files.forEach(function (file) {
          console.log("copy file: " + file.displayName);

          var delayed = $q.defer();
          promises.push( delayed.promise );

          file.copyAsync(targetFolder).then( function(copiedfile) {
            delayed.resolve( copiedfile );
          }, function(error) {
            delayed.reject( "Error copying file" + file.path );
          });
        });
      }
    });

    // Recursively copy each subfolder
    var getFoldersPromise = sourceFolder.getFoldersAsync();
    var copyFoldersPromise = getFoldersPromise.then(function (folders) {
      if ( folders ) {
        folders.forEach(function (folder) {
          var replace = Windows.Storage.CreationCollisionOption.replaceExisting;
          console.log("create folder: " + folder.name);

          var delayed = $q.defer();
          promises.push( delayed.promise );

          targetFolder.createFolderAsync(folder.name, replace).then(function (newFolder) {
            CopySubFolders(folder, newFolder).then( function(success) {
              delayed.resolve( newFolder );
            }, function(error) {
              delayed.reject( "Error copying folder " + newFolder.path );
            });
          });
        });
      }
    });

    $q.all( getFilesPromise, copyFilesPromise, getFoldersPromise, copyFoldersPromise, promises ).then( function() {
      return $q.all( promises );
    }).then( function() {
      deferred.resolve( true );
    }, function(error) {
      deferred.resolve( false );
    });

    return deferred.promise;
  }

  return CopySubFolders( sourceFolder, targetFolder );
}

One thing worth noting with this solution (another realisation), UWP promises are not Angularjs promises. I basically convert each UWP call into an AngularJS deferred promise - so I can use $q.all().


问:
GWT SENCHA password field not validating correctly on browser fill
I have the following code to check whether my password field isValid, which then enables the login button.

```<code>Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
            @Override
            public boolean execute() {
                login.setEnabled(isValid());  // checks password field
                return !hasLoggedIn;
            }
        }, 100);
</code>```

However my

```<code>private PasswordField password;
</code>```

returns null all the time even when filled/remembered by browser - until a key is pressed/mouse clicked. If I press any key, or click the mouse button (anywhere on webpage), the password field then returns a value (and validates correctly).

How can I auto enable login button when browser filled password field is remembered ?

答:
```<code>String bgColor = cell.getAppearance().getInputElement(passwordField.getElement()).getComputedStyle("background-color");
</code>```

And then if its yellow I can enable button.

Hacktastic!

Body:
I have the following code to check whether my password field isValid, which then enables the login button.

Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
            @Override
            public boolean execute() {
                login.setEnabled(isValid());  // checks password field
                return !hasLoggedIn;
            }
        }, 100);

However my

private PasswordField password;

returns null all the time even when filled/remembered by browser - until a key is pressed/mouse clicked. If I press any key, or click the mouse button (anywhere on webpage), the password field then returns a value (and validates correctly).

How can I auto enable login button when browser filled password field is remembered ?

Body:
String bgColor = cell.getAppearance().getInputElement(passwordField.getElement()).getComputedStyle("background-color");

And then if its yellow I can enable button.

Hacktastic!


问:
How to add Web API controller to an existing ASP.NET Core MVC?
I created a project using the default ASP.NET Core MVC template. I would like to also create a RESTful API under /api/{Controller}. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found. I tried adding a route in Startup.cs but it doesn't do anything:

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});
</code>```

EDIT:

Like I said, it's all default templates. Here's the Web API Controller that I added:

```<code>[Route("api/[controller]")]
public class AdminController : Controller
{
    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}
</code>```

答:
Try setting name to "Admin"</p>

```<code>        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "Admin",
                template: "api/{controller=Admin}");
        });
</code>```

Body:
I created a project using the default ASP.NET Core MVC template. I would like to also create a RESTful API under /api/{Controller}. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found. I tried adding a route in Startup.cs but it doesn't do anything:

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});

EDIT:

Like I said, it's all default templates. Here's the Web API Controller that I added:

[Route("api/[controller]")]
public class AdminController : Controller
{
    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

Body:
Try setting name to "Admin"

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "Admin",
                template: "api/{controller=Admin}");
        });


问:
AWS API gateway domain mapping
I have domain with aws example.com, currently I have record set so that when user goes to example.com, it serves static website from S3 (done with angular). Now, I have backend api (Lambda and API gate way), which is has url something like,

```<code>https://randomid.execute-api.region.amazonaws.com/Prod/api/getSomething?id=1
</code>```

so, what I am trying to do is if front end makes a http call to example.com /api/getSomething?id=1, it should return me data (since I am using relative urls).

I was reading aws documentation, it seems i cannot use root domain, I have to use subdomain (api.example.com), I am ok with it. But, I am not sure how can i do that, any help would be appreciated.

Also, I may move my front end to subdomain (web.example.com), if I do that, with my backend at (api.example.com, hope fully I will figure this part), will I run into CORS issue?

答:
Go through this AWS developer guide to change the domain name.

Apart from DNS configurations, it also requires to have a SSL certificate for the custom domain (Which could be taken from AWS Certificate Manager for free).

Also note that an API's custom domain name can be the name of a subdomain or the root domain (aka, zone apex) of a registered Internet domain.

If your Web and API have different subdomains, it will run into CORS. However you can setup a CloudFront distribution infront of both Web and API to avoid CORS.

Title: AWS API gateway domain mapping

Body:
I have domain with aws example.com, currently I have record set so that when user goes to example.com, it serves static website from S3 (done with angular). Now, I have backend api (Lambda and API gate way), which is has url something like,

https://randomid.execute-api.region.amazonaws.com/Prod/api/getSomething?id=1

so, what I am trying to do is if front end makes a http call to example.com /api/getSomething?id=1, it should return me data (since I am using relative urls).

I was reading aws documentation, it seems i cannot use root domain, I have to use subdomain (api.example.com), I am ok with it. But, I am not sure how can i do that, any help would be appreciated.

Also, I may move my front end to subdomain (web.example.com), if I do that, with my backend at (api.example.com, hope fully I will figure this part), will I run into CORS issue?


问:
AngularJS input with number get undefined when out of range
I am trying to validate custom input box as following

```<code><div class="form-group">
<label for="inputNetwork" class="control-label">{{'DNS_PRIMARY' | translate}}</label>
<div class="control-content">
    <p>
        <input type="number" integer min="1" max="223"
            class="ip-single-column" ng-model="network.dnsPrimary[0]" name="dnsP0" required ng-blur="dnsBlur('P', 0)"
            ng-class="{'has-error': networkForm.dnsP0.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[1]" name="dnsP1" required ng-blur="dnsBlur('P', 1)"
            ng-class="{'has-error': networkForm.dnsP1.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[2]" name="dnsP2" required ng-blur="dnsBlur('P', 2)"
            ng-class="{'has-error': networkForm.dnsP2.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="254"
            class="ip-single-column" ng-model="network.dnsPrimary[3]" name="dnsP3" required ng-blur="dnsBlur('P', 3)"
            ng-class="{'has-error': networkForm.dnsP3.$invalid}" validate-dns>
    </p>
</div>
</code>```

```<code>       $scope.dnsBlur= function(section, pos) {

        var elem = $scope.network.dnsPrimary;
        var i = pos;
        if(section.endsWith('P')) {
            // primary
            switch(i) {
                case 0:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 1 && elem[i] > 223))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 1:
                    // if (!elem[i] || (elem[i] < 0 && elem[i] > 254))
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 2:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 255))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 3:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
            }
        }
    }

}]).directive('validateDns', ['$rootScope',
function($rootScope) {
    function link($scope, elem, attrs, c) {
        $scope.$watch(attrs.ngModel, function(newValue, oldValue) {
            c.$setValidity('outOfRange', true);

            switch(c.$name.charAt(c.$name.length - 1)) {
                case 0:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 1 && $scope.network.dnsPrimary[i] > 223))
                        c.$setValidity('outOfRange', false);
                    break;
                case 1:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 2:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 3:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 254))
                        c.$setValidity('outOfRange', false);
                    break;
            }

        });
    }
    return {
        require: 'ngModel',
        link: link
    };
}
</code>```

But when I trying to get input number in Blur() function.

It will get undefined when the input out or range. For example, input 999 but get undefined.
Is it anyway to get 999 in Blur()?

答:
I found an answer at here Angular ng-model changes to undefined when checkbox on ng-repeat has the required attribute

But need AngularJS after 1.3.

I am using AngularJs 1.2. So, I need to find another way out.

Body:
I am trying to validate custom input box as following

{{'DNS_PRIMARY' | translate}}

        <input type="number" integer min="1" max="223"
            class="ip-single-column" ng-model="network.dnsPrimary[0]" name="dnsP0" required ng-blur="dnsBlur('P', 0)"
            ng-class="{'has-error': networkForm.dnsP0.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[1]" name="dnsP1" required ng-blur="dnsBlur('P', 1)"
            ng-class="{'has-error': networkForm.dnsP1.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[2]" name="dnsP2" required ng-blur="dnsBlur('P', 2)"
            ng-class="{'has-error': networkForm.dnsP2.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="254"
            class="ip-single-column" ng-model="network.dnsPrimary[3]" name="dnsP3" required ng-blur="dnsBlur('P', 3)"
            ng-class="{'has-error': networkForm.dnsP3.$invalid}" validate-dns>

       $scope.dnsBlur= function(section, pos) {

        var elem = $scope.network.dnsPrimary;
        var i = pos;
        if(section.endsWith('P')) {
            // primary
            switch(i) {
                case 0:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 1 && elem[i] > 223))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 1:
                    // if (!elem[i] || (elem[i] < 0 && elem[i] > 254))
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 2:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 255))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 3:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
            }
        }
    }

}]).directive('validateDns', ['$rootScope',
function($rootScope) {
    function link($scope, elem, attrs, c) {
        $scope.$watch(attrs.ngModel, function(newValue, oldValue) {
            c.$setValidity('outOfRange', true);

            switch(c.$name.charAt(c.$name.length - 1)) {
                case 0:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 1 && $scope.network.dnsPrimary[i] > 223))
                        c.$setValidity('outOfRange', false);
                    break;
                case 1:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 2:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 3:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 254))
                        c.$setValidity('outOfRange', false);
                    break;
            }

        });
    }
    return {
        require: 'ngModel',
        link: link
    };
}

But when I trying to get input number in Blur() function.

It will get undefined when the input out or range. For example, input 999 but get undefined.
Is it anyway to get 999 in Blur()?


问:
How can i transfer data between activities when one activity goes into onPause state?
I mean not using Intent putExtra.

When 'A' Activity goes into onPause or onDestroy state, i want to transfer String data type to 'B' Activity.

I'll appreciate with your response.

Thanks!!

答: Maybe use a static field in class A or make a singleton class that would keep track and override the onPause() method in class A.</p>


问:
How to use laravel query builder 'when' operator targeting a column of the same result set
Maybe I'm trying to accomplish this in the wrong way but I need to able to insert an if condition inside a laravel query builder:

```<code>$name = $request->input('name');
$query = DB::connection('dbconxz')
            ->table('all_items')->select('name', 'price', 'description', 'type', 'quantity', 'exempt')
            ->where('name', 'like', "%{$name}%")
            ->when('??? how to target the *TYPE* column?'== 'Inventory', function ($query) {
                return $query->where('quantity', '>', 0);
            })
            ->get();
</code>```

I have an ajax auto complete that is searching the table all_items and returning the collection of the items where the name is LIKE what the user is typing.. typical ajax autocomplete from database.  Now my problem is that the column named "type" some of the rows have the word 'Inventory' and I wish to only include that result if the quantity of that row is > 0.

Any ideas?

答:
when is used when you want a condition in the application. But here you need a condition for the database server so do something like the below

```<code>$query = DB::connection('dbconxz')
            ->table('all_items as t1')->select('name', 'price', 'description', 'type', 'quantity', 'exempt')
            ->where('name', 'like', "%{$name}%")
            ->where(function ($query1) {
                $query1->where(function ($query2) { $query2->where('type', '==', 'Inventory')->where('quantity', '>', 0); })
                      ->orWhere('type', '<>', 'Inventory')
            })
            ->get();
</code>```

Body:
Maybe I'm trying to accomplish this in the wrong way but I need to able to insert an if condition inside a laravel query builder:

$name = $request->input('name');
$query = DB::connection('dbconxz')
            ->table('all_items')->select('name', 'price', 'description', 'type', 'quantity', 'exempt')
            ->where('name', 'like', "%{$name}%")
            ->when('??? how to target the *TYPE* column?'== 'Inventory', function ($query) {
                return $query->where('quantity', '>', 0);
            })
            ->get();

I have an ajax auto complete that is searching the table all_items and returning the collection of the items where the name is LIKE what the user is typing.. typical ajax autocomplete from database.  Now my problem is that the column named "type" some of the rows have the word 'Inventory' and I wish to only include that result if the quantity of that row is > 0.

Any ideas?

Body:
when is used when you want a condition in the application. But here you need a condition for the database server so do something like the below

$query = DB::connection('dbconxz')
            ->table('all_items as t1')->select('name', 'price', 'description', 'type', 'quantity', 'exempt')
            ->where('name', 'like', "%{$name}%")
            ->where(function ($query1) {
                $query1->where(function ($query2) { $query2->where('type', '==', 'Inventory')->where('quantity', '>', 0); })
                      ->orWhere('type', '<>', 'Inventory')
            })
            ->get();


问:
Is this right? Minheap

Hello, I am wondering if these x's are in the right position for the min heap? Am I correct?

答:
The top position is not a possibility because the 3 would be larger than its children (somewhere below would be a 1 or 2).

The second level is possible because 2 and 3 could be sibling children of 1.

To be on the third level, the 3 would need to have 2 for an immediate parent, and 1 for a grandparent with nothing else in between.

The fourth level is not possible because there you would need three ancestors of 3 that are smaller than three.

The list form is a direct conversion from the tree form.  So, that is a match as well.

You might want to prove this yourself empirically by trying to insert every permutation of 9! into  minheap and observing where the 3 is found.  Here is a Python script that does that:

```<code>from heapq import heapify
from itertools import permutations

has_three = [False] * 9
for t in permutations('123456789'):
    s = list(t)
    heapify(s)
    i = s.index('3')
    has_three[i] = True
print(has_three)
</code>```

And the results are:

```<code>[False, True, True, True, True, True, True, False, False]
</code>```

Title: Is this right? Minheap

Body:
The top position is not a possibility because the 3 would be larger than its children (somewhere below would be a 1 or 2).

The second level is possible because 2 and 3 could be sibling children of 1.

To be on the third level, the 3 would need to have 2 for an immediate parent, and 1 for a grandparent with nothing else in between.

The fourth level is not possible because there you would need three ancestors of 3 that are smaller than three.

The list form is a direct conversion from the tree form.  So, that is a match as well.

You might want to prove this yourself empirically by trying to insert every permutation of 9! into  minheap and observing where the 3 is found.  Here is a Python script that does that:

from heapq import heapify
from itertools import permutations

has_three = [False] * 9
for t in permutations('123456789'):
    s = list(t)
    heapify(s)
    i = s.index('3')
    has_three[i] = True
print(has_three)

And the results are:

[False, True, True, True, True, True, True, False, False]


问:
How to use getUpdates after setWebhook in Telegram Bot API
I use setWebhook for my telegram-bot and now I need to use getUpdates. I have read the docs, and they say, that I can use only one method.

The problem is, that I have in console:

```<code>{"ok":false,"error_code":409,"description":"Error: Conflict: another webhook is active"}
</code>```

So the question is, how to UNSET webhook and use getUpdates?

答:
you can just call the method

```<code>deleteWebhook()
</code>```

https://core.telegram.org/bots/api#deletewebhook

for example using telepot

```<code>import telepot
bot = telepot.Bot('YOUR_AUTHORIZATION_TOKEN')
bot.deleteWebhook()
</code>```

Body:
I use setWebhook for my telegram-bot and now I need to use getUpdates. I have read the docs, and they say, that I can use only one method.

The problem is, that I have in console:

{"ok":false,"error_code":409,"description":"Error: Conflict: another webhook is active"}

So the question is, how to UNSET webhook and use getUpdates?

Body:
you can just call the method

deleteWebhook()

https://core.telegram.org/bots/api#deletewebhook

for example using telepot

import telepot
bot = telepot.Bot('YOUR_AUTHORIZATION_TOKEN')
bot.deleteWebhook()


问:
How can I use a local variable in the annotation @Preauthorize?
i need to do something like this

```<code>String myVar = "myString";
...
@Preauthorize("customMethod(myVar)")
public void myMethod() {
...
}
</code>```

but I'm failing at it. How can I do that? It says it cannot be resolved

EDIT:I'm decoupling few rest services and sometimes I have to share infos between them

```<code>@Value("${my-properties}")
String urlIWantToShare;
...
@PreAuthorize("isValid(#myValue,urlIWantToShare)")
@RequestMapping(value = "**/letsCheckSecurityConfig", method = RequestMethod.GET)
public boolean letsCheckSecurityConfig(@RequestHeader(name = "MY-VALUE") String myValue)) {
    return true;
}
</code>```

this "isValid" custom security method will call an external service, that doesn't know anything about the caller and his infos. I need to transmit few infos and I need to take them from different kind of sources

One of the sources is my application.properties

EDIT2: I managed to do this

```<code>@PreAuthorize("isValid(#myValue, #myProperty)")
@RequestMapping(value = "**/letsCheckSecurityConfig", method = RequestMethod.GET)
public boolean letsCheckSecurityConfig(@RequestHeader(name = "MY-VALUE") String myValue,
                                       @Value("${my-property-from-app-properties}") String myProperty))
</code>```

..but I want to use not only actual static properties but runtime one. Any help?

答:
Apologies if I have misunderstood what you are trying to do, but from my understanding you're trying to set an annotation at runtime based on a variable / app.properties, so that you can then read this variable and then execute your class?

If this is the case, You cannot do this from an annotation alone as annotations cannot read local variables and cannot be set at runtime.

However, one option for you is to have an object which contains the 'values' of interest for you and then read the values from the object.

Something like the below:

PoJo

```<code>public class testObject{
    @test
    private String myVar;
    private String myValue;

    //Getters and Setters
}
</code>```

Get Object values

```<code>public void getFields (Object obj){
    Field fields = obj.getClass().getDeclaredFields();

    for (Field f : fields){
        test fieldAnnotation = f.getAnnotation(test.Class);
        if (fieldAnnotation != null){
            f.get(obj);
            // Do checks based on this
        }
    }
}
</code>```

Main Class

```<code>public static void main(String[] args){
    //Create object
    testObject test = new testObject();

    test.setOne("testOne");
    test.setTwo("testTwo");
    getFields(test);
}
</code>```

I've pulled this code based on what I had to do to get the fields - but in my case, I did not know the object types I was going to be passed. You are simply using the annotation to 'mark' the fields you want to retrieve and then reading the value from the object.

If you're in a similar situation, then you can see my answer here: initial answer

Let me know if i've misunderstood this and I can try and further clarify my answer.

Body:
i need to do something like this

String myVar = "myString";
...
@Preauthorize("customMethod(myVar)")
public void myMethod() {
...
}

but I'm failing at it. How can I do that? It says it cannot be resolved

EDIT:I'm decoupling few rest services and sometimes I have to share infos between them

@Value("${my-properties}")
String urlIWantToShare;
...
@PreAuthorize("isValid(#myValue,urlIWantToShare)")
@RequestMapping(value = "**/letsCheckSecurityConfig", method = RequestMethod.GET)
public boolean letsCheckSecurityConfig(@RequestHeader(name = "MY-VALUE") String myValue)) {
    return true;
}

this "isValid" custom security method will call an external service, that doesn't know anything about the caller and his infos. I need to transmit few infos and I need to take them from different kind of sources

One of the sources is my application.properties

EDIT2: I managed to do this

@PreAuthorize("isValid(#myValue, #myProperty)")
@RequestMapping(value = "**/letsCheckSecurityConfig", method = RequestMethod.GET)
public boolean letsCheckSecurityConfig(@RequestHeader(name = "MY-VALUE") String myValue,
                                       @Value("${my-property-from-app-properties}") String myProperty))

..but I want to use not only actual static properties but runtime one. Any help?

Body:
Apologies if I have misunderstood what you are trying to do, but from my understanding you're trying to set an annotation at runtime based on a variable / app.properties, so that you can then read this variable and then execute your class?

If this is the case, You cannot do this from an annotation alone as annotations cannot read local variables and cannot be set at runtime.

However, one option for you is to have an object which contains the 'values' of interest for you and then read the values from the object.

Something like the below:

PoJo

public class testObject{
    @test
    private String myVar;
    private String myValue;

    //Getters and Setters
}

Get Object values

public void getFields (Object obj){
    Field fields = obj.getClass().getDeclaredFields();

    for (Field f : fields){
        test fieldAnnotation = f.getAnnotation(test.Class);
        if (fieldAnnotation != null){
            f.get(obj);
            // Do checks based on this
        }
    }
}

Main Class

public static void main(String[] args){
    //Create object
    testObject test = new testObject();

    test.setOne("testOne");
    test.setTwo("testTwo");
    getFields(test);
}

I've pulled this code based on what I had to do to get the fields - but in my case, I did not know the object types I was going to be passed. You are simply using the annotation to 'mark' the fields you want to retrieve and then reading the value from the object.

If you're in a similar situation, then you can see my answer here: initial answer

Let me know if i've misunderstood this and I can try and further clarify my answer.


问:
Can't properly build HttpUrl which contains hash-bang
I'm trying to build HttpUrl instance which contains hash-bang but can't properly do so. Final URL string value should look like this example: https://www.google.com/mobile/#!/id?platform=android

I've tried few solutions:

https://gist.github.com/novachevskyi/71529d8fdecf120e626af227193a9e0f
When adding hash-bang with HttpUrl.Builder::addEncodedPathSegment then final result would contain encoded hash symbol.

https://gist.github.com/novachevskyi/12b59e53d6162fb1cd4e6236b03fb504
After parsing base URL which contains hash-bang I'm getting next result:
https://www.google.com/mobile/?platform=android#!/id

Is there any way to build HttpUrl instance were string value would contain hash-bang in it?

答:
You can do it with .parse() or with .fragment().

```<code>HttpUrl a = HttpUrl.parse("https://www.google.com/mobile/#!/id?platform=android");
HttpUrl b = new HttpUrl.Builder()
    .scheme("https")
    .host("www.google.com")
    .encodedPath("/mobile/")
    .fragment("!/id?platform=android")
    .build();
</code>```

Body:
You can do it with .parse() or with .fragment().

HttpUrl a = HttpUrl.parse("https://www.google.com/mobile/#!/id?platform=android");
HttpUrl b = new HttpUrl.Builder()
    .scheme("https")
    .host("www.google.com")
    .encodedPath("/mobile/")
    .fragment("!/id?platform=android")
    .build();


问:
Problem in creating two identity columns in a single table
I am having a problem in creating two identity columns in a single table. This is my part of job... They need two identity columns in a single table at  any cost. Is there any way to do this.

Please provide any syntax for creating two identity columns in a single table at a time or later also.

Thanks in Advance,
Shashra

答:
you can't have two identical columns in the same table. If you were to have two columns named id in table X, what would be the result of this query:

```<code>select id from X
</code>```

obviously sql will have trouble with this. I think the best you can do is make another query with a similar name (like, Identity or ID2) and set every field of the new column to the vlue of the ID (original field) in that table

Body:
you can't have two identical columns in the same table. If you were to have two columns named id in table X, what would be the result of this query:

select id from X

obviously sql will have trouble with this. I think the best you can do is make another query with a similar name (like, Identity or ID2) and set every field of the new column to the vlue of the ID (original field) in that table


问:
Use vim to convert markdown headings to org headings
Use vim to convert a file of markdown headings to org heading.

For example, change this:

```<code># heading one
body
##heading two
### heading three
body
</code>```

to this:

```<code>* heading one
body
**heading two
****** heading six
</code>```

Only a continues sequence of '#' starting at column 0 should be substituted with an equal number of '*'.

This substitutes only the first '#' with '*':

```<code>%s/^[#]/*/c
</code>```

But there can be up to six '#' to substitute.

答:
Use sub-string expression

```<code>%s/^#\+/\=repeat('*', len(submatch(0)))/
</code>```

match whole of # leading a line

return repeated * numbered length of matched string

submatch(0) mean whole part of matched string

Body:
Use vim to convert a file of markdown headings to org heading.

For example, change this:

# heading one
body
##heading two
### heading three
body

to this:

* heading one
body
**heading two
****** heading six

Only a continues sequence of '#' starting at column 0 should be substituted with an equal number of '*'.

This substitutes only the first '#' with '*':

%s/^[#]/*/c

But there can be up to six '#' to substitute.

Body:
Use sub-string expression

%s/^#\+/\=repeat('*', len(submatch(0)))/

match whole of # leading a line

return repeated * numbered length of matched string

submatch(0) mean whole part of matched string


问:
Undefined is not a function in React Native project
I'm new to React Native. I'm trying to open existing React Native project in the emulator on Windows 10, but it throws this error:

```<code>undefined is not a function (evaluating '(0, _reactRedux.combineReducers)')
</code>```

I'm using 0.45.1 version of React Native. Why is this happening?

答:
combineReducers is a utility function exported by redux, not react-redux. It's not React-specific and it's a utility function so it's from the redux package. You're trying to import it from react-redux so it's undefined because it doesn't exist there, and when you try to execute the function it throws the error. Import it from redux:

```<code>import { combineReducers } from 'redux';
</code>```

Body:
I'm new to React Native. I'm trying to open existing React Native project in the emulator on Windows 10, but it throws this error:

undefined is not a function (evaluating '(0, _reactRedux.combineReducers)')

I'm using 0.45.1 version of React Native. Why is this happening?

Body:
combineReducers is a utility function exported by redux, not react-redux. It's not React-specific and it's a utility function so it's from the redux package. You're trying to import it from react-redux so it's undefined because it doesn't exist there, and when you try to execute the function it throws the error. Import it from redux:

import { combineReducers } from 'redux';


问:
Replace part of numpy 1D array with shorter array
I have a 1D numpy array containing some audio data. I'm doing some processing and want to replace certain parts of the data with white noise. The noise should, however, be shorter then the replaced part. Generating the noise is not a problem, but I'm wondering what the easiest way to replace the original data with the noise is. My first thought of doing data[10:110] = noise[0:10] does not work due to the obvious dimension mismatch.

What's the easiest way to replace a part of a numpy array with another part of different dimension?

edit:
The data is uncompressed PCM data that can be up to an hour long, taking up a few hundred MB of memory. I would like to avoid creating any additional copies in memory.

答:
What advantage does a numpy array have over a python list for your application? I think one of the weaknesses of numpy arrays is that they are not easy to resize:

http://mail.python.org/pipermail/python-list/2008-June/1181494.html

Do you really need to reclaim the memory from the segments of the array you're shortening? If not, maybe you can use a masked array:

http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html

When you want to replace a section of your signal with a shorter section of noise, replace the first chunk of the signal, then mask out the remainder of the removed signal.

EDIT: Here's some clunky numpy code that doesn't use masked arrays, and doesn't allocate more memory. It also doesn't free any memory for the deleted segments. The idea is to replace data that you want deleted by shifting the remainder of the array, leaving zeros (or garbage) at the end of the array.

```<code>import numpy
a = numpy.arange(10)
# [0 1 2 3 4 5 6 7 8 9]
## Replace a[2:7] with length-2 noise:
insert = -1 * numpy.ones((2))
new = slice(2, 4)
old = slice(2, 7)
#Just to indicate what we'll be replacing:
a[old] = 0
# [0 1 0 0 0 0 0 7 8 9]
a[new] = insert
# [0 1 -1 -1 0 0 0 7 8 9]
#Shift the remaining data over:
a[new.stop:(new.stop - old.stop)] = a[old.stop:]
# [0 1 -1 -1 7 8 9 7 8 9]
#Zero out the dangly bit at the end:
a[(new.stop - old.stop):] = 0
# [0 1 -1 -1 7 8 9 0 0 0]
</code>```

Body:
What advantage does a numpy array have over a python list for your application? I think one of the weaknesses of numpy arrays is that they are not easy to resize:

http://mail.python.org/pipermail/python-list/2008-June/1181494.html

Do you really need to reclaim the memory from the segments of the array you're shortening? If not, maybe you can use a masked array:

http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html

When you want to replace a section of your signal with a shorter section of noise, replace the first chunk of the signal, then mask out the remainder of the removed signal.

EDIT: Here's some clunky numpy code that doesn't use masked arrays, and doesn't allocate more memory. It also doesn't free any memory for the deleted segments. The idea is to replace data that you want deleted by shifting the remainder of the array, leaving zeros (or garbage) at the end of the array.

import numpy
a = numpy.arange(10)
# [0 1 2 3 4 5 6 7 8 9]
## Replace a[2:7] with length-2 noise:
insert = -1 * numpy.ones((2))
new = slice(2, 4)
old = slice(2, 7)
#Just to indicate what we'll be replacing:
a[old] = 0
# [0 1 0 0 0 0 0 7 8 9]
a[new] = insert
# [0 1 -1 -1 0 0 0 7 8 9]
#Shift the remaining data over:
a[new.stop:(new.stop - old.stop)] = a[old.stop:]
# [0 1 -1 -1 7 8 9 7 8 9]
#Zero out the dangly bit at the end:
a[(new.stop - old.stop):] = 0
# [0 1 -1 -1 7 8 9 0 0 0]


问:
I have a text file of a grid that has x y z coordinates and varying lengths of the sides of the cells(sx, sy and sz)
I have a text file of a grid that has x y z coordinates (of cell centers and are in UTM) and varying lengths of the sides of the cells(sx, sy and sz). The points are random points. I would like to plot this in Python. Can anyone offer any suggestions? </p>

```<code> x       y          z     sx    sy   sz
 584597 1848923    210   143    53   143
 584885 1848927    210   143    62   143
 585173 1853185    210   143   224   143
</code>```

答:
As far as how? I would start by:

1) using readline, you split each by the " "(space) values

2) create dict with a for loop, and setting the key.. x y z etc...

3) ??  You say you want to plot but since I don't know the end game here; I imagine matploit should be the goto forgraphical plotting

4) As to the other variables, the non-coordinantes, it's up to you in how you want to correlate/express these values.

ContentLicense: CC BY-SA 4.0

Body:
I have a text file of a grid that has x y z coordinates (of cell centers and are in UTM) and varying lengths of the sides of the cells(sx, sy and sz). The points are random points. I would like to plot this in Python. Can anyone offer any suggestions?

 x       y          z     sx    sy   sz
 584597 1848923    210   143    53   143
 584885 1848927    210   143    62   143
 585173 1853185    210   143   224   143


问:
How to have two buttons in JQuery Steps
I really need some help here. So I am using one Jquery Steps PlugIn. Now in this PlugIn when we go to the last tab it has a button name as "Finish" when clicked calls "onFinishing" Method.

```<code>onFinishing: function () {
            var loadedPrefix = MyNamespace.loadedPrefix;
            var inputBoxPrefix = $('#SitePrefix').val();
            $.ajax({
                type: 'POST',
                url: '/Settings/IsPrefixExists',
                data: { newPrefix: inputBoxPrefix, prefixLoadedFromDB: loadedPrefix },
                success: function (data) {
                      // do some stuff here
                    }
                },
                error: function () {
                    DisplayError('Failed to load the data.');
                }
            });
        }
</code>```

Now above works perfectly fine. But my manager wants  me to have two button there. One as "Save" and another as "Submit". And clicking on each of them will perform a different action. But this plugin has only one "Finish" button. And it is getting generated via PlugIn's Javascript code. Can I somehow use JQuery/Javascript to have one more button there, and write some code against it.

JS FIDDLE SAMPLE: JS FIDDLE SAMPLE

Image 1:

I want something like below
Image 2:

SAMPLE Example:
 JS FIDDLE

答:
Regardless of using the steps plugin, you can add a save button on the last step and bind a click handler like you would with any normal button:

```<code><input id='btnSave' name='btnSave' value='Save' type='button'>
</code>```

and in your javascript:

```<code>$('#btnSave').click(function() {
    $.ajax({
            type: 'POST',
            url: '/Settings/SavePrefix',
            data: { newPrefix: inputBoxPrefix, prefixLoadedFromDB: loadedPrefix },
            success: function (data) {
                  // do some stuff here
                }
            },
            error: function () {
                DisplayError('Failed to save the data.');
            }
        });
});
</code>```

You can also inject the button as needed.

Using the default plugin inside of a tag with and id of #steps-uid-8 you can get the finish element with $('#steps-uid-8 a').last(); It is nested inside of a
 which is inside of a
 so you can get a reference to the ul $('#steps-uid-8 a').last(),parent().parent()

Using that reference you can add a hyperlink so your "button" has the same style as the plugin, like this:

```<code>$('#steps-uid-8 a').last().parent().parent().prepend("<li><a id='btnSave' name='btnSave'>Save</a></li>");
</code>```

You can also add a function in your settings to only show the Save button on the last step if you need to

```<code>var numberOfSteps=3,// change as needed

var settings = {
    onStepChanged: function (event, currentIndex, priorIndex)
    {
    if(currentIndex==numberOfSteps) $('#btnSave').show();
    else $('#btnSave').hide();
    }
}
</code>```

Using your fiddle, the onload Javascript was simply changed.

```<code><script>
      function saveMe() {
        alert('Saving');
      }
      $(window).load(function() {
        var lastStep = 2;
        $("#example-basic").steps({
          headerTag: "h3",
          bodyTag: "section",
          transitionEffect: "slideLeft",
          onStepChanged: function(event, currentIndex, priorIndex) {
            //console.log(currentIndex);
            if (currentIndex == lastStep) $('#btnSave').show();
            else $('#btnSave').hide();
          },
          autoFocus: true,
          onFinishing: function() {
            alert("Hello");
          },
        }).find('a')
        .last().parent().parent()
        .prepend("<li><a style='display:none' href='#save' id='btnSave' name='btnSave' onclick='saveMe()'>Save</a></li>");
      });
    </script>
</code>```

Here is a working copy: https://jsfiddle.net/rwh64ja8/

Title: How to have two buttons in JQuery Steps

Body:
I really need some help here. So I am using one Jquery Steps PlugIn. Now in this PlugIn when we go to the last tab it has a button name as "Finish" when clicked calls "onFinishing" Method.

onFinishing: function () {
            var loadedPrefix = MyNamespace.loadedPrefix;
            var inputBoxPrefix = $('#SitePrefix').val();
            $.ajax({
                type: 'POST',
                url: '/Settings/IsPrefixExists',
                data: { newPrefix: inputBoxPrefix, prefixLoadedFromDB: loadedPrefix },
                success: function (data) {
                      // do some stuff here
                    }
                },
                error: function () {
                    DisplayError('Failed to load the data.');
                }
            });
        }

Now above works perfectly fine. But my manager wants  me to have two button there. One as "Save" and another as "Submit". And clicking on each of them will perform a different action. But this plugin has only one "Finish" button. And it is getting generated via PlugIn's Javascript code. Can I somehow use JQuery/Javascript to have one more button there, and write some code against it.

JS FIDDLE SAMPLE: JS FIDDLE SAMPLE

Image 1:

I want something like below
Image 2:

SAMPLE Example:
 JS FIDDLE

Body:
Regardless of using the steps plugin, you can add a save button on the last step and bind a click handler like you would with any normal button:

<input id='btnSave' name='btnSave' value='Save' type='button'>

and in your javascript:

$('#btnSave').click(function() {
    $.ajax({
            type: 'POST',
            url: '/Settings/SavePrefix',
            data: { newPrefix: inputBoxPrefix, prefixLoadedFromDB: loadedPrefix },
            success: function (data) {
                  // do some stuff here
                }
            },
            error: function () {
                DisplayError('Failed to save the data.');
            }
        });
});

You can also inject the button as needed.

Using the default plugin inside of a tag with and id of #steps-uid-8 you can get the finish element with $('#steps-uid-8 a').last(); It is nested inside of a <li> which is inside of a <ul> so you can get a reference to the ul $('#steps-uid-8 a').last(),parent().parent()

Using that reference you can add a hyperlink so your "button" has the same style as the plugin, like this:

$('#steps-uid-8 a').last().parent().parent().prepend("<li><a id='btnSave' name='btnSave'>Save</a></li>");

You can also add a function in your settings to only show the Save button on the last step if you need to

var numberOfSteps=3,// change as needed

var settings = {
    onStepChanged: function (event, currentIndex, priorIndex)
    {
    if(currentIndex==numberOfSteps) $('#btnSave').show();
    else $('#btnSave').hide();
    }
}

Using your fiddle, the onload Javascript was simply changed.

<script>
      function saveMe() {
        alert('Saving');
      }
      $(window).load(function() {
        var lastStep = 2;
        $("#example-basic").steps({
          headerTag: "h3",
          bodyTag: "section",
          transitionEffect: "slideLeft",
          onStepChanged: function(event, currentIndex, priorIndex) {
            //console.log(currentIndex);
            if (currentIndex == lastStep) $('#btnSave').show();
            else $('#btnSave').hide();
          },
          autoFocus: true,
          onFinishing: function() {
            alert("Hello");
          },
        }).find('a')
        .last().parent().parent()
        .prepend("<li><a style='display:none' href='#save' id='btnSave' name='btnSave' onclick='saveMe()'>Save</a></li>");
      });
    </script>

Here is a working copy: https://jsfiddle.net/rwh64ja8/


问:
Unit testing, Black-box testing and white box testing
What is Unit testing, Black-box testing and White-Box testing? I googled but all the explanation I found was very technical. Can anyone answer this question in a simple way with an appropriate example?</p>

答:
Black Box Testing:

Tester is a human and not the developer

Tester does not know how system was implemented *

Tester will report an issue when the response from the system to any step of the test is not the expected result.

White Box Testing:

Tester is a human and not the developer

Tester does know how system was implemented *

Tester will report an issue when the response from the system to any step of the test is not the expected result and is more likely to detect an issue with the test case itself or with the system despite receiving expected results.

Unit Testing:

Tester is usually code that tests a particular module within a system. For example, in Java, a project may have a class named Student and a test class named StudentTest. For each of the functions in Student (like getGrades), StudentTest might have 0 or more functions to test them (like getGradesTest). This is just one such way to go about it.

Testing code typically only knows the expected output for various input for a portion of a system.

Unit tests are often run before submitting code or run automatically when building an application to deploy. The goal is to prevent as many bugs from being introduced into the system when adding, changing or removing functionality.

* The amount of knowledge known between a black box tester and a white box tester varies from organization to organization. For example, what I consider usability testing, another company might call black box testing. A white box tester in some companies might be another developer (developer QA), whereas another organization may not allow any testing sign-offs to be completed by a developer. A black box tester could be someone who just has a list of instructions they need to follow and validate, or it could be someone who generally knows how the system works, but just not at a particularly detailed level. For example:

A black box tester may or may not identify an issue despite a test case that matches expectations, like an e-commerce test case that omits the step of collecting a guest checkout shipping address.

Essentially, white box and black box testing is rarely implemented strictly. Most organizations have unit tests, developer testing (that may or may not be formally documented - depends upon the implications of a failure), QA testers (black, white, and every shade of gray in between), and user testing / business sign-off (the people who should be involved throughout the project, but in poorly run organizations only show up at the beginning and end, and send a completed project back to design right before deployment).


问:
Is it bad practice to return from within a try catch finally block?
So I came across some code this morning that looked like this:

```<code>try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}
</code>```

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

答:
In your example either way is equivalent, I wouldn't even be suprised if the compiler generated the same code.  If an exception happens in the finally block you have the same issues whether you put the return statement in block or outside of it.

The real question is stylistically which is best. I like to write my methods so that there is only one return statement, this way it is easier to see the flow out of the method, it follows that I also like to put the return statement last so it is easy to see that it is the end of the method and this what it returns.

I think with the return statement so neatly placed as the last statement, others are less likely to come and sprinkle multiple returns statements into other parts of the method.

OwnerDisplayName: lomaxx

Body:
So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

OwnerDisplayName: BeWarned