问:
How to update field value by determining each digit in field?
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

```<code>create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end
</code>```

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

答:
assuming its always a 4 digit #; you could use substring like below
-- postgres SQL example</p>

```<code>SELECT CASE
         WHEN a = 0 THEN a + 4
         ELSE a + 3
       end AS a,
       CASE
         WHEN b = 0 THEN b + 4
         ELSE b + 3
       end AS b,
       CASE
         WHEN c = 0 THEN c + 4
         ELSE c + 3
       end AS c,
       CASE
         WHEN d = 0 THEN d + 4
         ELSE c + 3
       end AS d
FROM   ( SELECT Substr( '1010', 1, 1 ) :: INT AS a,
                Substr( '1010', 2, 1 ) :: INT b,
                Substr( '1010', 3, 1 ) :: INT c,
                Substr( '1010', 4, 1 ) :: INT d )a
</code>```

<p>--- Other option may be (tried in postgreSQL :) ) to split the number using regexp_split_to_table  into rows;then add individual each digit based on the case statement and then concat the digits back into a string </p>

```<code>SELECT array_to_string ( array
       (
              select
                     case
                            WHEN val = 0 THEN val +4
                            ELSE val +3
                     END
              FROM   (
                            SELECT regexp_split_to_table ( '101010','' ) ::INT val
                     ) a
       ) ,'' )
</code>```

Body:
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

Body:
assuming its always a 4 digit #; you could use substring like below
-- postgres SQL example

SELECT CASE
         WHEN a = 0 THEN a + 4
         ELSE a + 3
       end AS a,
       CASE
         WHEN b = 0 THEN b + 4
         ELSE b + 3
       end AS b,
       CASE
         WHEN c = 0 THEN c + 4
         ELSE c + 3
       end AS c,
       CASE
         WHEN d = 0 THEN d + 4
         ELSE c + 3
       end AS d
FROM   ( SELECT Substr( '1010', 1, 1 ) :: INT AS a,
                Substr( '1010', 2, 1 ) :: INT b,
                Substr( '1010', 3, 1 ) :: INT c,
                Substr( '1010', 4, 1 ) :: INT d )a

--- Other option may be (tried in postgreSQL :) ) to split the number using regexp_split_to_table  into rows;then add individual each digit based on the case statement and then concat the digits back into a string

SELECT array_to_string ( array
       (
              select
                     case
                            WHEN val = 0 THEN val +4
                            ELSE val +3
                     END
              FROM   (
                            SELECT regexp_split_to_table ( '101010','' ) ::INT val
                     ) a
       ) ,'' )


来源: stackexchange

问:
Clean dirty data
I have three variables (ID, Name and City) and need to generate a new variable flag.

There are something wrong with the observations. I need to find the wrong observations and create the flag.  The variable flag indicates which column contains the wrong observation.

Suppose just one bad observation at most in each row.

Given dirty data!!!!!

```<code>|ID      |Name             |City
|1       |IBM              |D
|1       |IBM              |D
|2       |IBM              |D
|3       |Google           |F
|3       |Microsoft        |F
|3       |Google           |F
|8       |Microsoft        |A
|8       |Microsoft        |B
|8       |Microsoft        |A
</code>```

Result

```<code>|ID      |Name             |City |flag
|1       |IBM              |D    |0
|1       |IBM              |D    |0
|2       |IBM              |D    |1
|3       |Google           |F    |0
|3       |Microsoft        |F    |2
|3       |Google           |F    |0
|8       |Microsoft        |A    |0
|8       |Microsoft        |B    |3
|8       |Microsoft        |A    |0
</code>```

答:
This code is based on Eric's answer.</p>

```<code>clear all
input float ID str9 Name str1 City
1 "IBM"       "D"
1 "IBM"       "D"
2 "IBM"       "D"
3 "Google"    "F"
3 "Microsoft" "F"
3 "Google"    "F"
8 "Microsoft" "A"
8 "Microsoft" "B"
8 "Microsoft" "A"
end

encode Name, gen(Name_n)
encode City, gen(City_n)

// get dummy variable for
duplicates tag ID Name, gen(col_12)
duplicates tag ID City, gen(col_13)
duplicates tag Name City, gen(col_23)
duplicates tag ID Name City, gen(col_123)

// generate the flag
gen flag = 0
replace flag = 1 if col_123 == 0 & col_23 ~= 0
replace flag = 2 if col_123 == 0 & col_13 ~= 0
replace flag = 3 if col_123 == 0 & col_12 ~= 0

drop Name_n City_n col_*
</code>```

ContentLicense: CC BY-SA 3.0

Title: Clean dirty data

Body:
I have three variables (ID, Name and City) and need to generate a new variable flag.

There are something wrong with the observations. I need to find the wrong observations and create the flag.  The variable flag indicates which column contains the wrong observation.

Suppose just one bad observation at most in each row.

Given dirty data!!!!!

|ID      |Name             |City
|1       |IBM              |D
|1       |IBM              |D
|2       |IBM              |D
|3       |Google           |F
|3       |Microsoft        |F
|3       |Google           |F
|8       |Microsoft        |A
|8       |Microsoft        |B
|8       |Microsoft        |A

Result

|ID      |Name             |City |flag
|1       |IBM              |D    |0
|1       |IBM              |D    |0
|2       |IBM              |D    |1
|3       |Google           |F    |0
|3       |Microsoft        |F    |2
|3       |Google           |F    |0
|8       |Microsoft        |A    |0
|8       |Microsoft        |B    |3
|8       |Microsoft        |A    |0

Body:
This code is based on Eric's answer.

clear all
input float ID str9 Name str1 City
1 "IBM"       "D"
1 "IBM"       "D"
2 "IBM"       "D"
3 "Google"    "F"
3 "Microsoft" "F"
3 "Google"    "F"
8 "Microsoft" "A"
8 "Microsoft" "B"
8 "Microsoft" "A"
end

encode Name, gen(Name_n)
encode City, gen(City_n)

// get dummy variable for
duplicates tag ID Name, gen(col_12)
duplicates tag ID City, gen(col_13)
duplicates tag Name City, gen(col_23)
duplicates tag ID Name City, gen(col_123)

// generate the flag
gen flag = 0
replace flag = 1 if col_123 == 0 & col_23 ~= 0
replace flag = 2 if col_123 == 0 & col_13 ~= 0
replace flag = 3 if col_123 == 0 & col_12 ~= 0

drop Name_n City_n col_*


问:
What is wrong with this join of a table to itself?
I have a table called TempAllAddresses with the following columns - ID, Address, State. I want to populate a new table with Address, State, and Count. Count should represent how many records there are in the TempAllAddresses table that have an address like this address followed by a wildcard. If that made no sense, here's an example to illustrate -
Let's say I have a record like this:

```<code>ID      Address      State
12345   13 Phoenix   NY
</code>```

What I want to do is insert a new record into a new table called AddressCount that has 13 Phoenix for the Address, NY for the State, and the number of records in the table that have NY as the State and an address LIKE '13 Phoenix%' for the Count.

I want to accomplish this with an inner join of TempAllAddresses on itself. This is what I've tried, but it doesn't seem to accomplish what I'm looking for:

```<code>SELECT t1.Address, t1.State, COUNT(t2.address) As NumEntities
FROM TempAllAddresses t1
INNER JOIN TempAllAddresses t2
 ON t1.state = t2.state
 AND T2.Address LIKE t1.address + '%'
GROUP BY t1.State, t1.Address
</code>```

The Count is definitely off, though. It should be equivalent to running "SELECT COUNT(*) FROM TempAllAddresses WHERE State=thisRecordsState and Address LIKE thisRecordsAddress + '%'". How can I accomplish this? What am I doing wrong?

Edit:

The count seems to be off in the following way -
If I have a record like I mentioned above, and then I have 2 other records that also have a state of NY, and then have addresses of "13 Phoenix Road" and "13 Phoenix Rd", then I want to get in my final table a record like this:

```<code>13 Phoenix    NY    3
</code>```

Instead, I seem to be getting:

```<code>13 Phoenix    NY    9
</code>```

I'm not quite sure what's happening here... some sort of cartesian product? Permutations...? Can anyone explain this?

