问:
Transition Rejection Angular UI Router
I have a HTTPInterceptor that should go to signin state whenever a 401 is caught. My problem is that I have 3 asynchronous call to API that almost starts the same time. When all of them returns 401, i got an error with the following message:

Transition Rejection($id: 0 type: 6, message: The transition errored, detail: "undefined")

This is my code for my interceptor:

```<code>switch (response.status) {
  case 401:
    let url = $location.absUrl();
    // This condition supposed to prevent
    // going to signin state again after a response of 401.
    // Not really sure if ui-router will navigate still on the same
    // state. So maybe this condition is not needed?
    if (url.indexOf('sign-in') !== -1) {
      deferred.reject(response.data.error);
    } else {
      if ($transitions._transitionCount === 1) {
        $state.go('signin');
      }
    }
    break;
</code>```

What ive tried so far is to check the transitionCount but still the error persist.

Thanks!

答:
In UI-Router legacy, users often complained that resolves would
  “swallow errors”. The errors were output as a $stateChangeError event,
  but applications sometimes didn’t listen to the event.

In UI-Router 1.0, we’ve added a default error handler. When a call to
  $state.go() fails, we pass the error to
  StateService.defaultErrorHandler.

You can handle this type of error with

```<code>$state.defaultErrorHandler(function(error) {
// This is a naive example of how to silence the default error handler.
console.log(error);
});
</code>```

Details

Title: Transition Rejection Angular UI Router

Body:
I have a HTTPInterceptor that should go to signin state whenever a 401 is caught. My problem is that I have 3 asynchronous call to API that almost starts the same time. When all of them returns 401, i got an error with the following message:

Transition Rejection($id: 0 type: 6, message: The transition errored, detail: "undefined")

This is my code for my interceptor:

switch (response.status) {
  case 401:
    let url = $location.absUrl();
    // This condition supposed to prevent
    // going to signin state again after a response of 401.
    // Not really sure if ui-router will navigate still on the same
    // state. So maybe this condition is not needed?
    if (url.indexOf('sign-in') !== -1) {
      deferred.reject(response.data.error);
    } else {
      if ($transitions._transitionCount === 1) {
        $state.go('signin');
      }
    }
    break;

What ive tried so far is to check the transitionCount but still the error persist.

Thanks!

Body:
In UI-Router legacy, users often complained that resolves would
  “swallow errors”. The errors were output as a $stateChangeError event,
  but applications sometimes didn’t listen to the event.

In UI-Router 1.0, we’ve added a default error handler. When a call to
  $state.go() fails, we pass the error to
  StateService.defaultErrorHandler.

You can handle this type of error with

$state.defaultErrorHandler(function(error) {
// This is a naive example of how to silence the default error handler.
console.log(error);
});

Details


来源: stackexchange

问:
Convert array of characters to array of ints c++?
I have an array of 10 numerical characters, and I want to convert it, index by index, to an array of ints. For instance, if array[0] = '2', I want to edit the array so that array[0] = 2.

How do I do this as part of a for loop? I was thinking something like this:

```<code>for (int i = 0; i < 10; i++){
 array[i] = array[i] - '0';
}
</code>```

Please let me know if this is right, or if I need to change something. Thank you!

答: The code above would not work as you are taking a char and trying to convert it to an int then place the int into the char. You should have another array for your int[].

ContentLicense: CC BY-SA 3.0

Body:
I have an array of 10 numerical characters, and I want to convert it, index by index, to an array of ints. For instance, if array[0] = '2', I want to edit the array so that array[0] = 2.

How do I do this as part of a for loop? I was thinking something like this:

for (int i = 0; i < 10; i++){
 array[i] = array[i] - '0';
}

Please let me know if this is right, or if I need to change something. Thank you!


问:
Why do vectors implement Associative?
I was surprised to discover that clojure vectors implement the Associative interface.

```<code>(associative? [1 2 3]) ; => true
</code>```

I assume this interface provides optimized indexing by keys. Following this assumption, the interface seems appropriate for map data structures, but odd for vectors, which don't follow a key-value heuristic in my mind.

Is my mental model for Associative or vector's implementation incorrect? What purpose does this design choice serve?

答:
It may not seem intuitive initially, but vectors are keyed by their indices, which allow them to make use of all the standard associative functions. This makes it very easy to do simple operations on them:

```<code>(def v [1 2 3])

(assoc v 1 4)
[1 4 3]

(update v 1 inc)
[1 3 3]

(get v 1) ; The same as (v 1)
2
</code>```

Or, if you have a 2D vector:

```<code>(def v [[1 2 3]
        [4 5 6]
        [7 8 9]])

(assoc-in v [2 1] 0)
[[1 2 3]
 [4 5 6]
 [7 0 9]]
</code>```

Without this design choice, an entire separate set of functions would need to be created and used specifically for vectors. Having a standardized interface allows you to write functions that don't care about specifically what structure they're working on.

Think about it this way: Say you wanted to write a function that "replaces" an element of a vector. Would its signature be any different from the existing assoc function; besides specifically expecting a vector?

Title: Why do vectors implement Associative?

Body:
I was surprised to discover that clojure vectors implement the Associative interface.

(associative? [1 2 3]) ; => true

I assume this interface provides optimized indexing by keys. Following this assumption, the interface seems appropriate for map data structures, but odd for vectors, which don't follow a key-value heuristic in my mind.

Is my mental model for Associative or vector's implementation incorrect? What purpose does this design choice serve?

Body:
It may not seem intuitive initially, but vectors are keyed by their indices, which allow them to make use of all the standard associative functions. This makes it very easy to do simple operations on them:

(def v [1 2 3])

(assoc v 1 4)
[1 4 3]

(update v 1 inc)
[1 3 3]

(get v 1) ; The same as (v 1)
2

Or, if you have a 2D vector:

(def v [[1 2 3]
        [4 5 6]
        [7 8 9]])

(assoc-in v [2 1] 0)
[[1 2 3]
 [4 5 6]
 [7 0 9]]

Without this design choice, an entire separate set of functions would need to be created and used specifically for vectors. Having a standardized interface allows you to write functions that don't care about specifically what structure they're working on.

Think about it this way: Say you wanted to write a function that "replaces" an element of a vector. Would its signature be any different from the existing assoc function; besides specifically expecting a vector?

ContentLicense: CC BY-SA 4.0


问:
Ansible - check if item in a list of dictionaries is present in other list of dictionaries
How to check if an object of a list of dictionaries is present in another list of dictionaries (with Ansible?)

You could try jinja filters selectattr - I had an issue with using it, so I did revert to a simplified but ugly solution - build a filtered list and compare filtered attributes only (list-to-list).
I do not like it, but it works.
Let me know if you know other way.

playbook:

```<code>- name: find existing system_crontabs  #would generate a list of dict
  find:
    path: /var/spool/cron/crontabs/
  register: system_side_crontabs
  become: True

- name: create lists of system_cron_names and repo_cron_names
  set_fact:
    system_cron_names: "[]"
    repo_cron_names: "[]"

- name: build list of system_cron_names
  set_fact:
    system_cron_names: "{{ system_cron_names }} + [ '{{ item.path |basename }}' ]"
  with_items: "{{ system_side_crontabs.files }}"

- name: build lists of repo_cron_names
  set_fact:
    repo_cron_names: "{{ repo_cron_names }} + [ '{{ item.user }}' ]"
  with_items: "{{ crontabs }}"

- name: assert check if an object of system_crontab is defined in repo_crontab
  assert:
    that: "{{ [item] |intersect(repo_cron_names) | length }} == 1"
  with_items: "{{ system_cron_names }}"
</code>```

hosts_vars/prd-inner-mgmt202  #a list of dictionaries

```<code>crontabs:
  - user: root
    crontab_rules: |
      11 1 * * * find /home/ansible/.ansible/tmp/ -atime +10  -delete
</code>```

a result of find

```<code>ok: [prd-inner-mgmt202] => {
    "changed": false,
    "examined": 1,
    "files": [                         ### List of dictionary
        {

            "path": "/var/spool/cron/crontabs/root",

        },
        {

            "path": "/var/spool/cron/crontabs/another_file",

        }
    ],
    "invocation": {
        "module_args": {
            "age": null,
            "age_stamp": "mtime",
            "contains": null,
            "file_type": "file",
            "follow": false,
            "get_checksum": false,
            "hidden": false,
            "path": "/var/spool/cron/crontabs/",
            "paths": [
                "/var/spool/cron/crontabs/"
            ],
            "patterns": [
                "*"
            ],
            "recurse": false,
            "size": null,
            "use_regex": false
        },
        "module_name": "find"
    },
    "matched": 1,
    "msg": ""
}
</code>```

generate a list of strings that are easy to compare

```<code>TASK [mid_crontab : build list of system_cron_names] **************************
   "ansible_facts": {
        "system_cron_names": [
            "root",

        ]
    },
    "changed": false,
    "invocation": {
        "module_args": {
            "system_cron_names": [
                "root"
            ]
        },
        "module_name": "set_fact"
    },
</code>```

generate another list of strings

```<code>TASK [mid_crontab : build list of repo_cron_names] *****************************

ok: [prd-inner-mgmt202] => (item={u'crontab_rules': u'11 1 * * * find /home/ansible/.ansible/tmp/ -atime +10  -delete\n', u'user': u'root'}) => {
    "ansible_facts": {
        "repo_cron_names": [
            "root"
        ]
    },
    "changed": false,
    "invocation": {
        "module_args": {
            "repo_cron_names": [
                "root",
        "other"
            ]
        },
        "module_name": "set_fact"
    },
    "item": {
        "crontab_rules": "11 1 * * * find /home/ansible/.ansible/tmp/ -atime +10  -delete\n",
        "user": "root"
    }
}
</code>```

Assert the required check, use intersect jinja filter. In my case a system defined object (cron record) should exist in my repository - so the list should have 1 element.

```<code>TASK [mid_crontab : assert check if system_crontab is defined in repo_crontab] *

ok: [prd-inner-mgmt202] => (item=root) => {
    "changed": false,
    "invocation": {
        "module_args": {
            "that": "1 == 1"
        },
        "module_name": "assert"
    },
    "item": "root",
    "msg": "All assertions passed"
}
</code>```

答:
Seems you want to reduce original dict to list of strings (names) and compare the difference:

```<code>---
- hosts: localhost
  gather_facts: no
  vars:
    crontabs:
      - user: root
        crontab_rules: xxx
  tasks:
    - find:
        path: /tmp/test
      register: myfiles
    - assert:
        that: sys_crons_violation | count == 0
        msg: "This crons are not defined in repo : {{ sys_crons_violation | join(', ') }}"
      vars:
        sys_crons: "{{ myfiles.files | map(attribute='path') | map('basename') | list }}"
        repo_crons: "{{ crontabs | map(attribute='user') | list }}"
        sys_crons_violation: "{{ sys_crons | difference(repo_crons) }}"
</code>```

result:

```<code>TASK [find] ************************

TASK [assert] **********************
fatal: [localhost]: FAILED! => {
    "assertion": "sys_crons_violation | count == 0",
    "changed": false,
    "evaluated_to": false,
    "msg": "This crons are not defined in repo : another_file"
}
</code>```

Body:
How to check if an object of a list of dictionaries is present in another list of dictionaries (with Ansible?)

You could try jinja filters selectattr - I had an issue with using it, so I did revert to a simplified but ugly solution - build a filtered list and compare filtered attributes only (list-to-list).
I do not like it, but it works.
Let me know if you know other way.

playbook:

- name: find existing system_crontabs  #would generate a list of dict
  find:
    path: /var/spool/cron/crontabs/
  register: system_side_crontabs
  become: True

- name: create lists of system_cron_names and repo_cron_names
  set_fact:
    system_cron_names: "[]"
    repo_cron_names: "[]"

- name: build list of system_cron_names
  set_fact:
    system_cron_names: "{{ system_cron_names }} + [ '{{ item.path |basename }}' ]"
  with_items: "{{ system_side_crontabs.files }}"

- name: build lists of repo_cron_names
  set_fact:
    repo_cron_names: "{{ repo_cron_names }} + [ '{{ item.user }}' ]"
  with_items: "{{ crontabs }}"

- name: assert check if an object of system_crontab is defined in repo_crontab
  assert:
    that: "{{ [item] |intersect(repo_cron_names) | length }} == 1"
  with_items: "{{ system_cron_names }}"

hosts_vars/prd-inner-mgmt202  #a list of dictionaries

crontabs:
  - user: root
    crontab_rules: |
      11 1 * * * find /home/ansible/.ansible/tmp/ -atime +10  -delete

a result of find

ok: [prd-inner-mgmt202] => {
    "changed": false,
    "examined": 1,
    "files": [                         ### List of dictionary
        {

            "path": "/var/spool/cron/crontabs/root",

        },
        {

            "path": "/var/spool/cron/crontabs/another_file",

        }
    ],
    "invocation": {
        "module_args": {
            "age": null,
            "age_stamp": "mtime",
            "contains": null,
            "file_type": "file",
            "follow": false,
            "get_checksum": false,
            "hidden": false,
            "path": "/var/spool/cron/crontabs/",
            "paths": [
                "/var/spool/cron/crontabs/"
            ],
            "patterns": [
                "*"
            ],
            "recurse": false,
            "size": null,
            "use_regex": false
        },
        "module_name": "find"
    },
    "matched": 1,
    "msg": ""
}

generate a list of strings that are easy to compare

TASK [mid_crontab : build list of system_cron_names] **************************
   "ansible_facts": {
        "system_cron_names": [
            "root",

        ]
    },
    "changed": false,
    "invocation": {
        "module_args": {
            "system_cron_names": [
                "root"
            ]
        },
        "module_name": "set_fact"
    },

generate another list of strings

TASK [mid_crontab : build list of repo_cron_names] *****************************

ok: [prd-inner-mgmt202] => (item={u'crontab_rules': u'11 1 * * * find /home/ansible/.ansible/tmp/ -atime +10  -delete\n', u'user': u'root'}) => {
    "ansible_facts": {
        "repo_cron_names": [
            "root"
        ]
    },
    "changed": false,
    "invocation": {
        "module_args": {
            "repo_cron_names": [
                "root",
        "other"
            ]
        },
        "module_name": "set_fact"
    },
    "item": {
        "crontab_rules": "11 1 * * * find /home/ansible/.ansible/tmp/ -atime +10  -delete\n",
        "user": "root"
    }
}

Assert the required check, use intersect jinja filter. In my case a system defined object (cron record) should exist in my repository - so the list should have 1 element.

TASK [mid_crontab : assert check if system_crontab is defined in repo_crontab] *

ok: [prd-inner-mgmt202] => (item=root) => {
    "changed": false,
    "invocation": {
        "module_args": {
            "that": "1 == 1"
        },
        "module_name": "assert"
    },
    "item": "root",
    "msg": "All assertions passed"
}

Body:
Seems you want to reduce original dict to list of strings (names) and compare the difference:

---
- hosts: localhost
  gather_facts: no
  vars:
    crontabs:
      - user: root
        crontab_rules: xxx
  tasks:
    - find:
        path: /tmp/test
      register: myfiles
    - assert:
        that: sys_crons_violation | count == 0
        msg: "This crons are not defined in repo : {{ sys_crons_violation | join(', ') }}"
      vars:
        sys_crons: "{{ myfiles.files | map(attribute='path') | map('basename') | list }}"
        repo_crons: "{{ crontabs | map(attribute='user') | list }}"
        sys_crons_violation: "{{ sys_crons | difference(repo_crons) }}"

result:

TASK [find] ************************

TASK [assert] **********************
fatal: [localhost]: FAILED! => {
    "assertion": "sys_crons_violation | count == 0",
    "changed": false,
    "evaluated_to": false,
    "msg": "This crons are not defined in repo : another_file"
}


问:
Does PowerShell support negation syntax in glob pattern?
In Linux, Bash supports negation syntax in glob pattern like [!abc] for one character other than a, b, and c.

I'm trying to find something similar in PowerShell.

In Supporting Wildcard Characters in Cmdlet Parameters, there is no description related to negation. Also, when test.txt exists, I confirmed the following, which indicates that ! is not supported as negation syntax like Bash.

ls tes[!s].txt returns nothing.

ls tes[!t].txt returns test.txt

Does PowerShell support negation syntax in glob pattern? If not, could you share some alternatives?

答:
No, it does not (as you correctly deduced from such a feature not being documented, nor working).

An alternative are regular expressions, but you'd have to do the filtering yourself, then:

```<code>Get-ChildItem | Where-Object Name -match '^tes[^t]\.txt$'
</code>```

Body:
No, it does not (as you correctly deduced from such a feature not being documented, nor working).

An alternative are regular expressions, but you'd have to do the filtering yourself, then:

Get-ChildItem | Where-Object Name -match '^tes[^t]\.txt$'


问:
Subreport overflowed on a band that does not support overflow
I recently had an issue with a subreport of my JasperReports's report in which I was getting the following error:

Subreport overflowed on a band that does not support overflow.

What is happening?

答:
I fixed the problem, so I thought I'd post my solution here in case someone found it useful.

Things to check:

If you're in a Detail band, check your report's Print Order. It has to be Vertical. Horizontal Print Order reports are not allowed to overflow on Detail bands.

Check your subreport's dimensions. The subreport's width must be smaller than the report's width, and, for non-growing bands (see point #3 below), the height must be smaller than the band's height.

Some bands grow, some bands don't. Keep this in mind with your subreports. If you have a subreport in a header or footer, make sure they do not grow, meaning that your datasource to that subreport can't send in too many elements, or send in repeating elements where your subreport is expecting one or few elements.

In my case, I had made a subreport and passed it a datasource that I wasn't actually using (it was an informational subreport not using any data from the datasource).

(the example is an XML datasource but the same concept applies to SQL datasources.)

e.g.

```<code>(net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}
    ).subDataSource("/Order/Note")
</code>```

Later, the "Note" was turned into an array instead of a single note. Which meant my footer-subreport was trying to repeat twice, thus the footer report was printing twice, making it too high. Thus the error.

Body:
I fixed the problem, so I thought I'd post my solution here in case someone found it useful.

Things to check:

If you're in a Detail band, check your report's Print Order. It has to be Vertical. Horizontal Print Order reports are not allowed to overflow on Detail bands.

Check your subreport's dimensions. The subreport's width must be smaller than the report's width, and, for non-growing bands (see point #3 below), the height must be smaller than the band's height.

Some bands grow, some bands don't. Keep this in mind with your subreports. If you have a subreport in a header or footer, make sure they do not grow, meaning that your datasource to that subreport can't send in too many elements, or send in repeating elements where your subreport is expecting one or few elements.

In my case, I had made a subreport and passed it a datasource that I wasn't actually using (it was an informational subreport not using any data from the datasource).

(the example is an XML datasource but the same concept applies to SQL datasources.)

e.g.

(net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}
    ).subDataSource("/Order/Note")

