问:
Pandas table computation
I have a table as follows:

```<code>+-------+-------+-------------+
| Code  | Event | No. of runs |
+-------+-------+-------------+
|    66 |     1 |             |
|    66 |     1 |           2 |
|    66 |     2 |             |
|    66 |     2 |             |
|    66 |     2 |           3 |
|    66 |     3 |             |
|    66 |     3 |             |
|    66 |     3 |             |
|    66 |     3 |             |
|    66 |     3 |           5 |
|    70 |     1 |             |
|    70 |     1 |             |
|    70 |     1 |             |
|    70 |     1 |           4 |
+-------+-------+-------------+
</code>```

Let's call each row a run. I want to count the no. of runs in each Event, separately for each Code. Would I need to use the groupby function? I have added the expected output in the No. of runs column.

答:
Try using groupby with transfrom then mask duplicated rows:

```<code>df['Runs'] = df.groupby(['Code', 'Event'])['Event']\
               .transform('count')\
               .mask(df.duplicated(['Code','Event'], keep='last'), '')
</code>```

Output (add new column to output dataframe from comparison to desired result):

```<code>    Code     Event    No. of runs Runs
0      66      1
1      66      1             2     2
2      66      2
3      66      2
4      66      2             3     3
5      66      3
6      66      3
7      66      3
8      66      3
9      66      3             5     5
10     70      1
11     70      1
12     70      1
13     70      1             4     4
</code>```

Title: Pandas table computation

Body:
I have a table as follows:

+-------+-------+-------------+
| Code  | Event | No. of runs |
+-------+-------+-------------+
|    66 |     1 |             |
|    66 |     1 |           2 |
|    66 |     2 |             |
|    66 |     2 |             |
|    66 |     2 |           3 |
|    66 |     3 |             |
|    66 |     3 |             |
|    66 |     3 |             |
|    66 |     3 |             |
|    66 |     3 |           5 |
|    70 |     1 |             |
|    70 |     1 |             |
|    70 |     1 |             |
|    70 |     1 |           4 |
+-------+-------+-------------+

Let's call each row a run. I want to count the no. of runs in each Event, separately for each Code. Would I need to use the groupby function? I have added the expected output in the No. of runs column.

Body:
Try using groupby with transfrom then mask duplicated rows:

df['Runs'] = df.groupby(['Code', 'Event'])['Event']\
               .transform('count')\
               .mask(df.duplicated(['Code','Event'], keep='last'), '')

Output (add new column to output dataframe from comparison to desired result):

    Code     Event    No. of runs Runs
0      66      1
1      66      1             2     2
2      66      2
3      66      2
4      66      2             3     3
5      66      3
6      66      3
7      66      3
8      66      3
9      66      3             5     5
10     70      1
11     70      1
12     70      1
13     70      1             4     4


来源: stackexchange

问:
Python-docx module not overwriting same file name
I have been using python-docx to create and save .docx files automatically. It works to create a single uniquely named .docx file, but if I want to overwrite that file it doesn't do anything.

I have tried doing os.remove, or deleting the file before running my program again, and still nothing.

The only thing which allows it to work is to go into the Recycle Bin and delete it permanently.

def writeDocx():
    # os.remove(client+' Invoice.docx')
    ###heading at top###
    document.add_heading(client+" Invoice", 0)
    document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
    table = document.add_table(rows=1, cols=3)
    t = table.rows[0].cells
    t[0].text = 'TEST'
    t[1].text = 'TEST'
    t[2].text = 'TEST'
    for i in range(6):
        row_cells = table.add_row().cells
        row_cells[0].text = str(i)
        row_cells[1].text = str(i)
        row_cells[2].text = str(i)
    document.save(client+' Invoice.docx')
```

It should overwrite already saved  Invoice.docx file with the newly generated file, but it does not.

It shows no error messages.

答:
document.save(filename) will overwrite filename if it exists.

Your code does not show where document comes from, but the following should be enough to reproduce the behavior:

```<code>Document().save(filename)
</code>```

I suggest you do this with a literal, like "Client Invoice.docx", which takes the name formation out of the possible causes.

If it is still problematic, I would look at permissions, like the user running Python is able to both read and write the file, although I suppose that would raise an exception. The other thing to check is whether the file is being written to another directory; the default directory for a Python program is sometimes not the expected one.

You should study this document for help in refining your reproducible problem statement. Often following this process helps you see where you went wrong, but in any case, gives us more of what we need to go on to help you:

https://stackoverflow.com/help/minimal-reproducible-example

ContentLicense: CC BY-SA 4.0

Body:
I have been using python-docx to create and save .docx files automatically. It works to create a single uniquely named .docx file, but if I want to overwrite that file it doesn't do anything.

I have tried doing os.remove, or deleting the file before running my program again, and still nothing.

The only thing which allows it to work is to go into the Recycle Bin and delete it permanently.

def writeDocx():
    # os.remove(client+' Invoice.docx')
    ###heading at top###
    document.add_heading(client+" Invoice", 0)
    document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
    table = document.add_table(rows=1, cols=3)
    t = table.rows[0].cells
    t[0].text = 'TEST'
    t[1].text = 'TEST'
    t[2].text = 'TEST'
    for i in range(6):
        row_cells = table.add_row().cells
        row_cells[0].text = str(i)
        row_cells[1].text = str(i)
        row_cells[2].text = str(i)
    document.save(client+' Invoice.docx')

It should overwrite already saved  Invoice.docx file with the newly generated file, but it does not.

It shows no error messages.

Body:
document.save(filename) will overwrite filename if it exists.

Your code does not show where document comes from, but the following should be enough to reproduce the behavior:

Document().save(filename)

I suggest you do this with a literal, like "Client Invoice.docx", which takes the name formation out of the possible causes.

If it is still problematic, I would look at permissions, like the user running Python is able to both read and write the file, although I suppose that would raise an exception. The other thing to check is whether the file is being written to another directory; the default directory for a Python program is sometimes not the expected one.

You should study this document for help in refining your reproducible problem statement. Often following this process helps you see where you went wrong, but in any case, gives us more of what we need to go on to help you:

https://stackoverflow.com/help/minimal-reproducible-example


问:
Read specific value of an object
I'm using an api that return this object:

```<code>   {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }
</code>```

I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...

Thanks

答:
You can use Object.values to convert the object into an array. Use map to loop and get the value

var obj = {"0155894402285712":{"type":"GBUserFieldText","value":"A0242","name":"Codice+tessera"},"0155894402283800":{"type":"GBUserFieldText","value":"LZZMRN55L53C003Z","name":"Codice+Fiscale"}}

var resut = Object.values(obj).map(o => o.value);
console.log(resut);```
</div>
</div>
</p>

<p>If you want to match the name and value, you can use <code>reduce</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {"0155894402285712":{"type":"GBUserFieldText","value":"A0242","name":"Codice+tessera"},"0155894402283800":{"type":"GBUserFieldText","value":"LZZMRN55L53C003Z","name":"Codice+Fiscale"}}

var resut = Object.values(obj).reduce((c, v) => Object.assign(c, {[v.name]: v.value}), {});
console.log(resut);</code>```

Title: Read specific value of an object

Body:
I'm using an api that return this object:

   {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }

I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...

Thanks

Body:
You can use Object.values to convert the object into an array. Use map to loop and get the value

var obj = {"0155894402285712":{"type":"GBUserFieldText","value":"A0242","name":"Codice+tessera"},"0155894402283800":{"type":"GBUserFieldText","value":"LZZMRN55L53C003Z","name":"Codice+Fiscale"}}

var resut = Object.values(obj).map(o => o.value);
console.log(resut);

If you want to match the name and value, you can use reduce

var obj = {"0155894402285712":{"type":"GBUserFieldText","value":"A0242","name":"Codice+tessera"},"0155894402283800":{"type":"GBUserFieldText","value":"LZZMRN55L53C003Z","name":"Codice+Fiscale"}}

var resut = Object.values(obj).reduce((c, v) => Object.assign(c, {[v.name]: v.value}), {});
console.log(resut);


问:
Using Awk to find Unique chars bought by a customer
I have log files like this (it's only space between them but for readibility i changed that) :

```<code>Customer  Car             Bought
François  Nissan Pajero   28/05/2016
Matthew   Mercedes S      10/01/2019
Andrew    Peugeot 508     05/0/2000
Matthew   Toyota Hilux    02/10/2012
</code>```

I need to make an awk script which display for each customer what car he has bought like this :

```<code>Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
Francois, car bought: Nissan Pjero, number of cars: 1
</code>```

I'm not able to know how to do it.

I think i should create an array for Customer and one for the car and indexed it with the number of line

```<code>awk ' { Customer[NR]=$1; Car[NR]=$2} END {}'
</code>```

What should i add in the END, i'm little perplexed

I thought doing this also:

```<code>awk ' { Customer[$1]=$2} END { for (i in Customer) print i,Customer[i]}'
</code>```

The problem with this array, it will destroy the previous value of the car in the Customer indexed array.

答: For this data I would use Splunk.  It can analyze up to 500MB each day for free.  You can get whatever reports and graph anything you like.

Body:
I have log files like this (it's only space between them but for readibility i changed that) :

Customer  Car             Bought
François  Nissan Pajero   28/05/2016
Matthew   Mercedes S      10/01/2019
Andrew    Peugeot 508     05/0/2000
Matthew   Toyota Hilux    02/10/2012

I need to make an awk script which display for each customer what car he has bought like this :

Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
Francois, car bought: Nissan Pjero, number of cars: 1

I'm not able to know how to do it.

I think i should create an array for Customer and one for the car and indexed it with the number of line

awk ' { Customer[NR]=$1; Car[NR]=$2} END {}'

What should i add in the END, i'm little perplexed

I thought doing this also:

awk ' { Customer[$1]=$2} END { for (i in Customer) print i,Customer[i]}'

The problem with this array, it will destroy the previous value of the car in the Customer indexed array.


问:
Mongoose update not updating document
I'm trying to update documents in my MongoDB via Mongoose but for some reason the requested documents can not be found...

```<code>Call.update({_id: data.call._id}, { $set: { approved: value }}, function (error, response) {
    console.log(error);
    console.log(response);
    if (error) {
        callback(error, null);
    } else {
        callback(null, response);
    }
});
</code>```

data.call._id contains a valid document _id and approved is of type Number.

response outputs the following:

```<code>{ ok: 1, nModified: 0, n: 0, lastOp: { _bsontype: 'Timestamp', low_: 0, high_: 0 }, electionId: 56a92375bfb5c1abc4e825a7 }
</code>```

The document is never updated in the database... value will either be set to 1 or -1 depending on an earlier condition.

Model:

```<code>const callSchema = new Schema({
    start: Date,
    duration: String,
    callerNumber: String,
    callerNumberAreaCode: String,
    trackingNumber: String,
    destinationNumber: String,
    answered: String,
    customerId: String,
    approved: Number
}, { collection: 'calls'});

