问:
Server side pagination [ Spring MVC & Angular 4 ]
I'm currently working on getting pages of data from server using Spring MVC and Angular to get the work done, but i'm facing a problem when i try to change the page.

profil-management.component.html

```<code>             <tr
              *ngFor="let profil of profilList | paginate: { id:'profils_pages', itemsPerPage: pageSize, currentPage: p, totalItems: totalObjectCount } ">
              <td><a (click)="onSelect(profil)" data-toggle="modal" data-target="#myModal2"
                     style="text-decoration: none; cursor: pointer">{{profil.eprLabel}}</a>
              </td>
              <td>
                <button type="submit" class="ti-pencil" (click)="onSelectUpdate(profil)" data-toggle="modal"
                        data-target="#myModal"></button>
              </td>
              <td>
                <button type="submit" class="ti-trash" data-toggle="modal" data-target="#deleteModal"
                        (click)="onSelect(profil)"></button>
              </td>
            </tr>
            <div style="text-align: center; margin-left: 35%; margin-top: 3%;">
              <pagination-controls id="profils_pages"
                                   maxSize="10"
                                   (pageChange)="p = getServerData($event)"
                                   directionLinks="true"
                                   autohide="true">
              </pagination-controls>
</code>```

I think the problem is in getServerData(event)

profil-management.component.ts

```<code>   getServerData(event) {
   this.profilManagementService.getProfilsPagination(event - 1).subscribe(
    res => {
     this.profilList = res.json().ecomProfils;
    }, error => {
    }
   );
 }
</code>```

The pagination cursor doesn't change yet it brings the second page from the server.

I'm using ngx-pagination in this code.

答: you need to return event back from your "getServerData" function. Event is nothing but a page number which is getting assign to p variable in pagination-controls directive.</p>

Body:
I'm currently working on getting pages of data from server using Spring MVC and Angular to get the work done, but i'm facing a problem when i try to change the page.

profil-management.component.html

              {{profil.eprLabel}}

                <button type="submit" class="ti-pencil" (click)="onSelectUpdate(profil)" data-toggle="modal"
                        data-target="#myModal"></button>

                <button type="submit" class="ti-trash" data-toggle="modal" data-target="#deleteModal"
                        (click)="onSelect(profil)"></button>

              <pagination-controls id="profils_pages"
                                   maxSize="10"
                                   (pageChange)="p = getServerData($event)"
                                   directionLinks="true"
                                   autohide="true">
              </pagination-controls>

I think the problem is in getServerData(event)

profil-management.component.ts

   getServerData(event) {
   this.profilManagementService.getProfilsPagination(event - 1).subscribe(
    res => {
     this.profilList = res.json().ecomProfils;
    }, error => {
    }
   );
 }

The pagination cursor doesn't change yet it brings the second page from the server.

I'm using ngx-pagination in this code.


来源: stackexchange

问:
Two training ops for slim.learning.train (TensorFlow, TF-Slim)
Some architectures require two or more training ops (for example, in GAN you need to train a generator and discriminator). How can you achieve that with TF-Slim training functions? As far as I can see slim.learning.train takes only one training op.</p>

答:
You can overide train_step_fn, which is the main body function when running slim.learning.train().

For example, suppose you have train_op1 and train_op2, set train_ops = [train_op1, train_op2], and then you can try the following:

```<code>def train_step_fn(session, train_ops, global_step, train_step_kwargs):
  session.run(train_ops[0], ...)
  session.run(train_ops[1], ...)
  ...

slim.learning.train(train_step_fn=train_step_fn, ...)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can overide train_step_fn, which is the main body function when running slim.learning.train().

For example, suppose you have train_op1 and train_op2, set train_ops = [train_op1, train_op2], and then you can try the following:

def train_step_fn(session, train_ops, global_step, train_step_kwargs):
  session.run(train_ops[0], ...)
  session.run(train_ops[1], ...)
  ...

slim.learning.train(train_step_fn=train_step_fn, ...)


问:
export default class Book extends Component VS export default Book
I'm new to react so its just a question that i want to know which one is more efficient and which give the best time complexity.

No. 1

```<code>    export default class BookingTabs extends Component {
  render() {
    return (
    );
  }
}
</code>```

No. 2

```<code>class Book extends Component {
  render() {
    return (
    );
  }
}
export default Book
</code>```

Questions:

which one is more efficient to use?

which one take less time? even difference in micro seconds?

what is the different between export default and module.export?

答:
There is no difference between them. but when you want to use some high order component you should use second one.
for example you want use "connect" for redux applications. you have to write</p>

```<code>class Book extends Component {
  render() {
    return (
    );
  }
}
export default connect(Book)
</code>```

Body:
I'm new to react so its just a question that i want to know which one is more efficient and which give the best time complexity.

No. 1

    export default class BookingTabs extends Component {
  render() {
    return (
    );
  }
}

No. 2

class Book extends Component {
  render() {
    return (
    );
  }
}
export default Book

Questions:

which one is more efficient to use?

which one take less time? even difference in micro seconds?

what is the different between export default and module.export?

Body:
There is no difference between them. but when you want to use some high order component you should use second one.
for example you want use "connect" for redux applications. you have to write

class Book extends Component {
  render() {
    return (
    );
  }
}
export default connect(Book)


问:
Is it good practice to make the constructor throw an exception?
Is it a good practice to make the constructor throw an exception?
For example I have a class Person and I have age as its only attribute. Now
I provide the class as

```<code>class Person{
  int age;
  Person(int age) throws Exception{
   if (age<0)
       throw new Exception("invalid age");
   this.age = age;
  }

  public void setAge(int age) throws Exception{
  if (age<0)
       throw new Exception("invalid age");
   this.age = age;
  }
}
</code>```

答:
I am not for throwing Exceptions in the constructor since I am considering this as non-clean. There are several reasons for my opinion.

As Richard mentioned you cannot initialize an instance in an easy manner. Especially in tests it is really annoying to build a test-wide object only by surrounding it in a try-catch during initialization.

Constructors should be logic-free. There is no reason at all to encapsulate logic in a constructor, since you are always aiming for the Separation of Concerns and Single Responsibility Principle. Since the concern of the constructor is to "construct an object" it should not encapsulate any exception handling if following this approach.

It smells like bad design. Imho if I am forced to do exception handling in the constructor I am at first asking myself if I have any design frauds in my class. It is necessary sometimes, but then I outsource this to a builder or factory to keep the constructor as simple as possible.

So if it is necessary to do some exception handling in the constructor, why would you not outsource this logic to a Builder of Factory? It might be a few more lines of code but gives you the freedom to implement a far more robust and well suited exception handling since you can outsource the logic for the exception handling even more and are not sticked to the constructor, which will encapsulate too much logic. And the client does not need to know anything about your constructing logic if you delegate the exception handling properly.

Body:
Is it a good practice to make the constructor throw an exception?
For example I have a class Person and I have age as its only attribute. Now
I provide the class as

class Person{
  int age;
  Person(int age) throws Exception{
   if (age<0)
       throw new Exception("invalid age");
   this.age = age;
  }

  public void setAge(int age) throws Exception{
  if (age<0)
       throw new Exception("invalid age");
   this.age = age;
  }
}


问:
Can't pickle local object while trying multiprocessing
I´m trying to do a multiprocessing scrape of a website, where I get a list of all the nodes I want to get information from, and then generate a Pool so instead of getting data one by one it does in parallel. My code is the following:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import multiprocessing

def ResPartido(node):

   ft=node.find_element_by_css_selector('.status').text
   if ft.strip()!='FT': return
   hora=node.find_element_by_css_selector('.time').text
   names=list()
   for nam in node.find_elements_by_xpath(
            './/td[contains(@style,"text-align")]/a[contains(@id,"team")]'):
     name=nam.text
     if '(N)' in name:
        name=name.split('(N)')[0]
     names.append(name)
   score=node.find_element_by_css_selector('.red')

   return [hora,name,score.text]

if __name__ == "__main__":

   browser=webdriver.Chrome()
   SOME CODE
   nodes=browser.find_elements_by_xpath(
        '//tr[contains(@align,"center")]/following-sibling::tr[.//div[contains(@class,"toolimg")]]')
   p = multiprocessing.Pool()

   p.map(ResPartido,nodes)   <---Here is the error
   .......

   >>AttributeError: Can't pickle local object '_createenviron.<locals>.encodekey'
</code>```

Image of my python terminal with the error

Checking the documentation, it says lists are pickable objects, and so are functions declared before the main one, so I don´t understand what am I doing wrong when using MultiProcessing.

答:
From what I´ve been reading, the problem is that nodes is a list of webdriver objects, which are not serializable. Given this, the only possible approach I can come with is the following.

1- Instead of getting the whole  tag as an element of nodes list, get only what makes it unique from the other . In my example, each row has a serial number identifier

```<code>nodes=browser.find_elements_by_xpath(
    '//tr[contains(@align,"center")]/following-sibling::tr[.//div[contains(@class,"toolimg")]]/@id').get_attribute()

nodes=['1232489','1242356',......]
</code>```

2- Pass it, along with the browser to the map function

```<code>pr=partial(ResPartido,b=browser)
p.map(pr,nodes)
</code>```

