问:
How can I apply BatchNormalization to an Input for a Keras LSTM?
I have:

```<code>    model = Sequential()
    model.add(LSTM(32, input_shape=(
        SEQ_LENGTH, VECTOR_SIZE), return_sequences=True))
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='relu')))

    adam_optimizer = optimizers.Adam(
        learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)
    model.compile(loss='mean_squared_error',
                  optimizer=adam_optimizer)
</code>```

The input and output of my model are both (100, 129).

答:
```<code>model.add(BatchNormalization(center=True, scale=True, beta_regularizer=regularizers.l2(0.01),
                                 gamma_regularizer=regularizers.l2(0.01),
                                 beta_constraint='max_norm', gamma_constraint='max_norm',
                                 input_shape=(x, y)))
</code>```

It's just a layer that you add into your model

Body:
I have:

    model = Sequential()
    model.add(LSTM(32, input_shape=(
        SEQ_LENGTH, VECTOR_SIZE), return_sequences=True))
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='relu')))

    adam_optimizer = optimizers.Adam(
        learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)
    model.compile(loss='mean_squared_error',
                  optimizer=adam_optimizer)

The input and output of my model are both (100, 129).

Body:
model.add(BatchNormalization(center=True, scale=True, beta_regularizer=regularizers.l2(0.01),
                                 gamma_regularizer=regularizers.l2(0.01),
                                 beta_constraint='max_norm', gamma_constraint='max_norm',
                                 input_shape=(x, y)))

It's just a layer that you add into your model


来源: stackexchange

问:
CollectionType expected argument of type "string or null", "array" given at property path "cc"
Can someone explain why i am getting this error? I am using CollectionType for first time. Used documentation.
Here is my part of where i am trying to use CollectionType:

```<code>$builder->add('cc', CollectionType::class, [
         'required' => false,
         'entry_type' => EmailType::class
])
</code>```

and here is my request:

```<code>{
    "email" => "test@test.com",
    "description" => "test description",
    "subject" => "test",
    "cc" => array:1 [
         0 => "test1@test.com"
    ]
}
</code>```

答:
I had pretty much the same problem as you, but your exact solution didn't work for me, but you put me on a path to solve it, therefore gave you +1 of course. I wanted to write this as a comment but it was too long. Here is what I had to change your solution to to make it work:</p>

```<code>$builder->get('myCollection')
    ->addModelTransformer(new CallbackTransformer(
        function ($array) {
            return $array;
        },
        function ($array) {
            $res = array();
            foreach($array as $item) {
                if ($item === null) {
                    $item = '';
                }
                $res[] = $item;
            }

            return $res;
        }
    ));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Can someone explain why i am getting this error? I am using CollectionType for first time. Used documentation.
Here is my part of where i am trying to use CollectionType:

$builder->add('cc', CollectionType::class, [
         'required' => false,
         'entry_type' => EmailType::class
])

and here is my request:

{
    "email" => "test@test.com",
    "description" => "test description",
    "subject" => "test",
    "cc" => array:1 [
         0 => "test1@test.com"
    ]
}

Body:
I had pretty much the same problem as you, but your exact solution didn't work for me, but you put me on a path to solve it, therefore gave you +1 of course. I wanted to write this as a comment but it was too long. Here is what I had to change your solution to to make it work:

$builder->get('myCollection')
    ->addModelTransformer(new CallbackTransformer(
        function ($array) {
            return $array;
        },
        function ($array) {
            $res = array();
            foreach($array as $item) {
                if ($item === null) {
                    $item = '';
                }
                $res[] = $item;
            }

            return $res;
        }
    ));


问:
Split on Split overlap [ RAKU ]
I stumbled upon a "strange" behaviour when I tried to parse a multiline string (with tab separated strings) with the intent to find all values separated by tabs, using two splits in a row:

```<code>use v6.d;   # 2020.01 release

my $s = "L1:C1\tL1:C2\tL1:C3\nL2:C1\tL2:C2\tL2:C3\nL3:C1\tL3:C2\tL3:C3";

say $s.split(/\n/).split(/\t/).raku;
</code>```

and the corresponding printout is as follows:

```<code>("L1:C1", "L1:C2", "L1:C3 L2:C1", "L2:C2", "L2:C3 L3:C1", "L3:C2", "L3:C3").Seq
</code>```

The "strange" behaviour is in the 3d and 5th member of the resulting sequence. It seems that there is an overlap of the "expected" last string of a line and the first string of the subsequent line.

My expectation was something like :

```<code>("L1:C1", "L1:C2", "L1:C3", "L2:C1", "L2:C2", "L2:C3", "L3:C1", "L3:C2", "L3:C3").Seq
</code>```

Anybody to give a detailed explanation to the innerworkings of this behaviour?

Just to clarify things, I know that the correct code is:

```<code>$s.split(/\n/)>>.split(/\t/).flat.raku
</code>```

but my question is about the innerworkings of the "wrong" code. How did Raku come to that result?

答:
If you would like your split to give you the individual pieces as one list, rather than a list of lists, you can use the split method's variant that takes a list of delimiters to split by:

```<code>say "L1:C1,L1:C2;L1:C3\nL2:C1-L2:C2|L2:C3^L3:C1".split([",", ";", "\n", "|", "^"]).raku;
# output: ("L1:C1", "L1:C2", "L1:C3", "L2:C1-L2:C2", "L2:C3", "L3:C1").Seq
</code>```

Passing the :k or :v adverbs to the split method call will leave the separator in the result list as separate entries; with :k the value will be the index in the separators list that has the matched separator in it, with :v the separator itself will be in the result list.

Title: Split on Split overlap [ RAKU ]

Body:
I stumbled upon a "strange" behaviour when I tried to parse a multiline string (with tab separated strings) with the intent to find all values separated by tabs, using two splits in a row:

use v6.d;   # 2020.01 release

my $s = "L1:C1\tL1:C2\tL1:C3\nL2:C1\tL2:C2\tL2:C3\nL3:C1\tL3:C2\tL3:C3";

say $s.split(/\n/).split(/\t/).raku;

and the corresponding printout is as follows:

("L1:C1", "L1:C2", "L1:C3 L2:C1", "L2:C2", "L2:C3 L3:C1", "L3:C2", "L3:C3").Seq

The "strange" behaviour is in the 3d and 5th member of the resulting sequence. It seems that there is an overlap of the "expected" last string of a line and the first string of the subsequent line.

My expectation was something like :

("L1:C1", "L1:C2", "L1:C3", "L2:C1", "L2:C2", "L2:C3", "L3:C1", "L3:C2", "L3:C3").Seq

Anybody to give a detailed explanation to the innerworkings of this behaviour?

Just to clarify things, I know that the correct code is:

$s.split(/\n/)>>.split(/\t/).flat.raku

but my question is about the innerworkings of the "wrong" code. How did Raku come to that result?

Body:
If you would like your split to give you the individual pieces as one list, rather than a list of lists, you can use the split method's variant that takes a list of delimiters to split by:

say "L1:C1,L1:C2;L1:C3\nL2:C1-L2:C2|L2:C3^L3:C1".split([",", ";", "\n", "|", "^"]).raku;
# output: ("L1:C1", "L1:C2", "L1:C3", "L2:C1-L2:C2", "L2:C3", "L3:C1").Seq

Passing the :k or :v adverbs to the split method call will leave the separator in the result list as separate entries; with :k the value will be the index in the separators list that has the matched separator in it, with :v the separator itself will be in the result list.


问:
xcode4 : How to use "git repository" to share same project with multiple users on different computer?
Xcode4's new feature "git repository" is good feature. But I am confuse with it.

Does it allow check-in and check-out functionality ?

Does it allow other user to modify same file if someone already modifying it ?

答: Yes, git is a full version control system (VCS). There are many great resources for learning about git such as all of the resources listed in this stack overflow question.</p>

ContentLicense: CC BY-SA 3.0


问:
Localhost connection refused when integrating WireMock and JMeter
I'm trying to integrate Wiremock into a Jmeter test plan so that every time I execute the test plan it will start up an instance of WireMock in the beginning and then run tests I have outlined. I followed this answer (https://stackoverflow.com/a/49130518/12912945) but the problem I am having is that I always get the error:

```<code>Response message:Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
</code>```

From what I can see, the Wiremock server never starts even though I have the following code in a JSR223 Sampler at the beginning of the test plan:

```<code>import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import static com.github.tomakehurst.wiremock.client.WireMock.*;

public class WireMockTest {