const Call = mongoose.model('Call', callSchema);
</code>```

答:
Hope this could help someone.

Make sure that your Scheme had a FIELD totally correct with your FIELD in $set clause.

For example:

if your updating is (set address field):

```<code>User.update({_id: mongoose.Types.ObjectId("<doc_id>")}, { $set: { address: "New York" }}, function (err, res) {
    if (err) {
        console.log("err:", err)
    } else {
        console.log("success with response:", res)
    }
})
</code>```

Your scheme needs to contain address field, such as:

```<code>let User = new mongoose.Scheme({
    name: String,
    address: String
})
</code>```

Thanks for reading.

ContentLicense: CC BY-SA 3.0

Title: Mongoose update not updating document

Body:
I'm trying to update documents in my MongoDB via Mongoose but for some reason the requested documents can not be found...

Call.update({_id: data.call._id}, { $set: { approved: value }}, function (error, response) {
    console.log(error);
    console.log(response);
    if (error) {
        callback(error, null);
    } else {
        callback(null, response);
    }
});

data.call._id contains a valid document _id and approved is of type Number.

response outputs the following:

{ ok: 1, nModified: 0, n: 0, lastOp: { _bsontype: 'Timestamp', low_: 0, high_: 0 }, electionId: 56a92375bfb5c1abc4e825a7 }

The document is never updated in the database... value will either be set to 1 or -1 depending on an earlier condition.

Model:

const callSchema = new Schema({
    start: Date,
    duration: String,
    callerNumber: String,
    callerNumberAreaCode: String,
    trackingNumber: String,
    destinationNumber: String,
    answered: String,
    customerId: String,
    approved: Number
}, { collection: 'calls'});

const Call = mongoose.model('Call', callSchema);

Body:
Hope this could help someone.

Make sure that your Scheme had a FIELD totally correct with your FIELD in $set clause.

For example:

if your updating is (set address field):

User.update({_id: mongoose.Types.ObjectId("<doc_id>")}, { $set: { address: "New York" }}, function (err, res) {
    if (err) {
        console.log("err:", err)
    } else {
        console.log("success with response:", res)
    }
})

Your scheme needs to contain address field, such as:

let User = new mongoose.Scheme({
    name: String,
    address: String
})

Thanks for reading.


问:
Quota exceeded for quota metric 'speech.googleapis.com/default_requests' not really understandable
I'm currently playing with a GCP service called API Speech-to-Text, using the NodeJS client library.
For that, I followed the quickstart documentation, trying to recognize a short local audio file (quite simply) first. However, I keep getting this error when I run node test_sample.js :

ERROR: { Error: Quota exceeded for quota metric 'speech.googleapis.com/default_requests' and limit 'DefaultRequestsPerMinutePerProject' of service 'speech.googleapis.com' for consumer 'project_number:764086051850'.
    at Http2CallStream.call.on (/Users/macOSuser/Projects/nodejs-speech/samples/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
    at Http2CallStream.emit (events.js:198:15)
    at Http2CallStream.endCall (/Users/macOSuser/Projects/nodejs-speech/samples/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
    at /Users/macOSuser/Projects/nodejs-speech/samples/node_modules/@grpc/grpc-js/build/src/call-stream.js:163:18
    at processTicksAndRejections (internal/process/task_queues.js:86:5)
```

Note : the mentioned project_number is not the same as mine

I have already tried to change my default gcloud project/account, as well as creating a brand new project and activating the API again.
I also checked on the GCP Console how were my request graphs, and yes they are empty

The sample code for quickstart can be found here

Thank you for your help on that

Edit solved : This was an authentification issue, which I solved using a service account's JSON key and refering by running export GOOGLE_APPLICATION_CREDENTIALS="/PATH-TO-FILE/key.json".
Thanks @JJ Geewax

答:
You noted that the project number isn't the same as the one you're seeing the error result, so that seems to be the bigger problem here... The Google Cloud client libraries get the project information and credentials from a few different places (with different priorities for each), so it's possible that you're accidentally picking up credentials and identity from the application defaults (possible the gcloud command-line tool). Can you update the question with the code you're running to get this error?

There are a few ways to fix an issue like this, but the easiest is probably to just run:
gcloud auth application-default login
in the command line (documentation).

Once you follow the authentication flow, you should end up with credentials for the intended project.

You also might want to take a look at the Getting Started with Authentication guide for GCP in Node.js which talks about creating a service account and setting those credentials using an environment variable.

Body:
I'm currently playing with a GCP service called API Speech-to-Text, using the NodeJS client library.
For that, I followed the quickstart documentation, trying to recognize a short local audio file (quite simply) first. However, I keep getting this error when I run node test_sample.js :

