问:
Running a docker command in docker build
I have an application which uses docker to build itself, and I want to build a docker image of it. This requires exposing the docker.sock to the application during the docker build command (similar to adding a -v /var/run/docker.sock:/var/run/docker.sock argument to a docker run command).

It there any way I can do this or should I resort to building in a virtual machine and copying the build artefacts into a container?
The Dockerfile look like this:

```<code>FROM docker

RUN docker run --rm -v /opt/<myapp>:/opt/<myapp> <myapp> /build_and_install.sh /opt/<myapp>

# etc...
</code>```

答: Your usecase is a little unclear. That said, in many cases this can be done with a multi-stage build. Docker has put out a sample Java application with a good example of a multi-stage Dockerfile.</p>

Body:
I have an application which uses docker to build itself, and I want to build a docker image of it. This requires exposing the docker.sock to the application during the docker build command (similar to adding a -v /var/run/docker.sock:/var/run/docker.sock argument to a docker run command).

It there any way I can do this or should I resort to building in a virtual machine and copying the build artefacts into a container?
The Dockerfile look like this:

FROM docker

RUN docker run --rm -v /opt/<myapp>:/opt/<myapp> <myapp> /build_and_install.sh /opt/<myapp>

# etc...


来源: stackexchange

问:
C# Forms. How to connect send button with checkbox?
I have a button that sends mail on click but I want it to send mail every time timer tick occurs and I use checkbox to tell the program it's suppose to send every 5 minutes. What should I write in if loop to make it execute what's in timer2_Tick? Else just sends mail once after clicking the button.</p>

```<code>  private void button2_Click(object sender, EventArgs e)
    {
        if (chbRepeat.Checked)
        {

        }
        else
        {
            MailHelper zmienna = new MailHelper();
            zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
        }

    }

    private void chbRepeat_CheckedChanged(object sender, EventArgs e)
    {
        MailHelper zmienna = new MailHelper();
        zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
    }

    private void timer2_Tick(object sender, EventArgs e)
    {

        MailHelper zmienna = new MailHelper();
        zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
    }
}
</code>```

答:
You need to start the timer

```<code>timer2.Start();
</code>```

You can also stop it with

```<code>timer2.Stop();
</code>```

You can also start and stop the timer through the Enabled property.

```<code>private void chbRepeat_CheckedChanged(object sender, EventArgs e)
{
    // This automatically starts the timer when you check the check-box and
    // stops it when you un-check the ckeck box.
    timer2.Enabled = chbRepeat.Checked;
}
</code>```

The don't repeat yourself (DRY) principle says that you shouldn't write the same code more than once. This enhances the maintainability, the testability and readability of your code. You wrote the send mail code 3 times. Extract this code to a new method.

See: Timer Class

ContentLicense: CC BY-SA 3.0

Body:
I have a button that sends mail on click but I want it to send mail every time timer tick occurs and I use checkbox to tell the program it's suppose to send every 5 minutes. What should I write in if loop to make it execute what's in timer2_Tick? Else just sends mail once after clicking the button.

  private void button2_Click(object sender, EventArgs e)
    {
        if (chbRepeat.Checked)
        {

        }
        else
        {
            MailHelper zmienna = new MailHelper();
            zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
        }

    }

    private void chbRepeat_CheckedChanged(object sender, EventArgs e)
    {
        MailHelper zmienna = new MailHelper();
        zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
    }

    private void timer2_Tick(object sender, EventArgs e)
    {

        MailHelper zmienna = new MailHelper();
        zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
    }
}

Body:
You need to start the timer

timer2.Start();

You can also stop it with

timer2.Stop();

You can also start and stop the timer through the Enabled property.

private void chbRepeat_CheckedChanged(object sender, EventArgs e)
{
    // This automatically starts the timer when you check the check-box and
    // stops it when you un-check the ckeck box.
    timer2.Enabled = chbRepeat.Checked;
}

The don't repeat yourself (DRY) principle says that you shouldn't write the same code more than once. This enhances the maintainability, the testability and readability of your code. You wrote the send mail code 3 times. Extract this code to a new method.

See: Timer Class


问:
Javascript : setInterval and ClearInterval on one click?
I'm trying to have the numbers 1-6 quickly flash on the screen when a button is clicked, then stop and display the random generated number. If I put clearInterval into the function it just displays the random Number and doesn't display the flashes up numbers before hand.

HTML

```<code><div id='dice'>
    <div id='number'>0</div>
</div>
<div id='button'>
    <button onclick='roll()'>Roll Dice</button>
</div>
</code>```

JAVASCRIPT

```<code>let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  let shuffleDice = setTimeout(function(){
    diceNumber.innerHTML = diceSides[i++];
    if(diceNumber == diceSides.length){
      i = 0;
    }
  }, 500);

  let random = Math.floor(Math.random() * 6);
    diceNumber.innerHTML = random;
}
</code>```

答:
SetTimeout only executes once. Also your variable is changed by the interval!
After its over, you have to clear the interval with clearInterval.

let rollButton = document.querySelector('button');

let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  var shuffleDice = setInterval(function(){
    diceNumber.innerHTML = diceSides[i++];
    //use i
    if(i == diceSides.length){
      i = 0;
      //clear
      clearInterval(shuffleDice);

      // moved because the interval will change it
      let random = Math.floor(Math.random() * 6);
      diceNumber.innerHTML = String(random);
    }
  }, 500);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = 'dice'>
      <div id = 'number'>0</div>
    </div>
    <div id = 'button'>
      <button onclick =  'roll()'>Roll Dice</button>
      </div></code>```

Body:
I'm trying to have the numbers 1-6 quickly flash on the screen when a button is clicked, then stop and display the random generated number. If I put clearInterval into the function it just displays the random Number and doesn't display the flashes up numbers before hand.

HTML

0

    <button onclick='roll()'>Roll Dice</button>

JAVASCRIPT

let rollButton = document.querySelector('button');
let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  let shuffleDice = setTimeout(function(){
    diceNumber.innerHTML = diceSides[i++];
    if(diceNumber == diceSides.length){
      i = 0;
    }
  }, 500);

  let random = Math.floor(Math.random() * 6);
    diceNumber.innerHTML = random;
}

Body:
SetTimeout only executes once. Also your variable is changed by the interval!
After its over, you have to clear the interval with clearInterval.

let rollButton = document.querySelector('button');

let diceNumber = document.getElementById ('number');

function roll(){
  diceSides = [1,2,3,4,5,6];
  var i = 0;
  var shuffleDice = setInterval(function(){
    diceNumber.innerHTML = diceSides[i++];
    //use i
    if(i == diceSides.length){
      i = 0;
      //clear
      clearInterval(shuffleDice);

      // moved because the interval will change it
      let random = Math.floor(Math.random() * 6);
      diceNumber.innerHTML = String(random);
    }
  }, 500);

}

<div id = 'dice'>
      <div id = 'number'>0</div>
    </div>
    <div id = 'button'>
      <button onclick =  'roll()'>Roll Dice</button>
      </div>


问:
How to update and delete duplicate in SQL Server?
I have two table Add (Parent table) and AddXref (Child Table) and want to delete duplicate records in parent table and also update in Child table. In AddXref table the two records should have anyone of AddId from Add Table.i Tried with basic update statement but it didn't worked. How can I update AddXref Table?

My Attempt:
I have written the query up to this point, but am stuck on what to do next

```<code>Update AddXref name
SET a.AddId=b.AddId
FROM AddXref a
INNER JOIN Add b ON a.AddId = b.AddId
WHERE b.AddId = ( Select Top 1 ax.Addid from Add ax
                  INNER JOIN Add ax1  on
ax.AddressMain = a.AddressMain and
              ax.city = a.city and
              ax.Country = a.Country and
              ax.State = a.State and
              ax.ZipCode = a.ZipCode);

| AddId  | AddressMain  | City    | Country | State   | ZipCode    |
|--------|--------------|---------|---------|---------|------------|
| 8CA25D | 1234 Main St | Antioch | USA     | Florida | 60002-9714 |
| 5T7YTR | 1234 Main St | Antioch | USA     | Florida | 60002-9714 |

| AddXrefId | AddressId | IndividualId | InstitutionId |
|-----------|-----------|--------------|---------------|
| 822145    | 8CA25D    | 7652ER       | NULL          |
| 435902    | 5T7YTR    | NULL         | NA1043        |

