问:
On my Magento store I cannot login on the frontend and cannot add items to my shopping cart after upgrading to 1.4.2. Any ideas what's wrong
I have just upgraded my Magento shopping cart to 1.4.2. Since the upgrade when I try to login on the frontend the page refreshes, but there's no evidence of being logged in. If I try to login with the wrong credentials I get an error message. I figured that it might be a session problem so I tried adding an item to my cart. When I do that I get an error message that says, "Cannot add the item to shopping cart." This might be an unrelated problem. Was wondering if anyone has any ideas where to look. Adding an item to the shopping cart adds the following line to the log:

```<code>DEBUG (7): Exception message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'additional_table.is_visible_on_front' in 'field list'
</code>```

Trace: #0 /var/www/magentobase/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)

Logging in produces no errors.

Thanks for looking!

答:
Its been fixed. The problem was that I wasn't thorough enough in re-indexing and flushing the cache. To get it working I:

Flushed Magento Cache and Cache
storage by pushing the buttons in
System -> Cache Management

Refreshed the cache by checking all
the items under System -> Cache and
selecting "Refresh"

Reindexed everything by going to
System -> Index Management and
selecting all times and then
selecting "Reindex Data".

I hope this helps!

Body:
I have just upgraded my Magento shopping cart to 1.4.2. Since the upgrade when I try to login on the frontend the page refreshes, but there's no evidence of being logged in. If I try to login with the wrong credentials I get an error message. I figured that it might be a session problem so I tried adding an item to my cart. When I do that I get an error message that says, "Cannot add the item to shopping cart." This might be an unrelated problem. Was wondering if anyone has any ideas where to look. Adding an item to the shopping cart adds the following line to the log:

DEBUG (7): Exception message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'additional_table.is_visible_on_front' in 'field list'

Trace: #0 /var/www/magentobase/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)

Logging in produces no errors.

Thanks for looking!


来源: stackexchange

问:
graph_transforms in tensorflow 1.4 when installing with pip
I installed tensorflow 1.4.0 with pip3. (Windows)

I'm trying to use cv2.dnn.readNetFromTensorflow with a retrained Inception V3 graph.

Unfortunately it seems cv2 does not support retrained graphs so I went through transform graph.pb into one usable by cv2, but unfortunately I can't find no transform_graph in graph_transforms in tensorflow.

Should I install tensorflow differently?

答:
You have to Build it first.

bazel build tensorflow/tools/graph_transforms:transform_graph

Note that it will not work if you're using a Opencv version below 3.3.1 and even than my graphs are not very accurate after loading.

Answer to edit:
yes that script has to be build with bazel and is not in your normal download.

ContentLicense: CC BY-SA 3.0


问:
Design with dashed line and arc in middle of the UIView
I am designing one of the screen which has quite complex UI.

The UIView has dashed-line in middle with arc on right and left side.

Please check below picture for better understanding.

Can anyone guide me how to achieve such design in iOS?

答:
Use this code to create a dashed line with custom parameters:

```<code>let  path = UIBezierPath()

let  point1 = CGPointMake(CGRectGetMinX(self.bounds),CGRectGetMidY(self.bounds))
path.moveToPoint(point1)

let  point2 = CGPointMake(CGRectGetMaxX(self.bounds),CGRectGetMidY(self.bounds))
path.addLineToPoint(point2)

let  dashes: [CGFloat] = [12.0, 24.0]
path.setLineDash(dashes, count: dashes.count, phase: 0.0)

path.lineWidth = 10.0
path.lineCapStyle = .Butt
UIColor.greenColor().set()
path.stroke()
</code>```

