问:
Unable to scroll and select desired year from Calender in WebDriver Python
I am trying to scroll the drop down and select an element via webdriver in python.
What Exactly I mean is, Drop down of "Calender" opens, scroll to "1990" year and then select it.
But unable to do it so.

```<code>def setUp(self):
    driverlocation ="/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver"
    os.environ["webdriver.chrome.driver"] = driverlocation
    self.driver = webdriver.Chrome(driverlocation)

def test_data(self):
    driver = self.driver
    url = "https://goods.theentertainerme.com/"
    driver.get(url)
    driver.maximize_window()
    driver.implicitly_wait(10)
    self.DateofBirth = driver.find_element_by_id("registrationform-date_of_birth")
    self.DateofBirth.click()
    Month = driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/div/div/select[1]/option[6]")
    Month.click()

    Year= driver.find_element_by_xpath("//*[@id='ui-datepicker-div']//div/select[2]")
    YearList = driver.find_elements_by_xpath("//*[@id='ui-datepicker-div']//div/select[2]")
    Year.click()
    Year1990= driver.find_element_by_xpath("//*[@id='ui-datepicker-div']//div/select[2]/option[28]")
    driver.execute_script ("return arguments[0].scrollIntoView();",Year1990)
</code>```

Can someone help me on this?

答:
Try something like this:

```<code>Year1990 = driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/div/select[2]/option[28]")
ActionChains(driver).move_to_element(Year1990).click(Year1990).perform()
</code>```

Note: I've moved the double "//" before div to be one "/" e.g. /div instad of //div

Or...

```<code>Year1990 = driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/div/select[2]/option[28]")
actions = ActionChains(driver)
actions.move_to_element(Year1990).Perform()
Year1990.click()
</code>```

For more information on Actions, see 7.2 of the following documentation http://selenium-python.readthedocs.io/api.html

Body:
I am trying to scroll the drop down and select an element via webdriver in python.
What Exactly I mean is, Drop down of "Calender" opens, scroll to "1990" year and then select it.
But unable to do it so.

def setUp(self):
    driverlocation ="/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver"
    os.environ["webdriver.chrome.driver"] = driverlocation
    self.driver = webdriver.Chrome(driverlocation)

def test_data(self):
    driver = self.driver
    url = "https://goods.theentertainerme.com/"
    driver.get(url)
    driver.maximize_window()
    driver.implicitly_wait(10)
    self.DateofBirth = driver.find_element_by_id("registrationform-date_of_birth")
    self.DateofBirth.click()
    Month = driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/div/div/select[1]/option[6]")
    Month.click()

    Year= driver.find_element_by_xpath("//*[@id='ui-datepicker-div']//div/select[2]")
    YearList = driver.find_elements_by_xpath("//*[@id='ui-datepicker-div']//div/select[2]")
    Year.click()
    Year1990= driver.find_element_by_xpath("//*[@id='ui-datepicker-div']//div/select[2]/option[28]")
    driver.execute_script ("return arguments[0].scrollIntoView();",Year1990)

Can someone help me on this?

Body:
Try something like this:

Year1990 = driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/div/select[2]/option[28]")
ActionChains(driver).move_to_element(Year1990).click(Year1990).perform()

Note: I've moved the double "//" before div to be one "/" e.g. /div instad of //div

Or...

Year1990 = driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/div/select[2]/option[28]")
actions = ActionChains(driver)
actions.move_to_element(Year1990).Perform()
Year1990.click()

For more information on Actions, see 7.2 of the following documentation http://selenium-python.readthedocs.io/api.html


来源: stackexchange

问:
Notified when lateinit var has been initialised (Kotlin)
This is a straight forward question but I cannot find an answer. Is there a way to be notified when a lateinit var has been initialised in Kotlin?

I know I can check if it has been initialised with this::coolvar.isInitialized but this is not the same.

Thank you

答:
lateinit var works well only in the simplest cases when uninitialized value doesn't make sense in the context of the app, such as dependency injection or late initialization in onCreate().

What you need is a property delegate with a particular behavior. Take a look at Delegates.observable :

