问:
update values of only certain rows in dataset1, with values from dataset2 in R - but only the ones that don't match, or else keep the original?
So, I have two dataframes, original and the one made from extracted rows of the original and then changed values in one of the columns.

They both have same no. of columns (10), but the original is bigger than the second one. Type of data is the same in both, and I need to replace values in one column which is made of factors. I've tried left_join and merge but I run into errors, which is probably my mistake, but I don't know what I'm doing wrong as I still don't understand R properly.

eg. dataframe 1:

ALB  Med

SKJ  Eq

ALB  Gyre

BUM  Eq

WHM  Trans

YFT  Eq

dataframe 2:

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

hat I want to get:

ALB  Med

SKJ  Eq

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

Excerpt of original data from R (dataset1):

```<code>    > print(catchesbyPPOW[1:10,])
   Species  Long   Lat tCatch_sqrt        ECOREGION                   REALM          PROVINC TYPE
1      ALB  17.5 -57.5   0.5099020             <NA>     Southern Cold Water        Antarctic PPOW
2      YFT  17.5 -57.5   0.2812472             <NA>     Southern Cold Water        Antarctic PPOW
3      BFT -67.5 -52.5   2.9238673 Patagonian Shelf Temperate South America       Magellanic MEOW
4      BFT -62.5 -52.5   3.2256782             <NA>     Atlantic Warm Water Malvinas Current PPOW
5      ALB -52.5 -52.5   0.2323575             <NA>     Southern Cold Water     Subantarctic PPOW
6      SWO -52.5 -52.5   0.9996549             <NA>     Southern Cold Water     Subantarctic PPOW
7      ALB -32.5 -52.5   0.4097926             <NA>     Southern Cold Water        Antarctic PPOW
8      BET -32.5 -52.5   1.4336387             <NA>     Southern Cold Water        Antarctic PPOW
9      SWO -32.5 -52.5   1.2541730             <NA>     Southern Cold Water        Antarctic PPOW
10     YFT -32.5 -52.5   1.2215236             <NA>     Southern Cold Water        Antarctic PPOW
                BIOME optional
1               Polar     TRUE
2               Polar     TRUE
3                <NA>     TRUE
4  Boundary - western     TRUE
5               Polar     TRUE
6               Polar     TRUE
7               Polar     TRUE
8               Polar     TRUE
9               Polar     TRUE
10              Polar     TRUE
</code>```

Dataset 2:

```<code>> print(outliers[1:10,])
    Species  Long   Lat tCatch_sqrt                  ECOREGION                   REALM TYPE BIOME optional
3       BFT -67.5 -52.5   2.9238673           Patagonian Shelf Temperate South America MEOW  <NA>     TRUE
39      SWO -62.5 -42.5   0.6316645     North Patagonian Gulfs Temperate South America MEOW  <NA>     TRUE
130     ALB -57.5 -37.5   7.6342489 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
131     BET -57.5 -37.5   0.8367258 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
132     BUM -57.5 -37.5   0.5127475 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
133     SAI -57.5 -37.5   1.3915028 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
134     SKJ -57.5 -37.5   1.2453915 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
135     SWO -57.5 -37.5   2.4453357 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
136     WHM -57.5 -37.5   0.2320991 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
137     YFT -57.5 -37.5   2.2360680 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
             PROVINC
3   Malvinas Current
39  Malvinas Current
130 Malvinas Current
131 Malvinas Current
132 Malvinas Current
133 Malvinas Current
134 Malvinas Current
135 Malvinas Current
136 Malvinas Current
137 Malvinas Current
</code>```

I deleted my failed attempts, I just have the latest one I tried with left_join:

```<code>PPOWoutliers<-left_join(catchesbyPPOW, outliers, by = NULL)
</code>```

Which gave me this warning:

```<code>Joining, by = c("Species", "Long", "Lat", "tCatch_sqrt", "ECOREGION", "REALM", "PROVINC", "TYPE", "BIOME", "optional")
Warning message:
In left_join_impl(x, y, by$x, by$y, suffix$x, suffix$y) :
  joining factors with different levels, coercing to character vector
</code>```

答:
EDITED to reflect that you may not have the same columns on both data sets

Merge doesn't take into account row names.

Try this:

```<code>columns_to_replace <- c("ECOREGION","REALM","TYPE")
dfnew <- df1
dfnew[as.numeric(rownames(df2)),columns_to_replace] <- df2[,columns_to_replace]
</code>```

or this if you have the same columns on both datasets:

```<code>dfnew[as.numeric(rownames(df2)),] <- df2
</code>```

Body:
So, I have two dataframes, original and the one made from extracted rows of the original and then changed values in one of the columns.

They both have same no. of columns (10), but the original is bigger than the second one. Type of data is the same in both, and I need to replace values in one column which is made of factors. I've tried left_join and merge but I run into errors, which is probably my mistake, but I don't know what I'm doing wrong as I still don't understand R properly.

eg. dataframe 1:

ALB  Med

SKJ  Eq

ALB  Gyre

BUM  Eq

WHM  Trans

YFT  Eq

dataframe 2:

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

hat I want to get:

ALB  Med

SKJ  Eq

ALB  North Atl

BUM  South Atl

WHM  Gyre

YFT  Gyre

Excerpt of original data from R (dataset1):

    > print(catchesbyPPOW[1:10,])
   Species  Long   Lat tCatch_sqrt        ECOREGION                   REALM          PROVINC TYPE
1      ALB  17.5 -57.5   0.5099020             <NA>     Southern Cold Water        Antarctic PPOW
2      YFT  17.5 -57.5   0.2812472             <NA>     Southern Cold Water        Antarctic PPOW
3      BFT -67.5 -52.5   2.9238673 Patagonian Shelf Temperate South America       Magellanic MEOW
4      BFT -62.5 -52.5   3.2256782             <NA>     Atlantic Warm Water Malvinas Current PPOW
5      ALB -52.5 -52.5   0.2323575             <NA>     Southern Cold Water     Subantarctic PPOW
6      SWO -52.5 -52.5   0.9996549             <NA>     Southern Cold Water     Subantarctic PPOW
7      ALB -32.5 -52.5   0.4097926             <NA>     Southern Cold Water        Antarctic PPOW
8      BET -32.5 -52.5   1.4336387             <NA>     Southern Cold Water        Antarctic PPOW
9      SWO -32.5 -52.5   1.2541730             <NA>     Southern Cold Water        Antarctic PPOW
10     YFT -32.5 -52.5   1.2215236             <NA>     Southern Cold Water        Antarctic PPOW
                BIOME optional
1               Polar     TRUE
2               Polar     TRUE
3                <NA>     TRUE
4  Boundary - western     TRUE
5               Polar     TRUE
6               Polar     TRUE
7               Polar     TRUE
8               Polar     TRUE
9               Polar     TRUE
10              Polar     TRUE

Dataset 2:

> print(outliers[1:10,])
    Species  Long   Lat tCatch_sqrt                  ECOREGION                   REALM TYPE BIOME optional
3       BFT -67.5 -52.5   2.9238673           Patagonian Shelf Temperate South America MEOW  <NA>     TRUE
39      SWO -62.5 -42.5   0.6316645     North Patagonian Gulfs Temperate South America MEOW  <NA>     TRUE
130     ALB -57.5 -37.5   7.6342489 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
131     BET -57.5 -37.5   0.8367258 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
132     BUM -57.5 -37.5   0.5127475 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
133     SAI -57.5 -37.5   1.3915028 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
134     SKJ -57.5 -37.5   1.2453915 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
135     SWO -57.5 -37.5   2.4453357 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
136     WHM -57.5 -37.5   0.2320991 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
137     YFT -57.5 -37.5   2.2360680 Uruguay-Buenos Aires Shelf Temperate South America MEOW  <NA>     TRUE
             PROVINC
3   Malvinas Current
39  Malvinas Current
130 Malvinas Current
131 Malvinas Current
132 Malvinas Current
133 Malvinas Current
134 Malvinas Current
135 Malvinas Current
136 Malvinas Current
137 Malvinas Current

I deleted my failed attempts, I just have the latest one I tried with left_join:

PPOWoutliers<-left_join(catchesbyPPOW, outliers, by = NULL)

Which gave me this warning:

Joining, by = c("Species", "Long", "Lat", "tCatch_sqrt", "ECOREGION", "REALM", "PROVINC", "TYPE", "BIOME", "optional")
Warning message:
In left_join_impl(x, y, by$x, by$y, suffix$x, suffix$y) :
  joining factors with different levels, coercing to character vector

Body:
EDITED to reflect that you may not have the same columns on both data sets

Merge doesn't take into account row names.

Try this:

columns_to_replace <- c("ECOREGION","REALM","TYPE")
dfnew <- df1
dfnew[as.numeric(rownames(df2)),columns_to_replace] <- df2[,columns_to_replace]

or this if you have the same columns on both datasets:

dfnew[as.numeric(rownames(df2)),] <- df2


来源: stackexchange

问:
How to get next cucumber step after passed if it is failed
I have AfterStep hook which can give me a step name. But it gives only name of passed step.

```<code>AfterStep do |result, step|
  puts step.name
end
</code>```

How to get next cucumber step after passed if next is failed?
Or how to get name of failed step?

Maybe somehow to calculate step position and take another one?

Any ideas?
I am sure that it is possible because we can see failed step name in error log.

答:
Found. We can use scenario.exception.backtrace
It will return an array with step name. And then just get need element from array.
But, maybe there is something else which can give that failed step?

ContentLicense: CC BY-SA 3.0

Body:
I have AfterStep hook which can give me a step name. But it gives only name of passed step.

AfterStep do |result, step|
  puts step.name
end

How to get next cucumber step after passed if next is failed?
Or how to get name of failed step?

Maybe somehow to calculate step position and take another one?

Any ideas?
I am sure that it is possible because we can see failed step name in error log.


问:
CSS Ribbon not working properly in IE 9
can anyone figure out why this isn't displaying properly in IE 9? Here's what it looks like:

and here's what it
should look like:

Here's my code -- any help would be much appreciated. Thank you!

html

```<code><div class="addl-colors-container">
<span class="addl-colors">
::before
"Multiple Options""
::after
</span>
</div>
</code>```

CSS