3- In the ResPartido function find that unique row with the string that identifies its @id

```<code>browser.find_elements_by_xpath('//tr[contains(@id,%s)]' %s node)
</code>```

With that bypass, which I haven´t tested yet, I think I could get what I intended without problems with pickleable objects

Body:
I´m trying to do a multiprocessing scrape of a website, where I get a list of all the nodes I want to get information from, and then generate a Pool so instead of getting data one by one it does in parallel. My code is the following:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import multiprocessing

def ResPartido(node):

   ft=node.find_element_by_css_selector('.status').text
   if ft.strip()!='FT': return
   hora=node.find_element_by_css_selector('.time').text
   names=list()
   for nam in node.find_elements_by_xpath(
            './/td[contains(@style,"text-align")]/a[contains(@id,"team")]'):
     name=nam.text
     if '(N)' in name:
        name=name.split('(N)')[0]
     names.append(name)
   score=node.find_element_by_css_selector('.red')

   return [hora,name,score.text]

if __name__ == "__main__":

   browser=webdriver.Chrome()
   SOME CODE
   nodes=browser.find_elements_by_xpath(
        '//tr[contains(@align,"center")]/following-sibling::tr[.//div[contains(@class,"toolimg")]]')
   p = multiprocessing.Pool()

   p.map(ResPartido,nodes)   <---Here is the error
   .......

   >>AttributeError: Can't pickle local object '_createenviron.<locals>.encodekey'

Image of my python terminal with the error

Checking the documentation, it says lists are pickable objects, and so are functions declared before the main one, so I don´t understand what am I doing wrong when using MultiProcessing.

Body:
From what I´ve been reading, the problem is that nodes is a list of webdriver objects, which are not serializable. Given this, the only possible approach I can come with is the following.

1- Instead of getting the whole  tag as an element of nodes list, get only what makes it unique from the other . In my example, each row has a serial number identifier

nodes=browser.find_elements_by_xpath(
    '//tr[contains(@align,"center")]/following-sibling::tr[.//div[contains(@class,"toolimg")]]/@id').get_attribute()

nodes=['1232489','1242356',......]

2- Pass it, along with the browser to the map function

pr=partial(ResPartido,b=browser)
p.map(pr,nodes)

3- In the ResPartido function find that unique row with the string that identifies its @id

browser.find_elements_by_xpath('//tr[contains(@id,%s)]' %s node)

With that bypass, which I haven´t tested yet, I think I could get what I intended without problems with pickleable objects


问:
VueJS: TypeError: Cannot read property of undefined when Reload
I have a page like this:

```<code><template>
  <div class="row flex">
    {{posts.id}}
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    async asyncData ({ route }) {
      let { data } = await axios.get('http://localhost:8000/api/v1/feeds/' + route.params.id + '/')
      return {
        posts: data
      }
    }
  }
</script>
</code>```

When I click link with hot reload (router-link), it display well. But when I reload this window, it appear in 1 seconds and disappear then.

Video: http://g.recordit.co/ht0a0K2X81.gif

Error Log:

How can I fix this?

答:
Add a property to your data i.e dataLoaded: false. When your ajax request has finished, set this.dataLoaded = true. On your template add v-if="dataLoaded. This will mean the template data won't render until you're ready.

You could also do v-if="posts" as another way but I generally have a consistent dataLoaded prop available to do this.

Edit: I just looked at your example again and doing something like this would work:

```<code><template>
  <div class="row flex" v-if="posts">
    {{posts.id}}
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    data () {
        return {
            posts: null
        }
    }
    methods:{
        loadPosts () {
            return axios.get('http://localhost:8000/api/v1/feeds/' + this.$route.params.id + '/')
        }
    },
    created () {
        this.loadPosts().then(({data}) => {
            this.posts = data
        })
    }
  }
</script>
</code>```

I've removed the async and just setting posts when the axios request returns it's promise. Then on the template, it's only showing posts is valid.

Edit

You can also use your original code and just add v-if="posts" to the div you have in your template.

Body:
I have a page like this:

<template>

    {{posts.id}}

</template>

When I click link with hot reload (router-link), it display well. But when I reload this window, it appear in 1 seconds and disappear then.

Video: http://g.recordit.co/ht0a0K2X81.gif

Error Log:

How can I fix this?

Body:
Add a property to your data i.e dataLoaded: false. When your ajax request has finished, set this.dataLoaded = true. On your template add v-if="dataLoaded. This will mean the template data won't render until you're ready.

You could also do v-if="posts" as another way but I generally have a consistent dataLoaded prop available to do this.

Edit: I just looked at your example again and doing something like this would work:

<template>
  <div class="row flex" v-if="posts">
    {{posts.id}}
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    data () {
        return {
            posts: null
        }
    }
    methods:{
        loadPosts () {
            return axios.get('http://localhost:8000/api/v1/feeds/' + this.$route.params.id + '/')
        }
    },
    created () {
        this.loadPosts().then(({data}) => {
            this.posts = data
        })
    }
  }
</script>

I've removed the async and just setting posts when the axios request returns it's promise. Then on the template, it's only showing posts is valid.

Edit

You can also use your original code and just add v-if="posts" to the div you have in your template.


问:
How to get values of check-boxes in nested ng-repeat in Angularjs
I have a nested ng-repeat, first one as a title of department, second one shows employees that belong to this department. I hope to know how to capture or get their values if I have multiple checked departments keys and multiple employees keys, then send them to a web API. Thanks in advance.

The HTML is like

```<code><fieldset id="field3">
   <table>
       <tr ng-repeat="e in empdepts | groupBy:'dep_LDesc'">
           <td>
               <label ng-click="showContent = !showContent"></label>
               <details ng-open="showContent">
               <summary><input type="checkbox" ng-model="e[0].master" ng-click="group(e[0].master,e)" /> {{e[0].dep_LDesc}}</summary>
               <div ng-repeat="employee in e">
               <input type="checkbox" ng-model="employee.details" > {{employee.Sname}}
               </div>
               </details>
           </td>
       </tr>
   </table>

   <hr />
   <table>
       <tr>
            <td><input type="checkbox" ng-model="all" ng-click="selectall(all)"  /> All Departments</td>
       </tr>
       <tr>
            <td><input type="checkbox" ng-model="self"/> Self Services </td>
       </tr>
    </table>
</fieldset>
</code>```

The Controller is like

```<code>Assign.controller("AssignController", function ($scope, Assignments) {

LoadEmpDepts();
function LoadEmpDepts() {
    Assignments.getempdepts().then(function (response) {
        $scope.empdepts = (response.data);
        console.log($scope.empdepts);
    })
}

$scope.group = function (m, x) {
    angular.forEach(x,function (cv) {
        cv.details = m;
    })
   return m;
}

$scope.selectall = function (value) {
    $scope.master = value;
    angular.forEach($scope.empdepts, function (cv) {
        cv.details = value;
        cv.master = value;
    })
}
</code>```

Thanks in advance

答:
Use Angular Copy which send only that checkbox value which is modified. And You need to push all the check boxes value in array.

See Example in Official Documentation of AngularJS

Push Code Example:

In controller

File Name: 1.js

```<code>var app = angular.module("myApp",[]);
app.controller("myController",function($scope){
$scope.newArray =[];
$scope.arrayPush =function()
{
    console.log("new1");
    $scope.newArray.push({name:$scope.name});
    console.log($scope.newArray);
}
})
</code>```

In Views

File Name: 1.html

```<code><div ng-app="myApp" ng-controller="myController">
<p>Input something in the input box:</p>
<input type="text" ng-model="name" placeholder="Enter name here">
<button ng-click="arrayPush()">Test Button</button>
</div>
</body>
 <script type="text/javascript" src="1.js"></script>
</code>```

Try this Code.. If you get any error then please mention in comment..

Thanks...

Answer Updated

Body:
I have a nested ng-repeat, first one as a title of department, second one shows employees that belong to this department. I hope to know how to capture or get their values if I have multiple checked departments keys and multiple employees keys, then send them to a web API. Thanks in advance.

The HTML is like

<fieldset id="field3">

               <input type="checkbox" ng-model="e[0].master" ng-click="group(e[0].master,e)" /> {{e[0].dep_LDesc}}

               <input type="checkbox" ng-model="employee.details" > {{employee.Sname}}

            <input type="checkbox" ng-model="all" ng-click="selectall(all)"  /> All Departments

            <input type="checkbox" ng-model="self"/> Self Services

</fieldset>

The Controller is like