ERROR: { Error: Quota exceeded for quota metric 'speech.googleapis.com/default_requests' and limit 'DefaultRequestsPerMinutePerProject' of service 'speech.googleapis.com' for consumer 'project_number:764086051850'.
    at Http2CallStream.call.on (/Users/macOSuser/Projects/nodejs-speech/samples/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
    at Http2CallStream.emit (events.js:198:15)
    at Http2CallStream.endCall (/Users/macOSuser/Projects/nodejs-speech/samples/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
    at /Users/macOSuser/Projects/nodejs-speech/samples/node_modules/@grpc/grpc-js/build/src/call-stream.js:163:18
    at processTicksAndRejections (internal/process/task_queues.js:86:5)

Note : the mentioned project_number is not the same as mine

I have already tried to change my default gcloud project/account, as well as creating a brand new project and activating the API again.
I also checked on the GCP Console how were my request graphs, and yes they are empty

The sample code for quickstart can be found here

Thank you for your help on that

Edit solved : This was an authentification issue, which I solved using a service account's JSON key and refering by running export GOOGLE_APPLICATION_CREDENTIALS="/PATH-TO-FILE/key.json".
Thanks @JJ Geewax


问:
Animate Canvas from Vue
I am trying to implement this post, which draws and animates a stick figure, into Vue.

```<code>   draw(timestamp, wave) {
        if(Date.now() < (timestamp+900)) return requestAnimationFrame(this.draw);

        context.clearRect(0, 0, window.innerWidth, window.innerHeight);
        context.beginPath();
        context.fillStyle = "black"; // #000000
        context.arc(200, 50, 30, 0, Math.PI * 2, true);
        context.fill(); //fill the circle

        context.beginPath();
        context.lineWidth = 6;
        context.stroke();

        //body
        context.beginPath();
        context.moveTo(200, 80);
        context.lineTo(200, 180);
        context.strokeStyle = "black";
        context.stroke();

        //arms
        context.beginPath();
        context.strokeStyle = "black";
        context.moveTo(200, 100);
        context.lineTo(150, 130);
        if(wave) {
        context.moveTo(200, 100);
        context.lineTo(250, 130);
        wave = false;
        }
        else {
        context.moveTo(200, 100);
        context.lineTo(250, 70);
        wave = true;
        }
        context.stroke();

        //legs
        context.beginPath();
        context.strokeStyle = "black";
        context.moveTo(200, 180);
        context.lineTo(150, 280);
        context.moveTo(200, 180);
        context.lineTo(250, 280);
        context.stroke();
        timestamp = Date.now();
        requestAnimationFrame(this.draw);
    }
},
mounted: function () {
    var canvas = document.getElementById("canvas");
    context = canvas.getContext("2d"); // get Canvas Context object
    let timestamp = Date.now();
    let wave = false;

    this.draw(timestamp, wave);
}
</code>```

If I do the entire draw method inside of my mounted method, it works. But when I move draw to it's own method, as shown above, it fails.

I know it's failing because the line if(Date.now() < (timestamp+900)) is always returning false when running the code above. But I'm not sure why that's happening, or what the difference is.

How can I get this canvas to animate?

答:
Here's an example of how this might look in a component.

Vue.component('canvas-demo', {
    data: function () {
        return {
            timestamp: Date.now(),
            wave: false
        }
    },
    mounted: function(){
        this.startDrawing(this.$el.getContext("2d"));
    },
    template: '<canvas></canvas>',
    methods: {
        startDrawing: function(context) {
            var draw = () => {
                if (Date.now() < (this.timestamp + 900)) return requestAnimationFrame(draw);

                context.clearRect(0, 0, window.innerWidth, window.innerHeight);
                context.beginPath();
                context.fillStyle = "black"; // #000000
                context.arc(200, 50, 30, 0, Math.PI * 2, true);
                context.fill(); //fill the circle

                context.beginPath();
                context.lineWidth = 6;
                context.stroke();

                //body
                context.beginPath();
                context.moveTo(200, 80);
                context.lineTo(200, 180);
                context.strokeStyle = "black";
                context.stroke();

                //arms
                context.beginPath();
                context.strokeStyle = "black";
                context.moveTo(200, 100);
                context.lineTo(150, 130);
                if (this.wave) {
                    context.moveTo(200, 100);
                    context.lineTo(250, 130);
                    this.wave = false;
                }
                else {
                    context.moveTo(200, 100);
                    context.lineTo(250, 70);
                    this.wave = true;
                }
                context.stroke();

                //legs
                context.beginPath();
                context.strokeStyle = "black";
                context.moveTo(200, 180);
                context.lineTo(150, 280);
                context.moveTo(200, 180);
                context.lineTo(250, 280);
                context.stroke();
                this.timestamp = Date.now();
                requestAnimationFrame(draw);
            }

            draw();
        }
    }
});

new Vue({
    el: '#app'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <canvas-demo></canvas-demo>
</div></code>```

Title: Animate Canvas from Vue

Body:
I am trying to implement this post, which draws and animates a stick figure, into Vue.

   draw(timestamp, wave) {
        if(Date.now() < (timestamp+900)) return requestAnimationFrame(this.draw);

        context.clearRect(0, 0, window.innerWidth, window.innerHeight);
        context.beginPath();
        context.fillStyle = "black"; // #000000
        context.arc(200, 50, 30, 0, Math.PI * 2, true);
        context.fill(); //fill the circle

        context.beginPath();
        context.lineWidth = 6;
        context.stroke();

        //body
        context.beginPath();
        context.moveTo(200, 80);
        context.lineTo(200, 180);
        context.strokeStyle = "black";
        context.stroke();

        //arms
        context.beginPath();
        context.strokeStyle = "black";
        context.moveTo(200, 100);
        context.lineTo(150, 130);
        if(wave) {
        context.moveTo(200, 100);
        context.lineTo(250, 130);
        wave = false;
        }
        else {
        context.moveTo(200, 100);
        context.lineTo(250, 70);
        wave = true;
        }
        context.stroke();

        //legs
        context.beginPath();
        context.strokeStyle = "black";
        context.moveTo(200, 180);
        context.lineTo(150, 280);
        context.moveTo(200, 180);
        context.lineTo(250, 280);
        context.stroke();
        timestamp = Date.now();
        requestAnimationFrame(this.draw);
    }
},
mounted: function () {
    var canvas = document.getElementById("canvas");
    context = canvas.getContext("2d"); // get Canvas Context object
    let timestamp = Date.now();
    let wave = false;

    this.draw(timestamp, wave);
}

If I do the entire draw method inside of my mounted method, it works. But when I move draw to it's own method, as shown above, it fails.

I know it's failing because the line if(Date.now() < (timestamp+900)) is always returning false when running the code above. But I'm not sure why that's happening, or what the difference is.

How can I get this canvas to animate?

Body:
Here's an example of how this might look in a component.

Vue.component('canvas-demo', {
    data: function () {
        return {
            timestamp: Date.now(),
            wave: false
        }
    },
    mounted: function(){
        this.startDrawing(this.$el.getContext("2d"));
    },
    template: '<canvas></canvas>',
    methods: {
        startDrawing: function(context) {
            var draw = () => {
                if (Date.now() < (this.timestamp + 900)) return requestAnimationFrame(draw);

                context.clearRect(0, 0, window.innerWidth, window.innerHeight);
                context.beginPath();
                context.fillStyle = "black"; // #000000
                context.arc(200, 50, 30, 0, Math.PI * 2, true);
                context.fill(); //fill the circle

                context.beginPath();
                context.lineWidth = 6;
                context.stroke();

                //body
                context.beginPath();
                context.moveTo(200, 80);
                context.lineTo(200, 180);
                context.strokeStyle = "black";
                context.stroke();

                //arms
                context.beginPath();
                context.strokeStyle = "black";
                context.moveTo(200, 100);
                context.lineTo(150, 130);
                if (this.wave) {
                    context.moveTo(200, 100);
                    context.lineTo(250, 130);
                    this.wave = false;
                }
                else {
                    context.moveTo(200, 100);
                    context.lineTo(250, 70);
                    this.wave = true;
                }
                context.stroke();

                //legs
                context.beginPath();
                context.strokeStyle = "black";
                context.moveTo(200, 180);
                context.lineTo(150, 280);
                context.moveTo(200, 180);
                context.lineTo(250, 280);
                context.stroke();
                this.timestamp = Date.now();
                requestAnimationFrame(draw);
            }

            draw();
        }
    }
});

new Vue({
    el: '#app'
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <canvas-demo></canvas-demo>
</div>


问:
In nifi usgae of Evaluate jsonpath processor will it affect performance impact because of attribute creation
I'm trying to integrate nifi REST API's with my application. So by mapping input and output from my application, I am trying to call nifi REST api for flow creation. So, in my use case most of the times I will extract the JSON values and will apply expression languages.

So, for simplifying all the use-cases I am using evaluate JSONpath processor for fetching all attributes using jsonpath and apply expression language function on that in extract processor. Below is the flow diagram regarding that.

Is it the right approach because for JSON to JSON manipulation having 30 keys this is the simplest way, and as I am trying to integrate nifi REST API's with my application I cannot generate JOLT transformation logic dynamically based on the user mapping.

So, in this case, does the usage of evaluating JSONpath processor creates any performance issues for about 50 use case with different transformation logic because as I saw in documentation attribute usage creates performance(regarding memory) issues.

答:
Your concern about having too many attributes in memory should not be an issue here; having 30 attributes per flowfile is higher than usual, but if these are all strings between 0 - ~100-200 characters, there should be minimal impact. If you start trying to extract KB worth of data from the flowfile content to the attributes on each flowfile, you will see increased heap usage, but the framework should still be able to handle this until you reach very high throughput (1000's of flowfiles per second on commodity hardware like a modern laptop).

You may want to investigate ReplaceTextWithMapping, as that processor can load from a definition file and handle many replace operations using a single processor.

It is usually a flow design "smell" to have multiple copies of the same flow process with different configuration values (with the occasional exception of database interaction). Rather, see if there is a way you can genericize the process and populate the relevant values for each flowfile using variable population (from the incoming flowfile attributes, the variable registry, environment variables, etc.).


问:
free(): invalid pointer Aborted (core dumped)
I-m trying to run my python program it seems that it should run smoothly however I encounter an error that I haven't seen before it says:

```<code>free(): invalid pointer
Aborted (core dumped)
</code>```

However I'm not sure how to try and fix error since it doesn't give me too much information about the problem itself.

At first I thought it should be a problem with the sizes of the tensor in my network however they are completely fine. I've google the problem a little and found that I can see that is a problem with allocating memory where I shouldn't, but I don't know how to fix this problem

My code is divided in two different files, and I use two libraries to be able to use Sinkhorn loss function and make sample randomly a mesh.

import argparse
import point_cloud_utils as pcu
import time

import numpy as np
import torch
import torch.nn as nn
from fml.nn import SinkhornLoss

import common
def main():
    # x is a tensor of shape [n, 3] containing the positions of the vertices that
    x = torch._C.from_numpy(common.loadpointcloud("sphere.txt"))
    # t is a tensor of shape [n, 3] containing a set of nicely distributed samples in the unit cube
    v, f = common.unit_cube()
    t = torch._C.sample_mesh_lloyd(pcu.lloyd(v,f,x.shape[0]).astype(np.float32)) # sample randomly a point cloud (cube for now?)

    # The model is a simple fully connected network mapping a 3D parameter point to 3D
    phi = common.MLP(in_dim=3, out_dim=3)

    # Eps is 1/lambda and max_iters is the maximum number of Sinkhorn iterations to do
    emd_loss_fun = SinkhornLoss(eps=1e-3, max_iters=20,
                                stop_thresh=1e-3, return_transport_matrix=True)

    mse_loss_fun = torch.nn.MSELoss()

    # Adam optimizer at first
    optimizer = torch.optim.Adam(phi.parameters(), lr= 10e-3)

    fit_start_time = time.time()

    for epoch in range(100):
        optimizer.zero_grad()

        # Do the forward pass of the neural net, evaluating the function at the parametric points
        y = phi(t)

        # Compute the Sinkhorn divergence between the reconstruction*(using the francis library) and the target
        # NOTE: The Sinkhorn function expects a batch of b point sets (i.e. tensors of shape [b, n, 3])
        # since we only have 1, we unsqueeze so x and y have dimension [1, n, 3]
        with torch.no_grad():
            _, P = emd_loss_fun(phi(t).unsqueeze(0), x.unsqueeze(0))

        # Project the transport matrix onto the space of permutation matrices and compute the L-2 loss
        # between the permuted points
        loss = mse_loss_fun(y[P.squeeze().max(0)[1], :], x)
        # loss = mse_loss_fun(P.squeeze() @ y,  x)  # Use the transport matrix directly

        # Take an optimizer step
        loss.backward()
        optimizer.step()

        print("Epoch %d, loss = %f" % (epoch, loss.item()))

    fit_end_time = time.time()

    print("Total time = %f" % (fit_end_time - fit_start_time))
    # Plot the ground truth, reconstructed points, and a mesh representing the fitted function, phi
    common.visualitation(x,t,phi)

if __name__ == "__main__":
    main()
```

The error message is:
free(): invalid pointer
Aborted (core dumped)

That again doesn't help me that much. I'll appreciate it a lot if someone has any idea what is happening or if you know more about this error.

答:
Note for future readers: This bug was filed as issue #21018.

This is not a problem in your Python code. It is a bug in PyTorch (probably) or in Python itself (unlikely, but possible).

free(3) is a C function that releases dynamically allocated memory when it is no longer needed. You cannot (easily) call it from Python, because memory management is a low-level implementation detail normally handled by the Python interpreter. However, you are also using PyTorch, which is written in C++ and C, and does have the ability to directly allocate and free memory.

In this case, some C code has tried to release a block of memory, but the block of memory it tried to release was not dynamically allocated in the first place, which is an error. You should report this behavior to the PyTorch developers. Include as much detail as possible, including the shortest code you can find that reproduces the problem, and the complete output of that program.

Body:
I-m trying to run my python program it seems that it should run smoothly however I encounter an error that I haven't seen before it says:

free(): invalid pointer
Aborted (core dumped)

However I'm not sure how to try and fix error since it doesn't give me too much information about the problem itself.

At first I thought it should be a problem with the sizes of the tensor in my network however they are completely fine. I've google the problem a little and found that I can see that is a problem with allocating memory where I shouldn't, but I don't know how to fix this problem

My code is divided in two different files, and I use two libraries to be able to use Sinkhorn loss function and make sample randomly a mesh.

import argparse
import point_cloud_utils as pcu
import time

import numpy as np
import torch
import torch.nn as nn
from fml.nn import SinkhornLoss

import common
def main():
    # x is a tensor of shape [n, 3] containing the positions of the vertices that
    x = torch._C.from_numpy(common.loadpointcloud("sphere.txt"))
    # t is a tensor of shape [n, 3] containing a set of nicely distributed samples in the unit cube
    v, f = common.unit_cube()
    t = torch._C.sample_mesh_lloyd(pcu.lloyd(v,f,x.shape[0]).astype(np.float32)) # sample randomly a point cloud (cube for now?)

    # The model is a simple fully connected network mapping a 3D parameter point to 3D
    phi = common.MLP(in_dim=3, out_dim=3)

    # Eps is 1/lambda and max_iters is the maximum number of Sinkhorn iterations to do
    emd_loss_fun = SinkhornLoss(eps=1e-3, max_iters=20,
                                stop_thresh=1e-3, return_transport_matrix=True)

    mse_loss_fun = torch.nn.MSELoss()

    # Adam optimizer at first
    optimizer = torch.optim.Adam(phi.parameters(), lr= 10e-3)

    fit_start_time = time.time()

    for epoch in range(100):
        optimizer.zero_grad()

        # Do the forward pass of the neural net, evaluating the function at the parametric points
        y = phi(t)

        # Compute the Sinkhorn divergence between the reconstruction*(using the francis library) and the target
        # NOTE: The Sinkhorn function expects a batch of b point sets (i.e. tensors of shape [b, n, 3])
        # since we only have 1, we unsqueeze so x and y have dimension [1, n, 3]
        with torch.no_grad():
            _, P = emd_loss_fun(phi(t).unsqueeze(0), x.unsqueeze(0))

        # Project the transport matrix onto the space of permutation matrices and compute the L-2 loss
        # between the permuted points
        loss = mse_loss_fun(y[P.squeeze().max(0)[1], :], x)
        # loss = mse_loss_fun(P.squeeze() @ y,  x)  # Use the transport matrix directly

        # Take an optimizer step
        loss.backward()
        optimizer.step()

        print("Epoch %d, loss = %f" % (epoch, loss.item()))

    fit_end_time = time.time()

    print("Total time = %f" % (fit_end_time - fit_start_time))
    # Plot the ground truth, reconstructed points, and a mesh representing the fitted function, phi
    common.visualitation(x,t,phi)

if __name__ == "__main__":
    main()

The error message is:
free(): invalid pointer
Aborted (core dumped)

That again doesn't help me that much. I'll appreciate it a lot if someone has any idea what is happening or if you know more about this error.


问:
Proving basic arithmetic properties
Im trying the theorem proving tool of TLA+ to prove safety properties of an algorithm. But i found that TLAPS cant figure very "simple" mathematical facts.

My first problem was with:

```<code>EXTENDS Naturals
CONSTANTS x,y
ASSUME x \in Nat /\ y \in Nat
LEMMA x=y+1 => y<x
  OBVIOUS
</code>```

TLAPS cant do it alone with any backend prover. I also tried using specific backend provers with other tactics:

```<code>LEMMA x=y+1 => y<x
  BY IsaM("blast")
</code>```

But also failed. In similar way, other kind of simple facts cant be checked, for example:

```<code>LEMMA x<y => x<y+0
</code>```

I have used some of those backend theorem provers in the past, like the Z Solver or Isabelle, and from what i remember they are very powerful.  I think im missing something here... or i don't understand the TLAPS proof organizer or i still need to load some other module with axioms?.

答:
It seems you hit a bug in TLAPM -- at least in the development version on my machine. The reason is that the SMT translation does not pick up the second assumption. Without the domain restriction, none of the assertions should be provable. As a hot fix, I added the domain restrictions to the local lemma. I can now prove:

```<code>LEMMA ASSUME x \in Nat, y \in Nat
      PROVE x=y+1 => y < x BY SMT
</code>```

Another way to get around it for the moment is to have named assumptions which are invoked whenever needed:

```<code>ASSUME DOM == x \in Nat /\ y \in Nat
LEMMA x=y+1 => y < x BY SMT, DOM
</code>```

should go through. In both cases you have to add EXTENDS TLAPS at the beginning of your spec to enable the SMT keyword.

I will also report the bug to the maintainers.

Update: it seems that global assumptions are generally disregarded by TLAPM (afaik for performance reasons). The version with named assumptions is the preferred way to go.

Title: Proving basic arithmetic properties

Body:
Im trying the theorem proving tool of TLA+ to prove safety properties of an algorithm. But i found that TLAPS cant figure very "simple" mathematical facts.

My first problem was with:

EXTENDS Naturals
CONSTANTS x,y
ASSUME x \in Nat /\ y \in Nat
LEMMA x=y+1 => y<x
  OBVIOUS

TLAPS cant do it alone with any backend prover. I also tried using specific backend provers with other tactics:

LEMMA x=y+1 => y<x
  BY IsaM("blast")

But also failed. In similar way, other kind of simple facts cant be checked, for example:

LEMMA x<y => x<y+0

I have used some of those backend theorem provers in the past, like the Z Solver or Isabelle, and from what i remember they are very powerful.  I think im missing something here... or i don't understand the TLAPS proof organizer or i still need to load some other module with axioms?.

Body:
It seems you hit a bug in TLAPM -- at least in the development version on my machine. The reason is that the SMT translation does not pick up the second assumption. Without the domain restriction, none of the assertions should be provable. As a hot fix, I added the domain restrictions to the local lemma. I can now prove:

LEMMA ASSUME x \in Nat, y \in Nat
      PROVE x=y+1 => y < x BY SMT

Another way to get around it for the moment is to have named assumptions which are invoked whenever needed:

ASSUME DOM == x \in Nat /\ y \in Nat
LEMMA x=y+1 => y < x BY SMT, DOM

should go through. In both cases you have to add EXTENDS TLAPS at the beginning of your spec to enable the SMT keyword.

I will also report the bug to the maintainers.

Update: it seems that global assumptions are generally disregarded by TLAPM (afaik for performance reasons). The version with named assumptions is the preferred way to go.


问:
Windows Registry Key Check Fails in C#
I am doing a java installation + version check but the installation check is failing.

I tried changing JavaKey and when I added a key that includes a space in it, it fails and returns false.

        bool checkIfJavaInstalled()
        {
            string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
            bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
            return installed;
        }
```

I expect the result to be true but it returns false.

答:
For Java check I use this code. is64 to specify which registry I want to check. Currently I call CheckJavaIsInstalled two times :)

```<code>public static bool CheckJavaIsInstalled(TaskLoggingHelper log) {
  if (CheckJavaIsInstalled(log, false) || CheckJavaIsInstalled(log, true))
    return true;
</code>```

...

```<code>private static bool CheckJavaIsInstalled(TaskLoggingHelper log, bool is64) {

  try {
    using (var rk = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, is64 ? RegistryView.Registry64 : RegistryView.Registry32)) {
      using (var subKey = rk.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment")) {
        if (subKey == null)
          return false;
        string currentVerion = subKey.GetValue("CurrentVersion").ToString();
        float version;
        if (float.TryParse(currentVerion, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out version)) {
          if (version < 1.8f)
            log.LogMessage(MessageImportance.High, "Java version {0} older than 1.8", version);
        }
        else
          log.LogMessage(MessageImportance.High, "Failed parse Java version {0} ", currentVerion);

      }
    }
  }
  catch (Exception ex) {
    log.LogError("Java check failed");
    log.LogErrorFromException(ex);
    return false;
  }
  return true;
}
</code>```

Title: Windows Registry Key Check Fails in C#

Body:
I am doing a java installation + version check but the installation check is failing.

I tried changing JavaKey and when I added a key that includes a space in it, it fails and returns false.

        bool checkIfJavaInstalled()
        {
            string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
            bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
            return installed;
        }

I expect the result to be true but it returns false.

Body:
For Java check I use this code. is64 to specify which registry I want to check. Currently I call CheckJavaIsInstalled two times :)

public static bool CheckJavaIsInstalled(TaskLoggingHelper log) {
  if (CheckJavaIsInstalled(log, false) || CheckJavaIsInstalled(log, true))
    return true;

...

private static bool CheckJavaIsInstalled(TaskLoggingHelper log, bool is64) {

  try {
    using (var rk = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, is64 ? RegistryView.Registry64 : RegistryView.Registry32)) {
      using (var subKey = rk.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment")) {
        if (subKey == null)
          return false;
        string currentVerion = subKey.GetValue("CurrentVersion").ToString();
        float version;
        if (float.TryParse(currentVerion, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out version)) {
          if (version < 1.8f)
            log.LogMessage(MessageImportance.High, "Java version {0} older than 1.8", version);
        }
        else
          log.LogMessage(MessageImportance.High, "Failed parse Java version {0} ", currentVerion);

      }
    }
  }
  catch (Exception ex) {
    log.LogError("Java check failed");
    log.LogErrorFromException(ex);
    return false;
  }
  return true;
}


问:
How to merge pdfs(Alive PDF) in flex3?
My flex application generates individual pdf documents based on individual selection criterion,but i need to merge those generated pdfs or is it possible to store individual pdfs temporarily then  merge those into single pdf?</p>

答:
Wouldn't it be simpler to just store the data, and when comes the time to 'merge', have both datasets create your pdf?

I think that merging PDF documents together is out of AlivePDF's scope.  You might have to revert to a server side technology if you want to do it.

Title: How to merge pdfs(Alive PDF) in flex3?


问:
Filter a one to many relation record result
I need to filter the results given from a one to many relation directly from the model object, but I cant find the right way.
Here, the relations:

I have a User model that can subscript to many companies (company model), and a company can have many users subscripted to it, so, is a many to many relation.

In every company, this user has a personal info, so, every user, could have many profiles (profile model) one for each company that is subscripted to.
So It is a one to many relation.

Imagine I want to retrieve the company that a user is currently viewing directly from the model, this, Im achieving by filtering the many to many relation:

```<code>class User extends Authenticatable
{
///
 public function obtainLoggedOnCompany()
 {
   return $this->belongsToMany('app\Company', 'user_company', 'id', 'company_id')->withPivot('selected')->wherePivot('selected', 1)
 }
</code>```

Then, if I want to return the selected company in a blade view I just call:

Auth::user()->obtainLoggedOnCompany->first();

All thanks to the withPivot and wherePivot clause.

Different is the case when I want to retrieve the registered profile of a currently selected company, I tried:

```<code>public function obtainSelectedProfile()
{
$SelectedCompany= $this->obtainLoggedOnCompany->first();

return $this->hasMany('app\Profile','user_id')->where('company_id', '=', $SelectedCompany->company_id);
}
</code>```

But it throws a Trying to get property of non object Exception.
Is there another way to filter one to many relations directly in the model relation function?

Iam using Laravel 5.2

答:
How about you do:

I assume that your Company.php model has

```<code>public function userProfile(){
return $this->hasMany('app\Profile','company_id');
}
</code>```

And Try this on the controller:

```<code>    $company_id=1; //suppose the current company viewing id is 1
        $user = User::where('id',Auth::id())->with(['obtainLoggedOnCompany'=>function($query) use($company_id){
        $query->where('company_id',$company_id);
        $query->with(['company_user_profile'=>function($query){
         $query->where('user_id',Auth::id());
         $query->last();
        }]);
        //$query->last();
        }])->first();
</code>```

And you can fetch the profile using:

```<code>dd($user->obtainLoggedOnCompany->company_user_profile);
</code>```

Body:
I need to filter the results given from a one to many relation directly from the model object, but I cant find the right way.
Here, the relations:

I have a User model that can subscript to many companies (company model), and a company can have many users subscripted to it, so, is a many to many relation.

In every company, this user has a personal info, so, every user, could have many profiles (profile model) one for each company that is subscripted to.
So It is a one to many relation.

Imagine I want to retrieve the company that a user is currently viewing directly from the model, this, Im achieving by filtering the many to many relation:

class User extends Authenticatable
{
///
 public function obtainLoggedOnCompany()
 {
   return $this->belongsToMany('app\Company', 'user_company', 'id', 'company_id')->withPivot('selected')->wherePivot('selected', 1)
 }

Then, if I want to return the selected company in a blade view I just call:

Auth::user()->obtainLoggedOnCompany->first();

All thanks to the withPivot and wherePivot clause.

Different is the case when I want to retrieve the registered profile of a currently selected company, I tried:

public function obtainSelectedProfile()
{
$SelectedCompany= $this->obtainLoggedOnCompany->first();

return $this->hasMany('app\Profile','user_id')->where('company_id', '=', $SelectedCompany->company_id);
}

But it throws a Trying to get property of non object Exception.
Is there another way to filter one to many relations directly in the model relation function?

Iam using Laravel 5.2

Body:
How about you do:

I assume that your Company.php model has

public function userProfile(){
return $this->hasMany('app\Profile','company_id');
}

And Try this on the controller:

    $company_id=1; //suppose the current company viewing id is 1
        $user = User::where('id',Auth::id())->with(['obtainLoggedOnCompany'=>function($query) use($company_id){
        $query->where('company_id',$company_id);
        $query->with(['company_user_profile'=>function($query){
         $query->where('user_id',Auth::id());
         $query->last();
        }]);
        //$query->last();
        }])->first();

And you can fetch the profile using:

dd($user->obtainLoggedOnCompany->company_user_profile);


问:
SSRS 2012: "The report execution has expired or cannot be found. (rsExecutionNotFound)"
I am using SQL Server Reporting Services 2012 and received this error without any known cause: The report execution eqaiekfzmk2snc55y0zrow55 has expired or cannot be found. (rsExecutionNotFound).

While I have found other posts describing problem through Google searches, the resolutions did not help me:

Restarting SQL Server, SQL Server Agent, and SQL Server Reporting services

Increasing the Execution Timeout through SQL Server Management Studio when connected to the Reporting server

Adding rs:ClearSession to the URL querystring (and trying IE, Chrome, and Firefox)

Redeploying after each troubleshooting step and retesting

I looked in the Reporting Services log file folder C:\Program Files\Microsoft SQL Server\MSRS11.MSSQLSERVER\Reporting Services\LogFiles but I see the datestamp is over two months old and I could see nothing related to the symptom.

I looked looked in ExecutionLog3 and did not see anything related to the symptom.  use ReportServer; select * from ExecutionLog3;

To find out what did work, I verified that:

The query and results are sound, as seen in Management Studio

I can preview the report in Data Tools on the server

I can view the report when remoting into the server

I only see the error when viewing the page from outside the server.  This is a relatively lightweight query and result set, so I cannot believe that this problem has anything to do with execution timeouts.

I changed the name of the file and redeployed. I am able to see that report now, but this isn't a true resolution because I still don't know what is truly causing the problem and how to fix it. If the symptom appears again, I can't keep changing the filename and redeploy.

Is there a way to get a better idea of what is happening? A specific log file or a property I need to change?

Update:

I thought I had this problem worked out, but apparently not. I found nothing useful in the error logs: only a restatement of the same error message visible in the browser.  When I redeploy (using SQL Server Data Tools), the error goes away... for a few hours or until the next day, when I need to redeploy to make the error go away.

答:
For us, the error appeared trying to run a report on an SSRS 2016 server using Internet Explorer 11. The user had created a bookmark that linked directly to the report. What may have happened: IE preserves cookies and temporary internet files for favorites to "help them load faster". The user may have initially ran the report, then created the bookmark to the report which contained session information.

To fix: Delete the bookmark, then cleared browser history in IE (CTL+SHIFT+DEL) being sure to uncheck "Preserve Favorites website data".


问:
Array subset unequal sums
I have a requirement to write a function to divide an array in 2 parts {4,5,2,1,3}, such that sum in first array is greater than in second array but length of 1st array is smaller than that of second.The union of their sums is total sum and they dont have any intersection.So, an answer would be {4,5}.

```<code>import java.util.ArrayList;
import java.util.Stack;

public class DP2 {

    public static void main(String args[]) {
        int[] arr= {5,2,10,4,1,11};
        ArrayList<Integer> list=new ArrayList<>();
        //calculate sum
        int finalSum=0;
        /*
        for(int i: arr)
            finalSum+=arr[i];
            */
        int len=arr.length;
        int mid=(len)/2;
        System.out.println(mid);
        int sum=0;
        //initialize 2 pointers

        //will use a stack
        Stack<Integer> stack = new Stack<Integer>();

        int i=0,j=len-1;
        int max=Integer.MIN_VALUE;
        while(i < j ) {
            //int max=Math.max(arr[i], arr[j]);
        //  System.out.println(max);
            while(stack.size() < mid) {

                max=Math.max(arr[i], arr[j]);
                stack.push(max);
                //System.out.println(stack.size());
            //  System.out.println(stack.peek());
                i++;
                j--;
            }

        //  max=Math.max(arr[i], arr[j]);
            i++;
            j--;

            if(stack.size() < mid  && stack.peek() < max  ) {

                    stack.pop();
                    stack.push(max);

                }

        }

        while(!stack.isEmpty())
            System.out.println(stack.pop());

        }
    }
</code>```

It wont return the expected answer. It is not popping out from stack as I had coded to do. Can someone please help what I am doing wrong.

答:
From what I can see there is nothing wrong, everything works as expected. The only problem was that the popping operation was giving you the result in reverse order. I have fixed that in the code below:

```<code>Integer[] result = new Integer[stack.size()];
for (int i1 = result.length - 1; i1 >= 0 && !stack.isEmpty(); i1--) {
    result[i1] = stack.pop();
}
System.out.println(Arrays.toString(result));
</code>```

Output
[4, 5]

EDIT: As requested here is a full solution to your problem:

```<code>/**
 * Convert an array of primitive numbers to Integer objects.
 */
private static Integer[] intToInteger(int[] array) {
    return Arrays.stream(array).boxed().toArray( Integer[]::new );
}

/**
 * Converts a primitive integer array to an ArrayList.
 */
private static ArrayList<Integer> intArrayTolist(int[] array) {
    return new ArrayList<>(Arrays.asList(intToInteger(array)));
}

public static void main(String[] args) {

    int[] arr0 = { 5, 2, 10, 4, 1, 11 };

    /* determine the size of the first array */
    float quotient = (float)arr0.length / 2;
    int mid = (int) Math.floor(quotient);

    int size = quotient != mid ? mid : mid - 1;

    /* Initialize arrays here */
    Integer[] arr1 = new Integer[size];
    Integer[] arr2 = new Integer[arr0.length - mid];

    List<Integer> list = intArrayTolist(arr0);

    /* Populate the first array with largest values
     * found within the main array
     */
    for (int i = 0; i < size; i++) {
        /*
         * Find out the largest value in the main array
         * and add that value to the first array
         */
        arr1[i] = java.util.Collections.max(list);
        list.remove(arr1[i]);
    }

    arr2 = list.toArray(arr2);
    int sum = Arrays.stream(arr0).sum();

    System.out.println("First array: " + Arrays.toString(arr1));
    System.out.println("Second array: " + Arrays.toString(arr2));
    System.out.println("Sum of all numbers: " + sum);
}
</code>```

Output

```<code>First array: [11, 10]
Second array: [5, 2, 4, 1]
Sum of all numbers: 33
</code>```

Note that it might not be as elegant I would have hopped but it gets the job done. I will see if I can do some further cleaning and optimizing as I feel there is a lot of redundancies in there. It's just a quick mock up so you can have something that actually works.

Title: Array subset unequal sums

Body:
I have a requirement to write a function to divide an array in 2 parts {4,5,2,1,3}, such that sum in first array is greater than in second array but length of 1st array is smaller than that of second.The union of their sums is total sum and they dont have any intersection.So, an answer would be {4,5}.

import java.util.ArrayList;
import java.util.Stack;

public class DP2 {

    public static void main(String args[]) {
        int[] arr= {5,2,10,4,1,11};
        ArrayList<Integer> list=new ArrayList<>();
        //calculate sum
        int finalSum=0;
        /*
        for(int i: arr)
            finalSum+=arr[i];
            */
        int len=arr.length;
        int mid=(len)/2;
        System.out.println(mid);
        int sum=0;
        //initialize 2 pointers

        //will use a stack
        Stack<Integer> stack = new Stack<Integer>();

        int i=0,j=len-1;
        int max=Integer.MIN_VALUE;
        while(i < j ) {
            //int max=Math.max(arr[i], arr[j]);
        //  System.out.println(max);
            while(stack.size() < mid) {

                max=Math.max(arr[i], arr[j]);
                stack.push(max);
                //System.out.println(stack.size());
            //  System.out.println(stack.peek());
                i++;
                j--;
            }

        //  max=Math.max(arr[i], arr[j]);
            i++;
            j--;

            if(stack.size() < mid  && stack.peek() < max  ) {

                    stack.pop();
                    stack.push(max);

                }

        }

        while(!stack.isEmpty())
            System.out.println(stack.pop());

        }
    }

It wont return the expected answer. It is not popping out from stack as I had coded to do. Can someone please help what I am doing wrong.

Body:
From what I can see there is nothing wrong, everything works as expected. The only problem was that the popping operation was giving you the result in reverse order. I have fixed that in the code below:

Integer[] result = new Integer[stack.size()];
for (int i1 = result.length - 1; i1 >= 0 && !stack.isEmpty(); i1--) {
    result[i1] = stack.pop();
}
System.out.println(Arrays.toString(result));

Output
[4, 5]

EDIT: As requested here is a full solution to your problem:

/**
 * Convert an array of primitive numbers to Integer objects.
 */
private static Integer[] intToInteger(int[] array) {
    return Arrays.stream(array).boxed().toArray( Integer[]::new );
}

/**
 * Converts a primitive integer array to an ArrayList.
 */
private static ArrayList<Integer> intArrayTolist(int[] array) {
    return new ArrayList<>(Arrays.asList(intToInteger(array)));
}

public static void main(String[] args) {

    int[] arr0 = { 5, 2, 10, 4, 1, 11 };

    /* determine the size of the first array */
    float quotient = (float)arr0.length / 2;
    int mid = (int) Math.floor(quotient);

    int size = quotient != mid ? mid : mid - 1;

    /* Initialize arrays here */
    Integer[] arr1 = new Integer[size];
    Integer[] arr2 = new Integer[arr0.length - mid];

    List<Integer> list = intArrayTolist(arr0);

    /* Populate the first array with largest values
     * found within the main array
     */
    for (int i = 0; i < size; i++) {
        /*
         * Find out the largest value in the main array
         * and add that value to the first array
         */
        arr1[i] = java.util.Collections.max(list);
        list.remove(arr1[i]);
    }

    arr2 = list.toArray(arr2);
    int sum = Arrays.stream(arr0).sum();

    System.out.println("First array: " + Arrays.toString(arr1));
    System.out.println("Second array: " + Arrays.toString(arr2));
    System.out.println("Sum of all numbers: " + sum);
}

Output

First array: [11, 10]
Second array: [5, 2, 4, 1]
Sum of all numbers: 33

Note that it might not be as elegant I would have hopped but it gets the job done. I will see if I can do some further cleaning and optimizing as I feel there is a lot of redundancies in there. It's just a quick mock up so you can have something that actually works.


问:
Best way to represent single valued time events with gnuplot?
I have the following which is event data from an electronic sensor. In a nutshell, anytime the sensor has an event, it logs a value of 1 with the timestamp.  I can plot this with gnuplot via plot "/tmp/data" using 1:3 with points which gives a bunch of dots (at Y1) grouped at the time intervals. It seems like there could be a better way to represent this data. How would you do plot this?

2016-10-12 21:41:54 1
2016-10-12 21:42:00 1
2016-10-12 21:42:09 1
2016-10-12 21:42:14 1
2016-10-12 21:42:25 1
2016-10-12 21:42:31 1
2016-10-12 21:42:36 1
2016-10-12 21:42:41 1
2016-10-12 21:51:35 1
2016-10-12 21:51:41 1
2016-10-12 22:01:03 1

答:
Old question, I know, but I like the lollipop graphs, which you can emulate in gnuplot with impulse and point.

See: https://subscription.packtpub.com/book/big_data_and_business_intelligence/9781849517249/1/ch01lvl1sec24/making-an-impulse-plot

(It is toward the end of the article. The best looking lollipops I've seen are not multicolored like they have in the article, but you can search for examples of what matches your taste.)

Image from here: https://datavizproject.com/data-type/lollipop-chart/


问:
Converting graphs from a scanned document into data
I'm currently trying to write something that can extract data from some uncommon graphs in a book. I scanned the pages of the book, and by using opencv I would like to detect some features from the graphs in order to convert it into useable data. In the left graph I'm looking for the height of the "triangles" and in the right graph the distance from the center to the points where the dotted lines intersect with the gray area. In both cases I would like to convert these values into numeric data for further usage.

The first thing I thought of was detecting the lines of the charts, in the hopes I could somehow measure their length or position. For this I'm using the Hough Line Transform. The following snippet of code shows how far I've gotten already.

```<code>import numpy as np
import cv2

# Reading the image
img = cv2.imread('test2.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Apply edge detection
edges = cv2.Canny(gray,50,150,apertureSize = 3)

# Line detection
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=50,maxLineGap=20)

for line in lines:
    x1,y1,x2,y2 = line[0]
    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imwrite('linesDetected.jpg',img)
</code>```

The only problem is that this detection algorithm is not accurate at all. At least not for me. And in order to extract some data from the charts, the detection of the lines should be somewhat accurate. Is their any way I could do this? Or is my strategy to detect lines just wrong in the first place? Should I maybe start with detecting something else, like circles,object sizes, contours or colors?

答:
Using color segmentation is an easy way to convert this graph to data. This method does require some manual annotation. After the graph is segmented, count the pixels for each color. Check out the 'watershed' demo in the demo files that are included in the OpenCV library:

```<code>import numpy as np
import cv2 as cv
from common import Sketcher

class App:
    def __init__(self, fn):
        self.img = cv.imread(fn)
        self.img = cv.resize(self.img, (654,654))
        h, w = self.img.shape[:2]
        self.markers = np.zeros((h, w), np.int32)
        self.markers_vis = self.img.copy()
        self.cur_marker = 1
        self.colors = np.int32( list(np.ndindex(2, 2, 3)) ) * 123
        self.auto_update = True
        self.sketch = Sketcher('img', [self.markers_vis, self.markers], self.get_colors)

    def get_colors(self):
        return list(map(int, self.colors[self.cur_marker])), self.cur_marker

    def watershed(self):
        m = self.markers.copy()
        cv.watershed(self.img, m)
        cv.imshow('img', self.img)
        overlay = self.colors[np.maximum(m, 0)]
        vis = cv.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv.CV_8UC3)
        cv.imshow('overlay', np.array(overlay, np.uint8))
        cv.imwrite('/home/stephen/Desktop/overlay.png', np.array(overlay, np.uint8))
        cv.imshow('watershed', vis)

    def run(self):
        while cv.getWindowProperty('img', 0) != -1 or cv.getWindowProperty('watershed', 0) != -1:
            ch = cv.waitKey(50)
            if ch >= ord('1') and ch <= ord('9'):
                self.cur_marker = ch - ord('0')
                print('marker: ', self.cur_marker)
            if self.sketch.dirty and self.auto_update:
                self.watershed()
                self.sketch.dirty = False
            if ch == 27: break
        cv.destroyAllWindows()

fn = '/home/stephen/Desktop/test.png'
App(cv.samples.findFile(fn)).run()
</code>```

The output will be an image like this:

You can count the pixels for each color using this code:

```<code># Extract the values from the image
vals = []
img = cv.imread('/home/stephen/Desktop/overlay.png')
# Get the colors in the image
flat = img.reshape(-1, img.shape[-1])
colors = np.unique(flat, axis=0)
# Iterate through the colors (ignore the first and last colors)
for color in colors[1:-1]:
    a,b,c = color
    lower = a-1, b-1, c-1
    upper = a+1,b+1,c+1
    lower = np.array(lower)
    upper = np.array(upper)
    mask = cv.inRange(img, lower, upper)
    vals.append(sum(sum(mask)))
    cv.imshow('mask', mask)
    cv.waitKey(0)
cv.destroyAllWindows()
</code>```

And print out the output data using this code:

```<code>names = ['alcohol', 'esters', 'biter', 'hoppy', 'acid', 'zoetheid', 'mout']
print(list(zip(names, vals)))
</code>```

The output is:

```<code>[('alcohol', 22118), ('esters', 26000), ('biter', 16245), ('hoppy', 21170), ('acid', 19156), ('zoetheid', 11090), ('mout', 7167)]
</code>```

Body:
I'm currently trying to write something that can extract data from some uncommon graphs in a book. I scanned the pages of the book, and by using opencv I would like to detect some features from the graphs in order to convert it into useable data. In the left graph I'm looking for the height of the "triangles" and in the right graph the distance from the center to the points where the dotted lines intersect with the gray area. In both cases I would like to convert these values into numeric data for further usage.

The first thing I thought of was detecting the lines of the charts, in the hopes I could somehow measure their length or position. For this I'm using the Hough Line Transform. The following snippet of code shows how far I've gotten already.

import numpy as np
import cv2

# Reading the image
img = cv2.imread('test2.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Apply edge detection
edges = cv2.Canny(gray,50,150,apertureSize = 3)

# Line detection
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=50,maxLineGap=20)

for line in lines:
    x1,y1,x2,y2 = line[0]
    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imwrite('linesDetected.jpg',img)

The only problem is that this detection algorithm is not accurate at all. At least not for me. And in order to extract some data from the charts, the detection of the lines should be somewhat accurate. Is their any way I could do this? Or is my strategy to detect lines just wrong in the first place? Should I maybe start with detecting something else, like circles,object sizes, contours or colors?

Body:
Using color segmentation is an easy way to convert this graph to data. This method does require some manual annotation. After the graph is segmented, count the pixels for each color. Check out the 'watershed' demo in the demo files that are included in the OpenCV library:

import numpy as np
import cv2 as cv
from common import Sketcher

class App:
    def __init__(self, fn):
        self.img = cv.imread(fn)
        self.img = cv.resize(self.img, (654,654))
        h, w = self.img.shape[:2]
        self.markers = np.zeros((h, w), np.int32)
        self.markers_vis = self.img.copy()
        self.cur_marker = 1
        self.colors = np.int32( list(np.ndindex(2, 2, 3)) ) * 123
        self.auto_update = True
        self.sketch = Sketcher('img', [self.markers_vis, self.markers], self.get_colors)

    def get_colors(self):
        return list(map(int, self.colors[self.cur_marker])), self.cur_marker

    def watershed(self):
        m = self.markers.copy()
        cv.watershed(self.img, m)
        cv.imshow('img', self.img)
        overlay = self.colors[np.maximum(m, 0)]
        vis = cv.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv.CV_8UC3)
        cv.imshow('overlay', np.array(overlay, np.uint8))
        cv.imwrite('/home/stephen/Desktop/overlay.png', np.array(overlay, np.uint8))
        cv.imshow('watershed', vis)

    def run(self):
        while cv.getWindowProperty('img', 0) != -1 or cv.getWindowProperty('watershed', 0) != -1:
            ch = cv.waitKey(50)
            if ch >= ord('1') and ch <= ord('9'):
                self.cur_marker = ch - ord('0')
                print('marker: ', self.cur_marker)
            if self.sketch.dirty and self.auto_update:
                self.watershed()
                self.sketch.dirty = False
            if ch == 27: break
        cv.destroyAllWindows()

fn = '/home/stephen/Desktop/test.png'
App(cv.samples.findFile(fn)).run()

The output will be an image like this:

You can count the pixels for each color using this code:

# Extract the values from the image
vals = []
img = cv.imread('/home/stephen/Desktop/overlay.png')
# Get the colors in the image
flat = img.reshape(-1, img.shape[-1])
colors = np.unique(flat, axis=0)
# Iterate through the colors (ignore the first and last colors)
for color in colors[1:-1]:
    a,b,c = color
    lower = a-1, b-1, c-1
    upper = a+1,b+1,c+1
    lower = np.array(lower)
    upper = np.array(upper)
    mask = cv.inRange(img, lower, upper)
    vals.append(sum(sum(mask)))
    cv.imshow('mask', mask)
    cv.waitKey(0)
cv.destroyAllWindows()

And print out the output data using this code:

names = ['alcohol', 'esters', 'biter', 'hoppy', 'acid', 'zoetheid', 'mout']
print(list(zip(names, vals)))

The output is:

[('alcohol', 22118), ('esters', 26000), ('biter', 16245), ('hoppy', 21170), ('acid', 19156), ('zoetheid', 11090), ('mout', 7167)]


问:
Use "perl6" command with Git Bash on windows
Using Windows, I installed Rakudo Star and Git and ensured that C:\rakudo\bin and C:\rakudo\share\perl6\site\bin are in my Path environment variable.

Now, typing perl6 inside Git Bash afterwards gives the command not found error, while the command does work inside powershell and cmd. Typing echo $PATH inside Git Bash confirms again that the folders above are in my path variable here as well.

How can I get the perl6 command working inside Git Bash?

Note: Using moar (moar.exe) which resides in the same folder as perl6 works as well in Git Bash. Also hitting Tab show the autocomplete suggestion for moar, it does not do that for perl6.

答:
I tried to install perl6 from the link you provided and I can confirm the same behavior on Cygwin on Windows 10.

If I type in the Cygwin terminal window:

```<code>$ perl6
-bash: perl6: command not found
$ echo  $PATH
/usr/local/bin:/usr/bin:/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS:/cygdrive/c/WINDOWS/System32/Wbem:/cygdrive/c/WINDOWS/System32/WindowsPowerShell/v1.0:/cygdrive/c/WINDOWS/System32/OpenSSH:/cygdrive/c/Users/Bruker/AppData/Local/Microsoft/WindowsApps:/cygdrive/c/rakudo/bin:/cygdrive/c/rakudo/share/perl6/site/bin
$ cd /cygdrive/c/rakudo/bin
$ ls -l
-rwxrwx---+ 1 SYSTEM SYSTEM  930663 May 11  2017 libgcc_s_seh-1.dll
-rwxrwx---+ 1 SYSTEM SYSTEM  136146 Mar 30 20:55 libmoar.dll.a
-rwxrwx---+ 1 SYSTEM SYSTEM   56978 May 11  2017 libwinpthread-1.dll
-rwxrwx---+ 1 SYSTEM SYSTEM 7021172 Mar 30 20:55 moar.dll
-rwxrwx---+ 1 SYSTEM SYSTEM   64066 Mar 30 20:55 moar.exe
-rwxrwx---+ 1 SYSTEM SYSTEM     126 Mar 30 20:56 nqp.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     126 Mar 30 20:56 nqp-m.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     242 Mar 30 20:56 perl6.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     248 Mar 30 20:56 perl6-debug-m.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     242 Mar 30 20:56 perl6-m.bat
$ cat perl6.bat
@ "C:\rakudo\bin\moar" --execname="%~dpf0" --libpath="C:\rakudo\share\nqp\lib" --libpath="C:\rakudo\share\nqp\lib" --libpath="C:\rakudo\share/perl6/lib" --libpath="C:\rakudo\share/perl6/runtime" C:\rakudo\share\perl6\runtime\perl6.moarvm %*
</code>```

Notice that the paths in the bat file are not cygwin paths. So that might explain why it does not work..

For example:

```<code>$ "C:\rakudo\bin\moar"
-bash: C:\rakudo\bin\moar: command not found
$  /cygdrive/c/rakudo/bin/moar
ERROR: Missing input file.

USAGE: moar [--crash] [--libpath=...] input.moarvm [program args]
       moar --dump input.moarvm
       moar --help
[...]
</code>```

Update:

I also tried install Git Bash, and then from the MINGW64 terminal window:

```<code>$ echo $PATH
/c/Users/Bruker/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:/c/Users/Bruker/bin:/c/WINDOWS/system32:/c/WINDOWS:/c/WINDOWS/System32/Wbem:/c/WINDOWS/System32/WindowsPowerShell/v1.0:/c/WINDOWS/System32/OpenSSH:/c/Users/Bruker/AppData/Local/Microsoft/WindowsApps:/usr/bin/vendor_perl:/usr/bin/core_perl
$ PATH=/c/rakudo/bin:$PATH
$ perl6
bash: perl6: command not found
$ moar
ERROR: Missing input file.
USAGE: moar [--crash] [--libpath=...] input.moarvm [program args]
       moar --dump input.moarvm
       moar --help
[...]
</code>```

Note that moar is an .exe file while perl6 is a .bat file.

Also it seems perl6 is not "offical" for Cygwin yet according to this issue.

Body:
I tried to install perl6 from the link you provided and I can confirm the same behavior on Cygwin on Windows 10.

If I type in the Cygwin terminal window:

$ perl6
-bash: perl6: command not found
$ echo  $PATH
/usr/local/bin:/usr/bin:/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS:/cygdrive/c/WINDOWS/System32/Wbem:/cygdrive/c/WINDOWS/System32/WindowsPowerShell/v1.0:/cygdrive/c/WINDOWS/System32/OpenSSH:/cygdrive/c/Users/Bruker/AppData/Local/Microsoft/WindowsApps:/cygdrive/c/rakudo/bin:/cygdrive/c/rakudo/share/perl6/site/bin
$ cd /cygdrive/c/rakudo/bin
$ ls -l
-rwxrwx---+ 1 SYSTEM SYSTEM  930663 May 11  2017 libgcc_s_seh-1.dll
-rwxrwx---+ 1 SYSTEM SYSTEM  136146 Mar 30 20:55 libmoar.dll.a
-rwxrwx---+ 1 SYSTEM SYSTEM   56978 May 11  2017 libwinpthread-1.dll
-rwxrwx---+ 1 SYSTEM SYSTEM 7021172 Mar 30 20:55 moar.dll
-rwxrwx---+ 1 SYSTEM SYSTEM   64066 Mar 30 20:55 moar.exe
-rwxrwx---+ 1 SYSTEM SYSTEM     126 Mar 30 20:56 nqp.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     126 Mar 30 20:56 nqp-m.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     242 Mar 30 20:56 perl6.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     248 Mar 30 20:56 perl6-debug-m.bat
-rwxrwx---+ 1 SYSTEM SYSTEM     242 Mar 30 20:56 perl6-m.bat
$ cat perl6.bat
@ "C:\rakudo\bin\moar" --execname="%~dpf0" --libpath="C:\rakudo\share\nqp\lib" --libpath="C:\rakudo\share\nqp\lib" --libpath="C:\rakudo\share/perl6/lib" --libpath="C:\rakudo\share/perl6/runtime" C:\rakudo\share\perl6\runtime\perl6.moarvm %*

Notice that the paths in the bat file are not cygwin paths. So that might explain why it does not work..

For example:

$ "C:\rakudo\bin\moar"
-bash: C:\rakudo\bin\moar: command not found
$  /cygdrive/c/rakudo/bin/moar
ERROR: Missing input file.

USAGE: moar [--crash] [--libpath=...] input.moarvm [program args]
       moar --dump input.moarvm
       moar --help
[...]

Update:

I also tried install Git Bash, and then from the MINGW64 terminal window:

$ echo $PATH
/c/Users/Bruker/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:/c/Users/Bruker/bin:/c/WINDOWS/system32:/c/WINDOWS:/c/WINDOWS/System32/Wbem:/c/WINDOWS/System32/WindowsPowerShell/v1.0:/c/WINDOWS/System32/OpenSSH:/c/Users/Bruker/AppData/Local/Microsoft/WindowsApps:/usr/bin/vendor_perl:/usr/bin/core_perl
$ PATH=/c/rakudo/bin:$PATH
$ perl6
bash: perl6: command not found
$ moar
ERROR: Missing input file.
USAGE: moar [--crash] [--libpath=...] input.moarvm [program args]
       moar --dump input.moarvm
       moar --help
[...]

Note that moar is an .exe file while perl6 is a .bat file.

Also it seems perl6 is not "offical" for Cygwin yet according to this issue.


问:
Selecting from a database from Today onwards
Im trying to select a bunch of stuff from a database. Each have a date and i'd like to only display the ones whose date is equal to today onwards.

$sql="SELECT * FROM bs_events WHERE NOW() ORDER BY eventDate ";

I have tried looking everywhere and cannot find anything.

Thanks for any help guys

答:
I think you want

where EventDate >= now()


问:
Dealing with floating point inaccuracy
With regex I created a program that solves mathematical expressions. It works perfectly fine, except for expressions such as these: (123.45*(678.90 / (-2.5+ 11.5)-(((80 -(19))) *33.25)) / 20) - (123.45*(678.90 / (-2.5+ 11.5)-(((80 -(19))) *33.25)) / 20) + (13 - 2)/ -(-11)".

My program solves the problem in the following steps:

The result should be exactly 1 but is slightly larger. My program loops until there is one single number in the correct format. I guess I can rewrite the regex so it accepts numbers in scientific format, but still, this would return the wrong answer. How do I deal with this?
My program uses following line:

```<code>while (!Regex.IsMatch(expression, @"\A([+-]?[0-9]*(?:\.[0-9]*)?)\Z"))
</code>```

答: I think you should just switch to Decimals instead of using floating points since, by definition, floating point numbers accurately represent only fractions that have a power of 2 in the denominator while Decimals don't have this specific problem.</p>

Title: Dealing with floating point inaccuracy

Body:
With regex I created a program that solves mathematical expressions. It works perfectly fine, except for expressions such as these: (123.45*(678.90 / (-2.5+ 11.5)-(((80 -(19))) *33.25)) / 20) - (123.45*(678.90 / (-2.5+ 11.5)-(((80 -(19))) *33.25)) / 20) + (13 - 2)/ -(-11)".

My program solves the problem in the following steps:

The result should be exactly 1 but is slightly larger. My program loops until there is one single number in the correct format. I guess I can rewrite the regex so it accepts numbers in scientific format, but still, this would return the wrong answer. How do I deal with this?
My program uses following line:

while (!Regex.IsMatch(expression, @"\A([+-]?[0-9]*(?:\.[0-9]*)?)\Z"))


问:
How to imshow a transparent image with background over background image
i want plot streeing wheel rotating on an instrument board image, to car streeing wheel simulation.

Making the background of the handle transparent has already been successful and i was try imshow image on the instrument board image using [hold on].

```<code>I = imread('audi_steering.PNG');
for i =1:10

    IY= imread('2016_Audi_A6_30T_instrument_cluster.png');
    imshow(IY);
    hold on;
    I_a=imrotate(I,i,'crop');
    h=imshow(I_a);

    alphadata = I_a<200;
    set(h,'AlphaData',alphadata(:,:,1));

end
</code>```

Instead of rotating only the steering wheel drawn on the dashboard image, the dashboard image of the area where the steering wheel were drawn was also partially rotated.

image is like under link.(i can not upload image...)
https://drive.google.com/file/d/1Q5AKEhYs-kwL-diZc3SRmSqlOz3N4mlL/view?usp=sharing

答:
Don't use set(h,'AlphaData'... with imshow I think it's meant to be used with graphs, not images.

You better change the RGB pixel values of the image, and display the modified image.

The following code sample copy image IY into temporary image J, then copy the elements from I_a where alphadata = 0.

Remark: the code works only if IY and I_a have the same size and dimensions.

```<code>IY = imread('2016_Audi_A6_30T_instrument_cluster.png');

for i = 1:10
    I_a = imrotate(I, i, 'crop');
    alphadata = I_a < 200;
    J = IY; %Copy IY to temporary image J
    J(~alphadata) = I_a(~alphadata); %Replace elements in J where alphadata = 0
    imshow(J);
    pause(1); %Pause between loops
end
</code>```

Body:
i want plot streeing wheel rotating on an instrument board image, to car streeing wheel simulation.

Making the background of the handle transparent has already been successful and i was try imshow image on the instrument board image using [hold on].

I = imread('audi_steering.PNG');
for i =1:10

    IY= imread('2016_Audi_A6_30T_instrument_cluster.png');
    imshow(IY);
    hold on;
    I_a=imrotate(I,i,'crop');
    h=imshow(I_a);

    alphadata = I_a<200;
    set(h,'AlphaData',alphadata(:,:,1));

end

Instead of rotating only the steering wheel drawn on the dashboard image, the dashboard image of the area where the steering wheel were drawn was also partially rotated.

image is like under link.(i can not upload image...)
https://drive.google.com/file/d/1Q5AKEhYs-kwL-diZc3SRmSqlOz3N4mlL/view?usp=sharing

Body:
Don't use set(h,'AlphaData'... with imshow I think it's meant to be used with graphs, not images.

You better change the RGB pixel values of the image, and display the modified image.

The following code sample copy image IY into temporary image J, then copy the elements from I_a where alphadata = 0.

Remark: the code works only if IY and I_a have the same size and dimensions.

IY = imread('2016_Audi_A6_30T_instrument_cluster.png');

for i = 1:10
    I_a = imrotate(I, i, 'crop');
    alphadata = I_a < 200;
    J = IY; %Copy IY to temporary image J
    J(~alphadata) = I_a(~alphadata); %Replace elements in J where alphadata = 0
    imshow(J);
    pause(1); %Pause between loops
end


问:
Search a value from another tab/sheet in google sheets based on cell reference
I'm trying to create a search page in google sheets where the user enters a value in one cell(s) and then other cells auto-populate with values from another tab/sheet based on the value entered in the search cell(s).

I'm trying to use VLOOKUP up in an array but it gives either error or N/A.

I have 'sheet1' with data from a google forms (columns from A to BN) and I'm trying to make a search page in 'Sheet2' where on top the user can write for example the ID-number, and I want to grab the value of a column from 'sheet1' that matches the ID-number written on the same row for 'sheet1'.

I've already checked:

VLOOKUP to the left from another sheet in Google Sheets

How to get value depending on list selection in spreadsheet?

Google sheets - VLOOKUP inside ARRAYFORMULA

There are others but I'm not looking for any scripts.

In simple form the formula would be:

```<code>=VLOOKUP(B3,'sheet1'!A:BN,40,False)
</code>```

But because I have too many columns and I'll be needing to grab other values too I'm using:

```<code>=ArrayFormula(IF(LEN(B3),VLOOKUP(B3,{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")},FALSE),""))
</code>```

Explanation:

B3 is the cell where the user inputs the id number value

Then ...:

```<code>{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")}
</code>```

is where I'm looking for the number of the column of the title of value I'm looking for, in this case, it is AN, which would be the column 40 but it could be any other.

And then the ArrayFormula is because sheet1 is data from a Google form that is on use and increasing rows constantly.

It gives me an error of #N/A because it doesn't find the value (input in B3 in sheet 2) in the range (tab sheet1 in all the columns from A to BN that have values)

Example sheet with working answer is [here]:
 (https://docs.google.com/spreadsheets/d/1qLcJdCn4EdV7lPOAfZ_CMak1LBkve45FL5SXyqBV3L8/edit?usp=sharing)

NOTE: The values to search/return are on the same row in sheet 1 and when a new search is entered then only the row changes.

答:
```<code>=ARRAYFORMULA(
 IF(B3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(B3,            data!A:E,  {1,2,3,5}, 0)), CHAR(10))), "♦", ),
 IF(C3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(C3, {data!C:C, data!A:E}, {2,3,4,6}, 0)), CHAR(10))), "♦", ),
 IF(D3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(D3, {data!E:E, data!A:E}, {2,3,4,6}, 0)), CHAR(10))), "♦", ), ))))