```<code> .addl-colors-container{
    width:105px;
    height:105px;
    position:absolute;
    z-index:1;
    text-align:center;
    pointer-events:none;
    margin:-10px;
    font-size:14px;
}
span.addl-colors {
    background:linear-gradient(#25aeca 0%, #5fc8c2 100%);
    box-shadow:0 3px 10px -5px rgba(0, 0, 0, 1);
    top:20px;
    line-height:22px;
    width:147px;
    right:-16px;
    transform:rotate(-37deg);
    -ms-transform:rotate(-37deg);
    -webkit-transform:rotate(-37deg);
    display:block;
    position:absolute;
    color:#fff;
    border-top-right-radius:75px;
    border-top-left-radius:75px;
    }
span.addl-colors:after{
    content:'';
    position:absolute;
    left:0px;
    top:100%;
    z-index:-1;
    border-left:3px solid #25aeca;
    border-right:3px solid transparent;
    border-bottom:3px solid transparent;
    border-top:3px solid #25aeca;
}
span.addl-colors:before{
    content:'';
    position:absolute;
    right:0%;
    top:100%;
    z-index:-1px;
    border-right:3px solid #25aeca;
    border-left:3px solid transparent;
    border-bottom:3px solid transparent;
    border-top:3px solid #25aeca;
}
</code>```

This is displayed inside another box. It was a lot of code so I didn't paste it but if it's needed, please let me know and I will post. Thank you!

答:
unfortunately linear-gradient not found in internet explorer, I had the same problem and y solv putting a simple background before the linear gradient

like this:

```<code>span.addl-colors {
    background: #25aeca;
    background:linear-gradient(#25aeca 0%, #5fc8c2 100%);
    ...
}
</code>```

Title: CSS Ribbon not working properly in IE 9

Body:
can anyone figure out why this isn't displaying properly in IE 9? Here's what it looks like:

and here's what it
should look like:

Here's my code -- any help would be much appreciated. Thank you!

html

::before
"Multiple Options""
::after

