问:
put together 4 rows of strings and count words
Error line is: strcpy( tmp, row1+ row2 + row3 + row4 );

I dunno how to put together all rows then count words?

I tried to make function then call it before IF but didn't make it.

Also i thinked about chaning char in int then show it in prinft , also tried to make a array then put all rows in that..

How should i do that?

```<code>int main() {

char row1[256];
char row2[256];
char row3[256];
char row4[256];

printf("4 rows of lyric:\n");
fgets(row1,100,stdin);
fgets(row2,100,stdin);
fgets(row3,100,stdin);
fgets(row4,100,stdin);

char *tmp[1000];
strcpy( tmp, row1+ row2 + row3 + row4 );

int count=0;
char *cur= tmp;

for (;;)
{
    while (*cur == ' ')
    {
        *cur++;
    }

    if (*cur == 0)
    {
        break;
    }

    count++;

    while (*cur != 0 && *cur != ' ')
    {
        *cur++;
    }
}

char a1=row1[strlen(row1)-1];
char a2=row1[strlen(row1)-2];
char a3=row1[strlen(row1)-3];

char b1=row2[strlen(row2)-1];
char b2=row2[strlen(row2)-2];
char b3=row2[strlen(row2)-3];

char c1=row3[strlen(row3)-1];
char c2=row3[strlen(row3)-2];
char c3=row3[strlen(row3)-3];

char d1=row4[strlen(row4)-1];
char d2=row4[strlen(row4)-2];
char d3=row4[strlen(row4)-3];

    if( a1==d1 &&
     a2==d2 &&
     a3==d3 &&
     b1==c1 &&
     b2==c2 &&
     b3==c3 ) {

            printf("1 = 4 and 2 = 3, number of words %c." cur);

}
else if ( a1==c1 &&
          a2==c2 &&
          a3==c3 &&
          b1==d1 &&
          b2==d2 &&
          b3==d3 ) {

            printf("1 = 3 and 2 = 4, number of words %c.", cur);

}
else if ( a1==b1 &&
          a2==b2 &&
          a3==b3 &&
          c1==d1 &&
          c2==d2 &&
          c3==d3 ) {

            printf("1 = 2 and 3 = 4, number of words %c.",cur);

}

else {

        printf("Nijedna rima nije pronadjena u strofi!");

}

return 0;

}
</code>```

答:
```<code> char * stpcpy(char * restrict dst, const char * restrict src);
</code>```

The parameter you passed is not of type char*.

Also you can't concatenate strings using + in c. Use strcat or strncat.

As reply to user's comment :-

There are 3 things that you should keep in mind

First parameter should be modifiable.

First parameter has enough space to hold the combined string.

No overlapping between first and second parameter.

With these 3 rules in mind those can be used.

Body:
Error line is: strcpy( tmp, row1+ row2 + row3 + row4 );

I dunno how to put together all rows then count words?

I tried to make function then call it before IF but didn't make it.

Also i thinked about chaning char in int then show it in prinft , also tried to make a array then put all rows in that..

How should i do that?

int main() {

char row1[256];
char row2[256];
char row3[256];
char row4[256];

printf("4 rows of lyric:\n");
fgets(row1,100,stdin);
fgets(row2,100,stdin);
fgets(row3,100,stdin);
fgets(row4,100,stdin);

char *tmp[1000];
strcpy( tmp, row1+ row2 + row3 + row4 );

int count=0;
char *cur= tmp;

for (;;)
{
    while (*cur == ' ')
    {
        *cur++;
    }

    if (*cur == 0)
    {
        break;
    }

    count++;

    while (*cur != 0 && *cur != ' ')
    {
        *cur++;
    }
}

char a1=row1[strlen(row1)-1];
char a2=row1[strlen(row1)-2];
char a3=row1[strlen(row1)-3];

char b1=row2[strlen(row2)-1];
char b2=row2[strlen(row2)-2];
char b3=row2[strlen(row2)-3];

char c1=row3[strlen(row3)-1];
char c2=row3[strlen(row3)-2];
char c3=row3[strlen(row3)-3];

char d1=row4[strlen(row4)-1];
char d2=row4[strlen(row4)-2];
char d3=row4[strlen(row4)-3];

    if( a1==d1 &&
     a2==d2 &&
     a3==d3 &&
     b1==c1 &&
     b2==c2 &&
     b3==c3 ) {

            printf("1 = 4 and 2 = 3, number of words %c." cur);

}
else if ( a1==c1 &&
          a2==c2 &&
          a3==c3 &&
          b1==d1 &&
          b2==d2 &&
          b3==d3 ) {

            printf("1 = 3 and 2 = 4, number of words %c.", cur);

}
else if ( a1==b1 &&
          a2==b2 &&
          a3==b3 &&
          c1==d1 &&
          c2==d2 &&
          c3==d3 ) {

            printf("1 = 2 and 3 = 4, number of words %c.",cur);

}

else {

        printf("Nijedna rima nije pronadjena u strofi!");

}

return 0;

}

Body:
 char * stpcpy(char * restrict dst, const char * restrict src);

The parameter you passed is not of type char*.

Also you can't concatenate strings using + in c. Use strcat or strncat.

As reply to user's comment :-

There are 3 things that you should keep in mind

First parameter should be modifiable.

First parameter has enough space to hold the combined string.

No overlapping between first and second parameter.

With these 3 rules in mind those can be used.


来源: stackexchange

问:
Visual Studio: Match Regex Across Varying Number of Newlines
Given the following HTML:

```<code><tag1>
    <tag2 attr2="val2"/>
</tag1>
<tag1>
    <tag2
    attr2="val2"/>
</tag1>
</code>```

I want to wipe out all tag2's in that HTML with one regex in Visual Studio.

To match the first:
\<tag2.+\/\>

To match the second:
\<tag2.*\n.*\/\>

So suppose I want to merge these 2 strategies to match both. None of the below match both tag2 tags:

```<code>\<tag2.*\/\>
\<tag2[.\n]*\/\>
\<tag2.*\n?.*\/\>
\<tag2[.\r\n]*\/\>
</code>```

I get:
First tag
No match
No match
No match

They really ought to, but it seems as though the variable number of newlines causes VS to never match. Bug?

This plagues me in VS2005, VS2008, and VS2010.

答:
. should be outside the [], otherwise it matches only a single literal . character. Try:

```<code>\<tag2(.|[\r\n])*\/\>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Given the following HTML:

<tag1>
    <tag2 attr2="val2"/>
</tag1>
<tag1>
    <tag2
    attr2="val2"/>
</tag1>

I want to wipe out all tag2's in that HTML with one regex in Visual Studio.

To match the first:
\<tag2.+\/\>

To match the second:
\<tag2.*\n.*\/\>

So suppose I want to merge these 2 strategies to match both. None of the below match both tag2 tags:

\<tag2.*\/\>
\<tag2[.\n]*\/\>
\<tag2.*\n?.*\/\>
\<tag2[.\r\n]*\/\>

I get:
First tag
No match
No match
No match

They really ought to, but it seems as though the variable number of newlines causes VS to never match. Bug?

This plagues me in VS2005, VS2008, and VS2010.

Body:
. should be outside the [], otherwise it matches only a single literal . character. Try:

\<tag2(.|[\r\n])*\/\>


问:
How do I end a method in Java after a certain amount of time?
I would like to force a method to end after a certain amount of time even if it has not completed its task. How would I go about doing this?

Edit (added clarification and code):
I am programming a robot using Android Studio for the FTC (First Tech Challenge) robotics competition. To control the robot, I am using the FTC SDK (see https://github.com/ftctechnh/ftc_app).

The method works fine for going a particular distance and then stopping but after it stops by setting the power of all the motors to zero, it appears to get hung and no subsequent methods are invoked. Currently, it is only supposed to have the motors be stopped for one second before exiting but it appears to still get stuck on the first invocation of the method that sets the motor power to zero (setPower). For this reason, I would like to be able to terminate setPower after it has been running for a certain amount of time so that my method can exit and subsequent methods can be invoked.

Here is my method:

```<code>public void moveLine(DcMotor m1, DcMotor m2, DcMotor m3, DcMotor m4, double distance /* distance to move in meters */, double motorPower /* power to set the motors */) {

    final double SPROCKET_CIRCUMFRENCE = Math.PI * 0.0652; //calculates the circumference of the sprocket
    final int ENCODER_CPR_NR60 = 1680; //encoder counts for NeveRest 60
    //final static int ENCODER_CPR_NR40 = 1120; //encoder counts for NeveRest 40

    double amountOfRotationsCalc = distance / SPROCKET_CIRCUMFRENCE; //calculates the amount of rotations to move to reach the target distance

    double amountOfEncUnitsCalc = ENCODER_CPR_NR60 * amountOfRotationsCalc; //calculates the amount of encoder units to move

    //this gets the sum of the encoder positions of the drive motors
    int currentEncPosSum = m1.getCurrentPosition() + m2.getCurrentPosition() + m3.getCurrentPosition() + m4.getCurrentPosition();

    //this gets the average encoder position
    int currentEncPosAvg = currentEncPosSum / 4;

    //if the robot is supposed to be moving forward (positive distance), the motors will be set to positive values
    if (distance > 0) {

        //it may make sense to make this a while loop. Will this fix the issue?
        if (currentEncPosAvg < amountOfEncUnitsCalc) {
            m1.setPower(motorPower);
            m2.setPower(motorPower);
            m3.setPower(motorPower);
            m4.setPower(motorPower);
        } else {
            //these stop the robot. Without them, it continues to move.
            long start = System.currentTimeMillis();
            long end = start + 1000;
            while (System.currentTimeMillis() < end) {
                m1.setPower(0);
                m2.setPower(0);
                m3.setPower(0);
                m4.setPower(0);
            }
            return; //this is supposed to exit this method
        }

    } else {

        //this is essentially the opposite of the code for going forwards
        if (currentEncPosAvg > amountOfEncUnitsCalc) {
            m1.setPower(-motorPower);
            m2.setPower(-motorPower);
            m3.setPower(-motorPower);
            m4.setPower(-motorPower);
        } else {
            //these stop the robot. Without them, it continues to move.
            long start = System.currentTimeMillis();
            long end = start + 1000;
            while (System.currentTimeMillis() < end) {
                m1.setPower(0);
                m2.setPower(0);
                m3.setPower(0);
                m4.setPower(0);
            }
            return;
        }

    }

}
</code>```

答:
I know this question is a bit old, but in the latest ftc_app Android SDKs it is recommended that for time aware methods and procedures that teams use the ElapsedTime class.

The most important thing to consider when pausing an opmode is that you can still shut it down when the stop button is pressed on the driver station app. you can make sure of this by including the opModeIsActive() method in your while condition

On our team we have a method for pausing OpModes that looks something like this. we have this declared in a separate class used for library purposes.

```<code>public static void pauseOpMode(LinearOpmode op, ElapsedTime et, double waitTime){
    double startTime = et.milliseconds();
    while (op.opModeIsActive() && et.milliseconds() < startTime + waitTime){}
}
</code>```

Now that this method exists, in our OpMode we can create an Elapsed time Object and pass the necessarry parameters to the function required to pause the OpMode

```<code>class someOpMode extends LinearOpMode{
    ElapsedTime gameTimer = new ElapsedTime();
    @Override
    public void RunOpMode(){
        //pause program for 5 seconds
        pauseOpMode(this,gameTimer,5000);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to force a method to end after a certain amount of time even if it has not completed its task. How would I go about doing this?

Edit (added clarification and code):
I am programming a robot using Android Studio for the FTC (First Tech Challenge) robotics competition. To control the robot, I am using the FTC SDK (see https://github.com/ftctechnh/ftc_app).

The method works fine for going a particular distance and then stopping but after it stops by setting the power of all the motors to zero, it appears to get hung and no subsequent methods are invoked. Currently, it is only supposed to have the motors be stopped for one second before exiting but it appears to still get stuck on the first invocation of the method that sets the motor power to zero (setPower). For this reason, I would like to be able to terminate setPower after it has been running for a certain amount of time so that my method can exit and subsequent methods can be invoked.

Here is my method:

public void moveLine(DcMotor m1, DcMotor m2, DcMotor m3, DcMotor m4, double distance /* distance to move in meters */, double motorPower /* power to set the motors */) {

    final double SPROCKET_CIRCUMFRENCE = Math.PI * 0.0652; //calculates the circumference of the sprocket
    final int ENCODER_CPR_NR60 = 1680; //encoder counts for NeveRest 60
    //final static int ENCODER_CPR_NR40 = 1120; //encoder counts for NeveRest 40

    double amountOfRotationsCalc = distance / SPROCKET_CIRCUMFRENCE; //calculates the amount of rotations to move to reach the target distance

    double amountOfEncUnitsCalc = ENCODER_CPR_NR60 * amountOfRotationsCalc; //calculates the amount of encoder units to move

    //this gets the sum of the encoder positions of the drive motors
    int currentEncPosSum = m1.getCurrentPosition() + m2.getCurrentPosition() + m3.getCurrentPosition() + m4.getCurrentPosition();

    //this gets the average encoder position
    int currentEncPosAvg = currentEncPosSum / 4;

    //if the robot is supposed to be moving forward (positive distance), the motors will be set to positive values
    if (distance > 0) {

        //it may make sense to make this a while loop. Will this fix the issue?
        if (currentEncPosAvg < amountOfEncUnitsCalc) {
            m1.setPower(motorPower);
            m2.setPower(motorPower);
            m3.setPower(motorPower);
            m4.setPower(motorPower);
        } else {
            //these stop the robot. Without them, it continues to move.
            long start = System.currentTimeMillis();
            long end = start + 1000;
            while (System.currentTimeMillis() < end) {
                m1.setPower(0);
                m2.setPower(0);
                m3.setPower(0);
                m4.setPower(0);
            }
            return; //this is supposed to exit this method
        }

    } else {

        //this is essentially the opposite of the code for going forwards
        if (currentEncPosAvg > amountOfEncUnitsCalc) {
            m1.setPower(-motorPower);
            m2.setPower(-motorPower);
            m3.setPower(-motorPower);
            m4.setPower(-motorPower);
        } else {
            //these stop the robot. Without them, it continues to move.
            long start = System.currentTimeMillis();
            long end = start + 1000;
            while (System.currentTimeMillis() < end) {
                m1.setPower(0);
                m2.setPower(0);
                m3.setPower(0);
                m4.setPower(0);
            }
            return;
        }

    }

}

Body:
I know this question is a bit old, but in the latest ftc_app Android SDKs it is recommended that for time aware methods and procedures that teams use the ElapsedTime class.

The most important thing to consider when pausing an opmode is that you can still shut it down when the stop button is pressed on the driver station app. you can make sure of this by including the opModeIsActive() method in your while condition

On our team we have a method for pausing OpModes that looks something like this. we have this declared in a separate class used for library purposes.

public static void pauseOpMode(LinearOpmode op, ElapsedTime et, double waitTime){
    double startTime = et.milliseconds();
    while (op.opModeIsActive() && et.milliseconds() < startTime + waitTime){}
}

Now that this method exists, in our OpMode we can create an Elapsed time Object and pass the necessarry parameters to the function required to pause the OpMode

class someOpMode extends LinearOpMode{
    ElapsedTime gameTimer = new ElapsedTime();
    @Override
    public void RunOpMode(){
        //pause program for 5 seconds
        pauseOpMode(this,gameTimer,5000);
    }
}


问:
Vertical align of different buttons inside a div
I have a bar with some buttons:

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
      margin-bottom: 10px;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

<div class="Languages">
    <button class="Type1" data-id="1">English</button>
    <button class="Type1" data-id="1">French</button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>
</div>

 <div class="Languages">
    <button class="Type1" data-id="1"></button>
    <button class="Type1" data-id="1"></button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>
</div>  </code>```

The first buttons fill the vertical space, and I want the second ones to be vertically centered. But I can't.

This has something to do with the text inside the buttons and the vertical align, with texts the buttons have a different vertical align that without them.

Does anyone know how to center vertically the second ones, with or without text, and without using flexbox?

答:
Add vertical-align to Type1 class. </p>

```<code>.Type1 {
  position: relative;
  height: 100%;
  width: 100px;
  font-size: 18px;
  margin-right: 10px;
  line-height: 62px;
  box-sizing: border-box;
  background-color: tomato;
  border: 0;
  padding: 0;
    vertical-align: middle;
}
</code>```

Body:
I have a bar with some buttons:

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
      margin-bottom: 10px;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }

    <button class="Type1" data-id="1">English</button>
    <button class="Type1" data-id="1">French</button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>

    <button class="Type1" data-id="1"></button>
    <button class="Type1" data-id="1"></button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>

The first buttons fill the vertical space, and I want the second ones to be vertically centered. But I can't.

This has something to do with the text inside the buttons and the vertical align, with texts the buttons have a different vertical align that without them.

Does anyone know how to center vertically the second ones, with or without text, and without using flexbox?

Body:
Add vertical-align to Type1 class.

.Type1 {
  position: relative;
  height: 100%;
  width: 100px;
  font-size: 18px;
  margin-right: 10px;
  line-height: 62px;
  box-sizing: border-box;
  background-color: tomato;
  border: 0;
  padding: 0;
    vertical-align: middle;
}


问:
Bash call function from another file while using symbolic link
I've create two bash files and place these in the same project folder. I've linked bash file one with this command ln -s ~/{path_to_bash_file_one} x. Now I want to use a function from bash file two inside bash file one like below.

Bash file one:

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

# include files
source  ./bash_file_two.sh

echo "hello " ${someFunc}
</code>```

Bash file two:

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

someFunc () {
    echo "someone"
}
</code>```

When I call it the terminal returns this error /usr/local/bin/x: line 135: someoneFunc: command not found. So my question is what's the right path to use when a file that's linked by a symbolic link?

答:
The error

```<code>/usr/local/bin/x: line 135: someoneFunc: command not found
</code>```

has got nothing to do with symbolic link imho.

Change bash file two to

```<code>someoneFunc () {
    echo "someone"
}
</code>```

Source it

```<code>. /path/to/bash/file2
./path/to/x # Then run x
</code>```

Also, the usage

```<code>echo "hello " someOneFunc
</code>```

doesn't look right at first sight. Did you, instead , look for command substitution

```<code>echo "hello " $(someOneFunc)
</code>```

Body:
I've create two bash files and place these in the same project folder. I've linked bash file one with this command ln -s ~/{path_to_bash_file_one} x. Now I want to use a function from bash file two inside bash file one like below.

Bash file one:

#!/usr/bin/env bash

# include files
source  ./bash_file_two.sh

echo "hello " ${someFunc}

Bash file two:

#!/bin/bash

someFunc () {
    echo "someone"
}

When I call it the terminal returns this error /usr/local/bin/x: line 135: someoneFunc: command not found. So my question is what's the right path to use when a file that's linked by a symbolic link?

Body:
The error

/usr/local/bin/x: line 135: someoneFunc: command not found

has got nothing to do with symbolic link imho.

Change bash file two to

someoneFunc () {
    echo "someone"
}

Source it

. /path/to/bash/file2
./path/to/x # Then run x

Also, the usage

echo "hello " someOneFunc

doesn't look right at first sight. Did you, instead , look for command substitution

echo "hello " $(someOneFunc)


答:
Add the following line to the code of type 1 class;

```<code>vertical-align: middle;
</code>```

CSS code should be like this;

```<code>.Type1 {
  position: relative;
  height: 100%;
  width: 100px;
  font-size: 18px;
  margin-right: 10px;
  line-height: 62px;
  box-sizing: border-box;
  background-color: tomato;
  border: 0;
  padding: 0;
  vertical-align: middle;
}
</code>```

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Languages">
        <button class="Type1" data-id="1">English</button>
        <button class="Type1" data-id="1">French</button>
        <button class="Type2 a"></button>
        <button class="Type2 b"></button>
        <button class="Type2 c"></button>
        <button class="Type2 d"></button>
</div></code>```

Title: Vertical align of different buttons inside a div

Body:
Add the following line to the code of type 1 class;

vertical-align: middle;

CSS code should be like this;

.Type1 {
  position: relative;
  height: 100%;
  width: 100px;
  font-size: 18px;
  margin-right: 10px;
  line-height: 62px;
  box-sizing: border-box;
  background-color: tomato;
  border: 0;
  padding: 0;
  vertical-align: middle;
}

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }

<div class="Languages">
        <button class="Type1" data-id="1">English</button>
        <button class="Type1" data-id="1">French</button>
        <button class="Type2 a"></button>
        <button class="Type2 b"></button>
        <button class="Type2 c"></button>
        <button class="Type2 d"></button>
</div>


问:
What is the difference between `->>` and `->` in Postgres SQL?
What is the difference between ->> and -> in SQL?

In this thread (Check if field exists in json type column postgresql), the answerer basically recommends using,

```<code>json->'attribute' is not null
</code>```

instead of,

```<code>json->>'attribute' is not null
</code>```

Why use a single arrow instead of a double arrow? In my limited experience, both do the same thing.

答:
PostgreSQL provides two native operators -> and ->> to help you query JSON data.

The operator -> returns JSON object field as JSON.
The operator ->> returns JSON object field as text.

The following query uses operator -> to get all customers in form of JSON:

SELECT
 info -> 'customer' AS customer
FROM
 orders;
```
```customer
--------
"John Doe"
"Lily Bush"
"Josh William"
"Mary Clark"
```
<p>And the following query uses operator <code>->></code> to get all customers in form of text:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
 info ->> 'customer' AS customer
FROM
 orders;
</code>```
```<code>customer
--------
John Doe
Lily Bush
Josh William
Mary Clark
</code>```

You can see more details in the link below
http://www.postgresqltutorial.com/postgresql-json/

Body:
What is the difference between ->> and -> in SQL?

In this thread (Check if field exists in json type column postgresql), the answerer basically recommends using,

json->'attribute' is not null

instead of,

json->>'attribute' is not null

Why use a single arrow instead of a double arrow? In my limited experience, both do the same thing.

Body:
PostgreSQL provides two native operators -> and ->> to help you query JSON data.

The operator -> returns JSON object field as JSON.
The operator ->> returns JSON object field as text.

The following query uses operator -> to get all customers in form of JSON:

SELECT
 info -> 'customer' AS customer
FROM
 orders;

customer
--------
"John Doe"
"Lily Bush"
"Josh William"
"Mary Clark"

And the following query uses operator ->> to get all customers in form of text:

SELECT
 info ->> 'customer' AS customer
FROM
 orders;

customer
--------
John Doe
Lily Bush
Josh William
Mary Clark

You can see more details in the link below
http://www.postgresqltutorial.com/postgresql-json/

ContentLicense: CC BY-SA 4.0


问:
How do i get my txt file named with 2 user inputs
My txt file created of each month has to be in the format as follow: "expense_month_year.txt".

Also, i can't get my output file to become txt file.

Please advice

```<code>using namespace std;

int main() {

    string month;
    int year;

    ofstream file;

    cout << "Please enter the month." << endl;
    getline(cin,month);

    cout << "Please enter the year." << endl;
    cin >> year;

    //Example of txt file has to be named as follow "expenses_January_2017"
    file.open(month.c_str() );
    file.close();

    return 0;
}
</code>```

答:
Use std::stringstream

```<code>#include <sstream>

string month
int year;

stringstream filename;

cin >> month;
cin >> year;

filename << "expenses_" << month << "_" << year;
ofstream file(filename.str());

// . . .
</code>```

Body:
My txt file created of each month has to be in the format as follow: "expense_month_year.txt".

Also, i can't get my output file to become txt file.

Please advice

using namespace std;

int main() {

    string month;
    int year;

    ofstream file;

    cout << "Please enter the month." << endl;
    getline(cin,month);

    cout << "Please enter the year." << endl;
    cin >> year;

    //Example of txt file has to be named as follow "expenses_January_2017"
    file.open(month.c_str() );
    file.close();

    return 0;
}

Body:
Use std::stringstream

#include <sstream>

string month
int year;

stringstream filename;

cin >> month;
cin >> year;

filename << "expenses_" << month << "_" << year;
ofstream file(filename.str());

// . . .


问:
Laravel 5.5 native multiauth with multiple model relation
I want to use Laravel native multi-auth for many types of user like students, schools, and admins.

I have 5 tables for this like:

user_types: stores types of users

users: stores login credentials

admins: stores other details for admins

students: stores other details for students

schools: stores other details for schools

I am struggling a long time for this. Can anyone give me the idea, how to acheive this? Thanks in advance.

The difference is that I am storing email/passwords for all users in the "user" table and other information in their respective tables.

答:
You should store all your user types in a single users table and then create different roles (users, admins, students, schools etc) in a roles table. Use a pivot table to assign relation between user and roles (user_roles).

Once you acheive this relation you can create different middleware to check for the roles and access autorization. See Detailed turorial here

https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/


问:
how do i find element  and click
Can someone help me how do i find  and click on it using Protractor

```<code><div class="col-md-3 col-sm-6 col-xs-8">
    <div class="nav-control pull-right">
            <li>
                <a class="btn theme-button" ng-click="loginSignUp()">Login/Signup</a>
            </li>
        </ul>
    </div>
</div>
</code>```

My attempts but none of them successfully so for.

```<code>$('.nav-control pull-right a').click();

var li = element(by.xpath('//ul/li/a'));
expect(li.getText()).toBe('Doge meme');

// by class name
element(by.className('btn theme-button')).click();

// by css
element(by.css('.btn')).click();
element(by.xpath('.//*[.="Login/Signup"]')).click();
element(by.xpath('//*[@id="top"]/div[4]/div/div/div[1]/div/div[1]/div[3]/div/ul/li/a')).click();
</code>```

Update:

I am able to click the  tag with following code.

```<code>  let el = element(by.cssContainingText('a', 'Login/Signup'));
  var EC = protractor.ExpectedConditions;
  browser.driver.wait(function () {
      browser.wait(EC.visibilityOf(el), 10000);
      browser.driver.manage().window().setSize(1280, 1024);
      el.click();
  });
</code>```

However, even it clicks the anchor tag but still complains in the console

Failed: unknown error: Element ... is not clickable at point (1164, 27).
  Other element would receive the click: ...
        (Session info: chrome=61.0.3163.100)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT
  10.0.15063 x86_64)

答:
A few ways you could do it.  Also just FYI, you are missing a . before some of your classes.  Either way, some of those looks like they may be too vague i.e. (.btn probably applies to multiple elements, but thats an assumption)

Your first few attempts may work if you change this: $('.nav-control pull-right a').click(); to this $('.nav-control.pull-right > li > a').click();

Or, you can try some of the below which should also work:

```<code>let el = $('[ng-click="loginSignUp()"]');
let el = element(by.cssContainingText('a', 'Login/Signup'));
let el = $('a.btn.btn-theme');
</code>```

Title: how do i find element <a> and click

Body:
Can someone help me how do i find  and click on it using Protractor

                Login/Signup

My attempts but none of them successfully so for.

$('.nav-control pull-right a').click();

var li = element(by.xpath('//ul/li/a'));
expect(li.getText()).toBe('Doge meme');

// by class name
element(by.className('btn theme-button')).click();

// by css
element(by.css('.btn')).click();
element(by.xpath('.//*[.="Login/Signup"]')).click();
element(by.xpath('//*[@id="top"]/div[4]/div/div/div[1]/div/div[1]/div[3]/div/ul/li/a')).click();

Update:

I am able to click the  tag with following code.

  let el = element(by.cssContainingText('a', 'Login/Signup'));
  var EC = protractor.ExpectedConditions;
  browser.driver.wait(function () {
      browser.wait(EC.visibilityOf(el), 10000);
      browser.driver.manage().window().setSize(1280, 1024);
      el.click();
  });

However, even it clicks the anchor tag but still complains in the console

Failed: unknown error: Element ... is not clickable at point (1164, 27).
  Other element would receive the click: ...
        (Session info: chrome=61.0.3163.100)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT
  10.0.15063 x86_64)

