问:
How do I custom the 24 hour start hour and finish hour for line plot? (for example, start at 7:30)
I have a 24 hour data starting from 7:30 today (for example), until 7:30 the next day, because I didn't link the date to the line plot, R sorts the hour starting from 00:00 despite the data starting at 7:30, I am a beginner in R, and I don't know where to begin to even solve this problem, should I try linking the date also to the X axis, or is there a better solution?

My time function somehow didn't work either, it used to work when I was plotting data for 15 minute increments.

```<code>library(chron)
d <- read.csv(file="data.csv", header = T)
t <- times(d$Time)
plot(t,d$MCO2, type="l")
</code>```

Graph created from the 24 hour data I have :

Graph created from a 15 minute data using the same code :

I wanted the outcome to be from 7:30 to 7:30 the next day, but it showed now a decimal number from 0.0 to 1

Here is the link to the data, just in case:
https://www.dropbox.com/s/wsg437gu00e5t08/Data%20210519.csv?dl=0

答:
The question is actually about combining a date column and a time column to create a timestamp containing date AND time. Note that I suggest to process everything as if we are in GMT timezone. You can pick whatever timezone you want, then stick to it.</p>

```<code># use ggplot
library(ggplot2)
# assume everything happens in GMT timezone
Sys.setenv( TZ = "GMT" )

# replicating the data: a measurement result sampled at 1 sec interval
t <- seq(start, end, by = "1 sec")
Time24 <- trimws(strftime(t, format = "%k:%M:%OS", tz="GMT"))
Date <- strftime(t, format = "%d/%m/%Y", tz="GMT")
head(Time24)
head(Date)
d <- data.frame(Date, Time24)
# this is just a random data of temperature
d$temp <- rnorm(length(d$Date),mean=25,sd=5)
head(d)
# the resulting data is as follows
#        Date  Time24     temp
#1 22/05/2019 0:00:00 22.67185
#2 22/05/2019 0:00:01 19.91123
#3 22/05/2019 0:00:02 19.57393
#4 22/05/2019 0:00:03 15.37280
#5 22/05/2019 0:00:04 31.76683
#6 22/05/2019 0:00:05 26.75153

# this is the answer to the question
# which is combining the the date and the time column of the data
# note we still assume that this happens in GMT
t <- as.POSIXct(paste(d$Date,d$Time24,sep=" "), format = "%d/%m/%Y %H:%M:%OS", tz="GMT")

# print the data into a plot
png(filename = "test.png", width = 800, height = 600, units = "px", pointsize = 22 )
ggplot(d,aes(x=t,y=temp)) + geom_line() +
  scale_x_datetime(date_breaks = "3 hour",
                   date_labels = "%H:%M\n%d-%b")
</code>```

Body:
I have a 24 hour data starting from 7:30 today (for example), until 7:30 the next day, because I didn't link the date to the line plot, R sorts the hour starting from 00:00 despite the data starting at 7:30, I am a beginner in R, and I don't know where to begin to even solve this problem, should I try linking the date also to the X axis, or is there a better solution?

My time function somehow didn't work either, it used to work when I was plotting data for 15 minute increments.

library(chron)
d <- read.csv(file="data.csv", header = T)
t <- times(d$Time)
plot(t,d$MCO2, type="l")

Graph created from the 24 hour data I have :

Graph created from a 15 minute data using the same code :

I wanted the outcome to be from 7:30 to 7:30 the next day, but it showed now a decimal number from 0.0 to 1

Here is the link to the data, just in case:
https://www.dropbox.com/s/wsg437gu00e5t08/Data%20210519.csv?dl=0

Body:
The question is actually about combining a date column and a time column to create a timestamp containing date AND time. Note that I suggest to process everything as if we are in GMT timezone. You can pick whatever timezone you want, then stick to it.

# use ggplot
library(ggplot2)
# assume everything happens in GMT timezone
Sys.setenv( TZ = "GMT" )

# replicating the data: a measurement result sampled at 1 sec interval
t <- seq(start, end, by = "1 sec")
Time24 <- trimws(strftime(t, format = "%k:%M:%OS", tz="GMT"))
Date <- strftime(t, format = "%d/%m/%Y", tz="GMT")
head(Time24)
head(Date)
d <- data.frame(Date, Time24)
# this is just a random data of temperature
d$temp <- rnorm(length(d$Date),mean=25,sd=5)
head(d)
# the resulting data is as follows
#        Date  Time24     temp
#1 22/05/2019 0:00:00 22.67185
#2 22/05/2019 0:00:01 19.91123
#3 22/05/2019 0:00:02 19.57393
#4 22/05/2019 0:00:03 15.37280
#5 22/05/2019 0:00:04 31.76683
#6 22/05/2019 0:00:05 26.75153

# this is the answer to the question
# which is combining the the date and the time column of the data
# note we still assume that this happens in GMT
t <- as.POSIXct(paste(d$Date,d$Time24,sep=" "), format = "%d/%m/%Y %H:%M:%OS", tz="GMT")

# print the data into a plot
png(filename = "test.png", width = 800, height = 600, units = "px", pointsize = 22 )
ggplot(d,aes(x=t,y=temp)) + geom_line() +
  scale_x_datetime(date_breaks = "3 hour",
                   date_labels = "%H:%M\n%d-%b")


来源: stackexchange

问:
Search element in array based on another array and change property
I have two array of objects like this:

```<code>const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];
</code>```

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

```<code>officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});
</code>```

But I need to search by array not single element so I've tried this but not succeeded:

```<code>officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});
</code>```

Expected Output:

```<code>  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }
</code>```

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

答:
you can find the item and if found change the name and return the changed item or return item simply (without change)</p>

```<code>officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       if (item.id === item2.id) {
          return { ...item, name: 'Change name for 56' }
       }
   }) || item;
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two array of objects like this:

const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});

But I need to search by array not single element so I've tried this but not succeeded:

officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});

Expected Output:

  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

Body:
you can find the item and if found change the name and return the changed item or return item simply (without change)

officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       if (item.id === item2.id) {
          return { ...item, name: 'Change name for 56' }
       }
   }) || item;
});


问:
How I can read a string of boolean operation and give it a priority?
I have to read a file line like this

```<code>assign x = (c OR (a AND B)) OR (NOT D)
</code>```

Where assign is a keyword that active a method of a class called Logic_gate, that compute and store the result of the boolean operation.

I read this line from the file by getline, and I read this string with a sstream object istringstream, but I don't know how to give a priority to the operation. I.e I want to do the first the operation between the bracket,then the other one.

In this example I want:

```<code>-A AND B
-(c OR (a AND B))
-(NOT D)
-(c OR (a AND B)) OR (NOT D)
-Store result in x
</code>```

答:
It sounds as though you are looking for a way to convert an infix expression into postfix notation? This lets you build a stack of operations that is trivially easy to evaluate. There's a really ancient expression parser that probably won't compile anymore, but that does the infix to postfix conversion (see the Parse function):  http://www.flipcode.com/archives/Expression_Compiler_Evaluator.shtml

If you know the operator precedence of or/not/and/(), then it should be pretty simple. (You may notice the order of if/else statements in Parse function matches the operator precedence of C++).

.... Obviously I'm not suggesting you compile this down to x86 machine code!! It was just some code I knew had some relevance :)

An extremely simple example:

```<code>// infix
x = A AND B

// postfix
x = A B AND

// to evaluate
A is a variable, push onto stack
B is a variable, push onto stack
AND is a binary op, so compute:
   stack[last - 1] = stack[last - 1] AND stack[last]
pop a value from the stack

// stack now contains 1 value, the result
</code>```

The original expression:

```<code>// infix
x = (c OR (a AND B)) OR (NOT D)

// postfix
x = A B AND C OR D NOT OR

// evaluated like so:
A is a var, push on stack
B is a var, push on stack
AND - perform op, pop value from stack, store result in stack.top()
C is a var, push on stack
OR - perform op, pop value from stack, store result in stack.top()
D is a var, push on stack
NOT is unary. store !stack.top() in stack.top(). DO NOT POP!
OR - perform op, pop value from stack, store result in stack.top()

// the stack should contain the result.
</code>```

Body:
I have to read a file line like this

assign x = (c OR (a AND B)) OR (NOT D)

Where assign is a keyword that active a method of a class called Logic_gate, that compute and store the result of the boolean operation.

I read this line from the file by getline, and I read this string with a sstream object istringstream, but I don't know how to give a priority to the operation. I.e I want to do the first the operation between the bracket,then the other one.

In this example I want:

-A AND B
-(c OR (a AND B))
-(NOT D)
-(c OR (a AND B)) OR (NOT D)
-Store result in x

Body:
It sounds as though you are looking for a way to convert an infix expression into postfix notation? This lets you build a stack of operations that is trivially easy to evaluate. There's a really ancient expression parser that probably won't compile anymore, but that does the infix to postfix conversion (see the Parse function):  http://www.flipcode.com/archives/Expression_Compiler_Evaluator.shtml

If you know the operator precedence of or/not/and/(), then it should be pretty simple. (You may notice the order of if/else statements in Parse function matches the operator precedence of C++).

.... Obviously I'm not suggesting you compile this down to x86 machine code!! It was just some code I knew had some relevance :)

An extremely simple example:

// infix
x = A AND B

// postfix
x = A B AND

// to evaluate
A is a variable, push onto stack
B is a variable, push onto stack
AND is a binary op, so compute:
   stack[last - 1] = stack[last - 1] AND stack[last]
pop a value from the stack

// stack now contains 1 value, the result

The original expression:

// infix
x = (c OR (a AND B)) OR (NOT D)

// postfix
x = A B AND C OR D NOT OR

// evaluated like so:
A is a var, push on stack
B is a var, push on stack
AND - perform op, pop value from stack, store result in stack.top()
C is a var, push on stack
OR - perform op, pop value from stack, store result in stack.top()
D is a var, push on stack
NOT is unary. store !stack.top() in stack.top(). DO NOT POP!
OR - perform op, pop value from stack, store result in stack.top()

// the stack should contain the result.


问:
Output Range same as input range
I have some history working with VBA, but can't seem to find the solution to this problem.  I found an iteration process to select a cell, do a process, and then select the next cell and do the process again, until NULL.  I am having a problem outputting each of the processes solutions into the next column. Here is what I have:

```<code>Sub Name ()

