问:
Filling a shape with color in python turtle
I'm trying to fill a shape with a color but when I run it, it does not show.
Am I not supposed to use classes for this? I am not proficient with python-3 and still learning how to use classes</p>

```<code>import turtle

t=turtle.Turtle()
t.speed(0)

class Star(turtle.Turtle):
    def __init__(self, x=0, y=0):
        turtle.Turtle.__init__(self)
        self.shape("")
        self.color("")
#Creates the star shape
    def shape(self, x=0, y=0):
        self.fillcolor("red")
        for i in range(9):
        self.begin_fill()
        self.left(90)
        self.forward(90)
        self.right(130)
        self.forward(90)
        self.end_fill()
#I was hoping this would fill the inside
    def octagon(self, x=0.0, y=0.0):
        turtle.Turtle.__init__(self)

    def octa(self):
        self.fillcolor("green")
        self.begin_fill()
        self.left(25)
        for x in range(9):
            self.forward(77)
            self.right(40)

#doesn't run with out this
a=Star()
</code>```

答:
Issues with your program: you create and set the speed of a turtle that you don't actually use; turtle.py already has a shape() method so don't override it to mean something else, pick a new name; you don't want the begin_fill() and end_fill() inside the loop but rather surrounding the loop; you call your own shape() method with invalid arguments.

The following rework of your code addresses the above issues:

```<code>from turtle import Turtle, Screen

class Star(Turtle):
    def __init__(self, x=0, y=0):
        super().__init__(visible=False)
        self.speed('fastest')
        self.draw_star(x, y)

    def draw_star(self, x=0, y=0):
        """ Creates the star shape """

        self.penup()
        self.setposition(x, y)
        self.pendown()

        self.fillcolor("red")

        self.begin_fill()

        for _ in range(9):
            self.left(90)
            self.forward(90)
            self.right(130)
            self.forward(90)

        self.end_fill()

t = Star()

screen = Screen()
screen.exitonclick()
</code>```

Body:
I'm trying to fill a shape with a color but when I run it, it does not show.
Am I not supposed to use classes for this? I am not proficient with python-3 and still learning how to use classes

import turtle

t=turtle.Turtle()
t.speed(0)

class Star(turtle.Turtle):
    def __init__(self, x=0, y=0):
        turtle.Turtle.__init__(self)
        self.shape("")
        self.color("")
#Creates the star shape
    def shape(self, x=0, y=0):
        self.fillcolor("red")
        for i in range(9):
        self.begin_fill()
        self.left(90)
        self.forward(90)
        self.right(130)
        self.forward(90)
        self.end_fill()
#I was hoping this would fill the inside
    def octagon(self, x=0.0, y=0.0):
        turtle.Turtle.__init__(self)

    def octa(self):
        self.fillcolor("green")
        self.begin_fill()
        self.left(25)
        for x in range(9):
            self.forward(77)
            self.right(40)

#doesn't run with out this
a=Star()

Body:
Issues with your program: you create and set the speed of a turtle that you don't actually use; turtle.py already has a shape() method so don't override it to mean something else, pick a new name; you don't want the begin_fill() and end_fill() inside the loop but rather surrounding the loop; you call your own shape() method with invalid arguments.

The following rework of your code addresses the above issues:

from turtle import Turtle, Screen

class Star(Turtle):
    def __init__(self, x=0, y=0):
        super().__init__(visible=False)
        self.speed('fastest')
        self.draw_star(x, y)

    def draw_star(self, x=0, y=0):
        """ Creates the star shape """

        self.penup()
        self.setposition(x, y)
        self.pendown()

        self.fillcolor("red")

        self.begin_fill()

        for _ in range(9):
            self.left(90)
            self.forward(90)
            self.right(130)
            self.forward(90)

        self.end_fill()

t = Star()

screen = Screen()
screen.exitonclick()


来源: stackexchange

问:
ImageIO : gif to jpeg problem -> the image becomes pink
I'm trying to convert a gif to a jpeg using imageIO but the resulting image is pink... Anyone can help?</p>

```<code>public byte[] convert(byte[] bytes)
throws Exception {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    BufferedImage bufferedImage = ImageIO.read(inputStream);
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    ImageOutputStream outputStream = ImageIO.createImageOutputStream(osByteArray);
    ImageIO.write(bufferedImage, "jpg", outputStream);
    outputStream.flush();
    outputStream.close();
    return osByteArray.toByteArray();
}
</code>```

答:
Perhaps, pink is defined as the transparency color for the gif image. If so, the following example might work. Basically, a new image is created and the "backgound color" is explicitly set to whatever is passed in.

```<code>public static byte[] convert(byte[] bytes, Color backgroundColor) throws Exception
{
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    BufferedImage bufferedImage = ImageIO.read(inputStream);
    BufferedImage newBi = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) newBi.getGraphics();
    g2d.drawImage(bufferedImage, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), backgroundColor, null);
    bufferedImage.getHeight(), null);
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    ImageOutputStream outputStream = ImageIO.createImageOutputStream(osByteArray);
    ImageIO.write(newBi, "jpg", outputStream);
    outputStream.flush();
    outputStream.close();
    return osByteArray.toByteArray();
}
</code>```

Looks like this might be related.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to convert a gif to a jpeg using imageIO but the resulting image is pink... Anyone can help?

public byte[] convert(byte[] bytes)
throws Exception {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    BufferedImage bufferedImage = ImageIO.read(inputStream);
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    ImageOutputStream outputStream = ImageIO.createImageOutputStream(osByteArray);
    ImageIO.write(bufferedImage, "jpg", outputStream);
    outputStream.flush();
    outputStream.close();
    return osByteArray.toByteArray();
}

Body:
Perhaps, pink is defined as the transparency color for the gif image. If so, the following example might work. Basically, a new image is created and the "backgound color" is explicitly set to whatever is passed in.

public static byte[] convert(byte[] bytes, Color backgroundColor) throws Exception
{
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    BufferedImage bufferedImage = ImageIO.read(inputStream);
    BufferedImage newBi = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) newBi.getGraphics();
    g2d.drawImage(bufferedImage, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), backgroundColor, null);
    bufferedImage.getHeight(), null);
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    ImageOutputStream outputStream = ImageIO.createImageOutputStream(osByteArray);
    ImageIO.write(newBi, "jpg", outputStream);
    outputStream.flush();
    outputStream.close();
    return osByteArray.toByteArray();
}

Looks like this might be related.


问:
Slick carrousel select option
Hi i want to link a carrousel to a input value option how can i do that ?

here is my carrousel :

```<code>$('.slider-for').slick({
 slidesToShow: 1,
 slidesToScroll: 1,
 arrows: false,
 fade: true,
 asNavFor: '.slider-nav'
});

$('.slider-nav').slick({
slidesToShow: 3,
slidesToScroll: 1,
asNavFor: '.slider-for',
dots: true,
centerMode: true,
focusOnSelect: true
});
</code>```

and my input value :

```<code><input id="test" name="test" value="changevalue">
</code>```

the slider-for will contain image i want to link with the input value

so i want my value to be change and synchronize with the "slide-for"

答:
You have to use afterChange event, it will fire after any slide change, and then you can use currentSlide parameter to get the active slide (img) and then update your input value, here is a working example:

$(document).ready(function(){

  $('.slider-for').slick({
     slidesToShow: 1,
     slidesToScroll: 1,
  });

  var $input = $('#test');

  $('.slider-for').on('afterChange', function(event, slick, currentSlide) {
    // get the active slide
    var $activeImg = $("[data-slick-index='" +  currentSlide + "']").children('img');
    // update input value
    $input.val( $activeImg.attr('src') );
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slider-for{
  margin: 50px;
}

#test {
  width: 300px;
}

body {
  background: #3498db;
}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick.css"/>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick-theme.css"/>

<input id="test" name="test" value="">```

ContentLicense: CC BY-SA 3.0

Title: Slick carrousel select option

Body:
Hi i want to link a carrousel to a input value option how can i do that ?

here is my carrousel :

$('.slider-for').slick({
 slidesToShow: 1,
 slidesToScroll: 1,
 arrows: false,
 fade: true,
 asNavFor: '.slider-nav'
});

$('.slider-nav').slick({
slidesToShow: 3,
slidesToScroll: 1,
asNavFor: '.slider-for',
dots: true,
centerMode: true,
focusOnSelect: true
});

and my input value :

<input id="test" name="test" value="changevalue">

the slider-for will contain image i want to link with the input value

so i want my value to be change and synchronize with the "slide-for"

Body:
You have to use afterChange event, it will fire after any slide change, and then you can use currentSlide parameter to get the active slide (img) and then update your input value, here is a working example:

$(document).ready(function(){

  $('.slider-for').slick({
     slidesToShow: 1,
     slidesToScroll: 1,
  });

  var $input = $('#test');

  $('.slider-for').on('afterChange', function(event, slick, currentSlide) {
    // get the active slide
    var $activeImg = $("[data-slick-index='" +  currentSlide + "']").children('img');
    // update input value
    $input.val( $activeImg.attr('src') );
  });

});

.slider-for{
  margin: 50px;
}

#test {
  width: 300px;
}

body {
  background: #3498db;
}

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick.css"/>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick-theme.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick.min.js"></script>

<div class="slider-for">
  <div><img alt="" src="http://via.placeholder.com/350x100"></div>
  <div><img alt="" src="http://via.placeholder.com/400x100"></div>
  <div><img alt="" src="http://via.placeholder.com/450x100"></div>
</div>

<input id="test" name="test" value="">


问:
How to change output format of material 2 date-picker
I am using angular material 2 Date-Picker component

The only string input it understands is in ISO date format

Ex. "2017-11-13T10:39:28.300Z"

But i want to patch my form control with locale date value

Ex. "11/13/2017, 4:09:46 PM"

So that it output the later format and even expects this format.

How can i do this? Is there a way to not use ISO but custom formats?

Some Thoughts:

Should i write customDateAdaptor?

Update:

https://stackblitz.com/edit/angular-material-moment-adapter-example-bqvm2f

i have tried to implement custom dateAdaptor by extending nativeDateAdaptor

答: you can call Emitter of this module (for example click event) and change model binded to this module to secondary model.</p>


问:
reagent/adapt-react-class fails with :optimizations :advanced
I'm importing a react component (using the :npm-deps support) and wrapping with the adapt-react-class adapter:

```<code>(:require [reagent.core :as reagent]
          [react-helmet])

(def meta-tags* (reagent/adapt-react-class (aget react-helmet "default")))

(defn main-panel []
  (let []
    (fn []
      [meta-tags*])))
</code>```

This works fine for development, but when advanced compiler is on:

Uncaught TypeError: Cannot call a class as a function

Minimimal repo:
https://github.com/fbielejec/npm-deps-demo

答:
meta-tags* is a class, but you're trying to call it like a function by placing it inside the Reagent square braces i.e. meta-tags*.

In the source code that you posted on GitHub, you also define a function called meta-tags. It looks like you're accidentally calling meta-tags* by mistake. Your full code (based on the Github demo) should read:

```<code>(ns app.views
  (:require [reagent.core :as reagent]
            [react-helmet]))

(def meta-tags* (reagent/adapt-react-class (aget react-helmet "default")))

(defn meta-tags [{:keys [:title :description]
                  :or {title "Some title"
                       description "some description"}}]
  [meta-tags* {:id "app-meta-tags"}
   [:title {:id "title" :title title}]
   [:meta {:id "description" :content description}]])

(defn main-panel []
  (let []
    (fn []
      [:div.container
       [meta-tags] ; <- no * star!
       [:h1 "Check for the meta-tags presence"]])))
</code>```

Body:
I'm importing a react component (using the :npm-deps support) and wrapping with the adapt-react-class adapter:

(:require [reagent.core :as reagent]
          [react-helmet])

(def meta-tags* (reagent/adapt-react-class (aget react-helmet "default")))

(defn main-panel []
  (let []
    (fn []
      [meta-tags*])))

This works fine for development, but when advanced compiler is on:

Uncaught TypeError: Cannot call a class as a function

Minimimal repo:
https://github.com/fbielejec/npm-deps-demo

Body:
meta-tags* is a class, but you're trying to call it like a function by placing it inside the Reagent square braces i.e. meta-tags*.

In the source code that you posted on GitHub, you also define a function called meta-tags. It looks like you're accidentally calling meta-tags* by mistake. Your full code (based on the Github demo) should read:

(ns app.views
  (:require [reagent.core :as reagent]
            [react-helmet]))

(def meta-tags* (reagent/adapt-react-class (aget react-helmet "default")))

(defn meta-tags [{:keys [:title :description]
                  :or {title "Some title"
                       description "some description"}}]
  [meta-tags* {:id "app-meta-tags"}
   [:title {:id "title" :title title}]
   [:meta {:id "description" :content description}]])

(defn main-panel []
  (let []
    (fn []
      [:div.container
       [meta-tags] ; <- no * star!
       [:h1 "Check for the meta-tags presence"]])))


问:
Using React props vs import , What is the best choice?
I'm trying to understand what is the best way to use props in React

Let's say I have a container that use import {FormattedMessage} from 'react-intl'

And let say I have a component used in the JSX of the container.

Now, If I wanted to use FormattedMessage in the component also, Should I use import again in the component?
or should I send FormattedMessage as a prop to the component via the container?

Example:

```<code>import {FormattedMessage} from 'react-intl';

class Container {
   render() {
        return (
                <Component formattedMessage={FormattedMessage} />
        );
   }
}
</code>```

答:
<FormattedMessage/> is a standalone component and passing it down to you child components in that manner completely unnecessary.

If you want to pass components from parent to child, use the special prop children instead.

<Container> render function:

```<code>return (<Component><FormattedMessage /></Component>)
</code>```

<Component> render function:

```<code>return (<div>{props.children}</div>)
</code>```

see: https://reactjs.org/docs/composition-vs-inheritance.html

Note: If you want to send the translated string into your child component as a prop, use injectIntl higher order component to pass the intl prop into your component. You can then call intl.formatMessage({id, defaultMessage}) from within your component to translate the string you want to pass as a prop into your child component.

see: https://github.com/yahoo/react-intl/wiki/API#injection-api

Body:
I'm trying to understand what is the best way to use props in React

Let's say I have a container that use import {FormattedMessage} from 'react-intl'

And let say I have a component used in the JSX of the container.

Now, If I wanted to use FormattedMessage in the component also, Should I use import again in the component?
or should I send FormattedMessage as a prop to the component via the container?

Example:

import {FormattedMessage} from 'react-intl';

class Container {
   render() {
        return (
                <Component formattedMessage={FormattedMessage} />
        );
   }
}

Body:
<FormattedMessage/> is a standalone component and passing it down to you child components in that manner completely unnecessary.

If you want to pass components from parent to child, use the special prop children instead.

<Container> render function:

return (<Component><FormattedMessage /></Component>)

<Component> render function:

return (<div>{props.children}</div>)

see: https://reactjs.org/docs/composition-vs-inheritance.html

Note: If you want to send the translated string into your child component as a prop, use injectIntl higher order component to pass the intl prop into your component. You can then call intl.formatMessage({id, defaultMessage}) from within your component to translate the string you want to pass as a prop into your child component.

see: https://github.com/yahoo/react-intl/wiki/API#injection-api


问:
How to solve SchemaValidationFailedException: Child is not present in schema
I'm trying to use Databroker of MD-SAL to save a list of data, after modifying the yang file and InstanceIdentifier many times but always facing similar validation issue, for example

java.util.concurrent.ExecutionException: TransactionCommitFailedException{message=canCommit encountered an unexpected failure, errorList=[RpcError [message=canCommit encountered an unexpected failure, severity=ERROR, errorType=APPLICATION, tag=operation-failed, applicationTag=null, info=null, cause=org.opendaylight.yangtools.yang.data.impl.schema.tree.SchemaValidationFailedException: Child /(urn:opendaylight:params:xml:ns:yang:testDataBroker?revision=2015-01-05)service-datas is not present in schema tree.]]}
        at org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture.wrapInExecutionExc

My goal is to use rpc save-device-info to get data from rest. Then use databroker api to save data in the memory and finally test if the data could be succesfully replicated into other cluster nodes.

Yang file:

```<code>module testDataBroker {
  yang-version 1;
  namespace "urn:opendaylight:params:xml:ns:yang:testDataBroker";
  prefix "testDataBroker";

  revision "2015-01-05" {
    description "Initial revision of testDataBroker model";
  }

  container service-datas {
    list service-data {
        key "service-id";
        uses service-id;
        uses device-info;
      }
  }

  grouping device-info {
    container device-info {
        leaf device-name {
           type string;
           config false;
        }

        leaf device-description {
            type string;
            config false;
        }
      }
  }

  grouping service-id {
    leaf service-id {
        type string;
        mandatory true;
    }
  }

  rpc save-device-info {
    input {
        uses service-id;
        uses device-info;
    }
    output {
        uses device-info;
    }
   }

   rpc get-device-info {
      output {
        uses device-info;
      }
   }
  }
</code>```

Java Code

```<code>    @Override public Future<RpcResult<SaveDeviceInfoOutput>> saveDeviceInfo(SaveDeviceInfoInput input) {
      String name = input.getDeviceInfo().getDeviceName();
      String description = input.getDeviceInfo().getDeviceDescription();
      String serviceId = input.getServiceId();

      WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
      DeviceInfo deviceInfo = new DeviceInfoBuilder().setDeviceDescription(description).setDeviceName(name).build();
      ServiceData serviceData = new ServiceDataBuilder().setServiceId(serviceId).setDeviceInfo(deviceInfo).build();
      InstanceIdentifier<ServiceData> instanceIdentifier =
        InstanceIdentifier.builder(ServiceDatas.class).child(ServiceData.class, serviceData.getKey()).build();

      writeTransaction.put(LogicalDatastoreType.CONFIGURATION, instanceIdentifier, serviceData, true);

      boolean isFailed = false;
      try {
          writeTransaction.submit().get();
          log.info("Create containers succeeded!");

       } catch (InterruptedException | ExecutionException e) {
          log.error("Create containers failed: ", e);
          isFailed = true;
      }

      return isFailed ?
        RpcResultBuilder.success(new SaveDeviceInfoOutputBuilder())
            .withError(RpcError.ErrorType.RPC, "Create container failed").buildFuture() :
        RpcResultBuilder.success(new SaveDeviceInfoOutputBuilder().setDeviceInfo(input.getDeviceInfo()))
            .buildFuture();
}
</code>```

Really need your help. Thanks.

Update:
With the same version of md-sal bundles, I installed feature odl-toaster on only one ODL instead of cluster nodes. It seems like rpc from odl-toaster is working properly on single node.

答: I didn't realize that rpc is also clustered. Sometimes the rpc request hit on other nodes which didn't deploy the same bundles. Now the problem has been solved after the bundle is distrubted on each node.</p>

Body:
I'm trying to use Databroker of MD-SAL to save a list of data, after modifying the yang file and InstanceIdentifier many times but always facing similar validation issue, for example

java.util.concurrent.ExecutionException: TransactionCommitFailedException{message=canCommit encountered an unexpected failure, errorList=[RpcError [message=canCommit encountered an unexpected failure, severity=ERROR, errorType=APPLICATION, tag=operation-failed, applicationTag=null, info=null, cause=org.opendaylight.yangtools.yang.data.impl.schema.tree.SchemaValidationFailedException: Child /(urn:opendaylight:params:xml:ns:yang:testDataBroker?revision=2015-01-05)service-datas is not present in schema tree.]]}
        at org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture.wrapInExecutionExc

My goal is to use rpc save-device-info to get data from rest. Then use databroker api to save data in the memory and finally test if the data could be succesfully replicated into other cluster nodes.

Yang file:

module testDataBroker {
  yang-version 1;
  namespace "urn:opendaylight:params:xml:ns:yang:testDataBroker";
  prefix "testDataBroker";

  revision "2015-01-05" {
    description "Initial revision of testDataBroker model";
  }

  container service-datas {
    list service-data {
        key "service-id";
        uses service-id;
        uses device-info;
      }
  }

  grouping device-info {
    container device-info {
        leaf device-name {
           type string;
           config false;
        }

        leaf device-description {
            type string;
            config false;
        }
      }
  }

  grouping service-id {
    leaf service-id {
        type string;
        mandatory true;
    }
  }

  rpc save-device-info {
    input {
        uses service-id;
        uses device-info;
    }
    output {
        uses device-info;
    }
   }

   rpc get-device-info {
      output {
        uses device-info;
      }
   }
  }

Java Code

    @Override public Future<RpcResult<SaveDeviceInfoOutput>> saveDeviceInfo(SaveDeviceInfoInput input) {
      String name = input.getDeviceInfo().getDeviceName();
      String description = input.getDeviceInfo().getDeviceDescription();
      String serviceId = input.getServiceId();

      WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
      DeviceInfo deviceInfo = new DeviceInfoBuilder().setDeviceDescription(description).setDeviceName(name).build();
      ServiceData serviceData = new ServiceDataBuilder().setServiceId(serviceId).setDeviceInfo(deviceInfo).build();
      InstanceIdentifier<ServiceData> instanceIdentifier =
        InstanceIdentifier.builder(ServiceDatas.class).child(ServiceData.class, serviceData.getKey()).build();

      writeTransaction.put(LogicalDatastoreType.CONFIGURATION, instanceIdentifier, serviceData, true);

      boolean isFailed = false;
      try {
          writeTransaction.submit().get();
          log.info("Create containers succeeded!");

       } catch (InterruptedException | ExecutionException e) {
          log.error("Create containers failed: ", e);
          isFailed = true;
      }

      return isFailed ?
        RpcResultBuilder.success(new SaveDeviceInfoOutputBuilder())
            .withError(RpcError.ErrorType.RPC, "Create container failed").buildFuture() :
        RpcResultBuilder.success(new SaveDeviceInfoOutputBuilder().setDeviceInfo(input.getDeviceInfo()))
            .buildFuture();
}

Really need your help. Thanks.

Update:
With the same version of md-sal bundles, I installed feature odl-toaster on only one ODL instead of cluster nodes. It seems like rpc from odl-toaster is working properly on single node.


问:
How to downcase the first character of a string?
There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase.

How can I do that in Python?

答:
This duplicate post lead me here.

If you've a list of strings like the one shown below

```<code>l = ['SentMessage', 'DeliverySucceeded', 'DeliveryFailed']
</code>```

Then, to convert the first letter of all items in the list, you can use

```<code>l = [x[0].lower() + x[1:] for x in l]
</code>```

Output

```<code>['sentMessage', 'deliverySucceeded', 'deliveryFailed']
</code>```

Body:
This duplicate post lead me here.

If you've a list of strings like the one shown below

l = ['SentMessage', 'DeliverySucceeded', 'DeliveryFailed']

Then, to convert the first letter of all items in the list, you can use

l = [x[0].lower() + x[1:] for x in l]

Output

['sentMessage', 'deliverySucceeded', 'deliveryFailed']


问:
Grunt doesn't start debug mode
I'm using Grunt to run my tests and it works well when I use it in normal mode "run local_test", but when I try to run it in debug mode "debug local_test" it shos me this Error:

```<code>    Error: listen EADDRINUSE :::59699
        at Object.exports._errnoException (util.js:1020:11)
        at exports._exceptionWithHostPort (util.js:1043:20)
        at Agent.Server._listen2 (net.js:1262:14)
        at listen (net.js:1298:10)
        at net.js:1408:9
        at _combinedTickCallback (internal/process/next_tick.js:83:11)
        at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

does anyone have an idea what could cause this behavior and how I could fix it?
thank you

答: The port is in use, you might need to kill a runaway process and try again or change the port number.</p>

Title: Grunt doesn't start debug mode

Body:
I'm using Grunt to run my tests and it works well when I use it in normal mode "run local_test", but when I try to run it in debug mode "debug local_test" it shos me this Error:

    Error: listen EADDRINUSE :::59699
        at Object.exports._errnoException (util.js:1020:11)
        at exports._exceptionWithHostPort (util.js:1043:20)
        at Agent.Server._listen2 (net.js:1262:14)
        at listen (net.js:1298:10)
        at net.js:1408:9
        at _combinedTickCallback (internal/process/next_tick.js:83:11)
        at process._tickCallback (internal/process/next_tick.js:104:9)

does anyone have an idea what could cause this behavior and how I could fix it?
thank you


问:
Can value after get "?" store in database just by loading the page?
If user open domain.com/article?username=bob then a new row get insert in database table under usernames with the value bob just by loading the page, is it possible ? if yes then how i can achieve this ?

Just like google analytics, if you have analytics on and open domain.com/article?utm_campaign=bob then google analytics store value for bob in their database including visitor's information just on loading the page.

Please pardon my English, Thanks

答:
Although you have not posted you codes here, i believe you should use cookies and sessions to achieve what you want.
Cookies are used to save users data, then transmitted back to server</p>


问:
VBA: How create a loop altering dates
I have a sheet of data where each row has been copied and pasted three time.  Each row has a date in column S.  Within these sets of three, the first row will remain the original date, the second row will be one month later than the original date, and the third row will be two months after the original date.

How do I turn this into a loop that repeats the process for the entire sheet?  My problem lies with the DateAdd function.  I''m getting a compile error on that function (never used it before).  Thanks in advance!  Here is the code that I have thus far:

```<code>Sub DateChange()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
With Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True
End Sub
</code>```

答:
Assuming that your code works:</p>

```<code>Sub DateChange()
    For r = 3 To 1000 Step 3
        Sheets("NameOfYourSheet").Range("S" & r) = "=DATE(YEAR(R[-1]C),MONTH(R[-1]C)+1,DAY(R[-1]C))"
        Sheets("NameOfYourSheet").Range("S" & r).AutoFill Destination:=Range("S3:S4"), Type:=xlFillDefault
    Next r
End Sub
</code>```

Title: VBA: How create a loop altering dates

Body:
I have a sheet of data where each row has been copied and pasted three time.  Each row has a date in column S.  Within these sets of three, the first row will remain the original date, the second row will be one month later than the original date, and the third row will be two months after the original date.

How do I turn this into a loop that repeats the process for the entire sheet?  My problem lies with the DateAdd function.  I''m getting a compile error on that function (never used it before).  Thanks in advance!  Here is the code that I have thus far:

Sub DateChange()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
With Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True
End Sub

Body:
Assuming that your code works:

Sub DateChange()
    For r = 3 To 1000 Step 3
        Sheets("NameOfYourSheet").Range("S" & r) = "=DATE(YEAR(R[-1]C),MONTH(R[-1]C)+1,DAY(R[-1]C))"
        Sheets("NameOfYourSheet").Range("S" & r).AutoFill Destination:=Range("S3:S4"), Type:=xlFillDefault
    Next r
End Sub


问:
Importjson to google spreadsheet, one field gives several results
I am trying to make a tracking system for our post @ work, and so far I feel that I am 90% done, but I get one problem.

I have added this script to google spreadsheet:https://gist.github.com/chrislkeller/5719258

Now, I am trying to pull out data with this "command":

```<code>=ImportJSON("https://tracking.bring.com/api/tracking.json?q="&A4;"/consignmentSet/packageSet/eventSet/recipientSignature,/consignmentSet/packageSet/eventSet/status,/consignmentSet/senderReference,/consignmentSet/packageSet/productName";"noInherit,noHeaders")
</code>```

And this works, but it gives me multiple results on status:

```<code>/consignmentSet/packageSet/eventSet/status
</code>```

If you see source, it have several "STATUS" in the source https://tracking.bring.com/api/tracking.json?q=TESTPACKAGE-AT-PICKUPPOINT, and this is the reason why it get all the results. What I want, is to get the last result for status in my google spreadsheet. This to give it a more clean look, and also to have less used cells for no use. The url provided, is a test package for bring, but when we send out, it will get even more "STATUS" up to 5 different status.

TLDR: Want to get one result for status, not several as shown in--> https://tracking.bring.com/api/tracking.json?q=TESTPACKAGE-AT-PICKUPPOINT when importing data to google spreadsheet.

答:
You need to modify the final output array. For that add/modify the following lines to the parseJSONObject_ function

```<code>var temp =  data.slice(1);
var final_data = [[temp[0][0],temp[temp.length-1][1],temp[temp.length-1][2],temp[0][3]]];
return hasOption_(options, "noHeaders") ? (data.length > 1 ? final_data : new Array()) : data;
</code>```

Entire Function:

```<code>/**
 * Parses a JSON object and returns a two-dimensional array containing the data of that object.
 */
function parseJSONObject_(object, query, options, includeFunc, transformFunc) {
  var headers = new Array();
  var data    = new Array();

  if (query && !Array.isArray(query) && query.toString().indexOf(",") != -1) {
    query = query.toString().split(",");
  }

  if (options) {
    options = options.toString().split(",");
  }

  parseData_(headers, data, "", 1, object, query, options, includeFunc);
  parseHeaders_(headers, data);
  transformData_(data, options, transformFunc);

  var temp =  data.slice(1);
  var final_data = [[temp[0][0],temp[0][1],temp[0][2],temp[0][3]]]; // Modified the index of the array
  return hasOption_(options, "noHeaders") ? (data.length > 1 ? final_data : new Array()) : data;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a tracking system for our post @ work, and so far I feel that I am 90% done, but I get one problem.

I have added this script to google spreadsheet:https://gist.github.com/chrislkeller/5719258

Now, I am trying to pull out data with this "command":

=ImportJSON("https://tracking.bring.com/api/tracking.json?q="&A4;"/consignmentSet/packageSet/eventSet/recipientSignature,/consignmentSet/packageSet/eventSet/status,/consignmentSet/senderReference,/consignmentSet/packageSet/productName";"noInherit,noHeaders")

And this works, but it gives me multiple results on status:

/consignmentSet/packageSet/eventSet/status

If you see source, it have several "STATUS" in the source https://tracking.bring.com/api/tracking.json?q=TESTPACKAGE-AT-PICKUPPOINT, and this is the reason why it get all the results. What I want, is to get the last result for status in my google spreadsheet. This to give it a more clean look, and also to have less used cells for no use. The url provided, is a test package for bring, but when we send out, it will get even more "STATUS" up to 5 different status.

TLDR: Want to get one result for status, not several as shown in--> https://tracking.bring.com/api/tracking.json?q=TESTPACKAGE-AT-PICKUPPOINT when importing data to google spreadsheet.

Body:
You need to modify the final output array. For that add/modify the following lines to the parseJSONObject_ function

var temp =  data.slice(1);
var final_data = [[temp[0][0],temp[temp.length-1][1],temp[temp.length-1][2],temp[0][3]]];
return hasOption_(options, "noHeaders") ? (data.length > 1 ? final_data : new Array()) : data;

Entire Function:

/**
 * Parses a JSON object and returns a two-dimensional array containing the data of that object.
 */
function parseJSONObject_(object, query, options, includeFunc, transformFunc) {
  var headers = new Array();
  var data    = new Array();

  if (query && !Array.isArray(query) && query.toString().indexOf(",") != -1) {
    query = query.toString().split(",");
  }

  if (options) {
    options = options.toString().split(",");
  }

  parseData_(headers, data, "", 1, object, query, options, includeFunc);
  parseHeaders_(headers, data);
  transformData_(data, options, transformFunc);

  var temp =  data.slice(1);
  var final_data = [[temp[0][0],temp[0][1],temp[0][2],temp[0][3]]]; // Modified the index of the array
  return hasOption_(options, "noHeaders") ? (data.length > 1 ? final_data : new Array()) : data;
}


问:
Docker-Machine do not work with Google Cloud service account
I Create a google compute instance with service account

```<code>gcloud --project my-proj compute instances create test1 \
--image-family "debian-9" --image-project "debian-cloud" \
--machine-type "g1-small" --network "default" --maintenance-policy "MIGRATE" \
--service-account "gke-build-robot@myproj-184015.iam.gserviceaccount.com" \
--scopes "https://www.googleapis.com/auth/cloud-platform" \
--tags "gitlab-runner" \
--boot-disk-size "10" --boot-disk-type "pd-standard" --boot-disk-device-name "$RESOURCE_NAME" \
--metadata register_token=mytoken,config_bucket=gitlab_config,runner_name=test1,gitlab_uri=myuri,runner_tags=backend \
--metadata-from-file "startup-script=startup-scripts/prepare-runner.sh"
</code>```

Log to instance though ssh: gcloud compute --project "myproj" ssh --zone "europe-west1-b" "gitlab-shared-runner-pool"

After install and configure docker machine. i try create instance:

```<code>     docker-machine create --driver google --google-project myproj test2
    Running pre-create checks...
    (test2) Check that the project exists
    (test2) Check if the instance already exists
    Creating machine...
    (test2) Generating SSH Key
    (test2) Creating host...
    (test2) Opening firewall ports
    (test2) Creating instance
    (test2) Waiting for Instance
Error creating machine: Error in driver during machine creation: Operation error: {EXTERNAL_RESOURCE_NOT_FOUND  The resource '1045904521672-compute@developer.gserviceaccount.com' of type 'serviceAccount' was not found. []}
</code>```

1045904521672-compute@developer.gserviceaccount.com is my default account.
I don;t understand why it used. Because activated is gke-build-robot@myproj-184015.iam.gserviceaccount.com

```<code>gcloud config list
[core]
account = gke-build-robot@myproj-184015.iam.gserviceaccount.com
disable_usage_reporting = True
project = novaposhta-184015
Your active configuration is: [default]

 gcloud auth list
                      Credentialed Accounts
ACTIVE  ACCOUNT
*       gke-build-robot@myproj-184015.iam.gserviceaccount.com
</code>```

Can some one explain me, what i do wrong?

答:
A similar issue (bosh-google-cpi-release issue 144) suggests somehow the

This error message is unclear, particularly because the credentials which also need to be specified in the manifest may be associated with another account altogether.

The default service_account for the bosh-google-cpi-release is set to "default" if it is not proactively set by the bosh manifest, so this will happen anytime you use service_scopes instead of a service_account.

While you are not using bosh-google-cpi-release, the last sentence made me double-check the gcloud reference page, in particular gcloud compute instance create.

A service account is an identity attached to the instance. Its access tokens can be accessed through the instance metadata server and are used to authenticate applications on the instance.

  The account can be either an email address or an alias corresponding to a service account. You can explicitly specify the Compute Engine default service account using the 'default' alias.

If not provided, the instance will get project's default service account.

It is as if your service account is either ignored or incorrect (and falls back to the project default's one)

See "Creating and Enabling Service Accounts for Instances" to double-check its value:

Usually, the service account's email is derived from the service account ID, in the format:

```<code>[SERVICE-ACCOUNT-NAME]@[PROJECT_ID].iam.gserviceaccount.com
</code>```

Or try setting first the service scope and account.

Body:
I Create a google compute instance with service account

gcloud --project my-proj compute instances create test1 \
--image-family "debian-9" --image-project "debian-cloud" \
--machine-type "g1-small" --network "default" --maintenance-policy "MIGRATE" \
--service-account "gke-build-robot@myproj-184015.iam.gserviceaccount.com" \
--scopes "https://www.googleapis.com/auth/cloud-platform" \
--tags "gitlab-runner" \
--boot-disk-size "10" --boot-disk-type "pd-standard" --boot-disk-device-name "$RESOURCE_NAME" \
--metadata register_token=mytoken,config_bucket=gitlab_config,runner_name=test1,gitlab_uri=myuri,runner_tags=backend \
--metadata-from-file "startup-script=startup-scripts/prepare-runner.sh"

Log to instance though ssh: gcloud compute --project "myproj" ssh --zone "europe-west1-b" "gitlab-shared-runner-pool"

After install and configure docker machine. i try create instance:

     docker-machine create --driver google --google-project myproj test2
    Running pre-create checks...
    (test2) Check that the project exists
    (test2) Check if the instance already exists
    Creating machine...
    (test2) Generating SSH Key
    (test2) Creating host...
    (test2) Opening firewall ports
    (test2) Creating instance
    (test2) Waiting for Instance
Error creating machine: Error in driver during machine creation: Operation error: {EXTERNAL_RESOURCE_NOT_FOUND  The resource '1045904521672-compute@developer.gserviceaccount.com' of type 'serviceAccount' was not found. []}

1045904521672-compute@developer.gserviceaccount.com is my default account.
I don;t understand why it used. Because activated is gke-build-robot@myproj-184015.iam.gserviceaccount.com

gcloud config list
[core]
account = gke-build-robot@myproj-184015.iam.gserviceaccount.com
disable_usage_reporting = True
project = novaposhta-184015
Your active configuration is: [default]

 gcloud auth list
                      Credentialed Accounts
ACTIVE  ACCOUNT
*       gke-build-robot@myproj-184015.iam.gserviceaccount.com

Can some one explain me, what i do wrong?

Body:
A similar issue (bosh-google-cpi-release issue 144) suggests somehow the

This error message is unclear, particularly because the credentials which also need to be specified in the manifest may be associated with another account altogether.

The default service_account for the bosh-google-cpi-release is set to "default" if it is not proactively set by the bosh manifest, so this will happen anytime you use service_scopes instead of a service_account.

While you are not using bosh-google-cpi-release, the last sentence made me double-check the gcloud reference page, in particular gcloud compute instance create.

A service account is an identity attached to the instance. Its access tokens can be accessed through the instance metadata server and are used to authenticate applications on the instance.

  The account can be either an email address or an alias corresponding to a service account. You can explicitly specify the Compute Engine default service account using the 'default' alias.

If not provided, the instance will get project's default service account.

It is as if your service account is either ignored or incorrect (and falls back to the project default's one)

See "Creating and Enabling Service Accounts for Instances" to double-check its value:

Usually, the service account's email is derived from the service account ID, in the format:

[SERVICE-ACCOUNT-NAME]@[PROJECT_ID].iam.gserviceaccount.com

Or try setting first the service scope and account.


问:
NodeJS Express pagination with Google Datastore how to integrate cursor queries with UI control
I am stuck on implementing Pagination and I just need a bit of help, either some example code or even just a hint to help me proceed in the right direction.

I'm looking for some guidance on how to integrate Google Datastore database cursors with front-end UI pagination controls. I know how to build an angular pagination service, but that's with retrieving all the data at once and due to performance issues (5,000 records+) I want to use cursors to retrieve data in subsets.

NOTE: There's a similar question here, but I need more detail than this accepted answer provides. Node pagination in google datastore

QUESTION: How can I integrate the paginated datastore cursor queries with the front-end UI controls to allow the user to select the current page and control number of results displayed on each page?

I need to build a page that displays a large number of records with dynamic pagination. The user must be able to select the number of records display on each page.

Since there are several thousand records that might be returned at one time, I want to use cursors to retrieve subsets of data.

There is an example of how to paginate in the docs, but it is a pretty basic example and does not demonstrate how to integrate with front-end UI controls.

Can anyone provide a more detailed example and/or point me in the right direction on where to begin with this requirement? Unfortunately I haven't been able to find any detailed examples online.

https://googlecloudplatform.github.io/google-cloud-node/#/docs/datastore/1.1.0/datastore

Paginating Records

```<code>var express = require('express');
var app = express();

var NUM_RESULTS_PER_PAGE = 15;

app.get('/contacts', function(req, res) {
  var query = datastore.createQuery('Contacts')
    .limit(NUM_RESULTS_PER_PAGE);

  if (req.query.nextPageCursor) {
    query.start(req.query.nextPageCursor);
  }

  datastore.runQuery(query, function(err, entities, info) {
    if (err) {
      // Error handling omitted.
      return;
    }

    // Respond to the front end with the contacts and the cursoring token
    // from the query we just ran.
    var frontEndResponse = {
      contacts: entities
    };

    // Check if  more results may exist.
    if (info.moreResults !== datastore.NO_MORE_RESULTS) {
      frontEndResponse.nextPageCursor = info.endCursor;
    }

    res.render('contacts', frontEndResponse);
  });
});
</code>```

答:
One thing to keep in mind is the first item on the Limitations of cursors list:

A cursor can be used only by the same project that performed the original query, and only to continue the same query. It is not
  possible to retrieve results using a cursor without setting up the
  same query from which it was originally generated.

So you need to always be able to re-create the original query inside your handler, which means you need to pass around the equivalent of your NUM_RESULTS_PER_PAGE value from one request to another. You also need to reset the query every time that value changes - meaning you can't continue browsing from where you were after changing the number of results displayed per page.

Then, to be able to use the pagination, you also need to pass around the current cursor value from one request to another, updated at every request.

Now I'm not a NodeJS user, so I can tell exactly how this passing values around from one request to another would typically be implemented. In your code req.query.nextPageCursor and frontEndResponse.nextPageCursor appear to be intended for this, but I can't tell if that's OK or not. Maybe this is a less specific question easier to find an answer for.

In python webapp2, for example, I can store such values server-side in the user's session in one request and read them from the session in a subsequent request. Donno if this is of any help.

Body:
I am stuck on implementing Pagination and I just need a bit of help, either some example code or even just a hint to help me proceed in the right direction.

I'm looking for some guidance on how to integrate Google Datastore database cursors with front-end UI pagination controls. I know how to build an angular pagination service, but that's with retrieving all the data at once and due to performance issues (5,000 records+) I want to use cursors to retrieve data in subsets.

NOTE: There's a similar question here, but I need more detail than this accepted answer provides. Node pagination in google datastore

QUESTION: How can I integrate the paginated datastore cursor queries with the front-end UI controls to allow the user to select the current page and control number of results displayed on each page?

I need to build a page that displays a large number of records with dynamic pagination. The user must be able to select the number of records display on each page.

Since there are several thousand records that might be returned at one time, I want to use cursors to retrieve subsets of data.

There is an example of how to paginate in the docs, but it is a pretty basic example and does not demonstrate how to integrate with front-end UI controls.

Can anyone provide a more detailed example and/or point me in the right direction on where to begin with this requirement? Unfortunately I haven't been able to find any detailed examples online.

https://googlecloudplatform.github.io/google-cloud-node/#/docs/datastore/1.1.0/datastore

Paginating Records

var express = require('express');
var app = express();

var NUM_RESULTS_PER_PAGE = 15;

app.get('/contacts', function(req, res) {
  var query = datastore.createQuery('Contacts')
    .limit(NUM_RESULTS_PER_PAGE);

  if (req.query.nextPageCursor) {
    query.start(req.query.nextPageCursor);
  }

  datastore.runQuery(query, function(err, entities, info) {
    if (err) {
      // Error handling omitted.
      return;
    }

    // Respond to the front end with the contacts and the cursoring token
    // from the query we just ran.
    var frontEndResponse = {
      contacts: entities
    };

    // Check if  more results may exist.
    if (info.moreResults !== datastore.NO_MORE_RESULTS) {
      frontEndResponse.nextPageCursor = info.endCursor;
    }

    res.render('contacts', frontEndResponse);
  });
});


问:
DynamoDB to Redshift
I am asking this in context of loading data from DynamoDb into Redshift. Per the Redshift Docs:

To avoid consuming excessive amounts of provisioned read throughput, we recommend that you not load data from Amazon DynamoDB tables that are in production environments.

My data is in Production, so how do I get it out of there?

Alternately is DynamoDB Streams a better overall choice to move data from DynamoDB into Redshift? (I understand this does not add to my RCU cost.)

答: Using AWS Data pipeline, you can do a  bulk copy data from DynamoDB  to a new or existing Redshift table.

Title: DynamoDB to Redshift


问:
MATLAB uicontrol callback return matrix
Original post: MATLAB scrolling plot

I got a second part in my problem now.
As before, I have a 19*1000*134 matrix that I'm plotting thanks to the nicely answer from Aero Engy on the last post.

I would like to create in my workspace a vector called clean that will have a 134 length.

By default, the value for clean(i) (with i between 1 and 134) will be 1 -- but, if I press a button on the UI interface, the value must get to 0.

My code bellow, just don't give me any ouput. The button seems to work, but when I close the figure, I don't get the vector clean.

```<code>function cleanData(data);
% data = rand(19,1000,134);
global clean
clean = ones(1,size(data,3));
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,clean,s});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
viewI = round(s.Value);
disp(['Current Epoch: ' num2str(viewI)]) %console print
xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])