    public static void main(String[] args) {
        WireMockServer wireMockServer = new WireMockServer();
        configureFor("127.0.0.1", 8080);
        wireMockServer.start();
        StubMapping foo = stubFor(get(urlEqualTo("/some/thing"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withBody("Hello World")));
        wireMockServer.addStubMapping(foo);
    }
}
</code>```

Could anyone point me in the right direction of how to correctly integrate the two, I have tried adding to the classpath but I feel like I have not done this correctly or I'm missing something

Thank you!

答:
You're defining the main function but I failed to see where you're executing it. In other words your Wiremock initialization code isn't getting executed at all.

You need to explicitly call this main function in order to get your code executed, to get this done add the next line to the end of your script:

```<code>WireMockTest.main()
</code>```

Once done the JSR223 Sampler will invoke the code inside the main function and the Wiremock server will be started.

Another option is to remove these class and function declarations and just use

```<code>import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import static com.github.tomakehurst.wiremock.client.WireMock.*;

WireMockServer wireMockServer = new WireMockServer();
configureFor("127.0.0.1", 8080);
wireMockServer.start();
StubMapping foo = stubFor(get(urlEqualTo("/some/thing"))
      .willReturn(aResponse()
              .withStatus(200)
              .withBody("Hello World")));
wireMockServer.addStubMapping(foo);
</code>```

as the script you define in the JSR223 Test elements don't require an entry point

Check out Apache Groovy - Why and How You Should Use It article for more information about Groovy scripting in JMeter tests.

Body:
I'm trying to integrate Wiremock into a Jmeter test plan so that every time I execute the test plan it will start up an instance of WireMock in the beginning and then run tests I have outlined. I followed this answer (https://stackoverflow.com/a/49130518/12912945) but the problem I am having is that I always get the error:

Response message:Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

From what I can see, the Wiremock server never starts even though I have the following code in a JSR223 Sampler at the beginning of the test plan:

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import static com.github.tomakehurst.wiremock.client.WireMock.*;

public class WireMockTest {

    public static void main(String[] args) {
        WireMockServer wireMockServer = new WireMockServer();
        configureFor("127.0.0.1", 8080);
        wireMockServer.start();
        StubMapping foo = stubFor(get(urlEqualTo("/some/thing"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withBody("Hello World")));
        wireMockServer.addStubMapping(foo);
    }
}

Could anyone point me in the right direction of how to correctly integrate the two, I have tried adding to the classpath but I feel like I have not done this correctly or I'm missing something

Thank you!

Body:
You're defining the main function but I failed to see where you're executing it. In other words your Wiremock initialization code isn't getting executed at all.

You need to explicitly call this main function in order to get your code executed, to get this done add the next line to the end of your script:

WireMockTest.main()

Once done the JSR223 Sampler will invoke the code inside the main function and the Wiremock server will be started.

Another option is to remove these class and function declarations and just use

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import static com.github.tomakehurst.wiremock.client.WireMock.*;

WireMockServer wireMockServer = new WireMockServer();
configureFor("127.0.0.1", 8080);
wireMockServer.start();
StubMapping foo = stubFor(get(urlEqualTo("/some/thing"))
      .willReturn(aResponse()
              .withStatus(200)
              .withBody("Hello World")));
wireMockServer.addStubMapping(foo);

as the script you define in the JSR223 Test elements don't require an entry point

Check out Apache Groovy - Why and How You Should Use It article for more information about Groovy scripting in JMeter tests.


问:
fluent plugin kafka json escaping
I am using version fluent-plugin-kafka version 0.12.3.

I have an application that outputs its logs in JSON format, but my console consumer shows that the logs are escaped.

for instance, the application output the following log line:

```<code>{
  "msg": "ok"
}
</code>```

when i look at the log using the console consumer, it outputs:

```<code>{
  "container_id": "7e...",
  "container_name": "/app",
  "source": "stdout",
  "log": "{\"msg\": \"ok\"}"
}
</code>```

how should fluent-plugin-kafka should be configured so the application log will be nested as a json without escaping it?

desired output:

```<code>{
  "container_id": "7e...",
  "container_name": "/app",
  "source": "stdout",
  "log": {
    "msg": "ok"
  }
}
</code>```

答: using record transformer filter i was able to mutate the incoming data.</p>

Title: fluent plugin kafka json escaping

Body:
I am using version fluent-plugin-kafka version 0.12.3.

I have an application that outputs its logs in JSON format, but my console consumer shows that the logs are escaped.

for instance, the application output the following log line:

{
  "msg": "ok"
}

when i look at the log using the console consumer, it outputs:

{
  "container_id": "7e...",
  "container_name": "/app",
  "source": "stdout",
  "log": "{\"msg\": \"ok\"}"
}

how should fluent-plugin-kafka should be configured so the application log will be nested as a json without escaping it?

desired output:

{
  "container_id": "7e...",
  "container_name": "/app",
  "source": "stdout",
  "log": {
    "msg": "ok"
  }
}


问:
Can't reach POST RESPONSE json - ReactJS, NodeJS
I've got my own API server which is connected to mysql db.
When I send request to server everything is ok, I see input from browser and output from db in console. But I can't see anything new in browser. I want update values, but nothing.Image of browser and server console or When I want to print state it won't get any update

Browser

```<code>import React, {Component} from 'react';
import './data_table.css';

class DataTable extends Component {
    constructor (props) {
        super(props);
        this.keys = [];

        this.state = {
            rows: {},
            queryOutput: [],
        }
    }