Dim X As Integer
Dim MyString as String

Application.ScreenUpdating = False
NumRows = Range("D2", Range("D2").End(xlDown)).Rows.Count
Range("D2").Select
For X = 1 To NumRows
    MyString = ActiveCell.Value
    MyString = Right(MyString, Len(MyString)-6)
    Range("I2 to I#").Value = MyString
    ActiveCell.Offset(1,0).Select
Next X

End Sub
</code>```

Range("I2 to I#").Value = MyString is the line that I need help with.  I need it to increment to I3, I4, I5, etc. until it reaches NumRows count.

答:
Another solution is Do Until. You could use this method if you dont have empty cells in the middle of your data.

```<code>Option Explicit

Sub Test()

    Dim StartingPoint As Long

    StartingPoint = 2 'Set the line to begin

    With ThisWorkbook.Worksheets("Sheet1") 'Set the worksheet

        Do Until .Cells(StartingPoint, "D").Value = "" 'Repeat the process until you find empty cell

           .Cells(StartingPoint, "I").Value = Right(.Cells(StartingPoint, "D").Value, Len(.Cells(StartingPoint, "D").Value) - 6)

           StartingPoint = StartingPoint + 1

        Loop

    End With

End Sub
</code>```

Title: Output Range same as input range

Body:
I have some history working with VBA, but can't seem to find the solution to this problem.  I found an iteration process to select a cell, do a process, and then select the next cell and do the process again, until NULL.  I am having a problem outputting each of the processes solutions into the next column. Here is what I have:

Sub Name ()

Dim X As Integer
Dim MyString as String

Application.ScreenUpdating = False
NumRows = Range("D2", Range("D2").End(xlDown)).Rows.Count
Range("D2").Select
For X = 1 To NumRows
    MyString = ActiveCell.Value
    MyString = Right(MyString, Len(MyString)-6)
    Range("I2 to I#").Value = MyString
    ActiveCell.Offset(1,0).Select
Next X

End Sub

Range("I2 to I#").Value = MyString is the line that I need help with.  I need it to increment to I3, I4, I5, etc. until it reaches NumRows count.

Body:
Another solution is Do Until. You could use this method if you dont have empty cells in the middle of your data.

Option Explicit

Sub Test()

    Dim StartingPoint As Long

    StartingPoint = 2 'Set the line to begin

    With ThisWorkbook.Worksheets("Sheet1") 'Set the worksheet

        Do Until .Cells(StartingPoint, "D").Value = "" 'Repeat the process until you find empty cell

           .Cells(StartingPoint, "I").Value = Right(.Cells(StartingPoint, "D").Value, Len(.Cells(StartingPoint, "D").Value) - 6)

           StartingPoint = StartingPoint + 1

        Loop

    End With

End Sub


问:
Scan multibranch now builds every (also unchanged) job
We have setup multiple multibranch pipeline projects. When clicking on the button 'Scan Multibranch Pipeline Now' all jobs are triggered and built again. It does not matter whether or not there are changes, every job will just start building.

When everything is build and manually scan again, it works as expected and only changed jobs are built.

Running on Jenkins 2.164.2.

```<code>Changes detected: master (null -> b95ffd48bf9fd032004e150ae4188cf48d3c28b2)
Scheduled build for branch: master
</code>```

We expect only the changed branches will be built again.

答:
We ran into the same issue some time ago, but then I found this issue:
https://issues.jenkins-ci.org/browse/JENKINS-57588

Can you check if you have the same version of that plugin (Branch API 2.5.0) running in your Jenkins instance?

Upgrading Branch API plugin the newest version 2.5.2 (already fixed in 2.5.1) fixed the problem.

Body:
We have setup multiple multibranch pipeline projects. When clicking on the button 'Scan Multibranch Pipeline Now' all jobs are triggered and built again. It does not matter whether or not there are changes, every job will just start building.

When everything is build and manually scan again, it works as expected and only changed jobs are built.

Running on Jenkins 2.164.2.

Changes detected: master (null -> b95ffd48bf9fd032004e150ae4188cf48d3c28b2)
Scheduled build for branch: master

We expect only the changed branches will be built again.


问:
Android. Controlling zooming speed
I'm creating View that can store, move, zoom and crop a picture. I'm aware about many projects which already done this, so link to other project wouldn't be answer, but i'm not sure that it's possible to achive my request.

So basically i'm using ScaleGestureDetector with ScaleGestureDetector.SimpleOnScaleGestureListener, to scale my Canvas, here's a code:

```<code>private float MIN_SCALE_FACTOR = 0.3f;
private float MAX_SCALE_FACTOR = 10.0f;
private float mScaleFactor = 1.f;
private ScaleGestureDetector mScaleDetector;
private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor *= detector.getScaleFactor();
        mScaleFactor = Math.max(MIN_SCALE_FACTOR, Math.min(mScaleFactor, MAX_SCALE_FACTOR));
        invalidate();
        return super.onScale(detector);
    }
};

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        canvas.save();
        super.onDraw(canvas);
        correctPositionValues();
        canvas.scale(mScaleFactor, mScaleFactor, mPositionX, mPositionY );
        canvas.drawBitmap(mBitmap, mPositionX, mPositionY, null);
        canvas.restore();
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    mScaleDetector.onTouchEvent(event);
}
</code>```

On my phone scale is happening almoust instantly and this looks bad.
Any suggestions highly appreciated

答:
Scale on the previous scale factor:</p>

```<code>private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
    private preScaleFactor = 1f;
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor = preScaleFactor*detector.getScaleFactor();
        mScaleFactor = Math.max(MIN_SCALE_FACTOR, Math.min(mScaleFactor, MAX_SCALE_FACTOR));
        invalidate();
        return super.onScale(detector);
    }

    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
       preScaleFactor = mScaleFactor;
       return true;
    }
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android. Controlling zooming speed

Body:
I'm creating View that can store, move, zoom and crop a picture. I'm aware about many projects which already done this, so link to other project wouldn't be answer, but i'm not sure that it's possible to achive my request.

So basically i'm using ScaleGestureDetector with ScaleGestureDetector.SimpleOnScaleGestureListener, to scale my Canvas, here's a code:

private float MIN_SCALE_FACTOR = 0.3f;
private float MAX_SCALE_FACTOR = 10.0f;
private float mScaleFactor = 1.f;
private ScaleGestureDetector mScaleDetector;
private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor *= detector.getScaleFactor();
        mScaleFactor = Math.max(MIN_SCALE_FACTOR, Math.min(mScaleFactor, MAX_SCALE_FACTOR));
        invalidate();
        return super.onScale(detector);
    }
};

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        canvas.save();
        super.onDraw(canvas);
        correctPositionValues();
        canvas.scale(mScaleFactor, mScaleFactor, mPositionX, mPositionY );
        canvas.drawBitmap(mBitmap, mPositionX, mPositionY, null);
        canvas.restore();
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    mScaleDetector.onTouchEvent(event);
}

On my phone scale is happening almoust instantly and this looks bad.
Any suggestions highly appreciated

Body:
Scale on the previous scale factor:

private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
    private preScaleFactor = 1f;
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor = preScaleFactor*detector.getScaleFactor();
        mScaleFactor = Math.max(MIN_SCALE_FACTOR, Math.min(mScaleFactor, MAX_SCALE_FACTOR));
        invalidate();
        return super.onScale(detector);
    }

    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
       preScaleFactor = mScaleFactor;
       return true;
    }
};


问:
Using a Microsoft access DB .accdb on a linux server with Node.js
So, I got this working on windows easy, and that is not surprising. But I am more concerned about running this on a production linux server.

Is there a way to get the Access Runtime 2013 to work on a linux based system without throwing some weird way of doing it. If not, then I am going to have to rethink my plans.

Just as a code base this is what I am doing:

```<code>const ADODB = require('node-adodb');
ADODB.debug = true;
//Bring in LUT Database
const LUTDB = ADODB.open(
  'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;Persist Security Info=False'
);
LUTDB.query('SELECT * FROM Table1')
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    console.log(err);
  });
</code>```

答:
Nope.

The Access Runtime (as well as the database engine and full application) is only compatible with Windows, and barring Wine stuff/other trickery that's not production-worthy, it plain won't work.

There are third-party ODBC/JDBC drivers for Access out there that do work on Linux, but nothing official from Microsoft.

My recommendation would be: either don't use Access on Linux (best), or try UCanAccess with a JDBC wrapper (not affiliated). Note that the accdb file format has changed a number of times, so you can expect trouble/incompatibilities if you don't use an actively maintained product.

Body:
So, I got this working on windows easy, and that is not surprising. But I am more concerned about running this on a production linux server.

Is there a way to get the Access Runtime 2013 to work on a linux based system without throwing some weird way of doing it. If not, then I am going to have to rethink my plans.

Just as a code base this is what I am doing:

const ADODB = require('node-adodb');
ADODB.debug = true;
//Bring in LUT Database
const LUTDB = ADODB.open(
  'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;Persist Security Info=False'
);
LUTDB.query('SELECT * FROM Table1')
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    console.log(err);
  });


问:
Terraform use existing policy for s3 bucket
In my terraform config I have a policy attached to some roles.

How can I reuse this policy when creating an s3 bucket?

```<code>
resource "aws_iam_policy" "s3-read-access" {
  name   = "my-warehouse-read-access"
  version = "2019-05-28"
  policy = "${data.aws_iam_policy_document.s3-read-access.json}"
}

resource "aws_s3_bucket" "my-warehouse" {
  bucket = "my-bucket"
  acl    = "private"
  policy = "${aws_iam_policy.s3-read-access.arn}"
}

</code>```

Unfortunately, I get an error: Error putting S3 policy: MalformedPolicy: Policies must be valid JSON and the first byte must be '{'.

Seems that policy needs a json config in heredoc-notation, but I have to re-use the existing policy.

How can I reference that policy in s3-bucket creation?

答:
You have multiple ways to achieve that. You can have a policy JSON and reference it in every bucket:

```<code>resource "aws_s3_bucket" "b" {
  bucket = "s3-website-test.hashicorp.com"
  acl    = "public-read"
  policy = "${file("policy.json")}"
}
</code>```

Or you can create a data block:

```<code>data "aws_iam_policy_document" "your_super_amazing_policy" {
 count  = "${length(keys(var.statement))}"

  statement {
    sid       = "CloudfrontBucketActions"
    actions   = ["s3:GetObject"]
    resources = ["*"]
  }
</code>```

And you that on buckets:

```<code>resource "aws_s3_bucket" "private_bucket" {
  bucket = "acme-private-bucket"
  acl = "private"
  policy = "${data.aws_iam_policy_document.your_super_amazing_policy.json}"

  tags {
    Name = "private-bucket"
    terraform = "true"
  }
}
</code>```

Body:
In my terraform config I have a policy attached to some roles.

How can I reuse this policy when creating an s3 bucket?

resource "aws_iam_policy" "s3-read-access" {
  name   = "my-warehouse-read-access"
  version = "2019-05-28"
  policy = "${data.aws_iam_policy_document.s3-read-access.json}"
}

resource "aws_s3_bucket" "my-warehouse" {
  bucket = "my-bucket"
  acl    = "private"
  policy = "${aws_iam_policy.s3-read-access.arn}"
}

Unfortunately, I get an error: Error putting S3 policy: MalformedPolicy: Policies must be valid JSON and the first byte must be '{'.

Seems that policy needs a json config in heredoc-notation, but I have to re-use the existing policy.

How can I reference that policy in s3-bucket creation?

Body:
You have multiple ways to achieve that. You can have a policy JSON and reference it in every bucket:

resource "aws_s3_bucket" "b" {
  bucket = "s3-website-test.hashicorp.com"
  acl    = "public-read"
  policy = "${file("policy.json")}"
}

Or you can create a data block:

data "aws_iam_policy_document" "your_super_amazing_policy" {
 count  = "${length(keys(var.statement))}"

  statement {
    sid       = "CloudfrontBucketActions"
    actions   = ["s3:GetObject"]
    resources = ["*"]
  }

And you that on buckets:

resource "aws_s3_bucket" "private_bucket" {
  bucket = "acme-private-bucket"
  acl = "private"
  policy = "${data.aws_iam_policy_document.your_super_amazing_policy.json}"

  tags {
    Name = "private-bucket"
    terraform = "true"
  }
}


问:
Time Spent by user on a web page + Iframe
I want to measure the time spent by a user on web pages. It's doesn't include the time when a user navigates away from the browser.

I found few open source libraries like Timejs library which can measure the time spent by a user on a web page, but when a user is watching a Youtube video on the page, these libraries don't measure that time.

.

Is there a way to handle this case or any other library which handles this case?

Actually, these libraries fail to calculate the time spent by the user inside an iFrame.What is the best way to know when a user is active in an IFrame?

How does Google/AppNexus/Motomo calculate interaction time? Is there a common design/architecture that they follow?

PS: I am trying to integrate the library with my react App. If there exists any similar method to solve this problem in React. Please let me know in comments/answers.

Thanks in advance

答:
HTML5 Page Visibility API is the answer of your question.

You need to just listen an event as per the browser and it will be triggered every time when user will jump to another tab.

Look to Page Visibility API


问:
Is it possible to use cfn-signal without using cfn-init in my cloudformation template?
I have a cloudformation stack right now that sets up a simple ec2 instance, and installs all of my python packages and files in the user data section. I never even mention cfn-init anywhere in my stack, nor do I have metadata. Is it possible to still use cfn-signal in order to alert my stack that setup of the ec2 instance is not yet done? Or must cfn-signal and cfn-init be used together?

Thank you.

答:
Nope, cfn-init and cfn-signal are two completely separate mechanics and can be used one without the other.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-signal.html

I use cfn-signal extensively in my Snowplow cloudformation template. Chucking here the relevant snippets...

Here's the snippet example of how I call cfn-signal by itself:

```<code>  EventCollectionGroup:
    Type: 'AWS::AutoScaling::AutoScalingGroup'
    Properties:
      LaunchConfigurationName: !Ref EventCollectionLc
    CreationPolicy:
      ResourceSignal:
        Count: 2
        Timeout: PT10M
    UpdatePolicy:
      AutoScalingRollingUpdate:
        MinInstancesInService: 1
        WaitOnResourceSignals: 'true'
        PauseTime: PT10M

  EventCollectionLc:
    Type: 'AWS::AutoScaling::LaunchConfiguration'
    Properties:
      UserData: !Base64
        'Fn::Sub': |
          #!/bin/bash
          docker run -t --rm ${ContainerAwsUtil} cfn-signal -e $? --stack ${AWS::StackName} --resource EventCollectionGroup --region ${AWS::Region}
    UpdatePolicy:
      AutoScalingReplacingUpdate:
        WillReplace: 'true'
</code>```

The above snippet have the extras trimmed out. You can find the template here:

https://github.com/Bit-Clouded/Glenlivet/blob/master/analytics/snowplow.template#L368

As you can see, I actually run the cfn-init in a container itself and do not install the util on the server even.

The docker container definition is here:

```<code>FROM alpine:3.6

RUN apk add --no-cache ca-certificates python py-pip groff less jq curl &&\
    pip install awscli &&\
    pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
</code>```

Again, with extras trimmed. Full file is here:

https://github.com/Bit-Clouded/Angostura/blob/master/utility/aws-util/Dockerfile

In fact, I personally have moved away from cfn-init altogether and moved all required binaries to be pulled in via docker instead. Just a bash script in the UserData section is far cleaner and easier to read.

Body:
Nope, cfn-init and cfn-signal are two completely separate mechanics and can be used one without the other.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-signal.html

I use cfn-signal extensively in my Snowplow cloudformation template. Chucking here the relevant snippets...

Here's the snippet example of how I call cfn-signal by itself:

  EventCollectionGroup:
    Type: 'AWS::AutoScaling::AutoScalingGroup'
    Properties:
      LaunchConfigurationName: !Ref EventCollectionLc
    CreationPolicy:
      ResourceSignal:
        Count: 2
        Timeout: PT10M
    UpdatePolicy:
      AutoScalingRollingUpdate:
        MinInstancesInService: 1
        WaitOnResourceSignals: 'true'
        PauseTime: PT10M

  EventCollectionLc:
    Type: 'AWS::AutoScaling::LaunchConfiguration'
    Properties:
      UserData: !Base64
        'Fn::Sub': |
          #!/bin/bash
          docker run -t --rm ${ContainerAwsUtil} cfn-signal -e $? --stack ${AWS::StackName} --resource EventCollectionGroup --region ${AWS::Region}
    UpdatePolicy:
      AutoScalingReplacingUpdate:
        WillReplace: 'true'

The above snippet have the extras trimmed out. You can find the template here:

https://github.com/Bit-Clouded/Glenlivet/blob/master/analytics/snowplow.template#L368

As you can see, I actually run the cfn-init in a container itself and do not install the util on the server even.

The docker container definition is here:

FROM alpine:3.6

RUN apk add --no-cache ca-certificates python py-pip groff less jq curl &&\
    pip install awscli &&\
    pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz

Again, with extras trimmed. Full file is here:

https://github.com/Bit-Clouded/Angostura/blob/master/utility/aws-util/Dockerfile

In fact, I personally have moved away from cfn-init altogether and moved all required binaries to be pulled in via docker instead. Just a bash script in the UserData section is far cleaner and easier to read.


问:
Replace a parameter in an expression with a constant
I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

```<code>public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}
</code>```

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.

答:
You should use an ExpressionVisitor which will helps you visit the expression and replace part of the expression.

```<code>public class ReplaceParameterVisitor : ExpressionVisitor
{
    public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>(
        Expression<Func<TElement, TElement, bool>> inputExpression,
        TElement element)
    {

        Expression body = inputExpression.Body;
        ReplaceParameterVisitor visitor =
            new ReplaceParameterVisitor(inputExpression.Parameters[1],
                                        Expression.Constant(element, typeof(TElement)));
        Expression newBody = visitor.Visit(body);

        Expression<Func<TElement, bool>> newExpression =
            Expression.Lambda<Func<TElement, Boolean>>(
                newBody,
                new ParameterExpression[] { inputExpression.Parameters[0] });
        return newExpression;
    }

    private ReplaceParameterVisitor(
        ParameterExpression param,
        ConstantExpression constant)
    {
        this._param = param;
        this._constant = constant;
    }

    private readonly ParameterExpression _param;
    private readonly ConstantExpression _constant;

    protected override Expression VisitParameter(ParameterExpression node)
    {
        if (node == this._param)
        {
            return this._constant;
        }
        else
        {
            return base.VisitParameter(node);
        }
    }
}
</code>```

Then

```<code>Expression<Func<Int32, Int32, Boolean>> f = (i1, i2) => i1 > i2;
Expression<Func<Int32, Boolean>> f2 = ReplaceParameterVisitor.ReplaceParameter(f, 5);
Boolean b = f2.Compile()(4);
</code>```

Body:
I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.

Body:
You should use an ExpressionVisitor which will helps you visit the expression and replace part of the expression.

public class ReplaceParameterVisitor : ExpressionVisitor
{
    public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>(
        Expression<Func<TElement, TElement, bool>> inputExpression,
        TElement element)
    {

        Expression body = inputExpression.Body;
        ReplaceParameterVisitor visitor =
            new ReplaceParameterVisitor(inputExpression.Parameters[1],
                                        Expression.Constant(element, typeof(TElement)));
        Expression newBody = visitor.Visit(body);

        Expression<Func<TElement, bool>> newExpression =
            Expression.Lambda<Func<TElement, Boolean>>(
                newBody,
                new ParameterExpression[] { inputExpression.Parameters[0] });
        return newExpression;
    }

    private ReplaceParameterVisitor(
        ParameterExpression param,
        ConstantExpression constant)
    {
        this._param = param;
        this._constant = constant;
    }

    private readonly ParameterExpression _param;
    private readonly ConstantExpression _constant;

    protected override Expression VisitParameter(ParameterExpression node)
    {
        if (node == this._param)
        {
            return this._constant;
        }
        else
        {
            return base.VisitParameter(node);
        }
    }
}

Then

Expression<Func<Int32, Int32, Boolean>> f = (i1, i2) => i1 > i2;
Expression<Func<Int32, Boolean>> f2 = ReplaceParameterVisitor.ReplaceParameter(f, 5);
Boolean b = f2.Compile()(4);


问:
what is the c++ equivalent of map(int,input().split()) of python?
I find it hard to do all the string manipulation and then parsing into an array of integers in c++ while we could get away with only a single line in python.

whats the easiest way to split the string of integers into an array of integers in c++ ?

答:
There are many options to do this. For example using standard stream this could be achieved using: </p>

<pre class="lang-cpp prettyprint-override"><code>#include <vector>
#include <string>
#include <sstream>

std::string s = "1 2 3";
std::vector<int> result;
std::istringstream iss(s);
for(int n; iss >> n; )
    result.push_back(n);
</code>```

Body:
There are many options to do this. For example using standard stream this could be achieved using:

#include <vector>
#include <string>
#include <sstream>

std::string s = "1 2 3";
std::vector<int> result;
std::istringstream iss(s);
for(int n; iss >> n; )
    result.push_back(n);


问:
Update Folder Count on cascade delete in Laravel via eloquent
I have 3 tables:

Tasks

Folders

Folder tasks

Tasks table will have all task_name, Folder table will have folder_name, task_count and Folder Tasks is a pivot table which will store folder_id and task_id.

All tables have many-to-many relationships.

I added cascade delete tasks. So, if i delete a task then it will deleted everywhere including pivot table. I'm deleting tasks using eloquent delete. This is working fine

But, I need to update the count of tasks of each folder in Folders table once I delete a task.

As a task can be stored in multiple folders, it's hard to update the count of all folder's task_count on cascade deleted tasks. I'm stuck here.

How can i update all task_count's of affected folders?

答:
Finally, i found a way to update tasks_count myself. It  may not be the efficient way but solves the issue.

```<code>$task = Tasks::find($domain_id);
$folders = $task->folders->pluck('pivot.folder_id');
Tasks::where('user_id', $user_id)->where('id', $domain_id)->delete();
foreach($folders as $key => $value){
    $folder_table = Folder::find($value);
    $folder_table->tasks_count = $folder_table->tasks()->count();
    $folder_table->save();
}
</code>```

Body:
Finally, i found a way to update tasks_count myself. It  may not be the efficient way but solves the issue.

$task = Tasks::find($domain_id);
$folders = $task->folders->pluck('pivot.folder_id');
Tasks::where('user_id', $user_id)->where('id', $domain_id)->delete();
foreach($folders as $key => $value){
    $folder_table = Folder::find($value);
    $folder_table->tasks_count = $folder_table->tasks()->count();
    $folder_table->save();
}


问:
how to edit xml file in C#
```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

答:
I've not tested this, but I think it's close.  It's a very manual approach, and there may be a slicker way to do it, but it's just manually grouping the categories into a new xdocument called groupedCategoryDocument.

```<code>var doc = XDocument.Parse(xmlString);
var groupedCategoryDocument = XDocument.Parse("<Family_Inventory />");

foreach(var category in doc.Root.Elements("FamilyCategory"))
{
  //create the category for the new document
  var groupedCategory = new XElement("FamilyCategory", category.Text);

  //get all of the families for this category
  foreach(var familyName in category.Elements("FamilyName"))
  {
     //add to new document
     groupedCategory.Add(XElement.Parse(familyName.ToString());
  }

  // add category to new document
  groupedCategoryDocument.Add(groupedCategory);
}
</code>```

On third preview, I think the XML you are trying to generate is too complex and I think this will be the easiest both in terms of generation & consumption

```<code><Family_Inventory>
  <Family category="{category-name}" name="{family-name}" symbol="{symbol-1}"/>
  <Family category="{category-name}" name="{family-name}" symbol="{symbol-2}"/>
  ...
  <Family category="{category-name}" name="{family-name}" symbol="{symbol-n}"/>
</Family_Inventory>
</code>```

Title: how to edit xml file in C#

Body:
<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

Body:
I've not tested this, but I think it's close.  It's a very manual approach, and there may be a slicker way to do it, but it's just manually grouping the categories into a new xdocument called groupedCategoryDocument.

var doc = XDocument.Parse(xmlString);
var groupedCategoryDocument = XDocument.Parse("<Family_Inventory />");

foreach(var category in doc.Root.Elements("FamilyCategory"))
{
  //create the category for the new document
  var groupedCategory = new XElement("FamilyCategory", category.Text);

  //get all of the families for this category
  foreach(var familyName in category.Elements("FamilyName"))
  {
     //add to new document
     groupedCategory.Add(XElement.Parse(familyName.ToString());
  }

  // add category to new document
  groupedCategoryDocument.Add(groupedCategory);
}

On third preview, I think the XML you are trying to generate is too complex and I think this will be the easiest both in terms of generation & consumption

<Family_Inventory>
  <Family category="{category-name}" name="{family-name}" symbol="{symbol-1}"/>
  <Family category="{category-name}" name="{family-name}" symbol="{symbol-2}"/>
  ...
  <Family category="{category-name}" name="{family-name}" symbol="{symbol-n}"/>
</Family_Inventory>


问:
Iterable disjunction in LINQ
Let's assume I have an IQueryable collection, and list of some strings.

I can build query this way:

```<code>foreach (var somestring in somestrings)
{
     collection = collection.Where(col=>col.Property.Contains(somestring);
}
</code>```

which will produce following SQL query:

```<code>SELECT ...... FROM ..... WHERE
(Property LIKE '%something1%') AND
(Property LIKE '%something2%') AND
(Property LIKE '%something3%')
</code>```

Note, that WHERE clauses are connected with ANDs.

Is there way, to construct similar query, but connected with ORs ?

答:
You can do this in one query without looping using Any:

```<code>var result = collection
    .Where(col => somestrings
        .Any(s => col.Property.Contains(s)));
</code>```

Or the same query with simplified syntax:

```<code>var result = collection
    .Where(col => somestrings
        .Any(col.Property.Contains));
</code>```

Title: Iterable disjunction in LINQ

Body:
Let's assume I have an IQueryable collection, and list of some strings.

I can build query this way:

foreach (var somestring in somestrings)
{
     collection = collection.Where(col=>col.Property.Contains(somestring);
}

which will produce following SQL query:

SELECT ...... FROM ..... WHERE
(Property LIKE '%something1%') AND
(Property LIKE '%something2%') AND
(Property LIKE '%something3%')

Note, that WHERE clauses are connected with ANDs.

Is there way, to construct similar query, but connected with ORs ?

Body:
You can do this in one query without looping using Any:

var result = collection
    .Where(col => somestrings
        .Any(s => col.Property.Contains(s)));

Or the same query with simplified syntax:

var result = collection
    .Where(col => somestrings
        .Any(col.Property.Contains));


问:
How to represent navigation links with Schema.org
I have a regular portfolio website (plain HTML) and this website includes a navigation with links to »about«, »imprint« and »contact«, so the resulting sitemap is:

                   index
                     |
        +-------+----+----+--------+
        |       |         |        |
      about   contact  imprint  projects
                                   |
                          +-----+--+--+-----+
                          |     |     |     |
                          A     B     C     D
```

<p>So on the <code>index</code> (<code>/</code>) page I want to include JSON-LD like so:</p>

<pre class="lang-html prettyprint-override"><code><script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "WebSite",
  …
  …
}
</script>
</code>```

How can the links to "about", "contact", … be represented with Schema.org? Would:

{
  …
  "@type": "WebSite",
  "links":
  [
    {
      "@type": "WebSite",
      "@id": "https://…"
    }
  ]
}
```

be right?

答:
You used the links property, which (given your @context) results in the property URI http://schema.org/links. But this is not a valid Schema.org property, so you must not use it.

To associate the WebPage items with their WebSite, you can use the hasPart/isPartOf property:

{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "@id": "/#site",
  "hasPart": [

    {
      "@type": "WebPage",
      "@id": "/page-1"
    },

    {
      "@type": "WebPage",
      "@id": "/page-2"
    }

  ]
}
```

<pre class="lang-json prettyprint-override"><code>{
  "@context": "http://schema.org",
  "@type": "WebPage",
  "@id": "/page-1",
  "isPartOf": {
    "@type": "WebSite",
    "@id": "/#site"
  }
}
</code>```

For the contact page, you can use the ContactPage type. For the about page, you can use the AboutPage type. Both are subtypes of WebPage. Schema.org doesn’t offer a subtype for each possible type of page, of course; for pages that have no specific subtype defined, you can use the broad WebPage type; in many cases, it’s also possible to either use ItemPage or CollectionPage.

If you want to represent the navigation itself, there is the SiteNavigationElement type.

Body:
I have a regular portfolio website (plain HTML) and this website includes a navigation with links to »about«, »imprint« and »contact«, so the resulting sitemap is:

                   index
                     |
        +-------+----+----+--------+
        |       |         |        |
      about   contact  imprint  projects
                                   |
                          +-----+--+--+-----+
                          |     |     |     |
                          A     B     C     D

So on the index (/) page I want to include JSON-LD like so:

How can the links to "about", "contact", … be represented with Schema.org? Would:

{
  …
  "@type": "WebSite",
  "links":
  [
    {
      "@type": "WebSite",
      "@id": "https://…"
    }
  ]
}

be right?

Body:
You used the links property, which (given your @context) results in the property URI http://schema.org/links. But this is not a valid Schema.org property, so you must not use it.

To associate the WebPage items with their WebSite, you can use the hasPart/isPartOf property:

{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "@id": "/#site",
  "hasPart": [

    {
      "@type": "WebPage",
      "@id": "/page-1"
    },

    {
      "@type": "WebPage",
      "@id": "/page-2"
    }

  ]
}

{
  "@context": "http://schema.org",
  "@type": "WebPage",
  "@id": "/page-1",
  "isPartOf": {
    "@type": "WebSite",
    "@id": "/#site"
  }
}

For the contact page, you can use the ContactPage type. For the about page, you can use the AboutPage type. Both are subtypes of WebPage. Schema.org doesn’t offer a subtype for each possible type of page, of course; for pages that have no specific subtype defined, you can use the broad WebPage type; in many cases, it’s also possible to either use ItemPage or CollectionPage.

If you want to represent the navigation itself, there is the SiteNavigationElement type.


问:
Convert int to it's ascii counterpart in xquery
I want to convert say 65 to 'A' in xquery, how do you do that?
There's a XML in which I've to insert sequencing into, like this.</p>

```<code><a>
<b>A
</b>
<b>B
</b>
<b>C
</b>
</a>
</code>```

答: codepoints-to-string(65) gives A: https://xqueryfiddle.liberty-development.net/b4GWVi, see the spec https://www.w3.org/TR/xpath-functions/#func-codepoints-to-string.

Body:
I want to convert say 65 to 'A' in xquery, how do you do that?
There's a XML in which I've to insert sequencing into, like this.

A

B

C


问:
MySQL: Updating data from one column to another using two matching columns
I'm trying to update columns based on two matching columns: firms.id = investors.firm and investors.firm_role = "ceo", but the server keeps rejecting my syntax. I have tried inner joins, without inner joins, it's all really too complex for me, so I'm not sure what to do next.

```<code>UPDATE firms
JOIN investors USING (firms.id = investors.firm)
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"
</code>```

Error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = investors.firm) SET firms.ceo = investors.name WHERE investors.firm_role =' at line 1

答:
You are very close with your syntax:

```<code>UPDATE firms
LEFT JOIN investors ON firms.id = investors.firm
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"
</code>```

Refer to this.

Body:
I'm trying to update columns based on two matching columns: firms.id = investors.firm and investors.firm_role = "ceo", but the server keeps rejecting my syntax. I have tried inner joins, without inner joins, it's all really too complex for me, so I'm not sure what to do next.

UPDATE firms
JOIN investors USING (firms.id = investors.firm)
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"

Error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = investors.firm) SET firms.ceo = investors.name WHERE investors.firm_role =' at line 1

Body:
You are very close with your syntax:

UPDATE firms
LEFT JOIN investors ON firms.id = investors.firm
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"

Refer to this.


问:
Search element in array based on another array and change property
I have two array of objects like this:

```<code>const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];
</code>```

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

```<code>officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});
</code>```

But I need to search by array not single element so I've tried this but not succeeded:

```<code>officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});
</code>```

Expected Output:

```<code>  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }
</code>```

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

答:
You could map the officers array. Get the object with the same id in searchAndChangeFor using find. Merge them using spread syntax

If you just want to merge, you could just do

```<code>return { ...item, ...searchAndChangeFor.find(o => o.id === item.id) }
</code>```

But, if you want to add new properties when a match is found, you can conditionally return like below:

const officers=[{id:20,name:'Captain Piett'},{id:24,name:'General Veers'},{id:56,name:'Admiral Ozzel'},{id:88,name:'Commander Jerjerrod'}],
    searchAndChangeFor = [{id:56,name:'New Name',additionalData:1},];

const output = officers.map(item => {
  const found = searchAndChangeFor.find(o => o.id === item.id);
  if (found)
    return { ...item, ...found, newProperty: 'value' }
  else
    return item;
})

console.log(output)```
</div>
</div>
</p>