Body:
A few ways you could do it.  Also just FYI, you are missing a . before some of your classes.  Either way, some of those looks like they may be too vague i.e. (.btn probably applies to multiple elements, but thats an assumption)

Your first few attempts may work if you change this: $('.nav-control pull-right a').click(); to this $('.nav-control.pull-right > li > a').click();

Or, you can try some of the below which should also work:

let el = $('[ng-click="loginSignUp()"]');
let el = element(by.cssContainingText('a', 'Login/Signup'));
let el = $('a.btn.btn-theme');


问:
Scala type mismatch when method return type is added
I have a method that runs when there is no specified return type, but as soon as the return type is added, a mismatch error is given. The return type of the returned value is the same.

This works fine:

```<code>def get_csv_page(url: String){
    scala.io.Source.fromURL(url).getLines.drop(1).toList
 }
</code>```

Returns:

```<code>res2: List[String]
</code>```

But adding : List[String] causes mismatch:

```<code>def get_csv_page(url: String) = List[String]{
    scala.io.Source.fromURL(url).getLines.drop(1).toList
}

:12: error: type mismatch;
 found   : List[String]
 required: String
        scala.io.Source.fromURL(url).getLines.drop(1).toList
                                                             ^
</code>```

答:
This is a syntax error, it should be a : to specify the return type and then an =:

```<code>def get_csv_page(url: String): List[String] = {
    scala.io.Source.fromURL(url).getLines.drop(1).toList
}
</code>```

What you have right now is trying to construct a List literal, which is why it is wanting you to provide a single String for an element of your list.

Body:
I have a method that runs when there is no specified return type, but as soon as the return type is added, a mismatch error is given. The return type of the returned value is the same.

This works fine:

def get_csv_page(url: String){
    scala.io.Source.fromURL(url).getLines.drop(1).toList
 }

Returns:

res2: List[String]

But adding : List[String] causes mismatch:

def get_csv_page(url: String) = List[String]{
    scala.io.Source.fromURL(url).getLines.drop(1).toList
}

:12: error: type mismatch;
 found   : List[String]
 required: String
        scala.io.Source.fromURL(url).getLines.drop(1).toList
                                                             ^

Body:
This is a syntax error, it should be a : to specify the return type and then an =:

def get_csv_page(url: String): List[String] = {
    scala.io.Source.fromURL(url).getLines.drop(1).toList
}

What you have right now is trying to construct a List literal, which is why it is wanting you to provide a single String for an element of your list.


问:
how to generically compare entire java beans?
I've been trying to grok the org.apache.commons.beanutils library for a method/idiom to evaluate for equality all properties between 2 instances i.e. a generic equals() method for beans.

Is there a simple way to do this usnig this library? Or am I going about this the wrong way?
Thanks.

答:
Try EqualsBuilder.reflectionEquals() of commons-lang. EqualsBuilder has a set of methods to include all fields, all non-transient fields and all but certain fields.

If all else fails, the code could serve as a good example how to implement this.

OwnerDisplayName: Aaron Digulla


问:
missing } after property list
I am trying to implement a content slider using jQuery in one of my website; however I keep getting this error:

```<code>missing } after property list
</code>```

Here is my code:

```<code><script type='text/javascript'>

featuredcontentslider.init({
id: 'slider1',
contentsource: ['inline', ''],
toc: '#increment',
nextprev: ['prev', 'next'],
revealtype: 'click',
enablefade: [true, 0.1],
autorotate: [true, 3000]
});
</script>
</code>```

When I click on view source in Firefox I found that the last curly bracket is missing but in the file the code is fine, and using firebug debug console I got this error:

```<code>missing } after property list
</code>```

I tried many things, searched for missing commas, eliminate most of the lines but could not find the source of the problem.

EDIT:
Firebug points to this line:

```<code>});
</code>```

as the one with error.

I just checked the script in IE8, Chrome and firefox and in all of the three broweser i get the code like this:

```<code><script type='text/javascript'>

featuredcontentslider.init({
id: 'slider1',
contentsource: ['inline', ''],
toc: '#increment',
nextprev: ['prev', 'next'],
revealtype: 'click',
enablefade: [true, 0.1],
autorotate: [true, 3000]
);  <---- notice the missing bracket
</script>
</code>```

I also tried to write one line only like so:

```<code>featuredcontentslider.init({  id: 'slider1'  });
</code>```

and still ended up with the same error. In localhost the script works fine, however in the actual website the script is functioning correctly.

I am wondering is there a possibility that other js code in the page might affect the behaviour of this one?

答:
Ok I solved the problem by adding an extra curly bracket but I am not sure why that solved the issue. My final script looks like this:

```<code><script type='text/javascript'>

featuredcontentslider.init({
id: 'slider1',
contentsource: ['inline', ''],
toc: '#increment',
nextprev: ['prev', 'next'],
revealtype: 'click',
enablefade: [true, 0.1],
autorotate: [true, 3000]
   } <--- notice the extra bracket
});
</script>
</code>```

and it is cross-browser compatible :)

Title: missing } after property list

Body:
I am trying to implement a content slider using jQuery in one of my website; however I keep getting this error:

missing } after property list

Here is my code:

When I click on view source in Firefox I found that the last curly bracket is missing but in the file the code is fine, and using firebug debug console I got this error:

missing } after property list

I tried many things, searched for missing commas, eliminate most of the lines but could not find the source of the problem.

EDIT:
Firebug points to this line:

});

as the one with error.

I just checked the script in IE8, Chrome and firefox and in all of the three broweser i get the code like this:

I also tried to write one line only like so:

featuredcontentslider.init({  id: 'slider1'  });

and still ended up with the same error. In localhost the script works fine, however in the actual website the script is functioning correctly.

I am wondering is there a possibility that other js code in the page might affect the behaviour of this one?

Body:
Ok I solved the problem by adding an extra curly bracket but I am not sure why that solved the issue. My final script looks like this:

<script type='text/javascript'>

featuredcontentslider.init({
id: 'slider1',
contentsource: ['inline', ''],
toc: '#increment',
nextprev: ['prev', 'next'],
revealtype: 'click',
enablefade: [true, 0.1],
autorotate: [true, 3000]
   } <--- notice the extra bracket
});
</script>

and it is cross-browser compatible :)


问:
How do I automatically adds/whitelist auto scaling instance IPs to the security group
I have some EC2 instances setup with auto scaling. It scaling up and down according to resource usage. These servers accessing some other Ec2 instance and rds instance. It connect using public ip (not using internal/private IP).

Each time new servers created, I have to update other server security group with new ip and logically its impossible, otherwise I have to configure security group to accept traffic from any IP.

How do I automatically white list new IPs on security group and delete those IPs when removing servers ?

Is it possible to attach set of elastic IPs to auto scaling group?

Thank you!

答: You shouldn't be using IP addresses in the security group in this scenario. In the security group rule you should be specifying the ID of the security group that the instances belong to.</p>


问:
Filter an aggregate by string length
I have performed the following query:

```<code>db.Indiv2.aggregate(
{$unwind: '$conso'},
{$group: {_id: {conso:'$conso.nom_commercial', region:"$region"}, sum:
{$sum: 1}}},
{$sort : {sum : -1}},
{$group: {
_id: "$_id.region",
"conso": {
    $first: "$_id.conso"
},
"sum": {
    $first: "$sum"
},
}},
{$sort : {_id : 1}}
);
</code>```

which returns the highest consumed food by region in the following format:

```<code>    {
        "_id" : {
            "conso" : "x",
            "region" : 1
        },
        "sum" : 73226.0
    },
    {
        "_id" : {
            "conso" : "x",
            "region" : 8
        },
        "sum" : 25683.0
    },
    {
        "_id" : {
            "conso" : "grandlait demi �cr�m� uht",
            "region" : 1
        },
        "sum" : 251.0
    }
</code>```

However, a lot of foods do not have names. Such items are named "x" (example above). I would like to filter my query to exclude such items. I am looking for an equivalent of a filter which can either filter strings which length are below 2 characters or filter the string "x".

答:
There is a $redact operator which might be helpful here:

Try:

```<code>db.collection.aggregate([
    //previous aggregations
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$_id.conso" }, 2] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])
</code>```

Title: Filter an aggregate by string length

Body:
I have performed the following query:

db.Indiv2.aggregate(
{$unwind: '$conso'},
{$group: {_id: {conso:'$conso.nom_commercial', region:"$region"}, sum:
{$sum: 1}}},
{$sort : {sum : -1}},
{$group: {
_id: "$_id.region",
"conso": {
    $first: "$_id.conso"
},
"sum": {
    $first: "$sum"
},
}},
{$sort : {_id : 1}}
);

which returns the highest consumed food by region in the following format:

    {
        "_id" : {
            "conso" : "x",
            "region" : 1
        },
        "sum" : 73226.0
    },
    {
        "_id" : {
            "conso" : "x",
            "region" : 8
        },
        "sum" : 25683.0
    },
    {
        "_id" : {
            "conso" : "grandlait demi �cr�m� uht",
            "region" : 1
        },
        "sum" : 251.0
    }

However, a lot of foods do not have names. Such items are named "x" (example above). I would like to filter my query to exclude such items. I am looking for an equivalent of a filter which can either filter strings which length are below 2 characters or filter the string "x".

Body:
There is a $redact operator which might be helpful here:

Try:

db.collection.aggregate([
    //previous aggregations
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$_id.conso" }, 2] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])


问:
Using Javascript to play sounds on buttons
Hi I want to use click to play audio I managed to use Javascript for playing one audio but I need for playing different audios on clicking a particular button.

I am able to play first one but the second one is also playing same audio. I am new in Javascript

function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio.play();
}
```

<pre class="lang-html prettyprint-override"><code><audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play()">
</code>```

(codepen)

答:
Here is a working example:

  function play(){
       var audio = document.getElementById("sound1");
       audio.play();
  }

  function play2(){
       var audio2 = document.getElementById("sound2");
       audio2.play();
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play"  onclick="play()">
<input type="button" value="play2"  onclick="play2()"></code>```

Body:
Hi I want to use click to play audio I managed to use Javascript for playing one audio but I need for playing different audios on clicking a particular button.

I am able to play first one but the second one is also playing same audio. I am new in Javascript

function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio.play();
}

<audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play()">

(codepen)

Body:
Here is a working example:

  function play(){
       var audio = document.getElementById("sound1");
       audio.play();
  }

  function play2(){
       var audio2 = document.getElementById("sound2");
       audio2.play();
  }

<audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play"  onclick="play()">
<input type="button" value="play2"  onclick="play2()">


答:
Try this here I have add pause method also for if someone try to play one audio while other audio is playing, currently running audio will pause and new one will play

var audio = new Audio('https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3')

var audio2 = new Audio('http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3')

function play() {
  audio2.pause();

  audio.play();
}

function play2() {
  audio.pause();
  audio2.play();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play2()"></code>```

Title: Using Javascript to play sounds on buttons

Body:
Try this here I have add pause method also for if someone try to play one audio while other audio is playing, currently running audio will pause and new one will play

var audio = new Audio('https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3')

var audio2 = new Audio('http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3')

function play() {
  audio2.pause();

  audio.play();
}

function play2() {
  audio.pause();
  audio2.play();
}

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play2()">


问:
Android camera2 enable auto flashlight
How can I enable default flashlight turn off or on feature in camera2, Can I enable settings options in it like default camera?

I seen some example like here and here but they are using their own buttons to turn on or off flash, here I want to use the default one by enabling it.

Any suggestions would be appreciated.

答:
You need to set the camera's auto-exposure mode to one of the flash-using ones; generally that's either AE_MODE_ON_AUTO_FLASH or AE_MODE_ON_ALWAYS_FLASH.

You can check which modes are available on your device via AE_AVAILABLE_MODES.

Then you'll need to use the AE precapture trigger before doing the main image capture, so that a preflash can be fired for accurate flash brightness control.

Ensure your preview request has the desired AE flash mode, have it set as the repeating request for your capture session.

Create a new capture request builder with your preview settings.

Set the precapture trigger to START for that builder

Create one request with that builder, and call CameraCaptureSession.capture() with it

Wait for the AE_STATE of PRECAPTURE to appear and disappear; during this time the camera device may light up the flash to measure how bright it needs to be.

Once AE_STATE_PRECAPTURE ends, issue the high-resolution capture request using the STILL_CAPTURE template (which sets the capture intent control to STILL_CAPTURE, triggering the main flash firing).

The Camera2Basic sample includes all this for flash operation, as a sample to follow. It uses AE_MODE_AUTO_FLASH if supported by the device.

Title: Android camera2 enable auto flashlight


问:
How to program Bios to automatically power up the computer at a specific date and time
I want to set the BIOS to power up the computer at a specific date and time. I can do it directly in BIOS but I want to do it in a program (made with Delphi).

I am aware that I can do this with scheduled tasks but I specifically wish to avoid using them.

I saw other programs that are able to do that so it's doable.

Does anyone know how to implement this...?

Thank you in advance for any reply.

答:
What you're asking is specific to the board manufacturer. Allowing arbitrary applications to modify bios settings is a security risk and is generally prevented by both the BIOS and OS. Both Dell and HP provide software which is tied to their hardware that can modify some system settings but I don't think this is available to just any application. My HP laptop came with a utility to change a few system settings without needing to go to the CMOS setup screen but most management software I've seen targets enterprise servers and workstations.

http://content.dell.com/us/en/enterprise/by-technology-systems-management.aspx
http://h18000.www1.hp.com/products/servers/management/hpsim/index.html

You can also check out the Distributed Management Taskforce. It is a standards body that maintains specifications for querying BIOS settings. I haven't looked deep enough to see if there is a standard for changing settings as well.


问:
ConstraintLayout make cell items fit screen viewport
I am trying to create a screen which should look like this

But when I create the view using the XML code as per below

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fb_constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="me.buddy.buddy.ui.BenefitsActivity$BenefitsFragment">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_animals"
        android:src="@drawable/animal_love"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_environment"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_meal_data"
        android:src="@drawable/food"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@id/fb_animals"
        app:layout_constraintBottom_toTopOf="@id/fb_health"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_environment"
        android:src="@drawable/environment"

        app:layout_constraintTop_toBottomOf="@id/fb_animals"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_health"
        app:layout_constraintBottom_toTopOf="@id/fb_hunger"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_health"
        android:src="@drawable/health"

        app:layout_constraintTop_toBottomOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_section_label"
        app:layout_constraintLeft_toRightOf="@id/fb_environment"
        app:layout_constraintRight_toRightOf="parent"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_hunger"
        android:src="@drawable/bowl"

        app:layout_constraintTop_toBottomOf="@id/fb_environment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_section_label"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_section_label"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"

        app:layout_constraintTop_toBottomOf="@id/fb_health"
        app:layout_constraintLeft_toRightOf="@id/fb_hunger"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>
</code>```

I am getting a screen like below in my app

Do note that this layout is inside a fragment of an activity as depicted in the tools tag in the xml. Hence the additional floating action button and the back arrow in the actual layout.

However what I am not able to understand is why is icon of the food bowl getting pushed below the visible screen space in the actual layout.

Any resolution to this issue? I would like to avoid using Scrollview as much as possible.

For reference, XML Code of parent activity is attached below

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="me.buddy.buddy.ui.BenefitsActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/ab_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/ab_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/ab_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/ab_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_share" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Java code for adding fragment to main activity as per below:

First the parent class:

```<code>setContentView(R.layout.activity_benefits);
Toolbar toolbar = (Toolbar) findViewById(R.id.ab_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.ab_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
</code>```

Then inside Fragment class:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_benefits_dashboard, container, false);
return rootView;}
</code>```

答:
The problem you are trying to solve is easily accomplished using ConstraintLayout Guidelines.

You just define 2 horizontal guidelines: one at 33%, the other one at 66%.
Then all you have to do, is to position your views relative to these guidelines.

Here's a skeleton implementation of your screen:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#53d94f"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toStartOf="@+id/view2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#d9c74f"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view1"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#4f68d9"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toStartOf="@+id/view4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/guideline" />

    <View
        android:id="@+id/view4"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#d95a4f"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view3"
        app:layout_constraintTop_toTopOf="@id/guideline" />

    <View
        android:id="@+id/view5"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#4fd4d9"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/view6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/guideline2" />

    <View
        android:id="@+id/view6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#c94fd9"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view5"
        app:layout_constraintTop_toBottomOf="@+id/guideline2" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.33" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.66" />
</android.support.constraint.ConstraintLayout>
</code>```

Here's the output:

Body:
I am trying to create a screen which should look like this

But when I create the view using the XML code as per below

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fb_constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="me.buddy.buddy.ui.BenefitsActivity$BenefitsFragment">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_animals"
        android:src="@drawable/animal_love"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_environment"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_meal_data"
        android:src="@drawable/food"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@id/fb_animals"
        app:layout_constraintBottom_toTopOf="@id/fb_health"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_environment"
        android:src="@drawable/environment"

        app:layout_constraintTop_toBottomOf="@id/fb_animals"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_health"
        app:layout_constraintBottom_toTopOf="@id/fb_hunger"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_health"
        android:src="@drawable/health"

        app:layout_constraintTop_toBottomOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_section_label"
        app:layout_constraintLeft_toRightOf="@id/fb_environment"
        app:layout_constraintRight_toRightOf="parent"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_hunger"
        android:src="@drawable/bowl"

        app:layout_constraintTop_toBottomOf="@id/fb_environment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_section_label"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_section_label"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"

        app:layout_constraintTop_toBottomOf="@id/fb_health"
        app:layout_constraintLeft_toRightOf="@id/fb_hunger"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>

I am getting a screen like below in my app

Do note that this layout is inside a fragment of an activity as depicted in the tools tag in the xml. Hence the additional floating action button and the back arrow in the actual layout.

However what I am not able to understand is why is icon of the food bowl getting pushed below the visible screen space in the actual layout.

Any resolution to this issue? I would like to avoid using Scrollview as much as possible.

For reference, XML Code of parent activity is attached below

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="me.buddy.buddy.ui.BenefitsActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/ab_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/ab_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/ab_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/ab_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_share" />
</android.support.design.widget.CoordinatorLayout>

Java code for adding fragment to main activity as per below:

First the parent class:

setContentView(R.layout.activity_benefits);
Toolbar toolbar = (Toolbar) findViewById(R.id.ab_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.ab_container);
mViewPager.setAdapter(mSectionsPagerAdapter);

Then inside Fragment class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_benefits_dashboard, container, false);
return rootView;}

Body:
The problem you are trying to solve is easily accomplished using ConstraintLayout Guidelines.

You just define 2 horizontal guidelines: one at 33%, the other one at 66%.
Then all you have to do, is to position your views relative to these guidelines.

Here's a skeleton implementation of your screen:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#53d94f"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toStartOf="@+id/view2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#d9c74f"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view1"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#4f68d9"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toStartOf="@+id/view4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/guideline" />

    <View
        android:id="@+id/view4"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#d95a4f"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view3"
        app:layout_constraintTop_toTopOf="@id/guideline" />

    <View
        android:id="@+id/view5"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#4fd4d9"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/view6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/guideline2" />

    <View
        android:id="@+id/view6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#c94fd9"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view5"
        app:layout_constraintTop_toBottomOf="@+id/guideline2" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.33" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.66" />
</android.support.constraint.ConstraintLayout>

Here's the output:


问:
Access denied when deleting folders created in SQL Server
I am creating directories with xp_cmdshell but I can't delete them after because of the permission, I am not even allowed to see the owner of the folders.
I have to enter in safe mode to be able of delete the folders.
I am using SQL Server 2008.</p>

答:
I'm assuming it's an ACL problem.

A directory created with xp_cmdshell is owned by SQL Server (The service account) and its access rights are inherited from the parent.

If you have to modify the directory's content after its creation, you'll have to :

Create your directory inside another one who already have good access rights.

Or grant more rights after its creation (with xp_cmdshell and icacls to manipulate the ACLs)

Eg, change domain\group & d:\folder_path in the following snippet to whatever suits you to give a group (your users, admins, etc...) full control on a directory :

```<code>exec xp_cmdshell 'icacls "d:\folder_path" /grant "domain\group":(f)'
</code>```

Body:
I'm assuming it's an ACL problem.

A directory created with xp_cmdshell is owned by SQL Server (The service account) and its access rights are inherited from the parent.

If you have to modify the directory's content after its creation, you'll have to :

Create your directory inside another one who already have good access rights.

Or grant more rights after its creation (with xp_cmdshell and icacls to manipulate the ACLs)

Eg, change domain\group & d:\folder_path in the following snippet to whatever suits you to give a group (your users, admins, etc...) full control on a directory :

exec xp_cmdshell 'icacls "d:\folder_path" /grant "domain\group":(f)'


问:
Incorrect graph in Word Ladder challenge
I am trying to implement the word ladder problem where I have to convert one word to another in shortest path possible.Obviously we can use the breadth first search (BFS) to solve it but before that we have to first draw the graph.I have implemented the concept of buckets where certain words fall under a bucket if they match the bucket type.But my graph is not implementing correctly.

The given word list is ["CAT", "BAT", "COT", "COG", "COW", "RAT", "BUT", "CUT", "DOG", "WED"]

So for each word I can create a bucket.For example for the word 'CAT', I can have three buckets _AT, C_T, CA_. Similarly I can create buckets for the rest of the words and which ever words match the bucket type will fall under those buckets.

Implementing with hand should give me a graph like this

Since the graph is undirected, so for the vertex COG, its neighbouring vertices should be DOG, COW, COT (relationship work both ways) but instead I am getting COG is connected to nothing.Here is my code below

```<code>class Vertex:
    def __init__(self,key):
        self.id = key
        self.connectedTo = {}

    def addNeighbour(self,nbr,weight=0):
        self.connectedTo[nbr] = weight

    #string representation of the object
    def __str__(self):
        return str(self.id) + " is connected to " + str([x.id for x in self.connectedTo])

    def getConnections(self):
        return self.connectedTo.keys()

    def getId(self):
        return self.id

    def getWeight(self,nbr):
        return self.connectedTo[nbr]

class Graph:
    def __init__(self):
        self.vertList = {}
        self.numVertices = 0

    def addVertex(self,key):
        self.numVertices += 1
        newVertex = Vertex(key)
        self.vertList[key] = newVertex
        return newVertex

    def getVertex(self,n):
        if n in self.vertList:
            return self.vertList[n]
        else:
            return None

    def addEdge(self,f,t,cost=0):
        if f not in self.vertList:
            nv = self.addVertex(f)

        if t not in self.vertList:
            nv = self.addVertex(t)

        self.addVertex(f).addNeighbour(self.addVertex(t),cost)

    def getVertices(self):
        return self.vertList.keys()

    def __iter__(self):
        return iter(self.vertList.values())

wordList = ["CAT", "BAT", "COT", "COG", "COW", "RAT", "BUT", "CUT", "DOG", "WED"]

def buildGraph(wordList):
    d = {} #in this dictionary the buckets will be the keys and the words will be their values
    g = Graph()
    for i in wordList:
        for j in range(len(i)):
            bucket = i[:j] + "_" + i[j+1:]
            if bucket in d:
                #we are storing the words that fall under the same bucket in a list
                d[bucket].append(i)
            else:
                d[bucket] = [i]

    # create vertices for the words under the buckets and join them
    #print("Dictionary",d)
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                #we ensure same words are not treated as two different vertices
                if word1 != word2:
                    g.addEdge(word1,word2)

    return g

# get the graph object
gobj = buildGraph(wordList)

for v in gobj: #the graph contains a set of vertices
    print(v)
</code>```

The result I get is

```<code>BUT is connected to ['BAT']
CUT is connected to ['COT']
COW is connected to ['COG']
COG is connected to []
CAT is connected to []
DOG is connected to ['COG']
RAT is connected to ['BAT']
COT is connected to []
BAT is connected to []
</code>```

I was hoping the results to be something like

```<code>BUT is connected to ['BAT', 'CUT']
CUT is connected to ['CAT', 'COT', 'BUT']
and so on....
</code>```

What am I doing wrong?

答:
The problem is in your addEdge method.

You are checking if vertices are already present in graph, ok. But if they are present, you are creating new vertices anyway and adding edge for those new vertices, throwing away the previous ones. That's why you have exactly one edge for each vertex in the end.

Just change the last line of addEdge to :

```<code>self.vertList[f].addNeighbour(self.vertList[t],cost)
</code>```

Body:
I am trying to implement the word ladder problem where I have to convert one word to another in shortest path possible.Obviously we can use the breadth first search (BFS) to solve it but before that we have to first draw the graph.I have implemented the concept of buckets where certain words fall under a bucket if they match the bucket type.But my graph is not implementing correctly.

The given word list is ["CAT", "BAT", "COT", "COG", "COW", "RAT", "BUT", "CUT", "DOG", "WED"]

So for each word I can create a bucket.For example for the word 'CAT', I can have three buckets _AT, C_T, CA_. Similarly I can create buckets for the rest of the words and which ever words match the bucket type will fall under those buckets.

Implementing with hand should give me a graph like this

Since the graph is undirected, so for the vertex COG, its neighbouring vertices should be DOG, COW, COT (relationship work both ways) but instead I am getting COG is connected to nothing.Here is my code below

class Vertex:
    def __init__(self,key):
        self.id = key
        self.connectedTo = {}

    def addNeighbour(self,nbr,weight=0):
        self.connectedTo[nbr] = weight

    #string representation of the object
    def __str__(self):
        return str(self.id) + " is connected to " + str([x.id for x in self.connectedTo])

    def getConnections(self):
        return self.connectedTo.keys()

    def getId(self):
        return self.id

    def getWeight(self,nbr):
        return self.connectedTo[nbr]

class Graph:
    def __init__(self):
        self.vertList = {}
        self.numVertices = 0

    def addVertex(self,key):
        self.numVertices += 1
        newVertex = Vertex(key)
        self.vertList[key] = newVertex
        return newVertex

    def getVertex(self,n):
        if n in self.vertList:
            return self.vertList[n]
        else:
            return None

    def addEdge(self,f,t,cost=0):
        if f not in self.vertList:
            nv = self.addVertex(f)

        if t not in self.vertList:
            nv = self.addVertex(t)

        self.addVertex(f).addNeighbour(self.addVertex(t),cost)

    def getVertices(self):
        return self.vertList.keys()

    def __iter__(self):
        return iter(self.vertList.values())

wordList = ["CAT", "BAT", "COT", "COG", "COW", "RAT", "BUT", "CUT", "DOG", "WED"]

def buildGraph(wordList):
    d = {} #in this dictionary the buckets will be the keys and the words will be their values
    g = Graph()
    for i in wordList:
        for j in range(len(i)):
            bucket = i[:j] + "_" + i[j+1:]
            if bucket in d:
                #we are storing the words that fall under the same bucket in a list
                d[bucket].append(i)
            else:
                d[bucket] = [i]

    # create vertices for the words under the buckets and join them
    #print("Dictionary",d)
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                #we ensure same words are not treated as two different vertices
                if word1 != word2:
                    g.addEdge(word1,word2)

    return g

# get the graph object
gobj = buildGraph(wordList)

for v in gobj: #the graph contains a set of vertices
    print(v)

The result I get is

BUT is connected to ['BAT']
CUT is connected to ['COT']
COW is connected to ['COG']
COG is connected to []
CAT is connected to []
DOG is connected to ['COG']
RAT is connected to ['BAT']
COT is connected to []
BAT is connected to []

I was hoping the results to be something like

BUT is connected to ['BAT', 'CUT']
CUT is connected to ['CAT', 'COT', 'BUT']
and so on....

What am I doing wrong?

Body:
The problem is in your addEdge method.

You are checking if vertices are already present in graph, ok. But if they are present, you are creating new vertices anyway and adding edge for those new vertices, throwing away the previous ones. That's why you have exactly one edge for each vertex in the end.

Just change the last line of addEdge to :

self.vertList[f].addNeighbour(self.vertList[t],cost)


问:
Gmail OAuth from within docker container
I have various backend services running in containers. I am writing a microservice to handle the sending of emails.

My email provider for business emails is GSuite (Gmail).

I've been reading the following tutorial

This all seems well and good but it requires human intervention in order to authorise the application to send emails.

I need this to be fully autonomous in that whenever the container starts up it requests access tokens and authorises itself.

Is this possible? I can't seem to find any literature to help

答:
So I found a solution to this and thought I would post it just incase anyone else stumbles across this problem.

The answer to accessing the GMAIL API with no human intervention is service accounts.

Service accounts can impersonate authenticated users. So for instance I now have a service account sending emails as if they are coming from michael@mydomainname.com

I basically followed this

There are a few other steps to setting up service accounts that can be found here

I hope this helps someone.


问:
SQL Query: Select most recent entry for each distinct field value?
i have this table POSITION:

```<code>CREATE TABLE `position` (
  `idposition` bigint(20) NOT NULL AUTO_INCREMENT,
  `latitude` varchar(45) DEFAULT NULL,
  `longitude` varchar(45) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `fk_email` varchar(100) DEFAULT NULL,
</code>```

with this population:

```<code>idposition  latitude    longitude   timestamp              fk_email
        1   39.49333    -0.33667    2010-12-10 17:15:39     david@test.es
         4  39.47333    -0.36167    2010-12-11 09:58:47     ronald@test.es
         5  39.50333    -0.34267    2010-12-10 21:11:10     david@test.es
        10  39.44333    -0.41667    2010-12-12 18:17:26     fanny@test.es
        11  39.45199    -0.31967    2010-12-12 21:01:18     victor@test.es
        12  39.52133    -0.36167    2010-12-12 17:43:11     carlos@test.es
        13  39.43199    -0.31967    2010-12-14 15:45:25     victor@test.es
        14  39.41199    -0.34567    2010-12-14 20:46:09     victor@test.es
        15  39.43433    -0.41667    2010-12-14 17:29:39     maria@test.es
        16  39.44133    -0.42667    2010-12-12 19:17:33     maria@test.es
        17  39.50333    -0.35667    2010-12-13 16:36:22     angel@test.es
        196     39.46454    -0.38978    0000-00-00 00:00:00     fanny@test.es
        271     33.63883    -0.45024    2010-12-17 11:36:45     fanny@test.es
        273     39.46680    -0.39452    2010-12-20 00:00:00     fanny@test.es
        441     39.44133    -0.41467    2010-12-15 17:45:13     carlos@test.es
        5326    39.47316    -0.38351    2011-01-18 18:09:56     pablo@upv.es
</code>```

ok, i want to make  SQL Query, that returns to me THE LAST (NEWEST) POSITION OF EACH FK_EMAIL, i mean, for each fk_email, the position with the last (newest) timestamp, only one position (te last) for each email.

it is possible to do it? can someone help me with the query? is too munch hard for me

答:
```
SELECT idposition, atitude, longitude, timestamp, fk_email
FROM   position

GROUP BY fk_email HAVING MAX( timestamp )
```

Body:
i have this table POSITION:

CREATE TABLE `position` (
  `idposition` bigint(20) NOT NULL AUTO_INCREMENT,
  `latitude` varchar(45) DEFAULT NULL,
  `longitude` varchar(45) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `fk_email` varchar(100) DEFAULT NULL,

with this population:

idposition  latitude    longitude   timestamp              fk_email
        1   39.49333    -0.33667    2010-12-10 17:15:39     david@test.es
         4  39.47333    -0.36167    2010-12-11 09:58:47     ronald@test.es
         5  39.50333    -0.34267    2010-12-10 21:11:10     david@test.es
        10  39.44333    -0.41667    2010-12-12 18:17:26     fanny@test.es
        11  39.45199    -0.31967    2010-12-12 21:01:18     victor@test.es
        12  39.52133    -0.36167    2010-12-12 17:43:11     carlos@test.es
        13  39.43199    -0.31967    2010-12-14 15:45:25     victor@test.es
        14  39.41199    -0.34567    2010-12-14 20:46:09     victor@test.es
        15  39.43433    -0.41667    2010-12-14 17:29:39     maria@test.es
        16  39.44133    -0.42667    2010-12-12 19:17:33     maria@test.es
        17  39.50333    -0.35667    2010-12-13 16:36:22     angel@test.es
        196     39.46454    -0.38978    0000-00-00 00:00:00     fanny@test.es
        271     33.63883    -0.45024    2010-12-17 11:36:45     fanny@test.es
        273     39.46680    -0.39452    2010-12-20 00:00:00     fanny@test.es
        441     39.44133    -0.41467    2010-12-15 17:45:13     carlos@test.es
        5326    39.47316    -0.38351    2011-01-18 18:09:56     pablo@upv.es

ok, i want to make  SQL Query, that returns to me THE LAST (NEWEST) POSITION OF EACH FK_EMAIL, i mean, for each fk_email, the position with the last (newest) timestamp, only one position (te last) for each email.

it is possible to do it? can someone help me with the query? is too munch hard for me


问:
I would like to look up two values to return the value in a specific row
I would like to look up the value in the right-hand table based on the value in Column L as well as the value in that row that is at least the value in column H, and return the value in row 2 of the right-hand table.

Example: find where 2% (from column L) is on the right-hand table, find the column that is at least 2,333,10, and return 30 mph.

答:
Type the following array formula into cell M8:

```<code>= INDEX($Q$4:$U$4,MATCH(TRUE,MMULT(TRANSPOSE($Q$5:$U$11),(L8=$P$5:$P$11)+0)>H8,0))
</code>```

Note, this is an array formula, so you must press Ctrl+Shift+Enter on the keyboard after typing it instead of just Enter.

Also note: This is just sample ranges for a simplified example. You will have to modify the ranges to however far your data extends.

See below for a basic working example. Also in the example below, I dragged this formula down to cell M9 to demonstrate it works when you drag down. I just used sample data because I didn't want to type out all of your data but it returns the expected result.

Body:
Type the following array formula into cell M8:

= INDEX($Q$4:$U$4,MATCH(TRUE,MMULT(TRANSPOSE($Q$5:$U$11),(L8=$P$5:$P$11)+0)>H8,0))

Note, this is an array formula, so you must press Ctrl+Shift+Enter on the keyboard after typing it instead of just Enter.

Also note: This is just sample ranges for a simplified example. You will have to modify the ranges to however far your data extends.

See below for a basic working example. Also in the example below, I dragged this formula down to cell M9 to demonstrate it works when you drag down. I just used sample data because I didn't want to type out all of your data but it returns the expected result.


问:
Typescript: TS2322 with Generics classes
Typescript gives me a hard time with generics. When compiling this project, I get a TS2322 error at return new TransformedBase(); (you can c/c this project in the Typescript playground, it works)

For more context, we have a lot of project using a Core project. The goal is to mutualize all we can into Core, and use Angular injection to change the behaviour in each app.

Since TB extends TransformedBase, and I'm returning a new TransformedBase() why is Typescript refusing to compile?

Thank you

```<code>// Projet 'Core'
class Base {
    a: string;
}

class TransformedBase {
    z: string;
}

class BaseTransformer<B extends Base, TB extends TransformedBase> {
    transform(source: B): TB {
        return new TransformedBase();
    }
}

class GenericService<B extends Base, TB extends TransformedBase> {
    private transformer: BaseTransformer<B, TB>;
    constructor(transformer: BaseTransformer<B, TB>) {
        // transformer is injected
        this.transformer = transformer;
    }

    doWork(source: B): TB {
        return this.transformer.transform(source)
    }
}

// One of the project which use Core
// import Base from 'core/Base'
// import TransformedBase from 'core/TransformedBase'
// import BaseClass from 'core/BaseClass'

class Better extends Base {
    b: string;
}

class TransformedBetter extends TransformedBase {
    w: string;

    constructor(transformedBase: TransformedBase) {
        super();
        // Do something
        this.w = `Hello ${transformedBase.z}`;
    }
}

class BetterTransformer extends BaseTransformer<Better, TransformedBetter> {
    transform(source: Better): TransformedBetter {
        super.transform(source);
        return new TransformedBetter(super.transform(source));
    }
}
</code>```

答:
If all you know is that TB extends TransformedBase then TB is a subtype of TransformedBase.  So every TB is a TransformedBase, but not every TransformedBase is necessarily a TB. So the implementation of transform() in BaseTransformer is incorrect. You'd need to return a new instance of TB but you don't have any constructor for it.

I'd suggest not even having an implementation for BaseTransformer, since it's pretty useless.  Maybe BaseTransformer should be an abstract class or interface instead.

Hope that helps; good luck!

Body:
Typescript gives me a hard time with generics. When compiling this project, I get a TS2322 error at return new TransformedBase(); (you can c/c this project in the Typescript playground, it works)

For more context, we have a lot of project using a Core project. The goal is to mutualize all we can into Core, and use Angular injection to change the behaviour in each app.

Since TB extends TransformedBase, and I'm returning a new TransformedBase() why is Typescript refusing to compile?

Thank you

// Projet 'Core'
class Base {
    a: string;
}

class TransformedBase {
    z: string;
}

class BaseTransformer {
    transform(source: B): TB {
        return new TransformedBase();
    }
}

class GenericService {
    private transformer: BaseTransformer;
    constructor(transformer: BaseTransformer) {
        // transformer is injected
        this.transformer = transformer;
    }

    doWork(source: B): TB {
        return this.transformer.transform(source)
    }
}

// One of the project which use Core
// import Base from 'core/Base'
// import TransformedBase from 'core/TransformedBase'
// import BaseClass from 'core/BaseClass'

class Better extends Base {
    b: string;
}

class TransformedBetter extends TransformedBase {
    w: string;

    constructor(transformedBase: TransformedBase) {
        super();
        // Do something
        this.w = `Hello ${transformedBase.z}`;
    }
}

class BetterTransformer extends BaseTransformer<Better, TransformedBetter> {
    transform(source: Better): TransformedBetter {
        super.transform(source);
        return new TransformedBetter(super.transform(source));
    }
}