答:
Finally
I found the problem is My program *srversion can't be the same as before i tried.
I learned a debug method for cumulocity.

1.changed your string template in your program.
2.Using curl to get the server recieved template.
$ curl -u  https://.cumulocity.com/inventory/managedObjects/X-Id

and then check the template is the same as template in your code.

thanks for your help.

Title: cumulocity string template expand issue

Body:
I am trying to expand string template for the cumulocity data.
example ex-03-measurement.

I changed like below

//===================================================================
   10,103,POST,/measurement/measurements,application/json,,%%,NOW UNSIGNED NUMBER NUMBER NUMBER NUMBER,"{""time"":""%%"",""source"":{""id"":""%%""},""type"":""c8y_RHTMeasurement"",""c8y_RHTMeasurement"":{""RH"":{""value"":%%,""unit"":""%""},""Temperature"":{""value"":%%,""unit"":""C""},""Temperature1"":{""value"":%%,""unit"":""C""},""Temperature2"":{""value"":%%,""unit"":""C""}}}"
  //==================================================================

And I use the code like below

//==================================================================
  agent.send("103," + agent.ID() + "," + to_string(rh) + "," + to_string(temperature)+ "," + to_string(temperature)+"," + to_string(temperature));
  //==================================================================

I always get response is

Is there have any one know how to expand the data on cumulocity server?

Add software debug log

Mar 30 11:17:28 DEBUG: HTTP recv:
Mar 30 11:17:28 INFO: reporter: listening...
==============Mar 30 11:17:29 DEBUG: HTTP post: 15,24555
103,78561,86.000000,83.000000,83.000000,83.000000

Mar 30 11:17:29 DEBUG: HTTP recv: 45,2,Wrong number of arguments

Mar 30 11:17:29 DEBUG: Drop Msg 45
==============Mar 30 11:17:30 DEBUG: HTTP post: 15,24555
103,78561,15.000000,77.000000,77.000000,77.000000

Mar 30 11:17:30 DEBUG: HTTP recv: 45,2,Wrong number of arguments

Mar 30 11:17:30 DEBUG: Drop Msg 45
==============Mar 30 11:17:31 DEBUG: HTTP post: 15,24555
103,78561,35.000000,93.000000,93.000000,93.000000

Mar 30 11:17:31 DEBUG: HTTP recv: 45,2,Wrong number of arguments

Mar 30 11:17:31 DEBUG: Drop Msg 45
==============Mar 30 11:17:32 DEBUG: HTTP post: 15,24555
103,78561,92.000000,86.000000,86.000000,86.000000

Mar 30 11:17:32 DEBUG: HTTP recv: 45,2,Wrong number of arguments

Mar 30 11:17:32 DEBUG: Drop Msg 45
==============Mar 30 11:17:33 DEBUG: HTTP post: 15,24555
103,78561,21.000000,49.000000,49.000000,49.000000

Mar 30 11:17:33 DEBUG: HTTP recv: 45,2,Wrong number of arguments

Mar 30 11:17:33 DEBUG: Drop Msg 45
==============Mar 30 11:17:34 DEBUG: HTTP post: 15,24555
103,78561,27.000000,62.000000,62.000000,62.000000

Mar 30 11:17:34 DEBUG: HTTP recv: 45,2,Wrong number of arguments


来源: stackexchange

问:
Raspberry pi : Make RPI code Read and Write Protected
1) I am working on a project on Raspberry pi. Once I finished my all stuff, I want my SD card/code to be properly locked. so that no one is able to read and write code just like we locked other small microcontrollers(AVR/PIC).Please help to do that.
2) I am generating logs in my code using logging library, will I be able to write logs if my SD card/code is write/read protected.

My objective is no one be able to steal my code or make modifications to the code. What should I do to protect my code from stealing and make changes into the code?

答:
Someone correct me on this if I'm wrong but python being interpreted in most common implementations, I don't believe you're going to be able to make it unreadable.

Assuming that you are running linux on your raspberry pi, you might be able to get the tiniest bit of security using chmod 100 on it, but I do not know enough to confirm or deny this for sure.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Design Patterns for a SuperMarket system
I'm a Software Developer I who is beginning to think like a Software Developer II. I am tasked with a relatively simple Use Case for a coding challenge following as part of an interview:build a Supermarket Pricing System.

Rules and Requirements: Each item at Super Foods is identified by a
  unique four-digit code. Today, pricing schemes at Super Foods use the
  following pricing categories, but beware: prices are constantly
  changing, and the sales department is always creating new incentives
  and deals, such as buy one-get-one free.