<p>Another option is to clone the <code>officers</code> array to avoid mutation and loop through the <code>searchAndChangeFor</code> instead (since it is the smaller array)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const officers=[{id:20,name:'Captain Piett'},{id:24,name:'General Veers'},{id:56,name:'Admiral Ozzel'},{id:88,name:'Commander Jerjerrod'}],
    searchAndChangeFor = [{id:56,name:'New Name',additionalData:1},],
    output = [...officers];

searchAndChangeFor.forEach(s => {
  const index = officers.findIndex(o => o.id === s.id);
  output[index] = Object.assign({}, output[index], s)
})

console.log(output)</code>```

Body:
I have two array of objects like this:

const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});

But I need to search by array not single element so I've tried this but not succeeded:

officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});

Expected Output:

  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

Body:
You could map the officers array. Get the object with the same id in searchAndChangeFor using find. Merge them using spread syntax

If you just want to merge, you could just do

return { ...item, ...searchAndChangeFor.find(o => o.id === item.id) }

But, if you want to add new properties when a match is found, you can conditionally return like below:

const officers=[{id:20,name:'Captain Piett'},{id:24,name:'General Veers'},{id:56,name:'Admiral Ozzel'},{id:88,name:'Commander Jerjerrod'}],
    searchAndChangeFor = [{id:56,name:'New Name',additionalData:1},];

const output = officers.map(item => {
  const found = searchAndChangeFor.find(o => o.id === item.id);
  if (found)
    return { ...item, ...found, newProperty: 'value' }
  else
    return item;
})

console.log(output)

Another option is to clone the officers array to avoid mutation and loop through the searchAndChangeFor instead (since it is the smaller array)

const officers=[{id:20,name:'Captain Piett'},{id:24,name:'General Veers'},{id:56,name:'Admiral Ozzel'},{id:88,name:'Commander Jerjerrod'}],
    searchAndChangeFor = [{id:56,name:'New Name',additionalData:1},],
    output = [...officers];

searchAndChangeFor.forEach(s => {
  const index = officers.findIndex(o => o.id === s.id);
  output[index] = Object.assign({}, output[index], s)
})

console.log(output)


问:
enforcement for abstract properties in python3
I have this abstract class

```<code>class Kuku(ABC):
    def __init__(self):
        self.a = 4
    @property
    @abstractmethod
    def kaka(self):
        pass
</code>```

kaka is an abstract property, So I would expect python to enforce it being a property in inheritors, But it allows me to create:

```<code>class KukuChild(Kuku):
     def kaka(self):
         return 3
</code>```

and KukuChild().kaka() returns 3 as if it's not a property. Is this intentional? Pycharm doesn't enforce this either, so why even add the property decorator in the abstract class?

答:
You are overriding the kaka property in the child class. You must also use @property to decorate the overridden methods in the child:

```<code>from abc import ABC, abstractmethod

class Kuku(ABC):
    def __init__(self):
        self.a = 4
    @property
    @abstractmethod
    def kaka(self):
        pass

class KukuChild(Kuku):
    @property
    def kaka(self):
         return 3

KukuChild().kaka    # <-- use as an attribute, not a method call.
</code>```

Body:
I have this abstract class

class Kuku(ABC):
    def __init__(self):
        self.a = 4
    @property
    @abstractmethod
    def kaka(self):
        pass

kaka is an abstract property, So I would expect python to enforce it being a property in inheritors, But it allows me to create:

class KukuChild(Kuku):
     def kaka(self):
         return 3

and KukuChild().kaka() returns 3 as if it's not a property. Is this intentional? Pycharm doesn't enforce this either, so why even add the property decorator in the abstract class?

Body:
You are overriding the kaka property in the child class. You must also use @property to decorate the overridden methods in the child:

from abc import ABC, abstractmethod

class Kuku(ABC):
    def __init__(self):
        self.a = 4
    @property
    @abstractmethod
    def kaka(self):
        pass

class KukuChild(Kuku):
    @property
    def kaka(self):
         return 3

KukuChild().kaka    # <-- use as an attribute, not a method call.


问:
How many unlucky numbers in segment [a;b]?
Some numbers are called unlucky if their decimal representation contain the number 5.

For example: 123456, 245, 1555 are unlucky numbers and 111, 123, 147 are not unlucky numbers.

How many unlucky numbers are there in segment [a:b]?, where 1 < a < b.

For example a = 1, b = 17 , we have the result is 2. Because, there are only 5, 15.

This is my try: I call f(a) is the amount of unlucky numbers in segment [1;a], then we have f(a+1) is the the amount of unlucky numbers in segment [1;a+1], so we have: f(a+1)=f(a) if a+1 is not unlucky number and f(a+1)=f(a)+1 if a+1 is unlucky number. My problem is to compute f(a) with O(log(n)), but I can't come to good solution!

答:
I won't give you the full solution, but I'll give you a hint that should point you in the correct direction.  You need to apply some mathematics (permutation & combination) knowledge to this problem.

Suppose you want to find the number of unlucky numbers in [0, 12345).  With some math, you can calculate the number of such numbers in [0, 10000) in O(1).  Then, you could calculate the number of such numbers in [10000, 12000) in O(1).  Then do it for [12000, 12300).  Now if you see where we're going...

To find the number of unlucky numbers in [a, b], we can simply calculate the number of unlucky numbers in [0, a) and the number of unlucky numbers in [0, b+1).

Note: You don't actually need to calculate the number of unlucky numbers in [0, 10000) in O(1).  It also suffices to find a way to calculate the number of unlucky numbers in [0, 10000) from the number of unlucky numbers in [10000, 12000) in O(1).


问:
How to insert a block of code between two specific html tags with a shell script?
I need to insert a block of code (in fact it is an adsense ads script) between two specific tags (html file) that are the following:

```<code></style>
<table border="1" class="dataframe">
</code>```

I need to insert it in the THIRD occurrence of these two labels.
The form of a typical Adsense block is:

```<code><script async
  src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
 lorem ipsum...
</script>
</code>```

In the end I need to have something like this:

```<code></style>

 <script async
  src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
  </script>
  <script>
   lorem ipsum...
  </script>

<table border="1" class="dataframe">
</code>```

I have inserted blocks of code using sed and indicating the line number, in this case it is not possible in this way because the line number can change.
Thank you very much for any help.

答:
Try this, if you can use bash. This solution is not very fast, but it should work.

insert_rubbish.sh

```<code>#!/bin/bash

StartPattern='</style>'
StopPattern='<table border="1" class="dataframe">'

content=$(cat << EOT
<script async
  src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
 lorem ipsum...
</script>
EOT
)

# loop over all lines
while read -r line; do

    # if pattern found
    if [[ $line =~ $StopPattern && $lastline =~ $StartPattern ]]; then

       # is it the third fund? --> then print content
       if [[ $count == 2 ]]; then
          printf "%s\n" "$content"
       fi

       # count pattern match
       (( count++ ))
    fi

    # write line
    printf "%s\n" "$line"

    # save line for next pattern match
    lastline="$line"