For framing just use a rectangle and a circle (you'll get an arc).

Body:
Use this code to create a dashed line with custom parameters:

let  path = UIBezierPath()

let  point1 = CGPointMake(CGRectGetMinX(self.bounds),CGRectGetMidY(self.bounds))
path.moveToPoint(point1)

let  point2 = CGPointMake(CGRectGetMaxX(self.bounds),CGRectGetMidY(self.bounds))
path.addLineToPoint(point2)

let  dashes: [CGFloat] = [12.0, 24.0]
path.setLineDash(dashes, count: dashes.count, phase: 0.0)

path.lineWidth = 10.0
path.lineCapStyle = .Butt
UIColor.greenColor().set()
path.stroke()

For framing just use a rectangle and a circle (you'll get an arc).


问:
Making dropdown visible javascript
I made a dropdown system with razor script in Umbraco. I finally got all the children working but how do I hide the sub items that should be a dropdown list? I tried something with javascript but that seemed to open all dropdowns instead of each one individually.

Here's my code:

```<code><div class="col-sm-3">
  <div class="well well-lg span-padding extra-padding top background-light">
    <ul class="nav nav-list tree">
      @ {
        var documentRootNodeId = Model.Content.GetPropertyValue("documentRoot", true); // Fetch recursive document root id.
        var selection = Umbraco.TypedContent(documentRootNodeId).Children.Where("Visible"); // Select all nodes below the document root.
      }
      @foreach(var item in Model.Content.Ancestor(1).Descendants("menu")) {
        foreach(var ItemChild in @item.Children("hoofdstuk")) {
        <li> @ItemChild.Name </li>
          foreach(var Subitem in @ItemChild.Children) {
          <li><a href = "@Subitem.Url"> @Subitem.Name </a></li>
              if (Subitem.Children.Any()) {
                foreach(var Finalitem in @Subitem.Children) {
                  <ul>
                    <li> < a href = "@Finalitem.Url" > @Finalitem.Name </a></li>
                  </ul>
                }
              }
            }
          }
        }
      }
    </ul>
  </div>
</div>
</code>```

Javascript:

```<code>function myFunction(a) {
    var itemcount = a.parentNode.getElementsByClassName("sub").length;
    for (i = 0; i < itemcount; i++) {
        a.parentNode.getElementsByClassName("sub")[i].classList.toggle("show");
    }
}
</code>```

This is what it displays:

Sub-Subtest1 and 2 needs to be hidden till we click it's ancestor which is SubTest1. Same goes for sub-subtest9.

I can't seem to get it working dynamically. If I create something with javascript it opens all the dropdown's at once and not individually.

答:
First, I would recommend you to use Visual Studio, that will help you to fix issues with your code. You should fix your html structure and nest the elements of your list properly. You have li as direct children of li which is invalid.

```<code><div class="col-sm-3">
    <div class="well well-lg span-padding extra-padding top background-light">
        <ul class="nav nav-list tree">
            @{
                var documentRootNodeId = Model.Content.GetPropertyValue("documentRoot", true); // Fetch recursive document root id.
                var selection = Umbraco.TypedContent(documentRootNodeId).Children.Where("Visible"); // Select all nodes below the document root.
            }
            @foreach (var item in Model.Content.Ancestor(1).Descendants("menu"))
            {
                foreach (var ItemChild in item.Children("hoofdstuk"))
                {
                    <li class="item">
                        @if (ItemChild.Children.Any())
                        {
                            <ul class="submenu">
                                @foreach (var Subitem in ItemChild.Children)
                                {
                                    <li class="item">
                                        <a href="@Subitem.Url"> @Subitem.Name </a>
                                        @if (Subitem.Children.Any())
                                         {
                                            foreach (var Finalitem in Subitem.Children)
                                            {
                                                <ul class="submenu">
                                                    <li> <a href="@Finalitem.Url"> @Finalitem.Name </a></li>
                                                </ul>
                                            }
                                        }
                                    </li>

                                }
                            </ul>
                        }
                    </li>
                }
            }
        </ul>
    </div>
</div>
</code>```

Then you can use jQuery to easily show the submenus. Use [children][1] to retrieve only the first level of submenus:

```<code>$(".item").click(function(){
    $(this).children(".submenu").toggle(); //it will display or hide your submenu when clicking the item.
});
</code>```

And your submenu should be hidden by default, you can do that with css:

```<code>.submenu{
    display: none;
}
</code>```

Note: to make the code more clear I would recommend you to use Razor helpers to create a recursive function for your sublists.

Title: Making dropdown visible javascript

Body:
I made a dropdown system with razor script in Umbraco. I finally got all the children working but how do I hide the sub items that should be a dropdown list? I tried something with javascript but that seemed to open all dropdowns instead of each one individually.

Here's my code:

      @ {
        var documentRootNodeId = Model.Content.GetPropertyValue("documentRoot", true); // Fetch recursive document root id.
        var selection = Umbraco.TypedContent(documentRootNodeId).Children.Where("Visible"); // Select all nodes below the document root.
      }
      @foreach(var item in Model.Content.Ancestor(1).Descendants("menu")) {
        foreach(var ItemChild in @item.Children("hoofdstuk")) {

 @ItemChild.Name

          foreach(var Subitem in @ItemChild.Children) {

 @Subitem.Name

              if (Subitem.Children.Any()) {
                foreach(var Finalitem in @Subitem.Children) {

  @Finalitem.Name

                }
              }
            }
          }
        }
      }

Javascript:

function myFunction(a) {
    var itemcount = a.parentNode.getElementsByClassName("sub").length;
    for (i = 0; i < itemcount; i++) {
        a.parentNode.getElementsByClassName("sub")[i].classList.toggle("show");
    }
}

This is what it displays:

Sub-Subtest1 and 2 needs to be hidden till we click it's ancestor which is SubTest1. Same goes for sub-subtest9.

I can't seem to get it working dynamically. If I create something with javascript it opens all the dropdown's at once and not individually.

Body:
First, I would recommend you to use Visual Studio, that will help you to fix issues with your code. You should fix your html structure and nest the elements of your list properly. You have li as direct children of li which is invalid.

<div class="col-sm-3">
    <div class="well well-lg span-padding extra-padding top background-light">
        <ul class="nav nav-list tree">
            @{
                var documentRootNodeId = Model.Content.GetPropertyValue("documentRoot", true); // Fetch recursive document root id.
                var selection = Umbraco.TypedContent(documentRootNodeId).Children.Where("Visible"); // Select all nodes below the document root.
            }
            @foreach (var item in Model.Content.Ancestor(1).Descendants("menu"))
            {
                foreach (var ItemChild in item.Children("hoofdstuk"))
                {
                    <li class="item">
                        @if (ItemChild.Children.Any())
                        {
                            <ul class="submenu">
                                @foreach (var Subitem in ItemChild.Children)
                                {
                                    <li class="item">
                                        <a href="@Subitem.Url"> @Subitem.Name </a>
                                        @if (Subitem.Children.Any())
                                         {
                                            foreach (var Finalitem in Subitem.Children)
                                            {
                                                <ul class="submenu">
                                                    <li> <a href="@Finalitem.Url"> @Finalitem.Name </a></li>
                                                </ul>
                                            }
                                        }
                                    </li>

                                }
                            </ul>
                        }
                    </li>
                }
            }
        </ul>
    </div>
</div>

Then you can use jQuery to easily show the submenus. Use [children][1] to retrieve only the first level of submenus:

$(".item").click(function(){
    $(this).children(".submenu").toggle(); //it will display or hide your submenu when clicking the item.
});

And your submenu should be hidden by default, you can do that with css:

.submenu{
    display: none;
}

Note: to make the code more clear I would recommend you to use Razor helpers to create a recursive function for your sublists.


问:
How to send data via using POST in Zend_Rest_Client
There is the next code:

```<code>$client = new Zend_Rest_Client('http://test.com/rest');
$client->sendData('data');
</code>```

if i send via GET (echo $client->get()) it works correct

if via POST (echo $client->post()) i'm getting the next message "No Method Specified."

how to send post using Zend_Rest_Client?

答:
Maybe this helps:</p>

```<code>$base_url = 'http://www.example.com';
$endpoint = '/path/to/endpoint';
$data = array(
    'param1' => 'value1',
    'param2' => 'value2',
    'param3' => 'value3'
);
$client = new Zend_Rest_Client($base_url);
$response = $client->restPost($endpoint, $data);
print_r($response);
</code>```

Body:
There is the next code:

$client = new Zend_Rest_Client('http://test.com/rest');
$client->sendData('data');

if i send via GET (echo $client->get()) it works correct

if via POST (echo $client->post()) i'm getting the next message "No Method Specified."

how to send post using Zend_Rest_Client?

Body:
Maybe this helps:

$base_url = 'http://www.example.com';
$endpoint = '/path/to/endpoint';
$data = array(
    'param1' => 'value1',
    'param2' => 'value2',
    'param3' => 'value3'
);
$client = new Zend_Rest_Client($base_url);
$response = $client->restPost($endpoint, $data);
print_r($response);

ContentLicense: CC BY-SA 4.0


问:
How does Reflection in Laravel work?
How does reflection in Laravel actually work?

I tried to debug it to see how Laravel uses reflection in a controller's constructor or methods to resolve their dependencies and sub-dependencies and then and give it back to us.

But I found it hard, and it's very complicated to see and to even understand 50% of. Jumping from class to class, I can't really see it. I tried a few times by debugging it with low results of understanding.

I am very impressed by this and by reflection, and the way Laravel uses it makes my heart burn—it's just beautiful. And I wish to fully understand that—the whole process—in general, and step by step.

Beginning from hitting the route to finally having, let's say, dd($x), where $x is from a method argument and is a TestClass that has another dependency of TestClass2 that should be constructed through: $x = new TestClass(new TestClass2());

I think those are beautiful mechanics and architecture, and understanding this is something I want so badly.

So again, my question is: how does reflection in Laravel actually work?

It's not about dd guys... Let's say without dd. Just as I said earlier - when we have this object instantiated from the class method. It's not about dumping it, it's just about having it from method injection by reflection.

The dd was only an example. It can even be die(var_dump()); and it will work

答:
Laravel uses PHP's reflection API for several components. Of these, the inverson-of-control (IoC) dependency injection container and controller method injection are most visible to developers.

To more clearly illustrate the use of reflection, here's a dramatically simplified version of the routine Laravel's IoC container class uses to build up an object's dependencies through constructor injection:

```<code>function build($className)
{
    $reflector = new ReflectionClass($className);
    $constructor = $reflector->getConstructor();

    foreach ($constructor->getParameters() as $dependency) {
        $instances[] = build($dependency->getClass()->name);
    }

    return $reflector->newInstanceArgs($instances);
}
</code>```

As we can see, the concept isn't too difficult to understand. The container uses PHP's ReflectionClass to find the names of the classes in an object's constructor, and then loops through each of these names recursively to create instances of each object in the dependency tree. With these instances, build() finally instantiates the original class and passes the dependencies as arguments to the constructor.

Controller method injection uses the same container functionality shown above to resolve instances of dependencies declared as method parameters, but there's a bit of extra logic needed to separate class dependencies from route parameters:

```<code>function dispatch(Route $route, Controller $controller, $methodName)
{
    $routeParameters = $route->parametersWithoutNulls();
    $method = new ReflectionMethod($controller, $methodName);

    foreach ($method->getParameters() as $index => $parameter) {
        $class = $parameter->getClass();

        if ($class !== null) {
            $instance = build($class->name);
            array_splice($routeParameters, $index, 0, [ $instance ]);
        }
    }

    $controller->callAction($methodName, $routeParameters);
}
</code>```

Again, this adaptation is slimmed-down to highlight the role reflection plays and relies on our build() function shown previously. The ControllerDispatcher class uses the getParameters() method of PHP's ReflectionMethod to determine which parameters a controller method expects, and then loops through these to find parameters that represent dependencies that it can resolve from the container. Then, it splices each dependency it finds back into the array of route parameters that it passes back to the controller method defined for the route. See RouteDependencyResolverTrait for details.

If we ignore the application bootstrapping process, this dependency injection cascade typically starts for a request when Laravel maps a request to a route, and then determines which controller to pass the request to. Laravel first resolves an instance of the controller from the container, which builds out any constructor-injected dependencies. Then, Laravel finds the appropriate controller method and resolves any more dependencies for the arguments as needed.

As shown here, Laravel uses relatively simple techniques to implement these tools using reflection. However, unlike the examples shown in this answer, the framework adds a lot of additional code to make them as robust and flexible as they are today.

Title: How does Reflection in Laravel work?

Body:
Laravel uses PHP's reflection API for several components. Of these, the inverson-of-control (IoC) dependency injection container and controller method injection are most visible to developers.

To more clearly illustrate the use of reflection, here's a dramatically simplified version of the routine Laravel's IoC container class uses to build up an object's dependencies through constructor injection:

function build($className)
{
    $reflector = new ReflectionClass($className);
    $constructor = $reflector->getConstructor();

    foreach ($constructor->getParameters() as $dependency) {
        $instances[] = build($dependency->getClass()->name);
    }

    return $reflector->newInstanceArgs($instances);
}

As we can see, the concept isn't too difficult to understand. The container uses PHP's ReflectionClass to find the names of the classes in an object's constructor, and then loops through each of these names recursively to create instances of each object in the dependency tree. With these instances, build() finally instantiates the original class and passes the dependencies as arguments to the constructor.

Controller method injection uses the same container functionality shown above to resolve instances of dependencies declared as method parameters, but there's a bit of extra logic needed to separate class dependencies from route parameters:

function dispatch(Route $route, Controller $controller, $methodName)
{
    $routeParameters = $route->parametersWithoutNulls();
    $method = new ReflectionMethod($controller, $methodName);

    foreach ($method->getParameters() as $index => $parameter) {
        $class = $parameter->getClass();

        if ($class !== null) {
            $instance = build($class->name);
            array_splice($routeParameters, $index, 0, [ $instance ]);
        }
    }

    $controller->callAction($methodName, $routeParameters);
}

Again, this adaptation is slimmed-down to highlight the role reflection plays and relies on our build() function shown previously. The ControllerDispatcher class uses the getParameters() method of PHP's ReflectionMethod to determine which parameters a controller method expects, and then loops through these to find parameters that represent dependencies that it can resolve from the container. Then, it splices each dependency it finds back into the array of route parameters that it passes back to the controller method defined for the route. See RouteDependencyResolverTrait for details.

If we ignore the application bootstrapping process, this dependency injection cascade typically starts for a request when Laravel maps a request to a route, and then determines which controller to pass the request to. Laravel first resolves an instance of the controller from the container, which builds out any constructor-injected dependencies. Then, Laravel finds the appropriate controller method and resolves any more dependencies for the arguments as needed.

As shown here, Laravel uses relatively simple techniques to implement these tools using reflection. However, unlike the examples shown in this answer, the framework adds a lot of additional code to make them as robust and flexible as they are today.


问:
How to unsubscribe from valueChanges in Angular 4 reactive forms?
I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:

```<code>this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});
</code>```

The above code works perfectly. But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work. Please help me solve this.

答:
subscribe returns an object of type Subscription from which you can unsubscribe

```<code>this.subscription = this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

...

ngOnDestroy() {
   this.subscription.unsubscribe();
}
</code>```

Body:
I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:

this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

The above code works perfectly. But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work. Please help me solve this.

Body:
subscribe returns an object of type Subscription from which you can unsubscribe

this.subscription = this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

...

ngOnDestroy() {
   this.subscription.unsubscribe();
}


问:
Auto popup based on JavaScript/jQuery cookie
I am trying to add an auto popup message in the website that depends in js/jQuery cookie, meaning the the popup will show once a day only to a visitor (instead of showing every time page gets reloaded)

the cookie will expire in 24 hours, once its expires the auto popup will show again.

Many Thanks

答:
Pseudo code:</p>

```<code>var currentDate = new Date().toLocaleString();
var alertCookieDate = getCookieDate();
var alertWasShown = getCookiePopup(); //set here boolean if popup was shown on true and false if not
if(alertCookieDate < currentDate && !alertWasShown){
   alert("popup here");
   updateCookie(); //code to update time here;
   updateCookiePopup(); //set boolean here
}
</code>```

Body:
Pseudo code:

var currentDate = new Date().toLocaleString();
var alertCookieDate = getCookieDate();
var alertWasShown = getCookiePopup(); //set here boolean if popup was shown on true and false if not
if(alertCookieDate < currentDate && !alertWasShown){
   alert("popup here");
   updateCookie(); //code to update time here;
   updateCookiePopup(); //set boolean here
}


问:
CSS slider wont Slide
I've got a CSS slider, But I can't get it to auto slide.

I've got 4 divs of backgrounds that I'm trying to get to auto slide as a splash page for a website.
I don't know if the issue is my data cycle or am I better of finding a JS tutorial for this?

Can anyone help, please

.content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 100}

                body
                {
                    background: #3B242D;
                    font-family: 'Raleway', sans-serif;
                }
        html,body{height:100%; overflow: hidden}
                .cycle-slideshow{position:fixed !important;top:0;bottom:0;left:0;right:0; z-index: 0}