Assign.controller("AssignController", function ($scope, Assignments) {

LoadEmpDepts();
function LoadEmpDepts() {
    Assignments.getempdepts().then(function (response) {
        $scope.empdepts = (response.data);
        console.log($scope.empdepts);
    })
}

$scope.group = function (m, x) {
    angular.forEach(x,function (cv) {
        cv.details = m;
    })
   return m;
}

$scope.selectall = function (value) {
    $scope.master = value;
    angular.forEach($scope.empdepts, function (cv) {
        cv.details = value;
        cv.master = value;
    })
}

Thanks in advance

Body:
Use Angular Copy which send only that checkbox value which is modified. And You need to push all the check boxes value in array.

See Example in Official Documentation of AngularJS

Push Code Example:

In controller

File Name: 1.js

var app = angular.module("myApp",[]);
app.controller("myController",function($scope){
$scope.newArray =[];
$scope.arrayPush =function()
{
    console.log("new1");
    $scope.newArray.push({name:$scope.name});
    console.log($scope.newArray);
}
})

In Views

File Name: 1.html

<div ng-app="myApp" ng-controller="myController">
<p>Input something in the input box:</p>
<input type="text" ng-model="name" placeholder="Enter name here">
<button ng-click="arrayPush()">Test Button</button>
</div>
</body>
 <script type="text/javascript" src="1.js"></script>

Try this Code.. If you get any error then please mention in comment..

Thanks...

Answer Updated


问:
custom spinner not showing drop down options
I have created a custom spinner with the following background. Now my issue is I can not use the drop down arrow (drop down arrow don't show options). Any help please?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorGreen"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topRightRadius="@dimen/x30" android:bottomRightRadius="@dimen/x30"/>
            <padding android:left="0dp" android:top="0dip" android:right="0dip" android:bottom="0dip" />
        </shape>
    </item>
    <item android:right="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorWhite"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topLeftRadius="@dimen/x30" android:bottomLeftRadius="@dimen/x30" ></corners>
            <padding android:left="0dip" android:top="0dip" android:right="0dp" android:bottom="0dip" />
        </shape>
    </item>
    <item
        android:bottom="@dimen/x20"
        android:top="@dimen/x20"
        android:right="@dimen/x20">
        <bitmap android:src="@drawable/drop_down"
            android:gravity="center|right" />
    </item>

</layer-list>
</code>```

答:
remove this from your xml

```<code><item
    android:bottom="@dimen/x20"
    android:top="@dimen/x20"
    android:right="@dimen/x20">
    <bitmap android:src="@drawable/drop_down"
        android:gravity="center|right" />
</item>
</code>```

And add another button in your xml very next to dropdown. Give that button background as drawable drop_down.Then in onCliskListener of that button you can show/hide your dropdown list. Set adapter in onClick and provide this adapter to spinner so upon click it will create your drop down and as they are very close to eachother your button looks part of your dropdown.

Body:
I have created a custom spinner with the following background. Now my issue is I can not use the drop down arrow (drop down arrow don't show options). Any help please?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorGreen"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topRightRadius="@dimen/x30" android:bottomRightRadius="@dimen/x30"/>
            <padding android:left="0dp" android:top="0dip" android:right="0dip" android:bottom="0dip" />
        </shape>
    </item>
    <item android:right="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorWhite"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topLeftRadius="@dimen/x30" android:bottomLeftRadius="@dimen/x30" ></corners>
            <padding android:left="0dip" android:top="0dip" android:right="0dp" android:bottom="0dip" />
        </shape>
    </item>
    <item
        android:bottom="@dimen/x20"
        android:top="@dimen/x20"
        android:right="@dimen/x20">
        <bitmap android:src="@drawable/drop_down"
            android:gravity="center|right" />
    </item>

</layer-list>

Body:
remove this from your xml

<item
    android:bottom="@dimen/x20"
    android:top="@dimen/x20"
    android:right="@dimen/x20">
    <bitmap android:src="@drawable/drop_down"
        android:gravity="center|right" />
</item>

And add another button in your xml very next to dropdown. Give that button background as drawable drop_down.Then in onCliskListener of that button you can show/hide your dropdown list. Set adapter in onClick and provide this adapter to spinner so upon click it will create your drop down and as they are very close to eachother your button looks part of your dropdown.


问:
How to compare Character for empty space
I need to check if a Character is a space, how do you do that?</p>

```<code>for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}
</code>```

答:
easiest way </p>

```<code>var str : String = textField.stringValue
for i in 0...str.count-1{
    var spaceChr : Character = str.removeFirst() //init
    if spaceChr == " " { //doit}
}
</code>```

Body:
I need to check if a Character is a space, how do you do that?

for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}

Body:
easiest way

var str : String = textField.stringValue
for i in 0...str.count-1{
    var spaceChr : Character = str.removeFirst() //init
    if spaceChr == " " { //doit}
}


问:
SearchExecutor (JSOM) did not retrieve values from Sharepoint online user profile
I'm trying to perform people search in SharePoint online user profile from Sharepoint hosted app but it returns no data.

I'm using the following code to do this:

```<code>clientContext = new SP.ClientContext.get_current();

// Building Keyword query for the search
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);

keywordQuery.set_queryText("mohammed");
keywordQuery.set_sourceId("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31");
keywordQuery.set_rowLimit(500);
keywordQuery.set_trimDuplicates(false);

var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
results = searchExecutor.executeQuery(keywordQuery);

clientContext.executeQueryAsync(
            function () {
                alert(results.m_value);
            },
            function (err) {
                alert("Error");
            }
        );
</code>```

I'm trying to search user profile which contains "mohammed" text.

searchExecutor.executeQuery(keywordQuery) executes without any error but results.m_value returns 0. If I get value from results.m_value then I can move towards reading UserProfile properties using PeopleManager

Note: I've user as Mohammed Arief Kannubasha

Anyone please advice, thanks in advance

答:
Try this</p>

```<code>keywordQuery.set_queryText("mohammed*");
</code>```

Body:
I'm trying to perform people search in SharePoint online user profile from Sharepoint hosted app but it returns no data.

I'm using the following code to do this:

clientContext = new SP.ClientContext.get_current();

// Building Keyword query for the search
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);

keywordQuery.set_queryText("mohammed");
keywordQuery.set_sourceId("B09A7990-05EA-4AF9-81EF-EDFAB16C4E31");
keywordQuery.set_rowLimit(500);
keywordQuery.set_trimDuplicates(false);

var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
results = searchExecutor.executeQuery(keywordQuery);

clientContext.executeQueryAsync(
            function () {
                alert(results.m_value);
            },
            function (err) {
                alert("Error");
            }
        );

I'm trying to search user profile which contains "mohammed" text.

searchExecutor.executeQuery(keywordQuery) executes without any error but results.m_value returns 0. If I get value from results.m_value then I can move towards reading UserProfile properties using PeopleManager

Note: I've user as Mohammed Arief Kannubasha

Anyone please advice, thanks in advance

Body:
Try this

keywordQuery.set_queryText("mohammed*");


问:
adding products to best selling products list in Storefront home page
I might lose my mind, but I could not find out anywhere in wp-admin for adding a product to best selling product lists in Storefront theme's homepage.

Anyone guides me please?
Thanks a lot.

答:
Thos are best selling products, to add them, you need to sell better :-).

I can think of 2 workarounds:

You can create a coupon code for you, to make them free, and buy a lot of them so they will be included in the best selling products.

You can use another widget and name it best selling products and include in it the products you want.

If this does not answer your needs, please provide more informations about your use case to find the best/better solution.

Cheers.


问:
applying Gregorian Calendar in JAVA
```<code>import  java.util.GregorianCalendar ;
public class MyCalendar extends  GregorianCalendar  {
public static void main(String[] args) {
           MyCalendar a = new MyCalendar();
           System.out.println(a.getCurrenttime());
}

public String getCurrenttime(){
     String time= YEAR+"-"+(MONTH+1)+"-"+DATE+"-"+HOUR+"-"+MINUTE+"-"+SECOND;
     return time;}}
</code>```

However, it always show the same time. What have I done wrong.

P.S. it is intended not to use command like gettime() directely. The string should remain there.

答:
By using YEAR, MONTH... and so on, Here you are accessing static fields inherited from the GregorianCalendar class.
However, you have to access the fields of your Calendar using these variables in somthing like this : </p>

```<code>     public String getCurrenttime(){

    String time= this.get(YEAR)+"-"+(this.get(MONTH)+1)+"-"+
            this.get(DATE)+"-"+this.get(HOUR_OF_DAY)+"-"+this.get(MINUTE)+"-"+this.get(SECOND);
    return time;
}
</code>```

Title: applying Gregorian Calendar in JAVA

Body:
import  java.util.GregorianCalendar ;
public class MyCalendar extends  GregorianCalendar  {
public static void main(String[] args) {
           MyCalendar a = new MyCalendar();
           System.out.println(a.getCurrenttime());
}

public String getCurrenttime(){
     String time= YEAR+"-"+(MONTH+1)+"-"+DATE+"-"+HOUR+"-"+MINUTE+"-"+SECOND;
     return time;}}

However, it always show the same time. What have I done wrong.

P.S. it is intended not to use command like gettime() directely. The string should remain there.

Body:
By using YEAR, MONTH... and so on, Here you are accessing static fields inherited from the GregorianCalendar class.
However, you have to access the fields of your Calendar using these variables in somthing like this :

     public String getCurrenttime(){

    String time= this.get(YEAR)+"-"+(this.get(MONTH)+1)+"-"+
            this.get(DATE)+"-"+this.get(HOUR_OF_DAY)+"-"+this.get(MINUTE)+"-"+this.get(SECOND);
    return time;
}


问:
overloading delete [] operator with throw in c++
As per code it should execute catch block but why is it not executing

How to test for the else operator in overloaded delete operator

Thanks in advance

```<code>#include<iostream>
#include<stdlib.h>

using namespace std;

void operator delete[](void *p) throw(int)
{
    if (p)
    {
        cout << "address of p is" << p << endl;
        free(p);
        cout << "in delete\n" << endl;

    }
    else
    {
        cout << "in throw \n";
        throw 5;
    }
}

int main()
{
    try
    {
        int *a = new int[20];
        a = NULL;
        delete[] a;
    }
    catch (...)
    {
        cout << "in catch" << endl;
    }
}
</code>```

答:
The *p in operator overloaded function accepts an address.
Send an address when calling it by using & after delete statement. In this example...

```<code>#include<iostream>
#include<stdlib.h>

using namespace std;

void operator delete[](void *p = NULL) throw(int)
{
    if (p)
    {
        cout << "address of p is" << p << endl;
        free(p);
        cout << "in delete\n" << endl;

    }
    else
    {
        cout << "in throw \n";
        throw 5;
    }
}

int main()
{
    try
    {
        int *a = new int[20];
        a = NULL;
        delete[] &a;
    }
    catch (...)
    {
        cout << "in catch" << endl;
    }
}
</code>```

Body:
As per code it should execute catch block but why is it not executing

How to test for the else operator in overloaded delete operator

Thanks in advance

#include<iostream>
#include<stdlib.h>

using namespace std;

void operator delete[](void *p) throw(int)
{
    if (p)
    {
        cout << "address of p is" << p << endl;
        free(p);
        cout << "in delete\n" << endl;

    }
    else
    {
        cout << "in throw \n";
        throw 5;
    }
}

int main()
{
    try
    {
        int *a = new int[20];
        a = NULL;
        delete[] a;
    }
    catch (...)
    {
        cout << "in catch" << endl;
    }
}

Body:
The *p in operator overloaded function accepts an address.
Send an address when calling it by using & after delete statement. In this example...

#include<iostream>
#include<stdlib.h>

using namespace std;

void operator delete[](void *p = NULL) throw(int)
{
    if (p)
    {
        cout << "address of p is" << p << endl;
        free(p);
        cout << "in delete\n" << endl;

    }
    else
    {
        cout << "in throw \n";
        throw 5;
    }
}

int main()
{
    try
    {
        int *a = new int[20];
        a = NULL;
        delete[] &a;
    }
    catch (...)
    {
        cout << "in catch" << endl;
    }
}


问:
Unable to merge dex
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

```<code>    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My app gradle:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}
</code>```

And my module gradle:

```<code>    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}
</code>```

My second module:

```<code>     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}
</code>```

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D

答:
In my case, Unfortunately, neither Michel's nor Suragch's solutions worked for me.

So I solved this issue by doing the following:

In gradle:3.0 the compile configuration is now deprecated and should be replaced by implementation or api. For more information you can read here You can read the official docs at Gradle Build Tool

The compile  configuration still exists but should not be used as it will not offer  the guarantees that the api and implementation
  configurations provide.

it's better to use implementation or api rather compile

just replace compile with implementation, debugCompile with debugImplementation, testCompile with testImplementation and androidtestcompile with androidTestImplementation

For example: Instead of this

```<code>compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.github.bumptech.glide:glide:4.0.0'
</code>```

use like this

```<code>implementation 'com.android.support:appcompat-v7:26.0.2'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.github.bumptech.glide:glide:4.0.0'
</code>```

After that

Delete the .gradle folder inside your project  ( Note that, in order to see .gradle, you need to switch to the "Project" view in the navigator on the top left )

Delete all the build folders and the gradle cache.

From the Build menu, press the Clean Project button.

After task completed, press the Rebuild Project button from the Build menu.

Hope it will helps !

Title: Unable to merge dex

Body:
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app gradle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}

And my module gradle:

    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}

My second module:

     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D

Body:
In my case, Unfortunately, neither Michel's nor Suragch's solutions worked for me.

So I solved this issue by doing the following:

In gradle:3.0 the compile configuration is now deprecated and should be replaced by implementation or api. For more information you can read here You can read the official docs at Gradle Build Tool

The compile  configuration still exists but should not be used as it will not offer  the guarantees that the api and implementation
  configurations provide.

it's better to use implementation or api rather compile

just replace compile with implementation, debugCompile with debugImplementation, testCompile with testImplementation and androidtestcompile with androidTestImplementation

For example: Instead of this

compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.github.bumptech.glide:glide:4.0.0'

use like this

implementation 'com.android.support:appcompat-v7:26.0.2'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.github.bumptech.glide:glide:4.0.0'

After that

Delete the .gradle folder inside your project  ( Note that, in order to see .gradle, you need to switch to the "Project" view in the navigator on the top left )

Delete all the build folders and the gradle cache.

From the Build menu, press the Clean Project button.

After task completed, press the Rebuild Project button from the Build menu.

Hope it will helps !


问:
Saving dictionary key values to a variable
I am passing keyword as the parameter to function and want to save the value of that keyword to a variable.

The is in the form of a dictionary:

This is the code so far:

```<code>def foo(**var2):
    print (var2)