    componentDidMount(){
        //Fetching number of affected and changed rows
        fetch('/api/update')
            .then(res => res.json())
            .then(rows => {this.setState({rows: rows})
            console.log(rows)});

        //Fetching output from user query
        fetch('/api/query',
            {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then(res => res.json())
            .then(qo =>{ this.setState({queryOutput: qo})
            console.log(qo)});
    }

    getReadyTable(){
        let objectToPrint;

        if(this.state.queryOutput[0]) {
             objectToPrint = this.state.queryOutput;

            this.keys = Object.keys(objectToPrint[0]);
            return (
                <table className={'output'}>
                    <thead>
                    <tr>{this.keys.map((key, val) => <th key={val}>{key}</th>)}</tr>
                    </thead>
                    <tbody>
                    {objectToPrint.map((obj, val) => <tr key={val}>{this.keys.map((key, idx) => <td
                        key={idx}>{obj[key]}</td>)}</tr>)}
                    </tbody>
                </table>
            );
        }
            else{
                objectToPrint = this.state.rows;
                this.keys = Object.keys(objectToPrint);
                return (
                    <table className={'output'}>
                        <thead ><tr >{this.keys.map( (key, val) =>  <th key={val}>{key}</th> )}</tr></thead>
                        <tbody><tr >{Object.values(objectToPrint).map( (obj, val) => <td key={val}>{obj}</td>)}</tr></tbody>
                    </table>

                );
            }

    }

    render() {

        return (
     <div>
    {this.getReadyTable()}
            </div>
        );
    }
}

export default DataTable;
</code>```

Server

```<code>//Some requires and uses...
app.post('/api/query', (req, res) => {
  console.log(`\n  Query input : ${JSON.stringify(req.body)}`);
  let queryInput = (Object.values(req.body).join(' '));

    if(queryInput.length>4){//provisional condition
      res.json(dbApi.queryFromUser(queryInput));
    }

    else{
      res.json(dbApi.queryOutput);
    }
});

</code>```

MySQL connection

```<code>//Connection and others...
    const receivingQuery =(queryInput) => {
        db.query(queryInput, (err, result) =>{
            if(err) throw err+' : '+queryInput;

            queryOutput = result;
            console.log("\nQuery output "+ JSON.stringify(queryOutput));
        });
        return queryOutput;
    }

module.exports={ queryFromUser: receivingQuery }
</code>```

答: Check "this.setState({rows})". this is not right. what state are you referring to?</p>

Body:
I've got my own API server which is connected to mysql db.
When I send request to server everything is ok, I see input from browser and output from db in console. But I can't see anything new in browser. I want update values, but nothing.Image of browser and server console or When I want to print state it won't get any update

Browser

import React, {Component} from 'react';
import './data_table.css';

class DataTable extends Component {
    constructor (props) {
        super(props);
        this.keys = [];

        this.state = {
            rows: {},
            queryOutput: [],
        }
    }

    componentDidMount(){
        //Fetching number of affected and changed rows
        fetch('/api/update')
            .then(res => res.json())
            .then(rows => {this.setState({rows: rows})
            console.log(rows)});

        //Fetching output from user query
        fetch('/api/query',
            {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then(res => res.json())
            .then(qo =>{ this.setState({queryOutput: qo})
            console.log(qo)});
    }

    getReadyTable(){
        let objectToPrint;

        if(this.state.queryOutput[0]) {
             objectToPrint = this.state.queryOutput;

            this.keys = Object.keys(objectToPrint[0]);
            return (

{this.keys.map((key, val) => {key}	)}

                    {objectToPrint.map((obj, val) =>
{this.keys.map((key, idx) => {obj[key]}	)}
)}

            );
        }
            else{
                objectToPrint = this.state.rows;
                this.keys = Object.keys(objectToPrint);
                return (

{this.keys.map( (key, val) =>  {key}	 )}

{Object.values(objectToPrint).map( (obj, val) => {obj}	)}

                );
            }

    }

    render() {

        return (

    {this.getReadyTable()}

        );
    }
}

export default DataTable;

Server

//Some requires and uses...
app.post('/api/query', (req, res) => {
  console.log(`\n  Query input : ${JSON.stringify(req.body)}`);
  let queryInput = (Object.values(req.body).join(' '));

    if(queryInput.length>4){//provisional condition
      res.json(dbApi.queryFromUser(queryInput));
    }

    else{
      res.json(dbApi.queryOutput);
    }
});

MySQL connection

//Connection and others...
    const receivingQuery =(queryInput) => {
        db.query(queryInput, (err, result) =>{
            if(err) throw err+' : '+queryInput;

            queryOutput = result;
            console.log("\nQuery output "+ JSON.stringify(queryOutput));
        });
        return queryOutput;
    }

module.exports={ queryFromUser: receivingQuery }


问:
Here Javascript API example CORS errors
Just getting started with here. I've tried the javascript sample and getting cors error. My test url is https://fleetcom511.com/all_drivers_new.php</p>

```<code>Access to XMLHttpRequest at 'https://vector.hereapi.com/v2/vectortiles/info?xnlp=CL_JSMv3.1.11.1&apikey=xxxxx' from origin 'http://fleetcom511.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
mapsjs-core.js:41 GET https://vector.hereapi.com/v2/vectortiles/info?xnlp=CL_JSMv3.1.11.1&apikey=xxxxx net::ERR_FAILED
d @ mapsjs-core.js:41
Lc @ mapsjs-core.js:42
application/json @ mapsjs-core.js:75
jf.qj @ mapsjs-core.js:74
(anonymous) @ mapsjs-core.js:52
(anonymous) @ mapsjs-core.js:52
$d.b @ mapsjs-core.js:52
$d.add @ mapsjs-core.js:51
Xd @ mapsjs-core.js:51
jf @ mapsjs-core.js:74
ip @ VM152:49
dp @ VM152:48
X.qb @ VM152:45
X.yj @ VM152:50
X.Ug @ VM152:60
(anonymous) @ all_drivers_new.php:50
all_drivers_new.php:1 Access to XMLHttpRequest at 'https://vector.hereapi.com/v2/vectortiles/base/mc/13/4096/4096/omv?xnlp=CL_JSMv3.1.11.1&apikey=xxxxxx' from origin 'http://fleetcom511.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
mapsjs-core.js:77 GET https://vector.hereapi.com/v2/vectortiles/base/mc/13/4096/4096/omv?xnlp=CL_JSMv3.1.11.1&apikey=xxxxx net::ERR_FAILED
</code>```

答:
The error message tells where is the problem: No 'Access-Control-Allow-Origin' header is present on the requested resource.

You should enable CORS on your server. I don't know what type of server you use, but if it's apache, then this article should help: https://tecadmin.net/enable-cors-apache/

Title: Here Javascript API example CORS errors

Body:
Just getting started with here. I've tried the javascript sample and getting cors error. My test url is https://fleetcom511.com/all_drivers_new.php

Access to XMLHttpRequest at 'https://vector.hereapi.com/v2/vectortiles/info?xnlp=CL_JSMv3.1.11.1&apikey=xxxxx' from origin 'http://fleetcom511.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
mapsjs-core.js:41 GET https://vector.hereapi.com/v2/vectortiles/info?xnlp=CL_JSMv3.1.11.1&apikey=xxxxx net::ERR_FAILED
d @ mapsjs-core.js:41
Lc @ mapsjs-core.js:42
application/json @ mapsjs-core.js:75
jf.qj @ mapsjs-core.js:74
(anonymous) @ mapsjs-core.js:52
(anonymous) @ mapsjs-core.js:52
$d.b @ mapsjs-core.js:52
$d.add @ mapsjs-core.js:51
Xd @ mapsjs-core.js:51
jf @ mapsjs-core.js:74
ip @ VM152:49
dp @ VM152:48
X.qb @ VM152:45
X.yj @ VM152:50
X.Ug @ VM152:60
(anonymous) @ all_drivers_new.php:50
all_drivers_new.php:1 Access to XMLHttpRequest at 'https://vector.hereapi.com/v2/vectortiles/base/mc/13/4096/4096/omv?xnlp=CL_JSMv3.1.11.1&apikey=xxxxxx' from origin 'http://fleetcom511.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
mapsjs-core.js:77 GET https://vector.hereapi.com/v2/vectortiles/base/mc/13/4096/4096/omv?xnlp=CL_JSMv3.1.11.1&apikey=xxxxx net::ERR_FAILED


问:
how can I extract text contents from GUI apps  in linux?
I want to  extract text contents from GUI apps,here are 2 examples::

example 1:

Suppose I opened  firefox, and input url : www.google.com

how can I extract the string "www.google.com" from firefox using my own app ?

example 2:

open calculator(using gcalctool),then input 1+1

How can I extract the string "1+1" of calculator from my own program?

in brief ,what I want is to find out whether there is a way to extract the text contents from any widget of an GUI application

Thanks

答:
I don't think there's a generic way to do this, at least not a very elegant one.

Some inelegant ideas:

You might be able to modify the X window system or even some toolkit framework to extract what is being displayed in specific window elements as text.

You could take a screenshot and use an OCR library to convert the pixels back into text for the interesting areas.

You could recompile the apps of interest to add some kind of mechanism for asking them questions.

You could use something like xtest to inject events highlighting the region of interest and copying it to the clipboard.


问:
Split Postal Code in R ( just the 2 first numbers)
I have a dataframe. One column is the postal code in Catalonia for example 17190 it's the village Salt when ‘08’ it's Barcelona, ‘17’ it's Girona, ‘25’ it's Lleida and ‘43’ it's Tarragona, the 4 counties.

I would like to know how to split/reduce 17190 to 17, for the grouped by counties

Thanks in advance

答:
Substract is ok and is the way i would do it, moreover if yo have 50 Postal codes you might want to have a second table where you can relation the code to the province name.

Here it is an example that might interest you:

```<code>Codis<-data.frame(codi=c("08","17","25","43"),
                  provincia=c("Barcelona","Girona","Lleida","Tarragona"))
ex<-data.frame(CP=c("17888","17963","08123","08951","25003","25195","43333","43005"))

ex$provincia<-Codis$provincia[match(unlist(substr(ej$CP,1,2)),Codis$codi)]
</code>```

The result:

```<code>     CP provincia
1 17888    Girona
2 17963    Girona
3 08123 Barcelona
4 08951 Barcelona
5 25003    Lleida
6 25195    Lleida
7 43333 Tarragona
8 43005 Tarragona
</code>```

Body:
Substract is ok and is the way i would do it, moreover if yo have 50 Postal codes you might want to have a second table where you can relation the code to the province name.

Here it is an example that might interest you:

Codis<-data.frame(codi=c("08","17","25","43"),
                  provincia=c("Barcelona","Girona","Lleida","Tarragona"))
ex<-data.frame(CP=c("17888","17963","08123","08951","25003","25195","43333","43005"))

ex$provincia<-Codis$provincia[match(unlist(substr(ej$CP,1,2)),Codis$codi)]

The result:

     CP provincia
1 17888    Girona
2 17963    Girona
3 08123 Barcelona
4 08951 Barcelona
5 25003    Lleida
6 25195    Lleida
7 43333 Tarragona
8 43005 Tarragona


问:
How do I get a single percentage/proportion plot using ggplot for separate groups?
```<code>
df <- data.frame(k = sample(1:3, 100, replace = TRUE),
g = sample(1:2, 100, replace = TRUE, prob = c(0.3, 0.7)))
</code>```

In this data frame I have two groups g which members are in one of three conditions k.

Now, I want to see the proportions of the conditions k in both groups.

```<code>ggplot(df, aes(x = k, fill = as.factor(g), y = (..count..)/sum(..count..))) +
    geom_bar(position=position_dodge())
</code>```

That looks nice at first but there is a problem. The group 2 is larger than group 1. Therefore the proportions are not right: It looks as if all conditions were more likely in group 2 than in group 1. I need to calculate the y = (..count..)/sum(..count..) for both groups separately. How do I do this?

答:
Here's how you can do it:</p>

```<code>library(tidyverse)

df %>%
  group_by(g) %>%
  count(k) %>%
  mutate(share = n / sum(n)) %>%
  ggplot(aes(x = k, fill = as.factor(g), y = share)) +
  geom_col(position = position_dodge())
</code>```

Body:
df <- data.frame(k = sample(1:3, 100, replace = TRUE),
g = sample(1:2, 100, replace = TRUE, prob = c(0.3, 0.7)))

In this data frame I have two groups g which members are in one of three conditions k.

Now, I want to see the proportions of the conditions k in both groups.

ggplot(df, aes(x = k, fill = as.factor(g), y = (..count..)/sum(..count..))) +
    geom_bar(position=position_dodge())

That looks nice at first but there is a problem. The group 2 is larger than group 1. Therefore the proportions are not right: It looks as if all conditions were more likely in group 2 than in group 1. I need to calculate the y = (..count..)/sum(..count..) for both groups separately. How do I do this?

Body:
Here's how you can do it:

library(tidyverse)

df %>%
  group_by(g) %>%
  count(k) %>%
  mutate(share = n / sum(n)) %>%
  ggplot(aes(x = k, fill = as.factor(g), y = share)) +
  geom_col(position = position_dodge())


问:
How can I get sqlite working on a shared hosting server?
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

```
-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
<b>ImportError: No module named _sqlite3</b>
```

I think I have everything set up right as far as the directory structure.

```
-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

```

And finally the contents of the sqlite3 directory:

```
-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

```

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !

答: In general, the first thing to do is to ask your host. I seems a bit odd that SQLite is not installed (or installed properly). So they'll likely fix it quite fast if you ask them.</p>

Body:
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
ImportError: No module named _sqlite3

I think I have everything set up right as far as the directory structure.

-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

And finally the contents of the sqlite3 directory:

-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !


问:
Summing up all entered number in a textbox and display it in a disabled box
I need to create a manual input counter using app script editor.

I've already have my website design with a single input textbox, reset button and a disabled box.

What I want is when I input a number in the textbox and press 'Enter' it will be displayed in the disabled box. If I repeat the process the new number in the textbox will sum up to the value inside the disabled box.

I would also like to have a reset button for the disabled box.

Lastly, having a record log of values inside the disabled box.

Is this even possible to make by just using HTML, JavaScript and AppScript?

Here's my code:

```<code>let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  box2.value = e.target.value;
  history.unshift(e.target.value);
  historyContainer.innerHTML += `<p>${e.target.value}</p>`;
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
});
</code>```

I've used this code and what's happening is, when I input a number and press enter it displays in the disabled box (that's a good thing) however, the value in the textbox doesn't clear. Second things is, if I input a new number it doesn't sum up in the disabled box. Lastly, the history log records all values entered in the textbox and not in the previous value of the disabled box.

How can I fix this?

答:
I have created a demo for you as per your need. Please let me know if it fulfill your need.

To fix the problem faced by you, i am storing new value instead of previous value.

let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  const summedValue = (box2.value && box2.value.trim() === "")  ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
  box2.value = summedValue;
  historyContainer.innerHTML += `<p>${box2.value}</p>`;
  box1.value = "";
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = ""
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="box1" />
<input type="number" id="box2" disabled />
<div id="history">
</div>

<button type="button" id="reset">
Reset
</button></code>```

Body:
I need to create a manual input counter using app script editor.

I've already have my website design with a single input textbox, reset button and a disabled box.

What I want is when I input a number in the textbox and press 'Enter' it will be displayed in the disabled box. If I repeat the process the new number in the textbox will sum up to the value inside the disabled box.

I would also like to have a reset button for the disabled box.

Lastly, having a record log of values inside the disabled box.

Is this even possible to make by just using HTML, JavaScript and AppScript?

Here's my code:

let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  box2.value = e.target.value;
  history.unshift(e.target.value);
  historyContainer.innerHTML += `<p>${e.target.value}</p>`;
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
});