@keyframes slidy {
0% { left: 0%; }
20% { left: 0%; }
25% { left: -100%; }
45% { left: -100%; }
50% { left: -200%; }
70% { left: -200%; }
75% { left: -300%; }
95% { left: -300%; }
100% { left: -400%; }
}
    div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 5s slidy infinite;
}

```

I have Had abit more of a play with it and Think this is a better code, However it still does'nt work.
Have I possibly got too many DIV's going on?
I dont know if its the Div Im trying to set to slide or the Keyframes?

Thank you

答:
Ive solved the issue.

Instead of putting background in the HTML I did it in the css and then did an animation per slide.

```<code><div class='slider'>
  <div class='slide1'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
BRINGING YOU
OUR ADVANCED SEARCH TOOLBAR</h2></div>
</div>
  <div class='slide2'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
USE #TAGS TO FIND YOUR PERFECT
IMAGES FROM OUR SUPPLIERS</h2></div>
</div>
  <div class='slide3'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
WE’RE DOING THINGS IN A
DIFFERENT WAY</h2></div>
</div>
   <div class='slide4'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
WITH THE SUPPORT FROM THE
BIGGEST NAMES OUT THERE</h2></div>

</div>
</div>
<div class="content">
        <a href="/home"><img class="logo-img" src="https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-logo.png" alt="" ></a>
        <div class="btnContainer">
            <a href="https://thetaguk.com/site/home-2/" class="btn btnA">ENTER</a>
        </div>
    </div>
        body
        {
            background: #3B242D;
            font-family: 'Raleway', sans-serif;
        }

        h1{color:#fff; border-bottom:3px solid; border-top:3px solid;}
        h2{color:#fff;}
        .text{height:50%; width:30%; float:right;padding-right:5%;}

    .slider{position:fixed !important;top:0;bottom:0;left:0;right:0; z-index: 0;  }
        .slider{background-position:inherit;background-size:cover;width:100%;height:100%; z-index: 1;}
.slide1,.slide2,.slide3,.slide4,.slide5 {
  position: absolute;
  width: 100%;
  height: 100%;
}
.slide1 {
  background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-1-image.png)no-repeat center;
      background-size: cover;
    animation:fade 12s infinite;
-webkit-animation:fade 12s infinite;

}
.slide2 {
  background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-2-image.png)no-repeat center;
      background-size: cover;
    animation:fade2 12s infinite;
-webkit-animation:fade2 12s infinite;
}
.slide3 {
    background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-3-image.png)no-repeat center;
      background-size: cover;
    animation:fade3 12s infinite;
-webkit-animation:fade3 12s infinite;
}
.slide4 {
    background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/spashpage-4-image-1.png)no-repeat center;
      background-size: cover;
    animation:fade3 12s infinite;
-webkit-animation:fade3 12s infinite;
}
@keyframes fade
{
  0%   {opacity:1}
  33.333% { opacity: 0}
  66.666% { opacity: 0}
  100% { opacity: 1}
}
@keyframes fade2
{
  0%   {opacity:0}
  33.333% { opacity: 1}
  66.666% { opacity: 0 }
  100% { opacity: 0}
}
@keyframes fade3
{
  0%   {opacity:0}
  33.333% { opacity: 0}
  66.666% { opacity: 1}
  100% { opacity: 0}
}
.btnContainer { margin-top: 20px; }

        .btn {
            display: inline-block;
            background: #3B242D;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
        }
.logo-img{
            width: 320px;
        }