CSS

 .addl-colors-container{
    width:105px;
    height:105px;
    position:absolute;
    z-index:1;
    text-align:center;
    pointer-events:none;
    margin:-10px;
    font-size:14px;
}
span.addl-colors {
    background:linear-gradient(#25aeca 0%, #5fc8c2 100%);
    box-shadow:0 3px 10px -5px rgba(0, 0, 0, 1);
    top:20px;
    line-height:22px;
    width:147px;
    right:-16px;
    transform:rotate(-37deg);
    -ms-transform:rotate(-37deg);
    -webkit-transform:rotate(-37deg);
    display:block;
    position:absolute;
    color:#fff;
    border-top-right-radius:75px;
    border-top-left-radius:75px;
    }
span.addl-colors:after{
    content:'';
    position:absolute;
    left:0px;
    top:100%;
    z-index:-1;
    border-left:3px solid #25aeca;
    border-right:3px solid transparent;
    border-bottom:3px solid transparent;
    border-top:3px solid #25aeca;
}
span.addl-colors:before{
    content:'';
    position:absolute;
    right:0%;
    top:100%;
    z-index:-1px;
    border-right:3px solid #25aeca;
    border-left:3px solid transparent;
    border-bottom:3px solid transparent;
    border-top:3px solid #25aeca;
}

This is displayed inside another box. It was a lot of code so I didn't paste it but if it's needed, please let me know and I will post. Thank you!

Body:
unfortunately linear-gradient not found in internet explorer, I had the same problem and y solv putting a simple background before the linear gradient

like this:

span.addl-colors {
    background: #25aeca;
    background:linear-gradient(#25aeca 0%, #5fc8c2 100%);
    ...
}


问:
save ansi special character in oracle database using php
Can somebody tell me how can i save œ which comes from ALT+0156 i tried to save in database but it is showing ¿

I have looked around but couldn't find any way. Currently i'm using

```<code>NLS_LANGUAGE =  AMERICAN
NLS_CHARACTERSET = 'AL32UTF8'
CHARACTER SET   WE8ISO8859P1
</code>```

Actually i need to save UTF8 data in database but these symbols not coming in right format. Please tell me what i'm missing.

Even i ran a query in Oracle Sql Developer Tools

```<code>select 'œ' val from dual;
</code>```

It returns

```<code>val => ¿ //as result
</code>```

答:
Even I faced similar issues with special characters in Oracle DB.

Your oracle might be compatible with that particular special character but your server/system is not hence you need to add an environmental variable named NLS_LANG.

For Linux/Unix you can simply add it in the .profile/.bash_profile

```<code>Eg. export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
</code>```

For Windows you can right click your

```<code>PC -> Goto properties -> Advanced system settings -> Environmental Variables.
</code>```

Path:[Control Panel\System and Security\System -> Advanced system settings -> Environmental Variables. ]

And add a NLS_LANG variable in system variables section.

Note: The value to save in this NLS_LANG environmental variable is returned using below query [In Windows/Linux both]:

```<code> select userenv('language') from dual
</code>```

Note that you need to restart your windows system after adding the variable.

Try the following reference link & do the necessary configurations : link and it should hopefully work out.

Body:
Can somebody tell me how can i save œ which comes from ALT+0156 i tried to save in database but it is showing ¿

I have looked around but couldn't find any way. Currently i'm using

NLS_LANGUAGE =  AMERICAN
NLS_CHARACTERSET = 'AL32UTF8'
CHARACTER SET   WE8ISO8859P1

Actually i need to save UTF8 data in database but these symbols not coming in right format. Please tell me what i'm missing.

Even i ran a query in Oracle Sql Developer Tools

select 'œ' val from dual;

It returns

val => ¿ //as result

Body:
Even I faced similar issues with special characters in Oracle DB.

Your oracle might be compatible with that particular special character but your server/system is not hence you need to add an environmental variable named NLS_LANG.

For Linux/Unix you can simply add it in the .profile/.bash_profile

Eg. export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

For Windows you can right click your

PC -> Goto properties -> Advanced system settings -> Environmental Variables.

Path:[Control Panel\System and Security\System -> Advanced system settings -> Environmental Variables. ]

And add a NLS_LANG variable in system variables section.

Note: The value to save in this NLS_LANG environmental variable is returned using below query [In Windows/Linux both]:

 select userenv('language') from dual

Note that you need to restart your windows system after adding the variable.

Try the following reference link & do the necessary configurations : link and it should hopefully work out.


问:
java.net.MalformedURLException: unknown protocol: f
I am trying to get histogram of an image using this code Displaying a histogram of image data. Normally it works fine when input image given by url. But while I give image from local directory

```<code>private BufferedImage getImage() {
    try {
        return ImageIO.read(new URL(
            "F:/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}
</code>```

it gives exception,

```<code> java.net.MalformedURLException: unknown protocol: f
</code>```

How to resolve this exception and get Histogram of an image

答:
The protocol is not valid.

If you need to load a file from the filesystem you need to use the file URI scheme

A file URI takes the form of file://host/path

where host is the fully qualified domain name of the system on which the path is accessible, and path is a hierarchical directory path of the form directory/directory/.../name. If host is omitted, it is taken to be "localhost", the machine from which the URL is being interpreted.

So the url should be:

```<code>file://F:/test.jpg
</code>```

Body:
I am trying to get histogram of an image using this code Displaying a histogram of image data. Normally it works fine when input image given by url. But while I give image from local directory

private BufferedImage getImage() {
    try {
        return ImageIO.read(new URL(
            "F:/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

it gives exception,

 java.net.MalformedURLException: unknown protocol: f

How to resolve this exception and get Histogram of an image

Body:
The protocol is not valid.

If you need to load a file from the filesystem you need to use the file URI scheme

A file URI takes the form of file://host/path

where host is the fully qualified domain name of the system on which the path is accessible, and path is a hierarchical directory path of the form directory/directory/.../name. If host is omitted, it is taken to be "localhost", the machine from which the URL is being interpreted.

So the url should be:

file://F:/test.jpg


问:
Symfony3 ClassNotFoundException after bundle creation
I wanted to start a new 3.3 project in Symfony and started as usual:

1.) Creating the new project: symfony new ArtProject

2.) Creating a new Bundle: php app/console generate:bundle (Paul/ArtBundle, yml, src/)

Then I run the local server and when I open 127.0.0.1:8000 I get this beautiful message:

(1/1) ClassNotFoundException

Attempted to load class "PaulArtBundle" from namespace
  "Paul\ArtBundle". Did you forget a "use" statement for another
  namespace? in AppKernel.php (line 19)

Which is strange and I haven't figured out why this happen so far. Before creating the Bundle, there was no error; I saw the typical startpage of symfony.

```<code>public function registerBundles()
{
    $bundles = [
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        ......
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new AppBundle\AppBundle(),
        new Paul\ArtBundle\PaulArtBundle(),
    ];
}
</code>```

```<code><?php

namespace Paul\ArtBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PaulArtBundle extends Bundle
{
}
</code>```

Any idea whats going on there? I did not change a thing, I only ran these commands.

答:
I just installed a fresh copy of S3.3.4 (latest version as of this writing) using:

```<code>composer create-project symfony/framework-standard-edition s334 "3.3.4"
bin/console generate:bundle
Share across multiple apps: yes
namespace: Paul\ArtBundle
bundle name: PaulArtBundle
Target Directory: src/
</code>```

Refreshed the browser and sure enough I got the class not found message.

The generate:bundle command is not updating the autload section of composer.json when a new namespace is introduced.  Edit composer.json and:

```<code># composer.json
"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "Paul\\": "src/Paul"
    },
    "classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},
</code>```

Then run

```<code>composer dumpautoload
</code>```

And restart the server(maybe).  That should fix the bundle class not found problem.

I have not used the generate:bundle command is quite some time ever since the standard was to put everything under AppBundle so I don't know how long this has been "broken".  But at least three questions in the last week or so indicates it was something recent.

And by the way, when I refreshed the browser I got "Hello World" which threw me for a bit.  Turns out the new bundle overrides the / route which is also sort of special.

And in case anybody is wondering why this started happening, Symfony 3.2 changed from

```<code>#composer.json
"psr-4": { "": "src/" },
To
"psr-4": { "AppBundle\\": "src/AppBundle" },
</code>```

You could always just change it back though I think spelling out individual namespaces might be "better".  Not sure.

And here is an issue with more details: https://github.com/symfony/symfony-standard/issues/1098

Looks like the maintainer favored a tiny speed improvement over breaking an existing command.  Oh well.  Symfony Flex is supposed to make everything great again.

Body:
I wanted to start a new 3.3 project in Symfony and started as usual:

1.) Creating the new project: symfony new ArtProject

2.) Creating a new Bundle: php app/console generate:bundle (Paul/ArtBundle, yml, src/)

Then I run the local server and when I open 127.0.0.1:8000 I get this beautiful message:

(1/1) ClassNotFoundException

Attempted to load class "PaulArtBundle" from namespace
  "Paul\ArtBundle". Did you forget a "use" statement for another
  namespace? in AppKernel.php (line 19)

Which is strange and I haven't figured out why this happen so far. Before creating the Bundle, there was no error; I saw the typical startpage of symfony.

public function registerBundles()
{
    $bundles = [
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        ......
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new AppBundle\AppBundle(),
        new Paul\ArtBundle\PaulArtBundle(),
    ];
}

<?php

namespace Paul\ArtBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PaulArtBundle extends Bundle
{
}

Any idea whats going on there? I did not change a thing, I only ran these commands.

Body:
I just installed a fresh copy of S3.3.4 (latest version as of this writing) using:

composer create-project symfony/framework-standard-edition s334 "3.3.4"
bin/console generate:bundle
Share across multiple apps: yes
namespace: Paul\ArtBundle
bundle name: PaulArtBundle
Target Directory: src/

Refreshed the browser and sure enough I got the class not found message.

The generate:bundle command is not updating the autload section of composer.json when a new namespace is introduced.  Edit composer.json and:

# composer.json
"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "Paul\\": "src/Paul"
    },
    "classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},

Then run

composer dumpautoload

And restart the server(maybe).  That should fix the bundle class not found problem.

I have not used the generate:bundle command is quite some time ever since the standard was to put everything under AppBundle so I don't know how long this has been "broken".  But at least three questions in the last week or so indicates it was something recent.

And by the way, when I refreshed the browser I got "Hello World" which threw me for a bit.  Turns out the new bundle overrides the / route which is also sort of special.

And in case anybody is wondering why this started happening, Symfony 3.2 changed from

#composer.json
"psr-4": { "": "src/" },
To
"psr-4": { "AppBundle\\": "src/AppBundle" },

You could always just change it back though I think spelling out individual namespaces might be "better".  Not sure.

And here is an issue with more details: https://github.com/symfony/symfony-standard/issues/1098

Looks like the maintainer favored a tiny speed improvement over breaking an existing command.  Oh well.  Symfony Flex is supposed to make everything great again.


问:
Why is my output Undefined or NaN?
For some reason, when I enter value, all of the output is
undefined and NaN and I have no idea why.I think the
error is really simple..so simple I would facepalm. Sorry
for my code, I'm still new to javascript. And also, nevermind about the Credit Card.

```<code>function processAmount(){
    var numOfLiters= parseInt(document.estore.noOfLiters.value);
    var result;
    var perLiterAmount;
    var gasType;

    switch(gasType){
    case "Premium":

            perLiterAmount= 50;
            result= 50*numOfLiters;
            break;
    case "Diesel":
           perLiterAmount= 38;
          result= 38*numOfLiters;
            break;

    case "Unleaded":
           perLiterAmount= 44;
            result= 44*numOfLiters;
            break;
    }

    var vat= result*0.12;

    document.write("<p>Fuel Type: " + gasType + "</p>");
    document.write("<p>Price per Liter amount: " + perLiterAmount + "</p>");
    document.write("<p>Purchase Amount: " + result + "</p>");
    document.write("<p>VAT: " + vat + "</p>");
    document.write("<p>TOTAL AMOUNT: " + (result+vat) + "</p>");
    document.write("<p>Credit Card : " + creditCard + "</p>");`
</code>```

and here is the form:

```<code> <form name='estore' id='estore'>
   <fieldset>
            <legend>Gasoline eStore</legend>
                <p>Enter gasoline type:
                    <select name='gastype' id='gastype'>
                        <option value="Premium"> Premium</option>
                        <option value="Unleaded"> Unleaded</option>
                        <option value="Diesel"> Diesel</option>
                        </select></p>

                <p> Enter number of Liters:
                    <input type='number' name='noOfLiters' id='noOfLiters'/>
                </p>

                <p> Enter Credit Card Number:
                    <input type="number" name='creditCardNumber' id='creditCardNumber'/>
                </p>

                <p>
                    <input type='button' value='Submit'
                        onclick="processAmount()"/>
                    <input type='reset'/>
                </p>
</code>```

答: First assign the value to gasType and then put it in switch case.

Title: Why is my output Undefined or NaN?

Body:
For some reason, when I enter value, all of the output is
undefined and NaN and I have no idea why.I think the
error is really simple..so simple I would facepalm. Sorry
for my code, I'm still new to javascript. And also, nevermind about the Credit Card.

function processAmount(){
    var numOfLiters= parseInt(document.estore.noOfLiters.value);
    var result;
    var perLiterAmount;
    var gasType;

    switch(gasType){
    case "Premium":

            perLiterAmount= 50;
            result= 50*numOfLiters;
            break;
    case "Diesel":
           perLiterAmount= 38;
          result= 38*numOfLiters;
            break;

    case "Unleaded":
           perLiterAmount= 44;
            result= 44*numOfLiters;
            break;
    }

    var vat= result*0.12;

    document.write("
Fuel Type: " + gasType + "
");
    document.write("
Price per Liter amount: " + perLiterAmount + "
");
    document.write("
Purchase Amount: " + result + "
");
    document.write("
VAT: " + vat + "
");
    document.write("
TOTAL AMOUNT: " + (result+vat) + "
");
    document.write("
Credit Card : " + creditCard + "
");`

and here is the form:

 <form name='estore' id='estore'>
   <fieldset>
            <legend>Gasoline eStore</legend>

Enter gasoline type:
                    <select name='gastype' id='gastype'>
                        <option value="Premium"> Premium</option>
                        <option value="Unleaded"> Unleaded</option>
                        <option value="Diesel"> Diesel</option>
                        </select>

 Enter number of Liters:
                    <input type='number' name='noOfLiters' id='noOfLiters'/>

 Enter Credit Card Number:
                    <input type="number" name='creditCardNumber' id='creditCardNumber'/>

                    <input type='button' value='Submit'
                        onclick="processAmount()"/>
                    <input type='reset'/>


问:
Click on RecyclerView item in ViewHolder
In my ViewHolder i have a function:

```<code>    private fun setupAmountLabel(amountLabelView: CategorizedAmountView, category: Category?,
                             amount: Double, percent: String, isParentView: Boolean) {
    amountLabelView.setTitle(category?.getLocalizedName() ?: "")
    amountLabelView.setSubTitle(percent)
    amountLabelView.setAmountSignType(AmountType.NEGATIVE)
    amountLabelView.setAmountAndCurrencyCode(amount, currencyCode)
    amountLabelView.setIconCategory(category)
    amountLabelView.setAmountColor(amount.toDataSetColor())
    amountLabelView.setOnClickListener {
        listItemClickListener?.onListItemClick(if (isParentView) 1 else 0, category?.guid ?: "")
    }
}
</code>```

Where i want to click on my listItemParent. Earlier this function was in the adapter, and I called the adapter by creating the setListClickListener method. But now i didn t know how i can make click on this item.

答:
Just do this inside your holder:</p>

```<code>itemView.setOnClickListener { yourFunction() }
</code>```

Body:
In my ViewHolder i have a function:

    private fun setupAmountLabel(amountLabelView: CategorizedAmountView, category: Category?,
                             amount: Double, percent: String, isParentView: Boolean) {
    amountLabelView.setTitle(category?.getLocalizedName() ?: "")
    amountLabelView.setSubTitle(percent)
    amountLabelView.setAmountSignType(AmountType.NEGATIVE)
    amountLabelView.setAmountAndCurrencyCode(amount, currencyCode)
    amountLabelView.setIconCategory(category)
    amountLabelView.setAmountColor(amount.toDataSetColor())
    amountLabelView.setOnClickListener {
        listItemClickListener?.onListItemClick(if (isParentView) 1 else 0, category?.guid ?: "")
    }
}

Where i want to click on my listItemParent. Earlier this function was in the adapter, and I called the adapter by creating the setListClickListener method. But now i didn t know how i can make click on this item.

Body:
Just do this inside your holder:

itemView.setOnClickListener { yourFunction() }


问:
Display users related to specified group
I need to display only users which is in a group.
For example, I have two fields group and assigned to.
   If i select a group, then i should get only list of that group.

Can you provide any solution for this problem please

答:
Use the filter function. Press "Add custom filter" and select "Groups" in the first line, "is equal to" in the second and your group name in the third.
Then press apply.</p>


问:
Completion block for dismiss light box
Is there way to execute the code right after lightBox has been dismissed? I am looking for an equivalent of completion block:</p>

```<code>Navigator.dismissLightBox();
//wait for it to dismiss and execute code
</code>```

答:
You can pass a callback in passProps and invoke that callback in componentwillunmount

```<code>Navigation.showLightBox({
  screen: "example.LightBoxScreen",
  passProps: {
    onDismiss: () => console.log('dismissed')
  }
});
</code>```

Title: Completion block for dismiss light box

Body:
Is there way to execute the code right after lightBox has been dismissed? I am looking for an equivalent of completion block:

Navigator.dismissLightBox();
//wait for it to dismiss and execute code

Body:
You can pass a callback in passProps and invoke that callback in componentwillunmount

Navigation.showLightBox({
  screen: "example.LightBoxScreen",
  passProps: {
    onDismiss: () => console.log('dismissed')
  }
});


问:
How to start launch configuration after finishing another launch programmatically? (Eclipse)
So I need to start an launch config. depending on output from another launch configuration.

Launch launch = (Launch) configurations[0].launch(ILaunchManager.RUN_MODE,
                            console);
                    do {
                        if(launch.isTerminated()){
                            configurations[1].launch(ILaunchManager.RUN_MODE,
                                    new NullProgressMonitor());
                            break;
                        }
                    } while (!launch.isTerminated());
```

Something like this, but even this is not working. It executes only first launch. And how can I acces the output(from console) of first launch?

答:
You get notified about the process associated with a launch terminating by using an IDebugEventSetListener listener.

Add the listener with:

DebugPlugin.getDefault().addDebugEventListener(listener);
```

When the process associated with the launch (if there is one) terminate a  DebugEvent will be passed to the listener's handleDebugEvents method.

The event getKind() method will return DebugEvent.TERMINATE for a terminated process. The event getSource() returns the IProcess which terminated.

Body:
So I need to start an launch config. depending on output from another launch configuration.

Launch launch = (Launch) configurations[0].launch(ILaunchManager.RUN_MODE,
                            console);
                    do {
                        if(launch.isTerminated()){
                            configurations[1].launch(ILaunchManager.RUN_MODE,
                                    new NullProgressMonitor());
                            break;
                        }
                    } while (!launch.isTerminated());

Something like this, but even this is not working. It executes only first launch. And how can I acces the output(from console) of first launch?

Body:
You get notified about the process associated with a launch terminating by using an IDebugEventSetListener listener.

Add the listener with:

DebugPlugin.getDefault().addDebugEventListener(listener);

When the process associated with the launch (if there is one) terminate a  DebugEvent will be passed to the listener's handleDebugEvents method.

The event getKind() method will return DebugEvent.TERMINATE for a terminated process. The event getSource() returns the IProcess which terminated.


问:
How to arrange line after line the sequential numbers in text
I am having numbers in text of size 819200 sequentially, like :

2,2,3,3,4,5,5,5,6,7,7,......................2,2,3,3,4,5,5,5,6,7,7,7,7,8,8,8,9,9,9,10,10,10,11,11.

When copied this data to some header file in C program they transform to weired symbols(corrupted data) due to the single line numbers arrangement.
Is there any way I can arrange the numbers in line by line as below:
2,2,3,3,4,5,5,5,6,7,7,7,7,8,8,8,9,9,9,10,10,10,11,11,
21,21,22,23,23,24,24,25,26,27,27,27,27,28,28,28,29,29,
.............................................so on new line arrangements.
What I want to do is the numbers should not be in single line, they should be arranged in line by line(each line may contain 100 numbers with comma followed).
Note: I tried word wrap but still the data is in sequential format only.

答:
Ctrl+H

Find what: (?:\d+,){100}

Replace with: $0\n

Replace all

This will add a linebreak after 100 numbers + comma

Explanation:

```<code>(?:      : non capture group
  \d+    : 1 or more digits
  ,      : a comma
){100}   : end group, repeated 100 times
</code>```

Replacement:

```<code>$0      : the whole match
\n      : linefeed
</code>```

Body:
Ctrl+H

Find what: (?:\d+,){100}

Replace with: $0\n

Replace all

This will add a linebreak after 100 numbers + comma

Explanation:

(?:      : non capture group
  \d+    : 1 or more digits
  ,      : a comma
){100}   : end group, repeated 100 times

Replacement:

$0      : the whole match
\n      : linefeed


问:
Fade In and Fade out in Animation Swift
I have an UIImageView with an Animation and, in the UIView, I apply a fadeIn effect, but I need to apply fade out when the UIImageView, which is animated, when is touched. </p>

<p>This is what I make to fade in. </p>

```<code>UIView.animateWithDuration(0.5, delay: delay,
    options: UIViewAnimationOptions.CurveEaseOut, animations: {
        uiImageView.alpha = 1.0
        }
</code>```

答:
Starting from iOS 10 Apple launched new iOS Animations SDK that is much more powerful, especially concerning timings functions and interactivity.

Fade out code with this approach will:

```<code>UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
    self.uiImageView.alpha = 0.0
}).startAnimation()
</code>```

To get more details about the Property Animator, take a look at iOS 10 Animations demo.

Title: Fade In and Fade out in Animation Swift

Body:
I have an UIImageView with an Animation and, in the UIView, I apply a fadeIn effect, but I need to apply fade out when the UIImageView, which is animated, when is touched.

This is what I make to fade in.

UIView.animateWithDuration(0.5, delay: delay,
    options: UIViewAnimationOptions.CurveEaseOut, animations: {
        uiImageView.alpha = 1.0
        }

Body:
Starting from iOS 10 Apple launched new iOS Animations SDK that is much more powerful, especially concerning timings functions and interactivity.

Fade out code with this approach will:

UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
    self.uiImageView.alpha = 0.0
}).startAnimation()