function notClean(c,evtData,clean,s)
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print
</code>```

What am I doing wrong ?

Bonus: It would be nice if

When I press the button "Not clean", the slider change values and increment aswell (Currently, I have to press the button, then the right Arrow of the slider to go to the next 2 secs of data).

Once I check "Clean" or "not clean" for one channel (one of the 19 rows of the matrix), for the next one, it will skip the "not clean" data (i.e. with a 0 in the clean matrix corresponding to the epoch number).

Thanks for the help, I'm quite new at MATLAB, and even if I improve quickly, I'm far from fully understanding this code.

答:
In the notClean callback I called clean out as a global.  I also removed it as an input ... since it is a global it is not necessary to pass it in.

Also I added the code to advance the slider 1 each time you pressed the button.

In your workspace after closing the GUI to see what you marked you just need to do the following at the command line to access your clean array.  (Numbers are random things I marked as not clean.

I have to leave right now so I can't address the second bullet about changing channels and skipping the ~clean elementr ... but it shouldn't be very hard.  I will get back here in a couple of hours.

```<code>>> global clean
>> find(~clean)
ans =
  3  4  11 19
</code>```

MODIFIED CODE:
EDIT: Added code protection at the edges for skipping channels.

```<code>function cleanData(data)
% data = rand(19,1000,134);
global clean
clean = ones(1,size(data,3));
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,s,a});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
global clean
persistent prevI