I've used this code and what's happening is, when I input a number and press enter it displays in the disabled box (that's a good thing) however, the value in the textbox doesn't clear. Second things is, if I input a new number it doesn't sum up in the disabled box. Lastly, the history log records all values entered in the textbox and not in the previous value of the disabled box.

How can I fix this?

Body:
I have created a demo for you as per your need. Please let me know if it fulfill your need.

To fix the problem faced by you, i am storing new value instead of previous value.

let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  const summedValue = (box2.value && box2.value.trim() === "")  ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
  box2.value = summedValue;
  historyContainer.innerHTML += `<p>${box2.value}</p>`;
  box1.value = "";
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = ""
});

<input type="number" id="box1" />
<input type="number" id="box2" disabled />
<div id="history">
</div>

<button type="button" id="reset">
Reset
</button>


问:
Setting multiple images to the response entity
I want to return response with multiple images to client. And in client side i want to download those images. I haven't find any method like .setEntity() for HttpServletResponse. So i have decided to add images in header fields. I am adding in following way,

```<code>File sourceFile = new File(serverLocation + "/" + filename);

servletresponse.setContentType(new MimetypesFileTypeMap().getContentType(sourceFile));
servletresponse.setContentLength((int)sourceFile.length());
servletresponse.setHeader(filename, "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
</code>```

I am unable to download on client side. This is what i am doing on client side,

```<code>CloseableHttpResponse response = httpclient.execute(httppost);
Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equals(filename)) {
                    imagename = headers[i].getValue();
                }
            }
InputStream fileInputStream = new ByteArrayInputStream(imagename.getBytes(StandardCharsets.UTF_8));
            byte[] bufffer = new byte[512];
            while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                fileOutputStream.write(bufffer, 0, bufferSize);
            }
</code>```

However its not writing images. How can i add multiple files and download it on client side. Please help.

答:
A single HTTP call can only return a single image(content). If you need to send over multiple images you could possibly:

Pass on image URLs in response instead of the actual resource and have client parse and download them

If you want to hide the response from the body you can use headers for the same purpose as you mentioned in the example (but that looks like a weird use case to me)

Body:
I want to return response with multiple images to client. And in client side i want to download those images. I haven't find any method like .setEntity() for HttpServletResponse. So i have decided to add images in header fields. I am adding in following way,

File sourceFile = new File(serverLocation + "/" + filename);

servletresponse.setContentType(new MimetypesFileTypeMap().getContentType(sourceFile));
servletresponse.setContentLength((int)sourceFile.length());
servletresponse.setHeader(filename, "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

I am unable to download on client side. This is what i am doing on client side,

CloseableHttpResponse response = httpclient.execute(httppost);
Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equals(filename)) {
                    imagename = headers[i].getValue();
                }
            }
InputStream fileInputStream = new ByteArrayInputStream(imagename.getBytes(StandardCharsets.UTF_8));
            byte[] bufffer = new byte[512];
            while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                fileOutputStream.write(bufffer, 0, bufferSize);
            }

However its not writing images. How can i add multiple files and download it on client side. Please help.


问:
Is there any way to get live telemetry data from the DJI Mavic 2 Zoom to another unit, say a computer?
As part of a course on my university we've been given the task of taking the live wind telemetry from a drone and then feeding it to a neural network so that it gives better estimates than just using a sensor.

The research we've concluded so far tells us that our drone, the DJI Mavic 2 Zoom, is only compatible with the Windows SDK but not the onboard SDK.

Simply our question is; is there any way for us to send the raw wind speed and direction data from the drones sensors to a computer?

答: Create Android application with DJI Mobile SDK and send data from msdk to your computer with wifi.</p>


问:
A difference output with difference ways for make a list that only exist from the dictionary
first i used a list methods remove() to delete the item that doesn't exist in the dictionary values.
The code is like this:

```<code>rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
for num in rollNumber:
    if num not in sampleDict.values():
        rollNumber.remove(num)

print('After removing unwanted element from list', rollNumber)
</code>```

output : [47,69,76,95,97]
this is wrong answer

the second one i made a empty list and used append() methods from the item that in dictionary.values
the code is like this:

```<code>rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
new = []
for num in rollNumber:
    if num in sampleDict.values():
        new.append(num)

print('After removing unwanted element from list', new)
</code>```

output : [47,69,76,97]
this the correct answer

Do you guys know why this happens?

答:
You try to modify a list while iterating on it, this is a common mistake.
Your 2nd way is the correct one, which can be written this way:</p>

```<code>print([num for num in rollNumber if num in sampleDict.values()])
</code>```

Body:
first i used a list methods remove() to delete the item that doesn't exist in the dictionary values.
The code is like this:

rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
for num in rollNumber:
    if num not in sampleDict.values():
        rollNumber.remove(num)

print('After removing unwanted element from list', rollNumber)

output : [47,69,76,95,97]
this is wrong answer

the second one i made a empty list and used append() methods from the item that in dictionary.values
the code is like this:

rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
new = []
for num in rollNumber:
    if num in sampleDict.values():
        new.append(num)

print('After removing unwanted element from list', new)

output : [47,69,76,97]
this the correct answer

Do you guys know why this happens?

Body:
You try to modify a list while iterating on it, this is a common mistake.
Your 2nd way is the correct one, which can be written this way:

print([num for num in rollNumber if num in sampleDict.values()])


问:
How can an app handle intents without having any intent-filters in its manifest?
My understanding is that, in order to handle external intents, an app's manifest.xml file must contain an intent-filter; however, using APK Analyzer, I saw that the manifest of the Spotify app is merely:

```<code><?xml version="1.0" encoding="UTF-8"?><manifest versionCode="55843262" configForSplit="" package="com.spotify.music" split="config.xxhdpi">
  <application hasCode="false">
    <meta-data name="com.android.vending.derived.apk.id" value="8"/>
  </application>
</manifest>
</code>```

This shows no intent filters; however, I am able to open Spotify with:

```<code>adb shell am start -a "android.media.action.MEDIA_PLAY_FROM_SEARCH" -e android.intent.extra.focus "vnd.android.cursor.item/*" -e query Bowie
</code>```

What am I missing?

答:
That manifest indicates the APK contains no code:

```<code><application hasCode="false">
</code>```

Either there is another APK with the code in it (which will also contain the rest of the manifest entries you are missing), or Spotify is using Google Play Dynamic Delivery which allows modules to be downloaded and installed on the fly.

In any case, you aren't looking at the whole manifest for the app.

Body:
My understanding is that, in order to handle external intents, an app's manifest.xml file must contain an intent-filter; however, using APK Analyzer, I saw that the manifest of the Spotify app is merely:

<?xml version="1.0" encoding="UTF-8"?><manifest versionCode="55843262" configForSplit="" package="com.spotify.music" split="config.xxhdpi">
  <application hasCode="false">
    <meta-data name="com.android.vending.derived.apk.id" value="8"/>
  </application>
</manifest>

This shows no intent filters; however, I am able to open Spotify with:

adb shell am start -a "android.media.action.MEDIA_PLAY_FROM_SEARCH" -e android.intent.extra.focus "vnd.android.cursor.item/*" -e query Bowie

What am I missing?

Body:
That manifest indicates the APK contains no code:

<application hasCode="false">

Either there is another APK with the code in it (which will also contain the rest of the manifest entries you are missing), or Spotify is using Google Play Dynamic Delivery which allows modules to be downloaded and installed on the fly.

In any case, you aren't looking at the whole manifest for the app.


问:
How to remove white space on the side of my website
I have a website (https://olsenspkg.com) that has white space on the right hand side of every page. Currently I have tried this to solve it:

body {
  overflow-x: hidden !important;
  width: 100%;
}```

It only fixes it on chrome though. Safari still acts like I haven't put that code in.

Regular Site View

White Space on the Right

答:
The problem is with the #searchBar from your header.
You gave it left:478px but it has position:relative. So it still occupies space. By giving it left 478px it made your website 478px larger to the right.

So remove that and position it using other solutions. Like a simple #searchBar { text-align:right } i guess will do the trick.

Also try to avoid using overflow-x: hidden on body . You never know what problems you might cause. Always in this scenarios try to find the element that is causing this unwanted overflow and deal with that specific element.

Body:
I have a website (https://olsenspkg.com) that has white space on the right hand side of every page. Currently I have tried this to solve it:

body {
  overflow-x: hidden !important;
  width: 100%;
}

It only fixes it on chrome though. Safari still acts like I haven't put that code in.

Regular Site View

White Space on the Right


问:
Transpose column names to rows and put values in seperate column
I have the following table which you can also find in the SQL fiddle here:

```<code>CREATE TABLE Flows (
    Product TEXT,
    Inbound_Date DATE,
    Outbound_Date DATE,
    Return_Date DATE,
    Quantity VARCHAR(255)
);

INSERT INTO Flows
(Product, Inbound_Date, Outbound_Date, Return_Date, Quantity)
VALUES

("Product A", "2019-01-01", NULL, NULL, "400"),
("Product A", NULL, "2019-05-08", NULL, "200"),
("Product A", NULL, NULL, "2019-06-25", "600"),

("Product B", "2019-03-08", NULL, NULL, "380"),
("Product B", NULL, "2019-03-15", NULL, "120"),
("Product B", NULL, NULL, "2019-04-17", "610");
</code>```

I use the following SQL to get the values from the table:

```<code>SELECT Product, Inbound_Date, Outbound_Date, Return_Date, sum(Quantity)
FROM Flows
GROUP BY 1,2,3,4;
</code>```

All this works fine so far.

However, now I want to achieve that the dates are displayed in one column called FLow_Date.

The result should look like this:

```<code>Product          Date_Type            Flow_Date
Product A        Inbound_Date        2019-01-01
Product A        Oubound_Date        2019-05-08
Product A        Return_Date         2019-06-25
Product B        Inbound_Date        2019-03-08
Product B        Outbound_Date       2019-03-15
Product B        Return_Date         2019-04-17
</code>```

What do I need to change in my code to make it work?

答:
you can use coalesce() and a case expression:

```<code>select
    product,
    case
        when inbound_date is null  then 'inbound_date'
        when outbound_date is null then 'outbound_date'
        when return_date is null   then 'return_date'
    end date_type,
    coalesce(inbound_date, outbound_date, return_date) flow_date
from mytable
</code>```

Of if you want this in your aggregate query:

```<code>select
    product,
    case
        when inbound_date is null  then 'inbound_date'
        when outbound_date is null then 'outbound_date'
        when return_date is null   then 'return_date'
    end date_type,
    coalesce(inbound_date, outbound_date, return_date) flow_date,
    sum(quantity) sum_quantity
from mytable
group by
    product,
    date_type,
    flow_date
</code>```

Body:
I have the following table which you can also find in the SQL fiddle here:

CREATE TABLE Flows (
    Product TEXT,
    Inbound_Date DATE,
    Outbound_Date DATE,
    Return_Date DATE,
    Quantity VARCHAR(255)
);

INSERT INTO Flows
(Product, Inbound_Date, Outbound_Date, Return_Date, Quantity)
VALUES

("Product A", "2019-01-01", NULL, NULL, "400"),
("Product A", NULL, "2019-05-08", NULL, "200"),
("Product A", NULL, NULL, "2019-06-25", "600"),

("Product B", "2019-03-08", NULL, NULL, "380"),
("Product B", NULL, "2019-03-15", NULL, "120"),
("Product B", NULL, NULL, "2019-04-17", "610");

I use the following SQL to get the values from the table:

SELECT Product, Inbound_Date, Outbound_Date, Return_Date, sum(Quantity)
FROM Flows
GROUP BY 1,2,3,4;

All this works fine so far.

However, now I want to achieve that the dates are displayed in one column called FLow_Date.

The result should look like this:

Product          Date_Type            Flow_Date
Product A        Inbound_Date        2019-01-01
Product A        Oubound_Date        2019-05-08
Product A        Return_Date         2019-06-25
Product B        Inbound_Date        2019-03-08
Product B        Outbound_Date       2019-03-15
Product B        Return_Date         2019-04-17

What do I need to change in my code to make it work?

Body:
you can use coalesce() and a case expression:

select
    product,
    case
        when inbound_date is null  then 'inbound_date'
        when outbound_date is null then 'outbound_date'
        when return_date is null   then 'return_date'
    end date_type,
    coalesce(inbound_date, outbound_date, return_date) flow_date
from mytable

Of if you want this in your aggregate query:

select
    product,
    case
        when inbound_date is null  then 'inbound_date'
        when outbound_date is null then 'outbound_date'
        when return_date is null   then 'return_date'
    end date_type,
    coalesce(inbound_date, outbound_date, return_date) flow_date,
    sum(quantity) sum_quantity
from mytable
group by
    product,
    date_type,
    flow_date


问:
How to access google shared drive data with php
All of my files and folders are inside shared drive named as "Z". I'm using google drive api to list all files and folders of the shared drive but it's returning me empty array. Is there any permissions issue</p>

```<code>$parentId = 'shareddriveid';
$queryString = "trashed = false and '$parentId' in parents";
$parameters = ['q' => $queryString,'pageSize' => 1000,0,'fields' => 'nextPageToken, files(id, name, fileExtension, fullFileExtension, kind, mimeType, createdTime, modifiedTime, iconLink, webViewLink, webContentLink, parents)'];
$f =$this->drive->files->listFiles($parameters);
dd($f);
</code>```

答:
You can get the Shared Drive's files on PHP using the following code:

```<code>// Print the names and IDs for up to 10 files.
$optParams = array(
    'corpora' => 'drive',
    'driveId' => 'your-shared-drive-id',
    'includeItemsFromAllDrives' => true,
    'pageSize' => 10,
    'supportsAllDrives' => true,
    'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

// print results
foreach ($results->getFiles() as $file){
    printf("%s (%s)\n", $file->getName(), $file->getId());
}
</code>```

As the Files: list endpoint states, you also have to set the corpora, includeItemsFromAllDrives and supportsAllDrives parameters.

Body:
All of my files and folders are inside shared drive named as "Z". I'm using google drive api to list all files and folders of the shared drive but it's returning me empty array. Is there any permissions issue

$parentId = 'shareddriveid';
$queryString = "trashed = false and '$parentId' in parents";
$parameters = ['q' => $queryString,'pageSize' => 1000,0,'fields' => 'nextPageToken, files(id, name, fileExtension, fullFileExtension, kind, mimeType, createdTime, modifiedTime, iconLink, webViewLink, webContentLink, parents)'];
$f =$this->drive->files->listFiles($parameters);
dd($f);

Body:
You can get the Shared Drive's files on PHP using the following code:

// Print the names and IDs for up to 10 files.
$optParams = array(
    'corpora' => 'drive',
    'driveId' => 'your-shared-drive-id',
    'includeItemsFromAllDrives' => true,
    'pageSize' => 10,
    'supportsAllDrives' => true,
    'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

// print results
foreach ($results->getFiles() as $file){
    printf("%s (%s)\n", $file->getName(), $file->getId());
}

As the Files: list endpoint states, you also have to set the corpora, includeItemsFromAllDrives and supportsAllDrives parameters.


答:
For debugging do a console.log in

```<code>.then(qo => this.setState({queryOutput: qo}));
</code>```

I.e.

```<code>.then(qo => console.log(qo));
</code>```

Title: Can't reach POST RESPONSE json - ReactJS, NodeJS

Body:
I've got my own API server which is connected to mysql db.
When I send request to server everything is ok, I see input from browser and output from db in console. But I can't see anything new in browser. I want update values, but nothing.Image of browser and server console or When I want to print state it won't get any update

Browser

import React, {Component} from 'react';
import './data_table.css';

class DataTable extends Component {
    constructor (props) {
        super(props);
        this.keys = [];

        this.state = {
            rows: {},
            queryOutput: [],
        }
    }

    componentDidMount(){
        //Fetching number of affected and changed rows
        fetch('/api/update')
            .then(res => res.json())
            .then(rows => {this.setState({rows: rows})
            console.log(rows)});

        //Fetching output from user query
        fetch('/api/query',
            {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then(res => res.json())
            .then(qo =>{ this.setState({queryOutput: qo})
            console.log(qo)});
    }

    getReadyTable(){
        let objectToPrint;

        if(this.state.queryOutput[0]) {
             objectToPrint = this.state.queryOutput;

            this.keys = Object.keys(objectToPrint[0]);
            return (

{this.keys.map((key, val) => {key}	)}

                    {objectToPrint.map((obj, val) =>
{this.keys.map((key, idx) => {obj[key]}	)}
)}

            );
        }
            else{
                objectToPrint = this.state.rows;
                this.keys = Object.keys(objectToPrint);
                return (

{this.keys.map( (key, val) =>  {key}	 )}

{Object.values(objectToPrint).map( (obj, val) => {obj}	)}

                );
            }

    }

    render() {

        return (

    {this.getReadyTable()}

        );
    }
}

export default DataTable;

Server

//Some requires and uses...
app.post('/api/query', (req, res) => {
  console.log(`\n  Query input : ${JSON.stringify(req.body)}`);
  let queryInput = (Object.values(req.body).join(' '));

    if(queryInput.length>4){//provisional condition
      res.json(dbApi.queryFromUser(queryInput));
    }

    else{
      res.json(dbApi.queryOutput);
    }
});

MySQL connection

//Connection and others...
    const receivingQuery =(queryInput) => {
        db.query(queryInput, (err, result) =>{
            if(err) throw err+' : '+queryInput;

            queryOutput = result;
            console.log("\nQuery output "+ JSON.stringify(queryOutput));
        });
        return queryOutput;
    }

module.exports={ queryFromUser: receivingQuery }

Body:
For debugging do a console.log in

.then(qo => this.setState({queryOutput: qo}));

I.e.

.then(qo => console.log(qo));


问:
Combine --user with --prefix error with setup.py install
I was trying to install Python packages a system I recently gained access to. I was trying to take advantage of Python's relatively new per user site-packages directory, and the new option --user. (The option is currently undocumented, however it exists for Python 2.6+; you can see the help by running python setup.py install --help.)

When I tried running

```<code>python setup.py install --user
</code>```

on any package I downloaded, I always got the following error:

```<code>error: can't combine user with with prefix/exec_prefix/home or install_(plat)base
</code>```

The error was extremely perplexing because, as you can see, I wasn't providing the --prefix, --exec-prefix, --install-base, or --install-platbase flags as command line options. I wasted a lot of time trying to figure out what the problem was. I document my answer below, in hopes to spare some other poor soul a few hours of yak shaving.

答:
I had have the same problem. It was hidden inside the ~/.config/pip/pip.conf with:

```<code>[global]
target=/foo/bar
</code>```

Such a config was created by a third-party script without my knowledge.

I suggest checking the pip configuration files and removing the target=/foo/bar options.

Body:
I was trying to install Python packages a system I recently gained access to. I was trying to take advantage of Python's relatively new per user site-packages directory, and the new option --user. (The option is currently undocumented, however it exists for Python 2.6+; you can see the help by running python setup.py install --help.)

When I tried running

python setup.py install --user

on any package I downloaded, I always got the following error:

error: can't combine user with with prefix/exec_prefix/home or install_(plat)base

The error was extremely perplexing because, as you can see, I wasn't providing the --prefix, --exec-prefix, --install-base, or --install-platbase flags as command line options. I wasted a lot of time trying to figure out what the problem was. I document my answer below, in hopes to spare some other poor soul a few hours of yak shaving.

Body:
I had have the same problem. It was hidden inside the ~/.config/pip/pip.conf with:

[global]
target=/foo/bar

Such a config was created by a third-party script without my knowledge.

I suggest checking the pip configuration files and removing the target=/foo/bar options.


问:
How to save a SQLite binding into an NSString
I have the following bind statement for binding an SQLite column. I want to save this value into an NSString named journeyName. For this I have written the following statement:

```<code>NSString * journeyName = sqlite3_bind_text( compiledStatement, 1,
                                           [Gjourney UTF8String], -1,
                                           SQLITE_TRANSIENT );
</code>```

This gives me a warning that

initialization makes pointer from integer without a cast

and my app crashes.

答:
Replace your code as the following:

```<code>NSString *journeyName = sqlite3_bind_text( compiledStatement, 1, [Gjourney UTF8String], -1, SQLITE_TRANSIENT);
</code>```

THis should work.

Body:
I have the following bind statement for binding an SQLite column. I want to save this value into an NSString named journeyName. For this I have written the following statement:

NSString * journeyName = sqlite3_bind_text( compiledStatement, 1,
                                           [Gjourney UTF8String], -1,
                                           SQLITE_TRANSIENT );

This gives me a warning that

initialization makes pointer from integer without a cast

and my app crashes.

Body:
Replace your code as the following:

NSString *journeyName = sqlite3_bind_text( compiledStatement, 1, [Gjourney UTF8String], -1, SQLITE_TRANSIENT);

THis should work.


问:
I keep getting this error for my program: VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.

```<code>//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }

//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

</code>```

Here's a picture of my error in the console

答:
you are calling the sort one more time after the array is being sorted

and the second array which is smallTwo become undefined

you can check if its undefined
before your while iterator

```<code>if (!smallTwo) {
    smallTwo = []
}
</code>```

that could solve you problem

or just send an empty array in your first call like this

```<code>mergeSort = (array) => {
return sort(divide(array), [])
}
</code>```

Body:
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.

//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }

//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

Here's a picture of my error in the console

Body:
you are calling the sort one more time after the array is being sorted

and the second array which is smallTwo become undefined

you can check if its undefined
before your while iterator

if (!smallTwo) {
    smallTwo = []
}

that could solve you problem

or just send an empty array in your first call like this

mergeSort = (array) => {
return sort(divide(array), [])
}


问:
How to pass a CheckedChange Listener to a custom view
I made a custom view with 3 toggle buttons. In my custom view class I set

```<code>public void setMyToggleButton1OnCheckedChangedListener(CompoundButton.OnCheckedChangeListener o) {
    myToggleButton1.setOnCheckedChangeListener(o);
}
</code>```

but when I try to handle this even in my main activity, it looks like this event never been triggered. In the main activity I tried

```<code>myCustomView.setMyToggleButton1OnCheckedChangedListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                //TODO something here
            }
            else {
                //TODO something here
            }
        }
    });