Later, the "Note" was turned into an array instead of a single note. Which meant my footer-subreport was trying to repeat twice, thus the footer report was printing twice, making it too high. Thus the error.


问:
Looping through multiple subjects/sessions
Hi everyone I wrote a for loop which I want to use on multiple sessions of a subject. I have a datapath: C:\Users\Rouve\Documents\Promotion\tDCS\DATA\VP01\ where three folders: Session1, Session2, Session3 are located. Each of these folders contains 15 textfiles (test1.txt, test2.txt ... test15.txt). My goal is to run the for loop, which loads the 15 files inside one session, puts them into a cell, extracts the max values of each dataset inside of that cell and then averages every three max values over all sessions and puts them into a final file, so I would get 5 values per session.
When I run the loop for one session it works and looks like this:

```<code>Volume_name='C:\Users\Rouve\Documents\Promotion\tDCS\DATA\VP02\Session1';

files=dir(fullfile(Volume_name,'*.txt'));
files={files.name}';
files_sorted=natsortfiles(files);
fileName=ls('*txt');

data = cell(numel(files_sorted),1);                %# store file contents
for i=1:numel(files_sorted)
    fname = fullfile(Volume_name,files_sorted{i});     %# full path to file
    data{i} = dlmread(fname, '\t', 19, 1);        %# load file
end
for i=1:length(data) %# get Max values of each trial (15 per session in total)
        MaxValues(i)=max(data{i});
end
MaxValues=MaxValues';

Mean_values=mean(reshape(MaxValues,3,[]));
Mean_values=Mean_values';
</code>```

I just cannot seem to figure out how to construct the for loop so it does this automatically for all three sessions and outputs three variables, containing the 5 values of session 01, session 02 and session 03. I really hope you can help me!

答:
You can concatenate strings using [] as if creating a regular array and then process each folder within a loop while storing the mean data in a common array,

```<code>subdir = {'Session1', 'Session2', 'Session3'};

Mean_values = zeros(3,5);
for nv = 1:3
    Volume_name=['C:\Users\Rouve\Documents\Promotion\tDCS\DATA\VP02\', char(subdir{nv})]

    files=dir(fullfile(Volume_name,'*.txt'));
    files={files.name}';
    files_sorted=natsortfiles(files);
    fileName=ls('*txt');

    data = cell(numel(files_sorted),1);                %# store file contents
    for i=1:numel(files_sorted)
        fname = fullfile(Volume_name,files_sorted{i});     %# full path to file
        data{i} = dlmread(fname, '\t', 19, 1);        %# load file
    end
    for i=1:length(data) %# get Max values of each trial (15 per session in total)
            MaxValues(i)=max(data{i});
    end
    MaxValues=MaxValues';

    Mean_values(nv, :)=mean(reshape(MaxValues,3,[]));

    % Reset the data and MaxValues cell
    data = {};
    MaxValues = [];
end

save('mean_out.txt', 'Mean_values', '-ascii')
</code>```