if isempty(prevI)
    prevI = 1;
end

viewI = round(s.Value);
sDir = sign(viewI - prevI);  %-1 if going backwards +1 if going forward
prevI = viewI;

if clean(viewI) == 0
    newPos = viewI + sDir;
    if newPos < 1 || newPos > s.Max
        return
    end
    s.Value = newPos;
    sliderChange(s,[],a)
else
    disp(['Current Epoch: ' num2str(viewI)]) %console print
    xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])
end

function notClean(c,evtData,s,a)
global clean %Call the global
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print
%Advance to the next slider position.
if num+1 < s.Max
    s.Value = num+1;
    sliderChange(s,[],a)
end
</code>```

Title: MATLAB uicontrol callback return matrix

Body:
Original post: MATLAB scrolling plot

I got a second part in my problem now.
As before, I have a 19*1000*134 matrix that I'm plotting thanks to the nicely answer from Aero Engy on the last post.

I would like to create in my workspace a vector called clean that will have a 134 length.

By default, the value for clean(i) (with i between 1 and 134) will be 1 -- but, if I press a button on the UI interface, the value must get to 0.

My code bellow, just don't give me any ouput. The button seems to work, but when I close the figure, I don't get the vector clean.

function cleanData(data);
% data = rand(19,1000,134);
global clean
clean = ones(1,size(data,3));
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,clean,s});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
viewI = round(s.Value);
disp(['Current Epoch: ' num2str(viewI)]) %console print
xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])

function notClean(c,evtData,clean,s)
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print

What am I doing wrong ?

Bonus: It would be nice if

When I press the button "Not clean", the slider change values and increment aswell (Currently, I have to press the button, then the right Arrow of the slider to go to the next 2 secs of data).

Once I check "Clean" or "not clean" for one channel (one of the 19 rows of the matrix), for the next one, it will skip the "not clean" data (i.e. with a 0 in the clean matrix corresponding to the epoch number).

Thanks for the help, I'm quite new at MATLAB, and even if I improve quickly, I'm far from fully understanding this code.

Body:
In the notClean callback I called clean out as a global.  I also removed it as an input ... since it is a global it is not necessary to pass it in.

Also I added the code to advance the slider 1 each time you pressed the button.

In your workspace after closing the GUI to see what you marked you just need to do the following at the command line to access your clean array.  (Numbers are random things I marked as not clean.

I have to leave right now so I can't address the second bullet about changing channels and skipping the ~clean elementr ... but it shouldn't be very hard.  I will get back here in a couple of hours.

>> global clean
>> find(~clean)
ans =
  3  4  11 19

MODIFIED CODE:
EDIT: Added code protection at the edges for skipping channels.

function cleanData(data)
% data = rand(19,1000,134);
global clean
clean = ones(1,size(data,3));
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,s,a});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
global clean
persistent prevI

if isempty(prevI)
    prevI = 1;
end

viewI = round(s.Value);
sDir = sign(viewI - prevI);  %-1 if going backwards +1 if going forward
prevI = viewI;

if clean(viewI) == 0
    newPos = viewI + sDir;
    if newPos < 1 || newPos > s.Max
        return
    end
    s.Value = newPos;
    sliderChange(s,[],a)
else
    disp(['Current Epoch: ' num2str(viewI)]) %console print
    xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])
end

function notClean(c,evtData,s,a)
global clean %Call the global
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print
%Advance to the next slider position.
if num+1 < s.Max
    s.Value = num+1;
    sliderChange(s,[],a)
end


问:
convert WPF WebBrowser to WinForms
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

```<code>System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();
</code>```

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!

答:
You can use ElementHost to add WPF System.Windows.Controls.WebBrowser to WinForms Form.

But I have no idea why you would want to do it.

Title: convert WPF WebBrowser to WinForms

Body:
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!


问:
React Router 3 Breadcrumb Dropdown
I am trying to change the route based on the dropdown option in the breadcrumb.Any suggestions would be appreciated.

This is the component that is getting the first option but I am not sure how to gran the other options after the dropdown is generated.

const MenuItemViews = ({ params: { category, subCategory, item }, children }) => {
  const menuItem = sideNavData.lookupItem(category, subCategory, item);
  console.log(menuItem);
  console.info(children);
  return (

      {
        menuItem.name === 'Bill'
          ?

Labels

            {
              !children
                ? <Link to={`/${category}/${subCategory}/${item}/${menuItem.childItems[0].name}`} >
                  <Image src={menuItem.content} />
                </Link>
                : children
            }

          : <ContentContainer>

{menuItem.name}

            <Image src={menuItem.content} alt='item' />
          </ContentContainer>
      }

  );
};```
</div>
</div>
</p>