```<code>var coolvar by Delegates.observable("initial value") { _, old, new ->
    println("coolvar has been updated")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
lateinit var works well only in the simplest cases when uninitialized value doesn't make sense in the context of the app, such as dependency injection or late initialization in onCreate().

What you need is a property delegate with a particular behavior. Take a look at Delegates.observable :

var coolvar by Delegates.observable("initial value") { _, old, new ->
    println("coolvar has been updated")
}


问:
Search by string date mysql
I need to run query that return a rows by range of dates.
the dates are saved in a string format like "22/11/2017"
i try to used in str_to_date but its not work so good.
my query :

```<code>SELECT Activities.Date AS 'dates'  FROM Attendance
                           INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                           INNER JOIN Groups ON Activities.GroupID=Groups.ID
                           INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                           WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND  (str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017" AND str_to_date(Activities.Date,'%d/%m/%Y')<='30/11/2017') GROUP BY Activities.Date
                            ORDER BY Groups.Name
</code>```

The result :

```<code>'24/09/2017','24/10/2017','24/11/2017','24/12/2017','25/09/2017','25/10/2017,..
</code>```

答:
You can use SQL wild card like Activities.Date LIKE "%11/2017" to get all the activities recorded in the month of november 2017. With that your query should be:

```<code>SELECT Activities.Date AS 'dates'  FROM Attendance
                       INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                       INNER JOIN Groups ON Activities.GroupID=Groups.ID
                       INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                       WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND Activities.Date LIKE "%11/2017" GROUP BY Activities.Date
                        ORDER BY Groups.Name
</code>```

Title: Search by string date mysql

Body:
I need to run query that return a rows by range of dates.
the dates are saved in a string format like "22/11/2017"
i try to used in str_to_date but its not work so good.
my query :

SELECT Activities.Date AS 'dates'  FROM Attendance
                           INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                           INNER JOIN Groups ON Activities.GroupID=Groups.ID
                           INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                           WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND  (str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017" AND str_to_date(Activities.Date,'%d/%m/%Y')<='30/11/2017') GROUP BY Activities.Date
                            ORDER BY Groups.Name

The result :

'24/09/2017','24/10/2017','24/11/2017','24/12/2017','25/09/2017','25/10/2017,..

Body:
You can use SQL wild card like Activities.Date LIKE "%11/2017" to get all the activities recorded in the month of november 2017. With that your query should be:

SELECT Activities.Date AS 'dates'  FROM Attendance
                       INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                       INNER JOIN Groups ON Activities.GroupID=Groups.ID
                       INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                       WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND Activities.Date LIKE "%11/2017" GROUP BY Activities.Date
                        ORDER BY Groups.Name


问:
curl command replication using requests in python
I am trying to replicate the below curl command in python using the requests module. The curl command is as follows:

```<code>curl -v -k -H "apikey:INTERNAL_TEST" http://api1/publicapi/macro/<sha256> -X POST
</code>```

I am able to replicate the whole curl command except the letter '-X' before POST.

Please inform me in case more information is required. Thank you in advance.

答:
The -X flag in curl is for specifying the HTTP method for your request.

You can used requests.post to make HTTP POST request.

```<code>url = 'http://api1/publicapi/macro/<sha256>'
headers = {'apikey': 'INTERNAL_TEST'}

response = requests.post(url, headers=headers)
</code>```

Body:
I am trying to replicate the below curl command in python using the requests module. The curl command is as follows:

curl -v -k -H "apikey:INTERNAL_TEST" http://api1/publicapi/macro/<sha256> -X POST

I am able to replicate the whole curl command except the letter '-X' before POST.

Please inform me in case more information is required. Thank you in advance.

Body:
The -X flag in curl is for specifying the HTTP method for your request.

You can used requests.post to make HTTP POST request.

url = 'http://api1/publicapi/macro/<sha256>'
headers = {'apikey': 'INTERNAL_TEST'}

response = requests.post(url, headers=headers)


问:
Automatically deducing the type of bind1st(mem_fun(&my_class::f), this)?
I would like to pass the bind1st(mem_fun(&my_class::f), this) functor to for_each. Unfortunately it is very difficult to read so I would like to give it a more readible name like this:

```<code>(the type I am looking for) meaningful_name = bind1st(mem_fun(&my_class::f), this);

for_each(v.begin(), v.end(), meaningful_name);
</code>```

Is there a simple way to deduce the type of the functor? (I know mem_fun saves us a lot of pain exactly for this reason.)

答:
No there is no simple way. The type name will be rather long and even more unreadable. And if you use boost, you don't need to use BOOST_AUTO, because you can just use boost::bind and have it readable, without a need for a local.

```<code>for_each(v.begin(), v.end(), boost::bind(&my_class::f, this));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would like to pass the bind1st(mem_fun(&my_class::f), this) functor to for_each. Unfortunately it is very difficult to read so I would like to give it a more readible name like this:

(the type I am looking for) meaningful_name = bind1st(mem_fun(&my_class::f), this);

for_each(v.begin(), v.end(), meaningful_name);

Is there a simple way to deduce the type of the functor? (I know mem_fun saves us a lot of pain exactly for this reason.)

Body:
No there is no simple way. The type name will be rather long and even more unreadable. And if you use boost, you don't need to use BOOST_AUTO, because you can just use boost::bind and have it readable, without a need for a local.

for_each(v.begin(), v.end(), boost::bind(&my_class::f, this));


问:
On remove of last left child node, my respective firebase table gets deleted
I have a scenario where I have firebase json db, in which I have a json object of agents. Here, if I delete the last left child node, then the table(node) agents gets removed as well.

How I can I restrict that this agents(parent node) doesnt get deleted even if I am deleting the last child left into it, or, How I can re-create the parent node(agents) after the removal of last left child node?

Below is what I am doing through code:

```<code>    FriendlyChat.prototype.signOut = function () {

      var userdetails = this.auth.currentUser;

      this.database.ref('agents').child(userdetails.displayName).remove();

      this.auth.signOut();
    };

FriendlyChat.prototype.onAuthStateChanged = function (user) {

  if (user) { // User is signed in!
    // Get profile pic and user's name from the Firebase user object.
    //console.log(user);
    var profilePicUrl = user.photoURL;
    var userEmail = user.email;
    var userName = user.displayName;
    this.agentsRef = this.database.ref('agents');
    var loginTime = Math.floor(new Date().getTime() / 1000);

    this.agentsRef.child(userName).set({
      emailId: userEmail,
      login_time: loginTime,
      name: userName
    })

  } else { // User is signed out!
    // Hide user's profile and sign-out button.
// Something happens

  }
};
</code>```

Firebase DB:

```<code>{
  "agents" : {
    "test test" : {
      "emailId" : "testrbcdemo@gmail.com",
      "login_time" : 7686887,
      "name" : "test test"
    }
  },
  "engagedUsers" : {
    "qwe" : {
      "agent_availability" : true,
      "conv_id" : "testrbcdemo_qwe",
      "emailId" : "qwe@gmail.com",
      "login_time" : 66565656,
      "name" : "qwe",
      "uid" : "adasfklsfjdskldgsgjgjkl"
    }
  },
}
</code>```

答:
That is normal behavior for Firebase since it is a node based system. The table gets regenerated when a new child is added. The reason Firebase does this is for you not to have empty tables (nodes).

The way Firebase works is by checking if the node already exists and recreates it if it does not. If it exists, a key value pair is added as a child of that node. This means that ultimately you need to end up with a key value pair, no matter how many nodes you have.

For example:

```<code> - Customer
     - Address
         - AddressLine1: The Hive
         - AddressLine2: Southampton Ave
         - AddressLine3: New York
         - Country: USA
</code>```

In the example above, the address node contains data separated in 4 children. If I remove AddressLine1, AddressLine2, AddressLine3 and Country, the Address node is automatically removed since it has no children.

Once I add a new address to that Customer, the Address node is recreated.

Body:
I have a scenario where I have firebase json db, in which I have a json object of agents. Here, if I delete the last left child node, then the table(node) agents gets removed as well.

How I can I restrict that this agents(parent node) doesnt get deleted even if I am deleting the last child left into it, or, How I can re-create the parent node(agents) after the removal of last left child node?

Below is what I am doing through code:

    FriendlyChat.prototype.signOut = function () {

      var userdetails = this.auth.currentUser;

      this.database.ref('agents').child(userdetails.displayName).remove();

      this.auth.signOut();
    };

FriendlyChat.prototype.onAuthStateChanged = function (user) {

  if (user) { // User is signed in!
    // Get profile pic and user's name from the Firebase user object.
    //console.log(user);
    var profilePicUrl = user.photoURL;
    var userEmail = user.email;
    var userName = user.displayName;
    this.agentsRef = this.database.ref('agents');
    var loginTime = Math.floor(new Date().getTime() / 1000);

    this.agentsRef.child(userName).set({
      emailId: userEmail,
      login_time: loginTime,
      name: userName
    })

  } else { // User is signed out!
    // Hide user's profile and sign-out button.
// Something happens

  }
};

Firebase DB:

{
  "agents" : {
    "test test" : {
      "emailId" : "testrbcdemo@gmail.com",
      "login_time" : 7686887,
      "name" : "test test"
    }
  },
  "engagedUsers" : {
    "qwe" : {
      "agent_availability" : true,
      "conv_id" : "testrbcdemo_qwe",
      "emailId" : "qwe@gmail.com",
      "login_time" : 66565656,
      "name" : "qwe",
      "uid" : "adasfklsfjdskldgsgjgjkl"
    }
  },
}

Body:
That is normal behavior for Firebase since it is a node based system. The table gets regenerated when a new child is added. The reason Firebase does this is for you not to have empty tables (nodes).

The way Firebase works is by checking if the node already exists and recreates it if it does not. If it exists, a key value pair is added as a child of that node. This means that ultimately you need to end up with a key value pair, no matter how many nodes you have.

For example:

 - Customer
     - Address
         - AddressLine1: The Hive
         - AddressLine2: Southampton Ave
         - AddressLine3: New York
         - Country: USA

In the example above, the address node contains data separated in 4 children. If I remove AddressLine1, AddressLine2, AddressLine3 and Country, the Address node is automatically removed since it has no children.

Once I add a new address to that Customer, the Address node is recreated.


问:
JSON - invalid model schema specified for specific schema
I've made a model that I have troubles saving in API Gateway.
If anyone could point me to a place in the code where I've made issue I will be very grateful.

The point is that I've tried to build an array there which seem like to not be build correctly. I was using several docs to perform it but I'm failing.

Thanks in advance and best regards.

{
 "$schema": "http://json-schema.org/draft-04/schema#",
 "title": "GetUser",
 "type": "object",
 "properties": {
  "user_id": {
   "type": "number"
  },
  "shop_id": {
   "type": "number"
  },
  "email": {
   "type": "string"
  },
  "first_name": {
   "type": "string"
  },
  "last_name": {
   "type": "string"
  },
  "gender_title": {
   "type": "string"
  },
  "language": {
   "type": "string"
  }
 },
 "birthday": {
  "type": "array",
  "items": {
   "type": "object",
   "properties": {
    "day": {
     "type": "number"
    },
    "month": {
     "type": "string"
    },
    "year": {
     "type": "number"
    },

    "loyality_club_points": {
     "type": "number"
    },
    "levels_points": {
     "type": "array",
     "items": {
      "points": {
       "type": "number"
      },
      "order_tax": {
       "type": "number"
      }

     }
    }
   }
  }
 }
}```

答:
What I want to have is:

```<code>{
"user_id":          ,(number)
"shop_id":          ,(number)
"email":            ,(string)
"first_name":       ,(string)
"last_name":        ,(string)
"gender_title":     ,(string)
"language":         ,(string)
"birthday":
    {
       "day":      ,(number)
       "month":    ,(string)
       "year":      (number)
    },
"loyalty_club_points":      ,(number)
"levels_points":
[
    {
       "points": 150,
       "order_tax": 3
    },
   {
       "points": 250,
       "order_tax": 6
    },
   {
       "points": 350,
       "order_tax": 9
    },
   {
       "points": 550,
       "order_tax": 12
    },
   {
      "points": 1000,
      "order_tax": 32
   }
</code>```

]
}

Body:
What I want to have is:

{
"user_id":          ,(number)
"shop_id":          ,(number)
"email":            ,(string)
"first_name":       ,(string)
"last_name":        ,(string)
"gender_title":     ,(string)
"language":         ,(string)
"birthday":
    {
       "day":      ,(number)
       "month":    ,(string)
       "year":      (number)
    },
"loyalty_club_points":      ,(number)
"levels_points":
[
    {
       "points": 150,
       "order_tax": 3
    },
   {
       "points": 250,
       "order_tax": 6
    },
   {
       "points": 350,
       "order_tax": 9
    },
   {
       "points": 550,
       "order_tax": 12
    },
   {
      "points": 1000,
      "order_tax": 32
   }

]
}


问:
How do I use extends for interface using typescript?
Below is my origin code

```<code>interface customerInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        name: string
        tel: number
    }
}

interface accountInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        xxx: number
        vvv: string
    }
}
</code>```

How can I use extends for this code?

```<code>interface outer {
    Success: boolean;
    Code: string;
    Message: string;
    Result: Object;
}

interface customerInfo extends outer.Result {
        name: string
        tel: number
}

interface accountInfo extends outer.Result {
        xxx: number
        vvv: string
}
</code>```

Is code above correct?
The content of interface customerInfo and accountInfo is under result Object.

答:
You could make outer generic and the type parameter will be the result type:

```<code>interface outer<T> {
    Success: boolean;
    Code: string;
    Message: string;
    Result: T;
}

interface customerInfo extends outer<{
    name: string
    tel: number
}> {
    //Other members
}