.content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 100}

        @media only screen and (max-width: 503px) {
            .tag{ padding-left:30px; background-size:contain; }
            .tag span{ font-size: 21px; }
            .logo-img{
                width: 160px;
            }
            h1 {
    color: #fff;
    border-bottom: 1px solid;
    border-top: 1px solid;
    font-size: 18px;
}
        h2{color:#fff; font-size:14px;}
        .text{height:50%; width:80%; }
        }
        @media only screen and (max-width: 768px){
    .cycle-slideshow .item{
    background-position:center center;
}
.tag.img-1 {
    bottom: auto;
    right: 10%;
    top: 70px;
}
.logo-img {
    width: 100px;
}
}
</code>```

See the PEN here

https://codepen.io/Chazlie/pen/MOmdEX

Title: CSS slider wont Slide

Body:
I've got a CSS slider, But I can't get it to auto slide.

I've got 4 divs of backgrounds that I'm trying to get to auto slide as a splash page for a website.
I don't know if the issue is my data cycle or am I better of finding a JS tutorial for this?

Can anyone help, please

.content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 100}

                body
                {
                    background: #3B242D;
                    font-family: 'Raleway', sans-serif;
                }
        html,body{height:100%; overflow: hidden}
                .cycle-slideshow{position:fixed !important;top:0;bottom:0;left:0;right:0; z-index: 0}
@keyframes slidy {
0% { left: 0%; }
20% { left: 0%; }
25% { left: -100%; }
45% { left: -100%; }
50% { left: -200%; }
70% { left: -200%; }
75% { left: -300%; }
95% { left: -300%; }
100% { left: -400%; }
}
    div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 5s slidy infinite;
}

I have Had abit more of a play with it and Think this is a better code, However it still does'nt work.
Have I possibly got too many DIV's going on?
I dont know if its the Div Im trying to set to slide or the Keyframes?

Thank you

Body:
Ive solved the issue.

Instead of putting background in the HTML I did it in the css and then did an animation per slide.

<div class='slider'>
  <div class='slide1'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
BRINGING YOU
OUR ADVANCED SEARCH TOOLBAR</h2></div>
</div>
  <div class='slide2'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
USE #TAGS TO FIND YOUR PERFECT
IMAGES FROM OUR SUPPLIERS</h2></div>
</div>
  <div class='slide3'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
WE’RE DOING THINGS IN A
DIFFERENT WAY</h2></div>
</div>
   <div class='slide4'><div class="text"><h2>TRUSTED ASIAN GUIDE</h2>
<h1>ASIAN WEDDING
DIRECTORY</h1>
<h2>
WITH THE SUPPORT FROM THE
BIGGEST NAMES OUT THERE</h2></div>

</div>
</div>
<div class="content">
        <a href="/home"><img class="logo-img" src="https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-logo.png" alt="" ></a>
        <div class="btnContainer">
            <a href="https://thetaguk.com/site/home-2/" class="btn btnA">ENTER</a>
        </div>
    </div>
        body
        {
            background: #3B242D;
            font-family: 'Raleway', sans-serif;
        }

        h1{color:#fff; border-bottom:3px solid; border-top:3px solid;}
        h2{color:#fff;}
        .text{height:50%; width:30%; float:right;padding-right:5%;}

    .slider{position:fixed !important;top:0;bottom:0;left:0;right:0; z-index: 0;  }
        .slider{background-position:inherit;background-size:cover;width:100%;height:100%; z-index: 1;}
.slide1,.slide2,.slide3,.slide4,.slide5 {
  position: absolute;
  width: 100%;
  height: 100%;
}
.slide1 {
  background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-1-image.png)no-repeat center;
      background-size: cover;
    animation:fade 12s infinite;
-webkit-animation:fade 12s infinite;

}
.slide2 {
  background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-2-image.png)no-repeat center;
      background-size: cover;
    animation:fade2 12s infinite;
-webkit-animation:fade2 12s infinite;
}
.slide3 {
    background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/splash-page-3-image.png)no-repeat center;
      background-size: cover;
    animation:fade3 12s infinite;
-webkit-animation:fade3 12s infinite;
}
.slide4 {
    background: url(https://thetaguk.com/site/wp-content/uploads/2017/11/spashpage-4-image-1.png)no-repeat center;
      background-size: cover;
    animation:fade3 12s infinite;
-webkit-animation:fade3 12s infinite;
}
@keyframes fade
{
  0%   {opacity:1}
  33.333% { opacity: 0}
  66.666% { opacity: 0}
  100% { opacity: 1}
}
@keyframes fade2
{
  0%   {opacity:0}
  33.333% { opacity: 1}
  66.666% { opacity: 0 }
  100% { opacity: 0}
}
@keyframes fade3
{
  0%   {opacity:0}
  33.333% { opacity: 0}
  66.666% { opacity: 1}
  100% { opacity: 0}
}
.btnContainer { margin-top: 20px; }

        .btn {
            display: inline-block;
            background: #3B242D;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
        }
.logo-img{
            width: 320px;
        }
.content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 100}

        @media only screen and (max-width: 503px) {
            .tag{ padding-left:30px; background-size:contain; }
            .tag span{ font-size: 21px; }
            .logo-img{
                width: 160px;
            }
            h1 {
    color: #fff;
    border-bottom: 1px solid;
    border-top: 1px solid;
    font-size: 18px;
}
        h2{color:#fff; font-size:14px;}
        .text{height:50%; width:80%; }
        }
        @media only screen and (max-width: 768px){
    .cycle-slideshow .item{
    background-position:center center;
}
.tag.img-1 {
    bottom: auto;
    right: 10%;
    top: 70px;
}
.logo-img {
    width: 100px;
}
}

See the PEN here

https://codepen.io/Chazlie/pen/MOmdEX


问:
What's the difference between Event Listeners & Handlers in Java?
In general terms of java, there are listeners & handlers for events.

I mean I use them unknowingly, just whichever is available in the API.

My question is, in what case do we use listeners and in what case do we use handlers for events?

What's the difference between them? Characteristics??

I've searched for reasons and I couldn't find a proper explanation for Java.

答:
A listener, listens for events which are data value objects which describe an event. When the event occurred and the order of events is often important. Pressing key '0' followed by '1' is different to '1' and '0'.

A handler, handles a complex object e.g. a new Socket connection.  The handler might process the object for any length of time.  The time of object creation and order is not so important. A connection from client0 or client1 can happen in any order.

ContentLicense: CC BY-SA 2.5


问:
react-native-maps: UrlTile and Polyline - zIndex/Overlaying not working
I am using react-native-maps. I use the <MapView.UrlTile/> and on top I am trying to visualize a <MapView.Polyline />. However, the Polyline is not visible. It lays under the passed URL Template. I can tell that, because when I zoom and pinch, I see the Polyline with the underlaying standard base map (on Android its google maps) for a brief time of rendering/loading the map.
With markers, this problem does not occur.

Any ideas how I get the Polyline on top of the URL Template?

答:
Apparently zIndex on PolyLine defaults to 0 while the Tiles zIndex defaults to -1 https://github.com/airbnb/react-native-maps/issues/1181.
However, that brings the PolyLine not into the foreground.

Setting the zIndex of the Tiles to negative while setting the zIndex of the Polyline to something positive solves the problem.


问:
Return Zip File from ZipOutputStream in Java
I have a function which creates a Zip file from a list of files. Is it possible to return the Zip file without it being saved on the disk? I need the file as I have to use the zip file as a parameter for another function. I am not sure of the ByteStream would be an option for me.

```<code>public File compressFileList(List<File> fileList,String fileName) {
    FileOutputStream fileOutputStream=null;
    ZipOutputStream zipOutputStream=null;
    FileInputStream fileInputStream=null;
    String compressedFileName=fileName +".zip";
    if(fileList.isEmpty())
        return null;
    try
    {
        fileOutputStream =  new FileOutputStream(compressedFileName);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        for (File file: fileList) {
            fileInputStream = new FileInputStream(file);
            ZipEntry zipEntry =  new ZipEntry(file.getName());
            zipOutputStream.putNextEntry(zipEntry);
            byte[] tmp = new byte[4*1024];
            int size = 0;
            while((size = fileInputStream.read(tmp)) != -1){
                zipOutputStream.write(tmp, 0, size);
            }
            zipOutputStream.flush();
            fileInputStream.close();
        }
        zipOutputStream.close();
        return compressedFile; //This is what I am missing

    }
    catch (FileNotFoundException e)
    {

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

EDIT : adding the use case

The idea is to create a zip file and use the CreateClassifierOptions method of VisualRecognition Service of Watson.

```<code>classifierOptions = new CreateClassifierOptions.Builder()
            .classifierName("Santa")
            .addClass("Santa", new File("C:\\app\\GitRepo\\images\\beagle.zip"))
            .negativeExamples(new File("C:\\app\\GitRepo\\images\\nosport.zip"))
            .build();
</code>```

The builder accepts the zip file as the parameter.

Understanding

Based on the explanation from Alexandre Dupriez, I think it is better to store the file at some place on the hard disk.

答:
```<code>public void compressFileList(List<File> fileList, OutputStream outputStream)
        throws IOException {
    try (ZipOutputStream zipOutputStream =
            new ZipOutputStream(new BufferedOutputStream(outputStream));
        for (File file: fileList) {
            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] tmp = new byte[4*1024];
                int size = 0;
                while((size = fileInputStream.read(tmp)) != -1){
                    zipOutputStream.write(tmp, 0, size);
                }
                zipOutputStream.flush();
            } catch (FileNotFoundException e) { // Maybe skip not found files.
                Logger.log(Level.INFO, "File not found {}", file.getPath());
            }
        }
    }
}
</code>```

Usage:

```<code>if (fileList.isEmpty()) {
    ...
    return;
}
try {
    compressFileList(fileList, servletRequest.getOutputStream())) {
} catch (FileNotFoundException e) {
   ...
} catch (IOException e) {
    ...
}
</code>```

Body:
I have a function which creates a Zip file from a list of files. Is it possible to return the Zip file without it being saved on the disk? I need the file as I have to use the zip file as a parameter for another function. I am not sure of the ByteStream would be an option for me.

public File compressFileList(List<File> fileList,String fileName) {
    FileOutputStream fileOutputStream=null;
    ZipOutputStream zipOutputStream=null;
    FileInputStream fileInputStream=null;
    String compressedFileName=fileName +".zip";
    if(fileList.isEmpty())
        return null;
    try
    {
        fileOutputStream =  new FileOutputStream(compressedFileName);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        for (File file: fileList) {
            fileInputStream = new FileInputStream(file);
            ZipEntry zipEntry =  new ZipEntry(file.getName());
            zipOutputStream.putNextEntry(zipEntry);
            byte[] tmp = new byte[4*1024];
            int size = 0;
            while((size = fileInputStream.read(tmp)) != -1){
                zipOutputStream.write(tmp, 0, size);
            }
            zipOutputStream.flush();
            fileInputStream.close();
        }
        zipOutputStream.close();
        return compressedFile; //This is what I am missing

    }
    catch (FileNotFoundException e)
    {

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

EDIT : adding the use case

The idea is to create a zip file and use the CreateClassifierOptions method of VisualRecognition Service of Watson.

classifierOptions = new CreateClassifierOptions.Builder()
            .classifierName("Santa")
            .addClass("Santa", new File("C:\\app\\GitRepo\\images\\beagle.zip"))
            .negativeExamples(new File("C:\\app\\GitRepo\\images\\nosport.zip"))
            .build();

The builder accepts the zip file as the parameter.

Understanding

Based on the explanation from Alexandre Dupriez, I think it is better to store the file at some place on the hard disk.

Body:
public void compressFileList(List<File> fileList, OutputStream outputStream)
        throws IOException {
    try (ZipOutputStream zipOutputStream =
            new ZipOutputStream(new BufferedOutputStream(outputStream));
        for (File file: fileList) {
            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] tmp = new byte[4*1024];
                int size = 0;
                while((size = fileInputStream.read(tmp)) != -1){
                    zipOutputStream.write(tmp, 0, size);
                }
                zipOutputStream.flush();
            } catch (FileNotFoundException e) { // Maybe skip not found files.
                Logger.log(Level.INFO, "File not found {}", file.getPath());
            }
        }
    }
}

Usage:

if (fileList.isEmpty()) {
    ...
    return;
}
try {
    compressFileList(fileList, servletRequest.getOutputStream())) {
} catch (FileNotFoundException e) {
   ...
} catch (IOException e) {
    ...
}


问:
Why std::begin uses trailing return type syntax?
The range-access function std::begin is declared as follows (for containers):

```<code>template< class C >
auto begin( C& c ) -> decltype(c.begin());
</code>```

I just wonder why it's not simply

```<code>template< class C >
decltype(C::begin) begin( C& c );
</code>```

Is there any difference between these two?

答:
The equivalent code would be

```<code>template< class C >
decltype(::std::declval<C &>().begin()) begin( C& c );
</code>```

which is longer and potentially more error-prone.

Body:
The range-access function std::begin is declared as follows (for containers):

template< class C >
auto begin( C& c ) -> decltype(c.begin());

I just wonder why it's not simply

template< class C >
decltype(C::begin) begin( C& c );

Is there any difference between these two?

Body:
The equivalent code would be

template< class C >
decltype(::std::declval<C &>().begin()) begin( C& c );

which is longer and potentially more error-prone.


问:
Best continuous integration setup for multi-platform development
What is the best continuous integration setup for a Devleopment department that codes in multiple environments?

At my company we write some code in C# and some in Java, I've previously used CC.Net but I've never done CInt with Java.

I'm aware of Continuum and was recently told about Hudson, but I've never used either.

Would it be better to use two CInt services one for each platform or to use a single one for both?

答: Why don't you try Team City from JetBrains? It is both for Java and C# and Professional version is free up to 20 user accounts and 3 build agents.</p>

OwnerDisplayName: Omar Kooheji

OwnerDisplayName: idursun

LastEditorDisplayName: idursun


问:
Reading info from existing pom.xml file using Gradle?
In Ant the Maven Ant Tasks can be used to read maven properties like this:

```<code><artifact:pom id="mypom" file="pom.xml" />
<echo>The version is ${mypom.version}</echo>
</code>```

Is there "native" support in Gradle for accessing pom elements from an existing physical pom.xml file or do I need to go through the above Ant approach in my .gradle file to make this work?

This page:

http://gradle.org/docs/current/userguide/maven_plugin.html

has info on generating pom files but thats not what I am looking for. I have tried to create a .gradle file that does the same:

```<code>    repositories {
      mavenCentral()
    }

    configurations {
        mavenAntTasks
    }

    dependencies {
        mavenAntTasks 'org.apache.maven:maven-ant-tasks:2.1.1'
    }

    task hello << {
      ant.taskdef(resource: 'org/apache/maven/artifact/ant/antlib.xml',
                  uri: 'antlib:org.apache.maven.artifact.ant',
                  classpath: configurations.mavenAntTasks.asPath)

     // what is the gradle syntax for this:
     // <artifact:pom id="mypom" file="maven-project/pom.xml" />
     // its not a property or a task...
     def artifact = groovy.xml.NamespaceBuilder.newInstance(ant,'antlib:org.apache.maven.artifact.ant')
     artifact.pom(id:'mypom', file: 'pom.xml')
     def text = properties['mypom.version']
     println "From pom file: " + text

    }
</code>```

where I have a simple pom.xml file located next to the build.gradle file. But I can't find any info in the gradle docs on the corresponding ant calls for this task. I have looked at:

http://www.gradle.org/docs/current/userguide/ant.html

for how to read ant properties and references but this:

```<code><artifact:pom id="mypom" file="maven-project/pom.xml" />
</code>```

seems to be neither a property or reference. I stumbled on this page:

http://snipplr.com/view/4082/

where a NamespaceBuilder is used:

```<code> def mvn = groovy.xml.NamespaceBuilder.newInstance(ant, 'antlib:org.apache.maven.artifact.ant')
</code>```

but when using this approach I get:

```<code>The AbstractTask.getDynamicObjectHelper() method has been deprecated and will be removed in the next version of Gradle. Please use the getAsDynamicObject() method instead.
From pom file: null
</code>```

after a bit of googling I found:

http://issues.gradle.org/browse/GRADLE-2385

which seems related, but the value of the property is still null.

答:
Please let me know the entry of the build.gradle file for the below pom.xml content:  </p>

```<code>            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <additionalClasspathElements>
                        <additionalClasspathElement>resources</additionalClasspathElement>
                    </additionalClasspathElements>
                    <forkCount>5</forkCount>
                    <reuseForks>true</reuseForks>
                    <includes>
                        <include>**/*IT.java</include>
                    </includes>
                    <runOrder>alphabetical</runOrder>
                    <argLine>-Duser.language=en</argLine>
                    <argLine>-Xmx512m</argLine>
                    <argLine>-XX:MaxPermSize=256m</argLine>
                    <argLine>-Dfile.encoding=UTF-8</argLine>
                    <systemPropertyVariables>
                        <!--<cucumber.options>--tags @example</cucumber.options>-->
                    </systemPropertyVariables>
                </configuration>
                <executions>
                    <execution>
                        <id>failsafe-integration-test</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.temyers</groupId>
                <artifactId>cucumber-jvm-parallel-plugin</artifactId>
                <version>4.2.0</version>
                <executions>
                    <execution>
                        <id>generateRunners</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>generateRunners</goal>
                        </goals>
                        <configuration>
                            <!-- Mandatory -->
                            <glue>com.cucumber.stepdefinitions</glue>
                            <strict>true</strict>
                            <monochrome>true</monochrome>
                             <!-- These are the default values -->
                            <outputDirectory>${project.build.directory}/generated-test-sources/cucumber</outputDirectory>
                            <featuresDirectory>src/test/resources/features/</featuresDirectory>
                            <cucumberOutputDir>target/cucumber-reports</cucumberOutputDir>
                            <format>json</format>
                             <tags>${TestType}</tags>
                            <tags>~@ignore</tags>
                            <customVmTemplate>
                                src/main/resources/cucumber-custom-runner.vm
                            </customVmTemplate>
                          <!--  <filterFeaturesByTags>true</filterFeaturesByTags>-->
                            <namingScheme>pattern</namingScheme>
                            <namingPattern>{f}_{c}IT</namingPattern>
                            <plugins>
                                <plugin>
                                    <name>com.cucumber.listener.ExtentCucumberFormatter</name>
                                    <extension>html</extension>
                                    <outputDirectory>output/</outputDirectory>

                                </plugin>
                            </plugins>
                            <parallelScheme>SCENARIO</parallelScheme>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

Body:
In Ant the Maven Ant Tasks can be used to read maven properties like this:

<artifact:pom id="mypom" file="pom.xml" />
<echo>The version is ${mypom.version}</echo>

Is there "native" support in Gradle for accessing pom elements from an existing physical pom.xml file or do I need to go through the above Ant approach in my .gradle file to make this work?

This page:

http://gradle.org/docs/current/userguide/maven_plugin.html

has info on generating pom files but thats not what I am looking for. I have tried to create a .gradle file that does the same:

    repositories {
      mavenCentral()
    }

    configurations {
        mavenAntTasks
    }

    dependencies {
        mavenAntTasks 'org.apache.maven:maven-ant-tasks:2.1.1'
    }

    task hello << {
      ant.taskdef(resource: 'org/apache/maven/artifact/ant/antlib.xml',
                  uri: 'antlib:org.apache.maven.artifact.ant',
                  classpath: configurations.mavenAntTasks.asPath)

     // what is the gradle syntax for this:
     // <artifact:pom id="mypom" file="maven-project/pom.xml" />
     // its not a property or a task...
     def artifact = groovy.xml.NamespaceBuilder.newInstance(ant,'antlib:org.apache.maven.artifact.ant')
     artifact.pom(id:'mypom', file: 'pom.xml')
     def text = properties['mypom.version']
     println "From pom file: " + text

    }

where I have a simple pom.xml file located next to the build.gradle file. But I can't find any info in the gradle docs on the corresponding ant calls for this task. I have looked at:

http://www.gradle.org/docs/current/userguide/ant.html

for how to read ant properties and references but this:

<artifact:pom id="mypom" file="maven-project/pom.xml" />

seems to be neither a property or reference. I stumbled on this page:

http://snipplr.com/view/4082/

where a NamespaceBuilder is used:

 def mvn = groovy.xml.NamespaceBuilder.newInstance(ant, 'antlib:org.apache.maven.artifact.ant')

but when using this approach I get:

The AbstractTask.getDynamicObjectHelper() method has been deprecated and will be removed in the next version of Gradle. Please use the getAsDynamicObject() method instead.
From pom file: null

after a bit of googling I found:

http://issues.gradle.org/browse/GRADLE-2385

which seems related, but the value of the property is still null.

Body:
Please let me know the entry of the build.gradle file for the below pom.xml content:

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <additionalClasspathElements>
                        <additionalClasspathElement>resources</additionalClasspathElement>
                    </additionalClasspathElements>
                    <forkCount>5</forkCount>
                    <reuseForks>true</reuseForks>
                    <includes>
                        <include>**/*IT.java</include>
                    </includes>
                    <runOrder>alphabetical</runOrder>
                    <argLine>-Duser.language=en</argLine>
                    <argLine>-Xmx512m</argLine>
                    <argLine>-XX:MaxPermSize=256m</argLine>
                    <argLine>-Dfile.encoding=UTF-8</argLine>
                    <systemPropertyVariables>
                        <!--<cucumber.options>&#45;&#45;tags @example</cucumber.options>-->
                    </systemPropertyVariables>
                </configuration>
                <executions>
                    <execution>
                        <id>failsafe-integration-test</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.temyers</groupId>
                <artifactId>cucumber-jvm-parallel-plugin</artifactId>
                <version>4.2.0</version>
                <executions>
                    <execution>
                        <id>generateRunners</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>generateRunners</goal>
                        </goals>
                        <configuration>
                            <!-- Mandatory -->
                            <glue>com.cucumber.stepdefinitions</glue>
                            <strict>true</strict>
                            <monochrome>true</monochrome>
                             <!-- These are the default values -->
                            <outputDirectory>${project.build.directory}/generated-test-sources/cucumber</outputDirectory>
                            <featuresDirectory>src/test/resources/features/</featuresDirectory>
                            <cucumberOutputDir>target/cucumber-reports</cucumberOutputDir>
                            <format>json</format>
                             <tags>${TestType}</tags>
                            <tags>~@ignore</tags>
                            <customVmTemplate>
                                src/main/resources/cucumber-custom-runner.vm
                            </customVmTemplate>
                          <!--  <filterFeaturesByTags>true</filterFeaturesByTags>-->
                            <namingScheme>pattern</namingScheme>
                            <namingPattern>{f}_{c}IT</namingPattern>
                            <plugins>
                                <plugin>
                                    <name>com.cucumber.listener.ExtentCucumberFormatter</name>
                                    <extension>html</extension>
                                    <outputDirectory>output/</outputDirectory>

                                </plugin>
                            </plugins>
                            <parallelScheme>SCENARIO</parallelScheme>
                        </configuration>
                    </execution>
                </executions>
            </plugin>


问:
AsyncTask <Map<String, List<Object>>
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

```<code>Map<String, List<Object>>
</code>```

I tried starting the asynctask like this:

```<code>public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>
</code>```

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

```<code>@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}
</code>```

and the on post execute like this:

```<code>@Override
public void onPostExecute(Map<String, List<Object>> map) {
}
</code>```

What is wrong with my syntax and how would I implement this correctly?

Thanks

答:
As I can see from documentation AsyncTask takes 3 generic parameters:

An asynchronous task is defined by 3 generic types, called Params, Progress and Result

You only provided "Params", so "Progress" and "Result" are Object by default.

Title: AsyncTask <Map<String, List<Object>>

Body:
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

Map<String, List<Object>>

I tried starting the asynctask like this:

public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}

and the on post execute like this:

@Override
public void onPostExecute(Map<String, List<Object>> map) {
}

What is wrong with my syntax and how would I implement this correctly?

Thanks


问:
How are subclasses of an interface get called
This is a question that has been bothering me for a while.

In frameworks like Jersey we have interface(s) that we can subclass to add some functionality to our program. for example to add request filtering in a RESt application we can implement ContainerRequestFilter then Voila we got authentication.

My question is how does the framework/library know that we have subclass one of its interfaces?

as per my understanding you can't instantiate an interface, only its subclass such as:

```<code>public interface Greeter{
    void sayHi();
}

public class SpanishGreeter implements Greeter{
    @override
    void sayHi(){
        System.out.println("Hola");
    }
}

public class Controller{
   public void main(String[] args){
       //We must know the name of subclass to instantiate?
       Greeter spanishG = new SpanishGreeter();
   }
}
</code>```

答:
What you're looking for is classpath scanning.

This isn't a trivial task, and it's pretty much what the name says: you basically need to scan the classpath and load every class you find (although the typical implementation will allow you to limit your search to certain packages and its subpackages only, to stop from things going really crazy).

There are no special tricks in the Java language that would make this task easy.

The good news is that you don't need to write it from scratch, as frameworks like Spring already have it built in, or if you want to have complete low-level control, you can use a dedicated library like Reflections.

Body:
This is a question that has been bothering me for a while.

In frameworks like Jersey we have interface(s) that we can subclass to add some functionality to our program. for example to add request filtering in a RESt application we can implement ContainerRequestFilter then Voila we got authentication.

My question is how does the framework/library know that we have subclass one of its interfaces?

as per my understanding you can't instantiate an interface, only its subclass such as:

public interface Greeter{
    void sayHi();
}

public class SpanishGreeter implements Greeter{
    @override
    void sayHi(){
        System.out.println("Hola");
    }
}

public class Controller{
   public void main(String[] args){
       //We must know the name of subclass to instantiate?
       Greeter spanishG = new SpanishGreeter();
   }
}


问:
How to configure Solr to do partial and prefix word matching
for example,search:cent point

should be match

cent point

centrepoint

centre points

no need match "point cent".

I try to use NGramFilterFactory in solr6.0,but it always get result that the match order is reversed.
like this:

```<code>  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.NGramFilterFactory" minGramSize="1" maxGramSize="25"/>
  </analyzer>
  <analyzer type="query">
  <tokenizer class="solr.WhitespaceTokenizerFactory"/>
  <filter class="solr.LowerCaseFilterFactory"/>
</code>```

I try to use PatternReplaceFilterFactory to replace space to  * .But it's didn't work ,only match it as an String.

答:
Since you only want to match prefixes, you can achieve what you want without using the NGramFilter:

```<code><analyzer>
  <tokenizer class="solr.KeywordTokenizerFactory"/>
  <filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</code>```

.. and then query using a wildcard:

```<code>field:cent*
</code>```

Since the KeywordTokenizer keeps the input as a single, large token, and you've lowercased it (the lowercase filter also works when doing wildcard searches), you avoid having to index a large number of tokens for each value (which is what the ngramfilter does) when you only care about the prefix of the value.

For your second requirement - the order - where an exact match is boosted higher, query a more plain field definition without the ngram filter - just a whitespace tokenizer and a lowercase filter. You can use the prefix query as your query for the returned documents, then use the other field as your boost query.

Depending on the rule to difference between #2 and #3, you might have to tweak the boost query to get the order you want.

Body:
for example,search:cent point

should be match

cent point

centrepoint

centre points

no need match "point cent".

I try to use NGramFilterFactory in solr6.0,but it always get result that the match order is reversed.
like this:

  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.NGramFilterFactory" minGramSize="1" maxGramSize="25"/>
  </analyzer>
  <analyzer type="query">
  <tokenizer class="solr.WhitespaceTokenizerFactory"/>
  <filter class="solr.LowerCaseFilterFactory"/>

I try to use PatternReplaceFilterFactory to replace space to  * .But it's didn't work ,only match it as an String.

Body:
Since you only want to match prefixes, you can achieve what you want without using the NGramFilter:

<analyzer>
  <tokenizer class="solr.KeywordTokenizerFactory"/>
  <filter class="solr.LowerCaseFilterFactory"/>
</analyzer>

.. and then query using a wildcard:

field:cent*

Since the KeywordTokenizer keeps the input as a single, large token, and you've lowercased it (the lowercase filter also works when doing wildcard searches), you avoid having to index a large number of tokens for each value (which is what the ngramfilter does) when you only care about the prefix of the value.

For your second requirement - the order - where an exact match is boosted higher, query a more plain field definition without the ngram filter - just a whitespace tokenizer and a lowercase filter. You can use the prefix query as your query for the returned documents, then use the other field as your boost query.

Depending on the rule to difference between #2 and #3, you might have to tweak the boost query to get the order you want.


问:
Getting fields on Pivot table through laravel
I have a Pivot table M:N relationship in Laravel 5.5.

Essentially my datastructure is;

```<code>Table_A
---------
id
name

Table_A_has_table_B <pivot>
---------
table_a_id
table_b_id
other_field

Table_B
---------
id
name
</code>```

In my Table_A Model I have

```<code>public function tableb()
{
    return $this->belongsToMany('App\Table_B', 'Table_A_has_table_B', 'table_a_id', 'table_b_id');
}
</code>```

And finally in my blade views I have this

```<code>        @foreach ($tablea->tableb as $tbl)
          <p><a href="#">{{ $tbl->name }}</a></p>
          <p>{{ $tbl->other_field}}</p>
        @endforeach
</code>```

All which seems to be working except the final line

{{ $tbl->other_field}}

How do I access the field on the pivot table and the data on tableb.
The pivot table contains information pertinent to the current view related to tableb.

Schema

```<code>    Schema::create('Table_A_has_table_B', function (Blueprint $table) {
        $table->integer('table_a_id')->unsigned()->index();
        $table->integer('table_b_id')->unsigned()->index();
        $table->integer('other_field')->unsigned();
        $table->primary(['table_a_id', 'competitor_id']);
        $table->foreign('table_a_id')->references('id')->on('table_a')->onDelete('cascade');
        $table->foreign('table_b_id')->references('id')->on('table_b')->onDelete('cascade');
    });
</code>```

答:
You have to add ->withPivot('column1', 'column2'); in your relationship like this (Documentation):

```<code>public function tableb()
{
    return $this->belongsToMany('App\Table_B', 'Table_A_has_table_B', 'table_a_id', 'table_b_id')->withPivot('other_field');
}
</code>```

Then use the pivot key word like this :

```<code>{{ $tbl->pivot->other_field}}
</code>```

Body:
I have a Pivot table M:N relationship in Laravel 5.5.

Essentially my datastructure is;

Table_A
---------
id
name

Table_A_has_table_B <pivot>
---------
table_a_id
table_b_id
other_field

Table_B
---------
id
name

In my Table_A Model I have

public function tableb()
{
    return $this->belongsToMany('App\Table_B', 'Table_A_has_table_B', 'table_a_id', 'table_b_id');
}

And finally in my blade views I have this

        @foreach ($tablea->tableb as $tbl)

{{ $tbl->name }}

{{ $tbl->other_field}}

        @endforeach

All which seems to be working except the final line

{{ $tbl->other_field}}

How do I access the field on the pivot table and the data on tableb.
The pivot table contains information pertinent to the current view related to tableb.

Schema

    Schema::create('Table_A_has_table_B', function (Blueprint $table) {
        $table->integer('table_a_id')->unsigned()->index();
        $table->integer('table_b_id')->unsigned()->index();
        $table->integer('other_field')->unsigned();
        $table->primary(['table_a_id', 'competitor_id']);
        $table->foreign('table_a_id')->references('id')->on('table_a')->onDelete('cascade');
        $table->foreign('table_b_id')->references('id')->on('table_b')->onDelete('cascade');
    });

Body:
You have to add ->withPivot('column1', 'column2'); in your relationship like this (Documentation):

public function tableb()
{
    return $this->belongsToMany('App\Table_B', 'Table_A_has_table_B', 'table_a_id', 'table_b_id')->withPivot('other_field');
}

Then use the pivot key word like this :

{{ $tbl->pivot->other_field}}


问:
Openshift: No nodes are available that match all of the following predicates:: Insufficient cpu (173), MatchNodeSelector (5)
I have a project in west-1 on Openshift v3. In it I have an app that worked fine and one that stopped working following a GitHub committing something very downstream within the code. The issue is with making a pod:

```<code>No nodes are available that match all of the following predicates::
 Insufficient cpu (173), MatchNodeSelector (5).
</code>```

I stopped it and then I scaled down the other pod to see if it was any weird settings that the new build for the other might have picked up and I get the same. Now both are broken.

Is it that Red Hat Openshift has run out of CPUs or have I got some weird default setting that has decided to request 173 CPUs and 5 Nodes?

答:
The message doesn't mean that the pod is requesting 173 CPUs.

The error message means that scheduling failed that on 173 machines there isn't enough CPU left available to fit the pod requests (see pod definition) and on 5 machines (nodes) it can't be scheduled because those nodes don't have the particular set of labels the pod is specifying in spec.nodeSelector of the pod definition. (There might be intersection between the 2 groups of nodes)

Body:
I have a project in west-1 on Openshift v3. In it I have an app that worked fine and one that stopped working following a GitHub committing something very downstream within the code. The issue is with making a pod:

No nodes are available that match all of the following predicates::
 Insufficient cpu (173), MatchNodeSelector (5).

I stopped it and then I scaled down the other pod to see if it was any weird settings that the new build for the other might have picked up and I get the same. Now both are broken.

Is it that Red Hat Openshift has run out of CPUs or have I got some weird default setting that has decided to request 173 CPUs and 5 Nodes?


问:
Exposing property to databinding in WPF
This is my scenario. I have internal class with a standard int property.

```<code>public class Session : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private ushort _Level;
    public ushort Level
    {
        get { return _Level; }
    }

    private void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    // a timer code here updates the _Level property every 60 seconds
    // and calls OnPropertyChange("Level");
}
</code>```

In my UI window, I have a label that binds to the Session instance and displays the Level value.

```<code> <TextBlock Name="LevelTextBlock" Text="{Binding SessionInstance.Level, StringFormat='0%'}" />
</code>```

And the window constructor has this code:

```<code> public MyWindow()
    {
        SessionInstance = new Session();

        this.InitializeComponent();
    }

    public Session SessionInstance { get; set; }
</code>```

However, as you can guess, when I update the value of _Level, the UI doesn't update the textblock. Adding DependancyProperty inside the Session class is unacceptable. I could do this on the window, but then I still need notifier that would check the value back to the Session instance.
I was wondering if there's elegant way of doing this. I can't think of anything, other than running another timer in the window that would check and refresh the textblock value.
Any thoughts?

答:
Implement INotifyPropertyChanged. There is even an tool which can do that automatically for all of your properties (or only ones marked by attribute, it is fairly configurable).

DependencyProperty is overkill if you don't need any of its other features (value inheritance, binding FROM the property etc.), it is best used for control properties, not model properties.

EDIT:

Correctly implemented it looks like this:

```<code>private string familyName;
public string FamilyName
{
    get { return familyName; }
    set
    {
        if (value != familyName)
        {
            familyName = value;
            OnPropertyChanged("FamilyName");
        }
    }
}
</code>```

Title: Exposing property to databinding in WPF

Body:
This is my scenario. I have internal class with a standard int property.

public class Session : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private ushort _Level;
    public ushort Level
    {
        get { return _Level; }
    }

    private void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    // a timer code here updates the _Level property every 60 seconds
    // and calls OnPropertyChange("Level");
}

In my UI window, I have a label that binds to the Session instance and displays the Level value.

 <TextBlock Name="LevelTextBlock" Text="{Binding SessionInstance.Level, StringFormat='0%'}" />

And the window constructor has this code:

 public MyWindow()
    {
        SessionInstance = new Session();

        this.InitializeComponent();
    }

    public Session SessionInstance { get; set; }

However, as you can guess, when I update the value of _Level, the UI doesn't update the textblock. Adding DependancyProperty inside the Session class is unacceptable. I could do this on the window, but then I still need notifier that would check the value back to the Session instance.
I was wondering if there's elegant way of doing this. I can't think of anything, other than running another timer in the window that would check and refresh the textblock value.
Any thoughts?

Body:
Implement INotifyPropertyChanged. There is even an tool which can do that automatically for all of your properties (or only ones marked by attribute, it is fairly configurable).

DependencyProperty is overkill if you don't need any of its other features (value inheritance, binding FROM the property etc.), it is best used for control properties, not model properties.

EDIT:

Correctly implemented it looks like this:

private string familyName;
public string FamilyName
{
    get { return familyName; }
    set
    {
        if (value != familyName)
        {
            familyName = value;
            OnPropertyChanged("FamilyName");
        }
    }
}


问:
Cassandra ODBC Datastax working with Cassandra 2.1 but not 3.0 in Windows
I have tried connecting to a remote Cassandra from Windows 10 using the latest Simba-Datastax ODBC Driver (trial version). I was successful with Cassandra 2.1 (I connected to a Cassandra docker actually) but failed with Cassandra 3.0.15 and 3.11. I have installed the driver and I am able to see it in the Windows Data sources tool (64 bits), under the System DSN tab.

When I specify the host, port and keyspace of my Cassandra 3.0 docker (exactly the same values that work allright for me with the Cassandra 2.1 docker) and press the "Test..." button to launch the connectivity test, I am getting a strange error that "not even procol version 1 is available".

According to this web site, Simba says the driver is compatible with Cassandra 3.X. Could you think of any reason why this fails but 2.1 is successful? :-(

PS: I see other people complaining here but with a different error message (No hosts available for the control connection)

答:
I fixed it! I think I was using a wrong version of the driver - I was using Datastax driver which apparently does not work for Cassandra 3.X. I have now downloaded the latest version of the ODBC driver from the Simba website (30-day trial version) and it is working :-)

The confusion came from the fact that I thought the Datastax driver and the Simba driver were the same as I read somewhere that "Simba and Datastax have partnered to develop a driver...".

Thank you very much Aaron anyway.


问:
Exception while referencing a .Net standard 2.0 project from WPF application
I am getting the following exception while referencing a .Net standard 2.0 project from WPF application developed using .Net framework 4.6.1 project

Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.'

Any suggestions?

答: Add reference to Microsoft.EntityFrameworkCore package in your WPF project.


问:
Is it beneficial to use ForkJoinPool as usual ExecutorService
Let's say I have a code like that:

```<code>class Foo {
    private final ExecutorService executor;

    public Foo(ExecutorService executor) {
        this.executor = executor;
    }

    public void doSomething() {
        executor.execute(() -> {/* Do important task */});
    }
}
</code>```

Can I gain better performance if instead of passing ThreadPoolExecutor in constructor I use ForkJoinPool. If yes then why and should I prefer use it in any circumstances instead of ThreadPoolExecutor.

Update 1

My question is about usage of ForkJoinPool through ExecutorService API and doesn't suppose recursive task splitting using ForkJoinPool specific API.

答:
It will be effective if you use newWorkStealingPool

```<code>public static ExecutorService newWorkStealingPool()
</code>```

Creates a work-stealing thread pool using all available processors as its target parallelism level.

You can find advantage from this documentation page:

A ForkJoinPool provides the entry point for submissions from non-ForkJoinTask clients, as well as management and monitoring operations.

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute tasks submitted to the pool and/or created by other active tasks (eventually blocking waiting for work if none exist).

This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks), as well as when many small tasks are submitted to the pool from external clients. Especially when setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.

Body:
Let's say I have a code like that:

class Foo {
    private final ExecutorService executor;

    public Foo(ExecutorService executor) {
        this.executor = executor;
    }

    public void doSomething() {
        executor.execute(() -> {/* Do important task */});
    }
}

Can I gain better performance if instead of passing ThreadPoolExecutor in constructor I use ForkJoinPool. If yes then why and should I prefer use it in any circumstances instead of ThreadPoolExecutor.

Update 1

My question is about usage of ForkJoinPool through ExecutorService API and doesn't suppose recursive task splitting using ForkJoinPool specific API.

Body:
It will be effective if you use newWorkStealingPool

public static ExecutorService newWorkStealingPool()

Creates a work-stealing thread pool using all available processors as its target parallelism level.

You can find advantage from this documentation page:

A ForkJoinPool provides the entry point for submissions from non-ForkJoinTask clients, as well as management and monitoring operations.

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute tasks submitted to the pool and/or created by other active tasks (eventually blocking waiting for work if none exist).

This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks), as well as when many small tasks are submitted to the pool from external clients. Especially when setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.


问:
Getting 404 error while call oAuth2 api in the browser
I used ruby on rails to make RESTful api and also used doorkeeper to handle authentication and authorization. As you know the doorkeeper generate some OAuth2 api's and the two of the them that i need to use is /users which is the post request and /oauth/token that make token for me. The api that i make which are post, get, put works greate in postman and android studio and web browser.
But the post api /users and /oauth/token which generated by the doorkeeper doesn't work in web browser but works great on android studio and postman.
That was confused for me. The error that i take while calling this api is 404, I checked the ruby production log on the server and it says no route match. The string thing here is that the type of method and routes is correct.

This is the code that i used in the reactjs. i used axios:

```<code>var url="http://x.x.x.x/oauth/token";
    axios.post(url,{
        "username":"1",
        "password":"password",
        "grant_type":"password"
      },{headers:{"Content-Type":"application/json"}}).then( (response) => {
          console.log(response.data);
        })
        .catch( (error) => {
          console.log(JSON.stringify(error));
        });
</code>```

And also used raw jQuery to make request and get the same error. all my api works well execpt this two api:

```<code>var firstname = document.forms["registerForm"]["first_name"].value;
    var lastname = document.forms["registerForm"]["last_name"].value;
    var pass = document.forms["registerForm"]["password"].value;
    var passconfirm = document.forms["registerForm"]["password_confirmation"].value;

    var json_data = {
        "async": true,
        "crossDomain": true,
        "url": send,
        "method": "POST",
        "headers": {
            "content-type": "application/json",
        },
        "processData": false,
        "data":
        {
            "user": {
                "user_name": username,
                "password": pass,
                "password_confirmation": passconfirm,
                "user_type": "admin"
            },
            "profile": {
                "first_name": firstname,
                "last_name": lastname
            }
        }
    }

    $.ajax(json_data).done(function (response) {
        console.log(response);
    });
    console.log(json_data['data']);
    console.log(username);
</code>```

the output of this code console.log(JSON.stringify(error)); is this:

```<code>{"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"},"method":"post","url":"http://x.x.x.x/oauth/token.json","data":"{\"username\":\"1\",\"password\":\"password\",\"grant_type\":\"password\"}"},"request":{}}
</code>```

I find the request header and response header into the browser:

```<code>Response Header:

Content-Type
application/json; charset=UTF-8
Content-Length
34
Connection
keep-alive
Status
404 Not Found
X-Request-Id
d593b73f-eec8-41cd-95cd-e4459663358c
X-Runtime
0.002108
Date
Mon, 13 Nov 2017 11:19:26 GMT
X-Powered-By
Phusion Passenger 5.1.11
Server
nginx/1.12.1 + Phusion Passenger 5.1.11

Request headers (427 B)
Host
x.x.x.x
User-Agent
Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/56.0
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Language
en-US,en;q=0.5
Accept-Encoding
gzip, deflate
Access-Control-Request-Method
POST
Access-Control-Request-Headers
Origin
http://localhost:3000
Connection
keep-alive
</code>```

答:
After checking their docs, it looks like you need to change Content-Type header to application/x-www-form-urlencoded and data as key=value pair:

const data = 'username=1&password=password&grant_type=password'

or simply:

```<code>const formData = {
  username: '1',
  password: 'password',
  grant_type: 'password',
}

const data = Object.keys(formData)
  .map(prop => `${prop}=${formData[prop]}`)
  .join('&')
</code>```

Final result would be:

```<code>var url="http://x.x.x.x/oauth/token";

axios.post(url, data, {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }
}).then( (response) => {
  console.log(response.data);
})
.catch( (error) => {
  console.log(JSON.stringify(error));
});
</code>```

Body:
I used ruby on rails to make RESTful api and also used doorkeeper to handle authentication and authorization. As you know the doorkeeper generate some OAuth2 api's and the two of the them that i need to use is /users which is the post request and /oauth/token that make token for me. The api that i make which are post, get, put works greate in postman and android studio and web browser.
But the post api /users and /oauth/token which generated by the doorkeeper doesn't work in web browser but works great on android studio and postman.
That was confused for me. The error that i take while calling this api is 404, I checked the ruby production log on the server and it says no route match. The string thing here is that the type of method and routes is correct.

This is the code that i used in the reactjs. i used axios:

var url="http://x.x.x.x/oauth/token";
    axios.post(url,{
        "username":"1",
        "password":"password",
        "grant_type":"password"
      },{headers:{"Content-Type":"application/json"}}).then( (response) => {
          console.log(response.data);
        })
        .catch( (error) => {
          console.log(JSON.stringify(error));
        });

And also used raw jQuery to make request and get the same error. all my api works well execpt this two api:

var firstname = document.forms["registerForm"]["first_name"].value;
    var lastname = document.forms["registerForm"]["last_name"].value;
    var pass = document.forms["registerForm"]["password"].value;
    var passconfirm = document.forms["registerForm"]["password_confirmation"].value;

    var json_data = {
        "async": true,
        "crossDomain": true,
        "url": send,
        "method": "POST",
        "headers": {
            "content-type": "application/json",
        },
        "processData": false,
        "data":
        {
            "user": {
                "user_name": username,
                "password": pass,
                "password_confirmation": passconfirm,
                "user_type": "admin"
            },
            "profile": {
                "first_name": firstname,
                "last_name": lastname
            }
        }
    }

    $.ajax(json_data).done(function (response) {
        console.log(response);
    });
    console.log(json_data['data']);
    console.log(username);

the output of this code console.log(JSON.stringify(error)); is this:

{"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"},"method":"post","url":"http://x.x.x.x/oauth/token.json","data":"{\"username\":\"1\",\"password\":\"password\",\"grant_type\":\"password\"}"},"request":{}}

I find the request header and response header into the browser:

Response Header:

Content-Type
application/json; charset=UTF-8
Content-Length
34
Connection
keep-alive
Status
404 Not Found
X-Request-Id
d593b73f-eec8-41cd-95cd-e4459663358c
X-Runtime
0.002108
Date
Mon, 13 Nov 2017 11:19:26 GMT
X-Powered-By
Phusion Passenger 5.1.11
Server
nginx/1.12.1 + Phusion Passenger 5.1.11

Request headers (427 B)
Host
x.x.x.x
User-Agent
Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/56.0
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Language
en-US,en;q=0.5
Accept-Encoding
gzip, deflate
Access-Control-Request-Method
POST
Access-Control-Request-Headers
Origin
http://localhost:3000
Connection
keep-alive

Body:
After checking their docs, it looks like you need to change Content-Type header to application/x-www-form-urlencoded and data as key=value pair:

const data = 'username=1&password=password&grant_type=password'

or simply:

const formData = {
  username: '1',
  password: 'password',
  grant_type: 'password',
}

const data = Object.keys(formData)
  .map(prop => `${prop}=${formData[prop]}`)
  .join('&')

Final result would be:

var url="http://x.x.x.x/oauth/token";

axios.post(url, data, {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }
}).then( (response) => {
  console.log(response.data);
})
.catch( (error) => {
  console.log(JSON.stringify(error));
});


答:
Just use the Object Class to qualify AsyncTask Params, Progress, Result

```<code> public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map ,Void,Map>{
    @Override
    protected Map doInBackground(Map... params) {
        return null;
    }

    @Override
    protected void onPostExecute(Map map) {
        super.onPostExecute(map);
    }
}
</code>```

Title: AsyncTask <Map<String, List<Object>>

Body:
Just use the Object Class to qualify AsyncTask Params, Progress, Result

 public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map ,Void,Map>{
    @Override
    protected Map doInBackground(Map... params) {
        return null;
    }

    @Override
    protected void onPostExecute(Map map) {
        super.onPostExecute(map);
    }
}


问:
Check for new mails in Hotmail using OpenPop.NET
I was advised to use OpenPop lib to fetch my mail from hotmail. But I could'nt find any better way to check for new mail except disconnecting and reconnecting again. And there, I found a problem, Hotmail doesn't allow more than 1 pop3 login each 15 minutes. I want to know if it's possible to get the new mail without disconnecting and reconnecting to their pop3 server. Here is my code:</p>

```<code>        Timer checker = new Timer();
        checker.Interval = 1000;
        checker.Tick += new EventHandler(delegate
        {
            Pop3Client client = new Pop3Client();
            client.Connect("pop3.live.com", 995, true);
            client.Authenticate("my.Email@hotmail.com", "myPassword");
            label1.Text = client.GetMessageCount().ToString();
            client.Disconnect();

        });
        checker.Start();