Edit 2:
A further edit since I seem to be misunderstood (and really need a solution :( )... Here is a query with a correlated subselect that accomplishes what I'm looking for. I'd like to do the same thing with an inner join of the table on itself rather than a subselect.

```<code>SELECT Address, State,
    (SELECT Count(*)
    FROM TempAllAddresses innerQry
    WHERE innerQry.address LIKE outerQry.address + '%'
        AND innerQry.state = outerQry.state) As NumEntities
FROM TempAllAddresses outerQry
</code>```

Basically, for each record, I want to get the number of records in the table that have the same state and an address that begins with this address (or is equal to... I do want to include this address as part of the count).

答:
Nested GroupBy:

The subquery will find the shortest address for each distinct address.

This doesn't consider case sensitivity.

Then each version of these addresses are counted.

SQL:

```<code>SELECT Address, State, count(1) As NumEntities
FROM (
    SELECT min(t1.Address) as Address, t1.State
    FROM TempAllAddresses t1
    INNER JOIN TempAllAddresses t2
     ON t1.state = t2.state
     AND T2.Address LIKE t1.address + '%'
    GROUP BY t1.State, t2.Address
) GROUP By State, Address
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a table called TempAllAddresses with the following columns - ID, Address, State. I want to populate a new table with Address, State, and Count. Count should represent how many records there are in the TempAllAddresses table that have an address like this address followed by a wildcard. If that made no sense, here's an example to illustrate -
Let's say I have a record like this:

ID      Address      State
12345   13 Phoenix   NY

What I want to do is insert a new record into a new table called AddressCount that has 13 Phoenix for the Address, NY for the State, and the number of records in the table that have NY as the State and an address LIKE '13 Phoenix%' for the Count.

I want to accomplish this with an inner join of TempAllAddresses on itself. This is what I've tried, but it doesn't seem to accomplish what I'm looking for:

SELECT t1.Address, t1.State, COUNT(t2.address) As NumEntities
FROM TempAllAddresses t1
INNER JOIN TempAllAddresses t2
 ON t1.state = t2.state
 AND T2.Address LIKE t1.address + '%'
GROUP BY t1.State, t1.Address

The Count is definitely off, though. It should be equivalent to running "SELECT COUNT(*) FROM TempAllAddresses WHERE State=thisRecordsState and Address LIKE thisRecordsAddress + '%'". How can I accomplish this? What am I doing wrong?

Edit:

The count seems to be off in the following way -
If I have a record like I mentioned above, and then I have 2 other records that also have a state of NY, and then have addresses of "13 Phoenix Road" and "13 Phoenix Rd", then I want to get in my final table a record like this:

13 Phoenix    NY    3

Instead, I seem to be getting:

13 Phoenix    NY    9

I'm not quite sure what's happening here... some sort of cartesian product? Permutations...? Can anyone explain this?

Edit 2:
A further edit since I seem to be misunderstood (and really need a solution :( )... Here is a query with a correlated subselect that accomplishes what I'm looking for. I'd like to do the same thing with an inner join of the table on itself rather than a subselect.

SELECT Address, State,
    (SELECT Count(*)
    FROM TempAllAddresses innerQry
    WHERE innerQry.address LIKE outerQry.address + '%'
        AND innerQry.state = outerQry.state) As NumEntities
FROM TempAllAddresses outerQry

Basically, for each record, I want to get the number of records in the table that have the same state and an address that begins with this address (or is equal to... I do want to include this address as part of the count).

Body:
Nested GroupBy:

The subquery will find the shortest address for each distinct address.

This doesn't consider case sensitivity.

Then each version of these addresses are counted.

SQL:

SELECT Address, State, count(1) As NumEntities
FROM (
    SELECT min(t1.Address) as Address, t1.State
    FROM TempAllAddresses t1
    INNER JOIN TempAllAddresses t2
     ON t1.state = t2.state
     AND T2.Address LIKE t1.address + '%'
    GROUP BY t1.State, t2.Address
) GROUP By State, Address


问:
How do I reference an object within an array within an object in xcode 8?
I'm looking to try and reference all "titles" within this json (link here) in xcode 8. The issue is there's an object and array that need to be referenced (i believe) before I can pull the title data, and I'm not sure how to do that.

So far this is what i've got:

```<code>func fetchFeed(){
    let urlRequest = URLRequest(url: URL(string: "http://itunes.apple.com/us/rss/topalbums/limit=10/json")!)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

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

        self.artists = [Artist]()
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {
                for feedFromJson in feedsFromJson {
                    let feed = Feed()
                    if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

                        feed.entry = entry

                        article.headline = title

                    }
                    self.articles?.append(article)
                }
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()
</code>```

And thank you for your help in advance!

答:
There is two kinds of titles.
the "feed" and the "entry".

if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

The practice of iOS is not this.

 feedFromJson["entry"] is nil ,not a string . I guess you try to get the "feed" title.

```<code>if let entry = (json["feed"] as Dictionary)?["title"]
</code>```

To get the "entry" title. Just traverse the array, and get the title.

```<code>let titleDict = feedFromJson["title"] as? Dictionary
let title = titleDict["title"] as? String
article.headline = title
</code>```

Better to know the structure of the JSON data.

It's too quick.

if let feedFromJson = json["feed"]?["entry"] as? [[String :
  AnyObject]] {

You should step by step.

```<code>if let feedFromJson = (json["feed"] as Dictionary)?["entry"] as? [[String : AnyObject]] {
</code>```

Body:
I'm looking to try and reference all "titles" within this json (link here) in xcode 8. The issue is there's an object and array that need to be referenced (i believe) before I can pull the title data, and I'm not sure how to do that.

So far this is what i've got:

func fetchFeed(){
    let urlRequest = URLRequest(url: URL(string: "http://itunes.apple.com/us/rss/topalbums/limit=10/json")!)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

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

        self.artists = [Artist]()
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {
                for feedFromJson in feedsFromJson {
                    let feed = Feed()
                    if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

                        feed.entry = entry

                        article.headline = title

                    }
                    self.articles?.append(article)
                }
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()

And thank you for your help in advance!

Body:
There is two kinds of titles.
the "feed" and the "entry".

if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

The practice of iOS is not this.

 feedFromJson["entry"] is nil ,not a string . I guess you try to get the "feed" title.

if let entry = (json["feed"] as Dictionary)?["title"]

To get the "entry" title. Just traverse the array, and get the title.

let titleDict = feedFromJson["title"] as? Dictionary
let title = titleDict["title"] as? String
article.headline = title

Better to know the structure of the JSON data.

It's too quick.

if let feedFromJson = json["feed"]?["entry"] as? [[String :
  AnyObject]] {

You should step by step.

if let feedFromJson = (json["feed"] as Dictionary)?["entry"] as? [[String : AnyObject]] {


问:
MLR and vector-valued classifiers / multi-task learning
The R package MLR supports multi-label classification that maps a feature vector into a set of discrete labels Y_1, Y_2,...,Y_k.  For example, Y_1, ..., might be categorical demographic traits such as age, income, gender, and multiple of these may apply to a given example in the training data.  This is sometimes called multi-task learning, I believe.

Some regression tasks, such as canonical correlation analysis, have a similar flavor, in which our labels are continuous and vector-valued.  What is the best way to represent such a task in MLR?  I have managed shoe-horn canonical correlation analysis into regular regression task, but I am badly abusing the predict and performance methods (I want to return a vector-valued prediction that is compared to vector-valued underlying truth).

Another approach would be to "vectorize" the training data, so that a K-valued target has each training example appearing K times.  This loses some nice structure to the problem, predictions and performance evaluation, however.

答: It sounds like this would require a special type of task and learner (or wrapped learner), just like the multilabel classification.</p>


问:
Sort table by matching record percentage
I have a table with parent_id and percentage_score which is a result of a simple deduplication. My problem now is how can I select the records and arrange them like this:

```<code>|id|lastname|firstname|number|parent_id|percentage_score|
--------------------------------------------------------
|1 |holmes  | james   |11112 |  0      |100%            |
|7 |holmes  | john    |11112 |  1      |80%             |
|8 |holmes  | james   |11113 |  1      |60%             |
|4 |sherlock| steve   |77777 |  0      |100%            |
|9 |sherlock| stove   |77777 |  4      |80%             |
|12|ketchum | ash     |00001 |  0      |100%            |
</code>```

I tried using order by parent_id, percentage_score but that's not even near to what I want.

答:
Your request is confusing because your expected result does not seem to be in a logical order. But, you can use the DESC command to change the priority in the ORDER by clause, like this:

```<code>SELECT id, lastname, firstname, number, parent_id, percentage_score
ORDER BY parent_id, percentage_score DESC
</code>```

Body:
I have a table with parent_id and percentage_score which is a result of a simple deduplication. My problem now is how can I select the records and arrange them like this:

|id|lastname|firstname|number|parent_id|percentage_score|
--------------------------------------------------------
|1 |holmes  | james   |11112 |  0      |100%            |
|7 |holmes  | john    |11112 |  1      |80%             |
|8 |holmes  | james   |11113 |  1      |60%             |
|4 |sherlock| steve   |77777 |  0      |100%            |
|9 |sherlock| stove   |77777 |  4      |80%             |
|12|ketchum | ash     |00001 |  0      |100%            |

I tried using order by parent_id, percentage_score but that's not even near to what I want.

Body:
Your request is confusing because your expected result does not seem to be in a logical order. But, you can use the DESC command to change the priority in the ORDER by clause, like this:

SELECT id, lastname, firstname, number, parent_id, percentage_score
ORDER BY parent_id, percentage_score DESC


问:
Can't use debugger for xamarin android project: System.IO.FileNotFoundException: Could not load file or assembly Mono.Posix
After upgrading my visual studio 2017 to 15.2v (26430.12)

Xamarin.Android SDK 7.3.1.2 (9dbc4c5)

Can't use the debugger anymore. The project builds successfully and deployment finishes but then this error happens:

Could not load file or assembly Mono.Posix

Full error message:

答:
This is a Known Issue. The root cause is lacking of Mono.Posix.dll file under C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Xamarin.VisualStudio\.

So, to fix the problem, you can download the dll file from attached file and copy it to the up mentioned location.


问:
Typescript is generating code for imports which isn't working client-side
I'm trying a very simple example using bower and the moment library.

In my .ts file I have

```<code>import * as moment from "./bower_components/moment/moment";
</code>```

which generates

```<code>Object.defineProperty(exports, "__esModule", { value: true });
var moment = require("./bower_components/moment/moment");
</code>```

which fails to work in the browser.

I'm working around this by using the import for debugging than changing it to

```<code>declare const moment: any;
</code>```

for deployment.

In the Index.html file I have

```<code><script src="bower_components/moment/moment.js"></script>
<script src="app.js"></script>
</code>```

I realize that there are a slew of tools to package this all together but I want to make sure I get this simple case working so I understand what is going on.

What am I doing wrong and what is the simplest "proper" way to use bower models client side.

(Later I can get into Npm vs. Bower vs. Browsify, webpack, gulp, grunt and the rest of the menagerie)

答:
but I want to make sure I get this simple case working so I understand what is going on.

import doesn't work in the browser natively right now so the  following

```<code>import * as moment from "./bower_components/moment/moment";
</code>```

is wrong unless you use a module bundler.

More

If you want to use modules use a module bundler e.g. webpack quickstart : https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html

Body:
I'm trying a very simple example using bower and the moment library.

In my .ts file I have

import * as moment from "./bower_components/moment/moment";

which generates

Object.defineProperty(exports, "__esModule", { value: true });
var moment = require("./bower_components/moment/moment");

which fails to work in the browser.

I'm working around this by using the import for debugging than changing it to

declare const moment: any;

for deployment.

In the Index.html file I have

I realize that there are a slew of tools to package this all together but I want to make sure I get this simple case working so I understand what is going on.

What am I doing wrong and what is the simplest "proper" way to use bower models client side.

(Later I can get into Npm vs. Bower vs. Browsify, webpack, gulp, grunt and the rest of the menagerie)

Body:
but I want to make sure I get this simple case working so I understand what is going on.

import doesn't work in the browser natively right now so the  following

import * as moment from "./bower_components/moment/moment";

is wrong unless you use a module bundler.

More

If you want to use modules use a module bundler e.g. webpack quickstart : https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html


问:
How to make Rx value sinks aware of outdated responses?
I have a live search with autocompletion in-place (i.e. the text box contents change).

I have a request/response mechanism: like .rx.text.flatMapLatest(requestSuggestion). But the result is merged with 2 other sources of changes, all 3 of them Drivers, though (on main thread, sharing replay, not erroring-out).

When binding the result back to the text field, there was a minimal time window where the user can type the next character but gets the suggestion for the last typing. So the response consumption lacks behind a tiny bit. I want to get rid of that race condition.

Request enumeration approach

I figured it'd be good to discard not rely on .flatMapLatest here on client side but make the component's value sink check for out-of-date-ness like you do in a server/client environment. In other words, I enumerate requests, the poor man's time stamp. Now I have a .rx.contentChange where the type has the text value + a requestNumber.

It seems to work, but I cannot come up with a useful design of the sink. Its overall setup looks clunky and the disposable in the capture group is ... not so good.

What I am aiming for is a setup similar to Observable.create where you can combine disposables, only Observers/sinks don't have this kind of stuff.

```<code>// Request and response are similar to:
struct Request  { let content: String; let requestNumber: Int }
struct Response { let content: String; let requestNumber: Int }

// Hacky sink that works, but meh:
public var enumeratedResponseSink: AnyObserver<Response> {

    // A reference to the ControlEvent that the client code is observing.
    // Using Driver here because I want to make this a UIBindingObserver later.
    let requestNumbers = self.requests.asDriver()
        .map { $0.requestNumber }
    let publish = PublishSubject<Response>()

    let disposable = publish.asDriver(onErrorDriveWith: .empty())
        .withLatestFrom(requestNumbers) { response, number in (response, number) }
        .filter { response, latestRequestNumber in response.requestNumber >= latestRequestNumber }
        .map { response, _ in response.content }
        .drive(self.content) // is a UIBindingObserver

    // Look, I put a strong reference to the disposable inside so it
    // doesn't go away, but man that doesn't feel right:
    return AnyObserver { [disposable] event in

        guard case .next(let response) = event else { return }

        publish.onNext(response)
    }
}
</code>```

So this is my attempt at letting the component know from inside the Observer declaration what it itself expects the next response number to be.

How I can make this freshness check work better?

Is this a proper approach at all, or do you have a better idea to solve the original problem?

答:
I'm thinking that, instead of using a "request number", you should include the text that was used to generate the response. When the text box receives an auto-fill response, it can compare what is currently in it with the response that was received and only use the response if the response extends it's current user input...

You might have to make a custom text box for this that can distinguish between user input and input that comes from a request response. I expect you have already done that in order to show the text in different fonts/colors for user consumption.

Or have I completely misunderstood what you are trying to do?

Body:
I have a live search with autocompletion in-place (i.e. the text box contents change).

I have a request/response mechanism: like .rx.text.flatMapLatest(requestSuggestion). But the result is merged with 2 other sources of changes, all 3 of them Drivers, though (on main thread, sharing replay, not erroring-out).

When binding the result back to the text field, there was a minimal time window where the user can type the next character but gets the suggestion for the last typing. So the response consumption lacks behind a tiny bit. I want to get rid of that race condition.

Request enumeration approach

I figured it'd be good to discard not rely on .flatMapLatest here on client side but make the component's value sink check for out-of-date-ness like you do in a server/client environment. In other words, I enumerate requests, the poor man's time stamp. Now I have a .rx.contentChange where the type has the text value + a requestNumber.

It seems to work, but I cannot come up with a useful design of the sink. Its overall setup looks clunky and the disposable in the capture group is ... not so good.

What I am aiming for is a setup similar to Observable.create where you can combine disposables, only Observers/sinks don't have this kind of stuff.

// Request and response are similar to:
struct Request  { let content: String; let requestNumber: Int }
struct Response { let content: String; let requestNumber: Int }

// Hacky sink that works, but meh:
public var enumeratedResponseSink: AnyObserver<Response> {

    // A reference to the ControlEvent that the client code is observing.
    // Using Driver here because I want to make this a UIBindingObserver later.
    let requestNumbers = self.requests.asDriver()
        .map { $0.requestNumber }
    let publish = PublishSubject<Response>()

    let disposable = publish.asDriver(onErrorDriveWith: .empty())
        .withLatestFrom(requestNumbers) { response, number in (response, number) }
        .filter { response, latestRequestNumber in response.requestNumber >= latestRequestNumber }
        .map { response, _ in response.content }
        .drive(self.content) // is a UIBindingObserver

    // Look, I put a strong reference to the disposable inside so it
    // doesn't go away, but man that doesn't feel right:
    return AnyObserver { [disposable] event in

        guard case .next(let response) = event else { return }

        publish.onNext(response)
    }
}

So this is my attempt at letting the component know from inside the Observer declaration what it itself expects the next response number to be.

How I can make this freshness check work better?

Is this a proper approach at all, or do you have a better idea to solve the original problem?


问:
Communication between multiple components with a service by using Observable and Subject in Angular 2
I am new to rxjs, so I would like to ask a question regarding Angular 2, Observables and BehaviorSubject/Subject.

So, what I want to achieve is : onclick of a button inside a ComponentA to notify other components for example ComponentB, ComponentC.

What I did so far is to create a service:

```<code>private isMenuOpenBS = new BehaviorSubject(false);

  toggleMenu(): void {
    this.isMenuOpenBS.next(!this.isMenuOpenBS.getValue());
  }

  getMenuState(): Observable<boolean> {
    return this.isMenuOpenBS.asObservable();
  }
</code>```

Then having one component with provide menuService is calling the this.menuService.toggleMenu() which changes the value of the BehaviorSubject. Code :

```<code>toggleMenu(): void {
    this.menuService.toggleMenu();
    this.menuService.isMenuOpenBS.subscribe(
      (data) => {
        console.log(data)
      },
      (e) => {console.log(e)},
      () => {console.log('completed')}
    )
  }
</code>```

And another component that OnInit() subscribes to the getMenuState() which is an Observable, but it get's values only on OnInit(). Code:

```<code>ngOnInit(): void {
    this.menuService.getMenuState().subscribe(
      (data)=>{
        this.messages = data;
        console.log('nav component');
      },
      (e) => {console.log(e)},
      () => {console.log('completed')}
    )
  }
</code>```

The complete function is never called.

Any ideas what am I doing wrong or if i am missing something in the logic ?

--

Edit : So, to explain a bit more the problem was that I could see the first value that the observable had oninit but nothing else. No error no complete after that or no "next" value which was wrong since I was sending new values from the subject. In the end the problem was with the provider list of the components and not a problem of observables or subjects, but before solving the problem it wasn't easy to see that the problem was there.

答:
A few things...

You don't need to return your BehaviorSubject as an observable, you should be able to subscribe to observables no issue.

You shouldn't keep on subscribing to the service every time the toggle function gets called. You're creating a lot of subscriptions by doing so. If you took my advice from above you can just log the return of the getValue() function.

Glad you resolved it though!

Body:
I am new to rxjs, so I would like to ask a question regarding Angular 2, Observables and BehaviorSubject/Subject.

So, what I want to achieve is : onclick of a button inside a ComponentA to notify other components for example ComponentB, ComponentC.

What I did so far is to create a service:

private isMenuOpenBS = new BehaviorSubject(false);

  toggleMenu(): void {
    this.isMenuOpenBS.next(!this.isMenuOpenBS.getValue());
  }

  getMenuState(): Observable<boolean> {
    return this.isMenuOpenBS.asObservable();
  }

Then having one component with provide menuService is calling the this.menuService.toggleMenu() which changes the value of the BehaviorSubject. Code :

toggleMenu(): void {
    this.menuService.toggleMenu();
    this.menuService.isMenuOpenBS.subscribe(
      (data) => {
        console.log(data)
      },
      (e) => {console.log(e)},
      () => {console.log('completed')}
    )
  }

And another component that OnInit() subscribes to the getMenuState() which is an Observable, but it get's values only on OnInit(). Code:

ngOnInit(): void {
    this.menuService.getMenuState().subscribe(
      (data)=>{
        this.messages = data;
        console.log('nav component');
      },
      (e) => {console.log(e)},
      () => {console.log('completed')}
    )
  }

The complete function is never called.

Any ideas what am I doing wrong or if i am missing something in the logic ?

--

Edit : So, to explain a bit more the problem was that I could see the first value that the observable had oninit but nothing else. No error no complete after that or no "next" value which was wrong since I was sending new values from the subject. In the end the problem was with the provider list of the components and not a problem of observables or subjects, but before solving the problem it wasn't easy to see that the problem was there.


问:
svg background IE and positioning issue
Hi I have two svg's that I use to create a banner like image in my header. One sits to the left, the other the right. In IE, they just sit in the middle, how do I fix this?

```<code>#header-left {
    background-position: 10% -7%;
    min-height: 250px;
    background-size: inherit;
    background-repeat: no-repeat;
    background-image: url(/wp-content/uploads/2017/05/banner-left-side-02-02.svg);
    max-height: 250px;
}

#header-right {
    background-color: rgba(169, 48, 37, 0);
    background-image: url(/wp-content/uploads/2017/05/banner-right-side-01.svg);
    background-position: 100% 100%;
    background-repeat: no-repeat;
    min-height: 250px;
}
</code>```

If you would like to see the problem..., http://dronework.com.au/

答:
Is this close to what you are looking for?

#header-left {
    background-image: url(http://dronework.com.au/wp-content/uploads/2017/05/banner-left-side-02-02.svg);
    background-repeat: no-repeat;
    background-color: silver;
    width: 50%;
    height: 100px;
    float: left;
}

#header-right {
    background-image: url(http://dronework.com.au/wp-content/uploads/2017/05/banner-right-side-01.svg);
    background-repeat: no-repeat;
    background-color: lightgray;
    width: 50%;
    height: 100px;
    float: right;
    background-position: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header-left"></div>
<div id="header-right"></div></code>```

Title: svg background IE and positioning issue

Body:
Hi I have two svg's that I use to create a banner like image in my header. One sits to the left, the other the right. In IE, they just sit in the middle, how do I fix this?

#header-left {
    background-position: 10% -7%;
    min-height: 250px;
    background-size: inherit;
    background-repeat: no-repeat;
    background-image: url(/wp-content/uploads/2017/05/banner-left-side-02-02.svg);
    max-height: 250px;
}