I'm not sure if I understood correctly (please clarify if not) - but you want an output file with the 5 means from each folder. This is what this program does - for each folder it finds the 5 means and stores them in a row of a common array Mean_values. After processing all the directories it saves the common array into a file 'mean_out.txt' using matlab save command for ascii format.

Since your program is not readily reproducible, I did not check it - if you run into an error, let me know.

Also this is one possibility - there are others, like appending the data into the file after each outer loop (nv) iteration in which case one would not need the common array. The reseting of reused variables at the end of the loop is not necessary since your data is all the same length, but it is good to keep in mind as a necessity for bug prevention when your data is not the same length.

Body:
Hi everyone I wrote a for loop which I want to use on multiple sessions of a subject. I have a datapath: C:\Users\Rouve\Documents\Promotion\tDCS\DATA\VP01\ where three folders: Session1, Session2, Session3 are located. Each of these folders contains 15 textfiles (test1.txt, test2.txt ... test15.txt). My goal is to run the for loop, which loads the 15 files inside one session, puts them into a cell, extracts the max values of each dataset inside of that cell and then averages every three max values over all sessions and puts them into a final file, so I would get 5 values per session.
When I run the loop for one session it works and looks like this:

Volume_name='C:\Users\Rouve\Documents\Promotion\tDCS\DATA\VP02\Session1';

files=dir(fullfile(Volume_name,'*.txt'));
files={files.name}';
files_sorted=natsortfiles(files);
fileName=ls('*txt');

data = cell(numel(files_sorted),1);                %# store file contents
for i=1:numel(files_sorted)
    fname = fullfile(Volume_name,files_sorted{i});     %# full path to file
    data{i} = dlmread(fname, '\t', 19, 1);        %# load file
end
for i=1:length(data) %# get Max values of each trial (15 per session in total)
        MaxValues(i)=max(data{i});
end
MaxValues=MaxValues';

Mean_values=mean(reshape(MaxValues,3,[]));
Mean_values=Mean_values';

I just cannot seem to figure out how to construct the for loop so it does this automatically for all three sessions and outputs three variables, containing the 5 values of session 01, session 02 and session 03. I really hope you can help me!

Body:
You can concatenate strings using [] as if creating a regular array and then process each folder within a loop while storing the mean data in a common array,

subdir = {'Session1', 'Session2', 'Session3'};

Mean_values = zeros(3,5);
for nv = 1:3
    Volume_name=['C:\Users\Rouve\Documents\Promotion\tDCS\DATA\VP02\', char(subdir{nv})]

    files=dir(fullfile(Volume_name,'*.txt'));
    files={files.name}';
    files_sorted=natsortfiles(files);
    fileName=ls('*txt');

    data = cell(numel(files_sorted),1);                %# store file contents
    for i=1:numel(files_sorted)
        fname = fullfile(Volume_name,files_sorted{i});     %# full path to file
        data{i} = dlmread(fname, '\t', 19, 1);        %# load file
    end
    for i=1:length(data) %# get Max values of each trial (15 per session in total)
            MaxValues(i)=max(data{i});
    end
    MaxValues=MaxValues';

    Mean_values(nv, :)=mean(reshape(MaxValues,3,[]));

    % Reset the data and MaxValues cell
    data = {};
    MaxValues = [];
end

save('mean_out.txt', 'Mean_values', '-ascii')

I'm not sure if I understood correctly (please clarify if not) - but you want an output file with the 5 means from each folder. This is what this program does - for each folder it finds the 5 means and stores them in a row of a common array Mean_values. After processing all the directories it saves the common array into a file 'mean_out.txt' using matlab save command for ascii format.

Since your program is not readily reproducible, I did not check it - if you run into an error, let me know.

Also this is one possibility - there are others, like appending the data into the file after each outer loop (nv) iteration in which case one would not need the common array. The reseting of reused variables at the end of the loop is not necessary since your data is all the same length, but it is good to keep in mind as a necessity for bug prevention when your data is not the same length.


问:
svn checkout fails with error svn cleanup required
When checking out source code on same server at same location at same time checkout fails with error
cleanup required

is there a way we can avoid this. Is this due to some race condition.

答:
The wording that sticks out to me is

... on same server at same location ...

If you're doing a checkout in the same location, you're pretty much asking for errors. To avoid this, checkout into a new directory each time and then do svn update commands on your checked out folder. You only need to check out once.


问:
CSS absolute position orients on sibling rather than parent
I am a little confused about absolute positioning right now. I have always thought that if I position an element absolutely it would be positioned relative to it's parent element (in contrast to relative to it's usual position like  relative positioning). During homework I now came across this situation and I'm confused:

```<code><body>
  <div> <!-- This is colored red in my example -->
    ...
  </div>
  <div style="position: absolute;"> <!-- This is colored green in my example -->
    ...
  </div>
</body>
</code>```

What I would expect:

What I got:

Of course when I set an actual position with left/right/top/bottom I get what I would expect from an absolutely positioned element. So is position: absolute just set to take the exact position it would be at without position: absolute when not specified otherwise?

答:
To clarify:

"I have always thought that if I position an element absolutely it would
  be positioned relative to it's parent element"

Nope. If an element has position: absolute;, it is positioned relative to the nearest parent in the DOM chain that has position: relative; or position: absolute; specified on it.  If no parents have it (ie. they are all position: static, which is the default), then it is positioned relative to the document (page).

When using position: absolute, always:

Be aware of what parent you want it positioned relative to, and make sure that parent has position: relative; on it.

Specify one or more of the top/right/bottom/left attributes on the absolutely positioned object.

Body:
I am a little confused about absolute positioning right now. I have always thought that if I position an element absolutely it would be positioned relative to it's parent element (in contrast to relative to it's usual position like  relative positioning). During homework I now came across this situation and I'm confused:

    ...

    ...

What I would expect:

What I got:

Of course when I set an actual position with left/right/top/bottom I get what I would expect from an absolutely positioned element. So is position: absolute just set to take the exact position it would be at without position: absolute when not specified otherwise?


问:
Spring State machine JPA persistence
I am new to Spring state machine I have the state configuration given below I need to persist the state changes using JPA in mysql. Any proper example is also very helpful for me. Thanks in advance</p>

```<code>@Configuration
@EnableStateMachine(name = "machine1")
public class Config extends StateMachineConfigurerAdapter<String, String>{

@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
    config.withConfiguration().autoStartup(true).listener(listener());
}

@Override
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
    states
        .withStates()
            .initial("S1")
            .state("S1")
            .state("S2",null,action1())
            .state("S3");
}

@Override
public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
    transitions
        .withExternal()
            .source("S1")
            .target("S2")
            .event("E1")
            .and().withExternal()
            .source("S2")
            .target("S3")
            .event("E2");
}

}
</code>```

答:
jpa-config is just an example keeping machine configuration(states, transitions, etc) in a DB. You don't need this if you use other means(javadsl or uml) of making a config. This support were adding as some people wanted to have a way to modify machine configs without compiling sources again. I'm currently working on adding better support for persisting machine via same type of spring data repository abstractions, this should land in 1.2.8.

Some other samples are some examples how thing can be done manually. Currently this process is indeed very manual, low level and rather cumbersome. If you not in rush, I'd recommend using 1.2.8 snapshots from 1.2.x branch. i.e. there's new sample datajpapersist showing cleaner model persisting machine at runtime.

Title: Spring State machine JPA persistence

Body:
I am new to Spring state machine I have the state configuration given below I need to persist the state changes using JPA in mysql. Any proper example is also very helpful for me. Thanks in advance

@Configuration
@EnableStateMachine(name = "machine1")
public class Config extends StateMachineConfigurerAdapter<String, String>{

@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
    config.withConfiguration().autoStartup(true).listener(listener());
}

@Override
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
    states
        .withStates()
            .initial("S1")
            .state("S1")
            .state("S2",null,action1())
            .state("S3");
}

@Override
public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
    transitions
        .withExternal()
            .source("S1")
            .target("S2")
            .event("E1")
            .and().withExternal()
            .source("S2")
            .target("S3")
            .event("E2");
}

}


问:
How to have objects contiguous in memory without loosing OOP?
Consider a code where we have a list of countries that contain a list of cities that contains a list of streets. Each City in a given Country contains exactly the same number of Streets (nbStreetsPerCity) and this number of streets per City is constant over time.

```<code>class Street
{

};

class City
{
   // Attribute
   std::vector<Street> Streets;

   // getter
   Street& getStreet(int street_index) {return Streets[street_index];}
   // More stuff

};

class Country
{
   // Attribute
   std::vector<City> Cities;

   // getter
   City& getCity(int city_index) {return Cities[city_index];}

   // More stuff

};
</code>```

I have to loop through each Street and the process is quite fast when I have many Streets and few Cityies but is quite slow when I have many Cityies with few Streets

With such code, the Streets of all Cityies of a given Country are not contiguous in memory. For performance reasons, I would like to try a code with having all Streets of a given Country being contiguous in memory. I can't think of a way to have all the Streets contiguous in memory without destroying part of the object oriented programming.

```<code>class Street
{

};

class Country
{
   // Attribute
   std::vector<Street> Streets;
   int nbStreetsPerCity;

   // getter
   City getStreet(int city_index, int street_index)
   {
       Streets[city_index*nbStreetsPerCity + street_index]
   };

   // More stuff

};
</code>```

With such code, all Streets of a given country are contiguous in memory, however, I lost the City object and therefore lost the advantage of OOP.

Is there a way to have all streets being contiguous in memory without loosing the advantage of OOP?

A very simple example would be very welcome!

答:
The way to do this is to have a 'StreetManager' that contains your vector of streets.  Your City and Country then contain references to the streets held by your street manager.

When I say 'references' these may be just indexes or some id or anything else that will allow lookup as per your read/write requirements.

By read/write requirements, I refer to the fact that references may be broken on vector edit, indexes will be broken on vector removal, and id will require a map of id -> index maintained by the manager.

The functions 'getStreets' in your City/country then just need to hand the indexes/ids to the manager and return the result.

The important thing to bear in mind is that attempting to edit the # of Streets in the manager will result in all the references being broken.

Body:
Consider a code where we have a list of countries that contain a list of cities that contains a list of streets. Each City in a given Country contains exactly the same number of Streets (nbStreetsPerCity) and this number of streets per City is constant over time.

class Street
{

};

class City
{
   // Attribute
   std::vector<Street> Streets;

   // getter
   Street& getStreet(int street_index) {return Streets[street_index];}
   // More stuff

};

class Country
{
   // Attribute
   std::vector<City> Cities;

   // getter
   City& getCity(int city_index) {return Cities[city_index];}

   // More stuff

};

I have to loop through each Street and the process is quite fast when I have many Streets and few Cityies but is quite slow when I have many Cityies with few Streets