</code>```

UPDATE:

```<code>=IFERROR(ARRAYFORMULA(
 IF(B3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(B3, {data!AN:AN, data!A:BN},  {41,38,19,11,55}, 0)), CHAR(10))), "♦", ),
 IF(C3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(C3, {data!AK:AK, data!A:BN}, {41,38,19,11,55}, 0)), CHAR(10))), "♦", ),
 IF(E3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(E3, {data!BJ:BJ, data!A:BN}, {41,38,19,11,55}, 0)), CHAR(10))), "♦", ),
 IF(D3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(D3, {data!R:R, data!A:BN}, {41,38,19,11,55}, 0)), CHAR(10))), "♦", ), ))))), "no match found")
</code>```

Body:
I'm trying to create a search page in google sheets where the user enters a value in one cell(s) and then other cells auto-populate with values from another tab/sheet based on the value entered in the search cell(s).

I'm trying to use VLOOKUP up in an array but it gives either error or N/A.

I have 'sheet1' with data from a google forms (columns from A to BN) and I'm trying to make a search page in 'Sheet2' where on top the user can write for example the ID-number, and I want to grab the value of a column from 'sheet1' that matches the ID-number written on the same row for 'sheet1'.

I've already checked:

VLOOKUP to the left from another sheet in Google Sheets

How to get value depending on list selection in spreadsheet?

Google sheets - VLOOKUP inside ARRAYFORMULA

There are others but I'm not looking for any scripts.

In simple form the formula would be:

=VLOOKUP(B3,'sheet1'!A:BN,40,False)

But because I have too many columns and I'll be needing to grab other values too I'm using:

=ArrayFormula(IF(LEN(B3),VLOOKUP(B3,{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")},FALSE),""))

Explanation:

B3 is the cell where the user inputs the id number value

Then ...:

{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")}

is where I'm looking for the number of the column of the title of value I'm looking for, in this case, it is AN, which would be the column 40 but it could be any other.

And then the ArrayFormula is because sheet1 is data from a Google form that is on use and increasing rows constantly.

It gives me an error of #N/A because it doesn't find the value (input in B3 in sheet 2) in the range (tab sheet1 in all the columns from A to BN that have values)

Example sheet with working answer is [here]:
 (https://docs.google.com/spreadsheets/d/1qLcJdCn4EdV7lPOAfZ_CMak1LBkve45FL5SXyqBV3L8/edit?usp=sharing)

NOTE: The values to search/return are on the same row in sheet 1 and when a new search is entered then only the row changes.

Body:
=ARRAYFORMULA(
 IF(B3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(B3,            data!A:E,  {1,2,3,5}, 0)), CHAR(10))), "♦", ),
 IF(C3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(C3, {data!C:C, data!A:E}, {2,3,4,6}, 0)), CHAR(10))), "♦", ),
 IF(D3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(D3, {data!E:E, data!A:E}, {2,3,4,6}, 0)), CHAR(10))), "♦", ), ))))

UPDATE:

=IFERROR(ARRAYFORMULA(
 IF(B3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(B3, {data!AN:AN, data!A:BN},  {41,38,19,11,55}, 0)), CHAR(10))), "♦", ),
 IF(C3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(C3, {data!AK:AK, data!A:BN}, {41,38,19,11,55}, 0)), CHAR(10))), "♦", ),
 IF(E3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(E3, {data!BJ:BJ, data!A:BN}, {41,38,19,11,55}, 0)), CHAR(10))), "♦", ),
 IF(D3<>"", SUBSTITUTE(TRANSPOSE(SPLIT(TEXTJOIN(CHAR(10)&"♦"&CHAR(10)&"♦", 1,
            VLOOKUP(D3, {data!R:R, data!A:BN}, {41,38,19,11,55}, 0)), CHAR(10))), "♦", ), ))))), "no match found")


问:
Slicing a string from end to begining
I am trying to perform palindromic slicing on a string and comparing the forward version of a string vs to the backward version of the string

```<code>string = "nitin"
i = 0
j = len(string)