foo(source_id=3, limit = 200)
foo(research_id = 1)
</code>```

I want to save values of source_id, limit and research_id to a variable.

答:
Is this what you are after:

```<code>def foo(**var2):
    print (var2)
    vars_passed = list(var2.values())
    return vars_passed

res = foo(source_id=3, limit = 200)
print(res)  # -> [3, 200]
</code>```

NOTE

I would not recommend the above practice because ordering in dictionaries is not guaranteed. As a result, in your case, you can't be sure what 3 and what 200 is. I would get the whole dict.

Body:
I am passing keyword as the parameter to function and want to save the value of that keyword to a variable.

The is in the form of a dictionary:

This is the code so far:

def foo(**var2):
    print (var2)

foo(source_id=3, limit = 200)
foo(research_id = 1)

I want to save values of source_id, limit and research_id to a variable.

Body:
Is this what you are after:

def foo(**var2):
    print (var2)
    vars_passed = list(var2.values())
    return vars_passed

res = foo(source_id=3, limit = 200)
print(res)  # -> [3, 200]

NOTE

I would not recommend the above practice because ordering in dictionaries is not guaranteed. As a result, in your case, you can't be sure what 3 and what 200 is. I would get the whole dict.


问:
Finding connections between objects to the nth degree
For the following models:

```<code>class Entity(models.Model):
    name = models.CharField(max_length=256)

class Entry(models.Model):
    """ A <subj> has a <connection> to an <obj>
    """
    subj = models.ForeignKey(Entity, related_name='subject')
    connection = models.CharField(max_length=512)
    obj = models.ForeignKey(Entity, related_name='object')