To get more details about the Property Animator, take a look at iOS 10 Animations demo.


问:
What is the difference between API vxReleaseNode and vxRemoveNode in OpenVX object node?
I am trying to understand the Open-vx object node for one of my requirement.I have gone through the specification but not able to understand the exact difference between an API vxRemoveNode() and vxReleaseNode(). Spec says vxReleaseNode :

```<code>"Releases a reference to a Node object. The object may not be garbage collected until its total reference count is zero."
</code>```

I don't get the second point in the above statement.

Regrading the vxRemoveNode as per my understanding it completely removes the node from the graph.

In the post condition after calling both the APIs,In the specs they mentioned:

"After returning from this function the reference is zeroed"

Please help me to understand the exact difference between these APIs.

答:
Never used OpenVX. This is what I understand from the documentation:

vx_status VX_API_CALL vxReleaseNode(vx_node * node): node does not point anymore to a vx_node object, the vx_node object will be completely garbage collected when there is no more variable that references this object. node pointer is set to zero after the call.

vx_status VX_API_CALL vxRemoveNode(vx_node * node): remove the vx_node object from the graph, node is set to zero after the call.

Body:
I am trying to understand the Open-vx object node for one of my requirement.I have gone through the specification but not able to understand the exact difference between an API vxRemoveNode() and vxReleaseNode(). Spec says vxReleaseNode :

"Releases a reference to a Node object. The object may not be garbage collected until its total reference count is zero."

I don't get the second point in the above statement.

Regrading the vxRemoveNode as per my understanding it completely removes the node from the graph.

In the post condition after calling both the APIs,In the specs they mentioned:

"After returning from this function the reference is zeroed"

Please help me to understand the exact difference between these APIs.


问:
Word2Vec Vocabulary not definded error
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code?

Here is my code:

```<code>file_object=open("SupremeCourt.txt","w")
from gensim.models import word2vec

data = word2vec.Text8Corpus('SupremeCourt.txt')
model = word2vec.Word2Vec(data, size=200)

out=model.most_similar()

print(out[1])
print(out[2])
</code>```

答:
You're opening that file in write mode with this line:

```<code>file_object = open("SupremeCourt.txt", "w")
</code>```

By doing this, you're erasing the contents of your file, so that when you try to pass the file the model for training, there is no data to read. That's why that error is thrown.

Remove that line (and also restore your file contents), and it'll work.

Title: Word2Vec Vocabulary not definded error

Body:
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code?

Here is my code:

file_object=open("SupremeCourt.txt","w")
from gensim.models import word2vec

data = word2vec.Text8Corpus('SupremeCourt.txt')
model = word2vec.Word2Vec(data, size=200)

out=model.most_similar()

print(out[1])
print(out[2])

Body:
You're opening that file in write mode with this line:

file_object = open("SupremeCourt.txt", "w")

By doing this, you're erasing the contents of your file, so that when you try to pass the file the model for training, there is no data to read. That's why that error is thrown.

Remove that line (and also restore your file contents), and it'll work.


问:
Setup Cron For a Route in Zend Franework 2
I am trying to setup a cron for a rout to send email on specific route defines in my module:

the route is as follows:

```<code>'company-testing' => array( //Company Invoice Page
            'type' => 'Segment',
            'options' => array(
                'route' => '/account/company-testing[/:action]',
                'defaults' => array(
                    'controller' => 'Company\Controller\CouponOrder',
                    'action' => 'tempTesty',
                ),
            ),
            'may_terminate' => true,
        ),
</code>```

My  page url for this route is as follows as per the above configuration:

```<code>http://shop.projekte-web.com/reisesparer/public/account/company-testing
</code>```

So I have tried to setup the cron through CLI in the following way but it is not working and not sending email with specified cron time.

but if i directly hit the route it generate the email and successfully send it.

CRON SETUP:

```<code>* * * * * /usr/bin/php /absolute_path_to_my_project/public /account/company-testing > / dev / null 2> & 1
</code>```

Any help regarding this issue?

答:
I recommend you create a console route to get a cron job done with Zend Framework. So if you created the console route that would look like the following

```<code>'console' => array(
    'router' => array(
        'routes' => array(
            'cron-company-testing' => array(
                'options' => array(
                    'route'    => 'cronmail', // route to be used in cli
                    'defaults' => array(
                        'controller' => 'Company\Controller\CouponOrder',
                        'action' => 'tempTesty',
                    ),
                ),
            ),
        ),
    ),
),
</code>```

Add this above configuration to your module.config.php.

First lets check it over the terminal locally. Do the following in your terminal

```<code>cd /path/to/your/project
php public/index.php cronmail
</code>```

Next up you may add a job to the crontab. Please look at the route name, in this case, cronmail.

```<code>* * * * * /usr/bin/php /path/to/project/public/index.php cronmail &> /dev/null
</code>```

Now you should check whether that job has added to the crontab or not. Use the following command in your terminal

```<code>crontab -l
</code>```

Body:
I am trying to setup a cron for a rout to send email on specific route defines in my module:

the route is as follows:

'company-testing' => array( //Company Invoice Page
            'type' => 'Segment',
            'options' => array(
                'route' => '/account/company-testing[/:action]',
                'defaults' => array(
                    'controller' => 'Company\Controller\CouponOrder',
                    'action' => 'tempTesty',
                ),
            ),
            'may_terminate' => true,
        ),

My  page url for this route is as follows as per the above configuration:

http://shop.projekte-web.com/reisesparer/public/account/company-testing

So I have tried to setup the cron through CLI in the following way but it is not working and not sending email with specified cron time.

but if i directly hit the route it generate the email and successfully send it.

CRON SETUP:

* * * * * /usr/bin/php /absolute_path_to_my_project/public /account/company-testing > / dev / null 2> & 1

Any help regarding this issue?

Body:
I recommend you create a console route to get a cron job done with Zend Framework. So if you created the console route that would look like the following

'console' => array(
    'router' => array(
        'routes' => array(
            'cron-company-testing' => array(
                'options' => array(
                    'route'    => 'cronmail', // route to be used in cli
                    'defaults' => array(
                        'controller' => 'Company\Controller\CouponOrder',
                        'action' => 'tempTesty',
                    ),
                ),
            ),
        ),
    ),
),

Add this above configuration to your module.config.php.

First lets check it over the terminal locally. Do the following in your terminal

cd /path/to/your/project
php public/index.php cronmail

Next up you may add a job to the crontab. Please look at the route name, in this case, cronmail.

* * * * * /usr/bin/php /path/to/project/public/index.php cronmail &> /dev/null

Now you should check whether that job has added to the crontab or not. Use the following command in your terminal

crontab -l


问:
How can I select the minimum price per item from my database?
I want to select minimum price per item from my MySQL database, but I'm not sure how to write the query.

Here is an example table.

```<code>  id |  price | quantity
    1|   $200 |      200
    2|  $1000 |       10
    3|     $5 |        1
</code>```

