问:
get list of files in a folder BUT in a predetermined order
I am using the below code to extract the names of files in a folder and then performing an operation on those files.

```<code>for library in lib/*
 do
  echo ${library##*/}
  cp -v ${library##*/} /opt/java/deploy/
 done
}
</code>```

The above yields an output of :

```<code>camel-amqp-2.16.0.jar
netty-all.jar
proton-j.jar
qpid-jms-client.jar
</code>```

I then need to copy the jar files one by one in the application deployment folder.

Right now I have 4 jar files but in the future the # of files will increase.

The above works all fine. But the dilemma for me is that I have to make sure that qpid-jms-client.jar & camel-amqp-2.16.0.jar are the last to load.

Basically I need to sort the output so that the qpid & camel jar files are at the bottom of the list and are hence the last ones to be loaded.

Using sort does not help here since sorting alphabetically wont be of much use.

Is there something else I can try out ?

答:
Using extglob you can do this:

```<code>shopt -s extglob nullglob

for lib in !(@(qpid-jms-client|camel-amqp-*)).jar qpid-jms-client.jar camel-amqp-*.jar; do

  echo "${lib##*/}"
  cp -v "${lib##*/}" /opt/java/deploy/

done
</code>```

How it works:

extglob pattern !(@(qpid-jms-client|camel-amqp-*)).jar matches all *.jar files except qpid-jms-client.jar & camel-amqp-2.16.0.jar files.

Those 2 files are listed in the end to make sure these 2 jar files are always matched in the end

Body:
I am using the below code to extract the names of files in a folder and then performing an operation on those files.

for library in lib/*
 do
  echo ${library##*/}
  cp -v ${library##*/} /opt/java/deploy/
 done
}

The above yields an output of :

camel-amqp-2.16.0.jar
netty-all.jar
proton-j.jar
qpid-jms-client.jar

I then need to copy the jar files one by one in the application deployment folder.

Right now I have 4 jar files but in the future the # of files will increase.

The above works all fine. But the dilemma for me is that I have to make sure that qpid-jms-client.jar & camel-amqp-2.16.0.jar are the last to load.

Basically I need to sort the output so that the qpid & camel jar files are at the bottom of the list and are hence the last ones to be loaded.

Using sort does not help here since sorting alphabetically wont be of much use.

Is there something else I can try out ?

Body:
Using extglob you can do this:

shopt -s extglob nullglob

for lib in !(@(qpid-jms-client|camel-amqp-*)).jar qpid-jms-client.jar camel-amqp-*.jar; do

  echo "${lib##*/}"
  cp -v "${lib##*/}" /opt/java/deploy/

done

How it works:

extglob pattern !(@(qpid-jms-client|camel-amqp-*)).jar matches all *.jar files except qpid-jms-client.jar & camel-amqp-2.16.0.jar files.

Those 2 files are listed in the end to make sure these 2 jar files are always matched in the end


来源: stackexchange

问:
How do I call a getter from another getter in Vuex?
Consider a simple Vue blog:

 I'm using Vuex as my datastore and I need to set up two getters: a getPost getter for retrieving a post by ID, as well as a listFeaturedPosts that returns the first few characters of each featured post. The datastore schema for the featured posts list references the posts by their IDs. These IDs need to be resolved to actual posts for the purposes of showing the excerpts.

store/state.js

```<code>export const state = {
  featuredPosts: [2, 0],
  posts: [
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
  ]
}
</code>```

store/getters.js

export default getPost = (state) => (postID) => {
  return state.posts[postID]
}

export default listFeaturedPosts = (state, getters) => () => {
  console.log(getters) // {}

  return state.featuredPosts.map(postID => getters.getPost(postID).substring(0, EXCERPT_LENGTH);
}
```

<p><strong>store/index.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import * as getters from './getters'
import * as mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  getters,
  mutations
})
</code>```

According to the documentation, the getters parameter can be used to access other getters. However, when I try to access getters from inside listFeaturedPosts, it's empty, and I get an error in the console due to getters.getPost being undefined in that context.

How do I call getPost as a Vuex getter from inside listFeaturedPosts in the example above?

答:
In VueJS 2.0, you must pass both state and getters.

Getters are passed to other getters as the 2nd Argument:

```<code>export default foo = (state, getters) => {
    return getters.yourGetter
}
</code>```

Official documentation: https://vuex.vuejs.org/guide/getters.html#property-style-access

ContentLicense: CC BY-SA 4.0

Body:
Consider a simple Vue blog:

 I'm using Vuex as my datastore and I need to set up two getters: a getPost getter for retrieving a post by ID, as well as a listFeaturedPosts that returns the first few characters of each featured post. The datastore schema for the featured posts list references the posts by their IDs. These IDs need to be resolved to actual posts for the purposes of showing the excerpts.

store/state.js

export const state = {
  featuredPosts: [2, 0],
  posts: [
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
    'Lorem et ipsum dolor sit amet',
  ]
}

store/getters.js

export default getPost = (state) => (postID) => {
  return state.posts[postID]
}

export default listFeaturedPosts = (state, getters) => () => {
  console.log(getters) // {}

  return state.featuredPosts.map(postID => getters.getPost(postID).substring(0, EXCERPT_LENGTH);
}

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import * as getters from './getters'
import * as mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  getters,
  mutations
})

According to the documentation, the getters parameter can be used to access other getters. However, when I try to access getters from inside listFeaturedPosts, it's empty, and I get an error in the console due to getters.getPost being undefined in that context.

How do I call getPost as a Vuex getter from inside listFeaturedPosts in the example above?

Body:
In VueJS 2.0, you must pass both state and getters.

Getters are passed to other getters as the 2nd Argument:

export default foo = (state, getters) => {
    return getters.yourGetter
}

Official documentation: https://vuex.vuejs.org/guide/getters.html#property-style-access


问:
Add values from an ng-repeat to a sum
So I have a table with data on the rows and I want to have on the last column the sum of them like here:

```<code>a   b   c   d   total
1   1   1   1     4
3   1   3   8    15
0   4   0   1     5
</code>```

this is how the body of the table:

```<code><tbody>
    <tr ng-repeat="rows in $ctrl.tableData[0] track by $index">
        <td ng-repeat="label in $ctrl.xTableAxis">{{$ctrl.tableData[$index][$parent.$index].toFixed(2)}}</td>
        <td>show the sum here</td>
    </tr>
</tbody>
</code>```

The values are here: $ctrl.tableData[$index][$parent.$index].toFixed(2), the problem is how to add them the print into the next .

Is there a way to add the values inside the body?

答:
Your suggested methodology cannot be done in an elegant way in ng-repeat (which is allready ugly enough by itself).

The right way to do it would be using a simple reduce function.

```<code><tbody>
    <tr ng-repeat="rows in $ctrl.tableData[0] track by $index">
        <td ng-repeat="label in $ctrl.xTableAxis">{{$ctrl.tableData[$index][$parent.$index].toFixed(2)}}</td>
        <td>{{ $ctrl.tableData[$index].reduce((a,b)=>a+b)}}</td>
    </tr>
</tbody>
</code>```

Edit:

In case you get a syntax error you can do the following:

In template:

```<code><tbody>
    <tr ng-repeat="rows in $ctrl.tableData[0] track by $index">
        <td ng-repeat="label in $ctrl.xTableAxis">{{$ctrl.tableData[$index][$parent.$index].toFixed(2)}}</td>
        <td>{{ $ctrl.tableData[$index].reduce(add)}}</td>
    </tr>
</tbody>
</code>```

In controller:

```<code>$scope.add = (a,b)=>a+b
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add values from an ng-repeat to a sum

Body:
So I have a table with data on the rows and I want to have on the last column the sum of them like here:

a   b   c   d   total
1   1   1   1     4
3   1   3   8    15
0   4   0   1     5

this is how the body of the table:

        {{$ctrl.tableData[$index][$parent.$index].toFixed(2)}}
        show the sum here

The values are here: $ctrl.tableData[$index][$parent.$index].toFixed(2), the problem is how to add them the print into the next .

Is there a way to add the values inside the body?

Body:
Your suggested methodology cannot be done in an elegant way in ng-repeat (which is allready ugly enough by itself).

The right way to do it would be using a simple reduce function.

<tbody>
    <tr ng-repeat="rows in $ctrl.tableData[0] track by $index">
        <td ng-repeat="label in $ctrl.xTableAxis">{{$ctrl.tableData[$index][$parent.$index].toFixed(2)}}</td>
        <td>{{ $ctrl.tableData[$index].reduce((a,b)=>a+b)}}</td>
    </tr>
</tbody>

Edit:

In case you get a syntax error you can do the following:

In template:

<tbody>
    <tr ng-repeat="rows in $ctrl.tableData[0] track by $index">
        <td ng-repeat="label in $ctrl.xTableAxis">{{$ctrl.tableData[$index][$parent.$index].toFixed(2)}}</td>
        <td>{{ $ctrl.tableData[$index].reduce(add)}}</td>
    </tr>
</tbody>

In controller:

$scope.add = (a,b)=>a+b


问:
Can AngularJS be used with jQuery bootgrid?
After 2 days reading all topics about jQuery Bootgrid and AngularJS, I still can't use angular directives on my generated grid.

I'm using AngularJS 1.6.6 and jQuery Bootgrid 1.3.1. The page that is using it is running fine and all the elements outside the grid are working with angular directives. All the elements are inside the right ng-app and ng-controller tagged root.

The problem is that I have some buttons inside the grid and they are all losing their events like onclick, tooltips, etc. So I wanted to map them using ng-click instead of the jQuery .click(function () {}).

There are no error messages, only the events are just not firing.

All functions pointed inside the directives are declared on my scope.

I'm almost concluding that the jQuery Bootgrid isolates its own scope and avoid angular to get into it. Does that proceed?

        <title>Example - jQuery Bootgrid and Angular</title>
        <meta charset="utf-8">

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

        <link href="https://cdn.bootcss.com/jquery-bootgrid/1.3.1/jquery.bootgrid.css" rel="stylesheet" />

Test

                    id
                    e-mail

                    1
                    xxx@yyy.com

                    2
                    www@yyy.com

                    3
                    zzz@yyy.com

```