<p>this is the component that is displaying the breadcrumbs.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const labelDropdownOptions = [
  { key: 'OptionOne', value: 'OptionOne', text: 'OptionOne' },
  { key: 'OptionTwo', value: 'OptionTwo', text: 'OptionTwo' },
  { key: 'OptionThree', value: 'OptionThree', text: 'OptionThree' },
];

class TopBar extends Component {
  resolver = (key) => {
    if (key === 'Home') {
      return key;
    }
    return this.props.params[key];
  }

  dropdownLink = (link, key, text, index, routes) => {
    console.log(routes);
    if (text === 'OptionOne') {
      return (
        <Dropdown defaultValue={'OptionOne'} key={key} options={labelDropdownOptions} />
      );
    }
    return <Link key={key} to={link}>{text}</Link>;
  }

  render() {
    const { routes, params } = this.props;
    return (
      <TopBarHeader>
        <IndexLink to='/'>
          <HomeIcon><Icon name='home' /></HomeIcon>
        </IndexLink>
        <BreadcrumbWrapper>
          <Breadcrumbs
            createLink={this.dropdownLink}
            params={params}
            resolver={this.resolver}
            routes={routes}
          />
        </BreadcrumbWrapper>
      </TopBarHeader>
    );
  }
}</code>```

答:
I was able to do this by passing this.props.router.push into the onClick prop and specifying the value.

class TopBar extends Component {
  resolver = (key) => {
    if (key === 'Home') {
      return key;
    }
    return this.props.params[key];
  }

  dropdownLink = (link, key, text, index, routes) => {
    const category = sideNavData.lookupCategory(this.props.category);
    if (link === '/TabTwo/Names/Bill/OptionOne' || link === '/TabTwo/Names/Bill/OptionTwo' || link === '/TabTwo/Names/Bill/OptionThree') {
      return (

          {
            Object.keys(category).map((subCategory, i) => {
              return (

                  {
                    Object.keys(category[subCategory]).map((item, itemIndex) => (

                        {
                          category[subCategory][item].name === 'Bill'
                            ? <Dropdown
                              defaultValue={'OptionOne'}
                              options={category[subCategory][item].childItems}
                              onChange={(event, data) => { this.props.router.push(`/${this.props.category}/${subCategory}/${category[subCategory][item].name}/${data.value}`); }}
                            />
                            : null
                        }

                    ))
                  }

              );
            })
          }

      );
    }
    return <Link key={key} to={link}>{text}</Link>;
  }

  render() {
    const { routes, params } = this.props;
    return (
      <TopBarHeader>
        <IndexLink to='/'>
          <HomeIcon><Icon name='home' /></HomeIcon>
        </IndexLink>
        <BreadcrumbWrapper>
          <Breadcrumbs
            createLink={this.dropdownLink}
            params={params}
            resolver={this.resolver}
            routes={routes}
          />
        </BreadcrumbWrapper>
      </TopBarHeader>
    );
  }
}```