In this case the price/item for id 1 would be $1 (200/200), for id 2 it's $100 (1000/10), for id 3 it's $5 (5/1) and the query would return $1, because it is the minimum price/item.

So how can it be translated to SQL? I thought about:

```<code>SELECT MIN(price)/200 WHERE quantity=200
</code>```

but it only works with a hard coded quantity and I must write the quantity for each id and would be impossible with 1000+ different prices and quantities. So I would need something flexible with variables or something, like:

```<code>SELECT MIN(price)/quantity
</code>```

but that's not correct syntax. (or it just doesn't work for me)

What is the correct way to write it in MySQL?

答:
Here is a portable version of Gordon Linoff's solution :

```<code>SELECT t.*, (price / quantity) as unit_price
FROM  t t1
WHERE NOT EXISTS (SELECT * FROM t t2 WHERE t2.price / t2.quantity < t1.price / t1.quantity);
</code>```

The point is that LIMIT is specific to some products (MySQL and PostgreSQL AFAIK).

Body:
I want to select minimum price per item from my MySQL database, but I'm not sure how to write the query.

Here is an example table.

  id |  price | quantity
    1|   $200 |      200
    2|  $1000 |       10
    3|     $5 |        1

In this case the price/item for id 1 would be $1 (200/200), for id 2 it's $100 (1000/10), for id 3 it's $5 (5/1) and the query would return $1, because it is the minimum price/item.

So how can it be translated to SQL? I thought about:

SELECT MIN(price)/200 WHERE quantity=200

but it only works with a hard coded quantity and I must write the quantity for each id and would be impossible with 1000+ different prices and quantities. So I would need something flexible with variables or something, like:

SELECT MIN(price)/quantity

but that's not correct syntax. (or it just doesn't work for me)

What is the correct way to write it in MySQL?

Body:
Here is a portable version of Gordon Linoff's solution :

SELECT t.*, (price / quantity) as unit_price
FROM  t t1
WHERE NOT EXISTS (SELECT * FROM t t2 WHERE t2.price / t2.quantity < t1.price / t1.quantity);

The point is that LIMIT is specific to some products (MySQL and PostgreSQL AFAIK).


问:
WAR fails to start on jetty9 in AWS but works on local installation
I have a maven project which produces a .war application. When I deploy this war in my local installation of jetty9 the app works. When I deploy to my machine in AWS it fails to start with the following error.

```<code>2017-07-05 17:53:43.336:WARN:oejuc.AbstractLifeCycle:main: FAILED o.e.j.w.WebAppContext@3dd3bcd{/my-app,file:/var/cache/jetty9/data/jetty-0.0.0.0-8080-my-app.war-_my-app-any-5436545420435013189.dir/webapp/,STARTING}{/my-app.war}: java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
        at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:331)
        at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
        at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
        at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
</code>```

This is a Jersey 2 app which communicates with another api via an old client written in Jersey 1. I've already had conflicts between both versions of Jersey and solved them using maven exclusions as indicated here, and that solved the problem locally, but for some reason it now fails when I deploy.

I've failed to spot the difference between the two environments. I ran java -jar /usr/share/jetty9/start.java --version and the result is identical (I diffed it) in both machines:

```<code>Jetty Server Classpath:
-----------------------
Version Information on 38 entries in the classpath.
Note: order presented here is how they would appear on the classpath.
      changes to the --module=name command line options will be reflected here.
 0:         (none specified) | ${jetty.home}/eclipse-ecj-3.11.0.jar
 1:         9.2.18.v20160721 | ${jetty.home}/jetty9-apache-jsp.jar
 2:                    1.2.5 | ${jetty.home}/taglibs-standard-impl.jar
 3:                    1.2.5 | ${jetty.home}/taglibs-standard-spec.jar
 4:                   8.0.37 | ${jetty.home}/tomcat8-api-8.0.37.jar
 5:                   3.0.FR | ${jetty.home}/tomcat8-el-api-8.0.37.jar
 6:                   8.0.37 | ${jetty.home}/tomcat8-jasper-8.0.37.jar
 7:                   8.0.37 | ${jetty.home}/tomcat8-jasper-el-8.0.37.jar
 8:                   2.3.FR | ${jetty.home}/tomcat8-jsp-api-8.0.37.jar
 9:                   8.0.37 | ${jetty.home}/tomcat8-juli-8.0.37.jar
10:                   8.0.37 | ${jetty.home}/tomcat8-util-8.0.37.jar
11:                   8.0.37 | ${jetty.home}/tomcat8-util-scan-8.0.37.jar
12:                    (dir) | ${jetty.base}/resources
13:                   3.1.FR | ${jetty.home}/servlet-api-3.1.jar
14:         9.2.18.v20160721 | ${jetty.home}/jetty9-http.jar
15:         9.2.18.v20160721 | ${jetty.home}/jetty9-server.jar
16:         9.2.18.v20160721 | ${jetty.home}/jetty9-xml.jar
17:         9.2.18.v20160721 | ${jetty.home}/jetty9-util.jar
18:         9.2.18.v20160721 | ${jetty.home}/jetty9-io.jar
19:         9.2.18.v20160721 | ${jetty.home}/jetty9-jndi.jar
20:                    1.5.6 | ${jetty.home}/javax.mail.jar
21:         9.2.18.v20160721 | ${jetty.home}/jetty9-security.jar
22:         9.2.18.v20160721 | ${jetty.home}/jetty9-servlet.jar
23:         9.2.18.v20160721 | ${jetty.home}/jetty9-webapp.jar
24:         9.2.18.v20160721 | ${jetty.home}/jetty9-deploy.jar
25:         9.2.18.v20160721 | ${jetty.home}/jetty9-plus.jar
26:         9.2.18.v20160721 | ${jetty.home}/jetty9-annotations.jar
27:                   3.0.FR | ${jetty.home}/tomcat8-annotations-api-8.0.37.jar
28:                      5.1 | ${jetty.home}/asm-commons-5.1.jar
29:                      5.1 | ${jetty.home}/asm-5.1.jar
30:                   1.1.FR | ${jetty.home}/tomcat8-websocket-api-8.0.37.jar
31:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-client-impl.jar
32:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-server-impl.jar
33:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-api.jar
34:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-client.jar
35:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-common.jar
36:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-server.jar
37:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-servlet.jar
</code>```

My question is: what could be different in the AWS machine that could cause this error? Where else should I look to get more info to solve this problem?

答:
Apparently the exclusions were not correctly configured. I was excluding com.sun.jersey:jersey-server but javax.ws.rs:jsr311-api was being included as a transitive dependency of com.sun.jersey:jersey-client. I explicitly excluded javax.ws.rs:jsr311-api and it worked.

I still don't know why it was working in my local jetty installation. A teammate suggested it may have something to do with the order the jars where loaded on each machine, but I'm not sure how to check that.

Body:
I have a maven project which produces a .war application. When I deploy this war in my local installation of jetty9 the app works. When I deploy to my machine in AWS it fails to start with the following error.

2017-07-05 17:53:43.336:WARN:oejuc.AbstractLifeCycle:main: FAILED o.e.j.w.WebAppContext@3dd3bcd{/my-app,file:/var/cache/jetty9/data/jetty-0.0.0.0-8080-my-app.war-_my-app-any-5436545420435013189.dir/webapp/,STARTING}{/my-app.war}: java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
        at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:331)
        at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
        at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
        at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)

This is a Jersey 2 app which communicates with another api via an old client written in Jersey 1. I've already had conflicts between both versions of Jersey and solved them using maven exclusions as indicated here, and that solved the problem locally, but for some reason it now fails when I deploy.

I've failed to spot the difference between the two environments. I ran java -jar /usr/share/jetty9/start.java --version and the result is identical (I diffed it) in both machines:

Jetty Server Classpath:
-----------------------
Version Information on 38 entries in the classpath.
Note: order presented here is how they would appear on the classpath.
      changes to the --module=name command line options will be reflected here.
 0:         (none specified) | ${jetty.home}/eclipse-ecj-3.11.0.jar
 1:         9.2.18.v20160721 | ${jetty.home}/jetty9-apache-jsp.jar
 2:                    1.2.5 | ${jetty.home}/taglibs-standard-impl.jar
 3:                    1.2.5 | ${jetty.home}/taglibs-standard-spec.jar
 4:                   8.0.37 | ${jetty.home}/tomcat8-api-8.0.37.jar
 5:                   3.0.FR | ${jetty.home}/tomcat8-el-api-8.0.37.jar
 6:                   8.0.37 | ${jetty.home}/tomcat8-jasper-8.0.37.jar
 7:                   8.0.37 | ${jetty.home}/tomcat8-jasper-el-8.0.37.jar
 8:                   2.3.FR | ${jetty.home}/tomcat8-jsp-api-8.0.37.jar
 9:                   8.0.37 | ${jetty.home}/tomcat8-juli-8.0.37.jar
10:                   8.0.37 | ${jetty.home}/tomcat8-util-8.0.37.jar
11:                   8.0.37 | ${jetty.home}/tomcat8-util-scan-8.0.37.jar
12:                    (dir) | ${jetty.base}/resources
13:                   3.1.FR | ${jetty.home}/servlet-api-3.1.jar
14:         9.2.18.v20160721 | ${jetty.home}/jetty9-http.jar
15:         9.2.18.v20160721 | ${jetty.home}/jetty9-server.jar
16:         9.2.18.v20160721 | ${jetty.home}/jetty9-xml.jar
17:         9.2.18.v20160721 | ${jetty.home}/jetty9-util.jar
18:         9.2.18.v20160721 | ${jetty.home}/jetty9-io.jar
19:         9.2.18.v20160721 | ${jetty.home}/jetty9-jndi.jar
20:                    1.5.6 | ${jetty.home}/javax.mail.jar
21:         9.2.18.v20160721 | ${jetty.home}/jetty9-security.jar
22:         9.2.18.v20160721 | ${jetty.home}/jetty9-servlet.jar
23:         9.2.18.v20160721 | ${jetty.home}/jetty9-webapp.jar
24:         9.2.18.v20160721 | ${jetty.home}/jetty9-deploy.jar
25:         9.2.18.v20160721 | ${jetty.home}/jetty9-plus.jar
26:         9.2.18.v20160721 | ${jetty.home}/jetty9-annotations.jar
27:                   3.0.FR | ${jetty.home}/tomcat8-annotations-api-8.0.37.jar
28:                      5.1 | ${jetty.home}/asm-commons-5.1.jar
29:                      5.1 | ${jetty.home}/asm-5.1.jar
30:                   1.1.FR | ${jetty.home}/tomcat8-websocket-api-8.0.37.jar
31:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-client-impl.jar
32:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-server-impl.jar
33:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-api.jar
34:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-client.jar
35:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-common.jar
36:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-server.jar
37:         9.2.18.v20160721 | ${jetty.home}/jetty9-websocket-servlet.jar