答: Since there was no definitive answer I changed my component and stopped looking for this compatibility issue. I still think that there was a way to attach the grid plugin to my angularjs scope, but time is not on my side here.</p>


问:
Subquery returned more than 1 value.4...Different query
Hello I have this query that i am trying to execute and i keep getting this error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.", Kindly help please.</p>

```<code>DECLARE @NUMCOUNT BIT

Select @NUMCOUNT = (SELECT
CASE WHEN

(SELECT COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ('A')
       ) IN
(SELECT   COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ( 'A','C') ) THEN 1 else  0 END AS NUMCOUNT1
       FROM         R5REQUISLINES JOIN
                      R5REQUISITIONS ON R5REQUISLINES.RQL_REQ = R5REQUISITIONS.REQ_CODE

       GROUP BY R5REQUISLINES.RQL_REQ, R5REQUISITIONS.REQ_CODE,R5REQUISLINES.RQL_STATUS

 )

IF @NUMCOUNT = '1'

begin

UPDATE R5REQUISITIONS

SET R5REQUISITIONS.REQ_STATUS = 'CP'

end
</code>```

答:
Your 'SELECT CASE' is returning more than 1 record, so it can't be assigned to @NUMBER.  Either fix the sub-query to only return the record your looking for or hack it to return only 1 with a 'LIMIT 1'  qualification.

I don't know what your data looks like so I can't tell you why your case subquery returns more records than you think it should.

Try running this and see what it returns, that will probably tell you wall you need to know:

```<code>SELECT
    CASE WHEN
        (SELECT COUNT(R5REQUISLINES.RQL_REQ)
            WHERE R5REQUISLINES.RQL_STATUS IN ('A')
        ) IN
        (SELECT COUNT(R5REQUISLINES.RQL_REQ)
            WHERE R5REQUISLINES.RQL_STATUS IN ( 'A','C')
        )
        THEN 1
        ELSE 0
        END AS NUMCOUNT1
    FROM R5REQUISLINES JOIN
        R5REQUISITIONS ON R5REQUISLINES.RQL_REQ = R5REQUISITIONS.REQ_CODE
    GROUP BY R5REQUISLINES.RQL_REQ, R5REQUISITIONS.REQ_CODE,R5REQUISLINES.RQL_STATUS
</code>```

If there is more than 1 row returned, that's where your problem is.

Body:
Hello I have this query that i am trying to execute and i keep getting this error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.", Kindly help please.

DECLARE @NUMCOUNT BIT

Select @NUMCOUNT = (SELECT
CASE WHEN

(SELECT COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ('A')
       ) IN
(SELECT   COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ( 'A','C') ) THEN 1 else  0 END AS NUMCOUNT1
       FROM         R5REQUISLINES JOIN
                      R5REQUISITIONS ON R5REQUISLINES.RQL_REQ = R5REQUISITIONS.REQ_CODE

       GROUP BY R5REQUISLINES.RQL_REQ, R5REQUISITIONS.REQ_CODE,R5REQUISLINES.RQL_STATUS

 )

IF @NUMCOUNT = '1'

begin

UPDATE R5REQUISITIONS

SET R5REQUISITIONS.REQ_STATUS = 'CP'

end

Body:
Your 'SELECT CASE' is returning more than 1 record, so it can't be assigned to @NUMBER.  Either fix the sub-query to only return the record your looking for or hack it to return only 1 with a 'LIMIT 1'  qualification.

I don't know what your data looks like so I can't tell you why your case subquery returns more records than you think it should.

Try running this and see what it returns, that will probably tell you wall you need to know:

SELECT
    CASE WHEN
        (SELECT COUNT(R5REQUISLINES.RQL_REQ)
            WHERE R5REQUISLINES.RQL_STATUS IN ('A')
        ) IN
        (SELECT COUNT(R5REQUISLINES.RQL_REQ)
            WHERE R5REQUISLINES.RQL_STATUS IN ( 'A','C')
        )
        THEN 1
        ELSE 0
        END AS NUMCOUNT1
    FROM R5REQUISLINES JOIN
        R5REQUISITIONS ON R5REQUISLINES.RQL_REQ = R5REQUISITIONS.REQ_CODE
    GROUP BY R5REQUISLINES.RQL_REQ, R5REQUISITIONS.REQ_CODE,R5REQUISLINES.RQL_STATUS

If there is more than 1 row returned, that's where your problem is.


答:
check this fiddles hope it helps

http://jsfiddle.net/hjk5evv2/

js:

```<code>angular.module('app',['QuickList']).controller('mainCtrl', function($scope){

    $scope.items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
$scope.sum = function(array){
return array.reduce(add, 0);
}

function add(a, b) {
    return a + b;
}
})
</code>```

html:

```<code><div ng-app='app' ng-controller='mainCtrl'>
    {{ctrlTest}}<hr/>Ng-Repeat<hr/>

  <table>
  <tr ng-repeat="x in items">
    <td ng-repeat="y in x">{{ y }}</td>
    <td>{{ sum(x) }}</td>
  </tr>
</table>

</div>
</code>```

Title: Add values from an ng-repeat to a sum

Body:
check this fiddles hope it helps

http://jsfiddle.net/hjk5evv2/

js:

angular.module('app',['QuickList']).controller('mainCtrl', function($scope){

    $scope.items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
$scope.sum = function(array){
return array.reduce(add, 0);
}

function add(a, b) {
    return a + b;
}
})

html:

<div ng-app='app' ng-controller='mainCtrl'>
    {{ctrlTest}}<hr/>Ng-Repeat<hr/>

  <table>
  <tr ng-repeat="x in items">
    <td ng-repeat="y in x">{{ y }}</td>
    <td>{{ sum(x) }}</td>
  </tr>
</table>

</div>


问:
Import Wizard only partially uploads csv table in MySQL
I'm relatively new to MySQL

I am trying to import a csv table with 25,000 rows and 37 variables into MySQL using the import wizard. The import wizard uploads successfully but only 2483 rows appear. How do I upload the entire csv file?

答:
Please use load file:
LOAD DATA INFILE 'data.CSV' INTO TABLE tbl_name
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;

Other option USE "LOCAL":

LOAD DATA LOCAL INFILE 'data.CSV' INTO TABLE tbl_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES;

If LOCAL is specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full path name to specify its exact location. If given as a relative path name, the name is interpreted relative to the directory in which the client program was started.


问:
Kotlin explain me about Backing Fields
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

```<code>var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }
</code>```

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

答:
A Backing Field is just a field that will be generated for a property
  in a class only if it uses the default implementation of at least one
  of the accessors

Backing field is generated only if a property uses the default implementation of getter/setter. If you see the following code with perspective of Java. It looks correct. However in "kotlin" it’ll throw Exception.

```<code>  class User{
       var firstName : String //backing field generated
      get() = firstName
      set(value) {
           firstName = value
      }
      var lastName : String //backing field generated
      get() = lastName
      set(value) {
           lastName = value
      }
      val name : String //no backing field generated
      get() = "{$firstName $lastName}"
      var address : String = "XYZ" //^because there is no default //^implementation of an accessor
 }
</code>```

In Kotlin the above code snippet will throw StackOverflow because when we access or set property "first-name" or "last name" the default accessor will be called. So in Kotlin "user.firstName = "value"” is same as Java’s "user.setFirstName("value")".

So when "set(value) {firstName = "value"} " is called, then a recursive callhappens and compiler throws a Exception exception because we are calling setter inside the setter.

Solution to this problem is to user backing fields. In Kotlin a backing field can be accessed using "field" keyword inside accessors. Take a look at corrected code snippet below.

```<code> class User{
      var firstName : String get() = field
      set(value) {
           field = value
      }
      var lastName : String get() = field
      set(value) {
           field = value}
      }
 }
</code>```

Title: Kotlin explain me about Backing Fields

Body:
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

Body:
A Backing Field is just a field that will be generated for a property
  in a class only if it uses the default implementation of at least one
  of the accessors

Backing field is generated only if a property uses the default implementation of getter/setter. If you see the following code with perspective of Java. It looks correct. However in "kotlin" it’ll throw Exception.

  class User{
       var firstName : String //backing field generated
      get() = firstName
      set(value) {
           firstName = value
      }
      var lastName : String //backing field generated
      get() = lastName
      set(value) {
           lastName = value
      }
      val name : String //no backing field generated
      get() = "{$firstName $lastName}"
      var address : String = "XYZ" //^because there is no default //^implementation of an accessor
 }

In Kotlin the above code snippet will throw StackOverflow because when we access or set property "first-name" or "last name" the default accessor will be called. So in Kotlin "user.firstName = "value"” is same as Java’s "user.setFirstName("value")".

So when "set(value) {firstName = "value"} " is called, then a recursive callhappens and compiler throws a Exception exception because we are calling setter inside the setter.

Solution to this problem is to user backing fields. In Kotlin a backing field can be accessed using "field" keyword inside accessors. Take a look at corrected code snippet below.

 class User{
      var firstName : String get() = field
      set(value) {
           field = value
      }
      var lastName : String get() = field
      set(value) {
           field = value}
      }
 }