done < "$1"
</code>```

Usage

```<code>insert_rubbish.sh "/path/to/your/file.html" > output.html
</code>```

Body:
I need to insert a block of code (in fact it is an adsense ads script) between two specific tags (html file) that are the following:

</style>

I need to insert it in the THIRD occurrence of these two labels.
The form of a typical Adsense block is:

In the end I need to have something like this:

</style>

I have inserted blocks of code using sed and indicating the line number, in this case it is not possible in this way because the line number can change.
Thank you very much for any help.

Body:
Try this, if you can use bash. This solution is not very fast, but it should work.

insert_rubbish.sh

#!/bin/bash

StartPattern='</style>'
StopPattern='<table border="1" class="dataframe">'

content=$(cat << EOT
<script async
  src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
 lorem ipsum...
</script>
EOT
)

# loop over all lines
while read -r line; do

    # if pattern found
    if [[ $line =~ $StopPattern && $lastline =~ $StartPattern ]]; then

       # is it the third fund? --> then print content
       if [[ $count == 2 ]]; then
          printf "%s\n" "$content"
       fi

       # count pattern match
       (( count++ ))
    fi

    # write line
    printf "%s\n" "$line"

    # save line for next pattern match
    lastline="$line"
done < "$1"

Usage

insert_rubbish.sh "/path/to/your/file.html" > output.html


问:
how to create class that adds, deletes and find words in a dictionary?
This is what I have and I'm new to Java:</p>

```<code> import java.util.*;

 public class WordPairs
 {

     // ArrayList<String> names = new ArrayList<String>();
     // ArrayList<String> meanings = new ArrayList<String>();
     //names.add("empty");
     //meanings.add("empty");
     String searchName;
     String searchMeaning;
        String names[] = new String[25];
        String meanings[] = new String[25];
        int Q = 1;

  public void setWordAdd(String name,String meaning)
  {
   names[Q] = name;
     meanings[Q] = meaning;
     Q = Q++;
  }

  public void setWordDelete(String name)
  {
     for(int i=0;i<names.length;i++)
     {
        String check =  names[i];
        if(check == name)
        {

           String meanings = meanings.remove(i);
        }
     }
  }

  public void setWordSearch(String name)
  {
     int a = 1;

     for(i=0;i<names.size();i++)
     {
        string check = names.get(i);

        if(check == name)
        {
           searchName = names.get(i);
           searchMeaning = meanings.get(i);

           a = 0;
        }
     }

     if(a == 1)
     {
        searchName = "word can not be found";
        searchMeaning = "meaning can not be found";
     }
  }

  public String getSearchName()
  {
     return searchName;
  }

  public String getSearchMeaning()
  {
     return searchMeaning;

  }
}
</code>```

答:
I believe you are a beginner, and by reading your code I assume you are not familiar with built-in collections yet (despite of some shy ArrayList attempt). That's ok, no one is born with that knowledge. Here is some reading for you:

Map interface: http://download.oracle.com/javase/6/docs/api/java/util/Map.html
All of implementations of this interface provide functionality you need, but in different ways. For example, HashMap is useful in most cases, but if you need keys (in your code - "names") sorted, TreeMap would be better. LinkedHashMap "remembers" the order in which keys were inserted, and so on. It's very interesting and informative reading and you definitely should know about maps, because they are among most useful Java classes.

Here is introduction to Java Collections Framework in general:
http://download.oracle.com/javase/tutorial/collections/index.html

Be sure to read it, because collections are irreplacable in even simplest Java applications.

I hope that helps, and good luck!

Body:
This is what I have and I'm new to Java:

 import java.util.*;

 public class WordPairs
 {

     // ArrayList<String> names = new ArrayList<String>();
     // ArrayList<String> meanings = new ArrayList<String>();
     //names.add("empty");
     //meanings.add("empty");
     String searchName;
     String searchMeaning;
        String names[] = new String[25];
        String meanings[] = new String[25];
        int Q = 1;

  public void setWordAdd(String name,String meaning)
  {
   names[Q] = name;
     meanings[Q] = meaning;
     Q = Q++;
  }

  public void setWordDelete(String name)
  {
     for(int i=0;i<names.length;i++)
     {
        String check =  names[i];
        if(check == name)
        {

           String meanings = meanings.remove(i);
        }
     }
  }

  public void setWordSearch(String name)
  {
     int a = 1;

     for(i=0;i<names.size();i++)
     {
        string check = names.get(i);

        if(check == name)
        {
           searchName = names.get(i);
           searchMeaning = meanings.get(i);

           a = 0;
        }
     }

     if(a == 1)
     {
        searchName = "word can not be found";
        searchMeaning = "meaning can not be found";
     }
  }

  public String getSearchName()
  {
     return searchName;
  }

  public String getSearchMeaning()
  {
     return searchMeaning;

  }
}


问:
I need to skip three rows from the dataframe while loading from a CSV file in scala
I am loading my CSV file to a data frame and I can do that but I need to skip the starting three lines from the file.

I tried .option() command by giving header as true but it is ignoring the only first line.

```<code>val df = spark.sqlContext.read
    .schema(Myschema)
    .option("header",true)
    .option("delimiter", "|")
    .csv(path)
</code>```

I thought of giving header as 3 lines but I couldn't find the way to do that.

alternative thought: skip those 3 lines from the data frame

Please help me with this. Thanks in Advance.

答:
You can try this option </p>

```<code>df.withColumn("Index",monotonically_increasing_id())
        .filter(col("Index") > 2)
        .drop("Index")
</code>```

Body:
I am loading my CSV file to a data frame and I can do that but I need to skip the starting three lines from the file.

I tried .option() command by giving header as true but it is ignoring the only first line.

val df = spark.sqlContext.read
    .schema(Myschema)
    .option("header",true)
    .option("delimiter", "|")
    .csv(path)

I thought of giving header as 3 lines but I couldn't find the way to do that.

alternative thought: skip those 3 lines from the data frame

Please help me with this. Thanks in Advance.

Body:
You can try this option

df.withColumn("Index",monotonically_increasing_id())
        .filter(col("Index") > 2)
        .drop("Index")


问:
Should this request be GET or POST?
My API accepts 2 parameters, product and quantity, and it returns a price.

At the moment this is a 'GET' request, which makes sense. But there are now new requirements to log every price that is returned in an audit table. This now feels like a POST?

Question

What is/where can I find the criteria for determining whether a request should be made as GET or POST?

答:
Well, this is some subjective, but I think I'll let the API as GET request. You're not creating or updating the price (your main entity), auditing it's just a side effect.

Also you can think, as a developer who doesn't know about the auditing process and consumes your API, getting information using POST can be weird.

Title: Should this request be GET or POST?


问:
SAPUI5 change operationMode to client in runtime
I am using SmartTable in my project.

I need to request some data from backend at begin and then work on received data in frontend.

By data, that i need from backend i must send some filter.

So i need at begin the operationMode Server, and after data come change it to Client

My SmartTable xml

<smartTable:SmartTable id="ReportSmartTable" entitySet="OwnSet"
    tableBindingPath="/OwnSet" tableType="AnalyticalTable"
    beforeRebindTable="onBeforeRebindTable" >
```

<p>onBeforeRebindTable</p>

<pre class="lang-js prettyprint-override"><code>onBeforeRebindTable: function (oEvent) {
    console.log("onBeforeRebindTable");
    var oBindingParams = oEvent.getParameter("bindingParams");
    oBindingParams.filters.push(new sap.ui.model.Filter("Prop", "EQ", "Value"));
},
</code>```

in onInit i set listener, to change the operation mode after data receiving

var oTable = this.getView().byId("ReportSmartTable"); //Get Hold of the table control
oTable.attachDataReceived(function (oEvent) { //Hits when the data is received from back-end server
    this.getModel().defaultOperationMode = "Client"; //Set operation mode to Client
    var oSource = oEvent.getSource();
    oSource.bClientOperation = true; //Set Client Operation to true
    oSource.sOperationMode = "Client"; //Set operation mode to Client
}.bind(this));
```

<p>i have also tried to change operationMode by following</p>

<pre class="lang-js prettyprint-override"><code>this.getOwnerComponent().getModel().sDefaultOperationMode = "Client";
this.getOwnerComponent().getModel().defaultOperationMode = "Client";
this.getModel().sDefaultOperationMode = "Client"; //Set operation mode to Client
this.getModel().defaultOperationMode = "Client"; //Set operation mode to Client
</code>```

but it doesn't work.

If i make some filter after data is received, there still comes request to backend.

By making Client operationMode from begin, onBeforeRebindTable is called before request, but the filter is not sended with batch

答:
You can't update the operation mode after a model is created. Even if you update the private attribute sDefaultOperationMode, it will not affect existing bindings.

You can specify the operationMode per binding, for example in a list:

```<code><List items="{path:'/myset',parameters:{operationMode:'Client'}}" ...>
</code>```

and use ListBase.bindItems to re-create a binding with a different operation mode.

For a SmartTable, however, you'd have to modify the internal table bindings and this would probably break a lot of things, therefore it's discouraged. Maybe the Smart Table is not the best fit for your use case.

Body:
I am using SmartTable in my project.

I need to request some data from backend at begin and then work on received data in frontend.

By data, that i need from backend i must send some filter.

So i need at begin the operationMode Server, and after data come change it to Client

My SmartTable xml

<smartTable:SmartTable id="ReportSmartTable" entitySet="OwnSet"
    tableBindingPath="/OwnSet" tableType="AnalyticalTable"
    beforeRebindTable="onBeforeRebindTable" >

onBeforeRebindTable

onBeforeRebindTable: function (oEvent) {
    console.log("onBeforeRebindTable");
    var oBindingParams = oEvent.getParameter("bindingParams");
    oBindingParams.filters.push(new sap.ui.model.Filter("Prop", "EQ", "Value"));
},

in onInit i set listener, to change the operation mode after data receiving

var oTable = this.getView().byId("ReportSmartTable"); //Get Hold of the table control
oTable.attachDataReceived(function (oEvent) { //Hits when the data is received from back-end server
    this.getModel().defaultOperationMode = "Client"; //Set operation mode to Client
    var oSource = oEvent.getSource();
    oSource.bClientOperation = true; //Set Client Operation to true
    oSource.sOperationMode = "Client"; //Set operation mode to Client
}.bind(this));

i have also tried to change operationMode by following

this.getOwnerComponent().getModel().sDefaultOperationMode = "Client";
this.getOwnerComponent().getModel().defaultOperationMode = "Client";
this.getModel().sDefaultOperationMode = "Client"; //Set operation mode to Client
this.getModel().defaultOperationMode = "Client"; //Set operation mode to Client

but it doesn't work.

If i make some filter after data is received, there still comes request to backend.

By making Client operationMode from begin, onBeforeRebindTable is called before request, but the filter is not sended with batch

Body:
You can't update the operation mode after a model is created. Even if you update the private attribute sDefaultOperationMode, it will not affect existing bindings.

You can specify the operationMode per binding, for example in a list:

<List items="{path:'/myset',parameters:{operationMode:'Client'}}" ...>

and use ListBase.bindItems to re-create a binding with a different operation mode.

For a SmartTable, however, you'd have to modify the internal table bindings and this would probably break a lot of things, therefore it's discouraged. Maybe the Smart Table is not the best fit for your use case.


问:
Change concrete class binding on demand in Laravel Service Container
How do I change a concrete class binding dynamically.

I'm trying to test an artisan command that consumes an external API.

```<code>class ConsumeApiCommand extends Command
{
    public function __construct(ClientInterface $client)
    {
        parent::__construct();

        $this->client = $client;
    }

    public function handle()
    {
        $api_response = $this->client->request('POST', 'http://external.api/resource');

        $response = json_decode($api_response);

        if(isset($response['error'])) {
            $this->error($response['error']);
        } else {
            $this->status($response['status']);
        }
    }
}
</code>```

Currently; I can fake the concrete class in my tests.

```<code>class FakeServiceProvider extends AppServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ClientInterface::class, function () {
            return new class implements ClientInterface {
                public function request($method, $uri, $headers = [], $body = [])
                {
                    return json_encode(['status' => "You've reached us."]);
                }
            };
        });
    }
}
</code>```

Passing.

```<code>public function test_can_consume_api_if_authenticated()
{
    $this->artisan('consume:api')
         ->expectsOutput("You've reached us.")
         ->assertExitCode(0);
}
</code>```

Failing; returns initially binded class response You've reached us.

```<code>public function test_cant_consume_api_if_not_authenticated()
{
    $this->app->bind(ClientInterface::class, function () {
        return new class implements ClientInterface {
            public function request($method, $uri, $headers = [], $body = [])
            {
                return json_encode(['error' => "Unauthorized."]);
            }
        };
    });

    $this->artisan('consume:api')
         ->expectsOutput("Unauthorized.")
         ->assertExitCode(0);
}
</code>```

Is it possible to achieve the desire behavior this way? Or service container bindings can't change during the request lifetime?

答:
Am just leaving a code snippet for those that might be wondering how I solved this.

Basing on Leonardo's answer, the source in the question is okay, but I had to manipulate the required interface manually, inject it into the command and add the command to the service container.

I was not able to override the binding dynamically.

```<code>use Illuminate\Container\Container;
use Illuminate\Contracts\Console\Kernel;