interface accountInfo extends outer<{
    xxx: number
    vvv: string
}>{
    //Other members
}
</code>```

In the above type the type parameter is an inline interface declaration, but if you want to reuse it, it might be best to use a named interface. Ex:

```<code>interface customerInfoResult {
    name: string
    tel: number
}
interface customerInfo extends outer<customerInfoResult> {
    //Other members
}
</code>```

Body:
Below is my origin code

interface customerInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        name: string
        tel: number
    }
}

interface accountInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        xxx: number
        vvv: string
    }
}

How can I use extends for this code?

interface outer {
    Success: boolean;
    Code: string;
    Message: string;
    Result: Object;
}

interface customerInfo extends outer.Result {
        name: string
        tel: number
}

interface accountInfo extends outer.Result {
        xxx: number
        vvv: string
}

Is code above correct?
The content of interface customerInfo and accountInfo is under result Object.

Body:
You could make outer generic and the type parameter will be the result type:

interface outer<T> {
    Success: boolean;
    Code: string;
    Message: string;
    Result: T;
}

interface customerInfo extends outer<{
    name: string
    tel: number
}> {
    //Other members
}

interface accountInfo extends outer<{
    xxx: number
    vvv: string
}>{
    //Other members
}

In the above type the type parameter is an inline interface declaration, but if you want to reuse it, it might be best to use a named interface. Ex:

interface customerInfoResult {
    name: string
    tel: number
}
interface customerInfo extends outer<customerInfoResult> {
    //Other members
}


问:
Countdown (Cookies)
How do I make this countdown able to not reset the countdown when it is refresh? Like when I click refresh it should continue the countdown instead of resetting the countdown again, from "14d, 22h, 23m, 32s" (refresh) to continue to "14d , 22, 59m, 59s".

With some research I saw I should use Cookies but I don't know how to create one, hope you can help me create one!

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import 'https://fonts.googleapis.com/css?family=Alegreya+Sans';

@font-face {
    font-family: 'ps';
    src: url("../fonts/personalservice.ttf");
}

@font-face {
    font-family: 'afb';
    src: url("../fonts/Agency_FB.ttf");
}

@font-face {
    font-family: 'blob';
    src: url("../fonts/Blobtastics.ttf");
}

@font-face {
    font-family: 'rv';
    src: url("../fonts/roundedvale.ttf");
}

/*start loading*/

.spinner{
    width: 80px;
    height: 80px;

    border: 2px solid #f3f3f3;
    border-top:3px solid #f25a41;
    border-radius: 100%;

    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right: 0;
    margin: auto;

    animation: spin 1s infinite linear;
}

@keyframes spin {
    from{
        transform: rotate(0deg);
    }to{
        transform: rotate(360deg);
    }
}

#overlay{
  height:100%;
  width:100%;
  background: #e1e1e1;
  opacity: .5;
  position:fixed;
  left:0;
  top:0;
 }

* {
    margin: 0;
    padding: 0;
    border: 0;
}

body {
    background: #e1e1e1;
    color: #67727A;
    font-family: 'Alegreya', Sans-serif;
}

#banner{
    height: 592px;
    vertical-align: center;
}

#branding{
    padding-top: 150px;
    width: 752px;
    height: 100px;
    padding-left: 400px;
}

#text{
    padding-top: 30px;
    font-family: 'ps';
    font-size: 40px;
    width: 500px;
    float: right;
}

#logo {
    float: left;
    width: 251px;
    height: 90px;
    background: url(../img/RH5.png) no-repeat center;
}

#clockdiv{
    font-family: sans-serif;
    color: #fff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 50px;
    padding-left: 440px;
}

#clockdiv > div{
    padding: 10px;
    border-radius: 3px;
    background: #00BF96;
    display: inline-block;
}

#clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #00816A;
    display: inline-block;
}

.smalltext{
    padding-top: 5px;
    font-size: 16px;
}

footer{
    background-color: #87ceeb;
    height: 70px;
}

#ig img{
    width: 49px;
    height: 49px;
    float: right;
    margin-right: 25px;
    margin-top: 10px;
    text-align: center;
}

#fb img{
    width: 49px;
    height: 49px;
    margin-top: 10px;
    margin-right: 625px;
    float: right;
    text-align: center;
    border-radius: 10px 10px 10px 10px;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="FSX Repaints">
    <meta name="keywords" content="fsx, repaints, project airbus, just flight, pmdg, captainsim, premier airraft design, pad, airlines, project opensky, posky, tom's ruth">
    <meta name="author" content="Raven Lescano">
    <title>Coming Soon | Raven's Hangar</title>
    <link rel="stylesheet" href="css/countdown.css" type="text/css">
    <link href="css/font-awesome.min.css" rel="stylesheet">

coming soon

Days

Hours

Minutes

Seconds

```

答:
in Java script you can use window.localstorage

so Update your code.

From :

```<code>var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
</code>```

To :

```<code>var deadline;
if(window.localStorage.hasOwnProperty('deadline')){
deadline = window.localStorage.getItem('deadline');
} else {
  deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
  window.localStorage.setItem('deadline',deadline);
}
initializeClock('clockdiv', deadline);
</code>```

Happy Coding :)

Title: Countdown (Cookies)

Body:
How do I make this countdown able to not reset the countdown when it is refresh? Like when I click refresh it should continue the countdown instead of resetting the countdown again, from "14d, 22h, 23m, 32s" (refresh) to continue to "14d , 22, 59m, 59s".

With some research I saw I should use Cookies but I don't know how to create one, hope you can help me create one!

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);

@import 'https://fonts.googleapis.com/css?family=Alegreya+Sans';

@font-face {
    font-family: 'ps';
    src: url("../fonts/personalservice.ttf");
}

@font-face {
    font-family: 'afb';
    src: url("../fonts/Agency_FB.ttf");
}

@font-face {
    font-family: 'blob';
    src: url("../fonts/Blobtastics.ttf");
}

@font-face {
    font-family: 'rv';
    src: url("../fonts/roundedvale.ttf");
}

/*start loading*/

.spinner{
    width: 80px;
    height: 80px;

    border: 2px solid #f3f3f3;
    border-top:3px solid #f25a41;
    border-radius: 100%;

    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right: 0;
    margin: auto;

    animation: spin 1s infinite linear;
}

@keyframes spin {
    from{
        transform: rotate(0deg);
    }to{
        transform: rotate(360deg);
    }
}

#overlay{
  height:100%;
  width:100%;
  background: #e1e1e1;
  opacity: .5;
  position:fixed;
  left:0;
  top:0;
 }

* {
    margin: 0;
    padding: 0;
    border: 0;
}

body {
    background: #e1e1e1;
    color: #67727A;
    font-family: 'Alegreya', Sans-serif;
}

#banner{
    height: 592px;
    vertical-align: center;
}

#branding{
    padding-top: 150px;
    width: 752px;
    height: 100px;
    padding-left: 400px;
}

#text{
    padding-top: 30px;
    font-family: 'ps';
    font-size: 40px;
    width: 500px;
    float: right;
}

#logo {
    float: left;
    width: 251px;
    height: 90px;
    background: url(../img/RH5.png) no-repeat center;
}

#clockdiv{
    font-family: sans-serif;
    color: #fff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 50px;
    padding-left: 440px;
}

#clockdiv > div{
    padding: 10px;
    border-radius: 3px;
    background: #00BF96;
    display: inline-block;
}

#clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #00816A;
    display: inline-block;
}

.smalltext{
    padding-top: 5px;
    font-size: 16px;
}

footer{
    background-color: #87ceeb;
    height: 70px;
}

#ig img{
    width: 49px;
    height: 49px;
    float: right;
    margin-right: 25px;
    margin-top: 10px;
    text-align: center;
}

#fb img{
    width: 49px;
    height: 49px;
    margin-top: 10px;
    margin-right: 625px;
    float: right;
    text-align: center;
    border-radius: 10px 10px 10px 10px;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="FSX Repaints">
    <meta name="keywords" content="fsx, repaints, project airbus, just flight, pmdg, captainsim, premier airraft design, pad, airlines, project opensky, posky, tom's ruth">
    <meta name="author" content="Raven Lescano">
    <title>Coming Soon | Raven's Hangar</title>
    <link rel="stylesheet" href="css/countdown.css" type="text/css">
    <link href="css/font-awesome.min.css" rel="stylesheet">

coming soon

Days

Hours

Minutes

Seconds

Body:
in Java script you can use window.localstorage

so Update your code.

From :

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);

To :

var deadline;
if(window.localStorage.hasOwnProperty('deadline')){
deadline = window.localStorage.getItem('deadline');
} else {
  deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
  window.localStorage.setItem('deadline',deadline);
}
initializeClock('clockdiv', deadline);

Happy Coding :)


问:
Configure output channel for service activator via .handle()
Edited
I am new to Spring integration, and I am trying to pass data from a service activator(via handle method) to a channel.

```<code>@Bean
public IntegrationFlow processFileFlow() {
    return IntegrationFlows
            .from("fileInputChannel")
            .transform(fileToStringTransformer())
            .handle("fileProcessor", "process")
            .channel("xmlChannel")
            .get();
}

@Bean
public DirectChannel fileInputChannel(){
    return new DirectChannel();
}

@Bean
public DirectChannel xmlChannel(){
    return new DirectChannel();
}

@Bean
public FileProcessor fileProcessor() {
    return new FileProcessor();
}

@Bean
public IntegrationFlow enrichDataFlow() {
    return IntegrationFlows
            .from("xmlChannel")
            .handle("enricher", "enrichProduct")
            .channel("bvChannel")
            .get();
}

@Bean
public Enricher enricher() {
    return new Enricher();
}
</code>```

This is the FileProcessor class

```<code>public class FileProcessor {

    @ServiceActivator(outputChannel = "xmlChannel")
    public String process(Message<String> msg) {
        String content = msg.getPayload();
        return content;
    }
}
</code>```