#header-right {
    background-color: rgba(169, 48, 37, 0);
    background-image: url(/wp-content/uploads/2017/05/banner-right-side-01.svg);
    background-position: 100% 100%;
    background-repeat: no-repeat;
    min-height: 250px;
}

If you would like to see the problem..., http://dronework.com.au/

Body:
Is this close to what you are looking for?

#header-left {
    background-image: url(http://dronework.com.au/wp-content/uploads/2017/05/banner-left-side-02-02.svg);
    background-repeat: no-repeat;
    background-color: silver;
    width: 50%;
    height: 100px;
    float: left;
}

#header-right {
    background-image: url(http://dronework.com.au/wp-content/uploads/2017/05/banner-right-side-01.svg);
    background-repeat: no-repeat;
    background-color: lightgray;
    width: 50%;
    height: 100px;
    float: right;
    background-position: right;
}

<div id="header-left"></div>
<div id="header-right"></div>


问:
Are nib/xib files meant to be used in diffrent view controllers ?
I watched multiple videos on youtube and bought two books with explanations (O'Reilly).

It seems like a nib file is always used in one view controller.
The file-owner is usually the view controller which will implement that nib.

I couldn't find an example in which a nib file is used in multiple view controllers.

I did come across a couple of posts that found ways around this but the posts are old and many people leave warnings.

My initial urge to use a nib file was because I had a table view cell that was used in multiple tableViewControllers. The tableViewCell was prototyped in one of the TableViewControllers in storyboard.

I thought that creating a nib would decouple that cell from one specific TableViewController.

I can't say that I really understand the purpose of a nib file.
It seems like it's very similar to storyboard.

I ended up creating the tableViewCell in code and reusing it throughout my project.

So my question is what are nib files used for ?

Are they used to decouple a view from a specific view controller ?

Are they used to avoid duplication within one ViewController ?

Any insight would be helpful.

答:
Yes, you can reuse xibs in many places within your app.

Xibs predate storyboards and act as factories for creating instances of UIView classes configured in Interface Builder. Using them to define the layout and attributes of a UIViewController's view and its subviews is one common use case but certainly not the only one.

A common place where a xib might be reused is when it contains a table or collection view cell. You could then register that xib with multiple table or collection views using register(_ nib: UINib?,
forCellWithReuseIdentifier identifier: String) to load instances of the cell when needed.


问:
TypeScript compile import's into a single file
Inside my TypeScript application I use different import's for my own modules and node modules.

Every time i use "import" i want it to really import the module and compile it into a single js-file. Currently it looks like this:

main.ts:

```<code>import * as $ from "jquery";
$('body').css({'color': 'red'});
</code>```

main.js (output)

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var $ = require("jquery");
$('body').css({ 'color': 'red' });
</code>```

But what i want is that instead of var $ = require("jquery"); it really imports jQuery into this file (but only if it wasn't imported earlier).

答:
TypeScript compile import's into a single file

You need a module bundler. e.g. Webpack or browserify.

More

Browser quickstart : https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html

Body:
Inside my TypeScript application I use different import's for my own modules and node modules.

Every time i use "import" i want it to really import the module and compile it into a single js-file. Currently it looks like this:

main.ts:

import * as $ from "jquery";
$('body').css({'color': 'red'});

main.js (output)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var $ = require("jquery");
$('body').css({ 'color': 'red' });

But what i want is that instead of var $ = require("jquery"); it really imports jQuery into this file (but only if it wasn't imported earlier).


问:
QSerialPort with thread
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

```<code>SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();
</code>```

The Serial Port read thread:

```<code>void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}
</code>```

The SerialPort Constructor:

```<code>serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();
</code>```

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

答:
While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data

I compiled the code you provided to a bug tracker, started it with a pair of virtual serial ports created with socat:

```<code> socat -d -d pty,raw,echo=0 pty,raw,echo=0
</code>```

and emulated sending data chunks, increasing their size by 1 byte each second:

```<code>#!/bin/bash
for i in {1..1000}
do
    dd if=/dev/urandom of=/dev/pts/25 bs=1 count=$i
    sleep 1