</code>```

I did try my other custom view with regular button and pass the standard button click event to it with the same method. I don't understand what makes it different to pass a standard button click event to custom view and passing a toggle button checkedchange event listener to a custom view.

PS: Here is what I did for regular button and its OnClickListener. This one works as I expected, that's why I try to replicate it to Toggle Button and the OnCheckedChangeListener.

in myCustomView2 (the custom view contains regular buttons)

```<code>public class myCustomView2 extends ConstraintLayout{
    private Button myRegBtn1;
    ...
    public myCustomView2(Context context) {
        this(context, null);
    }

    public myCustomView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
         setAttributes(context, attrs);
    }

    public myCustomView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setAttributes(context, attrs);
        init(context);
    }

    private void init(Context context) {
        myRegBtn = findViewById(R.id.btn1);
        ...
    }

    private void setAttributes(Context context, AttributeSet attrs) {
        ...
    }

    public void setMyRegBtnOnClickListener(OnClickListener o) {
        myRegBtn.setOnClickListener(o);
    }
}
</code>```

In my mainActivity,

```<code>public class myMainActivity extends AppCompatActivity{
    private MyCustomView2 myCustomView2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        myCustomView2.setMyRegBtnOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //TODO: some code execute here when button clicked
            }
        });
    ...
}
</code>```

答:
Okay, I find the solution. The reason causes the custom listener stop working in the custom class is the XML file layout. In the past, all my successful experiences are build on the LinearLayout. I missed that in my original problem description. the new custom view XML file I used ConstraintLayout, instead of LinearLayout. This causes the 'abnormal' inflate behavior that use to work with the LinearLayout.

In LinearLayout custom view class, init() function, I used

```<code>inflate(getContext(), R.layout.my_ll_custom_view,this);
</code>```

This won't work with the constraintlayout. I have to use following code,

```<code>View rootView = LayoutInflater.from(context).inflate(R.layout.my_cl_custom_view, this, false);
ConstraintSet constraintSet = new ConstraintSet();
this.addView(rootView);
ConstraintLayout.LayoutParams clp = new
ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
rootView.setLayoutParams(clp);
constraintSet.clone(this);
constraintSet.connect(rootView.getId(), ConstraintSet.LEFT, this.getId(), ConstraintSet.LEFT, 0);
constraintSet.connect(rootView.getId(), ConstraintSet.RIGHT, this.getId(), ConstraintSet.RIGHT, 0);
constraintSet.connect(rootView.getId(), ConstraintSet.TOP, this.getId(), ConstraintSet.TOP, 0);
constraintSet.connect(rootView.getId(), ConstraintSet.BOTTOM, this.getId(), ConstraintSet.BOTTOM, 0);
</code>```

More details can be found in https://jordan-dixon.com/2017/12/30/custom-views-with-constraint-layout-and-kotlin/

I read this blog to figure this out. and I appreciate it.

Body:
I made a custom view with 3 toggle buttons. In my custom view class I set

public void setMyToggleButton1OnCheckedChangedListener(CompoundButton.OnCheckedChangeListener o) {
    myToggleButton1.setOnCheckedChangeListener(o);
}

but when I try to handle this even in my main activity, it looks like this event never been triggered. In the main activity I tried

myCustomView.setMyToggleButton1OnCheckedChangedListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                //TODO something here
            }
            else {
                //TODO something here
            }
        }
    });

I did try my other custom view with regular button and pass the standard button click event to it with the same method. I don't understand what makes it different to pass a standard button click event to custom view and passing a toggle button checkedchange event listener to a custom view.

PS: Here is what I did for regular button and its OnClickListener. This one works as I expected, that's why I try to replicate it to Toggle Button and the OnCheckedChangeListener.

in myCustomView2 (the custom view contains regular buttons)

public class myCustomView2 extends ConstraintLayout{
    private Button myRegBtn1;
    ...
    public myCustomView2(Context context) {
        this(context, null);
    }

    public myCustomView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
         setAttributes(context, attrs);
    }

    public myCustomView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setAttributes(context, attrs);
        init(context);
    }

    private void init(Context context) {
        myRegBtn = findViewById(R.id.btn1);
        ...
    }

    private void setAttributes(Context context, AttributeSet attrs) {
        ...
    }

    public void setMyRegBtnOnClickListener(OnClickListener o) {
        myRegBtn.setOnClickListener(o);
    }
}

In my mainActivity,

public class myMainActivity extends AppCompatActivity{
    private MyCustomView2 myCustomView2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        myCustomView2.setMyRegBtnOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //TODO: some code execute here when button clicked
            }
        });
    ...
}

Body:
Okay, I find the solution. The reason causes the custom listener stop working in the custom class is the XML file layout. In the past, all my successful experiences are build on the LinearLayout. I missed that in my original problem description. the new custom view XML file I used ConstraintLayout, instead of LinearLayout. This causes the 'abnormal' inflate behavior that use to work with the LinearLayout.

In LinearLayout custom view class, init() function, I used

inflate(getContext(), R.layout.my_ll_custom_view,this);

This won't work with the constraintlayout. I have to use following code,

View rootView = LayoutInflater.from(context).inflate(R.layout.my_cl_custom_view, this, false);
ConstraintSet constraintSet = new ConstraintSet();
this.addView(rootView);
ConstraintLayout.LayoutParams clp = new
ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
rootView.setLayoutParams(clp);
constraintSet.clone(this);
constraintSet.connect(rootView.getId(), ConstraintSet.LEFT, this.getId(), ConstraintSet.LEFT, 0);
constraintSet.connect(rootView.getId(), ConstraintSet.RIGHT, this.getId(), ConstraintSet.RIGHT, 0);
constraintSet.connect(rootView.getId(), ConstraintSet.TOP, this.getId(), ConstraintSet.TOP, 0);
constraintSet.connect(rootView.getId(), ConstraintSet.BOTTOM, this.getId(), ConstraintSet.BOTTOM, 0);

More details can be found in https://jordan-dixon.com/2017/12/30/custom-views-with-constraint-layout-and-kotlin/

I read this blog to figure this out. and I appreciate it.


问:
Restructure Date in R
I have dataset like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4
</code>```

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