class ConsumeApiCommandTest extends TestCase
{
    public function test_can_consume_api_if_authenticated()
    {
        $this->artisan('consume:api')
             ->expectsOutput("You've reached us.")
             ->assertExitCode(0);
    }

    public function test_cant_consume_api_if_not_authenticated()
    {
        // Mock client interface.
        $mock = \Mockery::mock(ClientInterface::class);

        // Here you override the methods you want.
        $mock->shouldReceive('request')->once()
             ->andReturn(json_encode(['error' => "Unauthorized."]));

        $command = new ConsumeApiCommand($mock);

        // Re-register artisan command.
        Container::getInstance()->make(Kernel::class)->registerCommand($command);

        $this->artisan('consume:api')
             ->expectsOutput("Unauthorized.")
             ->assertExitCode(0);
    }
}
</code>```

Body:
How do I change a concrete class binding dynamically.

I'm trying to test an artisan command that consumes an external API.

class ConsumeApiCommand extends Command
{
    public function __construct(ClientInterface $client)
    {
        parent::__construct();

        $this->client = $client;
    }

    public function handle()
    {
        $api_response = $this->client->request('POST', 'http://external.api/resource');

        $response = json_decode($api_response);

        if(isset($response['error'])) {
            $this->error($response['error']);
        } else {
            $this->status($response['status']);
        }
    }
}

Currently; I can fake the concrete class in my tests.

class FakeServiceProvider extends AppServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ClientInterface::class, function () {
            return new class implements ClientInterface {
                public function request($method, $uri, $headers = [], $body = [])
                {
                    return json_encode(['status' => "You've reached us."]);
                }
            };
        });
    }
}

Passing.

public function test_can_consume_api_if_authenticated()
{
    $this->artisan('consume:api')
         ->expectsOutput("You've reached us.")
         ->assertExitCode(0);
}

Failing; returns initially binded class response You've reached us.

public function test_cant_consume_api_if_not_authenticated()
{
    $this->app->bind(ClientInterface::class, function () {
        return new class implements ClientInterface {
            public function request($method, $uri, $headers = [], $body = [])
            {
                return json_encode(['error' => "Unauthorized."]);
            }
        };
    });

    $this->artisan('consume:api')
         ->expectsOutput("Unauthorized.")
         ->assertExitCode(0);
}

Is it possible to achieve the desire behavior this way? Or service container bindings can't change during the request lifetime?

Body:
Am just leaving a code snippet for those that might be wondering how I solved this.

Basing on Leonardo's answer, the source in the question is okay, but I had to manipulate the required interface manually, inject it into the command and add the command to the service container.

I was not able to override the binding dynamically.

use Illuminate\Container\Container;
use Illuminate\Contracts\Console\Kernel;

class ConsumeApiCommandTest extends TestCase
{
    public function test_can_consume_api_if_authenticated()
    {
        $this->artisan('consume:api')
             ->expectsOutput("You've reached us.")
             ->assertExitCode(0);
    }

    public function test_cant_consume_api_if_not_authenticated()
    {
        // Mock client interface.
        $mock = \Mockery::mock(ClientInterface::class);

        // Here you override the methods you want.
        $mock->shouldReceive('request')->once()
             ->andReturn(json_encode(['error' => "Unauthorized."]));

        $command = new ConsumeApiCommand($mock);

        // Re-register artisan command.
        Container::getInstance()->make(Kernel::class)->registerCommand($command);

        $this->artisan('consume:api')
             ->expectsOutput("Unauthorized.")
             ->assertExitCode(0);
    }
}


问:
Plotting Pandas Crosstab Dataframe into 3D bar chart
I have a dataframe that has rownames of country, colnames of programming language and values showing the count respectively generated my pandas crosstab operation.

```<code>EG

Language    C     C++     Java    Python    Perl

Country

USA          3222   343     2112   10110      89

France      5432   323     1019     678        789

Japan       7878   467       767     8788       40
</code>```

I have tried using gca function and projection 3d. I also tried this but couldnt get it to work.

```<code>threedee = plt.figure().gca(projection='3d') <br/>
threedee.bar(repo_lang, repo_loc, repo_values) <br/>
threedee.set_xlabel('Index')<br/>
threedee.set_ylabel('H-L')<br/>
threedee.set_zlabel('Close')<br/>
plt.show()
</code>```

I want to display a 3D bar chart where two axis could be country name and language and the other their count.

答:
Try this:

```<code>from mpl_toolkits.mplot3d import Axes3D

# thickness of the bars
dx, dy = .8, .8

# prepare 3d axes
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)

# set up positions for the bars
xpos=np.arange(eg.shape[0])
ypos=np.arange(eg.shape[1])

# set the ticks in the middle of the bars
ax.set_xticks(xpos + dx/2)
ax.set_yticks(ypos + dy/2)

# create meshgrid
# print xpos before and after this block if not clear
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()

# the bars starts from 0 attitude
zpos=np.zeros(eg.shape).flatten()

# the bars' heights
dz = eg.values.ravel()

# plot
ax.bar3d(xpos,ypos,zpos,dx,dy,dz)

# put the column / index labels
ax.w_yaxis.set_ticklabels(eg.columns)
ax.w_xaxis.set_ticklabels(eg.index)

# name the axes
ax.set_xlabel('Country')
ax.set_ylabel('Language')
ax.set_zlabel('Count')