done
</code>```

Your application's log looked like:

```<code>"bytearray length:1"
"bytearray length:2"
"bytearray length:3"
"bytearray length:4"
"bytearray length:5"
"bytearray length:6"
"bytearray length:7"
...
</code>```

Then I tried to resize application window, move it, maximize/minimize, press buttons and so on. It has no effect: actually, no data has been lost at all (Ubuntu 16.04 x64) during a reasonably long test session. So if you still loose data, it's likely that the problem is in your virtual COM port with the description of "STMicroelectronics Virtual COM Port".

Title: QSerialPort with thread

Body:
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();

The Serial Port read thread:

void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}

The SerialPort Constructor:

serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

Body:
While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data

I compiled the code you provided to a bug tracker, started it with a pair of virtual serial ports created with socat:

 socat -d -d pty,raw,echo=0 pty,raw,echo=0

and emulated sending data chunks, increasing their size by 1 byte each second:

#!/bin/bash
for i in {1..1000}
do
    dd if=/dev/urandom of=/dev/pts/25 bs=1 count=$i
    sleep 1
done

Your application's log looked like:

"bytearray length:1"
"bytearray length:2"
"bytearray length:3"
"bytearray length:4"
"bytearray length:5"
"bytearray length:6"
"bytearray length:7"
...

Then I tried to resize application window, move it, maximize/minimize, press buttons and so on. It has no effect: actually, no data has been lost at all (Ubuntu 16.04 x64) during a reasonably long test session. So if you still loose data, it's likely that the problem is in your virtual COM port with the description of "STMicroelectronics Virtual COM Port".

ContentLicense: CC BY-SA 4.0


问:
Kurento screen sharing in room
I am currently facing some issues sharing my screen with any Kurento room that I join. For now I am using the repo (https://github.com/TribeMedia/kurento-group-call-1) and making modifications on the code to help attach a screen sharing conept to the application.

Currently, I am able to do the following:

Add a share screen button on the page (super simple)

Get the screen/window popup that comes when clicking the share screen button (using the getScreenId.js by muaz khan (https://github.com/muaz-khan/getScreenId))

After selecting required application/window, display it as local stream for user (to actually see what is being shared) and then remake the rtc connections.

The problem that I am facing is, when another peer joins the room, I get the webcam stream of the initial participants in the room and not the screenshare. Is there something that I am missing in the implementation? Would we really helpful if anybody can help me out!

Following are snippets of the code that I have implemented:

In index.html:

<button id="sharescreen" disabled="disabled" onClick="shareScreen()">Share Screen</button>

In the client side js code:
```</p>