</code>```

答:
I do not think that servers are allowed to show new mails to you during a POP3 session. I base this upon that it can certainly not delete emails as it would destroy the message numbers.

What would for example happen if the server says you have 100 messages, and when you fetch the message with number 55, it is actually not there since it was deleted in the meantime. I think the same applies to adding new emails during the session. Also, only one client can be logged into a POP3 account at a time, since the account will then be in a locked state. In that locked state, I do not think servers are allowed to change anything during the session.

I do not recall any methods in the POP3 specification which allows you to ask the server if new messages have been delivered.

If Hotmail does indeed only allow one POP3 login per 15 minutes, then I think you are left with just that. I do not know if there are other protocols which could be used here. IMAP is not supported, so that is not an option.

This is not the answer you want - but it is what I can give you.

Body:
I was advised to use OpenPop lib to fetch my mail from hotmail. But I could'nt find any better way to check for new mail except disconnecting and reconnecting again. And there, I found a problem, Hotmail doesn't allow more than 1 pop3 login each 15 minutes. I want to know if it's possible to get the new mail without disconnecting and reconnecting to their pop3 server. Here is my code:

        Timer checker = new Timer();
        checker.Interval = 1000;
        checker.Tick += new EventHandler(delegate
        {
            Pop3Client client = new Pop3Client();
            client.Connect("pop3.live.com", 995, true);
            client.Authenticate("my.Email@hotmail.com", "myPassword");
            label1.Text = client.GetMessageCount().ToString();
            client.Disconnect();

        });
        checker.Start();


问:
Replacing values of dataframe with NA values of another dataframe
I would like to replace values of one dataframe with NA of another dataframe that have the same identifier. That is, for all values of df1 that have the same id, assign the "NA" values of df2 at the corresponding id and indices.

I have df1 and df2:

```<code>df1 =data.frame(id = c(1,1,2,2,6,6),a = c(2,4,1,7,5,3), b = c(5,3,0,3,2,5),c = c(9,3,10,33,2,5))
df2 =data.frame(id = c(1,2,6),a = c("NA",0,"NA"), b= c("NA", 9, 9),c=c(0,"NA","NA"))
</code>```

what i would like is df3:

```<code>df3 = data.frame(id = c(1,1,2,2,6,6),a = c("NA","NA",1,7,"NA","NA"), b = c("NA","NA",0,3,2,5),c = c(9,3,"NA","NA","NA","NA"))
</code>```

I have tried the lookup function and the library "data.table", but i could get the correct df3. Could anyone please help me with this?

答:
We can do a join on 'id' and then replace the NA values by multiplying the .

```<code>library(data.table)
nm1 <- names(df1)[-1]
setDT(df1)[df2,  (nm1) := Map(function(x, y) x*(NA^is.na(y)), .SD,
                  mget(paste0('i.', nm1))), on = .(id), .SDcols = nm1]