My question is: what could be different in the AWS machine that could cause this error? Where else should I look to get more info to solve this problem?

ContentLicense: CC BY-SA 4.0


问:
SAP Cloud Platform - can you use existing on-Premise Fiori Logins
We are building an app on our SCP Trail account.
By default the login to this is our SCP trail account ID (begins with an S number).

In practice though, existing users of our on-Premise Fiori will need to login to the app using there existing Fiori login (as they wont have SCP logins).

How is this setup?

答:
You can connect your SCP to your on-premise identity repository. Either that or propagate the SCP account to your on-premise backend system. Both are standard methods documented by SAP. However, Identity Management is not part of the trial landscape so you should subscribe to a productive account first.

...and you should think twice about your strategy for this hybrid scenario as you already have some Fiori on-premise. :-)


问:
Implementing the Bentley-Ottmann algorithm
I am having some trouble correctly implementing the Bentley-Ottmann algorithm in C#. I am trying to implement it according to the pseudocode here. I have posted my main code below. Assuming my BST and PriorityQueue classes are implemented correctly, do you see any problems with the code?

There are no errors, but not all intersection points are found, only some. My guess is that there's an error in the else part of the code (when the current event is an intersection point). I'm not sure what the pseudocode means by swapping the position of two segments in the BST. Is the way I do it fine? Because in the end, the two aren't really swapped in the BST. I can't just change their positions either, because that could break the BST properties.

Also, am I right in assuming that segments are ordered in the BST by the Y-coordinate of their left endpoint?

Another error I've noticed that I can't seem to be able to track down is that sometimes the point (0, 0) gets into eventList. (0, 0) is outputted by Geometry.Intersects in case there is no intersection, but in that case the if conditions should stop it from getting added. I have no idea how it gets in. If I print the contents of eventList after adding a point in, (0, 0) never shows up. If I print the contents after extracting and popping an element, (0, 0) sometimes shows up. Could this have anything to do with the Pop() method messing with the references, or is it definitely a problem in my PriorityQueue implementation?

If needed I can show my implementations for the BST and priority queue as well.

```<code>static class BentleyOttman
{
    private static void AddIntersectionEvent(PriorityQueue eventList, Segment segEv, Segment segA, SegPoint i)
    {
        i.IntersectingSegments = new Tuple<Segment, Segment>(segEv, segA);
        i.Type = SegmentPointType.IntersectionPoint;

        eventList.Add(i);
    }

    public static void Solve(Panel surface, TextBox debug)
    {
        debug.Clear();
        var segList = Generator.SegList;

        PriorityQueue eventList = new PriorityQueue();

        foreach (Segment s in segList)
        {
            eventList.Add(new SegPoint(s.A, s, SegmentPointType.LeftEndpoint));
            eventList.Add(new SegPoint(s.B, s, SegmentPointType.RightEndpoint));
        }

        BST sweepLine = new BST();
        while (!eventList.Empty)
        {
            SegPoint ev = eventList.Top();

            eventList.Pop();

            if (ev.Type == SegmentPointType.LeftEndpoint)
            {
                Segment segEv = ev.Segment;
                sweepLine.Insert(segEv);

                Segment segA = sweepLine.InorderPre(segEv);
                Segment segB = sweepLine.InorderSuc(segEv);

                SegPoint i = new SegPoint();
                if (segA != null && Geometry.Intersects(segEv, segA, out i.Point))
                {
                    AddIntersectionEvent(eventList, segA, segEv, i);
                }
                if (segB != null && Geometry.Intersects(segEv, segB, out i.Point))
                {
                    AddIntersectionEvent(eventList, segEv, segB, i);
                }
            }
            else if (ev.Type == SegmentPointType.RightEndpoint)
            {
                Segment segEv = ev.Segment;

                Segment segA = sweepLine.InorderPre(segEv);
                Segment segB = sweepLine.InorderSuc(segEv);

                sweepLine.Remove(segEv);

                SegPoint i = new SegPoint();
                if (segA != null && segB != null && Geometry.Intersects(segA, segB, out i.Point))
                {
                    AddIntersectionEvent(eventList, segA, segB, i);
                }
            }
            else
            {
                Generator.DrawPoint(ev.Point, surface, Brushes.Red);

                Segment seg1 = ev.IntersectingSegments.Item1;
                Segment seg2 = ev.IntersectingSegments.Item2;

                sweepLine.Remove(seg1);
                sweepLine.Remove(seg2);

                Segment t = new Segment(seg1);
                seg1 = new Segment(seg2);
                seg2 = new Segment(t);

                sweepLine.Insert(seg1);
                sweepLine.Insert(seg2);

                Segment segA = sweepLine.InorderPre(seg2);
                Segment segB = sweepLine.InorderSuc(seg1);

                SegPoint i = new SegPoint();
                if (segA != null && Geometry.Intersects(seg2, segA, out i.Point))
                    AddIntersectionEvent(eventList, segA, seg2, i);
                if (segB != null && Geometry.Intersects(seg1, segB, out i.Point))
                    AddIntersectionEvent(eventList, seg1, segB, i);
            }
        }
    }
}
</code>```

答:
I really cannot understand your code without some idea of what exactly the other classes do, but I can answer some of your other questions.

The segments are ordered in the BST by the Y coordinate of their intersection with the sweep line.  So when we encounter a left endpoint we add the segment to the tree using the y coordinate of the left endpoint of the entering segment (comparing it with the Y coordinate of the intersection of the other segment with the sweep line).  When we encounter a right endpoint we remove the segment from the tree.  When we encounter an intersection, then the order of the intersections of the two segments with the sweep line switches, so we swap the two segments in the tree.  For example consider the two segments

```<code> A = {(-1,1),(1,-1)} and
 B = {(-1,-1),(1,1)}
</code>```

When the X coordinate of the sweep line is less than 0 then the intersection of segment A with the sweep line is greater than the intersection of segment B with the sweep line. and if the sweep line is greater than 0 the reverse is true.  (Draw a picture.)