This is the Enricher class:
    public class Enricher {

```<code>    public void enrichProduct(Message<String> msg) {
        System.out.println("Enriching product " + msg);
    }
}
</code>```

The message "Enriching product .." isn't getting printed, and I'm not really sure of what has gone wrong.

答:
Doesn't that .channel("xmlChannel") work for you?

That's definitely the proper way to compose IntegrationFlow - from one endpoint over a message channel to another endpoint.

And I would say that outputChannel = "xmlChannel" in the @ServiceActivator isn't going to work just  because there is no inputChannel. More over the .handle() will just ignore all those attributes and just will deal with the fileProcessor.process() method directly.

Body:
Edited
I am new to Spring integration, and I am trying to pass data from a service activator(via handle method) to a channel.

@Bean
public IntegrationFlow processFileFlow() {
    return IntegrationFlows
            .from("fileInputChannel")
            .transform(fileToStringTransformer())
            .handle("fileProcessor", "process")
            .channel("xmlChannel")
            .get();
}

@Bean
public DirectChannel fileInputChannel(){
    return new DirectChannel();
}

@Bean
public DirectChannel xmlChannel(){
    return new DirectChannel();
}

@Bean
public FileProcessor fileProcessor() {
    return new FileProcessor();
}

@Bean
public IntegrationFlow enrichDataFlow() {
    return IntegrationFlows
            .from("xmlChannel")
            .handle("enricher", "enrichProduct")
            .channel("bvChannel")
            .get();
}

@Bean
public Enricher enricher() {
    return new Enricher();
}

This is the FileProcessor class

public class FileProcessor {

    @ServiceActivator(outputChannel = "xmlChannel")
    public String process(Message<String> msg) {
        String content = msg.getPayload();
        return content;
    }
}

This is the Enricher class:
    public class Enricher {

    public void enrichProduct(Message<String> msg) {
        System.out.println("Enriching product " + msg);
    }
}

The message "Enriching product .." isn't getting printed, and I'm not really sure of what has gone wrong.


问:
UrhoSharp losing input when clicked
I'm using an UrhoSurface control in WPF. It's included in the NuGet package "UrhoSharp.Wpf". Everything works fine, but when UrhoSurface is clicked with either of the mouse buttons, it stops getting input from the keyboard. Setting Focusable to false doesn't help.
Here's the code I use to get the input:

```<code>using Urho;

if (Input.GetKeyDown(Key.W))
    CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
if (Input.GetKeyDown(Key.S))
    CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
if (Input.GetKeyDown(Key.A))
    CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
if (Input.GetKeyDown(Key.D))
    CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);
</code>```

I'm fairly new to WPF.

答:
I know it's a long time since you asked, but in case you or some other still need it: You can use c# way to check if a key is down and it works:</p>

```<code>if (System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.W)) { ... }
</code>```

Title: UrhoSharp losing input when clicked

Body:
I'm using an UrhoSurface control in WPF. It's included in the NuGet package "UrhoSharp.Wpf". Everything works fine, but when UrhoSurface is clicked with either of the mouse buttons, it stops getting input from the keyboard. Setting Focusable to false doesn't help.
Here's the code I use to get the input:

using Urho;

if (Input.GetKeyDown(Key.W))
    CameraNode.Translate(Vector3.UnitZ * moveSpeed * timeStep);
if (Input.GetKeyDown(Key.S))
    CameraNode.Translate(-Vector3.UnitZ * moveSpeed * timeStep);
if (Input.GetKeyDown(Key.A))
    CameraNode.Translate(-Vector3.UnitX * moveSpeed * timeStep);
if (Input.GetKeyDown(Key.D))
    CameraNode.Translate(Vector3.UnitX * moveSpeed * timeStep);

I'm fairly new to WPF.

Body:
I know it's a long time since you asked, but in case you or some other still need it: You can use c# way to check if a key is down and it works:

if (System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.W)) { ... }


问:
What's Is the Best File Format for Configuration Files
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.

What format would be the best for these config files?

Here is my quantification of best:

Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.

Remains easily read by humans even when there are a large amount of entries

Is a widely used standard, no custom formats

Succinctness is appreciated

I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there.

答:
YAML is a good option:
http://www.yaml.org/

It's very simple and powerful, too

Ruby projects use it a lot for configuration.

OwnerDisplayName: macinjosh

LastEditorDisplayName: InSciTek Jeff

OwnerDisplayName: nicholaides


问:
What's the most efficient bit vector compression method for my use case?

I'm working on a project in computational biology and I need to store an index of locuses that differ between many sequences. For now, I'm using a B+Tree for that purpose, but I guess using a bitmap index would be way faster for such a use case : only a small number of locus differ between two sequences, 1% on average, and they are nearly equally distributed along the sequence; so it seems like there is a lot of room for bitmap index compression.
My problem is that I cannot manage to find a compression method that can efficiently:

allow fast individual bit setting/unsetting

permit efficient range queries over the bitmap

possibly allow fast XOR-ing/AND-ing of two indexes

Thx in advance for your suggestions.

答:
Check out FastBit:

https://sdm.lbl.gov/fastbit/


问:
No serializer found for class org.jooq.impl.DefaultBinding
As part of my spring boot application, I am auto-generating my DO classes using jooq. After getting this data from db as do object, I am trying to convert it to map using jackson library. But it is giving the error:

com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.jooq.impl.DefaultBinding and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

Can I get some help on this?

答:
As of jOOQ version 3.10, you cannot simply serialise / deserialise jOOQ Record types using Jackson without specifying your own custom bindings. Another option is to map the jOOQ Record into your own POJO ("DO") object first, e.g. using:

```<code>Result<Record> result = ctx.select(...).from(...).fetch();
List<MyPojo> list = result.into(MyPojo.class);
</code>```

And then you should be able to easily serialise that list instead.

Body:
As of jOOQ version 3.10, you cannot simply serialise / deserialise jOOQ Record types using Jackson without specifying your own custom bindings. Another option is to map the jOOQ Record into your own POJO ("DO") object first, e.g. using:

Result<Record> result = ctx.select(...).from(...).fetch();
List<MyPojo> list = result.into(MyPojo.class);

And then you should be able to easily serialise that list instead.


问:
What is difference between eval_metric and feval in xgboost?
What is difference between feval and eval_metric in xgb.train, both parametrs are only for evaluation purpose.

Post from Kaggle gives some insight :

https://www.kaggle.com/c/prudential-life-insurance-assessment/forums/t/18473/custom-objective-for-xgboost

答:
feval is to create your own customized evaluation metric.

it must be a (custom, user-defined) function

eval_metric is for built in metrics xgboost package is implementing.

it's a string, e.g. rmse / logloss/ mlogloss/ merror/ error/ auc/ ndcg/ ...

ContentLicense: CC BY-SA 4.0


问:
JavaScript Math Object: Negative , Zero and Positive Value
I want to random a numbers like this from -5....0....5.

```<code><!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 7-1);
}
</script>

</body>
</html>
</code>```

In this case it returns only -1. It is possible to do in javascript math object?

答:
You could use a factor of 11 (this returns a value of 0 ... 10) and adjust the number by -5.

console.log(Math.floor(Math.random() * 11) - 5);```

Body:
I want to random a numbers like this from -5....0....5.

<!DOCTYPE html>

<button onclick="myFunction()">Try it</button>

In this case it returns only -1. It is possible to do in javascript math object?


问:
Built in function that constructs TSize?
Is there a built-in function in Delphi 7 that returns a TSize from a given cx and cy parameters?

Something similar to the functions Rect() and Point() etc...

I know that writing my own is very simple (although its a shame that Size is already an alias to TSize so I can't name my function Size). but I was wondering if there is a build-in function in the RTL.

答: There is no such built in function in the Delphi 7 RTL. </p>


问:
DataProperties in Subclass expression
I tried working with the OWL2-RL rules build into graphdb. I am obviously doing something wrong or understood something wrong. Here is my toy ontology.

```<code><?xml version="1.0"?>
<rdf:RDF xmlns="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182#"
     xml:base="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:untitled-ontology-182="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182#"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
     xmlns:ontology="http://www.some/ontology/">
    <owl:Ontology rdf:about="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182"/>

    <!-- http://www.some/ontology/hasValue -->
    <owl:DatatypeProperty rdf:about="http://www.some/ontology/hasValue">
         <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/>
    </owl:DatatypeProperty>

    <!-- http://www.some/ontology/ClassA -->
    <owl:Class rdf:about="http://www.some/ontology/ClassA"/>

    <!-- http://www.some/ontology/InvA -->
    <owl:NamedIndividual rdf:about="http://www.some/ontology/InvA">
        <rdf:type rdf:resource="http://www.some/ontology/ClassA"/>
        <ontology:hasValue rdf:datatype="http://www.w3.org/2001/XMLSchema#string">StringValue</ontology:hasValue>
    </owl:NamedIndividual>

    <!-- http://www.some/ontology/InvB -->
    <owl:NamedIndividual rdf:about="http://www.some/ontology/InvB">
        <ontology:hasValue rdf:datatype="http://www.w3.org/2001/XMLSchema#string">FooBar</ontology:hasValue>
    </owl:NamedIndividual>

    <owl:Restriction>
        <owl:onProperty rdf:resource="http://www.some/ontology/hasValue"/>
        <owl:someValuesFrom rdf:resource="http://www.w3.org/2001/XMLSchema#string"/>
        <rdfs:subClassOf rdf:resource="http://www.some/ontology/ClassA"/>
    </owl:Restriction>