| AddXrefId | AddressId | IndividualId | InstitutionId |
|-----------|-----------|--------------|---------------|
| 822145    | 8CA25D    | 7652ER       | NULL          |
| 435902    | 8CA25D    | NULL         | NA1043        | --Output either "8CA25D" or "5T7YTR" any one of it
</code>```

答:
first gather duplicate data.

```<code>select AddressMain, City, Country, State, ZipCode, min(addId) as minID, Max(addId) as MAxID
INTO #tmpData
from add
group by AddressMain, City, Country, State, ZipCode
</code>```

second update child table

```<code>Update AddXref
SET a.AddId=b.MaxID
FROM AddXref a
INNER JOIN #tmpData b ON a.AddId = b.MinID -- you can use maxId too if you want.
</code>```

third remove duplicate record from parents.

```<code>DELETE FROM Add where AddId IN (Select MinID FROM #tmpData)
</code>```

This code is not tested.

Body:
I have two table Add (Parent table) and AddXref (Child Table) and want to delete duplicate records in parent table and also update in Child table. In AddXref table the two records should have anyone of AddId from Add Table.i Tried with basic update statement but it didn't worked. How can I update AddXref Table?

My Attempt:
I have written the query up to this point, but am stuck on what to do next

Update AddXref name
SET a.AddId=b.AddId
FROM AddXref a
INNER JOIN Add b ON a.AddId = b.AddId
WHERE b.AddId = ( Select Top 1 ax.Addid from Add ax
                  INNER JOIN Add ax1  on
ax.AddressMain = a.AddressMain and
              ax.city = a.city and
              ax.Country = a.Country and
              ax.State = a.State and
              ax.ZipCode = a.ZipCode);

| AddId  | AddressMain  | City    | Country | State   | ZipCode    |
|--------|--------------|---------|---------|---------|------------|
| 8CA25D | 1234 Main St | Antioch | USA     | Florida | 60002-9714 |
| 5T7YTR | 1234 Main St | Antioch | USA     | Florida | 60002-9714 |

| AddXrefId | AddressId | IndividualId | InstitutionId |
|-----------|-----------|--------------|---------------|
| 822145    | 8CA25D    | 7652ER       | NULL          |
| 435902    | 5T7YTR    | NULL         | NA1043        |

| AddXrefId | AddressId | IndividualId | InstitutionId |
|-----------|-----------|--------------|---------------|
| 822145    | 8CA25D    | 7652ER       | NULL          |
| 435902    | 8CA25D    | NULL         | NA1043        | --Output either "8CA25D" or "5T7YTR" any one of it

Body:
first gather duplicate data.

select AddressMain, City, Country, State, ZipCode, min(addId) as minID, Max(addId) as MAxID
INTO #tmpData
from add
group by AddressMain, City, Country, State, ZipCode

second update child table

Update AddXref
SET a.AddId=b.MaxID
FROM AddXref a
INNER JOIN #tmpData b ON a.AddId = b.MinID -- you can use maxId too if you want.

third remove duplicate record from parents.

DELETE FROM Add where AddId IN (Select MinID FROM #tmpData)

This code is not tested.


问:
Is it possible to write a Java class in JScheme?
Can you write a Java class in JScheme?  It would be nice to be able to so that you could write a listener in JScheme.</p>

答: Yes. According to the following you can write a Java class in JScheme: http://www.java2s.com/Open-Source/Java-Document/Scripting/jscheme/Catalogjscheme.htm</p>

ContentLicense: CC BY-SA 2.5


答:
I suggest something like this:

```<code>var diceNumber = document.getElementById ('number');
const diceSides = [1,2,3,4,5,6];

function roll(){
    let arr = [...diceSides,diceSides[Math.floor(Math.random() * diceSides.length)]];
    cycle(diceNumber,arr,200);
}

function cycle(element,arr,delay) {
  element.innerText=arr.shift();
  if (arr.length > 0)
    setTimeout(cycle,delay,element,arr,delay);
}
</code>```

Given that you know precisely the list you want to iterate through, and thus the fixed number of iterations you want to execute, this seems cleaner and more concise than setInterval, which you would have to explicitly stop when you reach the end of the list. I like setInterval for things that will run an indeterminate period of time (for instance, until stopped by a user action).

What this says is: "Take this list of numbers (the last one being the random one). Show the first one and remove it from the list. Then wait a while and do it again, until you're out of numbers."

A couple other fine points here:

innerText rather than innerHTML, since you're just setting string content.

You want to use your random number as a key against your array of die faces, not directly - used directly, you get [0-5], not [1-6].

Use the length of your array, rather than hard-coding '6' - always avoid magic numbers when you can. By referring everything back to your constant array, changing the values on the faces of the die (or the number of them) becomes trivial; just change the array and everything else will still work.

Normally, there are stack-size concerns with recursive code. In this case, that wouldn't be a problem because of the small size of the array. But beyond that, the fact that the recursion is going through setTimeout means that each one is a seprate entry on the queue, and the prior isn't waiting for the next to complete before it can exit.

Title: Javascript : setInterval and ClearInterval on one click?

Body:
I suggest something like this:

var diceNumber = document.getElementById ('number');
const diceSides = [1,2,3,4,5,6];

function roll(){
    let arr = [...diceSides,diceSides[Math.floor(Math.random() * diceSides.length)]];
    cycle(diceNumber,arr,200);
}

function cycle(element,arr,delay) {
  element.innerText=arr.shift();
  if (arr.length > 0)
    setTimeout(cycle,delay,element,arr,delay);
}

Given that you know precisely the list you want to iterate through, and thus the fixed number of iterations you want to execute, this seems cleaner and more concise than setInterval, which you would have to explicitly stop when you reach the end of the list. I like setInterval for things that will run an indeterminate period of time (for instance, until stopped by a user action).

What this says is: "Take this list of numbers (the last one being the random one). Show the first one and remove it from the list. Then wait a while and do it again, until you're out of numbers."

A couple other fine points here:

innerText rather than innerHTML, since you're just setting string content.

You want to use your random number as a key against your array of die faces, not directly - used directly, you get [0-5], not [1-6].

Use the length of your array, rather than hard-coding '6' - always avoid magic numbers when you can. By referring everything back to your constant array, changing the values on the faces of the die (or the number of them) becomes trivial; just change the array and everything else will still work.

Normally, there are stack-size concerns with recursive code. In this case, that wouldn't be a problem because of the small size of the array. But beyond that, the fact that the recursion is going through setTimeout means that each one is a seprate entry on the queue, and the prior isn't waiting for the next to complete before it can exit.


问:
MongoDB: Collection aggregate with $sample in NodeJS
I am currently having issues with aggregation with NodeJS's implementation of aggregate with $sample.

The query I want to run from MongoDB is:

```<code>db.qmquestions.aggregate({$sample: {size: 1}})
</code>```

which will output:

```<code>{ "_id" : ObjectId("58bf0f29b6942f2dd471b6cc"), "question" : { "questionTitle" : "Test", "question" : "What is the Capital of England", "answer" : "London" } }
</code>```

The code i'm attempting to use is:

```<code>var generateQuestion = function(){
    var MongoClient = require('mongodb').MongoClient
    var url = 'mongodb://localhost/quizmaster';

    var results_from_mongo = [];

    MongoClient.connect(url, function (err, db) {
        var str = db.collection('qmquestions').find({}).toArray(function (err,docs){
            //console.log(docs)

            //for (var i = 0, len = docs.length; i < len; i++)
            //{
            var test = db.collection('qmquestions').aggregate(
                {$sample: {size: 1}}
            );

            console.log(test)
                //gameState.currentQuestion = docs[i].question.question
                //console.log("currentQuestion is " + gameState.currentQuestion)
            //}
            return gameState.currentQuestion
        })
    });
};
</code>```

But all what test is returning from console.log is (This is only a snippet as it's just returning MongoDB server information):

```<code>AggregationCursor {
  pool: null,
  server: null,
  disconnectHandler:
   Store {
     s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: BSON {},
  ns: 'quizmaster.qmquestions',
  cmd:
   { aggregate: 'qmquestions',
     pipeline: [ [Object] ],
     cursor: { batchSize: 1000 } },
  options:
   { readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
     promiseLibrary: [Function: Promise],
     cursorFactory: { [Function: AggregationCursor] super_: [Object], define: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
     cursor: { batchSize: 1000 },
     disconnectHandler: Store { s: [Object], length: [Getter] } },
</code>```

If anybody can spot where I'm going wrong that would be great as I can't see the issue the only thing I can think of is that it's not liking the aggregation inside the "var str" call.

EDIT:
I feel i'm not getting my issue across what I'm looking for is when the generateQuestion function is called for it to look inside the qmQuestions collection and pick a random result from that collection to then display in the test variable. This function calls on a button press in a form which isn't shown in the question which is irrelevant of the issue. Each time the function is called a random result will be placed within the test variable.

答:
You need to express the pipeline as an array

try

```<code>var test = db.collection('qmquestions').aggregate([
            {$sample: {size: 1}}
        ]);
</code>```

Body:
I am currently having issues with aggregation with NodeJS's implementation of aggregate with $sample.

The query I want to run from MongoDB is:

db.qmquestions.aggregate({$sample: {size: 1}})

which will output:

{ "_id" : ObjectId("58bf0f29b6942f2dd471b6cc"), "question" : { "questionTitle" : "Test", "question" : "What is the Capital of England", "answer" : "London" } }

The code i'm attempting to use is:

var generateQuestion = function(){
    var MongoClient = require('mongodb').MongoClient
    var url = 'mongodb://localhost/quizmaster';

    var results_from_mongo = [];

    MongoClient.connect(url, function (err, db) {
        var str = db.collection('qmquestions').find({}).toArray(function (err,docs){
            //console.log(docs)

            //for (var i = 0, len = docs.length; i < len; i++)
            //{
            var test = db.collection('qmquestions').aggregate(
                {$sample: {size: 1}}
            );

            console.log(test)
                //gameState.currentQuestion = docs[i].question.question
                //console.log("currentQuestion is " + gameState.currentQuestion)
            //}
            return gameState.currentQuestion
        })
    });
};

But all what test is returning from console.log is (This is only a snippet as it's just returning MongoDB server information):

AggregationCursor {
  pool: null,
  server: null,
  disconnectHandler:
   Store {
     s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: BSON {},
  ns: 'quizmaster.qmquestions',
  cmd:
   { aggregate: 'qmquestions',
     pipeline: [ [Object] ],
     cursor: { batchSize: 1000 } },
  options:
   { readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
     promiseLibrary: [Function: Promise],
     cursorFactory: { [Function: AggregationCursor] super_: [Object], define: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
     cursor: { batchSize: 1000 },
     disconnectHandler: Store { s: [Object], length: [Getter] } },

If anybody can spot where I'm going wrong that would be great as I can't see the issue the only thing I can think of is that it's not liking the aggregation inside the "var str" call.

EDIT:
I feel i'm not getting my issue across what I'm looking for is when the generateQuestion function is called for it to look inside the qmQuestions collection and pick a random result from that collection to then display in the test variable. This function calls on a button press in a form which isn't shown in the question which is irrelevant of the issue. Each time the function is called a random result will be placed within the test variable.

Body:
You need to express the pipeline as an array

try

var test = db.collection('qmquestions').aggregate([
            {$sample: {size: 1}}
        ]);


问:
Ruby Datamapper connection with SSL to MariaDB on Amazon RDS
How do I establish a ruby Datamapper connection to MariaDB on Amazon RDS with SSL?

Here's what I did:

A non-SSL connection works when testing with:

uri = 'mysql://user:pass@host:port/db_name'
connection = DataObjects::Connection.new(uri)
=> #<DataObjects::Mysql::Connection:0x000056179a3a5921

connection.secure?
=> false
```

<p>According to the MySQL datamapper wiki, an ssl connection requires the following options: <code>:ssl_ca, :client_key, and :client_cert</code>.</p>

<p>This would result in the following code:</p>

<pre class="lang-rb prettyprint-override"><code>uri = 'mysql://user:pass@host:port/db_name?'
ssl_opts = 'ssl[ssl_ca]=file&ssl[client_key]=file&ssl[client_cert]=file'

connection = DataObjects::Connection.new(uri + ssl_opts)
connection.secure?
=> false
</code>```

However the only files get is the RDS combind CA bundle, refered from the RDS docs

I do not have a client_cert at all.

Connecting with the mysql client on cli works with SSL:

```<code>mysql --ssl -h host -u user -p pass db_name
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1638
Server version: 10.1.26-MariaDB MariaDB Server
</code>```

答:
There's only one parameter required: :ssl => {:ca_cert => 'pem_file'}.

However it looks like using uri string for configuration does not work. The reason is a limitation in Addressable::Uri. It cannot handle query strings which aim to represent hashes with more than 1 level.

The good news is that it works using DataMapper.setup with a config Hash:

DataMapper.setup(:default,
    :adapter  => 'mysql',
    :user     => 'user',
    :database => 'db_name',
    :host     => 'host',
    :password => 'pass',
    :ssl => {
        :ca_cert  => '/path/to/rds-combined-ca-bundle.pem'
    }
)
```

Body:
How do I establish a ruby Datamapper connection to MariaDB on Amazon RDS with SSL?

Here's what I did:

A non-SSL connection works when testing with:

uri = 'mysql://user:pass@host:port/db_name'
connection = DataObjects::Connection.new(uri)
=> #<DataObjects::Mysql::Connection:0x000056179a3a5921

connection.secure?
=> false

According to the MySQL datamapper wiki, an ssl connection requires the following options: :ssl_ca, :client_key, and :client_cert.

This would result in the following code:

uri = 'mysql://user:pass@host:port/db_name?'
ssl_opts = 'ssl[ssl_ca]=file&ssl[client_key]=file&ssl[client_cert]=file'

connection = DataObjects::Connection.new(uri + ssl_opts)
connection.secure?
=> false

However the only files get is the RDS combind CA bundle, refered from the RDS docs

I do not have a client_cert at all.

Connecting with the mysql client on cli works with SSL:

mysql --ssl -h host -u user -p pass db_name
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1638
Server version: 10.1.26-MariaDB MariaDB Server


问:
Merge two columns in Select into one column based on a condition
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

```<code>+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+
</code>```

SQL for left table above

```<code>SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable
</code>```

Heres what I have so far

```<code>SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT
</code>```

答:
here are a couple of options.. possibly</p>

```<code>;with mycte as (
select null as a, 1 as b
union all
select null as a, 1 as b
union all
select 2 as a, null as b
union all
select 2 as a, 3 as b
union all
select 2 as a, 5 as b
union all
select null as a, null as b

)

Select
*,
CONCAT(a,case when b is not null and a is not null then (select null) else b end) case_statement
,COALESCE (a,b)  coalesce_statement
 from mycte
</code>```

Body:
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+

SQL for left table above

SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable

Heres what I have so far

SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT

Body:
here are a couple of options.. possibly

;with mycte as (
select null as a, 1 as b
union all
select null as a, 1 as b
union all
select 2 as a, null as b
union all
select 2 as a, 3 as b
union all
select 2 as a, 5 as b
union all
select null as a, null as b

)

Select
*,
CONCAT(a,case when b is not null and a is not null then (select null) else b end) case_statement
,COALESCE (a,b)  coalesce_statement
 from mycte


问:
Getting one element to match the scrolling of another
I have two tall and narrow elements of equal height that are next to each other. When I scroll one of these two elements, I want the other to scroll with it.

How can I do this using jQuery? I've tried the ScrollTo plugin but the documentation is so bad I can't figure out how to use it.

答:
This can be accomplished with some simple jQuery, as shown in this example (link).

Basically, you just set the .scrollTop() of one div to mimick the other on the scroll() event handler:

```<code>$('#leader').scroll(function(e){
    $('#copycat').scrollTop($(this).scrollTop());
});
</code>```

Body:
This can be accomplished with some simple jQuery, as shown in this example (link).

Basically, you just set the .scrollTop() of one div to mimick the other on the scroll() event handler:

$('#leader').scroll(function(e){
    $('#copycat').scrollTop($(this).scrollTop());
});


问:
More Depth on how getline works
So for example if I had a .dat file like this

```<code>410000 1905 7 50
410001 2015 3 25
410023 1857 12 -25
</code>```

I am trying to figure out how to store these numbers into a linked list, which i understand the linked list, but on cases where the .dat might look like

```<code>410000 1905 7 50
410001 2015 3 25
410023 1857 12
</code>```

where the last line only has 3 values, I am not quite sure how to get those values. what i originally had was.

```<code>while(filename >> location >> year >> month >> temp)
</code>```

but i was wondering if there were only 3 values on that line, would i get an error or would the temp value be taken off the next line, and since I did not think that would work, i wondered how getline works, and so I thought that maybe i could try

```<code>while ( getline(filename,location,year,month,temp))
</code>```

and i was wondering what would happen if that while loop hit the line with 3 values instead of 4.
So if anyone could possibly explain how I could get around the problem, any help is appreciated.

If there are only 3 values on a line i must tell the user there is an error, but keep checking all the other values, i cannot just return 0; and exit the program.

答:
getline() reads a full line from an istream. Your loop would look like:

```<code>string line;
while (getline(file,line)) {
    // parse the string in line to extract the compnents
    ...
}
</code>```

One way to decompose line is to use a stringstream:

```<code>    stringstream is(line);
    is >> location >> year >> month >> temp;
</code>```

If an error would happen in the format of the line, the state of is would be changed accordingly.

Title: More Depth on how getline works

Body:
So for example if I had a .dat file like this

410000 1905 7 50
410001 2015 3 25
410023 1857 12 -25

I am trying to figure out how to store these numbers into a linked list, which i understand the linked list, but on cases where the .dat might look like

410000 1905 7 50
410001 2015 3 25
410023 1857 12

where the last line only has 3 values, I am not quite sure how to get those values. what i originally had was.

while(filename >> location >> year >> month >> temp)

but i was wondering if there were only 3 values on that line, would i get an error or would the temp value be taken off the next line, and since I did not think that would work, i wondered how getline works, and so I thought that maybe i could try

while ( getline(filename,location,year,month,temp))

and i was wondering what would happen if that while loop hit the line with 3 values instead of 4.
So if anyone could possibly explain how I could get around the problem, any help is appreciated.

If there are only 3 values on a line i must tell the user there is an error, but keep checking all the other values, i cannot just return 0; and exit the program.

Body:
getline() reads a full line from an istream. Your loop would look like:

string line;
while (getline(file,line)) {
    // parse the string in line to extract the compnents
    ...
}

One way to decompose line is to use a stringstream:

    stringstream is(line);
    is >> location >> year >> month >> temp;

If an error would happen in the format of the line, the state of is would be changed accordingly.


问:
Setting global variable not working in Symfony
I could not access $result outside the foreach loop. When I use dump($results); inside the loop I'm getting result, but when I'm using dump($results); outside the loop result is empty.

```<code>$results = array();

foreach ($menu as $menus) {
    $mid = $menus->getId();
    $em = $this->getDoctrine()->getManager();
    $connection = $em->getConnection();

    $statement = $connection->prepare("SELECT s.subtitle,m.* FROM submenu as s,menu as m where s.menu_id=m.id and m.id=:data");
    $statement->bindValue('data', $mid);
    $statement->execute();
    $results = $statement->fetchAll();
}
dump($results)
</code>```

答:
You're overwriting the $results variable each time through the loop. So the final value will just be the result of the last query. I suspect you want to combine the results of all the queries, so you need to merge the arrays.

Change

```<code>$result = $statement->fetchAll();
</code>```

to:

```<code>$result += $statement->fetchAll();
</code>```

Alternatively you could just combine all the queries into a single query. Put all the menu IDs into an array $menuIDs, and do:

```<code>$sql = "SELECT s.subtitle,m.* FROM submenu as s,menu as m where s.menu_id=m.id and m.id IN (" . implode(',', array_fill(0, count($menuIDs), '?')) . ")";
$statement = $connection->prepare($sql);
$statement->execute($menuIDs);
$results = $statement->fetchAll();
</code>```

Body:
I could not access $result outside the foreach loop. When I use dump($results); inside the loop I'm getting result, but when I'm using dump($results); outside the loop result is empty.

$results = array();

foreach ($menu as $menus) {
    $mid = $menus->getId();
    $em = $this->getDoctrine()->getManager();
    $connection = $em->getConnection();

    $statement = $connection->prepare("SELECT s.subtitle,m.* FROM submenu as s,menu as m where s.menu_id=m.id and m.id=:data");
    $statement->bindValue('data', $mid);
    $statement->execute();
    $results = $statement->fetchAll();
}
dump($results)

Body:
You're overwriting the $results variable each time through the loop. So the final value will just be the result of the last query. I suspect you want to combine the results of all the queries, so you need to merge the arrays.

Change

$result = $statement->fetchAll();

to:

$result += $statement->fetchAll();

Alternatively you could just combine all the queries into a single query. Put all the menu IDs into an array $menuIDs, and do:

$sql = "SELECT s.subtitle,m.* FROM submenu as s,menu as m where s.menu_id=m.id and m.id IN (" . implode(',', array_fill(0, count($menuIDs), '?')) . ")";
$statement = $connection->prepare($sql);
$statement->execute($menuIDs);
$results = $statement->fetchAll();


问:
How do I get this selenium app to work without NUNIT?
I would like to be able to run this app without using NUNIT, specifically because I need to run it every hour. I am a beginner at NUNIT and selenium, and was wondering what I can do to convert this into a console app instead of having to run it through NUNIT?

The code is below. Thank you so much for your help.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Selenium;
using System.Threading;
using System.Data;
using System.IO;

namespace LogIn
{
    [TestFixture]
    public class LogIn
    {
       public static ISelenium selenium;
       private StringBuilder verificationErrors;

        [SetUp]
        public void SetupTest()
        {
            selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "https://.............aspx");
            selenium.Start();
            selenium.SetSpeed("900");
            selenium.WindowMaximize();
            selenium.WindowFocus();
            verificationErrors = new StringBuilder();
        }

        [Test]
        public void Login()
        {

            selenium.SetSpeed("900");
            selenium.Open("/Login.aspx");

            Assert.AreEqual("stuff", selenium.GetTitle());

            selenium.Type("id=ctl00_cphBody_objLogin_UserName", "username");

            selenium.Type("id=ctl00_cphBody_objLogin_Password", "Pass");

            selenium.Click("id=ctl00_cphBody_objLogin_LoginImageButton");

            selenium.WaitForPageToLoad("30000");

            Assert.AreEqual("labs", selenium.GetTitle());

            //i dont understand why do we need this?
            /*
            try
            {
                Assert.AreEqual("Orders - Drug Testing ", selenium.GetText("link=Orders - Drug Testing "));

            }
            catch (AssertionException e)
            {
                Console.WriteLine(e.Message + " " + DateTime.Now);
            }
            */

            Console.WriteLine("Congrats, you are logined successfully. " + DateTime.Now);

            selenium.Click("link=Specimen Volume Report - Drugs");
            selenium.WaitForPageToLoad("30000");
            selenium.Click("id=ctl00_cphBody_dtpFrom");
            selenium.Type("id=ctl00_cphBody_dtpFrom", DateTime.Now.ToString("MM/dd/yyyy"));
            selenium.Type("id=ctl00_cphBody_dtpTo", DateTime.Now.ToString("MM/dd/yyyy"));
            selenium.Click("id=ctl00_cphBody_btnExport");
            selenium.SetSpeed("6000");
            Console.WriteLine("Waiting for result complete");
            selenium.IsTextPresent("Specimen Volume Report");
            selenium.IsTextPresent("Display Specimen Detail");

        }

        [TearDown]
        public void FullTearDown()
        {
            selenium.Stop();
        }

}
</code>```

}

答:
make a new console app.  import the selenium driver (the nuget pkg should load appium as a prereq).  start writing static voids without the [Test] banner atop.  run them and handle your exceptions, log errors.

I actually find NUnit to be more of a hindrance than a help, whether or not I use it I have issues getting long-term functional/stress tests to run.

Calabash, appium, anything more than good old ADB is very prone to memory leaks and I suspect designed only for quicker unit tests.

UItest cloud even puts a limit, 6 hours per device, 30 minutes per test, 10 minutes per calabash step.  In my opinion they set the bar ridiculously low and encourage stress testing to be done in house

Body:
I would like to be able to run this app without using NUNIT, specifically because I need to run it every hour. I am a beginner at NUNIT and selenium, and was wondering what I can do to convert this into a console app instead of having to run it through NUNIT?

The code is below. Thank you so much for your help.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Selenium;
using System.Threading;
using System.Data;
using System.IO;

namespace LogIn
{
    [TestFixture]
    public class LogIn
    {
       public static ISelenium selenium;
       private StringBuilder verificationErrors;

        [SetUp]
        public void SetupTest()
        {
            selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "https://.............aspx");
            selenium.Start();
            selenium.SetSpeed("900");
            selenium.WindowMaximize();
            selenium.WindowFocus();
            verificationErrors = new StringBuilder();
        }

        [Test]
        public void Login()
        {

            selenium.SetSpeed("900");
            selenium.Open("/Login.aspx");

            Assert.AreEqual("stuff", selenium.GetTitle());

            selenium.Type("id=ctl00_cphBody_objLogin_UserName", "username");

            selenium.Type("id=ctl00_cphBody_objLogin_Password", "Pass");

            selenium.Click("id=ctl00_cphBody_objLogin_LoginImageButton");

            selenium.WaitForPageToLoad("30000");

            Assert.AreEqual("labs", selenium.GetTitle());

            //i dont understand why do we need this?
            /*
            try
            {
                Assert.AreEqual("Orders - Drug Testing ", selenium.GetText("link=Orders - Drug Testing "));

            }
            catch (AssertionException e)
            {
                Console.WriteLine(e.Message + " " + DateTime.Now);
            }
            */

            Console.WriteLine("Congrats, you are logined successfully. " + DateTime.Now);

            selenium.Click("link=Specimen Volume Report - Drugs");
            selenium.WaitForPageToLoad("30000");
            selenium.Click("id=ctl00_cphBody_dtpFrom");
            selenium.Type("id=ctl00_cphBody_dtpFrom", DateTime.Now.ToString("MM/dd/yyyy"));
            selenium.Type("id=ctl00_cphBody_dtpTo", DateTime.Now.ToString("MM/dd/yyyy"));
            selenium.Click("id=ctl00_cphBody_btnExport");
            selenium.SetSpeed("6000");
            Console.WriteLine("Waiting for result complete");
            selenium.IsTextPresent("Specimen Volume Report");
            selenium.IsTextPresent("Display Specimen Detail");

        }

        [TearDown]
        public void FullTearDown()
        {
            selenium.Stop();
        }

}

}


问:
To check if filename has substring of a word in a list
I have a list of keywords and I want to go through a directory looking for filename that contain the keyword. If found, binds the matching keyword and file path to a dictionary.

```<code>keywords = ['mon', 'tue', 'wed']
dict = {}

directory = os.fsencode(r"my_dir")

for file in os.listdir(directory):
  filename = os.fsdecode(file)
  ext = Path(file).suffix

  if filename in keywords:
    filepath = os.path.join(directory, filename, ext)
    dict[keyword] = filepath
</code>```

So at the end I want something like this:

```<code>{'mon': 'F:\mon_001.txt', 'tue': 'F:\tue_999.txt', 'wed': 'F\wed_123.txt'}
</code>```

Now how do I find the match?

答:
There isn't a nice one-liner for this case, because you need to know which keyword matched. An explicit loop is your best bet:

```<code>for file in os.listdir(directory):
    filename = os.fsdecode(file)
    ext = Path(file).suffix
    for keyword in keywords:
      if keyword in filename: # this tests for substrings
        filepath = os.path.join(directory, filename, ext)
        dict[keyword] = filepath
        break
</code>```

Body:
I have a list of keywords and I want to go through a directory looking for filename that contain the keyword. If found, binds the matching keyword and file path to a dictionary.

keywords = ['mon', 'tue', 'wed']
dict = {}

directory = os.fsencode(r"my_dir")

for file in os.listdir(directory):
  filename = os.fsdecode(file)
  ext = Path(file).suffix

  if filename in keywords:
    filepath = os.path.join(directory, filename, ext)
    dict[keyword] = filepath

So at the end I want something like this:

{'mon': 'F:\mon_001.txt', 'tue': 'F:\tue_999.txt', 'wed': 'F\wed_123.txt'}

Now how do I find the match?

Body:
There isn't a nice one-liner for this case, because you need to know which keyword matched. An explicit loop is your best bet:

for file in os.listdir(directory):
    filename = os.fsdecode(file)
    ext = Path(file).suffix
    for keyword in keywords:
      if keyword in filename: # this tests for substrings
        filepath = os.path.join(directory, filename, ext)
        dict[keyword] = filepath
        break


问:
EventEmitter: how to send the result back from the event handler to the "host" component
I have a child component with an @Output parameter:

```<code>@Output updateThis: EventEmitter<any> = new EventEmitter<any>;
</code>```

And:

```<code>this.updateThis.emit(myObject);
</code>```

I have a parent component that handles the event. It then calls a service to update the object:

```<code><my-component (updateThis)="onUpdateThis($event)" />
</code>```

And this is my question. After the parent component tries to modify the object, I need to signal the child component whether it could update it or not (i.e. whether the service threw an error or not).

How could I signal the result back to the child component? One idea is to add a new property to myObject (i.e. hasUpdateError). But are there any other ways? For example, I have seen that EventEmitter has a subscribe method, but I wouldn't know how to use it in this case.

答:
A shared service would be nice perhaps with observables. So, when the parent component receives the event from the child component, you could have a public set method to change the state of the Subject with .next. The child component would subscribe to the Observable of that Subject to get the new state.

It is explained quite nicely here https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service. The same logic can be applied for any component and not only for child-parent.

Body:
I have a child component with an @Output parameter:

@Output updateThis: EventEmitter<any> = new EventEmitter<any>;

And:

this.updateThis.emit(myObject);

I have a parent component that handles the event. It then calls a service to update the object:

<my-component (updateThis)="onUpdateThis($event)" />

And this is my question. After the parent component tries to modify the object, I need to signal the child component whether it could update it or not (i.e. whether the service threw an error or not).

How could I signal the result back to the child component? One idea is to add a new property to myObject (i.e. hasUpdateError). But are there any other ways? For example, I have seen that EventEmitter has a subscribe method, but I wouldn't know how to use it in this case.


问:
frequency table for all columns in pandas
I want to run frequency table on each of my variable in my df.

```<code>def frequency_table(x):
    return pd.crosstab(index=x,  columns="count")

for column in df:
    return frequency_table(column)
</code>```

I got an error of 'ValueError: If using all scalar values, you must pass an index'

How can i fix this?

Thank you!

答:
You aren't passing any data. You are just passing a column name.

```<code>for column in df:
    print(column) # will print column names as strings
</code>```

try

```<code>ctabs = {}
for column in df:
    ctabs[column]=frequency_table(df[column])
</code>```

then you can look at each crosstab by using the column name as keys in the ctabs dictionary

Body:
I want to run frequency table on each of my variable in my df.

def frequency_table(x):
    return pd.crosstab(index=x,  columns="count")

for column in df:
    return frequency_table(column)

I got an error of 'ValueError: If using all scalar values, you must pass an index'

How can i fix this?

Thank you!

Body:
You aren't passing any data. You are just passing a column name.

for column in df:
    print(column) # will print column names as strings

try

ctabs = {}
for column in df:
    ctabs[column]=frequency_table(df[column])

then you can look at each crosstab by using the column name as keys in the ctabs dictionary


问:
Excel Advanced Filter Very slow to run, but only after autofilter has been run
I have a very difficult issue I have been trying to solve for a few days, I would very much appreciate some help as I have tried to research this issue completely already.
One one sheet I have a database (18 columns and 72,000 rows) in 32 Bit Excel 2010, so its a large database. On this sheet I also have some entries to auto-filter some columns, as well as an advance filter. When I run the Advanced filter, the data filters in 1 second exactly. If I run an auto-filter, (via vba macros) then run advance filter afterwords, the Advanced filter takes 60 seconds to run, even after turning autofiltermode to false. Here is what i have tried but no luck

Removing all shapes on the sheet

THere are no comments on the sheet so none to removed

Removing all regular and conditional formatting

Turning off auto-filter mode

Setting all cell text on the sheet to WrappedText = False

Un-protecting the sheet

Un-hiding any rows and columns

Removing any sorting (.sort.sortfields.clear)

What else could cause this code to run 60 times slower but only after autofilter has previously run on the sheet, and how can i return it to that state? Any and all help would be greatly appreciated

答:
In my case I was programmatically creating named ranges for later use, and these named ranges used the .End(xlDown) functionality to find the end of the data set. For e.g:

```<code>Set DLPRange = .Range(.Cells(2, indexHeaders(2)), .Cells(i, indexHeaders(2)).End(xlDown))
DLPRange.Name = "DLPRangeName"
</code>```

... which creates a column range from the starting cell to the end of the document in my case. Originally this 'bad' way of finding the range went unnoticed because the file format of the workbook was .xls and maxed out at 65k rows. When I needed more I forced it to create a workbook in .xlsm format, which has ~1M rows. The filter ran on the whole column even though the huge majority of it was empty, resulting in the huge time overhead.

tl;dr: you've tricked excel into thinking it has a huge amount of data to filter. Untrick it by checking and making sure it's only filtering the range you think it should be filtering.

Body:
In my case I was programmatically creating named ranges for later use, and these named ranges used the .End(xlDown) functionality to find the end of the data set. For e.g:

Set DLPRange = .Range(.Cells(2, indexHeaders(2)), .Cells(i, indexHeaders(2)).End(xlDown))
DLPRange.Name = "DLPRangeName"

... which creates a column range from the starting cell to the end of the document in my case. Originally this 'bad' way of finding the range went unnoticed because the file format of the workbook was .xls and maxed out at 65k rows. When I needed more I forced it to create a workbook in .xlsm format, which has ~1M rows. The filter ran on the whole column even though the huge majority of it was empty, resulting in the huge time overhead.

tl;dr: you've tricked excel into thinking it has a huge amount of data to filter. Untrick it by checking and making sure it's only filtering the range you think it should be filtering.


答:
All you need to do is to start the timer.

```<code>this.timer2.Start();
</code>```

However, you can also cleanup your code so it ends up looking like this:

```<code>private void button2_Click(object sender, EventArgs e)
{
    if (chbRepeat.Checked)
    {
        this.timer2.Start();
    }
    else
    {
        this.timer2.Stop();
        this.SendMail();
    }
}

private void timer2_Tick(object sender, EventArgs e)
{
    this.SendMail();
}

private void SendMail()
{
    MailHelper zmienna = new MailHelper();
    zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
}
</code>```

Title: C# Forms. How to connect send button with checkbox?

Body:
I have a button that sends mail on click but I want it to send mail every time timer tick occurs and I use checkbox to tell the program it's suppose to send every 5 minutes. What should I write in if loop to make it execute what's in timer2_Tick? Else just sends mail once after clicking the button.

  private void button2_Click(object sender, EventArgs e)
    {
        if (chbRepeat.Checked)
        {

        }
        else
        {
            MailHelper zmienna = new MailHelper();
            zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
        }

    }

    private void chbRepeat_CheckedChanged(object sender, EventArgs e)
    {
        MailHelper zmienna = new MailHelper();
        zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
    }

    private void timer2_Tick(object sender, EventArgs e)
    {

        MailHelper zmienna = new MailHelper();
        zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
    }
}

Body:
All you need to do is to start the timer.

this.timer2.Start();

However, you can also cleanup your code so it ends up looking like this:

private void button2_Click(object sender, EventArgs e)
{
    if (chbRepeat.Checked)
    {
        this.timer2.Start();
    }
    else
    {
        this.timer2.Stop();
        this.SendMail();
    }
}

private void timer2_Tick(object sender, EventArgs e)
{
    this.SendMail();
}

private void SendMail()
{
    MailHelper zmienna = new MailHelper();
    zmienna.wyslijMaila(tbAdresat.Text, tbTemat.Text, tbTresc.Text);
}


问:
How Do I Let A Button Create A Countdown Timer, And Then Whenever It Is Clicked Again Add Time To The Timer?
I've got this button and when it is clicked it creates a timer.

The Problem is, it creates a timer every click.

What I wanted this button to do was to on the initial click, create a timer, and then on all subsequent clicks add five seconds to the myTime variable, until the timer ran out.

How would I remedy this?

This is the code that is executed when then button is clicked:

```<code>    myTime = myTime + 5000
    new CountDownTimer(myTime, 1000) {

        public void onTick(long millisUntilFinished) {
            myButton.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            myButton.setText("done!");
        }
    }.start();
</code>```

答:
You will need to delete the timer and restart it.  Capture the milliseconds of the last tick and add your 5 seconds to that. Make the ticks smaller so you don't lose a lot of time.</p>

```<code>CountDownTimer myTimer = null;
long myTime = STARTING_TIME_IN_MILLIS;
...
// In the button click action performed event

if (myTimer != null) {
    myTimer.cancel();  // Cancel the existing timer
    myTime = myTime + 5000;  // Add five seconds to the remaining time.
}
// Start a new timer with the remaining time as the starting point.
myTimer = new CountDownTimer(myTime, 100) {
        public void onTick(long millisUntilFinished) {
            myButton.setText("seconds remaining: " + millisUntilFinished / 1000);
            // Save the remaining time
            myTime = millisUntilFinished;
        }

        public void onFinish() {
            myButton.setText("done!");
        }
}.start();
</code>```

Body:
I've got this button and when it is clicked it creates a timer.

The Problem is, it creates a timer every click.

What I wanted this button to do was to on the initial click, create a timer, and then on all subsequent clicks add five seconds to the myTime variable, until the timer ran out.

How would I remedy this?

This is the code that is executed when then button is clicked:

    myTime = myTime + 5000
    new CountDownTimer(myTime, 1000) {

        public void onTick(long millisUntilFinished) {
            myButton.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            myButton.setText("done!");
        }
    }.start();

Body:
You will need to delete the timer and restart it.  Capture the milliseconds of the last tick and add your 5 seconds to that. Make the ticks smaller so you don't lose a lot of time.

CountDownTimer myTimer = null;
long myTime = STARTING_TIME_IN_MILLIS;
...
// In the button click action performed event

if (myTimer != null) {
    myTimer.cancel();  // Cancel the existing timer
    myTime = myTime + 5000;  // Add five seconds to the remaining time.
}
// Start a new timer with the remaining time as the starting point.
myTimer = new CountDownTimer(myTime, 100) {
        public void onTick(long millisUntilFinished) {
            myButton.setText("seconds remaining: " + millisUntilFinished / 1000);
            // Save the remaining time
            myTime = millisUntilFinished;
        }

        public void onFinish() {
            myButton.setText("done!");
        }
}.start();


问:
Generate Binary Data Array From a Range of Numbers
I need to create Boolean/Binary arrays with rows representing the binary form of each number in given a range. Each column hold values for a given bit position. The range is determined by the bit-width and binary encoding scheme. Then I need to count the number of cells in a column that do not match the preceding cell.

I believe the counting process is simply XORing the array with itself shifted down one row. The sum of each column in the XOR result is my transition count.

I need to do this for each combination of [signed, unsigned] values encoded as [hexadecimal, octal, decimal]. Mismatches between the encoding scheme and available bits results in unusable bits.

 e.g. A 4-bit unsigned octal array would still only have 8 rows. However, if it is signed then that 4th bit is used for sign and the array is the full 16 rows.

The ultimate goal is to create labeled set of summary n-grams for the number of transitions at each bit position for various bit widths, encoding, and use of sign. The summary n-gram for example 1 would be {3-bit, octal, unsigned, [1, 3, 7]}. The summary n-gram for example 3 is {4-bit, octal, signed, [1, 2, 6, 13]}. Example 4 is {4-bit, hexadecimal, signed, [1, 2, 6, 13]}.

Examples:

1) 8x3 Binary array of all possible 3-bit unsigned octal values:

0   0   0

0   0   1

0   1   0

0   1   1

1   0   0

1   0   1

1   1   0

1   1   1

2) 8x4 Binary array of all possible 4-bit unsigned octal values:

Same as #1 except with an additional leftmost column of all zeros

3) 16x4 Binary array of all possible 4-bit signed octal values:

Note: It's ok to double count zero (-0 and +0)
1   1   1   1

1   1   1   0

1   1   0   1

1   1   0   0

1   0   1   1

1   0   1   0

1   0   0   1

1   0   0   0

0   0   0   0

0   0   0   1

0   0   1   0

0   0   1   1

0   1   0   0

0   1   0   1

0   1   1   0

0   1   1   1

4) 16x4 Binary array of all possible 4-bit signed hexadecimal values:

Same as #3

Body:
You can use np.unpackbits, for example

np.unpackbits(np.arange(8).astype(np.uint8)[:, None], axis = 1)

Output:

array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 1],
       [0, 0, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1]], dtype=uint8)

Slice off unwanted zeros:

np.unpackbits(np.arange(8).astype(np.uint8)[:, None], axis = 1)[:, -3:]

Result:

array([[0, 0, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 1, 1],
       [1, 0, 0],
       [1, 0, 1],
       [1, 1, 0],
       [1, 1, 1]], dtype=uint8)

Use modulo for signed values:

np.unpackbits((np.arange(-4, 4)%8).astype(np.uint8)[:, None], axis = 1)[:, -3:]

Or view casting from signed to unsigned:

np.unpackbits(np.arange(-4, 4).astype(np.int8).view(np.uint8)[:, None], axis = 1)[:, -3:]

Result:

array([[1, 0, 0],
       [1, 0, 1],
       [1, 1, 0],
       [1, 1, 1],
       [0, 0, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 1, 1]], dtype=uint8)

Transition count:

x = np.unpackbits(np.arange(-4, 4).astype(np.int8).view(np.uint8)[:, None], axis = 1)[:, -3:]
np.abs(np.diff(x.view(np.int8), axis=0)).sum(axis=1)

Result:

array([1, 2, 1, 3, 1, 2, 1])

Or using your xor method:

(x[1:]^x[:-1]).sum(axis=1)

Result:

array([1, 2, 1, 3, 1, 2, 1], dtype=uint64)


答:
You're making this more complicated than it needs to be:

```<code>import os

keywords = ['mon', 'tue', 'wed']

directory = "my_dir"

result = {}  # dict store our results

for filename in os.listdir(directory):
    for keyword in keywords:
        if keyword in filename:
            result[keyword] = os.path.join(directory, filename)
</code>```

This doesn't handle duplicates, however. If you want to store all matching filenames just initialize result as collections.defaultdict(list) and then when setting the found keyword use: result[keyword].append(os.path.join(directory, filename))

Title: To check if filename has substring of a word in a list

Body:
You're making this more complicated than it needs to be:

import os

keywords = ['mon', 'tue', 'wed']

directory = "my_dir"

result = {}  # dict store our results

for filename in os.listdir(directory):
    for keyword in keywords:
        if keyword in filename:
            result[keyword] = os.path.join(directory, filename)

This doesn't handle duplicates, however. If you want to store all matching filenames just initialize result as collections.defaultdict(list) and then when setting the found keyword use: result[keyword].append(os.path.join(directory, filename))


问:
Binary data from AWS Api gateway
I just set-up an API gateway (AWS) to return binary data (image/png).
My API was read and decode base 64 successful from lambda, then return a binary data, but it can not display on my browser.
This is my gateway log:

When I request from the postman, it cannot be displayed, and response is base64 data:

Can anyone help me for this case?
Thank you!

答:
When you are getting an image from the browser, the browser will set the accept header to something like, Accept: image/webp,image/apng,image/*,*/*;q=0.8, and API Gateway will only pick the first value from the Accepts header.

If the first value matches the pattern in the binaryMediaTypes, API Gateway will consider it as binary data so it will be converted from base64 String to binary data or pass through the binary data.

If you don't have the behavior changes based on the Accepts header from the client/browsers, you can always set the contentHandling property to CONVERT_TO_BINARY on the integration response, then API Gateway will ignore the Accepts header.

I suggest that you can put image/* to the binaryMediaTypes on the API, then re-deploy the API and try again on the browsers. It should be returned as binary data.

Title: Binary data from AWS Api gateway


问:
How center the text between the limits of the picture
I'm doing a tool to help in a game. The original game looks like this:

I was able to do the elixir number on the purple drop on the top-left. The transparent label to show the Level. (still need to work with the right colors based in card rarity).

But cant make the label center on the bottom and if possible looks like inside the border instead of above the whole picture.

I was trying following this question CSS center text (horizontally and vertically) inside a div block but haven't be able to make it work.

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div></code>```

答:
There are a few things you need to take into consideration.

Centralising this element

To address your issue of centralising this element with a couple of methods:

Option 1.

You can make the entire span width 100% and center the text within it by adding this to #header-content:

```<code>width: 100%;
display: block;
text-align:center;
</code>```

As shown here: https://codepen.io/anon/pen/RjmMjQ

Option 2.

You can remove the absolute positioning, use display:inline-block, and, adding text-align:center; on the parent element like so:
https://codepen.io/anon/pen/wPbmrQ

Option 3.

If the element is position:absolute; you can also use:

```<code>left: 50%;
transform: translateX(-50%);
</code>```

Positioning the element relative to an image:

You also said you would like this element to be positioned inside the border. Because this border is set on the image itself, you will need to position your element so it is relative to the image.

To make sure everything lines up correctly with padding we need to set the following, otherwise padding & css borders are not included in any width you set.:

```<code>*{
  box-sizing: border-box;
}
</code>```

Then you need to get the exact position right for aligning you element with the image, these seem to work right:

```<code>width: 170px;
bottom: 18px;
left:50%;
transform: translateX(-50%);
border-radius: 0 0 12px 12px;
</code>```

This is done for you here:
https://codepen.io/anon/pen/YEbMYB

Body:
I'm doing a tool to help in a game. The original game looks like this:

I was able to do the elixir number on the purple drop on the top-left. The transparent label to show the Level. (still need to work with the right colors based in card rarity).

But cant make the label center on the bottom and if possible looks like inside the border instead of above the whole picture.

I was trying following this question CSS center text (horizontally and vertically) inside a div block but haven't be able to make it work.

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}

   4
   Level 2

Body:
There are a few things you need to take into consideration.

Centralising this element

To address your issue of centralising this element with a couple of methods:

Option 1.

You can make the entire span width 100% and center the text within it by adding this to #header-content:

width: 100%;
display: block;
text-align:center;

As shown here: https://codepen.io/anon/pen/RjmMjQ

Option 2.

You can remove the absolute positioning, use display:inline-block, and, adding text-align:center; on the parent element like so:
https://codepen.io/anon/pen/wPbmrQ

Option 3.

If the element is position:absolute; you can also use:

left: 50%;
transform: translateX(-50%);

Positioning the element relative to an image:

You also said you would like this element to be positioned inside the border. Because this border is set on the image itself, you will need to position your element so it is relative to the image.

To make sure everything lines up correctly with padding we need to set the following, otherwise padding & css borders are not included in any width you set.:

*{
  box-sizing: border-box;
}

Then you need to get the exact position right for aligning you element with the image, these seem to work right:

width: 170px;
bottom: 18px;
left:50%;
transform: translateX(-50%);
border-radius: 0 0 12px 12px;

This is done for you here:
https://codepen.io/anon/pen/YEbMYB


问:
Openflow : Creating a flow Tee
I want to create a flow Tee in a switch to send packets to an IDS.

That is, I want the following effects:

When packet comes into the switch match on source MAC.

If MAC matches make two copies of the packet:

For one of the copies, rewrite the target IP address and goto table 2.

For another copy Just goto table 2 without rewriting anything.

What is the best way to achieve this using OpenFlow?

Can a single instruction have multiple goto targets so the packet and a copy of it gets sent to two different tables?

Ranga.

答: I dug around and discovered multiple goto in a single flow is forbidden but you can have a goto and an output to a port. That is how you would create a flow tee.</p>

Title: Openflow : Creating a flow Tee


问:
Change color of labels on x-axis of a Google Chart timeline view
I'm trying to change the color of the black labels on the x-axis.  Now they're black, which don't go well with the background.  In the documentation I only found: rowLabelStyle or barLabelStyle.  How can I change the color of the labels on the x-axis?

答:
By using this CSS:

```<code>#timeline text {
  fill: #dddada;
}
</code>```

The text appears light.

Body:
By using this CSS:

#timeline text {
  fill: #dddada;
}

The text appears light.


问:
How to use a Class with a Collection of Controls
I tried adapting the solution in the link below to make a collection of text boxes allow numbers only.  I get no error but the class just doesn't apply to the textboxes.

Excel VBA Userform - Execute Sub when something changes

Class Module

```<code>Public WithEvents TextGroup As MSForms.TextBox

Public Property Set Control(tb As MSForms.TextBox)
    Set TextGroup = tb
End Property

Private Sub TextGroup_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii

Case 48 To 57
Case Else
KeyAscii = 0
End Select
End Sub
</code>```

UserForm

```<code>Dim tbCollection As Collection

Private Sub UserForm_Initialize()
    Dim obj As clsTextBox
    Dim ctrl As Control

    Set tbCollection = New Collection
        tbCollection.Add Me.tbAC
        tbCollection.Add Me.tbCR
        tbCollection.Add Me.tbHP

    For Each ctrl In tbCollection
        Set obj = New clsTextBox
        Set obj.Control = ctrl
    Next

End Sub
</code>```

答:
You need to put the obj objects in the collection, not the controls themselves

Untested:

```<code>Dim tbCollection As Collection

Private Sub UserForm_Initialize()
    Dim obj As clsTextBox
    Dim arr
    Dim ctrl

    Set tbCollection = New Collection

    arr = Array(Me.tbAC, Me.tbCR, Me.tbHP) '<< edit: no Set

    For Each ctrl in arr
        Set obj = New clsTextBox
        Set obj.Control = ctrl
        tbCollection.Add obj
    Next

End Sub
</code>```

Body:
I tried adapting the solution in the link below to make a collection of text boxes allow numbers only.  I get no error but the class just doesn't apply to the textboxes.

Excel VBA Userform - Execute Sub when something changes

Class Module

Public WithEvents TextGroup As MSForms.TextBox

Public Property Set Control(tb As MSForms.TextBox)
    Set TextGroup = tb
End Property

Private Sub TextGroup_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii

Case 48 To 57
Case Else
KeyAscii = 0
End Select
End Sub

UserForm

Dim tbCollection As Collection

Private Sub UserForm_Initialize()
    Dim obj As clsTextBox
    Dim ctrl As Control

    Set tbCollection = New Collection
        tbCollection.Add Me.tbAC
        tbCollection.Add Me.tbCR
        tbCollection.Add Me.tbHP

    For Each ctrl In tbCollection
        Set obj = New clsTextBox
        Set obj.Control = ctrl
    Next

End Sub

Body:
You need to put the obj objects in the collection, not the controls themselves

Untested:

Dim tbCollection As Collection

Private Sub UserForm_Initialize()
    Dim obj As clsTextBox
    Dim arr
    Dim ctrl

    Set tbCollection = New Collection

    arr = Array(Me.tbAC, Me.tbCR, Me.tbHP) '<< edit: no Set

    For Each ctrl in arr
        Set obj = New clsTextBox
        Set obj.Control = ctrl
        tbCollection.Add obj
    Next

End Sub


问:
Finding screen elements in appium(iOS) using contains
I am doing QA and recently started using appium and cucumber to automate some tests and am still new to this.

I succeeded in what I wanted to automate using some functions like this one.

```<code>def function(element_name)
    find_element(:xpath,
                 '//XCUIElementTypeOther[@name="' + element_name + '"]'
                ).click
end
</code>```

This works for what I want, but now I am trying to redo the same functions but using contains. Something like this

```<code>def function(element_name)
  find_element(:xpath,
               '//*[contains(text(), element_name)]'
              ).click
end
</code>```

What I'm getting is

An element could not be located on the page using the given search parameters.

I think I am just not using contains the right way but I am really not sure.

答:
Xpath is not a good way for searching elements in Appium/XCUITest as it is often too slow and might not work as you expect it to work (your case with contains).

Instead you should you try XCUITest native locator strategies: iOSNsPredicate or iOSClassChain, e.g.

```<code>driver.find_element_by_ios_predicate("label contains 'Some text'")
</code>```

You can check more examples here: python client tests, java client tests

ContentLicense: CC BY-SA 4.0

Body:
I am doing QA and recently started using appium and cucumber to automate some tests and am still new to this.

I succeeded in what I wanted to automate using some functions like this one.

def function(element_name)
    find_element(:xpath,
                 '//XCUIElementTypeOther[@name="' + element_name + '"]'
                ).click
end

This works for what I want, but now I am trying to redo the same functions but using contains. Something like this

def function(element_name)
  find_element(:xpath,
               '//*[contains(text(), element_name)]'
              ).click
end

What I'm getting is

An element could not be located on the page using the given search parameters.

I think I am just not using contains the right way but I am really not sure.

Body:
Xpath is not a good way for searching elements in Appium/XCUITest as it is often too slow and might not work as you expect it to work (your case with contains).

Instead you should you try XCUITest native locator strategies: iOSNsPredicate or iOSClassChain, e.g.

driver.find_element_by_ios_predicate("label contains 'Some text'")

You can check more examples here: python client tests, java client tests


问:
ActiveRecord queries: Accessing outer field in subquery
I'm confused at how to do an active record join. I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

```<code>class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses
  validates :response_limit, presence: true

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false
</code>```

In plain English, I'd like to create a query that given a query, returns all tasks that:

Has a Response count less than the :response_limit field in Task

The User has not responded to already.

I'm able to satisfy #2 with this nested query, which I got from an earlier question.

```<code>Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))
</code>```

However, I'm having difficulty satisfying the first. I took at stab at it and got this:

```<code>Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id])).where('response_limit > (?)', Response.where(task_id:task.id).count)
</code>```

My issue is that I'm not sure how to get the task_id from the outer query into the Response subquery.

答:
you can the number of responses to a task by

```<code>    Task.response.count
</code>```

then simply compare it with the task's response_limit

Body:
I'm confused at how to do an active record join. I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses
  validates :response_limit, presence: true

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false

In plain English, I'd like to create a query that given a query, returns all tasks that:

Has a Response count less than the :response_limit field in Task

The User has not responded to already.

I'm able to satisfy #2 with this nested query, which I got from an earlier question.

Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))