</code>```

I have this kind of data stored:

A works at Z

B works at Z

B is the brother of C

C lives next door to D

where A, B, C, D and Z are Entity instances
and "works at", etc are stored in the 'relation' field of the Entry model.

Now, how do I proceed to find a link between A and D, considering there are many connections between all of the Entities? I would like to be able to print out something like:

A is connected to D in the 4th degree (and show the steps in the meanwhile).

I've tagged this as a Django question as the intent is to use this on a Django-powered website, but I wonder whether Django's ORM can help here.

Thanks in advance!

答:
This is a graph theory problem. Your model represents edges connecting nodes, and you want to find paths between nodes. There are python libs for this kind of thing, such as the python interface to the Boost library.

read up on graph theory, and check out relevant python packages. The search algorithm you need will be breadth or depth first search.

ContentLicense: CC BY-SA 2.5

Body:
For the following models:

class Entity(models.Model):
    name = models.CharField(max_length=256)

class Entry(models.Model):
    """ A <subj> has a <connection> to an <obj>
    """
    subj = models.ForeignKey(Entity, related_name='subject')
    connection = models.CharField(max_length=512)
    obj = models.ForeignKey(Entity, related_name='object')

I have this kind of data stored:

A works at Z

B works at Z

B is the brother of C

C lives next door to D

where A, B, C, D and Z are Entity instances
and "works at", etc are stored in the 'relation' field of the Entry model.

Now, how do I proceed to find a link between A and D, considering there are many connections between all of the Entities? I would like to be able to print out something like:

A is connected to D in the 4th degree (and show the steps in the meanwhile).

I've tagged this as a Django question as the intent is to use this on a Django-powered website, but I wonder whether Django's ORM can help here.

Thanks in advance!


问:
Using variable number of float arguments
I'm trying to implement a flexible constructor for my struct Polynomial :

```<code>struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};
</code>```

The degree of the polynomial is variable.
What I would like is to have a constructor like

```<code>Polynomial(float... _coefficients);
</code>```

I've tried variadic template :

```<code>template<float... Args>
Polynomial(Args... args);
</code>```

But float is a non-type, so I've done :

```<code>template<typename... Args>
Polynomial(Args... args);
</code>```

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

```<code>Polynomial(size_t _degree, ...);
</code>```

But it is really unsafe.

At the moment I'm using :

```<code>Polynomial(std::vector<float>);
</code>```

But this force the call to be like :

```<code>Polynomial P({f1, f2, f3}); // with fn floats
</code>```

So I would like to know if there is a good way to do this.

Thank you !

答:
The way you are doing it is a "good way". Imagine the caller wants to pass 100 coefficients. If you use variadics you force the caller to do something like that:

```<code>float c1,c2,c3,....c100;
// init them
Polynomial P(c1, c2, c3,....,c100);
</code>```

If I was to use 100 coefficients I would certainly store them in a vector, and it would be rather cumbersome to pass them to your polynomial:

```<code>auto coeffs = std::vector<float>(100);
Polynomial P(coeffs[0],coeffs[1],....,coeffs[100]);
</code>```

If however, you accept a vector, the caller can do both without pain:

```<code>Polynomial P({c1,c2,c2});
Polynomial P(coeffs);
</code>```

On the other hand, using std::vector but not allowing a different container is an arbitrary restriction. The better way then would be to accept iterators, and let the caller do:

```<code>Polynomial P(coeffs.begin(),coeffs.end());
</code>```

Body:
I'm trying to implement a flexible constructor for my struct Polynomial :

struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};

The degree of the polynomial is variable.
What I would like is to have a constructor like

Polynomial(float... _coefficients);

I've tried variadic template :

template<float... Args>
Polynomial(Args... args);

But float is a non-type, so I've done :

template<typename... Args>
Polynomial(Args... args);

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

Polynomial(size_t _degree, ...);

But it is really unsafe.

At the moment I'm using :

Polynomial(std::vector<float>);

But this force the call to be like :

Polynomial P({f1, f2, f3}); // with fn floats

So I would like to know if there is a good way to do this.

Thank you !

Body:
The way you are doing it is a "good way". Imagine the caller wants to pass 100 coefficients. If you use variadics you force the caller to do something like that:

float c1,c2,c3,....c100;
// init them
Polynomial P(c1, c2, c3,....,c100);

If I was to use 100 coefficients I would certainly store them in a vector, and it would be rather cumbersome to pass them to your polynomial:

auto coeffs = std::vector<float>(100);
Polynomial P(coeffs[0],coeffs[1],....,coeffs[100]);

If however, you accept a vector, the caller can do both without pain:

Polynomial P({c1,c2,c2});
Polynomial P(coeffs);

On the other hand, using std::vector but not allowing a different container is an arbitrary restriction. The better way then would be to accept iterators, and let the caller do:

Polynomial P(coeffs.begin(),coeffs.end());


问:
How it is possible to show a choice field (checkboxes) with the selected value
I use an Symfony2 form with a choice field based on 4 checkboxes. Now i have the Problem, that i can't reload data in this choice field.That means, when in the database the value 9 is stored, will the checkbox "unknown if "lang test" performed" not be selected, when i load the entity in this form.

```<code>->add('fu5LangTest', 'choice', array(
           'choices' =>array(
               'poor compliance'=>0,
               'negative'=>1,
               'positive (recognizes at least 1 image reliably)'=>2,
               'unknown if "lang test" performed'=>9),
           'choice_value' =>function (DataEFu5 $entity = null) {
                            return $entity ? $entity->getFu5LangTest() : '';
                          },
           'expanded'=>true))
</code>```

I tried a lot of things with the choice_value Attribut, but i think i'm using it wrong. Whats the right way? i didn't found some useful Information. What i have to do, that the correct checkbox will be selected after an reload?

The storing process is working fine.

Thanks for an feedback

答:
The form is not the right place to do domain Logic.

Anyway, the data has the current fu5LangTest value. You should use

```<code>->add('fu5LangTest', 'choice', array(
       'choices' =>array(
           'poor compliance'=>0,
           'negative'=>1,
           'positive (recognizes at least 1 image reliably)'=>2,
           'unknown if "lang test" performed'=>9
       ),
       // ...
</code>```

Form creation in Controller:

```<code>$object = new DataEFu5(); //or get it by your repository
//this condition will be better in a service as it is business logic ;)
if(!in_array($object->getFu5LangTest, [0,1,2])) {
   $object->setFu5LangTest(9);
}

$form = $this->createForm(ObjectType, $object);
</code>```

Body:
I use an Symfony2 form with a choice field based on 4 checkboxes. Now i have the Problem, that i can't reload data in this choice field.That means, when in the database the value 9 is stored, will the checkbox "unknown if "lang test" performed" not be selected, when i load the entity in this form.

->add('fu5LangTest', 'choice', array(
           'choices' =>array(
               'poor compliance'=>0,
               'negative'=>1,
               'positive (recognizes at least 1 image reliably)'=>2,
               'unknown if "lang test" performed'=>9),
           'choice_value' =>function (DataEFu5 $entity = null) {
                            return $entity ? $entity->getFu5LangTest() : '';
                          },
           'expanded'=>true))

I tried a lot of things with the choice_value Attribut, but i think i'm using it wrong. Whats the right way? i didn't found some useful Information. What i have to do, that the correct checkbox will be selected after an reload?

The storing process is working fine.

Thanks for an feedback

Body:
The form is not the right place to do domain Logic.

Anyway, the data has the current fu5LangTest value. You should use

->add('fu5LangTest', 'choice', array(
       'choices' =>array(
           'poor compliance'=>0,
           'negative'=>1,
           'positive (recognizes at least 1 image reliably)'=>2,
           'unknown if "lang test" performed'=>9
       ),
       // ...

Form creation in Controller:

$object = new DataEFu5(); //or get it by your repository
//this condition will be better in a service as it is business logic ;)
if(!in_array($object->getFu5LangTest, [0,1,2])) {
   $object->setFu5LangTest(9);
}

$form = $this->createForm(ObjectType, $object);


问:
ImportError: cannot import name 'UserRequest'
I am developing a chatbot and I can't make it print a custom message before printing the search result. My custom messages are in difrent folder than the main script. The terminal prints "ImportError: cannot import name 'UserRequest'".

Here is the main script:

from google import search
import requests
from bs4 import BeautifulSoup
from RespondsToSearchQueries import UserRequest

def searchResults(query,start_num):
    """takes an input query, and returns number of websites and descriptions"""

```<code>for url in search(query, tld='com', lang='en', num = start_num,stop=5, pause = 3.0):
#for each URL found in google search
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    metas = soup.find_all('meta')
    metasList = list(meta.attrs['content'] for meta in metas if 'name' in meta.attrs and meta.attrs['name'] == 'description')
    #retrieve description of URL
    desc = ''.join(metasList)
    #convert list to string

    url_and_desc = url,"\n",desc,"\n"
    yield url_and_desc
</code>```

query = input("What would you like to look for?")
responses = search_results(query,1)
for url_and_desc in responses:
    print(UserRequest(query))
    print(url_and_desc)

and here is the script I am trying to import from:

from google_rewrite import *

def UserRequest(text):

```<code>text = text.lower()
for word in text:
    if "boneless pizza" in text:
        response = ""
        search_results(word)
    elif "pizza" in text:
        response = ""
    elif "weather" in text:
        response = ""
        #location = "Where are you right now?"
        response += weather_Lookup(location)
    elif "music" in text:
        response = ""
        response += search_results(response)
    elif "google" in text:
        reponse = ""
        response += search_results(reponse)
    elif "food" in text:
        response = ""
        response += search_results(response)
    elif "sport" or "sports" in text:
        rsponse = ""
        rsponse += search_results(response)
    elif "news" in text:
        rsponse = ""
        response += search_results(response)
    elif "sing" in text:
        response = ""
        response += search_results(response)
    #elif "joke" in text or "jokes" in text:
     #   response = "Jokes?! I know some, what to hear one?"
      #  if
      #  else:
      #  response += search_results(response)
    else:
        response = "Couldn't understand what are you looking for m8?"

return response
</code>```

答:
Do you have an __init__.py in the same folder as RespondsToSearchQueries.py? This is needed to make the folder a package from which you can import. __init__.py can be empty.

It's probably worth just trying this on the command line to make sure it's visible - start in the directory of your main script, start the interpreter and just type from RespondsToSearchQueries import UserRequest. You can then tinker with the __init__.py (and other factors until it works)?

Might be helpful if you show us your directory and file structure for this app so we can help diagnose import problem.

Body:
I am developing a chatbot and I can't make it print a custom message before printing the search result. My custom messages are in difrent folder than the main script. The terminal prints "ImportError: cannot import name 'UserRequest'".

Here is the main script:

from google import search
import requests
from bs4 import BeautifulSoup
from RespondsToSearchQueries import UserRequest

def searchResults(query,start_num):
    """takes an input query, and returns number of websites and descriptions"""

for url in search(query, tld='com', lang='en', num = start_num,stop=5, pause = 3.0):
#for each URL found in google search
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    metas = soup.find_all('meta')
    metasList = list(meta.attrs['content'] for meta in metas if 'name' in meta.attrs and meta.attrs['name'] == 'description')
    #retrieve description of URL
    desc = ''.join(metasList)
    #convert list to string

    url_and_desc = url,"\n",desc,"\n"
    yield url_and_desc

query = input("What would you like to look for?")
responses = search_results(query,1)
for url_and_desc in responses:
    print(UserRequest(query))
    print(url_and_desc)

and here is the script I am trying to import from:

from google_rewrite import *

def UserRequest(text):

text = text.lower()
for word in text:
    if "boneless pizza" in text:
        response = ""
        search_results(word)
    elif "pizza" in text:
        response = ""
    elif "weather" in text:
        response = ""
        #location = "Where are you right now?"
        response += weather_Lookup(location)
    elif "music" in text:
        response = ""
        response += search_results(response)
    elif "google" in text:
        reponse = ""
        response += search_results(reponse)
    elif "food" in text:
        response = ""
        response += search_results(response)
    elif "sport" or "sports" in text:
        rsponse = ""
        rsponse += search_results(response)
    elif "news" in text:
        rsponse = ""
        response += search_results(response)
    elif "sing" in text:
        response = ""
        response += search_results(response)
    #elif "joke" in text or "jokes" in text:
     #   response = "Jokes?! I know some, what to hear one?"
      #  if
      #  else:
      #  response += search_results(response)
    else:
        response = "Couldn't understand what are you looking for m8?"

return response


问:
Java: duplicate method signature in nested class
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}
</code>```

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

答:
Inner class in java can access all the members (i.e variables and methods) including private one, but outer class can not access member of inner class directly.

To access x() method of class B inside class A you can either create B's instance and call it or call like this A.this.x();

To access x() method outside class A you can do something like this:

```<code>B b = a.new B();
b.x();
</code>```

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

Body:
Inner class in java can access all the members (i.e variables and methods) including private one, but outer class can not access member of inner class directly.

To access x() method of class B inside class A you can either create B's instance and call it or call like this A.this.x();

To access x() method outside class A you can do something like this:

B b = a.new B();
b.x();


问:
iphone equivalent to android intents for opening other apps
Is there a android intent like functionality available in iphone. Android uses intents to open other applications from the calling app to use functionality already implemented by other apps. i read somewhere that iphone has url schemes but couldnot find more info on this.

thanks.

答:
IOS 3.2 and higher has 'DocumentInteraction' http://developer.apple.com/library/ios/ipad/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Introduction/Introduction.html

One app can provide some data and request another app to view or edit it (based on file format). The iOS takes care of copying the data from one sandbox to the other)
It also works with download links in safari or email attachements.

There is also openURL, but that's more cumbersome.


问:
nth-child with a PHP array
I'm using ACF to post WP posts on a page. But I to be able to control certain CSS properties using nth:child selectors. Heres the PHP which displays every thing fine.  Problem is (I'm assuming) that the "foreach" item is making the nth:child not work, because the are not siblings?</p>