With such code, the Streets of all Cityies of a given Country are not contiguous in memory. For performance reasons, I would like to try a code with having all Streets of a given Country being contiguous in memory. I can't think of a way to have all the Streets contiguous in memory without destroying part of the object oriented programming.

class Street
{

};

class Country
{
   // Attribute
   std::vector<Street> Streets;
   int nbStreetsPerCity;

   // getter
   City getStreet(int city_index, int street_index)
   {
       Streets[city_index*nbStreetsPerCity + street_index]
   };

   // More stuff

};

With such code, all Streets of a given country are contiguous in memory, however, I lost the City object and therefore lost the advantage of OOP.

Is there a way to have all streets being contiguous in memory without loosing the advantage of OOP?

A very simple example would be very welcome!


问:
Facebook token expiration and renewal, with Koala and omniauth-facebook
I'm writing a Rails app that uses omniauth-facebook to authenticate the user against FB (and to get a FB OAuth access token for the user).  The app then uses Koala to make various calls to the FB Graph API, using that saved OAuth token.

I update the saved token each time the user re-authenticates (typically when they log in to my app).  Even so, that saved token will expire (or otherwise become invalid) from time to time.

What's the best practice around guarding against auth failures and updating the token while using Koala?

Should all calls be wrapped in begin/rescue blocks, with an exception handler that re-authenticates the user against FB?

Is there some way (using Koala) to take advantage of the 'extending access tokens' process described here?  If not, are there best practices on writing my own code to extract the new token myself from a Koala call?

答:
You can do something like this where you check if the access_token is expired and generate another one.

```<code> %w[facebook].each do |provider|
   scope provider, -> { where(provider: provider) }
 end

 def client
   send("#{provider}_client")
 end

 def expired?
   expires_at? && expires_at <= Time.zone.now
 end

 def access_token
   send("#{provider}_refresh_token!", super) if expired?
   super
 end

 def facebook_refresh_token!(token)
   new_token_info =
   Koala::Facebook::OAuth.new.exchange_access_token_info(token)
   update(access_token: new_token_info["access_token"], expires_at: Time.zone.now + new_token_info["expires_in"])
 end
</code>```

You can check gorails screencast that explains this on depth.

Body:
You can do something like this where you check if the access_token is expired and generate another one.

 %w[facebook].each do |provider|
   scope provider, -> { where(provider: provider) }
 end

 def client
   send("#{provider}_client")
 end

 def expired?
   expires_at? && expires_at <= Time.zone.now
 end

 def access_token
   send("#{provider}_refresh_token!", super) if expired?
   super
 end

 def facebook_refresh_token!(token)
   new_token_info =
   Koala::Facebook::OAuth.new.exchange_access_token_info(token)
   update(access_token: new_token_info["access_token"], expires_at: Time.zone.now + new_token_info["expires_in"])
 end

You can check gorails screencast that explains this on depth.


问:
What is/are the generally accepted design patterns for Javascript bookmarklets?
Is it best to insert an iFrame and do whatever needs to be done in there, so as to not clutter the page with your extra scripts, CSS styles, etc? How do you detect that things are complete and remove the iFrame when you can't talk between the main window and the iFrame?

Is it acceptable to insert scripts/CSS into the DOM and do your work there?

My main example is the Instapaper bookmarklet, which uses an iFrame and closes it when it's all done.

答:
All the bookmarklets i have ever done are directly inserted into the DOM of the main page. All the code has lived inside a namespace for that bookmarklet so the DOM pollution is kept at a minimum, and of course there are checks to make sure there are no collisions with existing variable names.

The reason for insertion into the DOM of the main document is because it makes everything easier - there is rarely any good reason to make it harder on yourself than it has to be :)

But of course this depends on your goals.

ContentLicense: CC BY-SA 2.5


问:
automatically generating a map with the fields of a class
I have the following class

```<code>@Data
public class CMC{

  String f1;
  String f2;
  String f3;
  public Map<String, Supplier<String>> valuesMap() {
    return ImmutableMap.<String, Supplier<String>>builder()
        .put("f1", this::f1)
        .put("f2", this::f2)
        .put("f3", this::f3)
        .build();
  }

}
</code>```

As you can see I have a few fields and a map for that contains each field pointing to a function that returns the value of that field.

The problem with this solution is that a developer may get here and add a new field but forgets to add it to a map.

Is there a way to automate this process?

I was hoping for something like lombok to help me with this case. It's a common thing to need a list of the field from a class and have access to their values.

To solve this I would create an annotation and then somehow use reflection to obtain my desired behavior but I suppose something like this has been already implemented in some tools.

答:
You should look into: Class::getDeclaredFields; Class::getSuperclass; and Field.  Together, they should be able to get pretty much what you're looking for...  Something like:

```<code>final Map<String, Object> map = new HashMap<>();
Class<?> klass = this.getClass();
while (klass != null) {
    for (final Field field : klass.getDeclaredFields()) {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        map.put(field.getName(), field.get(this));
    }
    klass = klass.getSuperclass();
}
</code>```

You'll need to handle exceptions, work out where to call this, and confirm if you want to do it for all fields (private, etc.) or just some, whether to lazily cache the value somewhere, and whether everything needs converting to a String (in which case the Object in the map can be changed).

Body:
I have the following class

@Data
public class CMC{

  String f1;
  String f2;
  String f3;
  public Map<String, Supplier<String>> valuesMap() {
    return ImmutableMap.<String, Supplier<String>>builder()
        .put("f1", this::f1)
        .put("f2", this::f2)
        .put("f3", this::f3)
        .build();
  }

}

As you can see I have a few fields and a map for that contains each field pointing to a function that returns the value of that field.

The problem with this solution is that a developer may get here and add a new field but forgets to add it to a map.

Is there a way to automate this process?

I was hoping for something like lombok to help me with this case. It's a common thing to need a list of the field from a class and have access to their values.

To solve this I would create an annotation and then somehow use reflection to obtain my desired behavior but I suppose something like this has been already implemented in some tools.

Body:
You should look into: Class::getDeclaredFields; Class::getSuperclass; and Field.  Together, they should be able to get pretty much what you're looking for...  Something like:

final Map<String, Object> map = new HashMap<>();
Class<?> klass = this.getClass();
while (klass != null) {
    for (final Field field : klass.getDeclaredFields()) {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        map.put(field.getName(), field.get(this));
    }
    klass = klass.getSuperclass();
}

You'll need to handle exceptions, work out where to call this, and confirm if you want to do it for all fields (private, etc.) or just some, whether to lazily cache the value somewhere, and whether everything needs converting to a String (in which case the Object in the map can be changed).


问:
To be assigned value as variable in jq
json processor jq for a package.json

```<code>{
  "someparent" : {
    "somechild" : "oldvalue"
  }
}
</code>```

If I run the following command (to change oldvalue to somevalue):

```<code>jq '.someparent["somechild"] = "somevalue" "$aDirection/package.json"'
</code>```

It is successfully changed. However, if I give a variable instead of someValue:

```<code> aVar="anotherValue"
 jq '.someparent["somechild"] = "$aVar" "$aDirection/package.json"'
</code>```

It is not working.
What I already tried:

```<code>["aVar"] #interpreted as string
["$aVar"] #interpreted as string
"$aVar" # aVar is not defined
$avar #aVar is not defined
</code>```

答:
The single quotes around the jq filter are in  the wrong place. In your attempt made it is also enclosing the actual JSON file input. The right syntax when applying filter over files is

```<code>jq '<filter>' json-file
</code>```

In your case the right filter is just

```<code>.someparent["somechild"] = $aVar
</code>```

and to use a shell variable in to the jq, you need to use the --arg field. Putting together both of the options. The first variable after --arg is used in the context of jq and the one following it is the actual shell variable.

```<code>aVar="anotherValue"
jq --arg aVar "$aVar" '.someparent["somechild"] = $aVar' "$aDirection/package.json"
#                                                    ^^^^ Remember the single quote
#                                                    terminating here and not extended
</code>```

Title: To be assigned value as variable in jq

Body:
json processor jq for a package.json

{
  "someparent" : {
    "somechild" : "oldvalue"
  }
}

If I run the following command (to change oldvalue to somevalue):

jq '.someparent["somechild"] = "somevalue" "$aDirection/package.json"'

It is successfully changed. However, if I give a variable instead of someValue:

 aVar="anotherValue"
 jq '.someparent["somechild"] = "$aVar" "$aDirection/package.json"'

It is not working.
What I already tried:

["aVar"] #interpreted as string
["$aVar"] #interpreted as string
"$aVar" # aVar is not defined
$avar #aVar is not defined

Body:
The single quotes around the jq filter are in  the wrong place. In your attempt made it is also enclosing the actual JSON file input. The right syntax when applying filter over files is

jq '<filter>' json-file

In your case the right filter is just

.someparent["somechild"] = $aVar

and to use a shell variable in to the jq, you need to use the --arg field. Putting together both of the options. The first variable after --arg is used in the context of jq and the one following it is the actual shell variable.

aVar="anotherValue"
jq --arg aVar "$aVar" '.someparent["somechild"] = $aVar' "$aDirection/package.json"
#                                                    ^^^^ Remember the single quote
#                                                    terminating here and not extended


问:
Create JSON object from complex string array
I have been given these test inputs that need to be parsed into a JSON object organized by their Key split by an underscore.

```<code>var testInput1 = '{"Data_Structure_Test1": "Test1 Data"}';
var testInput2 = '{"Data_Structure_Test2": "Test2 Data"}';
var testInput3 = '{"Data_Structure_Test3": "Test3 Data"}';
var testInput4 = '{"Data_AnotherStructure": "AnotherStructure Data"}';
var testInput5 = '{"Data_JustAnother": "JustAnother Data"}';
var testInput6 = '{"NewData_NewTest": "NewTest Data"}';
</code>```

So the above testInputs should spit out:

```<code>{
    "Data": {
        "Structure": {
            "Test1": "Test1 Data",
            "Test2": "Test2 Data",
            "Test3": "Test3 Data"
        },
        "AnotherStructure": "AnotherStructure Data",
        "JustAnother": "JustAnother Data"
    },
    "NewData": {
        "NewTest": "NewTest Data"
    }
}
</code>```

I can't seem to get the JSON objects to collect into the correct container.

Here is a JSFiddle that I have been using to test with

Here is my function that I am calling to parse the string

```<code>function parse_input(aInput) {

let jObj = JSON.parse(aInput);

  for (let key in jObj) {

    let objKeys = key.split("_");

    for (i = 0; i < objKeys.length; i++) {

      if (data.hasOwnProperty(objKeys[i])) {

        data[key] = jObj[key];
      } else {

        data[objKeys[i]] = jObj[key];
      }
    }
</code>```

And how I am passing in the inputs:

```<code>var data = {};

parse_input(testInput1);
parse_input(testInput2);
parse_input(testInput3);
parse_input(testInput4);
parse_input(testInput5);
parse_input(testInput6);

var result = JSON.stringify(data, undefined, '\t');
</code>```