However, I'm having difficulty satisfying the first. I took at stab at it and got this:

Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id])).where('response_limit > (?)', Response.where(task_id:task.id).count)

My issue is that I'm not sure how to get the task_id from the outer query into the Response subquery.

Body:
you can the number of responses to a task by

    Task.response.count

then simply compare it with the task's response_limit


问:
UITapGestureRecognizer unrecognized selector sent to instance
I've searched for solutions to this problem but couldn't find anything that seems to address it in my case. I'm getting the above exception from a UITapGestureRecognizer.

Here's the simplified code:

```<code>import UIKit;

class ViewController : UIViewController, UIScrollViewDelegate
{
    @IBOutlet weak var scrollView:UIScrollView!;
    var imageView:UIImageView!;

    override func viewDidLoad()
    {
        super.viewDidLoad();

        ... set up imageView/scrollView here ...

        let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "onScrollViewDoubleTapped");
        doubleTapRecognizer.numberOfTapsRequired = 2;
        doubleTapRecognizer.numberOfTouchesRequired = 1;
        scrollView.addGestureRecognizer(doubleTapRecognizer);
    }

    func onScrollViewDoubleTapped(recognizer:UITapGestureRecognizer)
    {
    }
}
</code>```

Can anyone tell what is wrong with this code? It seems all correct to me. I suspect that it has to do with assigning ViewController as delegate to scrollView (or vice versa)? However the ViewController is set as the delegate to scrollView. But maybe it's something else that causes this error?