df1
#   id  a  b  c
#1:  1 NA NA  9
#2:  1 NA NA  3
#3:  2  1  0 NA
#4:  2  7  3 NA
#5:  6 NA  2 NA
#6:  6 NA  5 NA
</code>```

data

```<code>df2 =data.frame(id = c(1,2,6),a = c(NA,0,NA), b= c(NA, 9, 9),c=c(0,NA,NA))
</code>```

NOTE: In the OP's post NA were "NA"

Body:
I would like to replace values of one dataframe with NA of another dataframe that have the same identifier. That is, for all values of df1 that have the same id, assign the "NA" values of df2 at the corresponding id and indices.

I have df1 and df2:

df1 =data.frame(id = c(1,1,2,2,6,6),a = c(2,4,1,7,5,3), b = c(5,3,0,3,2,5),c = c(9,3,10,33,2,5))
df2 =data.frame(id = c(1,2,6),a = c("NA",0,"NA"), b= c("NA", 9, 9),c=c(0,"NA","NA"))

what i would like is df3:

df3 = data.frame(id = c(1,1,2,2,6,6),a = c("NA","NA",1,7,"NA","NA"), b = c("NA","NA",0,3,2,5),c = c(9,3,"NA","NA","NA","NA"))

I have tried the lookup function and the library "data.table", but i could get the correct df3. Could anyone please help me with this?

Body:
We can do a join on 'id' and then replace the NA values by multiplying the .

library(data.table)
nm1 <- names(df1)[-1]
setDT(df1)[df2,  (nm1) := Map(function(x, y) x*(NA^is.na(y)), .SD,
                  mget(paste0('i.', nm1))), on = .(id), .SDcols = nm1]
df1
#   id  a  b  c
#1:  1 NA NA  9
#2:  1 NA NA  3
#3:  2  1  0 NA
#4:  2  7  3 NA
#5:  6 NA  2 NA
#6:  6 NA  5 NA

data

df2 =data.frame(id = c(1,2,6),a = c(NA,0,NA), b= c(NA, 9, 9),c=c(0,NA,NA))

NOTE: In the OP's post NA were "NA"


问:
Generate Json schema from XML schema (XSD)
Does anybody know how to generate a JSON schema from a existing XML schema (XSD file)?
Are there any tools available for this?</p>

答: Copy your XML schema here & get the JSON schema code to the online tools which are available to generate JSON schema from XML schema.</p>


问:
How to convert java string to Code page 857
I have a requirement to convert java string to Code Page 857 . I am sending this string to another system which reads the string byte by byte. If this string contains any some Turkish character it will consume 2 bytes. So the client (external system owner) want us to convert (set the standard) the string to code page 857 (standard used to write Turkish chars under DOS operating system)

Please let me know if any one can help me on this
Thanks in advance
Shaji

答:
Internally, Java represents all Strings as UTF-16. Therefore, a String object itself cannot be converted to a  specific code page.

However, you can get a byte array which encodes the String using a specific character set:

```<code>String.getBytes(Charset charset)
</code>```

In your case, you should use:

```<code>byte[] stringAsByteArray=myString.getBytes(Charset.forName("Cp857"));
</code>```

According to here, Cp857 should be supported by Java, but you should check this with

```<code>Charset.isSupported("Cp857");
</code>```

Body:
Internally, Java represents all Strings as UTF-16. Therefore, a String object itself cannot be converted to a  specific code page.

However, you can get a byte array which encodes the String using a specific character set:

String.getBytes(Charset charset)

In your case, you should use:

byte[] stringAsByteArray=myString.getBytes(Charset.forName("Cp857"));

According to here, Cp857 should be supported by Java, but you should check this with

Charset.isSupported("Cp857");


问:
How to make border radius closer to the center
I want to make a shadow around a rounded image, to do so I used a border-radius: 100px and a box-shadow: 0 0 5px 5px #888; to it, but I want to make it deeper to reach the circle and remove that white part.

Here is a screenshot of what it looks like.

.bubbles {
  border-radius: 100px;
  box-shadow: 0 0 5px 5px #888;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="bubbles" src="https://img4.hostingpics.net/thumbs/mini_771288logomesure.png" alt="Heberger image" /></code>```

JSFiddle here

答:
You want to remove the "white part", is this part the white border around the image?

The border is due to the white background of the image you're using. I suggest you directly edit it (using Gimp or Inkscape) to get rid of it. See How to make a color transparent using Gimp to get an explanation.

Hope it will help !

Body:
I want to make a shadow around a rounded image, to do so I used a border-radius: 100px and a box-shadow: 0 0 5px 5px #888; to it, but I want to make it deeper to reach the circle and remove that white part.

Here is a screenshot of what it looks like.

.bubbles {
  border-radius: 100px;
  box-shadow: 0 0 5px 5px #888;
}

JSFiddle here