EG: Chips and salsa (items #6732 and #4900) cost $4.99 together, but
  they cost $2.49 and $3.49 alone, respectively.

EG2: Buy two toothbrushes $1.99 each, get one free.

EG3: A bottle of wine (item #0923) costs $15.49 and is taxed an
  additional 9.25%

Having read through Design Patterns, this looks like a natural place for some form of Decorator Pattern for totaling the sales of objects. A SQLite database, with schema <ID, ObjectName, Price> will also be useful somehow, though I'm rusty on how we go about making the data access objects in all this.

I'm trying to wrap my mind around this in a full stack MVC mindset, I feel like I might be rusty on something. Is this what the Spring Framework is renowned for? Maybe an even better API for this use case can be recommended?

Thank you for anyone helping me to brainstorm the design of this system out.

答:
possible steps:

define database model

mirror db model in Java

implement DAO layer -> CRUD operations

implement Service layer -> bussiness logic

expose service layer -> e.g. REST

implement client side which is client towards exposed Service layer


问:
gstreamer command to compose (pip) two videos
What command should I execute in gstreamer in order to compose two 320x240 videos into a single 640x240 side-by-side video?

let's say I have video1.avi and video2.avi

答:
videomixer plugin to the rescue:</p>

```<code>gst-launch -v \
filesrc location=video1.avi ! avidemux name=demux1 \
filesrc location=video2.avi ! avidemux name=demux2 \
videomixer name=mix \
        sink_0::xpos=0   sink_0::ypos=0 sink_0::alpha=0 \
        sink_1::xpos=0   sink_1::ypos=0 \
        sink_2::xpos=320 sink_2::ypos=0 \
    ! xvimagesink \
videotestsrc pattern="black" \
    ! video/x-raw-yuv,width=640,height=240 \
    ! mix.sink_0 \
demux1.video_00 \
    ! queue ! decodebin ! ffmpegcolorspace ! videoscale \
    ! video/x-raw-yuv,width=320,height=240 \
    ! mix.sink_1 \
demux2.video_00 \
    ! queue ! decodebin ! ffmpegcolorspace ! videoscale \
    ! video/x-raw-yuv,width=320,height=240 \
    ! mix.sink_2 \
</code>```

ContentLicense: CC BY-SA 2.5

Body:
videomixer plugin to the rescue:

gst-launch -v \
filesrc location=video1.avi ! avidemux name=demux1 \
filesrc location=video2.avi ! avidemux name=demux2 \
videomixer name=mix \
        sink_0::xpos=0   sink_0::ypos=0 sink_0::alpha=0 \
        sink_1::xpos=0   sink_1::ypos=0 \
        sink_2::xpos=320 sink_2::ypos=0 \
    ! xvimagesink \
videotestsrc pattern="black" \
    ! video/x-raw-yuv,width=640,height=240 \
    ! mix.sink_0 \
demux1.video_00 \
    ! queue ! decodebin ! ffmpegcolorspace ! videoscale \
    ! video/x-raw-yuv,width=320,height=240 \
    ! mix.sink_1 \
demux2.video_00 \
    ! queue ! decodebin ! ffmpegcolorspace ! videoscale \
    ! video/x-raw-yuv,width=320,height=240 \
    ! mix.sink_2 \


问:
Getting post web service response as undefined in angularjs
```<code> app.controller("blankCtrl", ['$scope', '$http', '$parse',
    function($scope, $http, $parse) {
        $scope.login = function() {
            $scope.spice = 'tooo';
            alert("hiii");
            $.ajax({
                url : "http://edudux.com/manage/index.php?/api/login",
                dataType:"json",
                success:function(data)
                {
                    alert("mobile:"+data.mobile+"\npassword:"+data.password);
                }
            });
        }
    }]);
</code>```

I am getting post web service response as undefined after executing above code.I am using angularjs to build cross platform project.

答:
Although as suggested in the comments that angular does have a $http module which can be used for the async requests. Yet if i see your code as you mentioned POST request which it does not seem to be because you are missing the type:"POST".

You can use it in angular way with $http:

```<code>$http({
    url : "http://edudux.com/manage/index.php?/api/login",
    method: 'POST'
}).then(function(response){
    console.log(response.data);
});
</code>```

Body:
 app.controller("blankCtrl", ['$scope', '$http', '$parse',
    function($scope, $http, $parse) {
        $scope.login = function() {
            $scope.spice = 'tooo';
            alert("hiii");
            $.ajax({
                url : "http://edudux.com/manage/index.php?/api/login",
                dataType:"json",
                success:function(data)
                {
                    alert("mobile:"+data.mobile+"\npassword:"+data.password);
                }
            });
        }
    }]);

I am getting post web service response as undefined after executing above code.I am using angularjs to build cross platform project.

Body:
Although as suggested in the comments that angular does have a $http module which can be used for the async requests. Yet if i see your code as you mentioned POST request which it does not seem to be because you are missing the type:"POST".

You can use it in angular way with $http:

$http({
    url : "http://edudux.com/manage/index.php?/api/login",
    method: 'POST'
}).then(function(response){
    console.log(response.data);
});


问:
purrr::discard How to delete elements in a vector containing one or more specific strings
I would like to remove the elements containing '_1' and '_3' in the vector using the discard function from purrr. Here the example:

```<code>library(purrr)
x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")
</code>```

答:
With discard we need to provide a logical vector indicating which values we need to discard.

To create a logical vector we use grepl giving TRUE values to the elements which have '_1' or '_3'

```<code>library(purrr)
discard(x, grepl("_1|_3", x))

#[1] "ZDRF73"  "FGSH41"  "JHSC_29"
</code>```

and as @Lazarus Thurston commented using str_subset should be a better choice here.

```<code>str_subset(x, '_(1|3)', negate = TRUE)
</code>```

Body:
I would like to remove the elements containing '_1' and '_3' in the vector using the discard function from purrr. Here the example:

library(purrr)
x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")

Body:
With discard we need to provide a logical vector indicating which values we need to discard.

To create a logical vector we use grepl giving TRUE values to the elements which have '_1' or '_3'

library(purrr)
discard(x, grepl("_1|_3", x))

#[1] "ZDRF73"  "FGSH41"  "JHSC_29"

and as @Lazarus Thurston commented using str_subset should be a better choice here.

str_subset(x, '_(1|3)', negate = TRUE)


问:
Injecting arguments in scrapy's pipeline
I have a custom pipeline with some arguments that i need to inject in the constructor, like:

```<code>class MyPipeline(object):
    def __init__(self, some_argument):
        self.some_argument = some_argument
...
</code>```

The script (let's call it run_crawler.py) from where I start the crawling process it's:

```<code>process = CrawlerProcess(get_project_settings())

process.crawl(SomeCrawler)
process.crawl(AnotherCrawler)
...
process.start()
</code>```

And in settings.py:

```<code>ITEM_PIPELINES = {
    'crawler.pipelines.SomePipeline': 100,
    'crawler.pipelines.MyPipeline': 300
}
</code>```

I guess this is a silly question but i've been unable to find in the docs how to instantiate MyPipeline with custom arguments. Could someone plz point me in the right direction?

In particular, i don't know how should (or if i should at all) modify run_crawler.py to instantiate the custom argument for MyPipeline, i'm guessing it should be something like:

```<code>process = CrawlerProcess(get_project_settings())

process.crawl(SomeCrawler)
process.crawl(AnotherCrawler)
...
some_argument = ... # instantiate my custom argument
# this is made up, it's what i've been unable to find how to do properly
my_pipeline = MyPipeline(some_argument)
process.pipelines.append(my_pipeline, ...)

process.start()
</code>```

答:
You can use the scrapy from_crawler method.
The scrapy docs have a good description and example:

```<code>class MongoPipeline(object):

    collection_name = 'scrapy_items'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )
</code>```

"If present, this classmethod is called to create a pipeline instance from a Crawler. It must return a new instance of the pipeline."

This way you can create new instance of the pipeline depend of the crawler or spider settings.

Body:
I have a custom pipeline with some arguments that i need to inject in the constructor, like:

class MyPipeline(object):
    def __init__(self, some_argument):
        self.some_argument = some_argument
...

The script (let's call it run_crawler.py) from where I start the crawling process it's:

process = CrawlerProcess(get_project_settings())

process.crawl(SomeCrawler)
process.crawl(AnotherCrawler)
...
process.start()

And in settings.py:

ITEM_PIPELINES = {
    'crawler.pipelines.SomePipeline': 100,
    'crawler.pipelines.MyPipeline': 300
}

I guess this is a silly question but i've been unable to find in the docs how to instantiate MyPipeline with custom arguments. Could someone plz point me in the right direction?

In particular, i don't know how should (or if i should at all) modify run_crawler.py to instantiate the custom argument for MyPipeline, i'm guessing it should be something like:

process = CrawlerProcess(get_project_settings())

process.crawl(SomeCrawler)
process.crawl(AnotherCrawler)
...
some_argument = ... # instantiate my custom argument
# this is made up, it's what i've been unable to find how to do properly
my_pipeline = MyPipeline(some_argument)
process.pipelines.append(my_pipeline, ...)

process.start()

Body:
You can use the scrapy from_crawler method.
The scrapy docs have a good description and example:

class MongoPipeline(object):

    collection_name = 'scrapy_items'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )

"If present, this classmethod is called to create a pipeline instance from a Crawler. It must return a new instance of the pipeline."

This way you can create new instance of the pipeline depend of the crawler or spider settings.


问:
I got Initialization error in Cucumber with maven and selenium
Test Runner

import org.junit.runner.RunWith;

```<code>import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {

}
</code>```

MyApplication.feature

```<code>Feature: Test test smoke scenario

  Scenario Outline: Test  login with valid credentials
    Given open fireFox and start application
    When I enter valid "username" and valid "password"
    Then User should be able to login successfully

Examples:
      | username   | password          |
      | 9739817000 | mnbvcxz  |
      | 9739817001 | mnbvcxz1  |
      | 9739817002 | mnbvcxz2  |
</code>```

Maven POM

```<code><groupId>demo</groupId>
  <artifactId>prac</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>prac</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
</dependency>
</dependencies>
</project>
</code>```

Smoke.java

```<code>public class Smoke {
    WebDriver driver;
    @Given("^open fireFox and start application$")
    public void open_fireFox_and_start_application() throws Throwable {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://testweb.com");

    }

    @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();

    }

    @When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
    public void enter_valid_and_valid(String un, String pwd) throws Throwable {
        driver.findElement(By.id("Username")).sendKeys(un);
        driver.findElement(By.id("Password")).sendKeys(pwd);

    }

    @Then("^Click on Login$")
    public void Click_on_Login() throws Throwable {
        driver.findElement(By.id("loginUser")).click();

    }
    @Then("^User should be able to login successfully$")
    public void User_should_be_able_to_login_successfully() throws Throwable {

    }
</code>```

These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error

enter image description here

答:
Scenario Outline is used to pass different sets of input data to your scenario. For instance 'ABC' and 'PWD' are your username, password respectively then update your feature file as below,</p>

```<code>Feature: Test Milacron smoke scenario
Scenario Outline: Test  login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully

Examples:
 | username      | password |
 | ABC           |  PWD     |
</code>```

Body:
Test Runner

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {

}

MyApplication.feature

Feature: Test test smoke scenario

  Scenario Outline: Test  login with valid credentials
    Given open fireFox and start application
    When I enter valid "username" and valid "password"
    Then User should be able to login successfully

Examples:
      | username   | password          |
      | 9739817000 | mnbvcxz  |
      | 9739817001 | mnbvcxz1  |
      | 9739817002 | mnbvcxz2  |

Maven POM

<groupId>demo</groupId>
  <artifactId>prac</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>prac</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
</dependency>
</dependencies>
</project>

Smoke.java

public class Smoke {
    WebDriver driver;
    @Given("^open fireFox and start application$")
    public void open_fireFox_and_start_application() throws Throwable {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://testweb.com");

    }

    @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();

    }

    @When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
    public void enter_valid_and_valid(String un, String pwd) throws Throwable {
        driver.findElement(By.id("Username")).sendKeys(un);
        driver.findElement(By.id("Password")).sendKeys(pwd);

    }

    @Then("^Click on Login$")
    public void Click_on_Login() throws Throwable {
        driver.findElement(By.id("loginUser")).click();

    }
    @Then("^User should be able to login successfully$")
    public void User_should_be_able_to_login_successfully() throws Throwable {

    }

These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error

enter image description here

Body:
Scenario Outline is used to pass different sets of input data to your scenario. For instance 'ABC' and 'PWD' are your username, password respectively then update your feature file as below,

Feature: Test Milacron smoke scenario
Scenario Outline: Test  login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully

Examples:
 | username      | password |
 | ABC           |  PWD     |


问:
Test post service jasmine karma angular js
I new to Unit testing and trying to run the test cases but always getting an error Unexpected request POST service
Below is my code

angular service

```<code> angular
    .module('testModule')
    .factory('testService', testService)

  testService.$inject = ['$q', '$http'];

  function testService($q, $http){

    return {
      getAll: function(obj){
        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        let deferred = $q.defer();
        let payload = 'keyQueryParam=' + obj

        $http.post('url', payload, config.headers).then(response => {
          deferred.resolve(response.contents)
        })

        return deferred.promise;
      }
    }
  }
</code>```

Unit test

```<code>describe('Test Service', function(){
    let mockTestFactory, httpBackend;

    beforeEach(function(){
        angular.mock.module('testModule');
    });

    beforeEach(inject(function($httpBackend, _testService_){
        httpBackend = $httpBackend;
        mockTestFactory= _testService_;
    }));

    it('Return a POST response from a Service function', function(){
        var url = "http://localhost:3000/";
        var obj = ['ret-2','ret-5','ret-6'];
        let payload = 'keyQueryParam=' + obj

        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        httpBackend
            .when('POST','url', payload, function(config.headers) {
                expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
                return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
            })
            .respond(200, { status : "success"});

        mockTestFactory.getAll(obj).then(function(response) {
            console.log(response);
        });

        httpBackend.flush();
        expect(true).toBe(true);
    });
});
</code>```

thanks in advance

答:
If your call is POST then use 201 status code as below

```<code>  httpBackend
    .when('POST', 'url', payload, function(config.headers) {
      expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
      return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
    })
    .respond(201, {
      status: "success"
    });
</code>```

Now try it should run.

Body:
I new to Unit testing and trying to run the test cases but always getting an error Unexpected request POST service
Below is my code

angular service

 angular
    .module('testModule')
    .factory('testService', testService)

  testService.$inject = ['$q', '$http'];

  function testService($q, $http){

    return {
      getAll: function(obj){
        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        let deferred = $q.defer();
        let payload = 'keyQueryParam=' + obj

        $http.post('url', payload, config.headers).then(response => {
          deferred.resolve(response.contents)
        })

        return deferred.promise;
      }
    }
  }

Unit test

describe('Test Service', function(){
    let mockTestFactory, httpBackend;

    beforeEach(function(){
        angular.mock.module('testModule');
    });

    beforeEach(inject(function($httpBackend, _testService_){
        httpBackend = $httpBackend;
        mockTestFactory= _testService_;
    }));

    it('Return a POST response from a Service function', function(){
        var url = "http://localhost:3000/";
        var obj = ['ret-2','ret-5','ret-6'];
        let payload = 'keyQueryParam=' + obj

        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        httpBackend
            .when('POST','url', payload, function(config.headers) {
                expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
                return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
            })
            .respond(200, { status : "success"});

        mockTestFactory.getAll(obj).then(function(response) {
            console.log(response);
        });

        httpBackend.flush();
        expect(true).toBe(true);
    });
});

thanks in advance

Body:
If your call is POST then use 201 status code as below

  httpBackend
    .when('POST', 'url', payload, function(config.headers) {
      expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
      return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
    })
    .respond(201, {
      status: "success"
    });

Now try it should run.


问:
how to "npm start" with pm2 cluster mode
this commend start pm2 with cluster mode.

```<code>$ pm2 start [app] -i 0
</code>```

this commend npm start with pm2 process.

```<code>$ pm2 start npm -- start
</code>```

So I want npm start of cluster mode.

```<code>$ pm2 start npm -- start -i 0
</code>```

But "npm start" don't start cluster mode.

How to "npm start" with cluster mode on pm2 ?

答:
the command line you have above does not seem to be correct. You wrote:

$ pm2 start npm -- start -i 0

it should be

$ pm2 start  app.js -i 0

from the docs

I would strongly suggest using a pm2.json configuration file so you can place all your needed parameters inside and start PM2 with the Json file.

To check if PM2 is actually in cluster mode:
PM2 list all or PM2 describe [name of app]
This will show you detailed information on the running apps.

Hope this helps

Body:
this commend start pm2 with cluster mode.

$ pm2 start [app] -i 0

this commend npm start with pm2 process.

$ pm2 start npm -- start

So I want npm start of cluster mode.

$ pm2 start npm -- start -i 0

But "npm start" don't start cluster mode.

How to "npm start" with cluster mode on pm2 ?


问:
replace multiple connecting instances of
 with one single
 php
I am stripping HTML and replacing all
 and
 tags with
 tags. Problem is that I am left with random
 tags like

```<code><br /><br /><br />
<br /><br />
<br /><br /><br /><br />
</code>```

I am taking the body of an email and stripping tags like

```<code>$comment = strip_tags($comment,'<div><p>');
$comment = preg_replace("/<p[^>]*?>/", "", $comment);
$comment = str_replace("</p>", "<br />", $comment);
$comment = preg_replace("/<div[^>]*?>/", "", $comment);
$comment = str_replace("</div>", "<br />", $comment);
</code>```

I want to be able to replace any instance of at least 2
 tags next to each other with one single
 tag. At this point every
 will match exactly as I have shown, but...there is a possibility that they can vary like
,
 so just need to make sure that I can replace any type of br tag (when there are at least 2 of them) with one single one when they are sequentially repeated next to each other.

The "possibility" of a br tag looking like
 is based on if it was already in the original HTML that I did not catch. I know I can do a str_replace("
", "
", $comment) but I was hoping to shorten my code and not add more lines.

Any idea how to do this? Im sure there is regex involved and preg_replace but not sure where to start.

答:
When you run $comment = strip_tags($comment, '

'), there will be no
 left as it is not an allowed tag. So the only
 would be from your four replacements below. You only need to care about the form "
" in the other words. But handling just
 vs. all other
 form aren't much different in difficulty.

Anyway, you could use:

```<code>$comment = preg_replace('/(\s*<br[^>]*>){2,}/', '\1', $comment);
</code>```

]*> — match any kind of
 tag

\s*
]*> — match zero or more whitespaces before the
 tag

(\s*
]*>) — group this regex and capture into \1

(…){2,} — match two or more such groups.

The replacement will keep the last
 found.

Body:
I am stripping HTML and replacing all
 and
 tags with
 tags. Problem is that I am left with random
 tags like

I am taking the body of an email and stripping tags like

$comment = strip_tags($comment,'

');
$comment = preg_replace("/
]*?>/", "", $comment);
$comment = str_replace("
", "
", $comment);
$comment = preg_replace("/
]*?>/", "", $comment);
$comment = str_replace("
", "
", $comment);

I want to be able to replace any instance of at least 2
 tags next to each other with one single
 tag. At this point every
 will match exactly as I have shown, but...there is a possibility that they can vary like
,
 so just need to make sure that I can replace any type of br tag (when there are at least 2 of them) with one single one when they are sequentially repeated next to each other.

The "possibility" of a br tag looking like
 is based on if it was already in the original HTML that I did not catch. I know I can do a str_replace("
", "
", $comment) but I was hoping to shorten my code and not add more lines.

Any idea how to do this? Im sure there is regex involved and preg_replace but not sure where to start.

Body:
When you run $comment = strip_tags($comment, '<div><p>'), there will be no <br> left as it is not an allowed tag. So the only <br /> would be from your four replacements below. You only need to care about the form "<br />" in the other words. But handling just <br /> vs. all other <br> form aren't much different in difficulty.

Anyway, you could use:

$comment = preg_replace('/(\s*<br[^>]*>){2,}/', '\1', $comment);

<br[^>]*> — match any kind of <br> tag

\s*<br[^>]*> — match zero or more whitespaces before the <br> tag

(\s*<br[^>]*>) — group this regex and capture into \1

(…){2,} — match two or more such groups.

The replacement will keep the last <br> found.


问:
How to overwrite a tag for a named entity with CoreNLP's RegexNER without specifying the original tag
I know that CoreNLP's RegexNER allows me to overwrite a tag using the mapping file. For example; I have the word EGFR which CoreNLP recognizes as an ORGANIZATION. If I have the following line in my mapping file, it still tags it as an ORGANIZATION.

EGFR    GENE

If I change that line to look like the following:

EGFR    GENE     ORGANIZATION

Then CoreNLP tags it as a GENE.

To be able to do this though, I have to know that CoreNLP tags EGFR as an ORGANIZATION and I can't always know that for every word in my mapping file. Now my question is, is there a way to tell the RegexNER to overwrite the tag for EGFR no matter what the original tag is? Something like

EGFR    GENE    .*

答:
You can provide a comma separated list of tags that can be overwritten.

For instance:

```<code>ORGANIZATION,PERSON,LOCATION,MISC
</code>```

will allow it to overwrite all of those tags.

I don't think there is an overwrite all option at the moment, so you do have to list each type you want overwritten.

If you always want to overwrite everything with what is in your rules you can supply that with this option to the TokensRegexNERAnnotator

```<code>regexner.backgroundSymbol ORGANIZATION,PERSON,LOCATION,MISC,O
</code>```

And then each rule doesn't have to have a list.

Body:
You can provide a comma separated list of tags that can be overwritten.

For instance:

ORGANIZATION,PERSON,LOCATION,MISC

will allow it to overwrite all of those tags.

I don't think there is an overwrite all option at the moment, so you do have to list each type you want overwritten.

If you always want to overwrite everything with what is in your rules you can supply that with this option to the TokensRegexNERAnnotator

regexner.backgroundSymbol ORGANIZATION,PERSON,LOCATION,MISC,O

And then each rule doesn't have to have a list.


问:
Hangman System.IO.IOException' occurred in mscorlib.dll
i am creating a hangman game that is to be used on a few computers, i have created the hangman game itself but i am using the "load form" function to create the list when the program first starts, but i am having this issue.

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'h:\Bryson\words.txt' because it is being used by another process.

```<code>Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
</code>```

^^that line is where the error pops up^^

I have inserted some in code Comments to make life easier. If anyone can help thanks in advance :)

```<code>'USED TO CREATE HANGMAN FILE IF NOT FOUND
    Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    fofound = False
    fifound = False
    MsgBox("remove this and change file path and fix qu2 quiz")
    'DESIGNER USE
    Dim path As String = "h:\Bryson\words.txt"
    'CREATE VAR FOR PATH
    If System.IO.Directory.Exists("h:\Bryson") Then
        'CHECKS IF FOLDER EXISTS
        fofound = True
    Else
        'IF IT DOES THEN IT MOVES ON
        System.IO.Directory.CreateDirectory("h:\Bryson")
        'IF NOT IT CREATES THE FOLDER
        fofound = True
        If File.Exists("h:\Bryson\test\words.txt") Then
            'CHECKS IF FILE EXISTS
            fifound = True
        Else
            'IF IT DOES IT MOVES ON
            IO.File.Create("h:\Bryson\words.txt")
            'IF NOT IT CREATES IT
            FileClose()

        End If

    End If
    If fofound And fifound = True Then
    Else
        Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
            'CRASH POINT The process cannot access the file 'C:\Bryson\words.txt'
            'because it Is being used by another process.
            sw.WriteLine("Hangman")
            sw.WriteLine("computer")
            sw.WriteLine("electrode")
            sw.WriteLine("independent")
            sw.WriteLine("stream")
            sw.WriteLine("enforcing")
        End Using
        'WRITES TO FILE
        MsgBox("file created")
        'DESIGNER USE
        FileClose()
        'CLOSES FILE
    End If
End Sub
</code>```

答:
FileClose() is a legacy function from VB6 and will not affect anything in the System.IO namespace. To close a file you need to call .Close() or .Dispose() on the stream that has opened the file (wrapping the stream in a Using block does this automatically).

Your problem is this line:

```<code>IO.File.Create("h:\Bryson\words.txt")
</code>```

The method creates a new file and opens a FileStream to it which locks the file. Since you never close the returned FileStream your file will remain locked until you close your application.

The File.Create() call is completely unnecessary though because File.CreateText() will create the file if it doesn't exist. So you should just remove the above line.

Body:
i am creating a hangman game that is to be used on a few computers, i have created the hangman game itself but i am using the "load form" function to create the list when the program first starts, but i am having this issue.

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'h:\Bryson\words.txt' because it is being used by another process.

Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")

^^that line is where the error pops up^^

I have inserted some in code Comments to make life easier. If anyone can help thanks in advance :)

'USED TO CREATE HANGMAN FILE IF NOT FOUND
    Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    fofound = False
    fifound = False
    MsgBox("remove this and change file path and fix qu2 quiz")
    'DESIGNER USE
    Dim path As String = "h:\Bryson\words.txt"
    'CREATE VAR FOR PATH
    If System.IO.Directory.Exists("h:\Bryson") Then
        'CHECKS IF FOLDER EXISTS
        fofound = True
    Else
        'IF IT DOES THEN IT MOVES ON
        System.IO.Directory.CreateDirectory("h:\Bryson")
        'IF NOT IT CREATES THE FOLDER
        fofound = True
        If File.Exists("h:\Bryson\test\words.txt") Then
            'CHECKS IF FILE EXISTS
            fifound = True
        Else
            'IF IT DOES IT MOVES ON
            IO.File.Create("h:\Bryson\words.txt")
            'IF NOT IT CREATES IT
            FileClose()

        End If

    End If
    If fofound And fifound = True Then
    Else
        Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
            'CRASH POINT The process cannot access the file 'C:\Bryson\words.txt'
            'because it Is being used by another process.
            sw.WriteLine("Hangman")
            sw.WriteLine("computer")
            sw.WriteLine("electrode")
            sw.WriteLine("independent")
            sw.WriteLine("stream")
            sw.WriteLine("enforcing")
        End Using
        'WRITES TO FILE
        MsgBox("file created")
        'DESIGNER USE
        FileClose()
        'CLOSES FILE
    End If
End Sub

Body:
FileClose() is a legacy function from VB6 and will not affect anything in the System.IO namespace. To close a file you need to call .Close() or .Dispose() on the stream that has opened the file (wrapping the stream in a Using block does this automatically).

Your problem is this line:

IO.File.Create("h:\Bryson\words.txt")

The method creates a new file and opens a FileStream to it which locks the file. Since you never close the returned FileStream your file will remain locked until you close your application.

The File.Create() call is completely unnecessary though because File.CreateText() will create the file if it doesn't exist. So you should just remove the above line.


问:
C# Regex.Split - Would like to split a string by a char but allow the char to be used between ' and '
I would like to split a string by / but also allow anything between ' and ' to contain my split character. While removing the ' and ' from the split and any blanks.

example /'TEST/:1'/3 is split into

Test/:1

3

I have something close:

```<code>regex.split(test, "/(?=(?:[^']*'[^']*')*[^']*$)"
</code>```

but it still has the ' and blanks in it.

```<code>string[] fields = Regex.Split(Path, "/(?=(?:[^']*'[^']*')*[^']*$)");
</code>```

Sorry I well be more clear its my own pathing format for parsing EDI like file it works like this. /Location:LineNumber/YPosition. All I want to do so is get in a command line /TEST:4/6 = /Location(Test):LineNumber(4)/YPosition(6). but my problem is that the Location is worked out by my code and could be anything up to the first delimiter. It could be a date format 12/03/03 which is common in EDI type files.

I would like to be able to get my command looking like this /'12/03/03':4/6 so that when the Location is split by my regex.split it does not include anything between the (' and ') location.

Any help please?

答:
```<code>class Program
    {
        static void Main(string[] args)
        {
            string input = "\"\"/one/\"two/threefour\"/five//";

            var separator = "/";

            var empty = "(?<empty>\\s*)";

            var word = string.Format("(?<word>[^{0}]+)",  separator);
            var quotedWord = "(?<word>[^\\\"]+)";

            var token = string.Format("((\"({0}|{1})\")|({0}|{2}))",empty, quotedWord, word);

            var pattern = string.Format("({0}/)+({0})", token);

            foreach (var capture in Regex.Match(input, pattern).Groups["word"].Captures)
                Console.WriteLine(capture);

        }

    }
</code>```

Body:
I would like to split a string by / but also allow anything between ' and ' to contain my split character. While removing the ' and ' from the split and any blanks.

example /'TEST/:1'/3 is split into

Test/:1

3

I have something close:

regex.split(test, "/(?=(?:[^']*'[^']*')*[^']*$)"

but it still has the ' and blanks in it.

string[] fields = Regex.Split(Path, "/(?=(?:[^']*'[^']*')*[^']*$)");

Sorry I well be more clear its my own pathing format for parsing EDI like file it works like this. /Location:LineNumber/YPosition. All I want to do so is get in a command line /TEST:4/6 = /Location(Test):LineNumber(4)/YPosition(6). but my problem is that the Location is worked out by my code and could be anything up to the first delimiter. It could be a date format 12/03/03 which is common in EDI type files.

I would like to be able to get my command looking like this /'12/03/03':4/6 so that when the Location is split by my regex.split it does not include anything between the (' and ') location.

Any help please?


问:
Port exhaustion issue with Akka.Cluster
We created an Akka Cluster infrastructure for Sms, Email and Push notifications. 3 different kind of nodes are exist in the system, which are client, sender and lighthouse. Client role is being used by Web application and API application(Web and API is hosted at IIS). Lighthouse and Sender roles are being hosted as a Windows service. We are also running 4 more console applications of same windows service that in sender role.

We've been experiencing port exhaustion problems in our Web Server for about 2 weeks. Our Web Server starting to consume the ports quickly and after a while we can not do any SQL operations.
Sometimes we have no choice but to do iis reset. This problems occur if there are more than one nodes that in sender role. We diagnosed it and found the source of the problem.

```<code>---------------
HOST                  OPEN    WAIT
SRV_NOTIFICATION      3429    0
SRV_LOCAL             198     0
SRV_UNDEFINED_IPV4    23      0
SRV_DATABASE          15      0
SRV_AUTH              4       0
SRV_API               6       0
SRV_UNDEFINED_IPV6    19      0
SRV_INBOUND           12347   5

TotalPortsInUse   : 17286
MaxUserPorts      : 64510
TcpTimedWaitDelay : 30
03/23/2017 09:30:10
---------------
</code>```

SRV_NOTIFICATION is server that lighthouse ve sender's nodes running. SRV_INBOUND is our Web Server. After checking this table, we checked what ports on the Web Server were assigned.
And we got results like table below. In netstat there were more than 12000 connections like this :

```<code>TCP    192.168.1.10:65531     192.168.1.10:3564      ESTABLISHED     5716   [w3wp.exe]
TCP    192.168.1.10:65532     192.168.1.101:17527    ESTABLISHED     5716   [w3wp.exe]
TCP    192.168.1.10:65533     192.168.1.101:17527    ESTABLISHED     5716   [w3wp.exe]
TCP    192.168.1.10:65534     192.168.1.10:3564      ESTABLISHED     5716   [w3wp.exe]
</code>```

192.168.1.10 Web Server
192.168.1.10:3564 API
192.168.1.101:17527 Lighthouse

The connections are opening but not closing.

After deployments our Web and Api applications are leaving and rejoining to do cluster and they configured for fixed ports. We're monitoring our cluster with application that created by @cgstevens. Even we implemented the grecaful shutdown logic for Actor System sometimes WEB and API applications cant leave the cluster so we have to remove nodes manualy and restart the actor system.

We have reproduce the problem in our development environment and recorded a video below

https://drive.google.com/file/d/0B5ZNfLACId3jMWUyOWliMUhNWTQ/view

Our hocon configuration for nodes are below :

WEB and API

```<code><akka>
    <hocon><![CDATA[
            akka{
                loglevel = DEBUG

                actor{
                    provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"

                    deployment {
                        /coordinatorRouter {
                            router = round-robin-group
                            routees.paths = ["/user/NotificationCoordinator"]
                            cluster {
                                    enabled = on
                                    max-nr-of-instances-per-node = 1
                                    allow-local-routees = off
                                    use-role = sender
                            }
                        }

                        /decidingRouter {
                            router = round-robin-group
                            routees.paths = ["/user/NotificationDeciding"]
                            cluster {
                                    enabled = on
                                    max-nr-of-instances-per-node = 1
                                    allow-local-routees = off
                                    use-role = sender
                            }
                        }
                    }

                    serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                    }

                    serialization-bindings {
                     "System.Object" = wire
                    }

                    debug{
                        receive = on
                        autoreceive = on
                        lifecycle = on
                        event-stream = on
                        unhandled = on
                    }
                }

                remote {
                    helios.tcp {
                            transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                            applied-adapters = []
                            transport-protocol = tcp
                            hostname = "192.168.1.10"
                            port = 3564
                    }
                }

                cluster {
                        seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [client]
                }
            }
        ]]>
    </hocon>
</akka>
</code>```

Lighthouse

```<code><akka>
    <hocon>
        <![CDATA[
                lighthouse{
                        actorsystem: "notificationSystem"
                    }

                akka {
                    actor {
                        provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"

                        serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                        }

                        serialization-bindings {
                            "System.Object" = wire
                        }
                    }

                    remote {
                        log-remote-lifecycle-events = DEBUG
                        helios.tcp {
                            transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                            applied-adapters = []
                            transport-protocol = tcp
                            #will be populated with a dynamic host-name at runtime if left uncommented
                            #public-hostname = "192.168.1.100"
                            hostname = "192.168.1.101"
                            port = 17527
                        }
                    }

                    loggers = ["Akka.Logger.NLog.NLogLogger,Akka.Logger.NLog"]

                    cluster {
                        seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [lighthouse]
                    }
                }
        ]]>
    </hocon>
</akka>
</code>```

Sender

```<code><akka>
    <hocon><![CDATA[
                akka{
                    # stdout-loglevel = DEBUG
                    loglevel = DEBUG
                    # log-config-on-start = on

                    loggers = ["Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog"]

                    actor{
                        debug {
                            # receive = on
                            # autoreceive = on
                            # lifecycle = on
                            # event-stream = on
                            # unhandled = on
                        }

                        provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"

                        serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                        }

                        serialization-bindings {
                         "System.Object" = wire
                        }

                        deployment{
                            /NotificationCoordinator/LoggingCoordinator/DatabaseActor{
                                router = round-robin-pool
                                resizer{
                                    enabled = on
                                    lower-bound = 3
                                    upper-bound = 5
                                }
                            }

                            /NotificationDeciding/NotificationDecidingWorkerActor{
                                router = round-robin-pool
                                resizer{
                                    enabled = on
                                    lower-bound = 3
                                    upper-bound = 5
                                }
                            }

                            /ScheduledNotificationCoordinator/SendToProMaster/JobToProWorker{
                                router = round-robin-pool
                                resizer{
                                    enabled = on
                                    lower-bound = 3
                                    upper-bound = 5
                                }
                            }
                        }
                    }

                 remote{
                            log-remote-lifecycle-events = DEBUG
                            log-received-messages = on

                            helios.tcp{
                                transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                                applied-adapters = []
                                transport-protocol = tcp
                                #will be populated with a dynamic host-name at runtime if left uncommented
                                #public-hostname = "POPULATE STATIC IP HERE"
                                hostname = "192.168.1.101"
                                port = 0
                        }
                    }

                    cluster {
                        seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [sender]
                    }
                }
            ]]></hocon>
</akka>
</code>```

Cluster.Monitor

```<code><akka>
    <hocon>
        <![CDATA[
                akka {
                    stdout-loglevel = INFO
                    loglevel = INFO
                    log-config-on-start = off

                    actor {
                        provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"

                        serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                        }
                        serialization-bindings {
                            "System.Object" = wire
                        }

                        deployment {
                            /clustermanager {
                                dispatcher = akka.actor.synchronized-dispatcher
                            }
                        }
                    }

                    remote {
                        log-remote-lifecycle-events = INFO
                        log-received-messages = off
                        log-sent-messages = off

                        helios.tcp {
                            transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                            applied-adapters = []
                            transport-protocol = tcp
                            #will be populated with a dynamic host-name at runtime if left uncommented
                            #public-hostname = "127.0.0.1"
                            hostname = "192.168.1.101"
                            port = 0
                        }
                    }

                    cluster {
                    seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [ClusterManager]

                        client {
                            initial-contacts = ["akka.tcp://notificationSystem@192.168.1.101:17527/system/receptionist"]
                        }
                    }
                }
        ]]>
    </hocon>
</akka>
</code>```

答:
This is a confirmed bug and probably will be fixed with CoordinatedShutdown feature in Akka.Net V1.2

https://github.com/akkadotnet/akka.net/issues/2575

You can use the latest nightly builds until 1.2 released

http://getakka.net/docs/akka-developers/nightly-builds

Edit : Akka.Net V1.2 released but this bug postponed to V1.3.

https://github.com/akkadotnet/akka.net/milestone/14

Title: Port exhaustion issue with Akka.Cluster

Body:
We created an Akka Cluster infrastructure for Sms, Email and Push notifications. 3 different kind of nodes are exist in the system, which are client, sender and lighthouse. Client role is being used by Web application and API application(Web and API is hosted at IIS). Lighthouse and Sender roles are being hosted as a Windows service. We are also running 4 more console applications of same windows service that in sender role.

We've been experiencing port exhaustion problems in our Web Server for about 2 weeks. Our Web Server starting to consume the ports quickly and after a while we can not do any SQL operations.
Sometimes we have no choice but to do iis reset. This problems occur if there are more than one nodes that in sender role. We diagnosed it and found the source of the problem.

---------------
HOST                  OPEN    WAIT
SRV_NOTIFICATION      3429    0
SRV_LOCAL             198     0
SRV_UNDEFINED_IPV4    23      0
SRV_DATABASE          15      0
SRV_AUTH              4       0
SRV_API               6       0
SRV_UNDEFINED_IPV6    19      0
SRV_INBOUND           12347   5

TotalPortsInUse   : 17286
MaxUserPorts      : 64510
TcpTimedWaitDelay : 30
03/23/2017 09:30:10
---------------

SRV_NOTIFICATION is server that lighthouse ve sender's nodes running. SRV_INBOUND is our Web Server. After checking this table, we checked what ports on the Web Server were assigned.
And we got results like table below. In netstat there were more than 12000 connections like this :

TCP    192.168.1.10:65531     192.168.1.10:3564      ESTABLISHED     5716   [w3wp.exe]
TCP    192.168.1.10:65532     192.168.1.101:17527    ESTABLISHED     5716   [w3wp.exe]
TCP    192.168.1.10:65533     192.168.1.101:17527    ESTABLISHED     5716   [w3wp.exe]
TCP    192.168.1.10:65534     192.168.1.10:3564      ESTABLISHED     5716   [w3wp.exe]

192.168.1.10 Web Server
192.168.1.10:3564 API
192.168.1.101:17527 Lighthouse

The connections are opening but not closing.

After deployments our Web and Api applications are leaving and rejoining to do cluster and they configured for fixed ports. We're monitoring our cluster with application that created by @cgstevens. Even we implemented the grecaful shutdown logic for Actor System sometimes WEB and API applications cant leave the cluster so we have to remove nodes manualy and restart the actor system.

We have reproduce the problem in our development environment and recorded a video below

https://drive.google.com/file/d/0B5ZNfLACId3jMWUyOWliMUhNWTQ/view

Our hocon configuration for nodes are below :

WEB and API

<akka>
    <hocon><![CDATA[
            akka{
                loglevel = DEBUG

                actor{
                    provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"

                    deployment {
                        /coordinatorRouter {
                            router = round-robin-group
                            routees.paths = ["/user/NotificationCoordinator"]
                            cluster {
                                    enabled = on
                                    max-nr-of-instances-per-node = 1
                                    allow-local-routees = off
                                    use-role = sender
                            }
                        }

                        /decidingRouter {
                            router = round-robin-group
                            routees.paths = ["/user/NotificationDeciding"]
                            cluster {
                                    enabled = on
                                    max-nr-of-instances-per-node = 1
                                    allow-local-routees = off
                                    use-role = sender
                            }
                        }
                    }

                    serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                    }

                    serialization-bindings {
                     "System.Object" = wire
                    }

                    debug{
                        receive = on
                        autoreceive = on
                        lifecycle = on
                        event-stream = on
                        unhandled = on
                    }
                }

                remote {
                    helios.tcp {
                            transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                            applied-adapters = []
                            transport-protocol = tcp
                            hostname = "192.168.1.10"
                            port = 3564
                    }
                }

                cluster {
                        seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [client]
                }
            }
        ]]>
    </hocon>
</akka>

Lighthouse

<akka>
    <hocon>
        <![CDATA[
                lighthouse{
                        actorsystem: "notificationSystem"
                    }

                akka {
                    actor {
                        provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"

                        serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                        }

                        serialization-bindings {
                            "System.Object" = wire
                        }
                    }

                    remote {
                        log-remote-lifecycle-events = DEBUG
                        helios.tcp {
                            transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                            applied-adapters = []
                            transport-protocol = tcp
                            #will be populated with a dynamic host-name at runtime if left uncommented
                            #public-hostname = "192.168.1.100"
                            hostname = "192.168.1.101"
                            port = 17527
                        }
                    }

                    loggers = ["Akka.Logger.NLog.NLogLogger,Akka.Logger.NLog"]

                    cluster {
                        seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [lighthouse]
                    }
                }
        ]]>
    </hocon>
</akka>

Sender

<akka>
    <hocon><![CDATA[
                akka{
                    # stdout-loglevel = DEBUG
                    loglevel = DEBUG
                    # log-config-on-start = on

                    loggers = ["Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog"]

                    actor{
                        debug {
                            # receive = on
                            # autoreceive = on
                            # lifecycle = on
                            # event-stream = on
                            # unhandled = on
                        }

                        provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"

                        serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                        }

                        serialization-bindings {
                         "System.Object" = wire
                        }

                        deployment{
                            /NotificationCoordinator/LoggingCoordinator/DatabaseActor{
                                router = round-robin-pool
                                resizer{
                                    enabled = on
                                    lower-bound = 3
                                    upper-bound = 5
                                }
                            }

                            /NotificationDeciding/NotificationDecidingWorkerActor{
                                router = round-robin-pool
                                resizer{
                                    enabled = on
                                    lower-bound = 3
                                    upper-bound = 5
                                }
                            }

                            /ScheduledNotificationCoordinator/SendToProMaster/JobToProWorker{
                                router = round-robin-pool
                                resizer{
                                    enabled = on
                                    lower-bound = 3
                                    upper-bound = 5
                                }
                            }
                        }
                    }

                 remote{
                            log-remote-lifecycle-events = DEBUG
                            log-received-messages = on

                            helios.tcp{
                                transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                                applied-adapters = []
                                transport-protocol = tcp
                                #will be populated with a dynamic host-name at runtime if left uncommented
                                #public-hostname = "POPULATE STATIC IP HERE"
                                hostname = "192.168.1.101"
                                port = 0
                        }
                    }

                    cluster {
                        seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [sender]
                    }
                }
            ]]></hocon>
</akka>

Cluster.Monitor

<akka>
    <hocon>
        <![CDATA[
                akka {
                    stdout-loglevel = INFO
                    loglevel = INFO
                    log-config-on-start = off

                    actor {
                        provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"

                        serializers {
                            wire = "Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"
                        }
                        serialization-bindings {
                            "System.Object" = wire
                        }

                        deployment {
                            /clustermanager {
                                dispatcher = akka.actor.synchronized-dispatcher
                            }
                        }
                    }

                    remote {
                        log-remote-lifecycle-events = INFO
                        log-received-messages = off
                        log-sent-messages = off

                        helios.tcp {
                            transport-class = "Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote"
                            applied-adapters = []
                            transport-protocol = tcp
                            #will be populated with a dynamic host-name at runtime if left uncommented
                            #public-hostname = "127.0.0.1"
                            hostname = "192.168.1.101"
                            port = 0
                        }
                    }

                    cluster {
                    seed-nodes = ["akka.tcp://notificationSystem@192.168.1.101:17527"]
                        roles = [ClusterManager]

                        client {
                            initial-contacts = ["akka.tcp://notificationSystem@192.168.1.101:17527/system/receptionist"]
                        }
                    }
                }
        ]]>
    </hocon>
</akka>


问:
Vue.js Router: history mode and AWS S3 (RoutingRules)
I have a Vue.js application up and running with Amazon S3 and Cloudflare.

When I open the index and browse to /dashboard, everything works fine. But when I open a route like dashboard directly in a new tab or refresh the page, I get the following error back from S3:

```<code>404 Not Found

Code: NoSuchKey
Message: The specified key does not exist.
Key: unternehmen
RequestId: 6514F8A1F4C29235
HostId: +BVrPLJSGdzSYogzWZ4GMBXkgkdSJWRVJVhcSs4EI/lmMUR422aCtCxpBGU6AMe5VkS1UbEn/Lc=
</code>```

Just read that the problem is Vue.js history mode: https://router.vuejs.org/de/essentials/history-mode.html

I would like to solve the problem with a routing rule in my Amazon S3 Bucket. How would the Apache RewriteRule look for S3?

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
</code>```

Tried the following but it does not work:

```<code><RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>domain.com</HostName>
      <ReplaceKeyWith>index.html</ReplaceKeyWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>
</code>```

If I do it like that I just get my Header and Footer rendered but nothing more.

Thank you!

答:
I think this problem has two components:

1.

If a request is made directly (outside of the Javascript App) to a sub path such as /jobs then S3 returns a 404, because the path/object doesn't exist. The simplest way to fix this is from within S3 itself, where you redirect all error pages back to index.html.

However this doesn't work from a CDN such as Cloudfront, and presumably Cloudflare.

A good trick is to use files inside S3 that redirect users like this:

jobs/ -> /index.html
jobs -> /index.html

For example if someone makes a request to site/ they will get the following html file:

```<code>"redirect":"<html><head><meta http-equiv=\"refresh\" content=\"0; url=http://example.com/site/index.html\" /></head>
<body>Redirecting to <a href=\"http://example.com/site/index.html\">Home</a></body></html>"
</code>```

Secondly...

If I do it like that I just get my Header and Footer rendered but
  nothing more.

This is a problem I've had where the router-view doesn't initialise properly, even though the component that contains the router-view has loaded.

What I have done for now is redirect my router when the main "App" component is created:

```<code>created () {
console.log('route', this.$route.path)
this.$router.replace(this.$route.query.redirect || '/')
}
</code>```

This has the added bonus of removing the index.html from your path (Which was put there by your new redirections) whilst forcing your router-view to render...

My #app component is the parent component, with a navbar, footer, and the router-view that renders all of the sub pages/components.

Body:
I have a Vue.js application up and running with Amazon S3 and Cloudflare.

When I open the index and browse to /dashboard, everything works fine. But when I open a route like dashboard directly in a new tab or refresh the page, I get the following error back from S3:

404 Not Found

Code: NoSuchKey
Message: The specified key does not exist.
Key: unternehmen
RequestId: 6514F8A1F4C29235
HostId: +BVrPLJSGdzSYogzWZ4GMBXkgkdSJWRVJVhcSs4EI/lmMUR422aCtCxpBGU6AMe5VkS1UbEn/Lc=

Just read that the problem is Vue.js history mode: https://router.vuejs.org/de/essentials/history-mode.html

I would like to solve the problem with a routing rule in my Amazon S3 Bucket. How would the Apache RewriteRule look for S3?

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Tried the following but it does not work:

<RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>domain.com</HostName>
      <ReplaceKeyWith>index.html</ReplaceKeyWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>

If I do it like that I just get my Header and Footer rendered but nothing more.

Thank you!

Body:
I think this problem has two components:

1.

If a request is made directly (outside of the Javascript App) to a sub path such as /jobs then S3 returns a 404, because the path/object doesn't exist. The simplest way to fix this is from within S3 itself, where you redirect all error pages back to index.html.

However this doesn't work from a CDN such as Cloudfront, and presumably Cloudflare.

A good trick is to use files inside S3 that redirect users like this:

jobs/ -> /index.html
jobs -> /index.html

For example if someone makes a request to site/ they will get the following html file:

"redirect":"<html><head><meta http-equiv=\"refresh\" content=\"0; url=http://example.com/site/index.html\" /></head>
<body>Redirecting to <a href=\"http://example.com/site/index.html\">Home</a></body></html>"

Secondly...

If I do it like that I just get my Header and Footer rendered but
  nothing more.

This is a problem I've had where the router-view doesn't initialise properly, even though the component that contains the router-view has loaded.

What I have done for now is redirect my router when the main "App" component is created:

created () {
console.log('route', this.$route.path)
this.$router.replace(this.$route.query.redirect || '/')
}

This has the added bonus of removing the index.html from your path (Which was put there by your new redirections) whilst forcing your router-view to render...

My #app component is the parent component, with a navbar, footer, and the router-view that renders all of the sub pages/components.


问:
how to update the results of a component's query based on the results of an other component's subscription?
I have 2 react components on the same page,

Component 1 query a list of users

Component 2 subscribe to the event
of creating a new user

I can’t figure out a way to update the results of the component 1 based on the results of component 2's subscription.

Component1:

```<code>class Comp1 extends React.Component {

    render() {
        return (
            <div>
            {this.props.data.loading? <span>loading…</span>
        : <span> //show the list of users </span>       }
        </div>
                    );
    }
}

export default graphql(queryAllUsers)(Comp1) ;
</code>```

Component2 :

```<code>class Comp2 extends React.Component {
   constructor(props) {
     super(props);
        this.state = {
        newUserCreated: false
            }
   }
 subscribeToNewUser() {
    this.subscription = this.props.data.subscribeToMore({
        document: subscribeToNewUsersQuery,
        variables: {//        },
    });
    }
    render() {
        return (
            <div>
            {this.state.newUserCreated}
        </div>
                    );
    }
}
</code>```

答:
I guess the easiest way is to use the query in the first component too and add the subscription to it via the subscribeToMore function.

Could look like this:

...

subscribeToNewUser() {
    this.subscription = this.props.queryAllUsers.subscribeToMore({
      document: subscribeToNewUsersQuery,
      variables: { /* your variables */ },
      updateQuery: (previousResult, { subscriptionData }) => {
        const changedItem = subscriptionData.data.<subscriptionName>;
        if (changedItem !== undefined && changedItem !== null) {
          return // update previous result
        }
        return previousResult;
      },
    });
  }

  ...

  export default graphql(queryAllUsers, {
    name: "queryAllUsers"
  })
  ...
  (Comp1)```

Therein you have the updateQuery functionality which will be called on the subscription event. When the resulting data is good you can update the store, e.g. push the new value to the users array

Body:
I have 2 react components on the same page,

Component 1 query a list of users

Component 2 subscribe to the event
of creating a new user

I can’t figure out a way to update the results of the component 1 based on the results of component 2's subscription.

Component1:

class Comp1 extends React.Component {

    render() {
        return (

            {this.props.data.loading? loading…
        :  //show the list of users        }

                    );
    }
}

export default graphql(queryAllUsers)(Comp1) ;

Component2 :

class Comp2 extends React.Component {
   constructor(props) {
     super(props);
        this.state = {
        newUserCreated: false
            }
   }
 subscribeToNewUser() {
    this.subscription = this.props.data.subscribeToMore({
        document: subscribeToNewUsersQuery,
        variables: {//        },
    });
    }
    render() {
        return (

            {this.state.newUserCreated}

                    );
    }
}

Body:
I guess the easiest way is to use the query in the first component too and add the subscription to it via the subscribeToMore function.

Could look like this:

...

subscribeToNewUser() {
    this.subscription = this.props.queryAllUsers.subscribeToMore({
      document: subscribeToNewUsersQuery,
      variables: { /* your variables */ },
      updateQuery: (previousResult, { subscriptionData }) => {
        const changedItem = subscriptionData.data.<subscriptionName>;
        if (changedItem !== undefined && changedItem !== null) {
          return // update previous result
        }
        return previousResult;
      },
    });
  }

  ...

  export default graphql(queryAllUsers, {
    name: "queryAllUsers"
  })
  ...
  (Comp1)

Therein you have the updateQuery functionality which will be called on the subscription event. When the resulting data is good you can update the store, e.g. push the new value to the users array


问:
How can I use jQuery to make an input readonly?
I have the following input:

```<code>  <input id="fieldName" name="fieldName" type="text" class="text_box" value="Firstname"/>
</code>```

How can I use jQuery to make this element a read-only input without changing the element or its value?

答:
Use this example to make text box ReadOnly or  Not.</p>

```<code><input type="textbox" class="txt" id="txt"/>
<input type="button" class="Btn_readOnly" value="Readonly" />
<input type="button" class="Btn_notreadOnly" value="Not Readonly" />

<script>

    $(document).ready(function(){
       ('.Btn_readOnly').click(function(){
           $("#txt").prop("readonly", true);
       });

       ('.Btn_notreadOnly').click(function(){
           $("#txt").prop("readonly", false);
       });
    });

</script>
</code>```

Body:
I have the following input:

  <input id="fieldName" name="fieldName" type="text" class="text_box" value="Firstname"/>

How can I use jQuery to make this element a read-only input without changing the element or its value?

Body:
Use this example to make text box ReadOnly or  Not.

<input type="textbox" class="txt" id="txt"/>
<input type="button" class="Btn_readOnly" value="Readonly" />
<input type="button" class="Btn_notreadOnly" value="Not Readonly" />

<script>

    $(document).ready(function(){
       ('.Btn_readOnly').click(function(){
           $("#txt").prop("readonly", true);
       });

       ('.Btn_notreadOnly').click(function(){
           $("#txt").prop("readonly", false);
       });
    });

</script>


问:
How to compile Java program with .jar library
I can't make javac recognize an external .jar file, whose classes I'm trying to extend. I have two files in the same directory: TestConsole.java and acm.jar. I'm compiling from the same directory using the following command:

javac -classpath .:acm.jar TestConsole.java

But it seems like javac is just ignoring acm.jar. It gives me the error:

```<code>TestConsole.java:1: package acm does not exist
import acm.program;
          ^
</code>```

Of course, acm.program is a package in acm.jar. All of the classes in acm.jar are already compiled; I just want to use them in my classes, not compile them.

What am I doing wrong?

I am running this on a Mac, and the directory structure of acm.jar appears to be valid: It contains an acm/program directory, which has ConsoleProgram.class, the only class that TestConsole extends.

javac -classpath ".:acm.jar" TestConsole.java does not work, either.

答:
I'm just adding for folks who are still looking for the answer to the same problem after successful compilation.

While compiling use the command as suggested above by @Michael Borgwardt:

```<code>javac -classpath .;acm.jar TestConsole.java
</code>```

For executing also you need to specify the class path:

```<code>java -classpath .;acm.jar TestConsole
</code>```

Body:
I can't make javac recognize an external .jar file, whose classes I'm trying to extend. I have two files in the same directory: TestConsole.java and acm.jar. I'm compiling from the same directory using the following command:

javac -classpath .:acm.jar TestConsole.java

But it seems like javac is just ignoring acm.jar. It gives me the error:

TestConsole.java:1: package acm does not exist
import acm.program;
          ^

Of course, acm.program is a package in acm.jar. All of the classes in acm.jar are already compiled; I just want to use them in my classes, not compile them.

What am I doing wrong?

I am running this on a Mac, and the directory structure of acm.jar appears to be valid: It contains an acm/program directory, which has ConsoleProgram.class, the only class that TestConsole extends.

javac -classpath ".:acm.jar" TestConsole.java does not work, either.

Body:
I'm just adding for folks who are still looking for the answer to the same problem after successful compilation.

While compiling use the command as suggested above by @Michael Borgwardt:

javac -classpath .;acm.jar TestConsole.java

For executing also you need to specify the class path:

java -classpath .;acm.jar TestConsole


问:
xtype vs type column in Sysobjects
Can anyone tell me why Sysobjects table have two columns xtype and type. Both are of data type char(2) and stores the object type.

答:
You can look at the definition of sysobjects

```<code>select OBJECT_DEFINITION(OBJECT_ID('sysobjects'))
AS [processing-instruction(x)] FOR XML PATH('')
</code>```

Which Gives

```<code>CREATE VIEW sys.sysobjects AS
 SELECT
 /*... Snip ...*/
 xtype = type collate database_default,
 /*... Snip ...*/
 type = convert(char(2), case type
  when 'UQ' then 'K' when 'PK' then 'K'
  else type collate database_default end),
 /*... Snip ...*/
 FROM sys.sysschobjs
</code>```

So it appears they only differ in whether UQ and PK or shown as K or not.

Title: xtype vs type column in Sysobjects

Body:
You can look at the definition of sysobjects

select OBJECT_DEFINITION(OBJECT_ID('sysobjects'))
AS [processing-instruction(x)] FOR XML PATH('')

Which Gives

CREATE VIEW sys.sysobjects AS
 SELECT
 /*... Snip ...*/
 xtype = type collate database_default,
 /*... Snip ...*/
 type = convert(char(2), case type
  when 'UQ' then 'K' when 'PK' then 'K'
  else type collate database_default end),
 /*... Snip ...*/
 FROM sys.sysschobjs

So it appears they only differ in whether UQ and PK or shown as K or not.


问:
Read and save list of Object using list of interface

I have seen someone's code and unable to understand how it works.

As the code save List of object in list of Interfaces and can read it back.

Please explain how it works. And can we save Object in interface (where Object implements it). AFAIK interface doesn't have members. How this code save and retrieve please explain.

ContactBO implementing BusinessObject

```<code>public class ContactBO implements BusinessObject {

    private String id, fullName, department, ;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public boolean isSection() {
        // TODO Auto-generated method stub
        return false;
    }

}
</code>```

Where BussinessObject

```<code>public interface BusinessObject {
    boolean isSection();
}
</code>```

Saving list of Contact code

```<code>List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
        List<BusinessObject> list = new ArrayList<BusinessObject>();
        list.addAll(contactList);
</code>```

read List of ContactBO using List of Interface

```<code>List<ContactBO> contactListItems = (List<ContactBO>) (List<?>) result.list;//where list is public List<BusinessObject> list;
</code>```

答:
"Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object."

```<code>   List<BusinessObject> list = new ArrayList<BusinessObject>();
</code>```

This line basically show Polymorphsim concept, Parent class reference can hold the Child class object.

Body:
I have seen someone's code and unable to understand how it works.

As the code save List of object in list of Interfaces and can read it back.

Please explain how it works. And can we save Object in interface (where Object implements it). AFAIK interface doesn't have members. How this code save and retrieve please explain.

ContactBO implementing BusinessObject

public class ContactBO implements BusinessObject {

    private String id, fullName, department, ;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public boolean isSection() {
        // TODO Auto-generated method stub
        return false;
    }

}

Where BussinessObject

public interface BusinessObject {
    boolean isSection();
}

Saving list of Contact code

List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
        List<BusinessObject> list = new ArrayList<BusinessObject>();
        list.addAll(contactList);

read List of ContactBO using List of Interface

List<ContactBO> contactListItems = (List<ContactBO>) (List<?>) result.list;//where list is public List<BusinessObject> list;

Body:
"Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object."

   List<BusinessObject> list = new ArrayList<BusinessObject>();

This line basically show Polymorphsim concept, Parent class reference can hold the Child class object.


问:
how to extract the specific word from a string?
I have a file with multiple lines and want to extract the first three words of every line.

```<code>str = []

str = [
Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web1 journal: afg-prod-web1 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"]
</code>```

I want to extract the date ie.  Feb 17 07:10:07 from every line and put that in an array.

I tried applying a for loop but it gives error:

```<code>IndexError: list index out of range
</code>```

Code I tried :

```<code>for i in splitdata:
            abc  = splitdata[logcount]
            aa = abc.split()
            if(aa[0] == "Feb"):
                aaa = "".join([aa[0],' ',aa[1],' ',aa[2]])
                logtime.append(aaa)
                logcount += 2
            else:
                pass
        print logtime
</code>```

答:
if your log is being saved in a file called log.log you can get dates by doing something like this: </p>

```<code>with open('log.log') as f:
    log_time = []
    for line in f:
        log_time.append(line[:15])
print(log_time)
</code>```

Body:
I have a file with multiple lines and want to extract the first three words of every line.

str = []

str = [
Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web1 journal: afg-prod-web1 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"]

I want to extract the date ie.  Feb 17 07:10:07 from every line and put that in an array.

I tried applying a for loop but it gives error:

IndexError: list index out of range

Code I tried :

for i in splitdata:
            abc  = splitdata[logcount]
            aa = abc.split()
            if(aa[0] == "Feb"):
                aaa = "".join([aa[0],' ',aa[1],' ',aa[2]])
                logtime.append(aaa)
                logcount += 2
            else:
                pass
        print logtime

Body:
if your log is being saved in a file called log.log you can get dates by doing something like this:

with open('log.log') as f:
    log_time = []
    for line in f:
        log_time.append(line[:15])
print(log_time)