```<code><div class="row">

<?php
        $posts = get_field('projects');
            if ( $posts ) {
                foreach ( $posts as $post ): ?>
            <div class="col-xl-6 no-space">
            <?php
                    setup_postdata($post); ?>
                    <div class="project__wrap">
                      <div class="project__project"><?php echo get_the_post_thumbnail(); ?></div>
                        <div class="project__description__list col-xl-6"><div class="project-content"><a href="<?php echo get_permalink(); ?>"><h2><?php echo get_the_title() ; ?></h2><p><?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 15 ) ); ?></p></a></div>

            <div class="heart"><?php
                $image = get_field('heart_icon');
                if( !empty($image) ): ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
            <?php endif; ?>
            </div>

                        </div> <!-- .project__description__list -->
                    </div> <!-- .project__wrap -->

                <?php wp_reset_postdata(); ?>
           </div>
                <?php endforeach;
                }
                ?>
</code>```

<p>      </p>

```<code>div.project-content:nth-child(odd) {
  top:0;
  left:0;
}

div.project-content:nth-child(even) {
  bottom:0;
  right:0;
}
</code>```

答:
The problem in your case is, project-content is always the first child of it's container (project__description__list). What you want is this for .col-xl-6.no-space. But this would be very ambiguous, so I would suggest, to add another class to this div - i.e. project-row-item.

```<code><div class="col-xl-6 no-space project-row-item">
</code>```

doing so, you could change your css like this

```<code>.project-row-item:nth-child(odd) div.project-content {
  top:0;
  left:0;
}

.project-row-item:nth-child(even) div.project-content {
  bottom:0;
  right:0;
}
</code>```

Title: nth-child with a PHP array

Body:
I'm using ACF to post WP posts on a page. But I to be able to control certain CSS properties using nth:child selectors. Heres the PHP which displays every thing fine.  Problem is (I'm assuming) that the "foreach" item is making the nth:child not work, because the are not siblings?

<?php
        $posts = get_field('projects');
            if ( $posts ) {
                foreach ( $posts as $post ): ?>

            <?php
                    setup_postdata($post); ?>

<?php echo get_the_post_thumbnail(); ?>

<a href="<?php echo get_permalink(); ?>">
<?php echo get_the_title() ; ?>

<?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 15 ) ); ?>

<?php
                $image = get_field('heart_icon');
                if( !empty($image) ): ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
            <?php endif; ?>

                <?php wp_reset_postdata(); ?>

                <?php endforeach;
                }
                ?>

div.project-content:nth-child(odd) {
  top:0;
  left:0;
}

div.project-content:nth-child(even) {
  bottom:0;
  right:0;
}

Body:
The problem in your case is, project-content is always the first child of it's container (project__description__list). What you want is this for .col-xl-6.no-space. But this would be very ambiguous, so I would suggest, to add another class to this div - i.e. project-row-item.

<div class="col-xl-6 no-space project-row-item">

doing so, you could change your css like this

.project-row-item:nth-child(odd) div.project-content {
  top:0;
  left:0;
}

.project-row-item:nth-child(even) div.project-content {
  bottom:0;
  right:0;
}


问:
Block UI thread and not display the label message
I have the following Thread method:

```<code>public void messageDelay()
{
    Thread.Sleep(5000);
}
</code>```

But when I call it, it hand the UI interface and I can not done any operation until the thread is finished.

```<code>private  void Porcessing_Click(object sender, EventArgs e)
{
    label1.Text = "start under process..";
    messageDelay();
    label1.Text = "Result";
}
</code>```

This is my main method. Any idea whats wrong I do?

答:
You need to use Asynchronous programming in this case. It is essential for activities that are potentially blocking, such as yours:

```<code>private async void Porcessing_Click(object sender, EventArgs e)
{
    label1.Text = "start under process..";
    await messageDelay();
    label1.Text = "Result";
}

public async Task messageDelay()
{
    await Task.Delay(5000);
}
</code>```

Note the use of async all the way down. Check this also https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

Body:
I have the following Thread method:

public void messageDelay()
{
    Thread.Sleep(5000);
}

But when I call it, it hand the UI interface and I can not done any operation until the thread is finished.

private  void Porcessing_Click(object sender, EventArgs e)
{
    label1.Text = "start under process..";
    messageDelay();
    label1.Text = "Result";
}

This is my main method. Any idea whats wrong I do?

Body:
You need to use Asynchronous programming in this case. It is essential for activities that are potentially blocking, such as yours:

private async void Porcessing_Click(object sender, EventArgs e)
{
    label1.Text = "start under process..";
    await messageDelay();
    label1.Text = "Result";
}

public async Task messageDelay()
{
    await Task.Delay(5000);
}

Note the use of async all the way down. Check this also https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html


问:
Unable to read a jade form field when it has enctype="multipart/form-data" (Nodejs)
I'm using Nodejs + express and I have a form, I need it to upload and image and other data, but the problem is when the form has enctype="multipart/form-data" I can not read the text fields, I don't know how to decrypt the data it contains cause I usually did it using:</p>

```<code>MYPROJECT.post("/example",function(req,res){
   var name = req.body.name; // or res.param('name')
   console.log(name) // And it works without enctype="multipart/form-data" in form, when it has enctype="multipart/form-data returns undefined
});
</code>```

答:
1st When you asking ,put the code sample , so that it will be easy to understand.
 As far i know , when you are posting some data with a file type , you need to have "multer" or any kind of this packages .check the code sample below with sample jada and js file,</p>

```<code>form(method='post' , action='/users/register',enctype='multipart/form-data')
    .form-group
        label Name
        input.form-control(type='text',name='name', value='' ,placeholder='Enter the Name')
    .form-group
        label Email
        input.form-control(type='email',name='email', placeholder='Enter the Email')
    .form-group
        label Password
        input.form-control(type='password',name='password', placeholder='Enter the Password')
    .form-group
        label Profile Image
        input.form-control(type='file',name='profileimage')
    input.btn.btn-default(name='submit' type='submit',value='Register')

var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({ dest: 'uploads/' })
router.post('/register',upload.single('avatar'),function(req,res,next){
  //your code
});
</code>```

Body:
I'm using Nodejs + express and I have a form, I need it to upload and image and other data, but the problem is when the form has enctype="multipart/form-data" I can not read the text fields, I don't know how to decrypt the data it contains cause I usually did it using:

MYPROJECT.post("/example",function(req,res){
   var name = req.body.name; // or res.param('name')
   console.log(name) // And it works without enctype="multipart/form-data" in form, when it has enctype="multipart/form-data returns undefined
});

Body:
1st When you asking ,put the code sample , so that it will be easy to understand.
 As far i know , when you are posting some data with a file type , you need to have "multer" or any kind of this packages .check the code sample below with sample jada and js file,