Title: React Router 3 Breadcrumb Dropdown

Body:
I am trying to change the route based on the dropdown option in the breadcrumb.Any suggestions would be appreciated.

This is the component that is getting the first option but I am not sure how to gran the other options after the dropdown is generated.

const MenuItemViews = ({ params: { category, subCategory, item }, children }) => {
  const menuItem = sideNavData.lookupItem(category, subCategory, item);
  console.log(menuItem);
  console.info(children);
  return (

      {
        menuItem.name === 'Bill'
          ?

Labels

            {
              !children
                ? <Link to={`/${category}/${subCategory}/${item}/${menuItem.childItems[0].name}`} >
                  <Image src={menuItem.content} />
                </Link>
                : children
            }

          : <ContentContainer>

{menuItem.name}

            <Image src={menuItem.content} alt='item' />
          </ContentContainer>
      }

  );
};

this is the component that is displaying the breadcrumbs.

const labelDropdownOptions = [
  { key: 'OptionOne', value: 'OptionOne', text: 'OptionOne' },
  { key: 'OptionTwo', value: 'OptionTwo', text: 'OptionTwo' },
  { key: 'OptionThree', value: 'OptionThree', text: 'OptionThree' },
];

class TopBar extends Component {
  resolver = (key) => {
    if (key === 'Home') {
      return key;
    }
    return this.props.params[key];
  }

  dropdownLink = (link, key, text, index, routes) => {
    console.log(routes);
    if (text === 'OptionOne') {
      return (
        <Dropdown defaultValue={'OptionOne'} key={key} options={labelDropdownOptions} />
      );
    }
    return <Link key={key} to={link}>{text}</Link>;
  }

  render() {
    const { routes, params } = this.props;
    return (
      <TopBarHeader>
        <IndexLink to='/'>
          <HomeIcon><Icon name='home' /></HomeIcon>
        </IndexLink>
        <BreadcrumbWrapper>
          <Breadcrumbs
            createLink={this.dropdownLink}
            params={params}
            resolver={this.resolver}
            routes={routes}
          />
        </BreadcrumbWrapper>
      </TopBarHeader>
    );
  }
}

Body:
I was able to do this by passing this.props.router.push into the onClick prop and specifying the value.

class TopBar extends Component {
  resolver = (key) => {
    if (key === 'Home') {
      return key;
    }
    return this.props.params[key];
  }

  dropdownLink = (link, key, text, index, routes) => {
    const category = sideNavData.lookupCategory(this.props.category);
    if (link === '/TabTwo/Names/Bill/OptionOne' || link === '/TabTwo/Names/Bill/OptionTwo' || link === '/TabTwo/Names/Bill/OptionThree') {
      return (
        <span key={index}>
          {
            Object.keys(category).map((subCategory, i) => {
              return (
                <span key={i}>
                  {
                    Object.keys(category[subCategory]).map((item, itemIndex) => (
                      <span key={itemIndex}>
                        {
                          category[subCategory][item].name === 'Bill'
                            ? <Dropdown
                              defaultValue={'OptionOne'}
                              options={category[subCategory][item].childItems}
                              onChange={(event, data) => { this.props.router.push(`/${this.props.category}/${subCategory}/${category[subCategory][item].name}/${data.value}`); }}
                            />
                            : null
                        }
                      </span>
                    ))
                  }
                </span>
              );
            })
          }
        </span>
      );
    }
    return <Link key={key} to={link}>{text}</Link>;
  }