问:
Template equivalence or template functional equivalence?
In the C++ standard [temp.over.link], it is explained that the determination of function template equivalence should not involve "heroic efforts" of the compiler.

As an example, the C++ standard propose this:

```<code>// guaranteed to be the same
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+10>);
// guaranteed to be different
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+11>);
// ill-formed, no diagnostic required
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+1+2+3+4>);
</code>```

Is this rule also applies to cases involving meta programming, as in the example below?

```<code>template<class T>
struct t_{
   using type = T;
   };
//ill-formed or different?
template<class T> T f(T);
template<class T> typename t_<T>::type f(T);
</code>```

答:
I think that in this scenario they are considered different:

```<code>template<class T>
struct t_{
   using type = T;
   };
//ill-formed or different?
template<class T> T f(T);
template<class T> typename t_<T>::type f(T);
</code>```

Because [temp.over.link] says (emphasis mine)

For determining whether two
  dependent names  are equivalent, only the name itself is considered, not the result of name lookup in
  the context of the template.

Since T and typename t_<T>::type differ in naming, the compiler will accept these template declarations.

Now, you couldn't actually call either of them because the resulting template instantiations are functionally equivalent, resulting in ambiguity. This sort of program is ill-formed, no diagnostic required* (See @Barry's great answer).

MSVC 19.00.23506, clang 6.0.0, and gcc 8.0.0 all appear to agree with me on this (none of them issue a diagnostic).

Note that the compiler allows these templates to be declared, so long as they aren't called, whereas something like this won't compile even if the templates are not instantiated:

```<code>template<class U> typename t_<U>::type f(U){return {};}
template<class T> typename t_<T>::type f(T){return {};}
</code>```

* "If a program contains declarations of function
templates that are functionally equivalent but not equivalent, the program is ill-formed, no diagnostic
required."

Body:
In the C++ standard [temp.over.link], it is explained that the determination of function template equivalence should not involve "heroic efforts" of the compiler.

As an example, the C++ standard propose this:

// guaranteed to be the same
template <int I> void f(A, A);
template <int I> void f(A, A);
// guaranteed to be different
template <int I> void f(A, A);
template <int I> void f(A, A);
// ill-formed, no diagnostic required
template <int I> void f(A, A);
template <int I> void f(A, A);

Is this rule also applies to cases involving meta programming, as in the example below?

template<class T>
struct t_{
   using type = T;
   };
//ill-formed or different?
template<class T> T f(T);
template<class T> typename t_<T>::type f(T);

Body:
I think that in this scenario they are considered different:

template<class T>
struct t_{
   using type = T;
   };
//ill-formed or different?
template<class T> T f(T);
template<class T> typename t_<T>::type f(T);

Because [temp.over.link] says (emphasis mine)

For determining whether two
  dependent names  are equivalent, only the name itself is considered, not the result of name lookup in
  the context of the template.

Since T and typename t_<T>::type differ in naming, the compiler will accept these template declarations.

Now, you couldn't actually call either of them because the resulting template instantiations are functionally equivalent, resulting in ambiguity. This sort of program is ill-formed, no diagnostic required* (See @Barry's great answer).

MSVC 19.00.23506, clang 6.0.0, and gcc 8.0.0 all appear to agree with me on this (none of them issue a diagnostic).

Note that the compiler allows these templates to be declared, so long as they aren't called, whereas something like this won't compile even if the templates are not instantiated:

template<class U> typename t_<U>::type f(U){return {};}
template<class T> typename t_<T>::type f(T){return {};}

* "If a program contains declarations of function
templates that are functionally equivalent but not equivalent, the program is ill-formed, no diagnostic
required."


问:
XSD equivalent code to this DTD code?
Assume that my DTD code have this following listing:

```<code><!ELEMENT body
  ((verse, bridge?, chorus)+) , coda)>
</code>```

Can I write XSD code, which defines that a sequence of three element (one optional) can be repeated one or more? If it can, what's the listing for that XSD?

答:
It's true, as Jim Garrison has pointed out in a comment, that the DTD and XSD schema languages are not 1:1 equivalent.  But XSD was designed to be able to define any language that can be defined by a DTD (modulo some things like hard-coding namespace prefixes, which were regarded as flaws rather than capabilities of DTDs).

So the short answer to your question is yes, you can write equivalent XSD declarations.

For the long answer, you will want to consult a tutorial on XSD (most question answerers on Stack Overflow will be happy to help you correct errors in your attempts to solve the problem, but not to solve it for you -- there are of course exceptions); the tutorial in Part 0 of XSD 1.0 is accurate and accessible.  You will want to pay particular attention to the xsd:sequence and xsd:element elements, and to the minOccurs and maxOccurs attributes on those elements.

Title: XSD equivalent code to this DTD code?

Body:
Assume that my DTD code have this following listing:

<!ELEMENT body
  ((verse, bridge?, chorus)+) , coda)>

Can I write XSD code, which defines that a sequence of three element (one optional) can be repeated one or more? If it can, what's the listing for that XSD?


问:
Get unique from list as values in Pandas python
I have a dataframe with more rows and columns but example with one is here: </p>

```<code>id    values
1   [v1, v2, v1]
</code>```

<p>How to get unique values from list in pandas column?
Desired output in second column v1, v2
I have tried with df['values'].unique() but obviously it's not working. </p>

答:
A simple solution would be agg pd.unique i.e </p>

```<code>df = pd.DataFrame({'x' : [['v','w','x','v','x']]})

df['x'].agg(pd.unique) # Also np.unique

0    [v, w, x]
Name: x, dtype: object
</code>```

<p>or </p>

```<code>df['x'].agg(set).agg(list)

0    [v, w, x]
Name: x, dtype: object
</code>```

Body:
I have a dataframe with more rows and columns but example with one is here:

id    values
1   [v1, v2, v1]

How to get unique values from list in pandas column?
Desired output in second column v1, v2
I have tried with df['values'].unique() but obviously it's not working.

Body:
A simple solution would be agg pd.unique i.e

df = pd.DataFrame({'x' : [['v','w','x','v','x']]})

df['x'].agg(pd.unique) # Also np.unique

0    [v, w, x]
Name: x, dtype: object

or

df['x'].agg(set).agg(list)

0    [v, w, x]
Name: x, dtype: object


问:
How to correctly implement C# interface with event in managed C++

Hello I'm trying to implement a C# interface in my managed c++ dll as seen bellow:

```<code>public ref class MyClass : public IMyInterface
{
 // Inherited via IMyInterface
 virtual event EventHandler<MyEventArgs ^> ^ MyLoadedEvent;

 public:
     virtual event EventHandler<MyEventArgs ^> MyLoadedEvent
                {
                    void add(MyEventArgs ^ f)
                    {
                      // some magic
                    }
                    void remove(MyEventArgs ^ f)
                    {
                      // some magic
                    }
                }
}
</code>```

But I keep getting two errors:

1) event type must be a handle-to-delegate type

2) class fails to implement interface member function "MyLoadedEvent::add" declared in ...dll

What am I missing in the implementation or what is the correct way to implement the event of the interface?

Thanks!

答:
First error is caused by missing the ^ hat, second error is caused by not naming the interface method you implement.  Assuming the interface event is named "Loaded", correct syntax ought to resemble:</p>

```<code>public ref class MyClass : IMyInterface {
    EventHandler<MyEventArgs^>^ MyLoadedEventBackingStore;
public:
    virtual event EventHandler<MyEventArgs^>^ MyLoadedEvent {
        void add(EventHandler<MyEventArgs^>^ arg) = IMyInterface::Loaded::add {
            MyLoadedEventBackingStore += arg;
        }
        void remove(EventHandler<MyEventArgs^>^ arg) = IMyInterface::Loaded::remove {
            MyLoadedEventBackingStore -= arg;
        }
    }
};
</code>```

Body:
Hello I'm trying to implement a C# interface in my managed c++ dll as seen bellow:

public ref class MyClass : public IMyInterface
{
 // Inherited via IMyInterface
 virtual event EventHandler<MyEventArgs ^> ^ MyLoadedEvent;

 public:
     virtual event EventHandler<MyEventArgs ^> MyLoadedEvent
                {
                    void add(MyEventArgs ^ f)
                    {
                      // some magic
                    }
                    void remove(MyEventArgs ^ f)
                    {
                      // some magic
                    }
                }
}

But I keep getting two errors:

1) event type must be a handle-to-delegate type

2) class fails to implement interface member function "MyLoadedEvent::add" declared in ...dll

What am I missing in the implementation or what is the correct way to implement the event of the interface?

Thanks!

Body:
First error is caused by missing the ^ hat, second error is caused by not naming the interface method you implement.  Assuming the interface event is named "Loaded", correct syntax ought to resemble:

public ref class MyClass : IMyInterface {
    EventHandler<MyEventArgs^>^ MyLoadedEventBackingStore;
public:
    virtual event EventHandler<MyEventArgs^>^ MyLoadedEvent {
        void add(EventHandler<MyEventArgs^>^ arg) = IMyInterface::Loaded::add {
            MyLoadedEventBackingStore += arg;
        }
        void remove(EventHandler<MyEventArgs^>^ arg) = IMyInterface::Loaded::remove {
            MyLoadedEventBackingStore -= arg;
        }
    }
};


问:
unable drag the item to the input field
I am using ember drag drop plugin in my ember-app:"ember install ember-drag-drop"
to drag the item from one place to another but i am unable to drop to the input field.

here is my code:

```<code>{{#draggable-object content=systemVariableInfo dragStartAction='myStartAction' dragEndAction='myEndAction'}}
{{item.name}}
{{/draggable-object}}
</code>```

controller::

```<code>myStartAction: function(content) {
        console.log("content"+content);
     //Content is the same as the content parameter set above
    },
    myEndAction: function(content) {
      //Content is the same as the content parameter set above
    },
</code>```

how to solve this issue.

答:
You have to put the target into draggable-object-target:

```<code><div>
    {{#each items as |item|}}
    {{#draggable-object content=item}}
      {{item.name}}
    {{/draggable-object}}
    {{/each}}
</div>
<br>
<form>
{{#draggable-object-target action="onDrop"}}
  {{input type="text" placeholder="drop here" value=inputValue}}
{{/draggable-object-target}}
</form>
</code>```

See Ember-Twiddle.

Title: unable drag the item to the input field

Body:
I am using ember drag drop plugin in my ember-app:"ember install ember-drag-drop"
to drag the item from one place to another but i am unable to drop to the input field.

here is my code:

{{#draggable-object content=systemVariableInfo dragStartAction='myStartAction' dragEndAction='myEndAction'}}
{{item.name}}
{{/draggable-object}}

controller::

myStartAction: function(content) {
        console.log("content"+content);
     //Content is the same as the content parameter set above
    },
    myEndAction: function(content) {
      //Content is the same as the content parameter set above
    },

how to solve this issue.

Body:
You have to put the target into draggable-object-target:

<div>
    {{#each items as |item|}}
    {{#draggable-object content=item}}
      {{item.name}}
    {{/draggable-object}}
    {{/each}}
</div>
<br>
<form>
{{#draggable-object-target action="onDrop"}}
  {{input type="text" placeholder="drop here" value=inputValue}}
{{/draggable-object-target}}
</form>

See Ember-Twiddle.


问:
Django multiple select with JS
Can anyone tell me, how(if it's possible) can I make select with JavaScript such as autogenerated select in admin panel (using which we select user permissions)?</p>

答:
It's possible, see another post about re-using the date widget but this will be too much trouble, you'd better try to use another widget which you will install, and so, know every dependencies and gotchas.

Here is another Multiselect for Django for example :

http://djangosnippets.org/snippets/2079/

...for this really cool jquery UI widget : http://www.quasipartikel.at/multiselect/

ContentLicense: CC BY-SA 2.5

Title: Django multiple select with JS


问:
Gaps and Island - Microsoft Access
I am trying to group my data by: State, Product, Edition, LG_SG, Area, and Area Factor. I then want to attach the minimum start date and the maximum end date to the record. I have a Gaps and Island issue though. If you look at the data, the .8428 shows up in two blocks that are not in chronological order. How do I solve this problem in Access?

Here is my current data.

```<code>state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   11/1/2010   PPO 6   SG  1   0.86
IL  11/1/2010   12/1/2010   PPO 6   SG  1   0.86
IL  12/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    2/1/2011    PPO 6   SG  1   0.8428
IL  2/1/2011    3/1/2011    PPO 6   SG  1   0.8428
IL  3/1/2011    4/1/2011    PPO 6   SG  1   0.8428
IL  4/1/2011    5/1/2011    PPO 6   SG  1   0.8428
IL  5/1/2011    6/1/2011    PPO 6   SG  1   0.8428
IL  6/1/2011    7/1/2011    PPO 6   SG  1   0.8428
IL  7/1/2011    8/1/2011    PPO 6   SG  1   0.8428
IL  8/1/2011    9/1/2011    PPO 6   SG  1   0.8428
IL  9/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   11/1/2011   PPO 6   SG  1   0.825944
IL  11/1/2011   12/1/2011   PPO 6   SG  1   0.825944
IL  12/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    2/1/2012    PPO 6   SG  1   0.8428
IL  2/1/2012    3/1/2012    PPO 6   SG  1   0.8428
IL  3/1/2012    4/1/2012    PPO 6   SG  1   0.8428
IL  4/1/2012    5/1/2012    PPO 6   SG  1   0.8428
</code>```

I would like it to look like this.

```<code>state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    5/1/2012    PPO 6   SG  1   0.8428
</code>```

Thank you all for your help.

答:
This code is a start

```<code>SELECT data.state, data.start_date, data.product, data.edition, data.lg_sg, data.area, data.area_factor, data_1.area_factor AS previous
FROM data LEFT JOIN data AS data_1 ON data.start_date = data_1.end_date
WHERE (((data_1.area_factor) Is Null Or (data_1.area_factor)<>[data].[area_factor]));
</code>```

It gives you the start date for each range, but not the end date.  If you're using this as a reference to search for a specific date, it might be enough - you can search for the last record that's less than or equal to your search date, without needing the end date.

I was initially thinking that an auto number field would help ID the end date, but now I'm not sure.  This query already does the work I would have done with an auto number field, and I don't quite see how to get the end date yet.

UPDATE:  This isn't elegant, but I can do it in a few steps:
Save the query above as StartDates.  Then use this query to find the next start date for the same area_factors:

```<code>SELECT StartDates.state, StartDates.start_date, StartDates.product, StartDates.edition, StartDates.lg_sg, StartDates.area, StartDates.area_factor, (select min(start_date) from StartDates T where T.area_factor=StartDates.area_factor and T.start_date>StartDates.start_date) AS [Next]
FROM StartDates
ORDER BY StartDates.start_date;
</code>```

Save this as NextDates, then use this final query to get the answer:

```<code>SELECT NextDates.state, NextDates.start_date, Max(data.end_date) AS end_date, NextDates.product, NextDates.edition, NextDates.lg_sg, NextDates.area, NextDates.area_factor
    FROM NextDates INNER JOIN data ON NextDates.area_factor = data.area_factor
    WHERE (((data.start_date)<[next])) OR (((NextDates.Next) Is Null))
    GROUP BY NextDates.state, NextDates.start_date, NextDates.product, NextDates.edition, NextDates.lg_sg, NextDates.area, NextDates.area_factor;
</code>```

Depending on the data, you made need to add joins to restrict the logic to matching states, or products, or other field(s).

Title: Gaps and Island - Microsoft Access

Body:
I am trying to group my data by: State, Product, Edition, LG_SG, Area, and Area Factor. I then want to attach the minimum start date and the maximum end date to the record. I have a Gaps and Island issue though. If you look at the data, the .8428 shows up in two blocks that are not in chronological order. How do I solve this problem in Access?

Here is my current data.

state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   11/1/2010   PPO 6   SG  1   0.86
IL  11/1/2010   12/1/2010   PPO 6   SG  1   0.86
IL  12/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    2/1/2011    PPO 6   SG  1   0.8428
IL  2/1/2011    3/1/2011    PPO 6   SG  1   0.8428
IL  3/1/2011    4/1/2011    PPO 6   SG  1   0.8428
IL  4/1/2011    5/1/2011    PPO 6   SG  1   0.8428
IL  5/1/2011    6/1/2011    PPO 6   SG  1   0.8428
IL  6/1/2011    7/1/2011    PPO 6   SG  1   0.8428
IL  7/1/2011    8/1/2011    PPO 6   SG  1   0.8428
IL  8/1/2011    9/1/2011    PPO 6   SG  1   0.8428
IL  9/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   11/1/2011   PPO 6   SG  1   0.825944
IL  11/1/2011   12/1/2011   PPO 6   SG  1   0.825944
IL  12/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    2/1/2012    PPO 6   SG  1   0.8428
IL  2/1/2012    3/1/2012    PPO 6   SG  1   0.8428
IL  3/1/2012    4/1/2012    PPO 6   SG  1   0.8428
IL  4/1/2012    5/1/2012    PPO 6   SG  1   0.8428

I would like it to look like this.

state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    5/1/2012    PPO 6   SG  1   0.8428

Thank you all for your help.

Body:
This code is a start

SELECT data.state, data.start_date, data.product, data.edition, data.lg_sg, data.area, data.area_factor, data_1.area_factor AS previous
FROM data LEFT JOIN data AS data_1 ON data.start_date = data_1.end_date
WHERE (((data_1.area_factor) Is Null Or (data_1.area_factor)<>[data].[area_factor]));

It gives you the start date for each range, but not the end date.  If you're using this as a reference to search for a specific date, it might be enough - you can search for the last record that's less than or equal to your search date, without needing the end date.

I was initially thinking that an auto number field would help ID the end date, but now I'm not sure.  This query already does the work I would have done with an auto number field, and I don't quite see how to get the end date yet.

UPDATE:  This isn't elegant, but I can do it in a few steps:
Save the query above as StartDates.  Then use this query to find the next start date for the same area_factors:

SELECT StartDates.state, StartDates.start_date, StartDates.product, StartDates.edition, StartDates.lg_sg, StartDates.area, StartDates.area_factor, (select min(start_date) from StartDates T where T.area_factor=StartDates.area_factor and T.start_date>StartDates.start_date) AS [Next]
FROM StartDates
ORDER BY StartDates.start_date;

Save this as NextDates, then use this final query to get the answer:

SELECT NextDates.state, NextDates.start_date, Max(data.end_date) AS end_date, NextDates.product, NextDates.edition, NextDates.lg_sg, NextDates.area, NextDates.area_factor
    FROM NextDates INNER JOIN data ON NextDates.area_factor = data.area_factor
    WHERE (((data.start_date)<[next])) OR (((NextDates.Next) Is Null))
    GROUP BY NextDates.state, NextDates.start_date, NextDates.product, NextDates.edition, NextDates.lg_sg, NextDates.area, NextDates.area_factor;

Depending on the data, you made need to add joins to restrict the logic to matching states, or products, or other field(s).


问:
Cannot resolve method setText(java.lang.String) in Fragment
I am using the Pedometer to count the steps since the last reboot of a device.

I have created a textView which I want to set the text of to be the number of steps when the sensor is being used. (My TextView is called count)

My code for doing this is:

```<code>@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }
</code>```

I am getting an error here Cannot resolve method setText(java.lang.String)

I can post the rest of the class if it would help to fix the problem

Thanks

This is the rest of the class:

```<code>public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    TextView count = (TextView) getActivity().findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
</code>```

This is the XML file associated with this class:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>
</code>```

答:
Change

```<code>private TextView textView;
</code>```

to

```<code>private TextView count;
</code>```

And change

```<code>TextView count = (TextView) getActivity().findViewById(R.id.count);
</code>```

to

```<code>count = (TextView) getActivity().findViewById(R.id.count);
</code>```

Body:
I am using the Pedometer to count the steps since the last reboot of a device.

I have created a textView which I want to set the text of to be the number of steps when the sensor is being used. (My TextView is called count)

My code for doing this is:

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

I am getting an error here Cannot resolve method setText(java.lang.String)

I can post the rest of the class if it would help to fix the problem

Thanks

This is the rest of the class:

public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    TextView count = (TextView) getActivity().findViewById(R.id.count);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    getActivity().getSystemService(Context.SENSOR_SERVICE);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(getActivity(), "Count sensor not available!", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

This is the XML file associated with this class:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>

Body:
Change

private TextView textView;

to

private TextView count;

And change

TextView count = (TextView) getActivity().findViewById(R.id.count);

to

count = (TextView) getActivity().findViewById(R.id.count);


问:
Access data stored in AsyncStorage from ios native code (objective c)
I need to access data stored in AsyncStorage from iOS native Objective C code.

This is needed to get the data in sync instead of sending App event to JS and then send it back to native code.

答:
My current solution. Which technically isn't a direct answer to the question but does offer a work-around for sharing data between Javascript and native code, is to use NSUserDefaults.

Using this package, react-native-default-preferences to easily persist the data into NSUserdefaults and then on the native side easily retrieve them as normal.

For my purposes I am persisting a token retrieved in Javascript, to be used later by extensions of the app. This means I also persist to a UserDefaults suite using the same key as my app.

React Native (Javascript):

```<code>DefaultPreference.setName('group.myApp');
DefaultPreference.set('TOKEN', token);
</code>```

Objective-C:

```<code>NSString *TOKEN = [[[NSUserDefaults alloc] initWithSuiteName:@"group.myApp"] stringForKey:@"TOKEN"];
</code>```

Body:
My current solution. Which technically isn't a direct answer to the question but does offer a work-around for sharing data between Javascript and native code, is to use NSUserDefaults.

Using this package, react-native-default-preferences to easily persist the data into NSUserdefaults and then on the native side easily retrieve them as normal.

For my purposes I am persisting a token retrieved in Javascript, to be used later by extensions of the app. This means I also persist to a UserDefaults suite using the same key as my app.

React Native (Javascript):

DefaultPreference.setName('group.myApp');
DefaultPreference.set('TOKEN', token);

Objective-C:

NSString *TOKEN = [[[NSUserDefaults alloc] initWithSuiteName:@"group.myApp"] stringForKey:@"TOKEN"];


问:
php get two different random array elements
From an array

```<code> $my_array = array('a','b','c','d','e');
</code>```

I want to get two DIFFERENT random elements.

With the following code:

```<code> for ($i=0; $i<2; $i++) {
    $random = array_rand($my_array);  # one random array element number
    $get_it = $my_array[$random];    # get the letter from the array
    echo $get_it;
 }
</code>```

it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that?
Thanks

答:
Here's how I did it. Hopefully this helps anyone confused.</p>

```<code>$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
  echo $newArray[$i];
}
</code>```

Body:
From an array

 $my_array = array('a','b','c','d','e');

I want to get two DIFFERENT random elements.

With the following code:

 for ($i=0; $i<2; $i++) {
    $random = array_rand($my_array);  # one random array element number
    $get_it = $my_array[$random];    # get the letter from the array
    echo $get_it;
 }

it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that?
Thanks

Body:
Here's how I did it. Hopefully this helps anyone confused.

$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
  echo $newArray[$i];
}


答:
The field keyword allows you to assign a value inside a custom setter. In kotlin counter = 3 will call set(3). So if you would define

```<code>var counter=0
set(value){
    counter = value
}
</code>```

It would recursively call itself until your stack is full and your process crashes.
The field keyword assigns the value directly without calling the setter again.

Title: Kotlin explain me about Backing Fields

Body:
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

Body:
The field keyword allows you to assign a value inside a custom setter. In kotlin counter = 3 will call set(3). So if you would define

var counter=0
set(value){
    counter = value
}

It would recursively call itself until your stack is full and your process crashes.
The field keyword assigns the value directly without calling the setter again.


问:
Unresolved reference: HtmlConverter in iText library
I am trying to convert HTML String to PDF file in Android. I am using iText library but it is showing error:

Unresolved reference: HtmlConverter

Code:

```<code>HtmlConverter.convertToPdf(htmlString, FileOutputStream(File(context.cacheDir.path + "/SensorReport.pdf")))
</code>```

iText library import in module level gradle:

```<code>compile 'com.itextpdf:itextg:5.5.10'
</code>```

Please help.

答:
Please take a look at the pdfHTML page on the official web site.

I quote:

pdfHTML is an iText 7 add-on that allows you to easily convert HTML and CSS into PDF documents.

You are using iTextG 5.5.10. That is not iText 7. Furthermore, having iText 7 isn't sufficient. You also need the pdfHTML add-on.

This explains the unresolved reference: HtmlConverter isn't an iText 5 class, it's not even an iText 7 class. The HtmlConverter class can be found in the pdfHTML add-on, which is an add-on on top of iText 7.

We didn't invest in an Android port of iText 7 because:

The poor sales of iTextG didn't justify the investment in an Android port. That's odd, because an Android app is a distributed app and if the app is proprietary / closed source a commercial license is mandatory.

Developers are now used to use technology such as Xamarin to develop on one platform and to port their applications to another platform.

If you want to keep on using iTextG 5, you need to use the XML Worker add-on. Note that iTextG and XML Worker are also AGPL (hence a commercial license will be needed if you don't want to distribute your source code and your application for free). Also: support for iTextG 5 and XML Worker is being discontinued. As you can read in the intro of the HTML to PDF tutorial, XML Worker has many flaws.

Body:
I am trying to convert HTML String to PDF file in Android. I am using iText library but it is showing error:

Unresolved reference: HtmlConverter

Code:

HtmlConverter.convertToPdf(htmlString, FileOutputStream(File(context.cacheDir.path + "/SensorReport.pdf")))

iText library import in module level gradle:

compile 'com.itextpdf:itextg:5.5.10'

Please help.


问:
Reduce config tables:SymmetricDS
Well i'm trying to migrate data from my in-memory DB1 to my DB2. For this I'm using SymmetricDS configured in such a way that, when SymmetricDS starts, it will perform an inital load from DB1 to DB2. Furthermore whenever some data modification occurs in DB1, the same is pulled to DB2.

Now this is where i have a problem. SymmetricDS requires configuration tables or Sym Tables to be present at both the DB1 side and DB2 side.

Since my DB1 is in-memory, these configuration tables are taking a lot of memory.

So what I would like to know is whether there is a way ,to keep the configuration tables entirely in a seperate on-disk db, from DB1 side, and yet retain the existing functionality?

Hope i was able to make myself clear.

Any and all suggestions would be appreciated.

答: SymmetricDS 3.9 will provide a "load only" feature that will allow you to load into a database and have the sym tables created in an on disk H2 database.   This would allow you to replicate to your D2 without any sym tables in it. </p>

Title: Reduce config tables:SymmetricDS


问:
Specifying a startdate for cronjobs in GAE?
I've set up a cron.yaml file for my app to run some cronjobs, i.e. every 2 mins, every 15 mins... Is it possible to specify the tasks to start from a specific date? Say I want to start running all cronjobs from 6th december 2017?</p>

答:
The GAE cron Schedule format doesn't have direct support for the functionality you seek.

However it's relatively easy to obtain such functionality, see How to make a cron job run during business hours on Google App Engine cron.yaml?


问:
how to create a selenium/standalone-chrome image with changeable port (the 4444)
I'm was wondering how can I pass a different port number as argument when I'm running the selenium container instead of the default port(4444)

Usually I'm using:

```<code>docker run --shm-size=2G -d --net=host -e TZ=UTC -e SCREEN_WIDTH=1920 -e SCREEN_HEIGHT=1080  selenium/standalone-chrome:3.7.0
</code>```

Is it possible to do so with the current selenium image or do I need to build a selenium image of my own and if so how to create that kind of image?

答:
Not sure if this works with your docker image, it might help if you try to build your own image.

Use this image from GitHub
https://github.com/SeleniumHQ/docker-selenium/tree/master/StandaloneChrome

Open entrypoint.sh and edit
java ${JAVA_OPTS} -jar /opt/selenium/selenium-server-standalone.jar -role hub -port (custom port no.)

Then in dockerfile change EXPOES (custom port)
Then build docker again

Body:
I'm was wondering how can I pass a different port number as argument when I'm running the selenium container instead of the default port(4444)

Usually I'm using:

docker run --shm-size=2G -d --net=host -e TZ=UTC -e SCREEN_WIDTH=1920 -e SCREEN_HEIGHT=1080  selenium/standalone-chrome:3.7.0

Is it possible to do so with the current selenium image or do I need to build a selenium image of my own and if so how to create that kind of image?


问:
material angular select dropdown renders totally outside app-root
https://material.angular.io/components/select/overview
the select dropdown renders totally outside app-root.
Basically it creats a div with class="cdk-overlay-container" which is appended as sibling of the app. I want the drop down to open at exactly where I embed <mat-select> tag. What am I missing.

Here is my code

```<code>import { Component, Input, Output, OnInit, OnChanges, SimpleChanges, ChangeDetectionStrategy, EventEmitter } from '@angular/core';

import {FormControl} from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <nav class="row navbar navbar-default navbar-fixed-top">
        <div class="navbar-container">
            <div class="navbar__content">
                <mat-form-field>
                    <mat-select [formControl]="pc" panelClass="example-panel-{{pc.value}}">
                        <mat-option *ngFor="let panelColor of panelColors" [value]="panelColor.value">
                        {{ panelColor.viewValue }}
                        </mat-option>
                    </mat-select>
                </mat-form-field>
            </div>
        </div>
    </nav>

    <div class="main-page">
      NAVBAR ENDED MAIN PAGE STARTS
    </div>
    `,
  styleUrls: [ './app.component.scss' ],
  changeDetection: ChangeDetectionStrategy.Default
})
export class AppComponent  {
  private pc = new FormControl('red');
  private panelColors = [
    {value: 'red', viewValue: 'red'},
    {value: 'blue', viewValue: 'blue'},
    {value: 'green', viewValue: 'green'}
  ];
}
</code>```

I created a stackblitz here

答:
This can help you find the right path :

In the app.component.html, add a class to select <mat-form-field> tag :

```<code><mat-form-field class="myForm">
</code>```

At the bottom of app.component.scss

```<code>/*.navbar-default{
  height: 120px;
}*/

.myForm {
  height: 100px;
}

#cdk-overlay-2 > div {
  margin-top: 80px;
}

.page-content {
  margin-top: 100px;
}

.main-page{
  height: 130px;
}
</code>```

Body:
https://material.angular.io/components/select/overview
the select dropdown renders totally outside app-root.
Basically it creats a div with class="cdk-overlay-container" which is appended as sibling of the app. I want the drop down to open at exactly where I embed <mat-select> tag. What am I missing.

Here is my code

import { Component, Input, Output, OnInit, OnChanges, SimpleChanges, ChangeDetectionStrategy, EventEmitter } from '@angular/core';

import {FormControl} from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `

                <mat-form-field>
                    <mat-select [formControl]="pc" panelClass="example-panel-{{pc.value}}">
                        <mat-option *ngFor="let panelColor of panelColors" [value]="panelColor.value">
                        {{ panelColor.viewValue }}
                        </mat-option>
                    </mat-select>
                </mat-form-field>

      NAVBAR ENDED MAIN PAGE STARTS

    `,
  styleUrls: [ './app.component.scss' ],
  changeDetection: ChangeDetectionStrategy.Default
})
export class AppComponent  {
  private pc = new FormControl('red');
  private panelColors = [
    {value: 'red', viewValue: 'red'},
    {value: 'blue', viewValue: 'blue'},
    {value: 'green', viewValue: 'green'}
  ];
}

I created a stackblitz here

Body:
This can help you find the right path :

In the app.component.html, add a class to select <mat-form-field> tag :

<mat-form-field class="myForm">

At the bottom of app.component.scss

/*.navbar-default{
  height: 120px;
}*/

.myForm {
  height: 100px;
}

#cdk-overlay-2 > div {
  margin-top: 80px;
}

.page-content {
  margin-top: 100px;
}

.main-page{
  height: 130px;
}


问:
Django way to "Pre-cache" an existing database table?
I have a 200MB sized csv file containing rows where a key term is matched against a list of strings inside the second column.

```<code>term_x | ["term_1","term_2"]
term_y | ["term_1","term_2"]
term_z | ["term_1","term_2"]
</code>```

My Django app is not configured to use any complex memory caching (Redis, Memcached) and in practice, I want to pass a term into the database table to retrieve the corresponding list value. Due to its size however, retrieving the list from the correct row takes around half a second to do, on top of other actions being performed while loading the page.

Is it possible in Django to "pre-cache" this table upon server startup? i.e. add all of those values to the cache with the first column being the key? I have attempted something similar by overriding the "ready" method in my app.py to load the database table into the cache on startup, but I get null values when I try to use a term I know is in the table:

```<code>class MyAppConfig(AppConfig):

    name = 'test_display'

    def ready(self):
        print("Loading RS Lookup cache..."),

        #setup database connection....

        cache_df = pd.read_sql_query("Select * from table_to_cache", engine)

        print("Table loaded")

        for index, row in cache_df.iterrows():

             cache.set(row['term'], row['list_of_terms'], None)

        print("RS Table loaded")
</code>```

My init.py in the same Django app has only one line:

```<code>default_app_config = 'test_display.apps.MyAppConfig'
</code>```

答:
Check whether the following is correct:

In the project settings you did not configure caching or used the local memory caching as described in the documentation.

You only use the default cache (from django.core.cache import cache) or correctly handle cache names.

Make sure your code in .ready() actually stores the values you are trying to read later. You can use one of the following:

```<code>assert "my_term" in cache, "The term is not cached!"
</code>```

or

```<code>from django.core.cache.backends import locmem
print(locmem._caches)
# now check what you have inside using your very own eyes and patience
</code>```

As for the following:

Is it possible in Django to "pre-cache" ... ?

Your solution utilizes AppConfig.ready() which is generally a very good place for activities that your server should only perform once per instance. At least I am not aware of a better solution.

Body:
I have a 200MB sized csv file containing rows where a key term is matched against a list of strings inside the second column.

term_x | ["term_1","term_2"]
term_y | ["term_1","term_2"]
term_z | ["term_1","term_2"]

My Django app is not configured to use any complex memory caching (Redis, Memcached) and in practice, I want to pass a term into the database table to retrieve the corresponding list value. Due to its size however, retrieving the list from the correct row takes around half a second to do, on top of other actions being performed while loading the page.

Is it possible in Django to "pre-cache" this table upon server startup? i.e. add all of those values to the cache with the first column being the key? I have attempted something similar by overriding the "ready" method in my app.py to load the database table into the cache on startup, but I get null values when I try to use a term I know is in the table:

class MyAppConfig(AppConfig):

    name = 'test_display'

    def ready(self):
        print("Loading RS Lookup cache..."),

        #setup database connection....

        cache_df = pd.read_sql_query("Select * from table_to_cache", engine)

        print("Table loaded")

        for index, row in cache_df.iterrows():

             cache.set(row['term'], row['list_of_terms'], None)

        print("RS Table loaded")

My init.py in the same Django app has only one line:

default_app_config = 'test_display.apps.MyAppConfig'

Body:
Check whether the following is correct:

In the project settings you did not configure caching or used the local memory caching as described in the documentation.

You only use the default cache (from django.core.cache import cache) or correctly handle cache names.

Make sure your code in .ready() actually stores the values you are trying to read later. You can use one of the following:

assert "my_term" in cache, "The term is not cached!"

or

from django.core.cache.backends import locmem
print(locmem._caches)
# now check what you have inside using your very own eyes and patience

As for the following:

Is it possible in Django to "pre-cache" ... ?

Your solution utilizes AppConfig.ready() which is generally a very good place for activities that your server should only perform once per instance. At least I am not aware of a better solution.


问:
Having trouble connecting to EC2 instance via SSH
Getting Permission denied (publickey) error when connecting to my newly created EC2 instance using the following command:

ssh console@my-ec2-instance

BACKGROUND

I'm following this guide.

Near the beginning, it has you create a stack from a template. The second step of stack creation wizard asks you for SSHPublicKey.

I opened my console and typed this:

```<code>ssh-keygen -t rsa -b 4096 -C "email@example.com"
</code>```

This created a "keypair" file and a "keypair.pub" file on C:\Users\Username.ssh.

I opened keypair.pub using a text editor. It looked like this:

```<code>ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDKMaPD3... email@example.com
</code>```

I copied the encrypted value to the SSHPublicKey field of the EC2 configuration shown in the above screenshot.

Then I added the private key file "keypair" to the SSH agent using:

```<code>ssh-add "C:\Users\Username\.ssh\keypair"
</code>```

I got a confirmation message that said "identity added". I confirmed by typing ssh-add -l which lists the identities:

```<code>λ ssh-add -l
4096 SHA256:TK5SQ7odC9x... C:\Users\Username\.ssh\keypair (RSA)
</code>```

So everything seems to be set up correctly? EC2 instance knows the public key, SSH Agent has the private key. So why am I getting permission denied (publickey)?

UPDATE:

I've also tried explicitly specifying the private key using the -i flag:

```<code>ssh -i "C:\Users\Username\keypair" console@my-ec2-instance
</code>```

Same error however.

答:
Are you sure that console is available as SSH user?

For Amazon Linux, the user name is ec2-user.

For RHEL, the user name is ec2-user or root.

For Ubuntu, the user name is ubuntu or root.

For Centos, the user name is centos.

For Fedora, the user name is ec2-user.

For SUSE, the user name is ec2-user or root.

See also the official AWS EC2 documentation.

Body:
Getting Permission denied (publickey) error when connecting to my newly created EC2 instance using the following command:

ssh console@my-ec2-instance

BACKGROUND

I'm following this guide.

Near the beginning, it has you create a stack from a template. The second step of stack creation wizard asks you for SSHPublicKey.

I opened my console and typed this:

ssh-keygen -t rsa -b 4096 -C "email@example.com"

This created a "keypair" file and a "keypair.pub" file on C:\Users\Username.ssh.

I opened keypair.pub using a text editor. It looked like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDKMaPD3... email@example.com

I copied the encrypted value to the SSHPublicKey field of the EC2 configuration shown in the above screenshot.

Then I added the private key file "keypair" to the SSH agent using:

ssh-add "C:\Users\Username\.ssh\keypair"

I got a confirmation message that said "identity added". I confirmed by typing ssh-add -l which lists the identities:

λ ssh-add -l
4096 SHA256:TK5SQ7odC9x... C:\Users\Username\.ssh\keypair (RSA)

So everything seems to be set up correctly? EC2 instance knows the public key, SSH Agent has the private key. So why am I getting permission denied (publickey)?

UPDATE:

I've also tried explicitly specifying the private key using the -i flag:

ssh -i "C:\Users\Username\keypair" console@my-ec2-instance

Same error however.


问:
Django 1.8 inspectdb command doesn't see PostgreSQL views as per documentation
I have a Django 1.8 application with a PostgreSQL database. I run the django inspectdb from the command line to examine models for the views, but the views don't show up in the model output.

Here's the version output:

```<code>17:36 $ python well/manage.py --version
1.8.2
</code>```

And here's what psql sees:

```<code>\dv
                List of relations
 Schema |             Name              | Type |  Owner
--------+-------------------------------+------+---------
 public | hospitalizations_over_30_days | view | dwatson
 public | interval_30_days              | view | dwatson
(2 rows)
</code>```

From the django 1.8.2 documentation:

```<code>New in Django 1.8:
A feature to inspect database views was added. In previous versions, only tables (not views) were inspected.
</code>```

How can I get the PostgreSQL views to appear in the Django 1.8.2 inspectdb output?

答:
As of Django 1.10, you can simply name an individual view as a parameter to your inspectdb command:

```<code>python well/manage.py inspectdb hospitalizations_over_30_days
</code>```

The default inspectdb will only output models.py for tables, but models for views can be generated individually by naming them.

In Django 2.1 and above, if you want inspectdb to generate models for all tables and views, use the inspectdb --include-views option, which I contributed to Django 2.1 as a result of this question!

```<code>python well/manage.py inspectdb --include-views
</code>```

To generate models for both tables and views in Django 2.0 and below, you have to edit the Django source code. In Django 2.0, change line 57 in django/core/management/commands/inspectdb.py to:

```<code>tables_to_introspect = options['table'] or connection.introspection.table_names(cursor=cursor, include_views=True)
</code>```

Beware that the generated models won't have fields with primary_key=True set, you will need to add primary keys manually.

Body:
I have a Django 1.8 application with a PostgreSQL database. I run the django inspectdb from the command line to examine models for the views, but the views don't show up in the model output.

Here's the version output:

17:36 $ python well/manage.py --version
1.8.2

And here's what psql sees:

\dv
                List of relations
 Schema |             Name              | Type |  Owner
--------+-------------------------------+------+---------
 public | hospitalizations_over_30_days | view | dwatson
 public | interval_30_days              | view | dwatson
(2 rows)

From the django 1.8.2 documentation:

New in Django 1.8:
A feature to inspect database views was added. In previous versions, only tables (not views) were inspected.

How can I get the PostgreSQL views to appear in the Django 1.8.2 inspectdb output?

Body:
As of Django 1.10, you can simply name an individual view as a parameter to your inspectdb command:

python well/manage.py inspectdb hospitalizations_over_30_days

The default inspectdb will only output models.py for tables, but models for views can be generated individually by naming them.

In Django 2.1 and above, if you want inspectdb to generate models for all tables and views, use the inspectdb --include-views option, which I contributed to Django 2.1 as a result of this question!

python well/manage.py inspectdb --include-views

To generate models for both tables and views in Django 2.0 and below, you have to edit the Django source code. In Django 2.0, change line 57 in django/core/management/commands/inspectdb.py to:

tables_to_introspect = options['table'] or connection.introspection.table_names(cursor=cursor, include_views=True)

Beware that the generated models won't have fields with primary_key=True set, you will need to add primary keys manually.


问:
Python 3 if statement recognition
The calculator does not recognize the price input being 60 as the first if statement, it will send you to else.</p>

```<code>while True:
    price = float(input("How much does it cost? (include cents!): $"))
    discount=float(price)*100 / 1000
    discount2=float(price)*200 /1000
    proceed = 60
    proceed2 = 120
    if price >= proceed << proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    if price >= proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    else:
        print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
</code>```

答:
I fixed it, the first if statement used << when it should have used <.

```<code>while True:
    price = float(input("How much does it cost? (include cents!): $"))
    discount=float(price)*100 / 1000
    discount2=float(price)*200 /1000
    proceed = 60
    proceed2 = 120
    if price >= proceed < proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    if price >= proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    else:
        print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
</code>```

Title: Python 3 if statement recognition

Body:
The calculator does not recognize the price input being 60 as the first if statement, it will send you to else.

while True:
    price = float(input("How much does it cost? (include cents!): $"))
    discount=float(price)*100 / 1000
    discount2=float(price)*200 /1000
    proceed = 60
    proceed2 = 120
    if price >= proceed << proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    if price >= proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    else:
        print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()

Body:
I fixed it, the first if statement used << when it should have used <.

while True:
    price = float(input("How much does it cost? (include cents!): $"))
    discount=float(price)*100 / 1000
    discount2=float(price)*200 /1000
    proceed = 60
    proceed2 = 120
    if price >= proceed < proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    if price >= proceed2:
        print("Your new cost is")
        print(round(price - discount, 2))
        print("Press any key to exit")
        input()
    else:
        print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()


问:
Python string join performance
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

```<code>import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t
</code>```

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697
```

Shouldn't it be exactly the other way around?

答:
Shouldn't it be exactly the other way round?

Not necessarily. I don't know the internals of Python well enough to comment specifically, but some common observations are that your first loop uses a simple operator + which is probably implemented as a primitive by the runtime. In contrast, the other loops first have to resolve a module name, resolve the variable/class found there and then call a member function on that.

Another note is that your loop might simply be too small to yield significant numbers. Considering your low overall running time, this probably makes your tests useless.

Also, your test case is highly specialized on two short strings. Such cases never give a clear picture of edge case performance.

OwnerDisplayName: Danny

Title: Python string join performance

Body:
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697

Shouldn't it be exactly the other way around?

LastEditorDisplayName: Danny

OwnerDisplayName: Konrad Rudolph


问:
Pyspark inverted index
I am creating an inverted index of documents, where the output should contain a word (from the text file) followed by all the files it appeared in. Something like

[word1: file1.txt file2.txt] [word2: file2.txt file3.txt]

I have written the code but it throws me this error.

for k, v in iterator:
  TypeError: () takes exactly 2 arguments (1 given)

Code:

```<code>from pyspark import SparkContext
sc = SparkContext("local", "app")

path = '/ebooks'
rdd = sc.wholeTextFiles(path)

output = rdd.flatMap(lambda (file,contents):contents.lower().split())\
            .map(lambda file,word: (word,file))\
            .reduceByKey(lambda a,b: a+b)
print output.take(10)
</code>```

I cannot figure out a way to emit both key and value (word and the filename) in the map. How can i go about it?

In mapreduce, the (word, key) pair can be emitted (key is the filename) but how can this be done in spark?

答:
I haven't tested this on dummy data, but looking at your code, I think the following modification should work:</p>

```<code>output = rdd.flatMap(lambda (file,contents):[(file, word) for word in contents.lower().split()])\
      .map(lambda (file, word): (word,[file]))\
      .reduceByKey(lambda a,b: a+b)
</code>```

Title: Pyspark inverted index

Body:
I am creating an inverted index of documents, where the output should contain a word (from the text file) followed by all the files it appeared in. Something like

[word1: file1.txt file2.txt] [word2: file2.txt file3.txt]

I have written the code but it throws me this error.

for k, v in iterator:
  TypeError: () takes exactly 2 arguments (1 given)

Code:

from pyspark import SparkContext
sc = SparkContext("local", "app")

path = '/ebooks'
rdd = sc.wholeTextFiles(path)

output = rdd.flatMap(lambda (file,contents):contents.lower().split())\
            .map(lambda file,word: (word,file))\
            .reduceByKey(lambda a,b: a+b)
print output.take(10)

I cannot figure out a way to emit both key and value (word and the filename) in the map. How can i go about it?

In mapreduce, the (word, key) pair can be emitted (key is the filename) but how can this be done in spark?

Body:
I haven't tested this on dummy data, but looking at your code, I think the following modification should work:

output = rdd.flatMap(lambda (file,contents):[(file, word) for word in contents.lower().split()])\
      .map(lambda (file, word): (word,[file]))\
      .reduceByKey(lambda a,b: a+b)


问:
How to get to invoice link in invoices api
I am interested to have a invoice link/pdf from the api which returns the invoice using new freshbooks api endpoint /invoices/<invoiceid" rel="nofollow noreferrer">https://api.freshbooks.com/accounting/account/<accountid>/invoices/<invoiceid>

Even including direct_links I am unable to get the link to the invoice. With direct_links it returns json with fields id, contactid, created_date, type, userid, objectid, token.

答:
I currently work at FreshBooks.

Unfortunately these direct link tokens will only work with old FreshBooks, which isn't mentioned in the documentation -- I'll see if we can fix that.

Poking through, it doesn't look like we've has exposed a way to access a PDF version of the invoice through the public API just yet. But I'll pass that on to the appropriate channels and I'll update this answer if that changes.

Body:
I am interested to have a invoice link/pdf from the api which returns the invoice using new freshbooks api endpoint <a href="https://api.freshbooks.com/accounting/account/<accountid>/invoices/<invoiceid" rel="nofollow noreferrer">https://api.freshbooks.com/accounting/account/<accountid>/invoices/<invoiceid>

Even including direct_links I am unable to get the link to the invoice. With direct_links it returns json with fields id, contactid, created_date, type, userid, objectid, token.


问:
How do I set up CORS correctly on a Jooby application
I am creating an API with the Jooby framework mostly following this guide. I am also using Vue.js as the frontend. However I am having issues with CORS. When I try to do a get request from my Vue.js frontend I get the error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

This is my Jooby application.conf file:

```<code># add or override properties
# See https://github.com/typesafehub/config/blob/master/HOCON.md for more
details
db = mem

schema = """

create table if not exists pets (

id int not null auto_increment,

name varchar(255) not null,

primary key (id)

);
"""
cors {
# Configures the Access-Control-Allow-Origin CORS header. Possibly values:
*, domain, regex or a list of previous values.
# Example:
# "*"
# ["http://foo.com"]
# ["http://*.com"]
# ["http://foo.com", "http://bar.com"]
origin: "*"

# If true, set the Access-Control-Allow-Credentials header
credentials: true

# Allowed methods: Set the Access-Control-Allow-Methods header
allowedMethods: [GET, POST]

# Allowed headers: set the Access-Control-Allow-Headers header. Possibly
values: *, header name or a list of previous values.
# Examples
# "*"
# Custom-Header
# [Header-1, Header-2]
allowedHeaders: ["X-Requested-With, Content-Type, Accept, Origin"]

# Preflight max age: number of seconds that preflight requests can be cached
by the client
maxAge: 30m

# Set the Access-Control-Expose-Headers header
# exposedHeaders: []
}
</code>```

And this is App.java file where I query the database

```<code>package org.jooby.guides;

import java.util.List;

import org.jooby.Jooby;
import org.jooby.Results;
import org.jooby.jdbc.Jdbc;
import org.jooby.jdbi.Jdbi;
import org.jooby.json.Jackson;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;

import com.typesafe.config.Config;

public class App extends Jooby {

{
use(new Jackson());

use(new Jdbc());

use(new Jdbi()
    // 1 dbi ready
    .doWith((final DBI dbi, final Config conf) -> {
      // 2 open a new handle
      try (Handle handle = dbi.open()) {
        // 3. execute script
        handle.execute(conf.getString("schema"));
      }
    }));

/** Pet API. */
use("/api/pets")
    /** List pets. */
    .get(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        PetRepository repo = handle.attach(PetRepository.class);
        List<Pet> pets = repo.list();
        return pets;
      });
    })
    /** Get a pet by ID. */
    .get("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        Pet pet = repo.findById(id);
        return pet;
      });
    })
    /** Create a pet. */
    .post(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        int petId = repo.insert(pet);
        pet.setId(petId);
        return pet;
      });
    })
    /** Update a pet. */
    .put(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        repo.update(pet);
        return pet;
      });
    })
    /** Delete a pet by ID. */
    .delete("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        repo.deleteById(id);
        return Results.noContent();
      });
    });
}