答:
Swift 4 using #selector.

```<code>let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSelectItem(sender:)))

@objc func didSelectItem(sender: AnyObject?) {
    print("didSelectItem: \(sender)")
}
</code>```

Body:
I've searched for solutions to this problem but couldn't find anything that seems to address it in my case. I'm getting the above exception from a UITapGestureRecognizer.

Here's the simplified code:

import UIKit;

class ViewController : UIViewController, UIScrollViewDelegate
{
    @IBOutlet weak var scrollView:UIScrollView!;
    var imageView:UIImageView!;

    override func viewDidLoad()
    {
        super.viewDidLoad();

        ... set up imageView/scrollView here ...

        let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "onScrollViewDoubleTapped");
        doubleTapRecognizer.numberOfTapsRequired = 2;
        doubleTapRecognizer.numberOfTouchesRequired = 1;
        scrollView.addGestureRecognizer(doubleTapRecognizer);
    }

    func onScrollViewDoubleTapped(recognizer:UITapGestureRecognizer)
    {
    }
}

Can anyone tell what is wrong with this code? It seems all correct to me. I suspect that it has to do with assigning ViewController as delegate to scrollView (or vice versa)? However the ViewController is set as the delegate to scrollView. But maybe it's something else that causes this error?

Body:
Swift 4 using #selector.