form(method='post' , action='/users/register',enctype='multipart/form-data')
    .form-group
        label Name
        input.form-control(type='text',name='name', value='' ,placeholder='Enter the Name')
    .form-group
        label Email
        input.form-control(type='email',name='email', placeholder='Enter the Email')
    .form-group
        label Password
        input.form-control(type='password',name='password', placeholder='Enter the Password')
    .form-group
        label Profile Image
        input.form-control(type='file',name='profileimage')
    input.btn.btn-default(name='submit' type='submit',value='Register')

var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({ dest: 'uploads/' })
router.post('/register',upload.single('avatar'),function(req,res,next){
  //your code
});


问:
What is the proper usage of Bundler groups in Rails 3 applications
I'm finding a disconnect between the description of how Bundler groups are used in Rails and what I see in examples of Bundler groups.

Supposedly, Rails normally loads gems from the default group as well as the group with the same name as the environment.  I commonly see examples, however, that seem to just put things in arbitrarily-named groups, and somehow, they just work.  So what's the real story, or what am I missing?

This example ( http://www.jonathanspies.com/posts/7-Rails-3-and-Shoulda ) for instance, says to list the 'shoulda' gem in a :shoulda group, and says that this works.  The environments that would need this, however, would be "test", and perhaps "development".  What causes gems in the "shoulda" group to be loaded?

In other examples such as http://comments.gmane.org/gmane.comp.programming.tools.cucumber/2691, I see cucumber-rails and related gems being placed into the :test group, but Cucumber tasks run with the "cucumber" environment, so again, how would the gems be loaded when they are needed?

答: In my capistrano recipe, Bundler is run with --without development test to prevent these groups from being installed which is I guess default behaviour.


问:
bootstrap-datepicker: Show DIV when selecting specific date
Using the bootstrap-datepicker plugin with the embedded markup...

How to show/reveal a DIV element when selecting a specific date AND hide it again when another date has been selected?

```<code><head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

  <style>
    #example {
      display: none;
      color: green;
      font-weight: bold;
    }

  </style>
</head>

<body>
  <div id="example">Yay my favorate day!</div>
  Please select <b>11/07/2017</b> to show an example:
  <br />
  <div id="myCalendar"></div>
  <input type="hidden" id="hiddenInput">

  <script>
    $(function() {
      $('#myCalendar').datepicker({
        format: 'mm-dd-yyyy',
        weekStart: 1,
        maxViewMode: 2,
        todayBtn: "linked",
        daysOfWeekHighlighted: "0,6",
        todayHighlight: true
      }).on('changeDate', function() {
        $('#hiddenInput').val(
          $('#myCalendar').datepicker('getFormattedDate')
        );
      }).change(function() {
        $("#example").toggle($(this).val() === "11-07-2017");
      });
    });

  </script>
</body>
</code>```

Demo on JSFiddle

答:
You can use changeDate event, as the docs says:

All events have extra data attached to the event object that is passed to any event handlers

date: the relevant Date object, in local timezone. For a multidate picker, this will be the latest date picked.

You can check what is the selected day (using setter like getDate(), getMonth() and getFullYear()) and the using jQuery show() and hide().

Here a live sample:

$(function() {
  $('#myCalendar').datepicker({
    format: 'mm-dd-yyyy',
    weekStart: 1,
    maxViewMode: 2,
    todayBtn: "linked",
    daysOfWeekHighlighted: "0,6",
    todayHighlight: true
  }).on('changeDate', function(e) {
    if( e.date && e.date.getDate() == 7 &&
        e.date.getMonth() == 10 &&
        e.date.getFullYear() == 2017 ){
      $("#example").show();
    } else {
      $("#example").hide();
    }
    $('#hiddenInput').val(
      $('#myCalendar').datepicker('getFormattedDate')
    );
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#example {
  display: none;
  color: green;
  font-weight: bold;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />

Yay my favorate day!

Please select 11/07/2017 to show an example:

<input type="hidden" id="hiddenInput">```

Body:
Using the bootstrap-datepicker plugin with the embedded markup...

How to show/reveal a DIV element when selecting a specific date AND hide it again when another date has been selected?

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />

Yay my favorate day!

  Please select 11/07/2017 to show an example:

  <input type="hidden" id="hiddenInput">

Demo on JSFiddle

Body:
You can use changeDate event, as the docs says:

All events have extra data attached to the event object that is passed to any event handlers

date: the relevant Date object, in local timezone. For a multidate picker, this will be the latest date picked.

You can check what is the selected day (using setter like getDate(), getMonth() and getFullYear()) and the using jQuery show() and hide().

Here a live sample:

$(function() {
  $('#myCalendar').datepicker({
    format: 'mm-dd-yyyy',
    weekStart: 1,
    maxViewMode: 2,
    todayBtn: "linked",
    daysOfWeekHighlighted: "0,6",
    todayHighlight: true
  }).on('changeDate', function(e) {
    if( e.date && e.date.getDate() == 7 &&
        e.date.getMonth() == 10 &&
        e.date.getFullYear() == 2017 ){
      $("#example").show();
    } else {
      $("#example").hide();
    }
    $('#hiddenInput').val(
      $('#myCalendar').datepicker('getFormattedDate')
    );
  });
});

#example {
  display: none;
  color: green;
  font-weight: bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

<div id="example">Yay my favorate day!</div>
Please select <b>11/07/2017</b> to show an example:
<br />
<div id="myCalendar"></div>
<input type="hidden" id="hiddenInput">


问:
Vb.net Sorting list
and DN125I have a list with the following values:

```<code>   DN32
   DN100
   DN50
   DN80
   DN125
   DN65
</code>```

I want to sort this list the following way:

```<code>DN125
DN100
DN80
DN65
DN50
DN32
</code>```

I tried using:

```<code>list.sort()
list.reverse()
</code>```

but this resulted in DN100 and DN125 ending up at the end of the list. so how can I sort this the way I want to?

答:
Since the list contains strings, List.Sort will perform an alphanumeric sorting. You want to sort the first part alphabetically and the numerical part numerically, like windows explorer.

If this format is fix(first 2 letters are letters, rest is an integer) you could use this LINQ approach:

```<code>list = list.
    Select(Function(s) New With {.String = s, .Letters = s.Remove(2), .Number = Int32.Parse(s.Substring(2))}).
    OrderBy(Function(x) x.Letters).
    ThenBy(Function(x) x.Number).
    Select(Function(x) x.String).
    ToList()
</code>```

Title: Vb.net Sorting list

Body:
and DN125I have a list with the following values:

   DN32
   DN100
   DN50
   DN80
   DN125
   DN65

I want to sort this list the following way:

DN125
DN100
DN80
DN65
DN50
DN32

I tried using:

list.sort()
list.reverse()

but this resulted in DN100 and DN125 ending up at the end of the list. so how can I sort this the way I want to?

Body:
Since the list contains strings, List.Sort will perform an alphanumeric sorting. You want to sort the first part alphabetically and the numerical part numerically, like windows explorer.

If this format is fix(first 2 letters are letters, rest is an integer) you could use this LINQ approach:

list = list.
    Select(Function(s) New With {.String = s, .Letters = s.Remove(2), .Number = Int32.Parse(s.Substring(2))}).
    OrderBy(Function(x) x.Letters).
    ThenBy(Function(x) x.Number).
    Select(Function(x) x.String).
    ToList()


问:
insert javascript var to thymeleaf url
How to insert JavaScript variable to thymeleaf URL?

example:

```<code>var i = x;
var actionCheck = /*[[@{/page/page1?action=add&param2=i}]]*/ '/memberrki/checkCardNum?action=add&param2=i}';
</code>```

param2 must be filled from var i ?

This is what I expected:

```<code>/memberrki/checkCardNum?action=add&param2=x
</code>```

答:
Did you try separating it into two variables ?</p>

```<code>var i = x;
var actionCheckBase = /*[[@{/page/page1?action=add&param2=}]]*/ '/memberrki/checkCardNum?action=add&param2=';
var actionCheck = actionCheckBase + i;
</code>```

Title: insert javascript var to thymeleaf url

Body:
How to insert JavaScript variable to thymeleaf URL?

example:

var i = x;
var actionCheck = /*[[@{/page/page1?action=add&param2=i}]]*/ '/memberrki/checkCardNum?action=add&param2=i}';

param2 must be filled from var i ?

This is what I expected:

/memberrki/checkCardNum?action=add&param2=x

Body:
Did you try separating it into two variables ?

var i = x;
var actionCheckBase = /*[[@{/page/page1?action=add&amp;param2=}]]*/ '/memberrki/checkCardNum?action=add&amp;param2=';
var actionCheck = actionCheckBase + i;


问:
KeyBinding with Command Binding dont work with TextBox UpdateSourceTrigger LostFocus
I'm using MVVM and have the following problem. My TextBox.Text is bound with UpdateSourceTrigger=LostFocus (thats what the user want). I have a Button with a SaveCommand CommandBinding - this works. Now i have a KeyBinding with Strg+S wich also execute the SaveCommand. And here is the problem: when i m in the Textbox and press Strg+s, the changes are not in the viewmodel.

is there any way to get MVVM Commands with KeyBinding and TextBox UpdateSourceTrigger=LostFocus working together?

some code to check out the problem

```<code><Window>
<Window.InputBindings>
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}"></KeyBinding>
</Window.InputBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Text="{Binding MyText1, UpdateSourceTrigger=LostFocus}" Width="100"></TextBox>
    <Button Grid.Row="1" Content="_Save" Command="{Binding SaveCommand}" IsDefault="True"></Button>
</Grid>
</Window>

public partial class MainWindow : Window
{
    private Viewmodel _data;
    public MainWindow()
    {
        _data = new Viewmodel();
        InitializeComponent();
        this.DataContext = _data;
    }
}

public class Viewmodel : INPCBase
{
    private string _myText1;
    private Lazy<DelegateCommand> _save;

    public Viewmodel()
    {
        this._save = new Lazy<DelegateCommand>(()=> new DelegateCommand(this.SaveCommandExecute));
    }

    private void SaveCommandExecute()
    {
        MessageBox.Show(MyText1);
    }

    public string MyText1
    {
        get { return _myText1; }
        set { _myText1 = value; this.NotifyPropertyChanged(()=>MyText1);}
    }

    public ICommand SaveCommand
    {
        get { return _save.Value; }
    }
}
</code>```

答:
I have the same problem and end up with attached property for TextBox.

```<code>public static bool GetCommitOnSave(DependencyObject obj)
{
    return (bool)obj.GetValue(CommitOnSaveProperty);
}

public static void SetCommitOnSave(DependencyObject obj, bool value)
{
    obj.SetValue(CommitOnSaveProperty, value);
}

public static readonly DependencyProperty CommitOnSaveProperty =
    DependencyProperty.RegisterAttached("CommitOnSave", typeof(bool), typeof(Helper), new PropertyMetadata(false, CommitOnSavePropertyChanged));

private static void CommitOnSavePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is TextBox textBox)
    {
        if ((bool)e.NewValue)
        {
            if ((bool)e.NewValue)
            {
                textBox.KeyDown += TextBox_KeyDown;
            }
            else
            {
                textBox.KeyDown -= TextBox_KeyDown;
            }
        }
    }
}

private static void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    var textBox = (TextBox)sender;
    if (e.Key == Key.S && Keyboard.Modifiers == ModifierKeys.Control)
    {
        BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty).UpdateSource();
    }
}
</code>```

Using <TextBox Text="{Binding Name}" local:Helper.CommitOnSave="True" />

Of course you can set attached property in style for all TextBoxes in a form.

Body:
I'm using MVVM and have the following problem. My TextBox.Text is bound with UpdateSourceTrigger=LostFocus (thats what the user want). I have a Button with a SaveCommand CommandBinding - this works. Now i have a KeyBinding with Strg+S wich also execute the SaveCommand. And here is the problem: when i m in the Textbox and press Strg+s, the changes are not in the viewmodel.

is there any way to get MVVM Commands with KeyBinding and TextBox UpdateSourceTrigger=LostFocus working together?

some code to check out the problem

<Window>
<Window.InputBindings>
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}"></KeyBinding>
</Window.InputBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Text="{Binding MyText1, UpdateSourceTrigger=LostFocus}" Width="100"></TextBox>
    <Button Grid.Row="1" Content="_Save" Command="{Binding SaveCommand}" IsDefault="True"></Button>
</Grid>
</Window>

public partial class MainWindow : Window
{
    private Viewmodel _data;
    public MainWindow()
    {
        _data = new Viewmodel();
        InitializeComponent();
        this.DataContext = _data;
    }
}

public class Viewmodel : INPCBase
{
    private string _myText1;
    private Lazy<DelegateCommand> _save;

    public Viewmodel()
    {
        this._save = new Lazy<DelegateCommand>(()=> new DelegateCommand(this.SaveCommandExecute));
    }

    private void SaveCommandExecute()
    {
        MessageBox.Show(MyText1);
    }

    public string MyText1
    {
        get { return _myText1; }
        set { _myText1 = value; this.NotifyPropertyChanged(()=>MyText1);}
    }

    public ICommand SaveCommand
    {
        get { return _save.Value; }
    }
}

Body:
I have the same problem and end up with attached property for TextBox.

public static bool GetCommitOnSave(DependencyObject obj)
{
    return (bool)obj.GetValue(CommitOnSaveProperty);
}

public static void SetCommitOnSave(DependencyObject obj, bool value)
{
    obj.SetValue(CommitOnSaveProperty, value);
}

public static readonly DependencyProperty CommitOnSaveProperty =
    DependencyProperty.RegisterAttached("CommitOnSave", typeof(bool), typeof(Helper), new PropertyMetadata(false, CommitOnSavePropertyChanged));

private static void CommitOnSavePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is TextBox textBox)
    {
        if ((bool)e.NewValue)
        {
            if ((bool)e.NewValue)
            {
                textBox.KeyDown += TextBox_KeyDown;
            }
            else
            {
                textBox.KeyDown -= TextBox_KeyDown;
            }
        }
    }
}

private static void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    var textBox = (TextBox)sender;
    if (e.Key == Key.S && Keyboard.Modifiers == ModifierKeys.Control)
    {
        BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty).UpdateSource();
    }
}

Using <TextBox Text="{Binding Name}" local:Helper.CommitOnSave="True" />

Of course you can set attached property in style for all TextBoxes in a form.


问:
MiniZinc: how to sum equal-length subarrays?
The problem I encountered is how to add variables in a[0..9] to b[10..19].
My code is:

```<code>array[0..19] of int: a=array1d(0..19,[0,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1,0]);
array[0..19] of int: b=array1d(0..19,[9,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9]);
array[0..9] of var int: c;
constraint
    forall(i in 0..9, j in 10..19)
    (
        c[i]=a[i]+b[j]
    );