public static void main(final String[] args) {
run(App::new, args);
}

}
</code>```

How do I fix this?

答:
From documentation you need to add a CorsHandler:

```<code>{
   use("*", new CorsHandler());
   ...
}
</code>```

Properties are optional, unless you want to change a default value.

Body:
I am creating an API with the Jooby framework mostly following this guide. I am also using Vue.js as the frontend. However I am having issues with CORS. When I try to do a get request from my Vue.js frontend I get the error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

This is my Jooby application.conf file:

# add or override properties
# See https://github.com/typesafehub/config/blob/master/HOCON.md for more
details
db = mem

schema = """

create table if not exists pets (

id int not null auto_increment,

name varchar(255) not null,

primary key (id)

);
"""
cors {
# Configures the Access-Control-Allow-Origin CORS header. Possibly values:
*, domain, regex or a list of previous values.
# Example:
# "*"
# ["http://foo.com"]
# ["http://*.com"]
# ["http://foo.com", "http://bar.com"]
origin: "*"

# If true, set the Access-Control-Allow-Credentials header
credentials: true

# Allowed methods: Set the Access-Control-Allow-Methods header
allowedMethods: [GET, POST]

# Allowed headers: set the Access-Control-Allow-Headers header. Possibly
values: *, header name or a list of previous values.
# Examples
# "*"
# Custom-Header
# [Header-1, Header-2]
allowedHeaders: ["X-Requested-With, Content-Type, Accept, Origin"]

# Preflight max age: number of seconds that preflight requests can be cached
by the client
maxAge: 30m

# Set the Access-Control-Expose-Headers header
# exposedHeaders: []
}

And this is App.java file where I query the database

package org.jooby.guides;

import java.util.List;

import org.jooby.Jooby;
import org.jooby.Results;
import org.jooby.jdbc.Jdbc;
import org.jooby.jdbi.Jdbi;
import org.jooby.json.Jackson;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;

import com.typesafe.config.Config;

public class App extends Jooby {

{
use(new Jackson());

use(new Jdbc());

use(new Jdbi()
    // 1 dbi ready
    .doWith((final DBI dbi, final Config conf) -> {
      // 2 open a new handle
      try (Handle handle = dbi.open()) {
        // 3. execute script
        handle.execute(conf.getString("schema"));
      }
    }));

/** Pet API. */
use("/api/pets")
    /** List pets. */
    .get(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        PetRepository repo = handle.attach(PetRepository.class);
        List<Pet> pets = repo.list();
        return pets;
      });
    })
    /** Get a pet by ID. */
    .get("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        Pet pet = repo.findById(id);
        return pet;
      });
    })
    /** Create a pet. */
    .post(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        int petId = repo.insert(pet);
        pet.setId(petId);
        return pet;
      });
    })
    /** Update a pet. */
    .put(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        repo.update(pet);
        return pet;
      });
    })
    /** Delete a pet by ID. */
    .delete("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        repo.deleteById(id);
        return Results.noContent();
      });
    });
}

public static void main(final String[] args) {
run(App::new, args);
}

}

How do I fix this?

Body:
From documentation you need to add a CorsHandler:

{
   use("*", new CorsHandler());
   ...
}

Properties are optional, unless you want to change a default value.


问:
www.topstonesoftware.com is not forwarding to topstonesoftware.com on AWS static web site
I've been trying to follow the directions on the AWS page

Example: Setting up a Static Website Using a Custom Domain

I have created two S3 buckets: topstonesoftware.com and www.topstonesoftware.com.  The www bucket forwards to the topstonesoftware.com bucket

I've made the Amazon Route 53 entries (see below).

For reasons that I don't understand, http://topstonesoftware.com works, but http://www.topstonesoftware.com doesn't work (e.g., entering www.topstonesoftware.com just hangs the browser and never resolves the DNS).

When I run "dig" (dig www.topstonesoftware.com) it reports that there is no error in the DNS lookup. Dig also shows the DNS query resolving to the S3 bucket for www.topstonesoftware.com:

```<code>;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47363
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.topstonesoftware.com.  IN  A