```function shareScreen(){
    var audioConstraints = {
        audio: false,
        video: true,
    };
    navigator.getUserMedia(audioConstraints, function(stream) {
        initiateScreenSharing(stream);
    }, function(error) {
        console.error("Could not get audio stream! " + error);
    });
}

function initiateScreenSharing(audioStream){
    getScreenId(function (error, sourceId, screen_constraints) {
        console.log("screen_constraints");
        console.log(screen_constraints);
        navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
        navigator.getUserMedia(screen_constraints, function (stream) {
            console.log(stream);

            var constraints = {
                audio: true,
                video: {
                    frameRate: {
                        min: 1, ideal: 15, max: 30
                    },
                    width: {
                        min: 32, ideal: 50, max: 320
                    },
                    height: {
                        min: 32, ideal: 50, max: 320
                    }
                }
            };

            var localParticipant = new Participant(sessionId);
            participants[sessionId] = localParticipant;
            localVideo = document.getElementById("local_video");
            var video = localVideo;

            var options = {
                localVideo: video,
                videoStream: stream,
                mediaConstraints: constraints,
                onicecandidate: localParticipant.onIceCandidate.bind(localParticipant),
                sendSource: 'desktop'
            };

            localParticipant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function (error) {
                if (error) {
                    return console.error(error);
                }

                // Set localVideo to new object if on IE/Safari
                localVideo = document.getElementById("local_video");

                // initial main video to local first
                localVideoCurrentId = sessionId;
                //localVideo.src = localParticipant.rtcPeer.localVideo.src;
                localVideo.muted = true;

                console.log("local participant id : " + sessionId);
                this.generateOffer(localParticipant.offerToReceiveVideo.bind(localParticipant));
            });

        }, function (error) {
            console.error(error);
        });
    });
}
```

<p>```

For example:

If PeerA joins the room 1st and shares the desktop, and PeerB joins the same room, then PeerB will see PeerA's webcam stream rather than desktop (that has been shared).
P.S. PeerA is able to actually see that desktop is being shared by for some reason that stream that is being sent over to PeerB is the webcam and not shared screen.

答:
Alright. So it turns out that all you need to do in screen sharing is playing with streams.

Here's how it goes:

Client-side:

make a call to getUserMedia() to firstly get the audio (use audio constraints n call)

next u need to make a call to getScreenId(), the function that will return the "screen" stream. The function return the screen constraints.

use these constraints now and make the "options variable ans pass "sendSource" as "screen"

make the call to:

new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function (error)

the callback of the function must make the call to generateOffer(which will have the "offer").

Make the message required for the websocket call

Server-side:

Now on the server side, firstly "release" the current userSession's outgoing endpoint as:

userSession.outgoingMedia.release();

Then you will need to delete the "incoming endpoints" of the rest of the ppl in the room as:

```<code> for (var i in usersInRoom) {
   var user = usersInRoom[i];
   // release viewer from this
   if(user.id == userSession.id){
     continue;
   }
   user.incomingMedia[userSession.id].release();
   delete user.incomingMedia[userSession.id];
 }
</code>```

now make a new endpoint and set this as the current usersessions's outgoing endpoint

After this do the steps that need to be done to send your current video and receive the other videos

NOTE: remember to make sure there is no duplication of the "div" element on the html page while displaying the streams. This causes some conflict and you wont receive the screen share on the other screens

Title: Kurento screen sharing in room

Body:
I am currently facing some issues sharing my screen with any Kurento room that I join. For now I am using the repo (https://github.com/TribeMedia/kurento-group-call-1) and making modifications on the code to help attach a screen sharing conept to the application.

Currently, I am able to do the following:

Add a share screen button on the page (super simple)

Get the screen/window popup that comes when clicking the share screen button (using the getScreenId.js by muaz khan (https://github.com/muaz-khan/getScreenId))

After selecting required application/window, display it as local stream for user (to actually see what is being shared) and then remake the rtc connections.

The problem that I am facing is, when another peer joins the room, I get the webcam stream of the initial participants in the room and not the screenshare. Is there something that I am missing in the implementation? Would we really helpful if anybody can help me out!

Following are snippets of the code that I have implemented:

In index.html:

<button id="sharescreen" disabled="disabled" onClick="shareScreen()">Share Screen</button>

In the client side js code:
```</p>

<pre><code>function shareScreen(){
    var audioConstraints = {
        audio: false,
        video: true,
    };
    navigator.getUserMedia(audioConstraints, function(stream) {
        initiateScreenSharing(stream);
    }, function(error) {
        console.error("Could not get audio stream! " + error);
    });
}

function initiateScreenSharing(audioStream){
    getScreenId(function (error, sourceId, screen_constraints) {
        console.log("screen_constraints");
        console.log(screen_constraints);
        navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
        navigator.getUserMedia(screen_constraints, function (stream) {
            console.log(stream);

            var constraints = {
                audio: true,
                video: {
                    frameRate: {
                        min: 1, ideal: 15, max: 30
                    },
                    width: {
                        min: 32, ideal: 50, max: 320
                    },
                    height: {
                        min: 32, ideal: 50, max: 320
                    }
                }
            };

            var localParticipant = new Participant(sessionId);
            participants[sessionId] = localParticipant;
            localVideo = document.getElementById("local_video");
            var video = localVideo;

            var options = {
                localVideo: video,
                videoStream: stream,
                mediaConstraints: constraints,
                onicecandidate: localParticipant.onIceCandidate.bind(localParticipant),
                sendSource: 'desktop'
            };

            localParticipant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function (error) {
                if (error) {
                    return console.error(error);
                }

                // Set localVideo to new object if on IE/Safari
                localVideo = document.getElementById("local_video");

                // initial main video to local first
                localVideoCurrentId = sessionId;
                //localVideo.src = localParticipant.rtcPeer.localVideo.src;
                localVideo.muted = true;

                console.log("local participant id : " + sessionId);
                this.generateOffer(localParticipant.offerToReceiveVideo.bind(localParticipant));
            });

        }, function (error) {
            console.error(error);
        });
    });
}
</code></pre>

<p>```

For example:

If PeerA joins the room 1st and shares the desktop, and PeerB joins the same room, then PeerB will see PeerA's webcam stream rather than desktop (that has been shared).
P.S. PeerA is able to actually see that desktop is being shared by for some reason that stream that is being sent over to PeerB is the webcam and not shared screen.

Body:
Alright. So it turns out that all you need to do in screen sharing is playing with streams.

Here's how it goes:

Client-side:

make a call to getUserMedia() to firstly get the audio (use audio constraints n call)

next u need to make a call to getScreenId(), the function that will return the "screen" stream. The function return the screen constraints.

use these constraints now and make the "options variable ans pass "sendSource" as "screen"

make the call to:

new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function (error)

the callback of the function must make the call to generateOffer(which will have the "offer").

Make the message required for the websocket call

Server-side:

Now on the server side, firstly "release" the current userSession's outgoing endpoint as:

userSession.outgoingMedia.release();

Then you will need to delete the "incoming endpoints" of the rest of the ppl in the room as:

 for (var i in usersInRoom) {
   var user = usersInRoom[i];
   // release viewer from this
   if(user.id == userSession.id){
     continue;
   }
   user.incomingMedia[userSession.id].release();
   delete user.incomingMedia[userSession.id];
 }

now make a new endpoint and set this as the current usersessions's outgoing endpoint

After this do the steps that need to be done to send your current video and receive the other videos

NOTE: remember to make sure there is no duplication of the "div" element on the html page while displaying the streams. This causes some conflict and you wont receive the screen share on the other screens


问:
How to deal with frame by queue?
I push frame to queue, then use another thread to deal with it, but always run in "the push frame thread".

```<code>VideoSource.NewFrame += VideoSource_NewFrame;
private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    var bitmap = (Bitmap)eventArgs.Frame;
    if (_fileWriter.IsOpen&&IsRecording)
    {
        _bitmaps.Enqueue(bitmap);
        //Thread.Sleep(10);
    }
}
</code>```

but if I process Thread.Sleep(10), the another thread will work.

another thread code:

```<code>new Task(() =>
{
    Bitmap bitmap = null;
    while (IsRecording==true)
    {
        if (_bitmaps.Count == 0)
            continue;
        _bitmaps.TryDequeue(out bitmap);
        if(bitmap!=null&& _fileWriter.IsOpen)
            _fileWriter.WriteVideoFrame(bitmap);
        if (_bitmaps.Count == 0 && IsRecording == false&&_fileWriter.IsOpen)
        {
            _fileWriter.Flush();
            _fileWriter.Close();
        }
    }
}).Start();
</code>```

How to use more elegant method deal with it?

答:
I just change code to this.
it work...</p>

```<code>var bitmap = (Bitmap)eventArgs.Frame.Clone();
</code>```

Title: How to deal with frame by queue?

Body:
I push frame to queue, then use another thread to deal with it, but always run in "the push frame thread".

VideoSource.NewFrame += VideoSource_NewFrame;
private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    var bitmap = (Bitmap)eventArgs.Frame;
    if (_fileWriter.IsOpen&&IsRecording)
    {
        _bitmaps.Enqueue(bitmap);
        //Thread.Sleep(10);
    }
}

but if I process Thread.Sleep(10), the another thread will work.

another thread code:

new Task(() =>
{
    Bitmap bitmap = null;
    while (IsRecording==true)
    {
        if (_bitmaps.Count == 0)
            continue;
        _bitmaps.TryDequeue(out bitmap);
        if(bitmap!=null&& _fileWriter.IsOpen)
            _fileWriter.WriteVideoFrame(bitmap);
        if (_bitmaps.Count == 0 && IsRecording == false&&_fileWriter.IsOpen)
        {
            _fileWriter.Flush();
            _fileWriter.Close();
        }
    }
}).Start();

How to use more elegant method deal with it?

Body:
I just change code to this.
it work...

var bitmap = (Bitmap)eventArgs.Frame.Clone();


问:
How to set the splash screen for react-native android
How does one set a splash screen for react-native android, I can't find anything on the topic and I thought it was odd.

Thanks

答:
This tutorial here works great - I quoted it and modified a bit, I added the react-native-background-color touch.

https://medium.com/react-native-development/change-splash-screen-in-react-native-android-app-74e6622d699 (which is based on this https://www.bignerdranch.com/blog/splash-screens-the-right-way/ - so this is native Android technique)

You need to create splash screen in res/drawable. Let’s call it splash_screen.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@android:color/white"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>
</code>```