solve satisfy;
output[show(c[i]) | i in 0..9];
</code>```

However, MiniZinc gives me the warning "model inconsistency detected, in call 'forall' in array comprehension expressionwith i = 0 with j = 11" and outputs "=====UNSATISFIABLE=====".

How do I get this to work?

答:
(Extracts the answer from my comments.)

Your forall loop tries to assign c[i] many times with different values, which is not allowed. In MiniZinc, unlike traditional programming languages, a decision variables cannot be reassigned.

I guess that you mean addition in a parallel loop:

```<code>constraint
  forall(i in 0..9) ( c[i]=a[i]+b[i+10])
;
</code>```

Body:
The problem I encountered is how to add variables in a[0..9] to b[10..19].
My code is:

array[0..19] of int: a=array1d(0..19,[0,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1,0]);
array[0..19] of int: b=array1d(0..19,[9,8,7,6,5,4,3,2,1,0,0,1,2,3,4,5,6,7,8,9]);
array[0..9] of var int: c;
constraint
    forall(i in 0..9, j in 10..19)
    (
        c[i]=a[i]+b[j]
    );
solve satisfy;
output[show(c[i]) | i in 0..9];

However, MiniZinc gives me the warning "model inconsistency detected, in call 'forall' in array comprehension expressionwith i = 0 with j = 11" and outputs "=====UNSATISFIABLE=====".

How do I get this to work?

Body:
(Extracts the answer from my comments.)

Your forall loop tries to assign c[i] many times with different values, which is not allowed. In MiniZinc, unlike traditional programming languages, a decision variables cannot be reassigned.

I guess that you mean addition in a parallel loop:

constraint
  forall(i in 0..9) ( c[i]=a[i]+b[i+10])
;


问:
Prestashop 1.7.1 - Top banner which hook shall be used?
Following this question I have created a new banner.
Now I want to insert a hook, but I am wondering which hook shall be used to display it on top of every page (as a promotional banner).

Thanks

答:
Assuming you're using the classic theme, you can use the displayBanner hook. If you look at header.tpl you can find the following block:

```<code>{block name='header_banner'}
   <div class="header-banner">
     {hook h='displayBanner'}
   </div>
{/block}
</code>```

which should be displayed on top of every page

Body:
Assuming you're using the classic theme, you can use the displayBanner hook. If you look at header.tpl you can find the following block:

{block name='header_banner'}
   <div class="header-banner">
     {hook h='displayBanner'}
   </div>
{/block}

which should be displayed on top of every page


问:
Distribute application without installing mono
I want to distribute my c# application to each computer on a linux cluster so that I can run it without having to install mono on each computer.

I have spent hours trying to get mkbundle to work, but it doesn't bundle properly (I am unable to run the application on another machine that doesn't have mono installed).

What is the best way to do this?

答: In this scenario it might be better to install mono seperately - updating your app will be easier if you don't have to include mono every time. The exact setup will depend a certain amount on what sort of linux you are using, but even if you are doing a source build there are ways to make the mono installation relatively painless.</p>


问:
pdfkit is working on python2 but it's not working in python3
import pdfkit

Error: Traceback (most recent call last):

  File "<stdin>", line 1, in <module> ImportError: No module named 'pdfkit'

when i use pdfkit in python2 then it works fine, but if i use in python3 it gives the above error

答:
Packages for Python 2 and Python 3 are completely separate. You have to install any package for both Python versions separately. Try:</p>

```<code>sudo python3 -m pip install pdfkit
</code>```

Body:
Packages for Python 2 and Python 3 are completely separate. You have to install any package for both Python versions separately. Try:

sudo python3 -m pip install pdfkit