;; ANSWER SECTION:
www.topstonesoftware.com. 300   IN  CNAME   www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com.
www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com. 60 IN CNAME s3-website-us-east-1.amazonaws.com.
s3-website-us-east-1.amazonaws.com. 5 IN A  52.216.17.170
</code>```

I've read thought Stackoverflow and the Amazon documentation, but so far, no joy.

Here's the DNS.  The alias record is for topstonesoftware.com and is the alias to the S3 bucket. The CNAME record details are shown.

Many thanks in advance.

答:
When you create the www.example.com bucket that is paired with your example.com bucket on AWS S3, create the www.example.com bucket with public permissions. Do not add the JSON permission record that you added for the example.com bucket. For some reason, this messes up access.

When I removed my www.topstonesoftware.com bucket and recreated it with public permissions and added forwarding to topstonesoftware.com, the www.topstonesoftware.com subdomain started to work.

As noted above, a CNAME record is not needed and may, in fact, be counter productive.

Body:
I've been trying to follow the directions on the AWS page

Example: Setting up a Static Website Using a Custom Domain

I have created two S3 buckets: topstonesoftware.com and www.topstonesoftware.com.  The www bucket forwards to the topstonesoftware.com bucket

I've made the Amazon Route 53 entries (see below).

For reasons that I don't understand, http://topstonesoftware.com works, but http://www.topstonesoftware.com doesn't work (e.g., entering www.topstonesoftware.com just hangs the browser and never resolves the DNS).

When I run "dig" (dig www.topstonesoftware.com) it reports that there is no error in the DNS lookup. Dig also shows the DNS query resolving to the S3 bucket for www.topstonesoftware.com:

;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47363
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.topstonesoftware.com.  IN  A

;; ANSWER SECTION:
www.topstonesoftware.com. 300   IN  CNAME   www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com.
www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com. 60 IN CNAME s3-website-us-east-1.amazonaws.com.
s3-website-us-east-1.amazonaws.com. 5 IN A  52.216.17.170

I've read thought Stackoverflow and the Amazon documentation, but so far, no joy.

Here's the DNS.  The alias record is for topstonesoftware.com and is the alias to the S3 bucket. The CNAME record details are shown.

Many thanks in advance.