Can anyone see what I am doing wrong?

I do have access the jQuery framework if that will make this any easier.

答:
```<code> function parse_input(json){
   const obj = JSON.parse(json);
   for(const key in obj){
      const keys = key.split("_");
      keys.slice(0,-1).reduce(function(obj, key){
          return obj[key] || (obj[key] = {});
      }, data)[keys.pop()] = obj[key];
   }
}
</code>```

You may want to use reduce to go deep into the data object.

Body:
I have been given these test inputs that need to be parsed into a JSON object organized by their Key split by an underscore.

var testInput1 = '{"Data_Structure_Test1": "Test1 Data"}';
var testInput2 = '{"Data_Structure_Test2": "Test2 Data"}';
var testInput3 = '{"Data_Structure_Test3": "Test3 Data"}';
var testInput4 = '{"Data_AnotherStructure": "AnotherStructure Data"}';
var testInput5 = '{"Data_JustAnother": "JustAnother Data"}';
var testInput6 = '{"NewData_NewTest": "NewTest Data"}';

So the above testInputs should spit out:

{
    "Data": {
        "Structure": {
            "Test1": "Test1 Data",
            "Test2": "Test2 Data",
            "Test3": "Test3 Data"
        },
        "AnotherStructure": "AnotherStructure Data",
        "JustAnother": "JustAnother Data"
    },
    "NewData": {
        "NewTest": "NewTest Data"
    }
}

I can't seem to get the JSON objects to collect into the correct container.

Here is a JSFiddle that I have been using to test with

Here is my function that I am calling to parse the string