```<code>a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a
</code>```

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

```<code>df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")
</code>```

It's giving the desired result but it's filling alternate NA values in DATE column like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4
</code>```

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

Title: Restructure Date in R

Body:
I have dataset like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")

It's giving the desired result but it's filling alternate NA values in DATE column like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

Body:
You can try the following base R code

df$DATE<- as.Date(z <- gsub("[A-Z]\\K([A-Z]+)","\\L\\1",df$DATE),
                  format = ifelse(grepl("[[:alpha:]]",z),"%d-%b-%y","%d-%m-%y"))

such that

> df
  CODE NAME       DATE HOUR
1    1   Ab 2019-01-01    1
2    1   Ab 2019-01-02    2
3    1   Ab 2019-01-03    3
4    1   Ab 2019-01-04    4
5    2   Xy 2019-01-01    1
6    2   Xy 2019-01-02    2
7    2   Xy 2019-01-03    3
8    2   Xy 2019-01-04    4


问:
How to update docker-compose version on windows 10
I have docker and docker toolbox installed on Win10 machine.

docker -v
Docker version 18.06.0-ce, build 0ffa825

docker-compose -v
docker-compose version 1.22.0, build f46880fe

My docker version is up-to-date but the composer is not.

Any idea how can I update the composer version.

答:
I was experiencing the same issue even though my docker-compose --version showed that the version of compose I had was 1.25.4. This didn't work, I had tried reinstalling compose and docker desktop entirely on windows 10.

Eventually I changed my installation to use Linux containers, and used experimental mode. Worked.

Good luck.


问:
How to get quantity of a WooCommerce subscription?
I am currently developing a WordPress project and I am using WooCommerce with WooCommerce Subscriptions plugin to offer subscriptions to my users. I need help on how to get the quantity of a subscription in PHP.

I am using this code to get subscription but I can not retrieve quantity:

```<code>$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );
</code>```

When a user purchases a subscription, the user can select the quantity of subscriptions. So I need to get the value of this field:

答:
Your code is correct and wcs_get_subscriptions() is the right and best way to get customer active subscriptions.

But you have missed a something after your code to get the customer subscription item quantity (code commented):

```<code>// Get current customer active subscriptions
$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );

if ( count( $subscriptions ) > 0 ) {
    // Loop through customer subscriptions
    foreach ( $subscriptions as $subscription ) {
        // Get the initial WC_Order object instance from the subscription
        $order = wc_get_order( $subscription->get_parent_id() );

        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product(); // Get the product object instance

            // Target only subscriptions products type
            if( in_array( $product->get_type(), ['subscription', 'subscription_variation'] ) ) {
                $quantity = $item->get_quantity(); // Get the quantity
                echo '<p>Quantity: ' . $quantity . '</p>';
            }
        }
    }
}
</code>```

Tested and works.

Body:
I am currently developing a WordPress project and I am using WooCommerce with WooCommerce Subscriptions plugin to offer subscriptions to my users. I need help on how to get the quantity of a subscription in PHP.

I am using this code to get subscription but I can not retrieve quantity:

$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );

When a user purchases a subscription, the user can select the quantity of subscriptions. So I need to get the value of this field:

Body:
Your code is correct and wcs_get_subscriptions() is the right and best way to get customer active subscriptions.

But you have missed a something after your code to get the customer subscription item quantity (code commented):

// Get current customer active subscriptions
$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );

if ( count( $subscriptions ) > 0 ) {
    // Loop through customer subscriptions
    foreach ( $subscriptions as $subscription ) {
        // Get the initial WC_Order object instance from the subscription
        $order = wc_get_order( $subscription->get_parent_id() );

        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product(); // Get the product object instance

            // Target only subscriptions products type
            if( in_array( $product->get_type(), ['subscription', 'subscription_variation'] ) ) {
                $quantity = $item->get_quantity(); // Get the quantity
                echo '<p>Quantity: ' . $quantity . '</p>';
            }
        }
    }
}

Tested and works.


问:
Bitcode bundle could not be generated (while archiving) because Static Framework (.framework) was built without full bitcode
We are trying to enable Bitcode fully in our Static Framework but we are receiving the following error while archiving the app when the framework is integrated with it though we are able to build it on the simulator or device.

```<code>ld: bitcode bundle could not be generated because '.framework/p-iOS(PTFWOperationPrepareTransaction.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build file '.framework/p-iOS' for architecture armv7
</code>```

We have verified Bitcode state through otool -l Versions/A/p-iOS  | grep __bitcode and seems like it is enabled correctly
.

Following are our project settings for bitcode on framework's end,

And following are our project settings for bitcode on app's end,

A humble request:
Please review our settings in the above screenshots as we have already checked all the related queries on SO so please do not give them as a reference.

Also, we have already tried Static Libraries, Frameworks, and Bitcode to get our things fixed.

Thanks in advance.

答:
I also had this problem with a framework I built.
This is what worked for me:

In Build Settings of the framework project set Other C Flags to -fembed-bitcode

In the Build Settings of the framework target add a user defined flag called BITCODE_GENERATION_MODE with the value of bitcode

Both in the framework project and target, Enable Bitcode should be set on Yes

Body:
We are trying to enable Bitcode fully in our Static Framework but we are receiving the following error while archiving the app when the framework is integrated with it though we are able to build it on the simulator or device.

ld: bitcode bundle could not be generated because '.framework/p-iOS(PTFWOperationPrepareTransaction.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build file '.framework/p-iOS' for architecture armv7

We have verified Bitcode state through otool -l Versions/A/p-iOS  | grep __bitcode and seems like it is enabled correctly
.

Following are our project settings for bitcode on framework's end,

And following are our project settings for bitcode on app's end,

A humble request:
Please review our settings in the above screenshots as we have already checked all the related queries on SO so please do not give them as a reference.

Also, we have already tried Static Libraries, Frameworks, and Bitcode to get our things fixed.

Thanks in advance.


问:
Detect if code is running as a service
Is there a way for an .NET library to detect whether or not it is being run as a service?

My library can be run either way. But when its run as a service, developers need to call an additional method indicating that fact or certain features won't work correctly. I want my library, which handles logging, to write a warning if it is used in a service without that method being called.

答:
You can add the Microsoft.Extensions.Hosting.WindowsServices NuGet package and use the WindowsServiceHelpers.IsWindowsService() helper method.

For Linux you can use Microsoft.Extensions.Hosting.Systemd and the SystemdHelpers.IsSystemdService() method.

OwnerDisplayName: Grauenwolf

ContentLicense: CC BY-SA 2.5

Title: Detect if code is running as a service


问:
Faking HTTP request responses for testing in Android
I'm writing an Android app which sometimes needs to request data through HTTP from a REST API. I'm using the Apache DefaultHttpClient for performing requests. Is there a way to write tests for this app and "replace" DefaultHttpClient's response when running the tests so that test results are always consistent?

As an example of the things I'd like to test, one of the web services I'm accessing takes a string and performs a text search, returning a paged list of objects. I need to test the cases where the list is empty, the list fits in the first page, or the list is larger than a page and the app needs to make several requests to get the complete list.

I'm not the developer of this web API nor can modify its responses, so I can't change what it returns. For the above example, if I want to test the case where the list returned is empty, I could just search for a string which I'm sure won't return any results, but the other two cases are harder because what the service can return is always changing.

I think ideally I would have a way to get a modified DefaultHttpClient when running tests, that returns a hardcoded result for requests to a given URL instead of actually doing the network request. This way I would always get consistent results independently of the real web service's response.

I'm currently using Robotium for testing but I'm open to using other tools too.

答:
You might give Charles a try for something like this. Sorta a non-code solution.

http://www.charlesproxy.com/

I use the Charles' reverse proxies and the map local tool for things like this.

What you do is point your request at your local box on the reverse proxy port. Charles in turn can be configured to provide a static hard-coded flat file but to your app it looks like a 100% genuine web service response.

There are lots of other cool things you can do with Charles - watch traffic from your android app to and from your server and breakpoints (which allows you to tweak requests and responses before they are sent and received). Definitely worth checking out.


问:
Xamarin iOS Firebase Cloud Messaging - Push Notifications - can not send test message with device token
Xamarin iOS Firebase Cloud Messaging - Push Notifications. I am sending notification from:
I can send notification for android device ("send test message" from https://console.firebase.google.com)   and it works.
Android device token looks like:

```<code>dffplp_ekKY:APA91bEVk83i3ZAA-ZB7FQZ4nlwCCxhkMdEQIH4nOiuHI7nI50VZs4Ti4Gsm-gHxtwfb6OvkQSXNI0kls71Fch2bGT6nN3lIzmZ1x1uzizlTKO9PaEibUG02CR-dGVdu6vclid4l3aDY
</code>```

on iOS in AppDelegate.cs:

```<code>  public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
   {
        var thisToken = deviceToken.Description;
        var DeviceToken = Regex.Replace(deviceToken.ToString(), "[^0-9a-zA-Z]+", "");
   }
</code>```

thisToken is:

```<code><e24cad44 37d26c68 6c3defad f3685749 70c0180e 56526ae4 8ceb9253 e280d7a9>
</code>```

DeviceToken is:

```<code>e24cad4437d26c686c3defadf368574970c0180e56526ae48ceb9253e280d7a9
</code>```

Now I go to https://console.firebase.google.com and try to send test message via device token, but nothing appears on real device. When I send notification via Target -> bundleId  then it works perfectly on iOS.

I read this:
https://medium.com/@kevinle/correctly-capture-ios-13-device-token-in-xamarin-3d0fa390b71b but actually I am compiling against iOS SDK 12.1 and the real device is iOS 13.3 so new changes (weird device token) does not affect my code.

The question is: does console.firebase.google.com function "send test message" has problem when I try to send notification using formatted (only letters and numbers) device token on iOS (android is working good) or the token that I have is wrong formatted or invalid?

答:
I think that you should register token with this method</p>

```<code>[Export("messaging:didReceiveRegistrationToken:")]
public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
{
    // Monitor token generation: To be notified whenever the token is updated.
    Console.WriteLine("Received token: " + fcmToken);
    // Handle here how your app is storing token locally or send it to server
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}
</code>```

Body:
Xamarin iOS Firebase Cloud Messaging - Push Notifications. I am sending notification from:
I can send notification for android device ("send test message" from https://console.firebase.google.com)   and it works.
Android device token looks like:

dffplp_ekKY:APA91bEVk83i3ZAA-ZB7FQZ4nlwCCxhkMdEQIH4nOiuHI7nI50VZs4Ti4Gsm-gHxtwfb6OvkQSXNI0kls71Fch2bGT6nN3lIzmZ1x1uzizlTKO9PaEibUG02CR-dGVdu6vclid4l3aDY

on iOS in AppDelegate.cs:

  public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
   {
        var thisToken = deviceToken.Description;
        var DeviceToken = Regex.Replace(deviceToken.ToString(), "[^0-9a-zA-Z]+", "");
   }

thisToken is:

<e24cad44 37d26c68 6c3defad f3685749 70c0180e 56526ae4 8ceb9253 e280d7a9>

DeviceToken is:

e24cad4437d26c686c3defadf368574970c0180e56526ae48ceb9253e280d7a9

Now I go to https://console.firebase.google.com and try to send test message via device token, but nothing appears on real device. When I send notification via Target -> bundleId  then it works perfectly on iOS.

I read this:
https://medium.com/@kevinle/correctly-capture-ios-13-device-token-in-xamarin-3d0fa390b71b but actually I am compiling against iOS SDK 12.1 and the real device is iOS 13.3 so new changes (weird device token) does not affect my code.

The question is: does console.firebase.google.com function "send test message" has problem when I try to send notification using formatted (only letters and numbers) device token on iOS (android is working good) or the token that I have is wrong formatted or invalid?

Body:
I think that you should register token with this method

[Export("messaging:didReceiveRegistrationToken:")]
public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
{
    // Monitor token generation: To be notified whenever the token is updated.
    Console.WriteLine("Received token: " + fcmToken);
    // Handle here how your app is storing token locally or send it to server
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}


问:
How to get parts of a string via regular expressions in Kotlin or Java?
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.

In order to match strings I use regular expressions.

```<code>@Test
fun test() {
    val text = "http://server.com/s123456" // Source string.
    val reg = "^http://server.com/s\\d+\$".toRegex()
    assertEquals(true, reg.matches(text))

    // Try to split the string with findAll().
    val a: Sequence<MatchResult> = reg.findAll(text, 0)
    val names = a.map { it.groupValues[0] }.joinToString()
    println(names) // http://server.com/s123456
}
</code>```

But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?

Body:
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.

In order to match strings I use regular expressions.

@Test
fun test() {
    val text = "http://server.com/s123456" // Source string.
    val reg = "^http://server.com/s\\d+\$".toRegex()
    assertEquals(true, reg.matches(text))

    // Try to split the string with findAll().
    val a: Sequence<MatchResult> = reg.findAll(text, 0)
    val names = a.map { it.groupValues[0] }.joinToString()
    println(names) // http://server.com/s123456
}

But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?

Body:
You can try just (\d+)

Example (written in Python):

a = 'http://server.com/s123456'
b = 'http://server.com/s123456&a=100'
c = 'http://server.com/s122&&&'
d = 'http://server.com/s1234!56&a=100terere'
lis=[a,b,c,d]
for item in lis:
    print(re.findall(r'(\d+)', item ))

output

['123456']
['123456', '100']
['122']
['1234', '56', '100']