</rdf:RDF>
</code>```

If I did not misunderstand Table 2 in OWL2-Profiles this ontology should be in OWL2 RL profile. I would expect "InvB" to be classified as type ClassA. But it doesn't. It actually does with reasoners (HermiT, Pellet, ...) but not with Rules (Drools, Graphdb) is this a gap in the specification.

How can my Ontology be "repaired" or is there any workaround?

Cheers,

Robert

答:
Not using anonymous classes on the left-hand side of the GCI is not an option for our application. And yes object properties work perfectly.

After some research we actually found out, that it can never work that way. In the GraphDB .pie file that corresponds to the RL-Profile there is only a notion to some rules "// These are not implemented (and probably not implementable)". This includes the rule "dt-type2" defined in OWL2 RL Section 4.3 Table 8. RDF section 3.1 gives the actual answer why this is not supposed to work.

RDF Graphs

An RDF graph is a set of RDF triples.

3.1 Triples

An RDF triple consists of three components:

the subject, which is an IRI or a blank node

the predicate, which is an IRI

the object, which is an IRI, a literal or a blank node

"FooBar"^^xsd:string rdf:type xsd:string this is simply not allowed but obviously required.

We are quite uncertain what the guys at w3c had in mind besides RDF?!

As it is now, this kind of inference will not work in GraphDB at all (and on no rule engines in general?). But it is not the fault of GraphDB but merely a gap in the specification chain.

However, we did a workaround in our ontology that solves the problem and is working for us. We simply

defined new concepts for the data types we use

Transformed all DataProperties to ObjectProperties

introduces new DataType properties with domain one of the new datatype concepts and range xsd:xyz. For example Property:hasStringValue Domain:string Range:xsd:string

This works for us.

Title: DataProperties in Subclass expression

Body:
I tried working with the OWL2-RL rules build into graphdb. I am obviously doing something wrong or understood something wrong. Here is my toy ontology.

<?xml version="1.0"?>
<rdf:RDF xmlns="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182#"
     xml:base="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:untitled-ontology-182="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182#"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
     xmlns:ontology="http://www.some/ontology/">
    <owl:Ontology rdf:about="http://www.semanticweb.org/rlehmann/ontologies/2017/10/untitled-ontology-182"/>

    <owl:DatatypeProperty rdf:about="http://www.some/ontology/hasValue">
         <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/>
    </owl:DatatypeProperty>

    <owl:Class rdf:about="http://www.some/ontology/ClassA"/>

    <owl:NamedIndividual rdf:about="http://www.some/ontology/InvA">
        <rdf:type rdf:resource="http://www.some/ontology/ClassA"/>
        <ontology:hasValue rdf:datatype="http://www.w3.org/2001/XMLSchema#string">StringValue</ontology:hasValue>
    </owl:NamedIndividual>

    <owl:NamedIndividual rdf:about="http://www.some/ontology/InvB">
        <ontology:hasValue rdf:datatype="http://www.w3.org/2001/XMLSchema#string">FooBar</ontology:hasValue>
    </owl:NamedIndividual>

    <owl:Restriction>
        <owl:onProperty rdf:resource="http://www.some/ontology/hasValue"/>
        <owl:someValuesFrom rdf:resource="http://www.w3.org/2001/XMLSchema#string"/>
        <rdfs:subClassOf rdf:resource="http://www.some/ontology/ClassA"/>
    </owl:Restriction>
</rdf:RDF>

If I did not misunderstand Table 2 in OWL2-Profiles this ontology should be in OWL2 RL profile. I would expect "InvB" to be classified as type ClassA. But it doesn't. It actually does with reasoners (HermiT, Pellet, ...) but not with Rules (Drools, Graphdb) is this a gap in the specification.

How can my Ontology be "repaired" or is there any workaround?

Cheers,

Robert


问:
Do I need momentJS if I'm using moment-with-locales?
Right now I'm adding scripts in my project in following sequence:

```<code>window.top.ak.getScript([
    window.top.akContextPath + "/scripts/css/xxx.css",
    window.top.akContextPath + "/scripts/js/xxx.min.js",
    window.top.akContextPath + "/scripts/js/polyfills.min.js",
    window.top.akContextPath + "/scripts/js/jquery.min.js",
    currHost + "/components/lib/lodash.min.js",
    window.top.akContextPath + "/scripts/js/moment.min.js",
    window.top.akContextPath + "/scripts/js/angular.min.js"
], function() {
    window.top.ak.getScript([
        window.top.akContextPath + "/scripts/js/angular-messages.js",
        window.top.akContextPath + "/scripts/js/angular-ui-router.js",
        window.top.akContextPath + "/scripts/js/angular-animate.js",
        currHost + "/components/lib/toaster.min.js",
        window.top.akContextPath + "/scripts/js/ui-grid.min.js",
        currHost + "/components/lib/defiant.min.js",
        window.top.akContextPath + "/scripts/js/xxx-ui.js",
        currHost + "/components/lib/polyfill-resize.js",
        currHost + "/components/lib/draggable-rows.js",
        currHost + "/components/lib/moment-with-locales.js",
    ], function() {
        window.top.ak.getAsset([
            currHost + "/components/common.bundle.js",
            currHost + "/components/myApp." + pagePath + ".bundle.js"
        ], document);
    }, document);
}, document);
</code>```

Where getScript/getAsset methods are adding these files to HTML. Which works quite fine.

But after inspection I'm curious do I need moment.min.js, if I'm using moment-with-locales.js, am I right?

If it is, where I can put it. is there any library other then xxx.**.js uses it?

答: Moment-with-locales.js is moment, with locales added ;-). So you don't need moment-min.js. Looking through the list of scripts, the other ones don't seem to need momentjs. But then again, momentjs is as basic as jQuery, so why not put it right in the top?</p>

Body:
Right now I'm adding scripts in my project in following sequence:

window.top.ak.getScript([
    window.top.akContextPath + "/scripts/css/xxx.css",
    window.top.akContextPath + "/scripts/js/xxx.min.js",
    window.top.akContextPath + "/scripts/js/polyfills.min.js",
    window.top.akContextPath + "/scripts/js/jquery.min.js",
    currHost + "/components/lib/lodash.min.js",
    window.top.akContextPath + "/scripts/js/moment.min.js",
    window.top.akContextPath + "/scripts/js/angular.min.js"
], function() {
    window.top.ak.getScript([
        window.top.akContextPath + "/scripts/js/angular-messages.js",
        window.top.akContextPath + "/scripts/js/angular-ui-router.js",
        window.top.akContextPath + "/scripts/js/angular-animate.js",
        currHost + "/components/lib/toaster.min.js",
        window.top.akContextPath + "/scripts/js/ui-grid.min.js",
        currHost + "/components/lib/defiant.min.js",
        window.top.akContextPath + "/scripts/js/xxx-ui.js",
        currHost + "/components/lib/polyfill-resize.js",
        currHost + "/components/lib/draggable-rows.js",
        currHost + "/components/lib/moment-with-locales.js",
    ], function() {
        window.top.ak.getAsset([
            currHost + "/components/common.bundle.js",
            currHost + "/components/myApp." + pagePath + ".bundle.js"
        ], document);
    }, document);
}, document);

Where getScript/getAsset methods are adding these files to HTML. Which works quite fine.

But after inspection I'm curious do I need moment.min.js, if I'm using moment-with-locales.js, am I right?

If it is, where I can put it. is there any library other then xxx.**.js uses it?


问:
Displaying MKMapView Without Internet Access
Ey guys, I was wondering if it was at all possible to display an MKMapView without an active internet connection, and if so, how would I go about doing that? Thanks in advance!</p>

答:
mhm, Jasconius,
i'm not sure you are right, the MKMapView uses google on-line services, as you can read on the apple help:

Important: The MapKit framework uses Google services to provide map data. Use of this class and the associated interfaces binds you to the Google Maps/Google Earth API terms of service. You can find these terms of service at http://code.google.com/apis/maps/iphone/terms.html.

If your app works... are you sure it just  have chaced the map area on your device when you tried it once you were on-line?
If you use googleMap when you are on-line and load the italy map, then you close your the app, then go in airplane mode and restart the app then you are able to look at italy again, but if you try to go to france you don't see it...

I tried to to use an off line map with MKMapView, but i had this problem...
now i'm using a map of my own using a UIScroll and a CATiledLayer loading a pdf file, the result is similar to the MKMapView...

luca


问:
total / count items from list json response
im trying to get count / total number of records from list api using Restassured.

Please share thoughts on how can we get it.

ex:

```<code>{
    "final list": [
        {
            "id": 123,
            "name": "sachin"
        },
        {
            "id": 234,
            "name": "sourav"
        }
    ]
}
</code>```

I am expecting total as 2 here. please suggest.

答:
Yo can do the following: </p>

```<code>jp = new JsonPath(response.asString());
String numFromsResponse = jp.get("final list.id.size()").toString();
</code>```

Body:
im trying to get count / total number of records from list api using Restassured.

Please share thoughts on how can we get it.

ex:

{
    "final list": [
        {
            "id": 123,
            "name": "sachin"
        },
        {
            "id": 234,
            "name": "sourav"
        }
    ]
}

I am expecting total as 2 here. please suggest.

Body:
Yo can do the following:

jp = new JsonPath(response.asString());
String numFromsResponse = jp.get("final list.id.size()").toString();


问:
How to deal with "none" values when inserting into SQL database?
Some rows in my data set are like this: where None is suppose to be integer.

```<code>Boston (2017)   Documentary Jon Dunham  5-Dec-17    100 5   None    63  None
</code>```

When I insert this line into Postgres, where the type of column of None is INTEGER, I got this error:

```<code>psycopg2.DataError: invalid input syntax for integer: "None"
</code>```

I store the original data in a csv file, it's a really big dataset(around 2000) how should I deal with the None value?

答:
No value, or unknown in postgres is NULL

https://www.postgresql.org/docs/current/static/functions-comparison.html

A null input is treated as the logical value “unknown”

if you sotre original data in csv format, then use unquoted empty string for importing csv to postgres, but from your sample it looks that you have tsc (tabs in place of commas) and thus you should use \N for nulls.

https://www.postgresql.org/docs/current/static/sql-copy.html

NULL

Specifies the string that represents a null value. The default is \N
  (backslash-N) in text format, and an unquoted empty string in CSV
  format. You might prefer an empty string even in text format for cases
  where you don't want to distinguish nulls from empty strings. This
  option is not allowed when using binary format.

also from quote above you can explicitely specify NULL representation in your csv, eg:

```<code>t=# create table n(i int, t text);
CREATE TABLE
t=# copy n from stdin delimiter '|' null 'None';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> 1|a
>> None|b
>> 2| None
>> None|None
>> \.
COPY 4
t=# select * from n;
 i |   t
---+-------
 1 | a
   | b
 2 |  None
   |