It is probably instructive to draw a simple example, and trace what is going on step by step, drawing the sweep line for each event and labeling the segments in columns between the events, then keeping track of  the BST and verifying that the BST keeps the same order as the segments in the region where it is valid.  (I'm sorry if that is not as clear as it could be.)

Note:  This assumes that your segments are in "general position", i.e. that no segment is vertical, no more than two segments intersect at a given point, etc.  Dealing with segments not in general position is outlined on the wikipedia page

ContentLicense: CC BY-SA 2.5

Body:
I am having some trouble correctly implementing the Bentley-Ottmann algorithm in C#. I am trying to implement it according to the pseudocode here. I have posted my main code below. Assuming my BST and PriorityQueue classes are implemented correctly, do you see any problems with the code?

There are no errors, but not all intersection points are found, only some. My guess is that there's an error in the else part of the code (when the current event is an intersection point). I'm not sure what the pseudocode means by swapping the position of two segments in the BST. Is the way I do it fine? Because in the end, the two aren't really swapped in the BST. I can't just change their positions either, because that could break the BST properties.

Also, am I right in assuming that segments are ordered in the BST by the Y-coordinate of their left endpoint?

Another error I've noticed that I can't seem to be able to track down is that sometimes the point (0, 0) gets into eventList. (0, 0) is outputted by Geometry.Intersects in case there is no intersection, but in that case the if conditions should stop it from getting added. I have no idea how it gets in. If I print the contents of eventList after adding a point in, (0, 0) never shows up. If I print the contents after extracting and popping an element, (0, 0) sometimes shows up. Could this have anything to do with the Pop() method messing with the references, or is it definitely a problem in my PriorityQueue implementation?

If needed I can show my implementations for the BST and priority queue as well.

static class BentleyOttman
{
    private static void AddIntersectionEvent(PriorityQueue eventList, Segment segEv, Segment segA, SegPoint i)
    {
        i.IntersectingSegments = new Tuple<Segment, Segment>(segEv, segA);
        i.Type = SegmentPointType.IntersectionPoint;

        eventList.Add(i);
    }

    public static void Solve(Panel surface, TextBox debug)
    {
        debug.Clear();
        var segList = Generator.SegList;

        PriorityQueue eventList = new PriorityQueue();

        foreach (Segment s in segList)
        {
            eventList.Add(new SegPoint(s.A, s, SegmentPointType.LeftEndpoint));
            eventList.Add(new SegPoint(s.B, s, SegmentPointType.RightEndpoint));
        }

        BST sweepLine = new BST();
        while (!eventList.Empty)
        {
            SegPoint ev = eventList.Top();

            eventList.Pop();

            if (ev.Type == SegmentPointType.LeftEndpoint)
            {
                Segment segEv = ev.Segment;
                sweepLine.Insert(segEv);

                Segment segA = sweepLine.InorderPre(segEv);
                Segment segB = sweepLine.InorderSuc(segEv);

                SegPoint i = new SegPoint();
                if (segA != null && Geometry.Intersects(segEv, segA, out i.Point))
                {
                    AddIntersectionEvent(eventList, segA, segEv, i);
                }
                if (segB != null && Geometry.Intersects(segEv, segB, out i.Point))
                {
                    AddIntersectionEvent(eventList, segEv, segB, i);
                }
            }
            else if (ev.Type == SegmentPointType.RightEndpoint)
            {
                Segment segEv = ev.Segment;

                Segment segA = sweepLine.InorderPre(segEv);
                Segment segB = sweepLine.InorderSuc(segEv);

                sweepLine.Remove(segEv);

                SegPoint i = new SegPoint();
                if (segA != null && segB != null && Geometry.Intersects(segA, segB, out i.Point))
                {
                    AddIntersectionEvent(eventList, segA, segB, i);
                }
            }
            else
            {
                Generator.DrawPoint(ev.Point, surface, Brushes.Red);

                Segment seg1 = ev.IntersectingSegments.Item1;
                Segment seg2 = ev.IntersectingSegments.Item2;

                sweepLine.Remove(seg1);
                sweepLine.Remove(seg2);

                Segment t = new Segment(seg1);
                seg1 = new Segment(seg2);
                seg2 = new Segment(t);

                sweepLine.Insert(seg1);
                sweepLine.Insert(seg2);

                Segment segA = sweepLine.InorderPre(seg2);
                Segment segB = sweepLine.InorderSuc(seg1);

                SegPoint i = new SegPoint();
                if (segA != null && Geometry.Intersects(seg2, segA, out i.Point))
                    AddIntersectionEvent(eventList, segA, seg2, i);
                if (segB != null && Geometry.Intersects(seg1, segB, out i.Point))
                    AddIntersectionEvent(eventList, seg1, segB, i);
            }
        }
    }
}

Body:
I really cannot understand your code without some idea of what exactly the other classes do, but I can answer some of your other questions.

The segments are ordered in the BST by the Y coordinate of their intersection with the sweep line.  So when we encounter a left endpoint we add the segment to the tree using the y coordinate of the left endpoint of the entering segment (comparing it with the Y coordinate of the intersection of the other segment with the sweep line).  When we encounter a right endpoint we remove the segment from the tree.  When we encounter an intersection, then the order of the intersections of the two segments with the sweep line switches, so we swap the two segments in the tree.  For example consider the two segments

 A = {(-1,1),(1,-1)} and
 B = {(-1,-1),(1,1)}

When the X coordinate of the sweep line is less than 0 then the intersection of segment A with the sweep line is greater than the intersection of segment B with the sweep line. and if the sweep line is greater than 0 the reverse is true.  (Draw a picture.)

It is probably instructive to draw a simple example, and trace what is going on step by step, drawing the sweep line for each event and labeling the segments in columns between the events, then keeping track of  the BST and verifying that the BST keeps the same order as the segments in the region where it is valid.  (I'm sorry if that is not as clear as it could be.)

Note:  This assumes that your segments are in "general position", i.e. that no segment is vertical, no more than two segments intersect at a given point, etc.  Dealing with segments not in general position is outlined on the wikipedia page


问:
Encryption and Decryption (java)
have adapted this codes from
- http://www.roseindia.net/answers/viewqa/Java-Beginners/7551-encryption-and-decryption.html

but i'm having some error.
on the (str) , it keeps saying to initiate variable.
and when i corrected it to be

String st,str = null;

and run, it gives me "Error: Could not find or load main class tryoutEncryption.encryptingfile"

package tryoutEncryption;

```<code>import java.io.*;
import java.security.*;
import javax.crypto.*;

class EncryptAndDecrypt {

public static void main (String[] args) throws Exception{
KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keygenerator.initialize(1024, random);

KeyPair keypair = keygenerator.generateKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);
BufferedReader br=new BufferedReader(new FileReader(new File("C:\\Users\\Desktop\\testing.txt")));
String st,str;
while((st=br.readLine()) != null)   {
    str+=st+" ";
}

byte[] cleartext = null;
cleartext = str.getBytes();
byte[] ciphertext = null;
ciphertext = cipher.doFinal(cleartext);
System.out.println("the encrypted text is: " + ciphertext.toString());

cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cleartext1 = cipher.doFinal(ciphertext);
System.out.println("the decrypted cleartext is: " + new String(cleartext1));
}
}
</code>```

答:
make class public and assign empty value to String </p>

```<code>import java.io.*;
import java.security.*;
import javax.crypto.*;

public class EncryptAndDecrypt
{

    public static void main(String[] args)
    {
        try{
        KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keygenerator.initialize(1024, random);

        KeyPair keypair = keygenerator.generateKeyPair();
        PrivateKey privateKey = keypair.getPrivate();
        PublicKey publicKey = keypair.getPublic();
        Cipher cipher = Cipher.getInstance("RSA");

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Desktop\\testing.txt")));
        String st="", str="";
        while ((st = br.readLine()) != null)
        {
            str += st + " ";
        }

        byte[] cleartext = null;
        cleartext = str.getBytes();
        byte[] ciphertext = null;
        ciphertext = cipher.doFinal(cleartext);
        System.out.println("the encrypted text is: " + ciphertext.toString());

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] cleartext1 = cipher.doFinal(ciphertext);
        System.out.println("the decrypted cleartext is: " + new String(cleartext1));
        }catch(Exception e){e.printStackTrace();}
    }

}
</code>```

Title: Encryption and Decryption (java)

Body:
have adapted this codes from
- http://www.roseindia.net/answers/viewqa/Java-Beginners/7551-encryption-and-decryption.html

but i'm having some error.
on the (str) , it keeps saying to initiate variable.
and when i corrected it to be

String st,str = null;

and run, it gives me "Error: Could not find or load main class tryoutEncryption.encryptingfile"

package tryoutEncryption;

import java.io.*;
import java.security.*;
import javax.crypto.*;

class EncryptAndDecrypt {

public static void main (String[] args) throws Exception{
KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keygenerator.initialize(1024, random);

KeyPair keypair = keygenerator.generateKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);
BufferedReader br=new BufferedReader(new FileReader(new File("C:\\Users\\Desktop\\testing.txt")));
String st,str;
while((st=br.readLine()) != null)   {
    str+=st+" ";
}

byte[] cleartext = null;
cleartext = str.getBytes();
byte[] ciphertext = null;
ciphertext = cipher.doFinal(cleartext);
System.out.println("the encrypted text is: " + ciphertext.toString());

cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cleartext1 = cipher.doFinal(ciphertext);
System.out.println("the decrypted cleartext is: " + new String(cleartext1));
}
}

Body:
make class public and assign empty value to String

import java.io.*;
import java.security.*;
import javax.crypto.*;

public class EncryptAndDecrypt
{

    public static void main(String[] args)
    {
        try{
        KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keygenerator.initialize(1024, random);

        KeyPair keypair = keygenerator.generateKeyPair();
        PrivateKey privateKey = keypair.getPrivate();
        PublicKey publicKey = keypair.getPublic();
        Cipher cipher = Cipher.getInstance("RSA");

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Desktop\\testing.txt")));
        String st="", str="";
        while ((st = br.readLine()) != null)
        {
            str += st + " ";
        }

        byte[] cleartext = null;
        cleartext = str.getBytes();
        byte[] ciphertext = null;
        ciphertext = cipher.doFinal(cleartext);
        System.out.println("the encrypted text is: " + ciphertext.toString());

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] cleartext1 = cipher.doFinal(ciphertext);
        System.out.println("the decrypted cleartext is: " + new String(cleartext1));
        }catch(Exception e){e.printStackTrace();}
    }

}


问:
Regext for the following
I am to get the following results as an extract from google sheets using Regex

If I have the following 2 field items:

S01_123_123_123

S02_1_123_123_123

I want to extract

S01

S02_1

I have tried the following formulas:

=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^(.*?)_")))))
This gives:

S01

S02

```<code>=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^z.*?_")))))
</code>```

S01_

S02_

Running out of ideas now. I have even tried non grouping (?:_) with and OR "|" but that doesn't seem to do anything.

答:
Thanks to Wiktor your solution worked.

```<code>^(.*?)(?:_[^_]+){3}$
</code>```

If you'd be so kind to explain how that is working

Title: Regext for the following

Body:
I am to get the following results as an extract from google sheets using Regex

If I have the following 2 field items:

S01_123_123_123

S02_1_123_123_123

I want to extract

S01

S02_1

I have tried the following formulas:

=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^(.*?)_")))))
This gives:

S01

S02

=iferror(sort(unique(arrayformula(REGEXEXTRACT(Sheet!A$2:A,"^z.*?_")))))

S01_

S02_

Running out of ideas now. I have even tried non grouping (?:_) with and OR "|" but that doesn't seem to do anything.

Body:
Thanks to Wiktor your solution worked.

^(.*?)(?:_[^_]+){3}$

If you'd be so kind to explain how that is working


问:
In React, how to update state AND call a function from a single event?
I have a child component that renders a button. When this button is pressed, I would like to animate the button, while simultaneously updating the state of the parent component so that it shows a different view.

How can these both be done from the one event? I thought to call a single function/method, but I am unsure how to update the parents state from within a method - I only know how to do this on an event listener in the render method.

Heres the child -

```<code>return (
        <View>
             <View style={styles.switch}>
                 <TouchableHighlight onPress={this.props.buttonClick}>
                    <Animated.View
                        style={{
                          marginLeft,
                          height: 30,
                          width: 40,
                          backgroundColor: 'red'}} />
                 </TouchableHighlight>
              </View>
        </View>

    );
  }
}
</code>```

答:
Pass a callback as a prop from the parent to the child (which it looks like you are doing already), but then wrap the call to it in a local event handler method to do anything else you need to do in the child as well, instead of referencing the callback directly in your onPress

Note the use of arrow function syntax in the onButtonClick method - this will mean you already have a lexically bound this to the scope of the class instance

SomeChild

```<code>onButtonClick = () => {
   // do whatever you need to get done in this child
   this.whatever()
   // call the parents callback to make it do whatever changes it needs
   this.props.buttonClicked()
}

render () {
  return (
        <View>
             <View style={styles.switch}>
                 <TouchableHighlight onPress={this.onButtonClick}>
                    <Animated.View
                        style={{
                          marginLeft,
                          height: 30,
                          width: 40,
                          backgroundColor: 'red'}} />
                 </TouchableHighlight>
              </View>
        </View>

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

Parent

```<code>onChildClickedCallbackMethod = () => {
  // do something with parent here...
}