let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSelectItem(sender:)))

@objc func didSelectItem(sender: AnyObject?) {
    print("didSelectItem: \(sender)")
}


问:
WebRTC browser-to-browser
I am trying to use WebRTC to implement browser to browser communication.

I want to allow communication between two browsers running on two different computers in the same LAN.

Can somebody confirm is this possible and if so, how.

I tried looking up the demos and seems they all have examples for application running in the same page. But I would like to connect to a peer computer using some IP address.

Regards

答: Yes, it is possible to create a Peer to pear connection using PEERJS. PeerJS simplifies WebRTC peer-to-peer data, video. PeerJS wraps the browser's WebRTC implementation to provide a complete, configurable, and easy-to-use peer-to-peer connection API within a LAN Network. PEERJS</p>

Title: WebRTC browser-to-browser


问:
How do I auto scale down a font in a Text widget to fit the max number of lines?
I'm trying to use BoxFit.scaleDown in a FittedBox's fit property to scale the font down in a Text widget to accommodate strings of varying length.

However, the below code will scale down the entire string and make it fit on one line, For the below example, I would like the font scaled down so that the string can fit on two lines (per maxLines property of the Text widget).

```<code>import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Multi-Line Label Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Multi-Line Label Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final textStyle = const TextStyle(fontSize: 28.0);
    final text =
        'Lorem Ipsum is simply dummy text of the printing and typesetting'
        'industry. Lorem Ipsum has been the industry\'s standard dummy text'
        'ever since the 1500s, when an unknown printer took a galley of type'
        'and scrambled it to make a type specimen book.';
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new FittedBox(
              fit: BoxFit.scaleDown,
              child: new Text(
                text,
                maxLines: 2,
                style: textStyle,
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
We got 2 ready-to-use solutions to this depending on the constraints you want to have.

1. Scale only

This solution works if you like how the layout looks on some reference screen size, want to treat the text area as a box and just scale up or down the entire box given other sized screens.

Take a reference screen. Lay everything out as intended. Find out the size of the box containing the text (by showing the render tree by pressing 't' during debug for instance). Then wrap the text containing box with a SizedBox of the same size as measured. Then wrap that with your FittedBox.

The restriction is basically that your text is laid out exactly the same way on all screens and you'll have the same aspect ratio for the text box.

2. Multiple references

Given a parent with variable size, first use a LayoutBuilder to get the parent's size during runtime, and then manually adjust the font size in the child text widget to make sure it fits.

The text layout is more fluid and the containing box can have different aspect ratios, but you'd have to check on as many screens sizes as the font size switches you have. Though it's easy to make sure that the text doesn't overflow at any screen size using widget tests

We can also create more complex but automatic means if there are more concrete examples of generalized use cases involving dependent font scaling

Body:
I'm trying to use BoxFit.scaleDown in a FittedBox's fit property to scale the font down in a Text widget to accommodate strings of varying length.

However, the below code will scale down the entire string and make it fit on one line, For the below example, I would like the font scaled down so that the string can fit on two lines (per maxLines property of the Text widget).

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Multi-Line Label Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Multi-Line Label Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final textStyle = const TextStyle(fontSize: 28.0);
    final text =
        'Lorem Ipsum is simply dummy text of the printing and typesetting'
        'industry. Lorem Ipsum has been the industry\'s standard dummy text'
        'ever since the 1500s, when an unknown printer took a galley of type'
        'and scrambled it to make a type specimen book.';
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new FittedBox(
              fit: BoxFit.scaleDown,
              child: new Text(
                text,
                maxLines: 2,
                style: textStyle,
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}


问:
Unable to pull from GCR registry using docker engine-api and long lived JSON file
In the advanced authentication methods documentation for google cloud container registry explains a method for login to the registry using a JSON Key file with the docker cli, this just works fine

$ docker login -u _json_key -p "$(cat keyfile.json)" https://gcr.io

However I'm trying to use that same keyfile.json file to login to the registry using the golang docker/engine-api libraries, I have some working code that this seems to be authenticating fine into other registryies, but always providing a file with the following structure

```<code>{
  "auths": {
    "cr.whatever.com": {
      "password": "PASSWORD",
      "username": "registry"
    }
  }
}
</code>```

By passing that Unmarshal file into ImageBuildOptions function here to then be consumed here

However is not working when using the keyfile.json or a working config.json ...

The docker documentation states that a JSON base64 encoded object with username and password should be used as described here into the Header Parameters section.

I've tried multiple option to produce a file that can be successfully consumed into the docker X-Registry-Config header without much luck...

Any help/hint would be much appreciated.

Thanks!

答:
I think the issue is that 'config' is an overloaded term. Looks like X-Registry-Config contains a base64-encoded version of the JSON-encoded value of options.AuthConfigs, rather than the full docker config file. If you only want to authenticate for https://gcr.io, your JSON input should be:

```<code>{
  "gcr.io": {
    "username": "_json_key",
    "password": "{contents of keyfile.json}"
  }
}
</code>```

Or, if you're willing to use Docker's golang libs:

```<code>import (
    "encoding/base64"
    "encoding/json"
    "net/http"

    "github.com/docker/engine-api/types"
)