while i<j:
    if string[i:j] == string[j-1:i-1:-1]:
        print("".join(string[i:j]))
    i +=1
    j-=1
</code>```

but I found the string[end:start-1:-1] method doesn't accept a parameter such as string[4:-1:-1]. I understand why (because index -1 is the same as the start of the string) but I don't know how to overcome this problem using list slicing in combination with my method.

(I mean I could shorten the string each time but I'd rather be able to solve my problem using list slicing if possible) as below:

```<code>string = "nitin"
i = 0
j = len(string)

while i+1<j:
    string=string[i:j]
    if string == string[::-1]:
        print(string)
    i +=1
    j-=1
</code>```

Any ideas?
Thanks

EDIT
I want every possible sub-palindromic sequence
(e.g: nitin would give nitin, iti)

答:
You can use recursion to get all sub palindromic. The result is a set in order to remove all duplicate sub palindromic.

```<code>def sub_palindromic(s):
    if len(s) <= 1:
        return set()
    elif len(s) == 2:
        if s[::-1] == s:
            return set([s])
        else:
            return set()
    else:
        if s[::-1] == s:
            return set([s]) | sub_palindromic(s[1:]) | sub_palindromic(s[:-1])
        else:
            return sub_palindromic(s[1:]) | sub_palindromic(s[:-1]) | sub_palindromic(s[:2]) | sub_palindromic(s[-2:])