Now you need to update res/values/styles.xml

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>

<style name="SplashTheme" parent="AppTheme">
        <item name="android:windowBackground">@drawable/splash_screen</item>
    </style>

</resources>
</code>```

Now open AndroidManifest.xml and replace AppTheme with SplashTheme in MainActivity

```<code><activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/SplashTheme"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
</activity>
</code>```

We use SplashTheme instead of updating AppTheme, to add this background only to start activity and leave other stuff without changes.

After you try the above out, you will notice the splash screen will always stay under your js views. You have two options to hide the splash screen:

Either use react-native-background-color module from https://github.com/ramilushev/react-native-background-color to set a color on the background which will remove the image. (This is the recommended way because when keyboard shows in some cases, it makes the root view visible for a split second.)

Or set a solid (non-transparent) background color on your root view.

Note on what "root view" means. This is the very first <View> you render in your app that you control (meaning that you can style it).

Custom Color

If you want to use a custom color, other then @android:color/*** then what you have to do is create colors.xml at android\app\src\main\res\values\colors.xml and define a colors like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="foobar">#ca949b</color>
</resources>
</code>```

You can use whatever name and whatever color code.

Then back in splash_screen.xml we update <item android:drawable="@android:color/white" /> to be <item android:drawable="@color/foobar" />

Extra info on removing the background splash image from behind

After you create a splash like this. You will notice that the image stays in the background forever. To remove this image use this module - https://github.com/ramilushev/react-native-background-color - and call BackgroundColor.setColor('#XXXXXX') with whatever color. It will remove the image.

Instead of using an opaque color on your root view to cover the splash, it is still recommended to use the above module, because when the keyboard shows, the background view shows for a split second.

Body:
This tutorial here works great - I quoted it and modified a bit, I added the react-native-background-color touch.

https://medium.com/react-native-development/change-splash-screen-in-react-native-android-app-74e6622d699 (which is based on this https://www.bignerdranch.com/blog/splash-screens-the-right-way/ - so this is native Android technique)

You need to create splash screen in res/drawable. Let’s call it splash_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@android:color/white"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Now you need to update res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>

<style name="SplashTheme" parent="AppTheme">
        <item name="android:windowBackground">@drawable/splash_screen</item>
    </style>

</resources>

Now open AndroidManifest.xml and replace AppTheme with SplashTheme in MainActivity

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/SplashTheme"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
</activity>

We use SplashTheme instead of updating AppTheme, to add this background only to start activity and leave other stuff without changes.

After you try the above out, you will notice the splash screen will always stay under your js views. You have two options to hide the splash screen:

Either use react-native-background-color module from https://github.com/ramilushev/react-native-background-color to set a color on the background which will remove the image. (This is the recommended way because when keyboard shows in some cases, it makes the root view visible for a split second.)

Or set a solid (non-transparent) background color on your root view.

Note on what "root view" means. This is the very first <View> you render in your app that you control (meaning that you can style it).

Custom Color

If you want to use a custom color, other then @android:color/*** then what you have to do is create colors.xml at android\app\src\main\res\values\colors.xml and define a colors like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="foobar">#ca949b</color>
</resources>

You can use whatever name and whatever color code.

Then back in splash_screen.xml we update <item android:drawable="@android:color/white" /> to be <item android:drawable="@color/foobar" />

Extra info on removing the background splash image from behind

After you create a splash like this. You will notice that the image stays in the background forever. To remove this image use this module - https://github.com/ramilushev/react-native-background-color - and call BackgroundColor.setColor('#XXXXXX') with whatever color. It will remove the image.

Instead of using an opaque color on your root view to cover the splash, it is still recommended to use the above module, because when the keyboard shows, the background view shows for a split second.


问:
react-redux connect() and error TS2345
I'm having trouble to figure out why this code fails to build with the following error:

```<code>(43,3): error TS2345: Argument of type 'typeof Day' is not assignable to parameter of type 'Component<Props | (Props & ConnectProps & DispatchProps)>'.
  Type 'typeof Day' is not assignable to type 'StatelessComponent<Props | (Props & ConnectProps & DispatchProps)>'.
    Type 'typeof Day' provides no match for the signature '(props: (Props & { children?: ReactNode; }) | (Props & ConnectProps & DispatchProps & { children?: ReactNode; }), context?: any): ReactElement<any>'.
</code>```

I am running typescript 2.3.3 and the @types/react-redux are at version 4.4.41.

```<code>import * as React from "react";
import { connect } from "react-redux";

export interface Props {
  date: Date;
}

export interface ConnectProps {
  shifts: string[];
}

export interface DispatchProps {}

class Day extends React.Component<Props & ConnectProps & DispatchProps, null> {
  render() {
    /* simplified */
    return <div />;
  }
}

const mapStateToProps = (state: any, ownProps?: Props): ConnectProps => {
  /* simplified */
  return {
    shifts: []
  };
};

const mapDispatchToProps = (dispatch: any): DispatchProps => ({});

export default connect<ConnectProps, DispatchProps, Props>(
  mapStateToProps,
  mapDispatchToProps
)(Day);

let component = <Day date={new Date()} />
</code>```

I want to avoid decorators as long as they are experimental.

答:
I want to avoid decorators as long as they are experimental.

Wrong way to approach it. They work just like JSX works. The current type definitions assume you are going to use decorators.

More

If you still don't want to use decorators you will have to write your own type definitions and then override the ones from redux, neither of which are simple challenges. You are welcome to tackle them for fun though but require more time than can be presented in a helpful SO answer.

Title: react-redux connect() and error TS2345

Body:
I'm having trouble to figure out why this code fails to build with the following error:

(43,3): error TS2345: Argument of type 'typeof Day' is not assignable to parameter of type 'Component<Props | (Props & ConnectProps & DispatchProps)>'.
  Type 'typeof Day' is not assignable to type 'StatelessComponent<Props | (Props & ConnectProps & DispatchProps)>'.
    Type 'typeof Day' provides no match for the signature '(props: (Props & { children?: ReactNode; }) | (Props & ConnectProps & DispatchProps & { children?: ReactNode; }), context?: any): ReactElement<any>'.

I am running typescript 2.3.3 and the @types/react-redux are at version 4.4.41.

import * as React from "react";
import { connect } from "react-redux";

export interface Props {
  date: Date;
}

export interface ConnectProps {
  shifts: string[];
}

export interface DispatchProps {}

class Day extends React.Component<Props & ConnectProps & DispatchProps, null> {
  render() {
    /* simplified */
    return
;
  }
}

const mapStateToProps = (state: any, ownProps?: Props): ConnectProps => {
  /* simplified */
  return {
    shifts: []
  };
};

const mapDispatchToProps = (dispatch: any): DispatchProps => ({});

export default connect<ConnectProps, DispatchProps, Props>(
  mapStateToProps,
  mapDispatchToProps
)(Day);

let component = <Day date={new Date()} />

I want to avoid decorators as long as they are experimental.


问:
2 Elements fill remaining height
I have a div in the middle with content inside.

I wish to have the top and bottom divs fill the remaining space.

Something like this

```<code><div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

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

If possible I would like the set a min height for the top and bottom containers.

答:
With flexbox you can do that