(4 rows)
</code>```

I deliberately made a "typo" with i=2, providing " None", instead of "None" - if you decide to use your null identifier you have to insure it does sright after delimiter, eg if you use tab (as I assume from your sample), it should be tab chr(9), not two or four spaces, otherwise "  None" will be treated as string value, not as NULL...

Body:
Some rows in my data set are like this: where None is suppose to be integer.

Boston (2017)   Documentary Jon Dunham  5-Dec-17    100 5   None    63  None

When I insert this line into Postgres, where the type of column of None is INTEGER, I got this error:

psycopg2.DataError: invalid input syntax for integer: "None"

I store the original data in a csv file, it's a really big dataset(around 2000) how should I deal with the None value?

Body:
No value, or unknown in postgres is NULL

https://www.postgresql.org/docs/current/static/functions-comparison.html

A null input is treated as the logical value “unknown”

if you sotre original data in csv format, then use unquoted empty string for importing csv to postgres, but from your sample it looks that you have tsc (tabs in place of commas) and thus you should use \N for nulls.

https://www.postgresql.org/docs/current/static/sql-copy.html

NULL

Specifies the string that represents a null value. The default is \N
  (backslash-N) in text format, and an unquoted empty string in CSV
  format. You might prefer an empty string even in text format for cases
  where you don't want to distinguish nulls from empty strings. This
  option is not allowed when using binary format.

also from quote above you can explicitely specify NULL representation in your csv, eg:

t=# create table n(i int, t text);
CREATE TABLE
t=# copy n from stdin delimiter '|' null 'None';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> 1|a
>> None|b
>> 2| None
>> None|None
>> \.
COPY 4
t=# select * from n;
 i |   t
---+-------
 1 | a
   | b
 2 |  None
   |
(4 rows)

I deliberately made a "typo" with i=2, providing " None", instead of "None" - if you decide to use your null identifier you have to insure it does sright after delimiter, eg if you use tab (as I assume from your sample), it should be tab chr(9), not two or four spaces, otherwise "  None" will be treated as string value, not as NULL...


问:
Deep copy in ES6 using the spread syntax
I am trying to create a deep copy map method for my Redux project that will work with objects rather than arrays. I read that in Redux each state should not change anything in the previous states.

export const mapCopy = (object, callback) => {
    return Object.keys(object).reduce(function (output, key) {

        output[key] = callback.call(this, {...object[key]});

        return output;
      },
   {});
}
```
<p>It works:</p>
<pre class="lang-js prettyprint-override"><code>return mapCopy(state, e => {

    if (e.id === action.id) {
         e.title = 'new item';
    }

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

However it does not deep copy inner items so I need to tweak it to:

```<code>export const mapCopy = (object, callback) => {
    return Object.keys(object).reduce(function (output, key) {

    let newObject = {...object[key]};
    newObject.style = {...newObject.style};
    newObject.data = {...newObject.data};

    output[key] = callback.call(this, newObject);

    return output;
    }, {});
}
</code>```

This is less elegant as it requires to know which objects are passed.
Is there a way in ES6 to use the spread syntax to deep copy an object?

答:
Use JSON for deep copy

```<code>var newObject = JSON.parse(JSON.stringify(oldObject))
</code>```

var oldObject = {
  name: 'A',
  address: {
    street: 'Station Road',
    city: 'Pune'
  }
}
var newObject = JSON.parse(JSON.stringify(oldObject));

newObject.address.city = 'Delhi';
console.log('newObject');
console.log(newObject);
console.log('oldObject');
console.log(oldObject);```

Body:
I am trying to create a deep copy map method for my Redux project that will work with objects rather than arrays. I read that in Redux each state should not change anything in the previous states.

export const mapCopy = (object, callback) => {
    return Object.keys(object).reduce(function (output, key) {

        output[key] = callback.call(this, {...object[key]});

        return output;
      },
   {});
}

It works:

return mapCopy(state, e => {

    if (e.id === action.id) {
         e.title = 'new item';
    }

    return e;
})

However it does not deep copy inner items so I need to tweak it to:

export const mapCopy = (object, callback) => {
    return Object.keys(object).reduce(function (output, key) {

    let newObject = {...object[key]};
    newObject.style = {...newObject.style};
    newObject.data = {...newObject.data};

    output[key] = callback.call(this, newObject);

    return output;
    }, {});
}

This is less elegant as it requires to know which objects are passed.
Is there a way in ES6 to use the spread syntax to deep copy an object?

Body:
Use JSON for deep copy

var newObject = JSON.parse(JSON.stringify(oldObject))

var oldObject = {
  name: 'A',
  address: {
    street: 'Station Road',
    city: 'Pune'
  }
}
var newObject = JSON.parse(JSON.stringify(oldObject));

newObject.address.city = 'Delhi';
console.log('newObject');
console.log(newObject);
console.log('oldObject');
console.log(oldObject);


问:
setState with nested JSON
I am new to RN and am trying to figure out how to use setState with nested JSON.

My object is in the following format:

```<code>{
  "data": {
    "count": 1,
    "current": [
      {
        "Id":"284"
      },
      {
        "Id":"285"
      },
      {
        "Id":"286"
      }
    ]
  }
}
</code>```

I have set the state as follow:

```<code>state = { notices: [data] };
</code>```

I need to update the count value and set state:

```<code>this.state.notices[0].data.count = newcount
</code>```

I am trying to do it wth this.setState but I can't figure out how to set it for nested JSON.

答:
You can do this as following:

```<code>updateNotices = (newcount) => {
  const { notices } = this.state;
  const newNotices = [... notices];
  newNotices[0].data.count = newcount;
  this.setState({ notices: newNotices });
}
</code>```

Then, you can call updateNotices(1).

Title: setState with nested JSON

Body:
I am new to RN and am trying to figure out how to use setState with nested JSON.

My object is in the following format:

{
  "data": {
    "count": 1,
    "current": [
      {
        "Id":"284"
      },
      {
        "Id":"285"
      },
      {
        "Id":"286"
      }
    ]
  }
}

I have set the state as follow:

state = { notices: [data] };

I need to update the count value and set state:

this.state.notices[0].data.count = newcount

I am trying to do it wth this.setState but I can't figure out how to set it for nested JSON.

Body:
You can do this as following:

updateNotices = (newcount) => {
  const { notices } = this.state;
  const newNotices = [... notices];
  newNotices[0].data.count = newcount;
  this.setState({ notices: newNotices });
}

Then, you can call updateNotices(1).


问:
Accessing controls in Master page from content page
I am trying to access control in Master page from Content page(Asp.net) using javascript like this

```<code>alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').value);
</code>```

control in Master page is as follow,

```<code> <asp:Label ID="lbl" runat="server" Text="one"></asp:Label>
</code>```

But unfortunately it is not working. I am getting undefined value

答:
Using getElementById didn't work for me. The following can be used instead:

```<code>$find('<%=((Label)Master.FindControl("lbl")).ClientID %>');
</code>```

Body:
I am trying to access control in Master page from Content page(Asp.net) using javascript like this

alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').value);

control in Master page is as follow,

 <asp:Label ID="lbl" runat="server" Text="one"></asp:Label>

But unfortunately it is not working. I am getting undefined value

Body:
Using getElementById didn't work for me. The following can be used instead:

$find('<%=((Label)Master.FindControl("lbl")).ClientID %>');


问:
How to save user input to local storage
I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have

$(document).ready(function() {
  $("#add-playername").click(function(e) {
    e.preventDefault();
    var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
    var label = 'Playername ' + (numberOfPlayernames + 1) + ' ';
    var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
    var removeButton = '<button class="remove-playername">Remove</button>';
    var html = "
" + label + input + removeButton + "
";
    $("#form1").find("#add-playername").before(html);
  });
});

$(document).on("click", ".remove-playername", function(e) {
  e.preventDefault();
  $(this).parents(".playername").remove(); //remove playername is connected to this

  $("#form1").find("label[for^='data[playername]']").each(function() {
    $(this).html("Playername " + ($(this).parents('.playername').index() + 1));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
  <div class="gamename">
    <label><b>Enter Game Name</b></label>
    <input type="text" name="game name" placeholder="Game Name" id="user_input">
  </div>
</form>
<form id="form1" method="post">
  <div class="playername">
    <label for="data[playername][0]">Add Player Name</label>
    <input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
  </div>
  <button id="add-playername">Add Player</button>
  <br>
  <br>
  <input type="submit" value="Submit" />
</form></code>```

答:
Grab game and players using the jquery selector on form submit by preventing the form using jquery

Prepare object for the game and players

Convert the object to a string using the JSON.stringify( your_data_object) function

Save to localStorage using localStorage.setItem( 'key' , 'value' ) function

```<code><script>
    $('#form1').submit(function(){

    var game_name = $("#form2 #user_input").val();
    var players = [];

    var players_inputs = $("#form1").find("input[name^='data[playername]']");

    $.each(players_inputs, function(){
        var player = $(this).val();
        players.push(player);
    });

    var data = {
        game_name : game_name,
        players: players
    }
    console.log(data);

    // save to localstorage
    localStorage.setItem('game_players', JSON.stringify(data) );
    event.preventDefault();
});
</script>
</code>```

Title: How to save user input to local storage

Body:
I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have

$(document).ready(function() {
  $("#add-playername").click(function(e) {
    e.preventDefault();
    var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
    var label = 'Playername ' + (numberOfPlayernames + 1) + ' ';
    var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
    var removeButton = '<button class="remove-playername">Remove</button>';
    var html = "
" + label + input + removeButton + "
";
    $("#form1").find("#add-playername").before(html);
  });
});

$(document).on("click", ".remove-playername", function(e) {
  e.preventDefault();
  $(this).parents(".playername").remove(); //remove playername is connected to this

  $("#form1").find("label[for^='data[playername]']").each(function() {
    $(this).html("Playername " + ($(this).parents('.playername').index() + 1));
  });
});

<form id="form2" method="post">

    Enter Game Name
    <input type="text" name="game name" placeholder="Game Name" id="user_input">

</form>
<form id="form1" method="post">

    Add Player Name
    <input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />

  <button id="add-playername">Add Player</button>

  <input type="submit" value="Submit" />
</form>

Body:
Grab game and players using the jquery selector on form submit by preventing the form using jquery

Prepare object for the game and players

Convert the object to a string using the JSON.stringify( your_data_object) function

Save to localStorage using localStorage.setItem( 'key' , 'value' ) function

<script>
    $('#form1').submit(function(){

    var game_name = $("#form2 #user_input").val();
    var players = [];

    var players_inputs = $("#form1").find("input[name^='data[playername]']");

    $.each(players_inputs, function(){
        var player = $(this).val();
        players.push(player);
    });

    var data = {
        game_name : game_name,
        players: players
    }
    console.log(data);

    // save to localstorage
    localStorage.setItem('game_players', JSON.stringify(data) );
    event.preventDefault();
});
</script>


问:
Angular 5 TypeError: AngularCompilerPlugin is not a constructor
Angular 5 aspnetcore 2.0 is my environment.

And I updated my packages to angular 5 and replace AotPlugin to AngularCompilerPlugin in webpack.config.js. while publishing my project, I'm getting this error.

```<code> TypeError: AngularCompilerPlugin is not a constructor
2017-12-07T06:25:19.8388691Z       at module.exports (d:\a\1\s\web\source\webpack.config.js:48:13)
2017-12-07T06:25:19.8388916Z       at requireConfig (d:\a\1\s\web\source\node_modules\webpack\bin\convert-argv.js:102:15)
2017-12-07T06:25:19.8389187Z       at d:\a\1\s\web\source\node_modules\webpack\bin\convert-argv.js:109:17
2017-12-07T06:25:19.8389479Z       at Array.forEach (native)
2017-12-07T06:25:19.8389687Z       at module.exports (d:\a\1\s\web\source\node_modules\webpack\bin\convert-argv.js:107:15)
2017-12-07T06:25:19.8389914Z       at Object.<anonymous> (d:\a\1\s\web\source\node_modules\webpack\bin\webpack.js:153:40)
2017-12-07T06:25:19.8390154Z       at Module._compile (module.js:570:32)
2017-12-07T06:25:19.8390340Z       at Object.Module._extensions..js (module.js:579:10)
2017-12-07T06:25:19.8390524Z       at Module.load (module.js:487:32)
2017-12-07T06:25:19.8390881Z       at tryModuleLoad (module.js:446:12)
2017-12-07T06:25:19.8569143Z d:\a\1\s\web\source\CA.IDM.PAdmin.Web.csproj(41,5): error MSB3073: The command "node node_modules/webpack/bin/webpack.js --env.prod" exited with code 1.
2017-12-07T06:25:19.9453100Z ##[error]Error: C:\Program Files\dotnet\dotnet.exe failed with return code: 1
2017-12-07T06:25:19.9454881Z ##[error]Dotnet command failed with non-zero exit code on the following projects : d:\a\1\s\web\source\CA.IDM.PAdmin.Web.csproj
</code>```

So I revoked this changes and restored AotPlugin in webpack.config.js now my publish got success.

Actually for angular 5 AngularCompilerPlugin used instead of AotPlugin. so my question is did I miss something? what I did wrong here?.

webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin ;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AngularCompilerPlugin ({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin ({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};
</code>```

package.json

```<code>{
  "name": "Web5",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "devDependencies": {
    "@angular/animations": "5.0.5",
    "@angular/common": "5.0.5",
    "@angular/compiler": "5.0.5",
    "@angular/compiler-cli": "5.0.5",
    "@angular/core": "5.0.5",
    "@angular/forms": "5.0.5",
    "@angular/http": "5.0.5",
    "@angular/platform-browser": "5.0.5",
    "@angular/platform-browser-dynamic": "5.0.5",
    "@angular/platform-server": "5.0.5",
    "@angular/router": "5.0.5",
    "@ngtools/webpack": "1.8.5",
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.5.53",
    "@types/webpack-env": "1.13.0",
    "angular2-router-loader": "0.3.5",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "3.2.1",
    "bootstrap": "3.3.7",
    "chai": "4.0.2",
    "css": "2.2.1",
    "css-loader": "0.28.4",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "0.7.3",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "html-loader": "0.4.5",
    "isomorphic-fetch": "2.2.1",
    "jasmine-core": "2.6.4",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",
    "karma": "1.7.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.3",
    "preboot": "4.5.2",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.5.4",
    "style-loader": "0.18.2",
    "to-string-loader": "1.1.5",
    "typescript": "2.6.2",
    "url-loader": "0.5.9",
    "webpack": "2.5.1",
    "webpack-hot-middleware": "2.18.2",
    "webpack-merge": "4.1.0",
    "zone.js": "0.8.12"
  }
}
</code>```

As I check while publishing it not taking the updated versions. what would be the reason?

```<code>12-07T06:23:03.8757490Z   Web5 -> d:\a\1\s\web5.dll
2017-12-07T06:24:43.8922441Z   Web5@0.0.0 d:\a\1\s\web\
2017-12-07T06:24:43.8923186Z   +-- @angular/animations@4.2.5
2017-12-07T06:24:43.8923751Z   +-- @angular/common@4.2.5
2017-12-07T06:24:43.8925363Z   +-- @angular/compiler@4.2.5
2017-12-07T06:24:43.8935332Z   +-- @angular/compiler-cli@4.2.5
2017-12-07T06:24:43.8936589Z   | `-- minimist@1.2.0
2017-12-07T06:24:43.8936969Z   +-- @angular/core@4.2.5
2017-12-07T06:24:43.8937290Z   +-- @angular/forms@4.2.5
2017-12-07T06:24:43.8937696Z   +-- @angular/http@4.2.5
2017-12-07T06:24:43.8938023Z   +-- @angular/platform-browser@4.2.5
2017-12-07T06:24:43.8938348Z   +-- @angular/platform-browser-dynamic@4.2.5
2017-12-07T06:24:43.8938687Z   +-- @angular/platform-server@4.2.5
2017-12-07T06:24:43.8939007Z   +-- @angular/router@4.2.5
2017-12-07T06:24:43.8939341Z   +-- @angular/tsc-wrapped@4.2.5
</code>```

答:
Hard to tell without seeing your webpack.config.

This is the way I prefer:

```<code>const AotPlugin = require('@ngtools/webpack').AngularCompilerPlugin;

plugins: [
        new AotPlugin({
            tsConfigPath: './tsconfig.json',
            entryModule: path.join(__dirname, 'src/app/app.module#AppModule')
        })
]
</code>```

Body:
Angular 5 aspnetcore 2.0 is my environment.

And I updated my packages to angular 5 and replace AotPlugin to AngularCompilerPlugin in webpack.config.js. while publishing my project, I'm getting this error.

 TypeError: AngularCompilerPlugin is not a constructor
2017-12-07T06:25:19.8388691Z       at module.exports (d:\a\1\s\web\source\webpack.config.js:48:13)
2017-12-07T06:25:19.8388916Z       at requireConfig (d:\a\1\s\web\source\node_modules\webpack\bin\convert-argv.js:102:15)
2017-12-07T06:25:19.8389187Z       at d:\a\1\s\web\source\node_modules\webpack\bin\convert-argv.js:109:17
2017-12-07T06:25:19.8389479Z       at Array.forEach (native)
2017-12-07T06:25:19.8389687Z       at module.exports (d:\a\1\s\web\source\node_modules\webpack\bin\convert-argv.js:107:15)
2017-12-07T06:25:19.8389914Z       at Object.<anonymous> (d:\a\1\s\web\source\node_modules\webpack\bin\webpack.js:153:40)
2017-12-07T06:25:19.8390154Z       at Module._compile (module.js:570:32)
2017-12-07T06:25:19.8390340Z       at Object.Module._extensions..js (module.js:579:10)
2017-12-07T06:25:19.8390524Z       at Module.load (module.js:487:32)
2017-12-07T06:25:19.8390881Z       at tryModuleLoad (module.js:446:12)
2017-12-07T06:25:19.8569143Z d:\a\1\s\web\source\CA.IDM.PAdmin.Web.csproj(41,5): error MSB3073: The command "node node_modules/webpack/bin/webpack.js --env.prod" exited with code 1.
2017-12-07T06:25:19.9453100Z ##[error]Error: C:\Program Files\dotnet\dotnet.exe failed with return code: 1
2017-12-07T06:25:19.9454881Z ##[error]Dotnet command failed with non-zero exit code on the following projects : d:\a\1\s\web\source\CA.IDM.PAdmin.Web.csproj

So I revoked this changes and restored AotPlugin in webpack.config.js now my publish got success.

Actually for angular 5 AngularCompilerPlugin used instead of AotPlugin. so my question is did I miss something? what I did wrong here?.

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin ;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AngularCompilerPlugin ({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin ({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

package.json

{
  "name": "Web5",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "devDependencies": {
    "@angular/animations": "5.0.5",
    "@angular/common": "5.0.5",
    "@angular/compiler": "5.0.5",
    "@angular/compiler-cli": "5.0.5",
    "@angular/core": "5.0.5",
    "@angular/forms": "5.0.5",
    "@angular/http": "5.0.5",
    "@angular/platform-browser": "5.0.5",
    "@angular/platform-browser-dynamic": "5.0.5",
    "@angular/platform-server": "5.0.5",
    "@angular/router": "5.0.5",
    "@ngtools/webpack": "1.8.5",
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.5.53",
    "@types/webpack-env": "1.13.0",
    "angular2-router-loader": "0.3.5",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "3.2.1",
    "bootstrap": "3.3.7",
    "chai": "4.0.2",
    "css": "2.2.1",
    "css-loader": "0.28.4",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "0.7.3",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "html-loader": "0.4.5",
    "isomorphic-fetch": "2.2.1",
    "jasmine-core": "2.6.4",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",
    "karma": "1.7.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.3",
    "preboot": "4.5.2",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.5.4",
    "style-loader": "0.18.2",
    "to-string-loader": "1.1.5",
    "typescript": "2.6.2",
    "url-loader": "0.5.9",
    "webpack": "2.5.1",
    "webpack-hot-middleware": "2.18.2",
    "webpack-merge": "4.1.0",
    "zone.js": "0.8.12"
  }
}

As I check while publishing it not taking the updated versions. what would be the reason?

12-07T06:23:03.8757490Z   Web5 -> d:\a\1\s\web5.dll
2017-12-07T06:24:43.8922441Z   Web5@0.0.0 d:\a\1\s\web\
2017-12-07T06:24:43.8923186Z   +-- @angular/animations@4.2.5
2017-12-07T06:24:43.8923751Z   +-- @angular/common@4.2.5
2017-12-07T06:24:43.8925363Z   +-- @angular/compiler@4.2.5
2017-12-07T06:24:43.8935332Z   +-- @angular/compiler-cli@4.2.5
2017-12-07T06:24:43.8936589Z   | `-- minimist@1.2.0
2017-12-07T06:24:43.8936969Z   +-- @angular/core@4.2.5
2017-12-07T06:24:43.8937290Z   +-- @angular/forms@4.2.5
2017-12-07T06:24:43.8937696Z   +-- @angular/http@4.2.5
2017-12-07T06:24:43.8938023Z   +-- @angular/platform-browser@4.2.5
2017-12-07T06:24:43.8938348Z   +-- @angular/platform-browser-dynamic@4.2.5
2017-12-07T06:24:43.8938687Z   +-- @angular/platform-server@4.2.5
2017-12-07T06:24:43.8939007Z   +-- @angular/router@4.2.5
2017-12-07T06:24:43.8939341Z   +-- @angular/tsc-wrapped@4.2.5

Body:
Hard to tell without seeing your webpack.config.

This is the way I prefer:

const AotPlugin = require('@ngtools/webpack').AngularCompilerPlugin;

plugins: [
        new AotPlugin({
            tsConfigPath: './tsconfig.json',
            entryModule: path.join(__dirname, 'src/app/app.module#AppModule')
        })
]


答:
Try this may this works (There you can give a range also to the random number)...

```<code><button onclick="getRandomInt(-5,5)">Try it</button>
<p id="demo"></p>

<script>
function getRandomInt(min, max) {
    document.getElementById("demo").innerHTML = Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</code>```

REF Link

Title: JavaScript Math Object: Negative , Zero and Positive Value

Body:
I want to random a numbers like this from -5....0....5.

<!DOCTYPE html>

<button onclick="myFunction()">Try it</button>

In this case it returns only -1. It is possible to do in javascript math object?

Body:
Try this may this works (There you can give a range also to the random number)...

<button onclick="getRandomInt(-5,5)">Try it</button>
<p id="demo"></p>

<script>
function getRandomInt(min, max) {
    document.getElementById("demo").innerHTML = Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>

REF Link


问:
DataGridColumn Visibility with Converter
I have a DataGrid with an Itemsource of a collection. This DataGrid shows me some values of the axis of a machine. There are different columns, the first important is the axisName. The last important one is the "ReferenceSetting" button.

After pressing this button, a ReferenceSequence is starting. Now, not all Axis are configured to set a reference, this buttons should be collapsed or hidden.

All configured Axis are saved on a List.

Now how can I bind the name of the column to the visibility property of the button column and give the converter the list to check the configuration?

Thanks for helping.

```<code>            <DataGrid Margin="8" Style="{StaticResource CoDeDataGrid}" ItemsSource="{Binding Path=TableDataGridView}"
                                      AutoGenerateColumns="False" IsReadOnly="True" Name="AxisGrid">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Name}">
                        <DataGridTextColumn.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding DataContext.Coordinatesystem,
                                    Converter={StaticResource EnumToDisplayTextConverter} , RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                            </DataTemplate>
                        </DataGridTextColumn.HeaderTemplate>
                    </DataGridTextColumn>
                    ...
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                            <Button Style="{StaticResource CoDeButtonSmall}"
                                    Command="{Binding  Path=DataContext.OnSetReferenceCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                                    CommandParameter="{Binding ElementName=AxisGrid, Path=SelectedItem}">
                                <!-- Visibility="{Binding Name, Converter={StaticResource ButtonNameToVisibilityConverter}, ConverterParameter={...Property TeachAxis of My ViewModel....}">-->
                                <Image Source="C:\Users\PA\Source\Repos\Source\Common.Resources\ImageResources\TestPicture.jpg" Height="24" Width="24"/>
                            </Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
            </DataGrid.Columns>
            </DataGrid>
</code>```

答:
This should do the job</p>

```<code><DataGrid Margin="8" Style="{StaticResource CoDeDataGrid}" ItemsSource="{Binding Path=TableDataGridView}"
          AutoGenerateColumns="False" IsReadOnly="True" Name="AxisGrid">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}">
            <DataGridTextColumn.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.Coordinatesystem,
                      Converter={StaticResource EnumToDisplayTextConverter} , RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                </DataTemplate>
            </DataGridTextColumn.HeaderTemplate>
        </DataGridTextColumn>
        ...
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Style="{StaticResource CoDeButtonSmall}"
                       Command="{Binding  Path=DataContext.OnSetReferenceCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                       CommandParameter="{Binding ElementName=AxisGrid, Path=SelectedItem}"
                       Visibility="{Binding Name, Converter={StaticResource ButtonNameToVisibilityConverter}, ConverterParameter={DataContext.TeachAxis}">
                        <Image Source="C:\Users\PA\Source\Repos\Source\Common.Resources\ImageResources\TestPicture.jpg" Height="24" Width="24"/>
                    </Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

Body:
I have a DataGrid with an Itemsource of a collection. This DataGrid shows me some values of the axis of a machine. There are different columns, the first important is the axisName. The last important one is the "ReferenceSetting" button.

After pressing this button, a ReferenceSequence is starting. Now, not all Axis are configured to set a reference, this buttons should be collapsed or hidden.

All configured Axis are saved on a List.

Now how can I bind the name of the column to the visibility property of the button column and give the converter the list to check the configuration?

Thanks for helping.

            <DataGrid Margin="8" Style="{StaticResource CoDeDataGrid}" ItemsSource="{Binding Path=TableDataGridView}"
                                      AutoGenerateColumns="False" IsReadOnly="True" Name="AxisGrid">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Name}">
                        <DataGridTextColumn.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding DataContext.Coordinatesystem,
                                    Converter={StaticResource EnumToDisplayTextConverter} , RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                            </DataTemplate>
                        </DataGridTextColumn.HeaderTemplate>
                    </DataGridTextColumn>
                    ...
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                            <Button Style="{StaticResource CoDeButtonSmall}"
                                    Command="{Binding  Path=DataContext.OnSetReferenceCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                                    CommandParameter="{Binding ElementName=AxisGrid, Path=SelectedItem}">

                                <Image Source="C:\Users\PA\Source\Repos\Source\Common.Resources\ImageResources\TestPicture.jpg" Height="24" Width="24"/>
                            </Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
            </DataGrid.Columns>
            </DataGrid>

Body:
This should do the job

<DataGrid Margin="8" Style="{StaticResource CoDeDataGrid}" ItemsSource="{Binding Path=TableDataGridView}"
          AutoGenerateColumns="False" IsReadOnly="True" Name="AxisGrid">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}">
            <DataGridTextColumn.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.Coordinatesystem,
                      Converter={StaticResource EnumToDisplayTextConverter} , RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                </DataTemplate>
            </DataGridTextColumn.HeaderTemplate>
        </DataGridTextColumn>
        ...
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Style="{StaticResource CoDeButtonSmall}"
                       Command="{Binding  Path=DataContext.OnSetReferenceCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                       CommandParameter="{Binding ElementName=AxisGrid, Path=SelectedItem}"
                       Visibility="{Binding Name, Converter={StaticResource ButtonNameToVisibilityConverter}, ConverterParameter={DataContext.TeachAxis}">
                        <Image Source="C:\Users\PA\Source\Repos\Source\Common.Resources\ImageResources\TestPicture.jpg" Height="24" Width="24"/>
                    </Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>


问:
Calculating Cursor Position in c#
Hi All
I have a Form with a panel in it.
I want to move an image according to the cursor position.
I have a mouse over function, but how do i do the calculation right ? since the cursor position is from the monitor and the picturebox is from the panel</p>

答:
You can use Control.PointToClient method to convert screen coordinates to the local ones.  If you follow the MSDN link there's a good example that shows how to do that.

```<code>Point localCoordinates = myPictureBox.PointToClient(mouseScreenCoordinates);
</code>```

Title: Calculating Cursor Position in c#

Body:
You can use Control.PointToClient method to convert screen coordinates to the local ones.  If you follow the MSDN link there's a good example that shows how to do that.

Point localCoordinates = myPictureBox.PointToClient(mouseScreenCoordinates);