render() {
   return <SomeChild buttonClicked={this.onChildClickedCallbackMethod} />
}
</code>```

Body:
I have a child component that renders a button. When this button is pressed, I would like to animate the button, while simultaneously updating the state of the parent component so that it shows a different view.

How can these both be done from the one event? I thought to call a single function/method, but I am unsure how to update the parents state from within a method - I only know how to do this on an event listener in the render method.

Heres the child -

return (
        <View>
             <View style={styles.switch}>
                 <TouchableHighlight onPress={this.props.buttonClick}>
                    <Animated.View
                        style={{
                          marginLeft,
                          height: 30,
                          width: 40,
                          backgroundColor: 'red'}} />
                 </TouchableHighlight>
              </View>
        </View>

    );
  }
}

Body:
Pass a callback as a prop from the parent to the child (which it looks like you are doing already), but then wrap the call to it in a local event handler method to do anything else you need to do in the child as well, instead of referencing the callback directly in your onPress

Note the use of arrow function syntax in the onButtonClick method - this will mean you already have a lexically bound this to the scope of the class instance

SomeChild

onButtonClick = () => {
   // do whatever you need to get done in this child
   this.whatever()
   // call the parents callback to make it do whatever changes it needs
   this.props.buttonClicked()
}

render () {
  return (
        <View>
             <View style={styles.switch}>
                 <TouchableHighlight onPress={this.onButtonClick}>
                    <Animated.View
                        style={{
                          marginLeft,
                          height: 30,
                          width: 40,
                          backgroundColor: 'red'}} />
                 </TouchableHighlight>
              </View>
        </View>

      );
    }
  }
}

Parent

onChildClickedCallbackMethod = () => {
  // do something with parent here...
}

render() {
   return <SomeChild buttonClicked={this.onChildClickedCallbackMethod} />
}


问:
Integration Rich client application with HP load runner
We use Teamcenter software at our environment and it is a rich client Java application. We wanted to measure its performance by using the HP load runner software. However this is not working as the load runner is not able to start the application.

The support team of HP got back to us with the statement as below:

The root of the issue in fact that AUT has unexpected by Vugen
  multi-process hierarchy, Vugen cannot record process outside of
  single-root tree, specified at Start Recording Dialog. You can ask
  your app Dev team to rebuild the software so all new process will be
  children of parent process.

Can you please help me understand what can be done here?. Has anyone experienced such a problem?.

Thanks,
Pavan.

答:
Big questions:

What is the next upstream architectural component from the client?

What well known ports/protocols are identified by a wireshark trace of your application?

When querying "The Google" using the terms "acuity teamcenter architecture" I ran across a SOA whitepaper that would suggest that at least some interfaces can be exercised via a standard HTTP client which could be captured via proxy.   I do not know if the Java client leverages this same interface model, but if it does then changing your global application proxy to point to an instance of the LoadRunner HTTP recording proxy will then allow you to record the conversation.


问:
Execute Command Linux in PHP
How to execute linux command in php?

EDIT: this command is not output the result, this command is saving the scraped data into json file and display it using php, html

```<code><?php
    if (isset($_POST['button']))
    {
         exec('(cd /var/www/html && scrapy crawl quotes -o - > /var/www/html/items.json -t json)');
    }
?>
</code>```

答:
```<code><?php system("cd /var/www/html && scrapy crawl quotes -o - > /var/www/html/items.json -t json", $retval); echo $retval; ?>
</code>```

<p>or you can put your command in backticks </p>

```<code><?php
  $output = `cd /var/www/html && scrapy crawl quotes -o - > /var/www/html/items.json -t json`;
 echo "```$output```";
?>
</code>```

Title: Execute Command Linux in PHP

Body:
How to execute linux command in php?

EDIT: this command is not output the result, this command is saving the scraped data into json file and display it using php, html

<?php
    if (isset($_POST['button']))
    {
         exec('(cd /var/www/html && scrapy crawl quotes -o - > /var/www/html/items.json -t json)');
    }
?>

Body:
<?php system("cd /var/www/html && scrapy crawl quotes -o - > /var/www/html/items.json -t json", $retval); echo $retval; ?>

or you can put your command in backticks

<?php
  $output = `cd /var/www/html && scrapy crawl quotes -o - > /var/www/html/items.json -t json`;
 echo "<pre>$output</pre>";
?>


问:
CSS Text-overflow Ellipsis Not Displaying Correctly
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

```<code>.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}
</code>```

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

答:
I think the issue is caused by the length of the word(s) "TestingTestingTestingTestingTestingTesting"
Using word-wrap (word-wrap: break-word;) would alleviate the issue: example here

Body:
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting


问:
Unable to set focus to textbox in dojo datagrid
I have a Dojo Datagrid with one of the columns being rendered as a textbox by a formatter function. When I click on the rendered textbox to enter some value, the cursor appears in the textbox and focus is immediately lost (i.e, the cursor disappears - typing does not produce anything). I have to click once more on the textbox for the focus to set - only then can I enter values.

Is there any way to set the focus on the first click itself?

Here is the code:

```<code><table dojoType="dojox.grid.DataGrid" store="selectedItemsStore" class="resultsGridClass" jsid="selecteditems">
<thead>
<tr>
<th field="field1" formatter="renderTextBox" width="20%">Field 1</th>
</tr>
</thead>
</table>
</code>```

And here is the formatter function:

```<code>function renderTextBox(value, rowIndex) {
var htmlString = "<input type='text' name= 'exp' />";
return htmlString;
}
</code>```

答:
In my case below code works perfectly for the text box focus issue:

```<code>dojo.connect(this.floorTable,"onRowClick",this,function(row){
    row.target.focus();
});
</code>```

where this.floorTable is a table object.

Body:
I have a Dojo Datagrid with one of the columns being rendered as a textbox by a formatter function. When I click on the rendered textbox to enter some value, the cursor appears in the textbox and focus is immediately lost (i.e, the cursor disappears - typing does not produce anything). I have to click once more on the textbox for the focus to set - only then can I enter values.

Is there any way to set the focus on the first click itself?

Here is the code:

Field 1

And here is the formatter function:

function renderTextBox(value, rowIndex) {
var htmlString = "<input type='text' name= 'exp' />";
return htmlString;
}

Body:
In my case below code works perfectly for the text box focus issue:

dojo.connect(this.floorTable,"onRowClick",this,function(row){
    row.target.focus();
});

where this.floorTable is a table object.


答:
You can pass a callback from parent to the child in the form of props to the child component.

On click of the button, you can first animate the button and once that is done, you can call the callback that is passed from parent to child.

Alternatively, you can first call the callback and then animate. This depends on your requirements and how does your code run.

How to update parent's state in React?

Title: In React, how to update state AND call a function from a single event?


问:
Using jsPDF to export a Div in my website into a PDF format report but can't get the right format
as what the title says, I'm using jsPDF to export a div section in my website to be exported as a PDF document.

These are my codes

```<code><script>
function exportToPDF() {
    var pdf = new jsPDF('l', 'pt', 'a4');
    // source can be HTML-formatted string, or a reference
    // to an actual DOM element from which the text will be scraped.
    source = $('#tab_cm')[0];

    // we support special element handlers. Register them with jQuery-style
    // ID selector for either ID or node name. ("#iAmID", "div", "span"
    etc.)
    // There is no support for any other type of selectors
    // (class, of compound) at this time.
    specialElementHandlers = {
        // element with id of "bypass" - jQuery style selector
        '#bypassme': function (element, renderer) {
            // true = "handled elsewhere, bypass text extraction"
            return true
        }
    };
    margins = {
        top: 30,
        bottom: 60,
        left: 30,
        width: 500
    };
    // all coords and widths are in jsPDF instance's declared units
    // 'inches' in this case
    pdf.fromHTML(
        source, // HTML string or DOM elem ref.
        margins.left, // x coord
        margins.top, { // y coord
            'width': margins.width, // max width of content on PDF
            'elementHandlers': specialElementHandlers
        },

        function (dispose) {
            // dispose: object with X, Y of the last line add to the PDF
            //          this allow the insertion of new lines after html
            pdf.save(pdfName);
        }, margins
    );
}
</script>
</code>```

My Div section looks like this:
https://drive.google.com/file/d/0B2mHDe7wmRSfU2Q0UjM4QV9Sc2c/view?usp=sharing

But it looks like this once exported
https://drive.google.com/file/d/0B2mHDe7wmRSfMndIVGZUQ2FHLW8/view?usp=sharing

As you can see I don't know how to properly align those texts inside the table of my exported PDF.

Thank you in advance for your help!

答: jspdf don't support css, so it can be hard to get the right format. You can make an image of your html, and then add it to pdf. See this answer: https://stackoverflow.com/a/43064789/7751910</p>

Body:
as what the title says, I'm using jsPDF to export a div section in my website to be exported as a PDF document.

These are my codes

My Div section looks like this:
https://drive.google.com/file/d/0B2mHDe7wmRSfU2Q0UjM4QV9Sc2c/view?usp=sharing

But it looks like this once exported
https://drive.google.com/file/d/0B2mHDe7wmRSfMndIVGZUQ2FHLW8/view?usp=sharing

As you can see I don't know how to properly align those texts inside the table of my exported PDF.

Thank you in advance for your help!


问:
AngularJS ui-sref external (absolute) link
I wrote a little angular app. I've got an array of menu items which I print in my template:

```<code><nav id="menu">
  <ul>
    <li ng-repeat="i in menuItems"
        ui-sref="{{ i | removeSpacesThenLowercase }}"
        ui-sref-active="active">{{ i }}</li>
  </ul>
</nav>
</code>```

And in my app.js I declared my states using ui-router like:

```<code>.state('camera', {
  url: '/selection',
  templateUrl: '/views/selection.html',
  uiShade: 'light back',
  back: 'intro'
})
</code>```

Internal URLs work just fine, but what if I want to do this?

```<code>.state('facebook', {
  url: 'https://www.facebook.com/'
})
</code>```

This obviously doesn't work. What would be the best approach to have some external (absolute) links in my template without having two separate arrays?

答:
I fixed this in my application using ng-if.

Example menu items:

```<code>     $scope.navItems = [{
        id: 1,
        title: 'Internal Link',
        href: null,
        sref: 'internal-state'
    },
    {
        id: 2,
        title: 'External Link',
        href: 'https:/google.co.uk',
        sref: null
    }];
</code>```

Then in the HTML I set the ng-repeat on the
 but include an  for href and one for sref, each with an ng-if.

```<code>     <li ng-repeat="item in navItems">
         <a ng-if="item.sref" ui-sref="{{item.sref}}">{{ item.title }}</a>
         <a ng-if="item.href" href="{{item.href}}">{{ item.title }}</a>
     </li>
</code>```

Body:
I wrote a little angular app. I've got an array of menu items which I print in my template:

{{ i }}

And in my app.js I declared my states using ui-router like:

.state('camera', {
  url: '/selection',
  templateUrl: '/views/selection.html',
  uiShade: 'light back',
  back: 'intro'
})

Internal URLs work just fine, but what if I want to do this?

.state('facebook', {
  url: 'https://www.facebook.com/'
})

This obviously doesn't work. What would be the best approach to have some external (absolute) links in my template without having two separate arrays?

Body:
I fixed this in my application using ng-if.

Example menu items:

     $scope.navItems = [{
        id: 1,
        title: 'Internal Link',
        href: null,
        sref: 'internal-state'
    },
    {
        id: 2,
        title: 'External Link',
        href: 'https:/google.co.uk',
        sref: null
    }];

Then in the HTML I set the ng-repeat on the <li> but include an <a> for href and one for sref, each with an ng-if.

     <li ng-repeat="item in navItems">
         <a ng-if="item.sref" ui-sref="{{item.sref}}">{{ item.title }}</a>
         <a ng-if="item.href" href="{{item.href}}">{{ item.title }}</a>
     </li>