def addDockerAuthsHeader(keyfile_contents string, headers http.Header) error {
    authConfigs := map[string]types.AuthConfig{
        "gcr.io": {
            Username: "_json_key",
            Password: keyfile_contents
        }
    }

    buf, err := json.Marshal(authConfigs)
    if err != nil {
        return err
    }

    headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))

    return nil
}
</code>```

Generating keyfile_contents is left as an exercise for the reader :)

Body:
In the advanced authentication methods documentation for google cloud container registry explains a method for login to the registry using a JSON Key file with the docker cli, this just works fine

$ docker login -u _json_key -p "$(cat keyfile.json)" https://gcr.io

However I'm trying to use that same keyfile.json file to login to the registry using the golang docker/engine-api libraries, I have some working code that this seems to be authenticating fine into other registryies, but always providing a file with the following structure

{
  "auths": {
    "cr.whatever.com": {
      "password": "PASSWORD",
      "username": "registry"
    }
  }
}

By passing that Unmarshal file into ImageBuildOptions function here to then be consumed here

However is not working when using the keyfile.json or a working config.json ...

The docker documentation states that a JSON base64 encoded object with username and password should be used as described here into the Header Parameters section.

I've tried multiple option to produce a file that can be successfully consumed into the docker X-Registry-Config header without much luck...

Any help/hint would be much appreciated.

Thanks!

Body:
I think the issue is that 'config' is an overloaded term. Looks like X-Registry-Config contains a base64-encoded version of the JSON-encoded value of options.AuthConfigs, rather than the full docker config file. If you only want to authenticate for https://gcr.io, your JSON input should be:

{
  "gcr.io": {
    "username": "_json_key",
    "password": "{contents of keyfile.json}"
  }
}

Or, if you're willing to use Docker's golang libs:

import (
    "encoding/base64"
    "encoding/json"
    "net/http"

    "github.com/docker/engine-api/types"
)

def addDockerAuthsHeader(keyfile_contents string, headers http.Header) error {
    authConfigs := map[string]types.AuthConfig{
        "gcr.io": {
            Username: "_json_key",
            Password: keyfile_contents
        }
    }

    buf, err := json.Marshal(authConfigs)
    if err != nil {
        return err
    }

    headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))

    return nil
}

Generating keyfile_contents is left as an exercise for the reader :)


问:
Travis CI build terminated 10 minutes after Mocha v4 tests pass
I'm using Travis CI and Mocha. My tests pass locally with no issues.

When I push to Github the Travis CI process starts, the tests run and successfully pass, then nothing. The Travis console shows nothing for about 10 minutes and then outputs:

No output has been received in the last 10m0s, this potentially indicates a stalled build or something wrong with the build itself.
  Check the details on how to adjust your build configuration on: https://docs.travis-ci.com/user/common-build-problems/#Build-times-out-because-no-output-was-received

My initial thought the issue was due to a faulty test. After removing all tests the Travis CI build completes successfully in about 50 seconds. So I know the build works.

I then added a super simple test - to request my root page and check for a 200 status. Again the test passes locally. The Travis CI build starts, the test passes, then it hangs for 10 minutes and displays the message above.

Additionally, the build was previously working using these same tests. The only thing I can think that changed was I cleared node_modules and ran npm install again.

Currently using Node v8.7.0 with Mocha v4.0.0.

Why does Travis hang and eventually terminate the build even when the tests are passing?

答:
Total newb here, but I recently encountered this exact issue while building a node app. All tests passing but the build would just hang. It was driving me nuts.

Apparently the upgrade from Mocha v3 to Mocha v4 is causing the issue. See here for some folks with the same question on github: https://github.com/mochajs/mocha/issues/3044

For a quick fix, in your package.json file, use mocha --exit.


问:
Keyboard not showing after MFMessageComposeViewController
In an iPhone app I have a UITextView and a button, which lets the user send the content of the UITextView as a text message. The code looks like this:

```<code>MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;