function parse_input(aInput) {

let jObj = JSON.parse(aInput);

  for (let key in jObj) {

    let objKeys = key.split("_");

    for (i = 0; i < objKeys.length; i++) {

      if (data.hasOwnProperty(objKeys[i])) {

        data[key] = jObj[key];
      } else {

        data[objKeys[i]] = jObj[key];
      }
    }

And how I am passing in the inputs:

var data = {};

parse_input(testInput1);
parse_input(testInput2);
parse_input(testInput3);
parse_input(testInput4);
parse_input(testInput5);
parse_input(testInput6);

var result = JSON.stringify(data, undefined, '\t');

Can anyone see what I am doing wrong?

I do have access the jQuery framework if that will make this any easier.

Body:
 function parse_input(json){
   const obj = JSON.parse(json);
   for(const key in obj){
      const keys = key.split("_");
      keys.slice(0,-1).reduce(function(obj, key){
          return obj[key] || (obj[key] = {});
      }, data)[keys.pop()] = obj[key];
   }
}

You may want to use reduce to go deep into the data object.


问:
solving non-linear equation with constraints in R
I need to convert an VBA script to R. There is solver involved and I do not know which package to choose or how to implement the following problem:

equations:

y=0.42*a+(1-0.42)*b

(y is a given value between 0 and 1)

4.65=(a/(1-a))/(b/(1-b))

variables: a, b

constraints:

0 < a < 1; 0 < b < 1

Could anyone help me with this?

答:
Construct a function f like this

```<code>f <- function(x,y) {
    z <- numeric(length(x))
    # x[1] is a
    # x[2] is b
    # y=0.42*a+(1-0.42)*b
    # 4.65=(a/(1-a))/(b/1-b))

    z[1] <- y - (.42*x[1]+(1-.42)*x[2])
    z[2] <- 4.65 - (x[1]/(1-x[1]))/(x[2]/(1-x[2]))
    z
}
</code>```

To find a zero for f different values for y satisfying you restriction you could try something like this:

```<code>xstart <- c(.5,.5)

for( y in seq(.1,.9,.1) ) {
    res <- nleqslv(xstart,f,y=y)
    cat("*** y = ", y, "***\n")
    print(res)
}
</code>```

And do not forget to test if a solution was found (see the documentation of package nleqslv). It appears that the solution satisfies your restriction.
You can't constrain the solution if you want to find a zero of the function. If it doesn't satisfy your restriction there is no solution.
If a solution does not satisfy your restrictions you could skip it.

Body:
Construct a function f like this

f <- function(x,y) {
    z <- numeric(length(x))
    # x[1] is a
    # x[2] is b
    # y=0.42*a+(1-0.42)*b
    # 4.65=(a/(1-a))/(b/1-b))

    z[1] <- y - (.42*x[1]+(1-.42)*x[2])
    z[2] <- 4.65 - (x[1]/(1-x[1]))/(x[2]/(1-x[2]))
    z
}

To find a zero for f different values for y satisfying you restriction you could try something like this:

xstart <- c(.5,.5)

for( y in seq(.1,.9,.1) ) {
    res <- nleqslv(xstart,f,y=y)
    cat("*** y = ", y, "***\n")
    print(res)
}

And do not forget to test if a solution was found (see the documentation of package nleqslv). It appears that the solution satisfies your restriction.
You can't constrain the solution if you want to find a zero of the function. If it doesn't satisfy your restriction there is no solution.
If a solution does not satisfy your restrictions you could skip it.


问:
How I can I lazily read multiple JSON values from a file/stream in Python?
I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately json.load() just .read()s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.

Is there any way to do this? Using the standard library would be ideal, but if there's a third-party library I'd use that instead.

At the moment I'm putting each object on a separate line and using json.loads(f.readline()), but I would really prefer not to need to do this.

Example Use

example.py

import my_json as json
import sys

for o in json.iterload(sys.stdin):
    print("Working on a", type(o))
```

<h3>in.txt</h3>

<pre class="lang-js prettyprint-override"><code>{"foo": ["bar", "baz"]} 1 2 [] 4 5 6
</code>```

example session

$ python3.2 example.py < in.txt
Working on a dict
Working on a int
Working on a int
Working on a list
Working on a int
Working on a int
Working on a int
```

答:
I believe a better way of doing it would be to use a state machine. Below is a sample code that I worked out by converting a NodeJS code on below link to Python <s>3 (used nonlocal keyword only available in Python 3, code won't work on Python 2)</s>

Edit-1: Updated and made code compatible with Python 2

Edit-2: Updated and added a Python3 only version as well

https://gist.github.com/creationix/5992451

Python 3 only version

```<code># A streaming byte oriented JSON parser.  Feed it a single byte at a time and
# it will emit complete objects as it comes across them.  Whitespace within and
# between objects is ignored.  This means it can parse newline delimited JSON.
import math

def json_machine(emit, next_func=None):
    def _value(byte_data):
        if not byte_data:
            return

        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _value  # Ignore whitespace

        if byte_data == 0x22:  # "
            return string_machine(on_value)

        if byte_data == 0x2d or (0x30 <= byte_data < 0x40):  # - or 0-9
            return number_machine(byte_data, on_number)

        if byte_data == 0x7b:  #:
            return object_machine(on_value)

        if byte_data == 0x5b:  # [
            return array_machine(on_value)

        if byte_data == 0x74:  # t
            return constant_machine(TRUE, True, on_value)

        if byte_data == 0x66:  # f
            return constant_machine(FALSE, False, on_value)

        if byte_data == 0x6e:  # n
            return constant_machine(NULL, None, on_value)

        if next_func == _value:
            raise Exception("Unexpected 0x" + str(byte_data))

        return next_func(byte_data)

    def on_value(value):
        emit(value)
        return next_func

    def on_number(number, byte):
        emit(number)
        return _value(byte)

    next_func = next_func or _value
    return _value

TRUE = [0x72, 0x75, 0x65]
FALSE = [0x61, 0x6c, 0x73, 0x65]
NULL = [0x75, 0x6c, 0x6c]

def constant_machine(bytes_data, value, emit):
    i = 0
    length = len(bytes_data)

    def _constant(byte_data):
        nonlocal i
        if byte_data != bytes_data[i]:
            i += 1
            raise Exception("Unexpected 0x" + str(byte_data))

        i += 1
        if i < length:
            return _constant
        return emit(value)

    return _constant

def string_machine(emit):
    string = ""

    def _string(byte_data):
        nonlocal string

        if byte_data == 0x22:  # "
            return emit(string)

        if byte_data == 0x5c:  # \
            return _escaped_string

        if byte_data & 0x80:  # UTF-8 handling
            return utf8_machine(byte_data, on_char_code)

        if byte_data < 0x20:  # ASCII control character
            raise Exception("Unexpected control character: 0x" + str(byte_data))

        string += chr(byte_data)
        return _string

    def _escaped_string(byte_data):
        nonlocal string

        if byte_data == 0x22 or byte_data == 0x5c or byte_data == 0x2f:  # " \ /
            string += chr(byte_data)
            return _string

        if byte_data == 0x62:  # b
            string += "\b"
            return _string

        if byte_data == 0x66:  # f
            string += "\f"
            return _string

        if byte_data == 0x6e:  # n
            string += "\n"
            return _string

        if byte_data == 0x72:  # r
            string += "\r"
            return _string

        if byte_data == 0x74:  # t
            string += "\t"
            return _string

        if byte_data == 0x75:  # u
            return hex_machine(on_char_code)

    def on_char_code(char_code):
        nonlocal string
        string += chr(char_code)
        return _string

    return _string

# Nestable state machine for UTF-8 Decoding.
def utf8_machine(byte_data, emit):
    left = 0
    num = 0

    def _utf8(byte_data):
        nonlocal num, left
        if (byte_data & 0xc0) != 0x80:
            raise Exception("Invalid byte in UTF-8 character: 0x" + byte_data.toString(16))

        left = left - 1

        num |= (byte_data & 0x3f) << (left * 6)
        if left:
            return _utf8
        return emit(num)

    if 0xc0 <= byte_data < 0xe0:  # 2-byte UTF-8 Character
        left = 1
        num = (byte_data & 0x1f) << 6
        return _utf8

    if 0xe0 <= byte_data < 0xf0:  # 3-byte UTF-8 Character
        left = 2
        num = (byte_data & 0xf) << 12
        return _utf8

    if 0xf0 <= byte_data < 0xf8:  # 4-byte UTF-8 Character
        left = 3
        num = (byte_data & 0x07) << 18
        return _utf8

    raise Exception("Invalid byte in UTF-8 string: 0x" + str(byte_data))

# Nestable state machine for hex escaped characters
def hex_machine(emit):
    left = 4
    num = 0

    def _hex(byte_data):
        nonlocal num, left

        if 0x30 <= byte_data < 0x40:
            i = byte_data - 0x30
        elif 0x61 <= byte_data <= 0x66:
            i = byte_data - 0x57
        elif 0x41 <= byte_data <= 0x46:
            i = byte_data - 0x37
        else:
            raise Exception("Expected hex char in string hex escape")

        left -= 1
        num |= i << (left * 4)

        if left:
            return _hex
        return emit(num)

    return _hex

def number_machine(byte_data, emit):
    sign = 1
    number = 0
    decimal = 0
    esign = 1
    exponent = 0

    def _mid(byte_data):
        if byte_data == 0x2e:  # .
            return _decimal

        return _later(byte_data)

    def _number(byte_data):
        nonlocal number
        if 0x30 <= byte_data < 0x40:
            number = number * 10 + (byte_data - 0x30)
            return _number

        return _mid(byte_data)

    def _start(byte_data):
        if byte_data == 0x30:
            return _mid

        if 0x30 < byte_data < 0x40:
            return _number(byte_data)

        raise Exception("Invalid number: 0x" + str(byte_data))

    if byte_data == 0x2d:  # -
        sign = -1
        return _start

    def _decimal(byte_data):
        nonlocal decimal
        if 0x30 <= byte_data < 0x40:
            decimal = (decimal + byte_data - 0x30) / 10
            return _decimal

        return _later(byte_data)

    def _later(byte_data):
        if byte_data == 0x45 or byte_data == 0x65:  # E e
            return _esign

        return _done(byte_data)

    def _esign(byte_data):
        nonlocal esign
        if byte_data == 0x2b:  # +
            return _exponent

        if byte_data == 0x2d:  # -
            esign = -1
            return _exponent

        return _exponent(byte_data)

    def _exponent(byte_data):
        nonlocal exponent
        if 0x30 <= byte_data < 0x40:
            exponent = exponent * 10 + (byte_data - 0x30)
            return _exponent

        return _done(byte_data)

    def _done(byte_data):
        value = sign * (number + decimal)
        if exponent:
            value *= math.pow(10, esign * exponent)

        return emit(value, byte_data)

    return _start(byte_data)

def array_machine(emit):
    array_data = []

    def _array(byte_data):
        if byte_data == 0x5d:  # ]
            return emit(array_data)

        return json_machine(on_value, _comma)(byte_data)

    def on_value(value):
        array_data.append(value)

    def _comma(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return json_machine(on_value, _comma)

        if byte_data == 0x5d:  # ]
            return emit(array_data)

        raise Exception("Unexpected byte: 0x" + str(byte_data) + " in array body")

    return _array

def object_machine(emit):
    object_data = {}
    key = None

    def _object(byte_data):
        if byte_data == 0x7d:  #
            return emit(object_data)

        return _key(byte_data)

    def _key(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _object  # Ignore whitespace

        if byte_data == 0x22:
            return string_machine(on_key)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    def on_key(result):
        nonlocal key
        key = result
        return _colon

    def _colon(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _colon  # Ignore whitespace

        if byte_data == 0x3a:  # :
            return json_machine(on_value, _comma)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    def on_value(value):
        object_data[key] = value

    def _comma(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return _key

        if byte_data == 0x7d:  #
            return emit(object_data)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    return _object
</code>```

Python 2 compatible version

```<code># A streaming byte oriented JSON parser.  Feed it a single byte at a time and
# it will emit complete objects as it comes across them.  Whitespace within and
# between objects is ignored.  This means it can parse newline delimited JSON.
import math

def json_machine(emit, next_func=None):
    def _value(byte_data):
        if not byte_data:
            return

        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _value  # Ignore whitespace

        if byte_data == 0x22:  # "
            return string_machine(on_value)

        if byte_data == 0x2d or (0x30 <= byte_data < 0x40):  # - or 0-9
            return number_machine(byte_data, on_number)

        if byte_data == 0x7b:  #:
            return object_machine(on_value)

        if byte_data == 0x5b:  # [
            return array_machine(on_value)

        if byte_data == 0x74:  # t
            return constant_machine(TRUE, True, on_value)

        if byte_data == 0x66:  # f
            return constant_machine(FALSE, False, on_value)

        if byte_data == 0x6e:  # n
            return constant_machine(NULL, None, on_value)

        if next_func == _value:
            raise Exception("Unexpected 0x" + str(byte_data))

        return next_func(byte_data)

    def on_value(value):
        emit(value)
        return next_func

    def on_number(number, byte):
        emit(number)
        return _value(byte)

    next_func = next_func or _value
    return _value

TRUE = [0x72, 0x75, 0x65]
FALSE = [0x61, 0x6c, 0x73, 0x65]
NULL = [0x75, 0x6c, 0x6c]

def constant_machine(bytes_data, value, emit):
    local_data = {"i": 0, "length": len(bytes_data)}

    def _constant(byte_data):
        # nonlocal i, length
        if byte_data != bytes_data[local_data["i"]]:
            local_data["i"] += 1
            raise Exception("Unexpected 0x" + byte_data.toString(16))

        local_data["i"] += 1

        if local_data["i"] < local_data["length"]:
            return _constant
        return emit(value)

    return _constant

def string_machine(emit):
    local_data = {"string": ""}

    def _string(byte_data):
        # nonlocal string

        if byte_data == 0x22:  # "
            return emit(local_data["string"])

        if byte_data == 0x5c:  # \
            return _escaped_string

        if byte_data & 0x80:  # UTF-8 handling
            return utf8_machine(byte_data, on_char_code)

        if byte_data < 0x20:  # ASCII control character
            raise Exception("Unexpected control character: 0x" + byte_data.toString(16))

        local_data["string"] += chr(byte_data)
        return _string

    def _escaped_string(byte_data):
        # nonlocal string

        if byte_data == 0x22 or byte_data == 0x5c or byte_data == 0x2f:  # " \ /
            local_data["string"] += chr(byte_data)
            return _string

        if byte_data == 0x62:  # b
            local_data["string"] += "\b"
            return _string

        if byte_data == 0x66:  # f
            local_data["string"] += "\f"
            return _string

        if byte_data == 0x6e:  # n
            local_data["string"] += "\n"
            return _string

        if byte_data == 0x72:  # r
            local_data["string"] += "\r"
            return _string

        if byte_data == 0x74:  # t
            local_data["string"] += "\t"
            return _string

        if byte_data == 0x75:  # u
            return hex_machine(on_char_code)

    def on_char_code(char_code):
        # nonlocal string
        local_data["string"] += chr(char_code)
        return _string

    return _string

# Nestable state machine for UTF-8 Decoding.
def utf8_machine(byte_data, emit):
    local_data = {"left": 0, "num": 0}

    def _utf8(byte_data):
        # nonlocal num, left
        if (byte_data & 0xc0) != 0x80:
            raise Exception("Invalid byte in UTF-8 character: 0x" + byte_data.toString(16))

        local_data["left"] -= 1

        local_data["num"] |= (byte_data & 0x3f) << (local_data["left"] * 6)
        if local_data["left"]:
            return _utf8
        return emit(local_data["num"])

    if 0xc0 <= byte_data < 0xe0:  # 2-byte UTF-8 Character
        local_data["left"] = 1
        local_data["num"] = (byte_data & 0x1f) << 6
        return _utf8

    if 0xe0 <= byte_data < 0xf0:  # 3-byte UTF-8 Character
        local_data["left"] = 2
        local_data["num"] = (byte_data & 0xf) << 12
        return _utf8

    if 0xf0 <= byte_data < 0xf8:  # 4-byte UTF-8 Character
        local_data["left"] = 3
        local_data["num"] = (byte_data & 0x07) << 18
        return _utf8

    raise Exception("Invalid byte in UTF-8 string: 0x" + str(byte_data))

# Nestable state machine for hex escaped characters
def hex_machine(emit):
    local_data = {"left": 4, "num": 0}

    def _hex(byte_data):
        # nonlocal num, left
        i = 0  # Parse the hex byte
        if 0x30 <= byte_data < 0x40:
            i = byte_data - 0x30
        elif 0x61 <= byte_data <= 0x66:
            i = byte_data - 0x57
        elif 0x41 <= byte_data <= 0x46:
            i = byte_data - 0x37
        else:
            raise Exception("Expected hex char in string hex escape")

        local_data["left"] -= 1
        local_data["num"] |= i << (local_data["left"] * 4)

        if local_data["left"]:
            return _hex
        return emit(local_data["num"])

    return _hex

def number_machine(byte_data, emit):
    local_data = {"sign": 1, "number": 0, "decimal": 0, "esign": 1, "exponent": 0}

    def _mid(byte_data):
        if byte_data == 0x2e:  # .
            return _decimal

        return _later(byte_data)

    def _number(byte_data):
        # nonlocal number
        if 0x30 <= byte_data < 0x40:
            local_data["number"] = local_data["number"] * 10 + (byte_data - 0x30)
            return _number

        return _mid(byte_data)

    def _start(byte_data):
        if byte_data == 0x30:
            return _mid

        if 0x30 < byte_data < 0x40:
            return _number(byte_data)

        raise Exception("Invalid number: 0x" + byte_data.toString(16))

    if byte_data == 0x2d:  # -
        local_data["sign"] = -1
        return _start

    def _decimal(byte_data):
        # nonlocal decimal
        if 0x30 <= byte_data < 0x40:
            local_data["decimal"] = (local_data["decimal"] + byte_data - 0x30) / 10
            return _decimal

        return _later(byte_data)

    def _later(byte_data):
        if byte_data == 0x45 or byte_data == 0x65:  # E e
            return _esign

        return _done(byte_data)

    def _esign(byte_data):
        # nonlocal esign
        if byte_data == 0x2b:  # +
            return _exponent

        if byte_data == 0x2d:  # -
            local_data["esign"] = -1
            return _exponent

        return _exponent(byte_data)

    def _exponent(byte_data):
        # nonlocal exponent
        if 0x30 <= byte_data < 0x40:
            local_data["exponent"] = local_data["exponent"] * 10 + (byte_data - 0x30)
            return _exponent

        return _done(byte_data)

    def _done(byte_data):
        value = local_data["sign"] * (local_data["number"] + local_data["decimal"])
        if local_data["exponent"]:
            value *= math.pow(10, local_data["esign"] * local_data["exponent"])

        return emit(value, byte_data)

    return _start(byte_data)

def array_machine(emit):
    local_data = {"array_data": []}

    def _array(byte_data):
        if byte_data == 0x5d:  # ]
            return emit(local_data["array_data"])

        return json_machine(on_value, _comma)(byte_data)

    def on_value(value):
        # nonlocal array_data
        local_data["array_data"].append(value)

    def _comma(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return json_machine(on_value, _comma)

        if byte_data == 0x5d:  # ]
            return emit(local_data["array_data"])

        raise Exception("Unexpected byte: 0x" + str(byte_data) + " in array body")

    return _array

def object_machine(emit):
    local_data = {"object_data": {}, "key": ""}

    def _object(byte_data):
        # nonlocal object_data, key
        if byte_data == 0x7d:  #
            return emit(local_data["object_data"])

        return _key(byte_data)

    def _key(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _object  # Ignore whitespace

        if byte_data == 0x22:
            return string_machine(on_key)

        raise Exception("Unexpected byte: 0x" + byte_data.toString(16))

    def on_key(result):
        # nonlocal object_data, key
        local_data["key"] = result
        return _colon

    def _colon(byte_data):
        # nonlocal object_data, key
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _colon  # Ignore whitespace

        if byte_data == 0x3a:  # :
            return json_machine(on_value, _comma)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    def on_value(value):
        # nonlocal object_data, key
        local_data["object_data"][local_data["key"]] = value

    def _comma(byte_data):
        # nonlocal object_data
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return _key

        if byte_data == 0x7d:  #
            return emit(local_data["object_data"])

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    return _object
</code>```

Testing it

```<code>if __name__ == "__main__":
    test_json = """[1,2,"3"] {"name":
    "tarun"} 1 2
    3 [{"name":"a",
    "data": [1,
    null,2]}]
"""
    def found_json(data):
        print(data)

    state = json_machine(found_json)

    for char in test_json:
        state = state(ord(char))
</code>```

The output of the same is

```<code>[1, 2, '3']
{'name': 'tarun'}
1
2
3
[{'name': 'a', 'data': [1, None, 2]}]
</code>```

Body:
I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately json.load() just .read()s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.

Is there any way to do this? Using the standard library would be ideal, but if there's a third-party library I'd use that instead.

At the moment I'm putting each object on a separate line and using json.loads(f.readline()), but I would really prefer not to need to do this.

Example Use

example.py

import my_json as json
import sys

for o in json.iterload(sys.stdin):
    print("Working on a", type(o))

in.txt

{"foo": ["bar", "baz"]} 1 2 [] 4 5 6

example session

$ python3.2 example.py < in.txt
Working on a dict
Working on a int
Working on a int
Working on a list
Working on a int
Working on a int
Working on a int

Body:
I believe a better way of doing it would be to use a state machine. Below is a sample code that I worked out by converting a NodeJS code on below link to Python <s>3 (used nonlocal keyword only available in Python 3, code won't work on Python 2)</s>

Edit-1: Updated and made code compatible with Python 2

Edit-2: Updated and added a Python3 only version as well

https://gist.github.com/creationix/5992451

Python 3 only version

# A streaming byte oriented JSON parser.  Feed it a single byte at a time and
# it will emit complete objects as it comes across them.  Whitespace within and
# between objects is ignored.  This means it can parse newline delimited JSON.
import math

def json_machine(emit, next_func=None):
    def _value(byte_data):
        if not byte_data:
            return

        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _value  # Ignore whitespace

        if byte_data == 0x22:  # "
            return string_machine(on_value)

        if byte_data == 0x2d or (0x30 <= byte_data < 0x40):  # - or 0-9
            return number_machine(byte_data, on_number)

        if byte_data == 0x7b:  #:
            return object_machine(on_value)

        if byte_data == 0x5b:  # [
            return array_machine(on_value)

        if byte_data == 0x74:  # t
            return constant_machine(TRUE, True, on_value)

        if byte_data == 0x66:  # f
            return constant_machine(FALSE, False, on_value)

        if byte_data == 0x6e:  # n
            return constant_machine(NULL, None, on_value)

        if next_func == _value:
            raise Exception("Unexpected 0x" + str(byte_data))

        return next_func(byte_data)

    def on_value(value):
        emit(value)
        return next_func

    def on_number(number, byte):
        emit(number)
        return _value(byte)

    next_func = next_func or _value
    return _value

TRUE = [0x72, 0x75, 0x65]
FALSE = [0x61, 0x6c, 0x73, 0x65]
NULL = [0x75, 0x6c, 0x6c]

def constant_machine(bytes_data, value, emit):
    i = 0
    length = len(bytes_data)

    def _constant(byte_data):
        nonlocal i
        if byte_data != bytes_data[i]:
            i += 1
            raise Exception("Unexpected 0x" + str(byte_data))

        i += 1
        if i < length:
            return _constant
        return emit(value)

    return _constant

def string_machine(emit):
    string = ""

    def _string(byte_data):
        nonlocal string

        if byte_data == 0x22:  # "
            return emit(string)

        if byte_data == 0x5c:  # \
            return _escaped_string

        if byte_data & 0x80:  # UTF-8 handling
            return utf8_machine(byte_data, on_char_code)

        if byte_data < 0x20:  # ASCII control character
            raise Exception("Unexpected control character: 0x" + str(byte_data))

        string += chr(byte_data)
        return _string

    def _escaped_string(byte_data):
        nonlocal string

        if byte_data == 0x22 or byte_data == 0x5c or byte_data == 0x2f:  # " \ /
            string += chr(byte_data)
            return _string

        if byte_data == 0x62:  # b
            string += "\b"
            return _string

        if byte_data == 0x66:  # f
            string += "\f"
            return _string

        if byte_data == 0x6e:  # n
            string += "\n"
            return _string

        if byte_data == 0x72:  # r
            string += "\r"
            return _string

        if byte_data == 0x74:  # t
            string += "\t"
            return _string

        if byte_data == 0x75:  # u
            return hex_machine(on_char_code)

    def on_char_code(char_code):
        nonlocal string
        string += chr(char_code)
        return _string

    return _string

# Nestable state machine for UTF-8 Decoding.
def utf8_machine(byte_data, emit):
    left = 0
    num = 0

    def _utf8(byte_data):
        nonlocal num, left
        if (byte_data & 0xc0) != 0x80:
            raise Exception("Invalid byte in UTF-8 character: 0x" + byte_data.toString(16))

        left = left - 1

        num |= (byte_data & 0x3f) << (left * 6)
        if left:
            return _utf8
        return emit(num)

    if 0xc0 <= byte_data < 0xe0:  # 2-byte UTF-8 Character
        left = 1
        num = (byte_data & 0x1f) << 6
        return _utf8

    if 0xe0 <= byte_data < 0xf0:  # 3-byte UTF-8 Character
        left = 2
        num = (byte_data & 0xf) << 12
        return _utf8

    if 0xf0 <= byte_data < 0xf8:  # 4-byte UTF-8 Character
        left = 3
        num = (byte_data & 0x07) << 18
        return _utf8

    raise Exception("Invalid byte in UTF-8 string: 0x" + str(byte_data))

# Nestable state machine for hex escaped characters
def hex_machine(emit):
    left = 4
    num = 0

    def _hex(byte_data):
        nonlocal num, left

        if 0x30 <= byte_data < 0x40:
            i = byte_data - 0x30
        elif 0x61 <= byte_data <= 0x66:
            i = byte_data - 0x57
        elif 0x41 <= byte_data <= 0x46:
            i = byte_data - 0x37
        else:
            raise Exception("Expected hex char in string hex escape")

        left -= 1
        num |= i << (left * 4)

        if left:
            return _hex
        return emit(num)

    return _hex

def number_machine(byte_data, emit):
    sign = 1
    number = 0
    decimal = 0
    esign = 1
    exponent = 0

    def _mid(byte_data):
        if byte_data == 0x2e:  # .
            return _decimal

        return _later(byte_data)

    def _number(byte_data):
        nonlocal number
        if 0x30 <= byte_data < 0x40:
            number = number * 10 + (byte_data - 0x30)
            return _number

        return _mid(byte_data)

    def _start(byte_data):
        if byte_data == 0x30:
            return _mid

        if 0x30 < byte_data < 0x40:
            return _number(byte_data)

        raise Exception("Invalid number: 0x" + str(byte_data))

    if byte_data == 0x2d:  # -
        sign = -1
        return _start

    def _decimal(byte_data):
        nonlocal decimal
        if 0x30 <= byte_data < 0x40:
            decimal = (decimal + byte_data - 0x30) / 10
            return _decimal

        return _later(byte_data)

    def _later(byte_data):
        if byte_data == 0x45 or byte_data == 0x65:  # E e
            return _esign

        return _done(byte_data)

    def _esign(byte_data):
        nonlocal esign
        if byte_data == 0x2b:  # +
            return _exponent

        if byte_data == 0x2d:  # -
            esign = -1
            return _exponent

        return _exponent(byte_data)

    def _exponent(byte_data):
        nonlocal exponent
        if 0x30 <= byte_data < 0x40:
            exponent = exponent * 10 + (byte_data - 0x30)
            return _exponent

        return _done(byte_data)

    def _done(byte_data):
        value = sign * (number + decimal)
        if exponent:
            value *= math.pow(10, esign * exponent)

        return emit(value, byte_data)

    return _start(byte_data)

def array_machine(emit):
    array_data = []

    def _array(byte_data):
        if byte_data == 0x5d:  # ]
            return emit(array_data)

        return json_machine(on_value, _comma)(byte_data)

    def on_value(value):
        array_data.append(value)

    def _comma(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return json_machine(on_value, _comma)

        if byte_data == 0x5d:  # ]
            return emit(array_data)

        raise Exception("Unexpected byte: 0x" + str(byte_data) + " in array body")

    return _array

def object_machine(emit):
    object_data = {}
    key = None

    def _object(byte_data):
        if byte_data == 0x7d:  #
            return emit(object_data)

        return _key(byte_data)

    def _key(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _object  # Ignore whitespace

        if byte_data == 0x22:
            return string_machine(on_key)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    def on_key(result):
        nonlocal key
        key = result
        return _colon

    def _colon(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _colon  # Ignore whitespace

        if byte_data == 0x3a:  # :
            return json_machine(on_value, _comma)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    def on_value(value):
        object_data[key] = value

    def _comma(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return _key

        if byte_data == 0x7d:  #
            return emit(object_data)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    return _object

Python 2 compatible version

# A streaming byte oriented JSON parser.  Feed it a single byte at a time and
# it will emit complete objects as it comes across them.  Whitespace within and
# between objects is ignored.  This means it can parse newline delimited JSON.
import math

def json_machine(emit, next_func=None):
    def _value(byte_data):
        if not byte_data:
            return

        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _value  # Ignore whitespace

        if byte_data == 0x22:  # "
            return string_machine(on_value)

        if byte_data == 0x2d or (0x30 <= byte_data < 0x40):  # - or 0-9
            return number_machine(byte_data, on_number)

        if byte_data == 0x7b:  #:
            return object_machine(on_value)

        if byte_data == 0x5b:  # [
            return array_machine(on_value)

        if byte_data == 0x74:  # t
            return constant_machine(TRUE, True, on_value)

        if byte_data == 0x66:  # f
            return constant_machine(FALSE, False, on_value)

        if byte_data == 0x6e:  # n
            return constant_machine(NULL, None, on_value)

        if next_func == _value:
            raise Exception("Unexpected 0x" + str(byte_data))

        return next_func(byte_data)

    def on_value(value):
        emit(value)
        return next_func

    def on_number(number, byte):
        emit(number)
        return _value(byte)

    next_func = next_func or _value
    return _value

TRUE = [0x72, 0x75, 0x65]
FALSE = [0x61, 0x6c, 0x73, 0x65]
NULL = [0x75, 0x6c, 0x6c]

def constant_machine(bytes_data, value, emit):
    local_data = {"i": 0, "length": len(bytes_data)}

    def _constant(byte_data):
        # nonlocal i, length
        if byte_data != bytes_data[local_data["i"]]:
            local_data["i"] += 1
            raise Exception("Unexpected 0x" + byte_data.toString(16))

        local_data["i"] += 1

        if local_data["i"] < local_data["length"]:
            return _constant
        return emit(value)

    return _constant

def string_machine(emit):
    local_data = {"string": ""}

    def _string(byte_data):
        # nonlocal string

        if byte_data == 0x22:  # "
            return emit(local_data["string"])

        if byte_data == 0x5c:  # \
            return _escaped_string

        if byte_data & 0x80:  # UTF-8 handling
            return utf8_machine(byte_data, on_char_code)

        if byte_data < 0x20:  # ASCII control character
            raise Exception("Unexpected control character: 0x" + byte_data.toString(16))

        local_data["string"] += chr(byte_data)
        return _string

    def _escaped_string(byte_data):
        # nonlocal string

        if byte_data == 0x22 or byte_data == 0x5c or byte_data == 0x2f:  # " \ /
            local_data["string"] += chr(byte_data)
            return _string

        if byte_data == 0x62:  # b
            local_data["string"] += "\b"
            return _string

        if byte_data == 0x66:  # f
            local_data["string"] += "\f"
            return _string

        if byte_data == 0x6e:  # n
            local_data["string"] += "\n"
            return _string

        if byte_data == 0x72:  # r
            local_data["string"] += "\r"
            return _string

        if byte_data == 0x74:  # t
            local_data["string"] += "\t"
            return _string

        if byte_data == 0x75:  # u
            return hex_machine(on_char_code)

    def on_char_code(char_code):
        # nonlocal string
        local_data["string"] += chr(char_code)
        return _string

    return _string

# Nestable state machine for UTF-8 Decoding.
def utf8_machine(byte_data, emit):
    local_data = {"left": 0, "num": 0}

    def _utf8(byte_data):
        # nonlocal num, left
        if (byte_data & 0xc0) != 0x80:
            raise Exception("Invalid byte in UTF-8 character: 0x" + byte_data.toString(16))

        local_data["left"] -= 1

        local_data["num"] |= (byte_data & 0x3f) << (local_data["left"] * 6)
        if local_data["left"]:
            return _utf8
        return emit(local_data["num"])

    if 0xc0 <= byte_data < 0xe0:  # 2-byte UTF-8 Character
        local_data["left"] = 1
        local_data["num"] = (byte_data & 0x1f) << 6
        return _utf8

    if 0xe0 <= byte_data < 0xf0:  # 3-byte UTF-8 Character
        local_data["left"] = 2
        local_data["num"] = (byte_data & 0xf) << 12
        return _utf8

    if 0xf0 <= byte_data < 0xf8:  # 4-byte UTF-8 Character
        local_data["left"] = 3
        local_data["num"] = (byte_data & 0x07) << 18
        return _utf8

    raise Exception("Invalid byte in UTF-8 string: 0x" + str(byte_data))

# Nestable state machine for hex escaped characters
def hex_machine(emit):
    local_data = {"left": 4, "num": 0}

    def _hex(byte_data):
        # nonlocal num, left
        i = 0  # Parse the hex byte
        if 0x30 <= byte_data < 0x40:
            i = byte_data - 0x30
        elif 0x61 <= byte_data <= 0x66:
            i = byte_data - 0x57
        elif 0x41 <= byte_data <= 0x46:
            i = byte_data - 0x37
        else:
            raise Exception("Expected hex char in string hex escape")

        local_data["left"] -= 1
        local_data["num"] |= i << (local_data["left"] * 4)

        if local_data["left"]:
            return _hex
        return emit(local_data["num"])

    return _hex

def number_machine(byte_data, emit):
    local_data = {"sign": 1, "number": 0, "decimal": 0, "esign": 1, "exponent": 0}

    def _mid(byte_data):
        if byte_data == 0x2e:  # .
            return _decimal

        return _later(byte_data)

    def _number(byte_data):
        # nonlocal number
        if 0x30 <= byte_data < 0x40:
            local_data["number"] = local_data["number"] * 10 + (byte_data - 0x30)
            return _number

        return _mid(byte_data)

    def _start(byte_data):
        if byte_data == 0x30:
            return _mid

        if 0x30 < byte_data < 0x40:
            return _number(byte_data)

        raise Exception("Invalid number: 0x" + byte_data.toString(16))

    if byte_data == 0x2d:  # -
        local_data["sign"] = -1
        return _start

    def _decimal(byte_data):
        # nonlocal decimal
        if 0x30 <= byte_data < 0x40:
            local_data["decimal"] = (local_data["decimal"] + byte_data - 0x30) / 10
            return _decimal

        return _later(byte_data)

    def _later(byte_data):
        if byte_data == 0x45 or byte_data == 0x65:  # E e
            return _esign

        return _done(byte_data)

    def _esign(byte_data):
        # nonlocal esign
        if byte_data == 0x2b:  # +
            return _exponent

        if byte_data == 0x2d:  # -
            local_data["esign"] = -1
            return _exponent

        return _exponent(byte_data)

    def _exponent(byte_data):
        # nonlocal exponent
        if 0x30 <= byte_data < 0x40:
            local_data["exponent"] = local_data["exponent"] * 10 + (byte_data - 0x30)
            return _exponent

        return _done(byte_data)

    def _done(byte_data):
        value = local_data["sign"] * (local_data["number"] + local_data["decimal"])
        if local_data["exponent"]:
            value *= math.pow(10, local_data["esign"] * local_data["exponent"])

        return emit(value, byte_data)

    return _start(byte_data)

def array_machine(emit):
    local_data = {"array_data": []}

    def _array(byte_data):
        if byte_data == 0x5d:  # ]
            return emit(local_data["array_data"])

        return json_machine(on_value, _comma)(byte_data)

    def on_value(value):
        # nonlocal array_data
        local_data["array_data"].append(value)

    def _comma(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return json_machine(on_value, _comma)

        if byte_data == 0x5d:  # ]
            return emit(local_data["array_data"])

        raise Exception("Unexpected byte: 0x" + str(byte_data) + " in array body")

    return _array

def object_machine(emit):
    local_data = {"object_data": {}, "key": ""}

    def _object(byte_data):
        # nonlocal object_data, key
        if byte_data == 0x7d:  #
            return emit(local_data["object_data"])

        return _key(byte_data)

    def _key(byte_data):
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _object  # Ignore whitespace

        if byte_data == 0x22:
            return string_machine(on_key)

        raise Exception("Unexpected byte: 0x" + byte_data.toString(16))

    def on_key(result):
        # nonlocal object_data, key
        local_data["key"] = result
        return _colon

    def _colon(byte_data):
        # nonlocal object_data, key
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _colon  # Ignore whitespace

        if byte_data == 0x3a:  # :
            return json_machine(on_value, _comma)

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    def on_value(value):
        # nonlocal object_data, key
        local_data["object_data"][local_data["key"]] = value

    def _comma(byte_data):
        # nonlocal object_data
        if byte_data == 0x09 or byte_data == 0x0a or byte_data == 0x0d or byte_data == 0x20:
            return _comma  # Ignore whitespace

        if byte_data == 0x2c:  # ,
            return _key

        if byte_data == 0x7d:  #
            return emit(local_data["object_data"])

        raise Exception("Unexpected byte: 0x" + str(byte_data))

    return _object

Testing it

if __name__ == "__main__":
    test_json = """[1,2,"3"] {"name":
    "tarun"} 1 2
    3 [{"name":"a",
    "data": [1,
    null,2]}]
"""
    def found_json(data):
        print(data)

    state = json_machine(found_json)

    for char in test_json:
        state = state(ord(char))

The output of the same is

[1, 2, '3']
{'name': 'tarun'}
1
2
3
[{'name': 'a', 'data': [1, None, 2]}]


问:
How to get element by name in vb.net
I am trying to get Element by name in vb.net

HTML Code:

```<code><input name="domains[]" value="gamesolutionz.com" type="text">
</code>```

VB.net:

```<code>Private Sub FlatTextBox1_TextChanged(sender As Object, e As EventArgs) Handles FlatTextBox1.TextChanged
    WebBrowser1.Document.GetElementById("domains[]").SetAttribute("value", FlatTextBox1.Text)
End Sub
</code>```

答:
```<code><input name="domains[]" value="gamesolutionz.com" type="text">
</code>```

you are trying to acess element by ID but there is no ID present on that input element that is the reason you are not able to access that element

you need to try out

```<code>Private doc As HtmlDocument = webBrowser1.Document

Private elems As HtmlElementCollection = doc.All.GetElementsByName("domains[]")

Private elem As HtmlElement = elems(0)
</code>```

Title: How to get element by name in vb.net

Body:
I am trying to get Element by name in vb.net

HTML Code:

<input name="domains[]" value="gamesolutionz.com" type="text">

VB.net:

Private Sub FlatTextBox1_TextChanged(sender As Object, e As EventArgs) Handles FlatTextBox1.TextChanged
    WebBrowser1.Document.GetElementById("domains[]").SetAttribute("value", FlatTextBox1.Text)
End Sub

Body:
<input name="domains[]" value="gamesolutionz.com" type="text">

you are trying to acess element by ID but there is no ID present on that input element that is the reason you are not able to access that element

you need to try out

Private doc As HtmlDocument = webBrowser1.Document

Private elems As HtmlElementCollection = doc.All.GetElementsByName("domains[]")

Private elem As HtmlElement = elems(0)


问:
Convert array of characters to array of ints c++?
I have an array of 10 numerical characters, and I want to convert it, index by index, to an array of ints. For instance, if array[0] = '2', I want to edit the array so that array[0] = 2.

How do I do this as part of a for loop? I was thinking something like this:

```<code>for (int i = 0; i < 10; i++){
 array[i] = array[i] - '0';
}
</code>```

Please let me know if this is right, or if I need to change something. Thank you!

答:
You cannot just change the type of an array. If the first array is a char array, you need to create a new array that would hold integers. Then index by index you need to convert the character from the first array to an integer and then store it in your new array.</p>

```<code> int intArray[10];
 char charArray[10];
 for (int i = 0; i < 10; i++){
     intArray[i] = charArray[i] - '0';
  }
</code>```

Body:
I have an array of 10 numerical characters, and I want to convert it, index by index, to an array of ints. For instance, if array[0] = '2', I want to edit the array so that array[0] = 2.

How do I do this as part of a for loop? I was thinking something like this:

for (int i = 0; i < 10; i++){
 array[i] = array[i] - '0';
}

Please let me know if this is right, or if I need to change something. Thank you!

Body:
You cannot just change the type of an array. If the first array is a char array, you need to create a new array that would hold integers. Then index by index you need to convert the character from the first array to an integer and then store it in your new array.

 int intArray[10];
 char charArray[10];
 for (int i = 0; i < 10; i++){
     intArray[i] = charArray[i] - '0';
  }