sub_palindromic('nitin') # {'nitin', 'iti'}
sub_palindromic('abca') # set()
sub_palindromic('abab') # {'bab', 'aba'}
sub_palindromic('abba') # {'abba', 'bb'}
sub_palindromic("aaaaa") # {'aa', 'aaa', 'aaaa', 'aaaaa'}
sub_palindromic('abcbacab') # {'abcba', 'aca', 'bacab', 'bcb'}
sub_palindromic("1122bb2211") # {'11', '1122bb2211', '122bb221', '22', '22bb22', '2bb2', 'bb'}

</code>```

Title: Slicing a string from end to begining

Body:
I am trying to perform palindromic slicing on a string and comparing the forward version of a string vs to the backward version of the string

string = "nitin"
i = 0
j = len(string)

while i<j:
    if string[i:j] == string[j-1:i-1:-1]:
        print("".join(string[i:j]))
    i +=1
    j-=1

but I found the string[end:start-1:-1] method doesn't accept a parameter such as string[4:-1:-1]. I understand why (because index -1 is the same as the start of the string) but I don't know how to overcome this problem using list slicing in combination with my method.

(I mean I could shorten the string each time but I'd rather be able to solve my problem using list slicing if possible) as below:

string = "nitin"
i = 0
j = len(string)

while i+1<j:
    string=string[i:j]
    if string == string[::-1]:
        print(string)
    i +=1
    j-=1

Any ideas?
Thanks

EDIT
I want every possible sub-palindromic sequence
(e.g: nitin would give nitin, iti)

Body:
You can use recursion to get all sub palindromic. The result is a set in order to remove all duplicate sub palindromic.

def sub_palindromic(s):
    if len(s) <= 1:
        return set()
    elif len(s) == 2:
        if s[::-1] == s:
            return set([s])
        else:
            return set()
    else:
        if s[::-1] == s:
            return set([s]) | sub_palindromic(s[1:]) | sub_palindromic(s[:-1])
        else:
            return sub_palindromic(s[1:]) | sub_palindromic(s[:-1]) | sub_palindromic(s[:2]) | sub_palindromic(s[-2:])

sub_palindromic('nitin') # {'nitin', 'iti'}
sub_palindromic('abca') # set()
sub_palindromic('abab') # {'bab', 'aba'}
sub_palindromic('abba') # {'abba', 'bb'}
sub_palindromic("aaaaa") # {'aa', 'aaa', 'aaaa', 'aaaaa'}
sub_palindromic('abcbacab') # {'abcba', 'aca', 'bacab', 'bcb'}
sub_palindromic("1122bb2211") # {'11', '1122bb2211', '122bb221', '22', '22bb22', '2bb2', 'bb'}


问:
Camouflage product id's on website
I'm currently building a retail e-shop for a jewellery manufacturer which also sells wholesale to other shops and I'm looking for an efficient way to "hide"/"camouflage" the product id's for all products so that other competitors wont be able to see the product's barcodes and find out that the manufacturer is doing direct sales at lower prices.

All products on the website have a 4-5 digit id which is also the name of the products' images, ie for Product #1234 image filename is 1234.jpg

One thought was to add a 3-digit random int before and after the product ID that would make it quite hard for someone to figure out the product id. Another thought would be to reverse the id's or perform some sort of scrambling. This would work fine for all the links within the site and all i'd have to do would be to strip off the first and last 3 digits off the product id's or de-scramble before using in the queries but what can I do when it comes to displaying product images? I don't want visitors to be able to see the filenames, that would completely blow the cover for a ll product id's.

Suggestions and ideas are very welcome.

答:
The products don't need to be identified by barcode - you could use a meaningless identifier for the products, and only look up the barcode when you actually need it. Example:

```<code>product_barcode | product_identifier
7310791268002   | deadbeef01234cafe
</code>```

Then, you'd use deadbeef01234cafe both for identifying the product in the store, and for the image name.

Title: Camouflage product id's on website

Body:
The products don't need to be identified by barcode - you could use a meaningless identifier for the products, and only look up the barcode when you actually need it. Example:

product_barcode | product_identifier
7310791268002   | deadbeef01234cafe

Then, you'd use deadbeef01234cafe both for identifying the product in the store, and for the image name.


问:
How can I choose the node version when using .nvm to install
In the terminal, using nvm, I would like to run npm install <something> and have npm install the package in the node version that I'm currently using.  Currently, no matter what version I have set using nvm, by default, nvm is installing all packages in node version 9.4.0.

I have ran the command nvm use v10.15.3 which switches me to that current version.  When I run a command npm install -g ionic@latest (or any global command) it always installs it in the version 9.4.0 directory.

My output after running the command...

```<code>.../.nvm/versions/node/v9.4.0/bin/ionic -> .../.nvm/versions/node/v9.4.0/lib/node_modules/ionic/bin/ionic
</code>```

This happens even though I'm currently on 10.15.3 (I would expect to install in the directory v10.15.3 and not v9.4.0

I'm using nvm version 0.34.0.

bash_profile

```<code>export NVM_DIR=~/.nvm
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

source ~/.nvm/nvm.sh
</code>```

答: I think it's a path issue, can you add your bashrc, npmrc or profile to the question?</p>

Body:
In the terminal, using nvm, I would like to run npm install <something> and have npm install the package in the node version that I'm currently using.  Currently, no matter what version I have set using nvm, by default, nvm is installing all packages in node version 9.4.0.

I have ran the command nvm use v10.15.3 which switches me to that current version.  When I run a command npm install -g ionic@latest (or any global command) it always installs it in the version 9.4.0 directory.

My output after running the command...

.../.nvm/versions/node/v9.4.0/bin/ionic -> .../.nvm/versions/node/v9.4.0/lib/node_modules/ionic/bin/ionic

This happens even though I'm currently on 10.15.3 (I would expect to install in the directory v10.15.3 and not v9.4.0

I'm using nvm version 0.34.0.

bash_profile

export NVM_DIR=~/.nvm
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

source ~/.nvm/nvm.sh