html, body {
  margin: 0;
}
body {
  display: flex;            /*  IE fix  */
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;              /*  IE fix  */
}
.top, .bottom {
  flex: 1;                  /*  fill remaining space  */
  background: lightblue;
}
.middle {
  background: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

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

And if you need, you can also add a min-height to the top/bottom elements

html, body {
  margin: 0;
}
body {
  display: flex;            /*  IE fix  */
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;              /*  IE fix  */
}
.top, .bottom {
  flex: 1;                  /*  fill remaining space  */
  background: lightblue;
  min-height: 200px;        /*  set a min-height  */
}
.middle {
  background: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

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

Title: 2 Elements fill remaining height

Body:
I have a div in the middle with content inside.

I wish to have the top and bottom divs fill the remaining space.

Something like this

        Content

If possible I would like the set a min height for the top and bottom containers.

Body:
With flexbox you can do that

html, body {
  margin: 0;
}
body {
  display: flex;            /*  IE fix  */
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;              /*  IE fix  */
}
.top, .bottom {
  flex: 1;                  /*  fill remaining space  */
  background: lightblue;
}
.middle {
  background: lightgreen;
}

<div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

    </div>
</div>

And if you need, you can also add a min-height to the top/bottom elements

html, body {
  margin: 0;
}
body {
  display: flex;            /*  IE fix  */
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;              /*  IE fix  */
}
.top, .bottom {
  flex: 1;                  /*  fill remaining space  */
  background: lightblue;
  min-height: 200px;        /*  set a min-height  */
}
.middle {
  background: lightgreen;
}

<div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

    </div>
</div>


问:
Changing "name" of launcher for ios/android
I created my react native project with react-native init runupdownnow. That is short for "Run Up Down Now".

I now am ready to release my app to the stores. I was able to change the icon on android and ios. But I am not able to change the "name" that appear below the launcher icon. Is the only option to react-native init "Run Up Down Now"?

答:
This can be changed by following the specifics for each platform - for Android inside the ApplicationManifest.xml, and in the application settings for iOS.

This isn't something that is controlled from within React Native - the init for the name is pre-setting these values, however can be changed as if they were native apps.


问:
Passing data between tab viewed controllers in swift?
What it does

When the first page in my tab bar controller loads, I retrieve data from a json file

I store it in an array (in the first view controller)

The data obtained will be displayed in the second view controller. The data is already loaded and stored in an array in the first view controller.

Problem:

I can't figure out a way to pass the data between the two view controllers. Can't pass data based on the segue identifier since it is a tab bar controller

Please help!

答:
I ended up using a singleton as Woodster suggested in his answer above.

In Swift 3

Create a new swift file and create a class:

```<code>class Items {
    static let sharedInstance = Items()
    var array = [String]()
}
</code>```

In any of your view controllers you can access your array like this:

```<code>Items.sharedInstance.array.append("New String")
print(Items.sharedInstance.array)
</code>```

Body:
I ended up using a singleton as Woodster suggested in his answer above.

In Swift 3

Create a new swift file and create a class:

class Items {
    static let sharedInstance = Items()
    var array = [String]()
}

In any of your view controllers you can access your array like this:

Items.sharedInstance.array.append("New String")
print(Items.sharedInstance.array)


问:
Use Python to parse multiple json items into a SQLite database
I'm looking for a non-explicit way to parse a JSON list (i.e. [] with {} items inside) into a sqlite database.

Specifically, I'm stuck at point where I want to say

```<code>INSERT into MYTABLE (col 1, col2, ...) this datarow in this jsondata
</code>```

I feel that there should be a way to abstract things such that the line above is almost what it takes. My data is a JSON list, containing a multiple JSON dictionaries. Each dictionary has a dozen or so key:value pairs. Nothing nested.

```<code>{"object_id":3          ,"name":"rsid"          ,"column_id":1
,"system_type_id":127   ,"user_type_id":127     ,"max_length":8
,"precision":19         ,"scale":0              ,"collation_name":null
,"is_nullable":false    ,"is_ansi_padded":false ,"is_rowguidcol":false
,"is_identity":false    ,"is_computed":false    ,"is_filestream":false
,"is_replicated":false  ,"is_non_sql_subscribed":false
,"is_merge_published":false                     ,"is_dts_replicated":false
,"is_xml_document":false                        ,"xml_collection_id":0
,"default_object_id":0  ,"rule_object_id":0     ,"is_sparse":false
,"is_column_set":false}
</code>```

Every single itesm in the json list [{k1:v1a, k2:v2a}, {k1:v1b,k2:v2b},...] will have the exact same KEY names. I've taken these as the names of the columns in my sqlite database. The VALUES will be different though. Hence a table is filled by getting the VALUES for each KEY/COLUMN into that row for that item.

```<code>k1  | k2  | k3  | ... | km
v1a | v2a | v3a | ... | vma
v1b | v2b | v3b | ... | vmb
...
v1n | v2n | v3n | ... | vmn
</code>```

IN SQL, insert statements need not be written in the exact same order as the columns of the database. This is because you specify the columns you are inserting for (and thus the order) in the INSERT declaration. This seems to be perfect for JSON, in which every single row/item in the JSON list contains its column-name (the key). Therefore, I want a statement that says "given this row of JSON, insert all of its data into the SQL table by coordinating the JSON key name with the SQL table column name". This is what I mean by non-explicit.

```<code>import json

r3 = some data file you read and close
r4 = json.loads(r3)
# let's dump this into SQLite

import sqlite3

the_database = sqlite3.connect("sys_col_database.sqlite")
the_cursor = the_database.cursor()

row_keys = r4[0].keys()
# all of the key are below for reference. 25 total keys.
'''
'is_merge_published',   'rule_object_id',   'system_type_id',
'is_xml_document',      'user_type_id',     'is_ansi_padded',
'column_id',            'is_column_set',    'scale',
'is_dts_replicated',    'object_id',        'xml_collection_id',
'max_length',           'collation_name',   'default_object_id',
'is_rowguidcol',        'precision',        'is_computed',
'is_sparse',            'is_filestream',    'name',
'is_nullable',          'is_identity',      'is_replicated',
'is_non_sql_subscribed'
'''

sys_col_table_statement = """create table sysColumns (
    is_merge_published text,
    rule_object_id integer,
    system_type_id integer,
    is_xml_document text,
    user_type_id integer,
    is_ansi_padded text,
    column_id integer,
    is_column_set text,
    scale integer,
    is_dts_replicated text,
    object_id integer,
    xml_collection_id integer,
    max_length integer,
    collation_name text,
    default_object_id integer,
    is_rowguidcol text,
    precision integer,
    is_computed text,
    is_sparse text,
    is_filestream text,
    name text,
    is_nullable text,
    is_identity text,
    is_replicated text,
    is_non_sql_subscribed text
    )
"""

the_cursor.execute(sys_col_table_statement)

insert_statement = """insert into sysColumns values (
{0},{1},{2},{3},{4},
{5},{6},{7},{8},{9},
{10},{11},{12},{13},{14},
{15},{16},{17},{18},{19},
{20},{21},{22},{23},{24})""".format(*r4[0].keys())
</code>```

This where I am stuck. insert_statement is a construction of the string that will be executed. Now I need to execute it, but feed it the right data from each JSON item in r4. I'm not sure how to write that.

答:
Here are two options. I also loaded the JSON data in one step.

```<code>#python 3.4.3

import json
import sqlite3

with open("data.json",'r') as f:
    r4 = json.load(f)

the_database = sqlite3.connect("sys_col_database.sqlite")
the_cursor = the_database.cursor()

row_keys = list(r4[0].keys())
# all of the key are below for reference. 25 total keys.
'''
'is_merge_published',   'rule_object_id',   'system_type_id',
'is_xml_document',      'user_type_id',     'is_ansi_padded',
'column_id',            'is_column_set',    'scale',
'is_dts_replicated',    'object_id',        'xml_collection_id',
'max_length',           'collation_name',   'default_object_id',
'is_rowguidcol',        'precision',        'is_computed',
'is_sparse',            'is_filestream',    'name',
'is_nullable',          'is_identity',      'is_replicated',
'is_non_sql_subscribed'
'''

sys_col_table_statement = """create table sysColumns (
is_merge_published text,
rule_object_id integer,
system_type_id integer,
is_xml_document text,
user_type_id integer,
is_ansi_padded text,
column_id integer,
is_column_set text,
scale integer,
is_dts_replicated text,
object_id integer,
xml_collection_id integer,
max_length integer,
collation_name text,
default_object_id integer,
is_rowguidcol text,
precision integer,
is_computed text,
is_sparse text,
is_filestream text,
name text,
is_nullable text,
is_identity text,
is_replicated text,
is_non_sql_subscribed text
)
"""
# method 1
# create a string with the keys prepopulated
prepared_insert_statement = """insert into sysColumns (\
{0}, {1}, {2}, {3}, {4}, \
{5}, {6}, {7}, {8}, {9}, \
{10}, {11}, {12}, {13}, {14}, \
{15}, {16}, {17}, {18}, {19}, \
{20}, {21}, {22}, {23}, {24}) values (\
'{{{0}}}', '{{{1}}}', '{{{2}}}', '{{{3}}}', '{{{4}}}', \
'{{{5}}}', '{{{6}}}', '{{{7}}}', '{{{8}}}', '{{{9}}}', \
'{{{10}}}', '{{{11}}}', '{{{12}}}', '{{{13}}}', '{{{14}}}', \
'{{{15}}}', '{{{16}}}', '{{{17}}}', '{{{18}}}', '{{{19}}}', \
'{{{20}}}', '{{{21}}}', '{{{22}}}', '{{{23}}}', '{{{24}}}'\
)""".format(*r4[0].keys())

# unpack the dictionary to extract the values
insert_statement = prepared_insert_statement.format(**r4[0])

# method 2
# get the keys and values in one step
r4_0_items = list(r4[0].items())
insert_statement2 = """insert into sysColumns (\
{0[0]}, {1[0]}, {2[0]}, {3[0]}, {4[0]}, \
{5[0]}, {6[0]}, {7[0]}, {8[0]}, {9[0]}, \
{10[0]}, {11[0]}, {12[0]}, {13[0]}, {14[0]}, \
{15[0]}, {16[0]}, {17[0]}, {18[0]}, {19[0]}, \
{20[0]}, {21[0]}, {22[0]}, {23[0]}, {24[0]}) values (\
'{0[1]}', '{1[1]}', '{2[1]}', '{3[1]}', '{4[1]}', \
'{5[1]}', '{6[1]}', '{7[1]}', '{8[1]}', '{9[1]}', \
'{10[1]}', '{11[1]}', '{12[1]}', '{13[1]}', '{14[1]}', \
'{15[1]}', '{16[1]}', '{17[1]}', '{18[1]}', '{19[1]}', \
'{20[1]}', '{21[1]}', '{22[1]}', '{23[1]}', '{24[1]}'\
)""".format(*r4_0_items)

the_cursor.execute(sys_col_table_statement)
#the_cursor.execute(insert_statement)
the_cursor.execute(insert_statement2)
the_database.commit()
</code>```

For reference:

unpack dictionary

string formatting examples

Body:
I'm looking for a non-explicit way to parse a JSON list (i.e. [] with {} items inside) into a sqlite database.

Specifically, I'm stuck at point where I want to say

INSERT into MYTABLE (col 1, col2, ...) this datarow in this jsondata

I feel that there should be a way to abstract things such that the line above is almost what it takes. My data is a JSON list, containing a multiple JSON dictionaries. Each dictionary has a dozen or so key:value pairs. Nothing nested.

{"object_id":3          ,"name":"rsid"          ,"column_id":1
,"system_type_id":127   ,"user_type_id":127     ,"max_length":8
,"precision":19         ,"scale":0              ,"collation_name":null
,"is_nullable":false    ,"is_ansi_padded":false ,"is_rowguidcol":false
,"is_identity":false    ,"is_computed":false    ,"is_filestream":false
,"is_replicated":false  ,"is_non_sql_subscribed":false
,"is_merge_published":false                     ,"is_dts_replicated":false
,"is_xml_document":false                        ,"xml_collection_id":0
,"default_object_id":0  ,"rule_object_id":0     ,"is_sparse":false
,"is_column_set":false}

Every single itesm in the json list [{k1:v1a, k2:v2a}, {k1:v1b,k2:v2b},...] will have the exact same KEY names. I've taken these as the names of the columns in my sqlite database. The VALUES will be different though. Hence a table is filled by getting the VALUES for each KEY/COLUMN into that row for that item.

k1  | k2  | k3  | ... | km
v1a | v2a | v3a | ... | vma
v1b | v2b | v3b | ... | vmb
...
v1n | v2n | v3n | ... | vmn

IN SQL, insert statements need not be written in the exact same order as the columns of the database. This is because you specify the columns you are inserting for (and thus the order) in the INSERT declaration. This seems to be perfect for JSON, in which every single row/item in the JSON list contains its column-name (the key). Therefore, I want a statement that says "given this row of JSON, insert all of its data into the SQL table by coordinating the JSON key name with the SQL table column name". This is what I mean by non-explicit.

import json

r3 = some data file you read and close
r4 = json.loads(r3)
# let's dump this into SQLite

import sqlite3

the_database = sqlite3.connect("sys_col_database.sqlite")
the_cursor = the_database.cursor()

row_keys = r4[0].keys()
# all of the key are below for reference. 25 total keys.
'''
'is_merge_published',   'rule_object_id',   'system_type_id',
'is_xml_document',      'user_type_id',     'is_ansi_padded',
'column_id',            'is_column_set',    'scale',
'is_dts_replicated',    'object_id',        'xml_collection_id',
'max_length',           'collation_name',   'default_object_id',
'is_rowguidcol',        'precision',        'is_computed',
'is_sparse',            'is_filestream',    'name',
'is_nullable',          'is_identity',      'is_replicated',
'is_non_sql_subscribed'
'''

sys_col_table_statement = """create table sysColumns (
    is_merge_published text,
    rule_object_id integer,
    system_type_id integer,
    is_xml_document text,
    user_type_id integer,
    is_ansi_padded text,
    column_id integer,
    is_column_set text,
    scale integer,
    is_dts_replicated text,
    object_id integer,
    xml_collection_id integer,
    max_length integer,
    collation_name text,
    default_object_id integer,
    is_rowguidcol text,
    precision integer,
    is_computed text,
    is_sparse text,
    is_filestream text,
    name text,
    is_nullable text,
    is_identity text,
    is_replicated text,
    is_non_sql_subscribed text
    )
"""

the_cursor.execute(sys_col_table_statement)

insert_statement = """insert into sysColumns values (
{0},{1},{2},{3},{4},
{5},{6},{7},{8},{9},
{10},{11},{12},{13},{14},
{15},{16},{17},{18},{19},
{20},{21},{22},{23},{24})""".format(*r4[0].keys())

This where I am stuck. insert_statement is a construction of the string that will be executed. Now I need to execute it, but feed it the right data from each JSON item in r4. I'm not sure how to write that.

Body:
Here are two options. I also loaded the JSON data in one step.

#python 3.4.3

import json
import sqlite3

with open("data.json",'r') as f:
    r4 = json.load(f)

the_database = sqlite3.connect("sys_col_database.sqlite")
the_cursor = the_database.cursor()

row_keys = list(r4[0].keys())
# all of the key are below for reference. 25 total keys.
'''
'is_merge_published',   'rule_object_id',   'system_type_id',
'is_xml_document',      'user_type_id',     'is_ansi_padded',
'column_id',            'is_column_set',    'scale',
'is_dts_replicated',    'object_id',        'xml_collection_id',
'max_length',           'collation_name',   'default_object_id',
'is_rowguidcol',        'precision',        'is_computed',
'is_sparse',            'is_filestream',    'name',
'is_nullable',          'is_identity',      'is_replicated',
'is_non_sql_subscribed'
'''

sys_col_table_statement = """create table sysColumns (
is_merge_published text,
rule_object_id integer,
system_type_id integer,
is_xml_document text,
user_type_id integer,
is_ansi_padded text,
column_id integer,
is_column_set text,
scale integer,
is_dts_replicated text,
object_id integer,
xml_collection_id integer,
max_length integer,
collation_name text,
default_object_id integer,
is_rowguidcol text,
precision integer,
is_computed text,
is_sparse text,
is_filestream text,
name text,
is_nullable text,
is_identity text,
is_replicated text,
is_non_sql_subscribed text
)
"""
# method 1
# create a string with the keys prepopulated
prepared_insert_statement = """insert into sysColumns (\
{0}, {1}, {2}, {3}, {4}, \
{5}, {6}, {7}, {8}, {9}, \
{10}, {11}, {12}, {13}, {14}, \
{15}, {16}, {17}, {18}, {19}, \
{20}, {21}, {22}, {23}, {24}) values (\
'{{{0}}}', '{{{1}}}', '{{{2}}}', '{{{3}}}', '{{{4}}}', \
'{{{5}}}', '{{{6}}}', '{{{7}}}', '{{{8}}}', '{{{9}}}', \
'{{{10}}}', '{{{11}}}', '{{{12}}}', '{{{13}}}', '{{{14}}}', \
'{{{15}}}', '{{{16}}}', '{{{17}}}', '{{{18}}}', '{{{19}}}', \
'{{{20}}}', '{{{21}}}', '{{{22}}}', '{{{23}}}', '{{{24}}}'\
)""".format(*r4[0].keys())

# unpack the dictionary to extract the values
insert_statement = prepared_insert_statement.format(**r4[0])

# method 2
# get the keys and values in one step
r4_0_items = list(r4[0].items())
insert_statement2 = """insert into sysColumns (\
{0[0]}, {1[0]}, {2[0]}, {3[0]}, {4[0]}, \
{5[0]}, {6[0]}, {7[0]}, {8[0]}, {9[0]}, \
{10[0]}, {11[0]}, {12[0]}, {13[0]}, {14[0]}, \
{15[0]}, {16[0]}, {17[0]}, {18[0]}, {19[0]}, \
{20[0]}, {21[0]}, {22[0]}, {23[0]}, {24[0]}) values (\
'{0[1]}', '{1[1]}', '{2[1]}', '{3[1]}', '{4[1]}', \
'{5[1]}', '{6[1]}', '{7[1]}', '{8[1]}', '{9[1]}', \
'{10[1]}', '{11[1]}', '{12[1]}', '{13[1]}', '{14[1]}', \
'{15[1]}', '{16[1]}', '{17[1]}', '{18[1]}', '{19[1]}', \
'{20[1]}', '{21[1]}', '{22[1]}', '{23[1]}', '{24[1]}'\
)""".format(*r4_0_items)

the_cursor.execute(sys_col_table_statement)
#the_cursor.execute(insert_statement)
the_cursor.execute(insert_statement2)
the_database.commit()

For reference:

unpack dictionary

string formatting examples