  render() {
    const { routes, params } = this.props;
    return (
      <TopBarHeader>
        <IndexLink to='/'>
          <HomeIcon><Icon name='home' /></HomeIcon>
        </IndexLink>
        <BreadcrumbWrapper>
          <Breadcrumbs
            createLink={this.dropdownLink}
            params={params}
            resolver={this.resolver}
            routes={routes}
          />
        </BreadcrumbWrapper>
      </TopBarHeader>
    );
  }
}


问:
dict_keys object has no attribute plot while using nltk
I am using

```<code>python 3.6(Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32)
</code>```

working on nltk with python3.6, when I am trying to get plot of frequency distribution an error is coming.

Trying below script

```<code>from nltk.book import *

freq = FreqDist(text5)
freq12 = freq.keys()
freq12.plot(50, cumulative=True)
</code>```

I receive the following traceback

```<code>Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    freq12.plot(50, cumulative=True)
AttributeError: 'dict_keys' object has no attribute 'plot'
</code>```

How do I get plot while using python 3.6?

答:
I have never used the library, but guessing based on some other question in SO I think

```<code>freq12.plot(50, cumulative=True)
</code>```

should be

```<code>freq.plot(50, cumulative=True)
</code>```

Body:
I am using

python 3.6(Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32)

working on nltk with python3.6, when I am trying to get plot of frequency distribution an error is coming.

Trying below script

from nltk.book import *

freq = FreqDist(text5)
freq12 = freq.keys()
freq12.plot(50, cumulative=True)

I receive the following traceback

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    freq12.plot(50, cumulative=True)
AttributeError: 'dict_keys' object has no attribute 'plot'

How do I get plot while using python 3.6?

Body:
I have never used the library, but guessing based on some other question in SO I think

freq12.plot(50, cumulative=True)

should be

freq.plot(50, cumulative=True)


问:
Is installing NodeJS packages locally equivalent to Python's virtualenv?
I've been using Python for a while and I've learned we should always use a virtual env for each project where we pip install <name> the packages as needed, etc

I'm new to JS but would downloading packages using npm install <name> without the -g option mean it will only download it in the specific project directory, similarly to how Python's virtual env is keeping the pip packages separate? or is there also some sort of virtual env that needs to be created?

Sorry if I'm misunderstanding anything here... just want to make sure that installing packages using npm install isn't going to mess w/ anything globally or something!

答:
Correct, installing packages via npm install <package> installs them only for the specific project, by default in a folder node_modules in the project root.

npm install --global <package> installs a package globally.

See the npm docs for more info.


问:
How to convert an already open file to string?
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)</p>

```<code>def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''
</code>```

答:
```<code>def read_file(myfile):
    return myfile.read()
</code>```

Body:
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)

def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''


问:
Is it possible to vectorise the sequential update of the elements of a vector in R?
Is it possible to vectorise code like the following?

```<code>length(x) <- 100;
x[1]      <- 1;
y         <- rnorm(100);

for(i in 2:100) {
    x[i] <- 2 * y[i] * x[i-1];
}
</code>```

I appreciate that this is a trivial example, but it serves to illustrate the idea.

I often need to write code where the i-th value in a vector depends on the (i-1)-th value and if possible, I'd like to write this without needing a for loop, as profiling suggests the functions with this type of operation are the major bottlenecks in my code.

Is this operation vectorizable so I do not need to use a for() loop in the calculation?

答: I don't have full details on this yet, but it looks the function filter() is going to be useful to do what I need.

Body:
Is it possible to vectorise code like the following?

length(x) <- 100;
x[1]      <- 1;
y         <- rnorm(100);

for(i in 2:100) {
    x[i] <- 2 * y[i] * x[i-1];
}

I appreciate that this is a trivial example, but it serves to illustrate the idea.

I often need to write code where the i-th value in a vector depends on the (i-1)-th value and if possible, I'd like to write this without needing a for loop, as profiling suggests the functions with this type of operation are the major bottlenecks in my code.

Is this operation vectorizable so I do not need to use a for() loop in the calculation?


问:
Python 3 CSV file nominees
```<code>import csv

title = input('Winning title: ')

with open('nominees.csv', newline='') as f:
  for line in csv.DictReader(f):
     print('Congratulations: ',line['director(s)'])
</code>```

This code outputs:

```<code>Winning title: O brother, Where Art Thou?
Congratulations:  Steven Spielberg
Congratulations:  Joel Coen, Ethan Coen
Congratulations:  Stanley Kubrick
Congratulations:  Buster Keaton, Roscoe Arbuckle
</code>```

I'm trying to get it to output this:

```<code>Winning title: O Brother, Where Art Thou?
Congratulations: Joel Coen, Ethan Coen
</code>```

I know I am missing a bunch of code...for loop???

答:
Change the following

```<code>with open('nominees.csv', newline='') as f:
  for line in csv.DictReader(f):
    print('Congratulations: ',line['director(s)'])
</code>```

to

```<code>with open('nominees.csv', newline='') as f:
  for line in csv.DictReader(f):
    if line['title'] == title:
      print('Congratulations: ',line['director(s)'])
</code>```

Title: Python 3 CSV file nominees

Body:
import csv

title = input('Winning title: ')

with open('nominees.csv', newline='') as f:
  for line in csv.DictReader(f):
     print('Congratulations: ',line['director(s)'])

This code outputs:

Winning title: O brother, Where Art Thou?
Congratulations:  Steven Spielberg
Congratulations:  Joel Coen, Ethan Coen
Congratulations:  Stanley Kubrick
Congratulations:  Buster Keaton, Roscoe Arbuckle

I'm trying to get it to output this:

Winning title: O Brother, Where Art Thou?
Congratulations: Joel Coen, Ethan Coen

I know I am missing a bunch of code...for loop???

Body:
Change the following

with open('nominees.csv', newline='') as f:
  for line in csv.DictReader(f):
    print('Congratulations: ',line['director(s)'])

to

with open('nominees.csv', newline='') as f:
  for line in csv.DictReader(f):
    if line['title'] == title:
      print('Congratulations: ',line['director(s)'])


问:
CloudFoundry/Springboot app using Liberty for Java on Bluemix all of a sudden crashes when starting, no changes in code for months
I have a javascript/html/css application being served with Springboot on Bluemix.  Running the app locally works just fine, and the code has not been changed in a couple months.  When I attempt to push the app using the CF CLI, I get the following error:

```<code>   2017-11-13T12:18:29.89-0600 [CELL/0] OUT Successfully destroyed container
   2017-11-13T12:19:33.32-0600 [CELL/0] OUT Creating container
   2017-11-13T12:19:37.70-0600 [CELL/0] OUT Successfully created container
   2017-11-13T12:19:55.79-0600 [CELL/0] OUT Starting health monitoring of container
   2017-11-13T12:19:59.83-0600 [APP/PROC/WEB/0] OUT 18:19:59.812 [main] INFO app.Application -  App Started
   2017-11-13T12:20:03.49-0600 [APP/PROC/WEB/0] OUT 2017-11-13 18:20:03,485 INFO  [main] app : app.Application : Starting Application on  with PID 13 (/home/vcap/app/BOOT-INF/classes started by vcap in /home/vcap/app)
   2017-11-13T12:20:03.49-0600 [APP/PROC/WEB/0] OUT 2017-11-13 18:20:03,487 INFO  [main] app : app.Application : No active profile set, falling back to default profiles: default
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR J9Generic_Signal_Number=00000004 Signal_Number=0000000b Error_Value=00000000 Signal_Code=00000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR RCX=0000000000000536 RDX=0000000000000000 R8=000000000000000C R9=00000000FFFFFFF9
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR RIP=00007F82CB50AADF GS=0000 FS=0000 RSP=00007F82CC39F460
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm12 4207fffffff8016a (f: 4294443264.000000, d: 1.288490e+10)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm13 3c57c00000000000 (f: 0.000000, d: 5.149960e-18)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Module=/home/vcap/app/.java/jre/lib/amd64/compressedrefs/libj9vm29.so
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR CPU=amd64 (4 logical CPUs) (0x7daa33000 RAM)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4E869F [libj9vm29.so+0xeb69f])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4DED50 [libj9vm29.so+0xe1d50])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Java_java_lang_ClassLoader_defineClassImpl+0xa4 (0x00007F82C0D69134 [libjclse7b_29.so+0x11134])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Unhandled exception
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Type=Segmentation error vmState=0x00000000
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Handler1=00007F82CB481AA0 Handler2=00007F82CAD8BE00 InaccessibleAddress=0000000000000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR EFlags=0000000000010246 CS=0033 RBP=00007F82CC39F9B0 ERR=0000000000000004
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR TRAPNO=000000000000000E OLDMASK=0000000000000000 CR2=0000000000000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm6 1610000ab3f109b8 (f: 3018918400.000000, d: 2.041302e-202)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm11 3c4cd58858eb8000 (f: 1491828736.000000, d: 3.126201e-18)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm15 4028f40b5ed97f00 (f: 1591312128.000000, d: 1.247665e+01)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4DDEDA [libj9vm29.so+0xe0eda])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR R14=0000000000000000 R15=0000000000000000
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm0 00ff000000000000 (f: 0.000000, d: 7.063274e-304)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm2 6a003e74696e693c (f: 1768843520.000000, d: 3.978864e+202)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm7 b8d41014f309b3f1 (f: 4077499392.000000, d: -6.037435e-35)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm10 3fe0000000000000 (f: 0.000000, d: 5.000000e-01)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR ----------- Stack Backtrace -----------
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4E6C85 [libj9vm29.so+0xe9c85])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR ---------------------------------------
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR R10=0000000000000522 R11=00007F82CC39FA0C R12=0000000000000000 R13=00007F82CBB9F520
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm3 105953dd10130610 (f: 269682176.000000, d: 6.525551e-230)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm4 d91013075953130a (f: 1498616576.000000, d: -1.037698e+121)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm5 5953cc0913045953 (f: 319052128.000000, d: 2.044833e+122)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm8 0000000000000000 (f: 0.000000, d: 0.000000e+00)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm9 09b3fe01b8042e01 (f: 3087281664.000000, d: 6.348990e-262)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Module_base_address=00007F82CB3FD000
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Target=2_90_20170901_363591 (Linux 4.4.0-75-generic)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB50AADF [libj9vm29.so+0x10dadf])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB502134 [libj9vm29.so+0x105134])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4E7E64 [libj9vm29.so+0xeae64])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82C0D74DD9 [libjclse7b_29.so+0x1cdd9])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR RDI=00007F82CC39F9B0 RSI=0000000000000000 RAX=0000000000000001 RBX=0000000000000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm1 0000ffffffffffff (f: 4294967296.000000, d: 1.390671e-309)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm14 bc5b599f227becbb (f: 578546880.000000, d: -5.930604e-18)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82B053920E [<unknown>+0x0])
   2017-11-13T12:20:03.89-0600 [APP/PROC/WEB/0] OUT Exit status 255
   2017-11-13T12:20:03.92-0600 [CELL/0] OUT Exit status 0
   2017-11-13T12:20:03.94-0600 [CELL/0] OUT Destroying container
   2017-11-13T12:20:03.94-0600 [CELL/0] OUT Stopping instance 5a3e2441-bbd9-402c-5748-fd68
   2017-11-13T12:20:03.96-0600 [API/0] OUT Process has crashed with type: "web"
   2017-11-13T12:20:03.97-0600 [API/0] OUT App instance exited with guid f7a4a8ff-ebbc-49cf-96eb-37895fb88edd payload: {"instance"=>"5a3e2441-bbd9-402c-5748-fd68", "index"=>0, "reason"=>"CRASHED", "exit_description"=>"APP/PROC/WEB: Exited with status 255", "crash_count"=>4, "crash_timestamp"=>1510597203938616258, "version"=>"7ebb8072-9edc-40e3-a749-ce83273fb0d3"}
</code>```

I have other apps using the liberty for java buildpack on Bluemix that are doing fine, but this app specifically has started crashing with no changes to the environment or code, and the errors are not too helpful.  I've tried increasing memory and using several different buildpacks (IBM's websphere libery as well as cloud foundry's) to no avail Any advice would be appreciated.

答:
Was able to fix this by using the community java buildpack, java_buildpack

It seems that there was a problem with the default buildpack.  I imagine an update to the buildpack caused something to break.

Body:
I have a javascript/html/css application being served with Springboot on Bluemix.  Running the app locally works just fine, and the code has not been changed in a couple months.  When I attempt to push the app using the CF CLI, I get the following error:

   2017-11-13T12:18:29.89-0600 [CELL/0] OUT Successfully destroyed container
   2017-11-13T12:19:33.32-0600 [CELL/0] OUT Creating container
   2017-11-13T12:19:37.70-0600 [CELL/0] OUT Successfully created container
   2017-11-13T12:19:55.79-0600 [CELL/0] OUT Starting health monitoring of container
   2017-11-13T12:19:59.83-0600 [APP/PROC/WEB/0] OUT 18:19:59.812 [main] INFO app.Application -  App Started
   2017-11-13T12:20:03.49-0600 [APP/PROC/WEB/0] OUT 2017-11-13 18:20:03,485 INFO  [main] app : app.Application : Starting Application on  with PID 13 (/home/vcap/app/BOOT-INF/classes started by vcap in /home/vcap/app)
   2017-11-13T12:20:03.49-0600 [APP/PROC/WEB/0] OUT 2017-11-13 18:20:03,487 INFO  [main] app : app.Application : No active profile set, falling back to default profiles: default
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR J9Generic_Signal_Number=00000004 Signal_Number=0000000b Error_Value=00000000 Signal_Code=00000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR RCX=0000000000000536 RDX=0000000000000000 R8=000000000000000C R9=00000000FFFFFFF9
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR RIP=00007F82CB50AADF GS=0000 FS=0000 RSP=00007F82CC39F460
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm12 4207fffffff8016a (f: 4294443264.000000, d: 1.288490e+10)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm13 3c57c00000000000 (f: 0.000000, d: 5.149960e-18)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Module=/home/vcap/app/.java/jre/lib/amd64/compressedrefs/libj9vm29.so
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR CPU=amd64 (4 logical CPUs) (0x7daa33000 RAM)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4E869F [libj9vm29.so+0xeb69f])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4DED50 [libj9vm29.so+0xe1d50])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Java_java_lang_ClassLoader_defineClassImpl+0xa4 (0x00007F82C0D69134 [libjclse7b_29.so+0x11134])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Unhandled exception
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Type=Segmentation error vmState=0x00000000
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Handler1=00007F82CB481AA0 Handler2=00007F82CAD8BE00 InaccessibleAddress=0000000000000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR EFlags=0000000000010246 CS=0033 RBP=00007F82CC39F9B0 ERR=0000000000000004
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR TRAPNO=000000000000000E OLDMASK=0000000000000000 CR2=0000000000000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm6 1610000ab3f109b8 (f: 3018918400.000000, d: 2.041302e-202)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm11 3c4cd58858eb8000 (f: 1491828736.000000, d: 3.126201e-18)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm15 4028f40b5ed97f00 (f: 1591312128.000000, d: 1.247665e+01)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4DDEDA [libj9vm29.so+0xe0eda])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR R14=0000000000000000 R15=0000000000000000
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm0 00ff000000000000 (f: 0.000000, d: 7.063274e-304)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm2 6a003e74696e693c (f: 1768843520.000000, d: 3.978864e+202)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm7 b8d41014f309b3f1 (f: 4077499392.000000, d: -6.037435e-35)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm10 3fe0000000000000 (f: 0.000000, d: 5.000000e-01)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR ----------- Stack Backtrace -----------
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4E6C85 [libj9vm29.so+0xe9c85])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR ---------------------------------------
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR R10=0000000000000522 R11=00007F82CC39FA0C R12=0000000000000000 R13=00007F82CBB9F520
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm3 105953dd10130610 (f: 269682176.000000, d: 6.525551e-230)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm4 d91013075953130a (f: 1498616576.000000, d: -1.037698e+121)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm5 5953cc0913045953 (f: 319052128.000000, d: 2.044833e+122)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm8 0000000000000000 (f: 0.000000, d: 0.000000e+00)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm9 09b3fe01b8042e01 (f: 3087281664.000000, d: 6.348990e-262)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Module_base_address=00007F82CB3FD000
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR Target=2_90_20170901_363591 (Linux 4.4.0-75-generic)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB50AADF [libj9vm29.so+0x10dadf])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB502134 [libj9vm29.so+0x105134])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82CB4E7E64 [libj9vm29.so+0xeae64])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82C0D74DD9 [libjclse7b_29.so+0x1cdd9])
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR RDI=00007F82CC39F9B0 RSI=0000000000000000 RAX=0000000000000001 RBX=0000000000000001
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm1 0000ffffffffffff (f: 4294967296.000000, d: 1.390671e-309)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR xmm14 bc5b599f227becbb (f: 578546880.000000, d: -5.930604e-18)
   2017-11-13T12:20:03.79-0600 [APP/PROC/WEB/0] ERR (0x00007F82B053920E [<unknown>+0x0])
   2017-11-13T12:20:03.89-0600 [APP/PROC/WEB/0] OUT Exit status 255
   2017-11-13T12:20:03.92-0600 [CELL/0] OUT Exit status 0
   2017-11-13T12:20:03.94-0600 [CELL/0] OUT Destroying container
   2017-11-13T12:20:03.94-0600 [CELL/0] OUT Stopping instance 5a3e2441-bbd9-402c-5748-fd68
   2017-11-13T12:20:03.96-0600 [API/0] OUT Process has crashed with type: "web"
   2017-11-13T12:20:03.97-0600 [API/0] OUT App instance exited with guid f7a4a8ff-ebbc-49cf-96eb-37895fb88edd payload: {"instance"=>"5a3e2441-bbd9-402c-5748-fd68", "index"=>0, "reason"=>"CRASHED", "exit_description"=>"APP/PROC/WEB: Exited with status 255", "crash_count"=>4, "crash_timestamp"=>1510597203938616258, "version"=>"7ebb8072-9edc-40e3-a749-ce83273fb0d3"}

I have other apps using the liberty for java buildpack on Bluemix that are doing fine, but this app specifically has started crashing with no changes to the environment or code, and the errors are not too helpful.  I've tried increasing memory and using several different buildpacks (IBM's websphere libery as well as cloud foundry's) to no avail Any advice would be appreciated.