plt.show()
</code>```

Output:

Body:
I have a dataframe that has rownames of country, colnames of programming language and values showing the count respectively generated my pandas crosstab operation.

EG

Language    C     C++     Java    Python    Perl

Country

USA          3222   343     2112   10110      89

France      5432   323     1019     678        789

Japan       7878   467       767     8788       40

I have tried using gca function and projection 3d. I also tried this but couldnt get it to work.

threedee = plt.figure().gca(projection='3d')

threedee.bar(repo_lang, repo_loc, repo_values)

threedee.set_xlabel('Index')

threedee.set_ylabel('H-L')

threedee.set_zlabel('Close')

plt.show()

I want to display a 3D bar chart where two axis could be country name and language and the other their count.

Body:
Try this:

from mpl_toolkits.mplot3d import Axes3D

# thickness of the bars
dx, dy = .8, .8

# prepare 3d axes
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)

# set up positions for the bars
xpos=np.arange(eg.shape[0])
ypos=np.arange(eg.shape[1])

# set the ticks in the middle of the bars
ax.set_xticks(xpos + dx/2)
ax.set_yticks(ypos + dy/2)

# create meshgrid
# print xpos before and after this block if not clear
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()

# the bars starts from 0 attitude
zpos=np.zeros(eg.shape).flatten()

# the bars' heights
dz = eg.values.ravel()

# plot
ax.bar3d(xpos,ypos,zpos,dx,dy,dz)

# put the column / index labels
ax.w_yaxis.set_ticklabels(eg.columns)
ax.w_xaxis.set_ticklabels(eg.index)

# name the axes
ax.set_xlabel('Country')
ax.set_ylabel('Language')
ax.set_zlabel('Count')

plt.show()

Output:


问:
How to use @Input() correctly in an Angular 5 app?
I have the following template in the parent component:

```<code><my-table (loaded)="onTableLoaded()" [objId]="objId"></my-table>
</code>```

The problem I have is that the objId is null when loading the child component.
I can add api call in the child but I want to avoid it. Any idea how to allow
the value from api call in the parent can be transfer to child ?

答:
Normally the code should be enough

```<code><my-table [objId]="objId"></my-table>
</code>```

So the problem must be on an another side.
First you should name it properly

```<code><my-table [childObjectId]="parentObjectId"></my-table>
</code>```

something like that, choose what you think is a good name.

Then you should be able to use it.
If you use the objectId asynchron you need to check/handle it in a lifecyle hook. Here the available lifecycle hooks: Angular - Lifecycle Hooks.

If this didn't help you should be sure that a value is not empty which you want to insert or you can post your component here.

Body:
I have the following template in the parent component:

<my-table (loaded)="onTableLoaded()" [objId]="objId"></my-table>

The problem I have is that the objId is null when loading the child component.
I can add api call in the child but I want to avoid it. Any idea how to allow
the value from api call in the parent can be transfer to child ?

Body:
Normally the code should be enough

<my-table [objId]="objId"></my-table>

So the problem must be on an another side.
First you should name it properly

<my-table [childObjectId]="parentObjectId"></my-table>

something like that, choose what you think is a good name.

Then you should be able to use it.
If you use the objectId asynchron you need to check/handle it in a lifecyle hook. Here the available lifecycle hooks: Angular - Lifecycle Hooks.

If this didn't help you should be sure that a value is not empty which you want to insert or you can post your component here.


问:
iPhone: How to programmatically convert String entered by user into Init caps?
I have a textbox where in user enters the string.

I want to programmatically convert this string to init caps.

How can I do that?

答:
Use the UITextInputTraits protocol which is confirm by both (UITextView and UITextField)
input method ...

```<code>@property(nonatomic) UITextAutocapitalizationType autocapitalizationType
</code>```

Try with UITextAutocapitalizationTypeAllCharacters to Capitalize all characters automatically.

```<code>myTextView.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
</code>```

Eidted:
If you want to Capitalize after getting the text from you textView use below

```<code>  NSString myTextString = [myTextView.text capitalizedString];
</code>```

Body:
Use the UITextInputTraits protocol which is confirm by both (UITextView and UITextField)
input method ...

@property(nonatomic) UITextAutocapitalizationType autocapitalizationType

Try with UITextAutocapitalizationTypeAllCharacters to Capitalize all characters automatically.

myTextView.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;

Eidted:
If you want to Capitalize after getting the text from you textView use below

  NSString myTextString = [myTextView.text capitalizedString];


答:
This can be easilly solved in O(log N) time using dynamic programming known as "dp on digits"

First note that instead of calculating unlucky numbers in inertval [L,R] we can instead define some function
f(X) that calculates unlucky numbers in interval [0,x], so unlucky numbers in interval [L,R]
can be calculated as f(R) - f(L-1)

Creating function f() is kinda straightforward, we have our state as dp[pos][ls][unlucky] where:

pos - current digit we are trying to fill

ls - just a flag that saysif our prefix matches the limit of how high we can go

unlucky - another flag that says if our number is already unlucky or not

Then we can do simple recursion expansion digit by digits + memoization.

Sample code (C++11) :

```<code>#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll dp[51][2][2];
ll digits[51];
int amount_of_digits;

ll solve(ll pos, ll ls, ll unlucky)
{
    if(pos >= amount_of_digits)return unlucky;
    if(dp[pos][ls][unlucky]!=-1)return dp[pos][ls][unlucky];

    dp[pos][ls][unlucky]=0;

    for(int i=0; i<=(ls ? 9 : digits[pos]); i++) //next digit
        dp[pos][ls][unlucky]+=solve(pos+1,ls | (i<digits[pos]), unlucky | (i==5));

    return dp[pos][ls][unlucky];
}

ll f(ll x)
{
    string s = to_string(x);
    amount_of_digits = s.size();

    for(int i=0; i<s.size(); i++)
        digits[i] = s[i]-'0';

    memset(dp, -1, sizeof dp);
    return solve(0,0,0);
}

ll calc_interval(ll L, ll R)
{
    return f(R) - f(L-1);
}

int main()
{
    cout<<calc_interval(2,17);
}
</code>```

Title: How many unlucky numbers in segment [a;b]?

Body:
Some numbers are called unlucky if their decimal representation contain the number 5.

For example: 123456, 245, 1555 are unlucky numbers and 111, 123, 147 are not unlucky numbers.

How many unlucky numbers are there in segment [a:b]?, where 1 < a < b.

For example a = 1, b = 17 , we have the result is 2. Because, there are only 5, 15.

This is my try: I call f(a) is the amount of unlucky numbers in segment [1;a], then we have f(a+1) is the the amount of unlucky numbers in segment [1;a+1], so we have: f(a+1)=f(a) if a+1 is not unlucky number and f(a+1)=f(a)+1 if a+1 is unlucky number. My problem is to compute f(a) with O(log(n)), but I can't come to good solution!

Body:
This can be easilly solved in O(log N) time using dynamic programming known as "dp on digits"

First note that instead of calculating unlucky numbers in inertval [L,R] we can instead define some function
f(X) that calculates unlucky numbers in interval [0,x], so unlucky numbers in interval [L,R]
can be calculated as f(R) - f(L-1)

Creating function f() is kinda straightforward, we have our state as dp[pos][ls][unlucky] where:

pos - current digit we are trying to fill

ls - just a flag that saysif our prefix matches the limit of how high we can go

unlucky - another flag that says if our number is already unlucky or not

Then we can do simple recursion expansion digit by digits + memoization.

Sample code (C++11) :

#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll dp[51][2][2];
ll digits[51];
int amount_of_digits;

ll solve(ll pos, ll ls, ll unlucky)
{
    if(pos >= amount_of_digits)return unlucky;
    if(dp[pos][ls][unlucky]!=-1)return dp[pos][ls][unlucky];

    dp[pos][ls][unlucky]=0;

    for(int i=0; i<=(ls ? 9 : digits[pos]); i++) //next digit
        dp[pos][ls][unlucky]+=solve(pos+1,ls | (i<digits[pos]), unlucky | (i==5));

    return dp[pos][ls][unlucky];
}

ll f(ll x)
{
    string s = to_string(x);
    amount_of_digits = s.size();

    for(int i=0; i<s.size(); i++)
        digits[i] = s[i]-'0';

    memset(dp, -1, sizeof dp);
    return solve(0,0,0);
}

ll calc_interval(ll L, ll R)
{
    return f(R) - f(L-1);
}

int main()
{
    cout<<calc_interval(2,17);
}


问:
How to loop through a json string with PL/SQL?
My example only returns BMW 2010.
How do I get it to return AUDI 2000 and BMW 2010?

```<code>declare
    sample_json   varchar2 (32767)
        := '

            [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]
';
begin
    apex_json.parse (sample_json);
    dbms_output.put_line (apex_json.get_varchar2 ('NAME'));
    dbms_output.put_line (apex_json.get_varchar2 ('YEAR'));
end;
</code>```

答:
TL;DR - You cannot as you have duplicate keys in an object.

From JSON Standard - RFC 7159

Objects

An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members).  A name is a
string.  A single colon comes after each name, separating the name
from the value.  A single comma separates a value from a following
name.  The names within an object SHOULD be unique.

(Added emphasis)

```<code>{"NAME":"AUDI","YEAR":"2000","NAME":"BMW","YEAR":"2010"}
</code>```

While technically it is syntactically correct JSON, it does not make sense as you are duplicating keys so most (every) JSON parsers following RFC 7159 will overwrite the first instance of a key with later occurrences so your JSON is effectively:

```<code>{"NAME":"BMW","YEAR":"2010"}
</code>```

And you cannot get AUDI/2000 from the output (unless you parse the JSON by hand).

If you want to send multiple values then you should use an array:

```<code>[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]
</code>```

Update

You can try:

```<code>declare
  sample_json varchar2(32767) := '{"data":[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
begin
  apex_json.parse (sample_json);
  dbms_output.put_line (apex_json.get_varchar2 ('data[1].NAME'));
  dbms_output.put_line (apex_json.get_varchar2 ('data[1].YEAR'));
  dbms_output.put_line (apex_json.get_varchar2 ('data[2].NAME'));
  dbms_output.put_line (apex_json.get_varchar2 ('data[2].YEAR'));
end;
</code>```

or (if apex will accept an array as its outer object):

```<code>declare
    sample_json varchar2(32767) := '[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]';
begin
  apex_json.parse (sample_json);
  FOR i IN 1 .. 2 LOOP
    dbms_output.put_line (apex_json.get_varchar2(p_path=>'[%d].NAME',p0=>i));
    dbms_output.put_line (apex_json.get_varchar2(p_path=>'[%d].YEAR',p0=>i));
  END LOOP;
end;
</code>```

Body:
My example only returns BMW 2010.
How do I get it to return AUDI 2000 and BMW 2010?

declare
    sample_json   varchar2 (32767)
        := '

            [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]
';
begin
    apex_json.parse (sample_json);
    dbms_output.put_line (apex_json.get_varchar2 ('NAME'));
    dbms_output.put_line (apex_json.get_varchar2 ('YEAR'));
end;

Body:
TL;DR - You cannot as you have duplicate keys in an object.

From JSON Standard - RFC 7159

Objects

An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members).  A name is a
string.  A single colon comes after each name, separating the name
from the value.  A single comma separates a value from a following
name.  The names within an object SHOULD be unique.

(Added emphasis)

{"NAME":"AUDI","YEAR":"2000","NAME":"BMW","YEAR":"2010"}

While technically it is syntactically correct JSON, it does not make sense as you are duplicating keys so most (every) JSON parsers following RFC 7159 will overwrite the first instance of a key with later occurrences so your JSON is effectively:

{"NAME":"BMW","YEAR":"2010"}

And you cannot get AUDI/2000 from the output (unless you parse the JSON by hand).

If you want to send multiple values then you should use an array:

[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]

Update

You can try:

declare
  sample_json varchar2(32767) := '{"data":[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
begin
  apex_json.parse (sample_json);
  dbms_output.put_line (apex_json.get_varchar2 ('data[1].NAME'));
  dbms_output.put_line (apex_json.get_varchar2 ('data[1].YEAR'));
  dbms_output.put_line (apex_json.get_varchar2 ('data[2].NAME'));
  dbms_output.put_line (apex_json.get_varchar2 ('data[2].YEAR'));
end;

or (if apex will accept an array as its outer object):

declare
    sample_json varchar2(32767) := '[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]';
begin
  apex_json.parse (sample_json);
  FOR i IN 1 .. 2 LOOP
    dbms_output.put_line (apex_json.get_varchar2(p_path=>'[%d].NAME',p0=>i));
    dbms_output.put_line (apex_json.get_varchar2(p_path=>'[%d].YEAR',p0=>i));
  END LOOP;
end;