picker.body = textView.text;

[self presentModalViewController:picker animated:YES];
</code>```

Everything works fine, except for when the message is either sent or Cancel is tapped in the MFMessageComposer: The keyboard for the UITextView is not shown anymore, even though the cursor blinks.

I tried a few things, including a [textView resignFirstRepsonder] in both the button code and -viewDidDisappear. [textView becomeFirstResponder] in the MFMessageComposeViewControllerDelegate method or the -viewDidAppear didn't change anything either...

Any ideas?

答:
After the view has disappeared, you need to make your view first responder. Add the MFMessageComposeViewControllerDelegate protocol to your header, then use the following:

```<code>- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    [self dismissModalViewControllerAnimated:YES];
    [self becomeFirstResponder];
}
</code>```

Happy coding,

Zane

Body:
In an iPhone app I have a UITextView and a button, which lets the user send the content of the UITextView as a text message. The code looks like this:

MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;

picker.body = textView.text;

[self presentModalViewController:picker animated:YES];

Everything works fine, except for when the message is either sent or Cancel is tapped in the MFMessageComposer: The keyboard for the UITextView is not shown anymore, even though the cursor blinks.

I tried a few things, including a [textView resignFirstRepsonder] in both the button code and -viewDidDisappear. [textView becomeFirstResponder] in the MFMessageComposeViewControllerDelegate method or the -viewDidAppear didn't change anything either...

Any ideas?

Body:
After the view has disappeared, you need to make your view first responder. Add the MFMessageComposeViewControllerDelegate protocol to your header, then use the following:

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    [self dismissModalViewControllerAnimated:YES];
    [self becomeFirstResponder];
}

Happy coding,

Zane


问:
Add +1 In Front of Each Selected Row of Database
I have a MySQL table containing 10 digit numbers. I need to add +1 in front of each via an UPDATE.

Let's say my SELECT statement looks like this:

```<code>SELECT *
FROM num_data
WHERE number REGEXP '^[0-9]{10}$'
</code>```

How do I add +1 in front of each result of my query above?

答:
Use CONCAT to concatenate strings in MySQL.

```<code>UPDATE num_data
SET number = CONCAT('+1', number)
WHERE number REGEXP '^[0-9]{10}$'
</code>```

Body:
I have a MySQL table containing 10 digit numbers. I need to add +1 in front of each via an UPDATE.

Let's say my SELECT statement looks like this:

SELECT *
FROM num_data
WHERE number REGEXP '^[0-9]{10}$'

How do I add +1 in front of each result of my query above?

Body:
Use CONCAT to concatenate strings in MySQL.

UPDATE num_data
SET number = CONCAT('+1', number)
WHERE number REGEXP '^[0-9]{10}$'