问:
Angular 2 can't resolve all parameters for service
I have two services: LoginService and UserService. I am trying to inject UserService into LoginService and the app won't run.

In the console, I have the error:

Error: Can't resolve all parameters for UserService: ([object Object],
  ?). at SyntaxError.ZoneAwareError
  (http://localhost:4200/polyfills.bundle.js:7156:33) at
  SyntaxError.BaseError [as constructor]

this is my LoginService:

```<code>import {UserService} from '../services/user.service';
@Injectable()
export class LoginService {

  constructor(public _http: Http,public us:UserService) {
  }
</code>```

and UserService:

```<code> @Injectable()
    export class UserService {
    constructor(private _http: Http , public _ls: LoginService) {

    }
</code>```

angular module:

```<code>import {LoginService} from './services/login.service';
import {UserService} from './services/user.service';

@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserService, LoginService, appRoutingProviders],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
You have a circular reference.

Your UserService requires LoginService, and LoginService requires UserService.

Remove one of the dependencies. E.g. refactor your UserService so that it does not require a reference to LoginService

ContentLicense: CC BY-SA 4.0

Body:
I have two services: LoginService and UserService. I am trying to inject UserService into LoginService and the app won't run.

In the console, I have the error:

Error: Can't resolve all parameters for UserService: ([object Object],
  ?). at SyntaxError.ZoneAwareError
  (http://localhost:4200/polyfills.bundle.js:7156:33) at
  SyntaxError.BaseError [as constructor]

this is my LoginService:

import {UserService} from '../services/user.service';
@Injectable()
export class LoginService {

  constructor(public _http: Http,public us:UserService) {
  }

and UserService:

 @Injectable()
    export class UserService {
    constructor(private _http: Http , public _ls: LoginService) {

    }

angular module:

import {LoginService} from './services/login.service';
import {UserService} from './services/user.service';

@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserService, LoginService, appRoutingProviders],
  bootstrap: [AppComponent]
})
export class AppModule { }


来源: stackexchange

问:
Prolog - remove the non unique elements
I have a predicate to check if the element is member of list and looks the following:

```<code>member(X,[X|_]).
member(X,[_|T]) :- member(X,T).
</code>```

When I called: ?- member(1,[2,3,1,4])
I get: true.

And now I have to use it to write predicate which will remove all non unique elements from list of lists like the following:

```<code>remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]],X).
X = [[t],[w],[i,b,b],[z,c]]
</code>```

How can I do that?

答:
Going by your example and @false's comment, the actual problem seems to be something like removing elements from each sublist that occur in any other sublist. My difficulty conceptualizing this into words has led me to build what I consider a pretty messy and gross piece of code.

So first I want a little helper predicate to sort of move member/2 up to lists of sublists.

```<code>in_sublist(X, [Sublist|_])  :- member(X, Sublist).
in_sublist(X, [_|Sublists]) :- in_sublist(X, Sublists).
</code>```

This is no great piece of work, and in truth I feel like it should be inlined somehow because I just can't see myself ever wanting to use this on its own.

Now, my initial solution wasn't correct and looked like this:

```<code>remove([Sub1|Subs], [Res1|Result]) :-
    findall(X, (member(X, Sub1), \+ in_sublist(X, Subs)), Res1),
    remove(Subs, Result).
remove([], []).
</code>```

You can see the sort of theme I'm going for here though: let's use findall/3 to enumerate the elements of the sublist in here and then we can filter out the ones that occur in the other lists. This doesn't quite do the trick, the output looks like this.

```<code>?- remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]], R).
R = [[t], [a, w], [i, k, b, b], [z, m, m, c]].
</code>```

So, it starts off looking OK with [t] but then loses the plot with [a,w] because there is not visibility into the input [a,m,t,a] when we get to the first recursive call. There are several ways we could deal with it; a clever one would probably be to form a sort of zipper, where we have the preceding elements of the list and the succeeding ones together. Another approach would be to remove the elements in this list from all the succeeding lists before the recursive call. I went for a "simpler" solution which is messier and harder to read but took less time. I would strongly recommend you investigate the other options for readability.

```<code>remove(In, Out) :- remove(In, Out, []).
remove([Sub1|Subs], [Res1|Result], Seen) :-
    findall(X, (member(X, Sub1),
                \+ member(X, Seen),
                \+ in_sublist(X, Subs)), Res1),
    append(Sub1, Seen, Seen1),
    remove(Subs, Result, Seen1).
remove([], [], _).
</code>```

So basically now I'm keeping a "seen" list. Right before the recursive call, I stitch together the stuff I've seen so far and the elements of this list. This is not particularly efficient, but it seems to get the job done:

```<code>?- remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]], R).
R = [[t], [w], [i, b, b], [z, c]].
</code>```

This strikes me as a pretty nasty problem. I'm surprised how nasty it is, honestly. I'm hoping someone else can come along and find a better solution that reads better.

Another thing to investigate would be DCGs, which can be helpful for doing these kinds of list processing tasks.

ContentLicense: CC BY-SA 3.0

Title: Prolog - remove the non unique elements

Body:
I have a predicate to check if the element is member of list and looks the following:

member(X,[X|_]).
member(X,[_|T]) :- member(X,T).

When I called: ?- member(1,[2,3,1,4])
I get: true.

And now I have to use it to write predicate which will remove all non unique elements from list of lists like the following:

remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]],X).
X = [[t],[w],[i,b,b],[z,c]]

How can I do that?

Body:
Going by your example and @false's comment, the actual problem seems to be something like removing elements from each sublist that occur in any other sublist. My difficulty conceptualizing this into words has led me to build what I consider a pretty messy and gross piece of code.

So first I want a little helper predicate to sort of move member/2 up to lists of sublists.

in_sublist(X, [Sublist|_])  :- member(X, Sublist).
in_sublist(X, [_|Sublists]) :- in_sublist(X, Sublists).

This is no great piece of work, and in truth I feel like it should be inlined somehow because I just can't see myself ever wanting to use this on its own.

Now, my initial solution wasn't correct and looked like this:

remove([Sub1|Subs], [Res1|Result]) :-
    findall(X, (member(X, Sub1), \+ in_sublist(X, Subs)), Res1),
    remove(Subs, Result).
remove([], []).

You can see the sort of theme I'm going for here though: let's use findall/3 to enumerate the elements of the sublist in here and then we can filter out the ones that occur in the other lists. This doesn't quite do the trick, the output looks like this.

?- remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]], R).
R = [[t], [a, w], [i, k, b, b], [z, m, m, c]].

So, it starts off looking OK with [t] but then loses the plot with [a,w] because there is not visibility into the input [a,m,t,a] when we get to the first recursive call. There are several ways we could deal with it; a clever one would probably be to form a sort of zipper, where we have the preceding elements of the list and the succeeding ones together. Another approach would be to remove the elements in this list from all the succeeding lists before the recursive call. I went for a "simpler" solution which is messier and harder to read but took less time. I would strongly recommend you investigate the other options for readability.

remove(In, Out) :- remove(In, Out, []).
remove([Sub1|Subs], [Res1|Result], Seen) :-
    findall(X, (member(X, Sub1),
                \+ member(X, Seen),
                \+ in_sublist(X, Subs)), Res1),
    append(Sub1, Seen, Seen1),
    remove(Subs, Result, Seen1).
remove([], [], _).

So basically now I'm keeping a "seen" list. Right before the recursive call, I stitch together the stuff I've seen so far and the elements of this list. This is not particularly efficient, but it seems to get the job done:

?- remove([[a,m,t,a],[k,a,w],[i,k,b,b],[z,m,m,c]], R).
R = [[t], [w], [i, b, b], [z, c]].

This strikes me as a pretty nasty problem. I'm surprised how nasty it is, honestly. I'm hoping someone else can come along and find a better solution that reads better.

Another thing to investigate would be DCGs, which can be helpful for doing these kinds of list processing tasks.


问:
Cython bytes to C char*
I am trying to write a Cython extension to CPython to wrap the mcrypt library, so that I can use it with Python 3.  However, I am running into a problem where I segfault while trying to use one of the mcrypt APIs.

The code that is failing is:

```<code>def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval
</code>```

Now, the way I understand the Cython documentation, the assignment on line 3 should copy the contents of the buffer (a  object in Python 3) to the C string pointer.  I would figure that this would also mean that it would allocate the memory, but when I made this modification:

```<code>def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = <char *>malloc(src_len)
    ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval
</code>```

it still crashed with a segfault.  It's crashing inside of mcrypt_generic, but when I use plain C code I am able to make it work just fine, so there has to be something that I am not quite understanding about how Cython is working with C data here.

Thanks for any help!

ETA:  The problem was a bug on my part.  I was working on this after being awake for far too many hours (isn't that something we've all done at some point?) and missed something stupid.  The code that I now have, which works, is:

```<code>def _real_encrypt(self, source):
    src_len = len(source)
    cdef char *ciphertext = <char *>malloc(src_len)
    cmc.strncpy(ciphertext, source, src_len)
    cmc.mcrypt_generic_init(self._mcStream, <void *>self._key,
                            len(self._key), NULL)
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext,
                       src_len)

    retval = ciphertext[:src_len]
    cmc.mcrypt_generic_deinit(self._mcStream)
    return retval
</code>```

It's probably not the most efficient code in the world, as it makes a copy to do the encryption and then a second copy to the return value.  I'm not sure if it is possible to avoid that, though, since I'm not sure if it is possible to take a newly-allocated buffer and return it to Python in-place as a bytestring.  But now that I have a working function, I'm going to implement a block-by-block method as well, so that one can provide an iterable of blocks for encryption or decryption, and be able to do it without having the entire source and destination all in memory all at once---that way, it'd be possible to encrypt/decrypt huge files without having to worry about holding up to three copies of it in memory at any one point...

Thanks for the help, everyone!

答:
The approach I've used (with Python 2.x) is to declare the string type parameters in the function signature so that the Cython code does all conversions and type checking automatically:

```<code>def _real_encrypt(self,char* src):
    ...
</code>```

ContentLicense: CC BY-SA 2.5

Title: Cython bytes to C char*

Body:
I am trying to write a Cython extension to CPython to wrap the mcrypt library, so that I can use it with Python 3.  However, I am running into a problem where I segfault while trying to use one of the mcrypt APIs.

The code that is failing is:

def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval

Now, the way I understand the Cython documentation, the assignment on line 3 should copy the contents of the buffer (a  object in Python 3) to the C string pointer.  I would figure that this would also mean that it would allocate the memory, but when I made this modification:

def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = <char *>malloc(src_len)
    ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval

it still crashed with a segfault.  It's crashing inside of mcrypt_generic, but when I use plain C code I am able to make it work just fine, so there has to be something that I am not quite understanding about how Cython is working with C data here.

Thanks for any help!

ETA:  The problem was a bug on my part.  I was working on this after being awake for far too many hours (isn't that something we've all done at some point?) and missed something stupid.  The code that I now have, which works, is:

def _real_encrypt(self, source):
    src_len = len(source)
    cdef char *ciphertext = <char *>malloc(src_len)
    cmc.strncpy(ciphertext, source, src_len)
    cmc.mcrypt_generic_init(self._mcStream, <void *>self._key,
                            len(self._key), NULL)
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext,
                       src_len)

    retval = ciphertext[:src_len]
    cmc.mcrypt_generic_deinit(self._mcStream)
    return retval

It's probably not the most efficient code in the world, as it makes a copy to do the encryption and then a second copy to the return value.  I'm not sure if it is possible to avoid that, though, since I'm not sure if it is possible to take a newly-allocated buffer and return it to Python in-place as a bytestring.  But now that I have a working function, I'm going to implement a block-by-block method as well, so that one can provide an iterable of blocks for encryption or decryption, and be able to do it without having the entire source and destination all in memory all at once---that way, it'd be possible to encrypt/decrypt huge files without having to worry about holding up to three copies of it in memory at any one point...

Thanks for the help, everyone!

Body:
The approach I've used (with Python 2.x) is to declare the string type parameters in the function signature so that the Cython code does all conversions and type checking automatically:

def _real_encrypt(self,char* src):
    ...


问:
MySQL bidirectional trigger
I have to do two triggers, first one, after insert in test1 table, to insert in test2 table another row. All right, the problem is that i have to do same trigger in reverse form, after insert row in test2 table, insert new row on test1. I know that trigger can't insert in a table when a trigger is firing, but i need resolve this. I don't have a lot experience with triggers, i hope that this could be resolved.

```<code>DELIMITER $$ CREATE TRIGGER `ai_test1_test2` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN INSERT INTO test2 (vtest2) VALUES (new.vtest1)
END$$
DELIMITER ;
</code>```

Bidirectional trigger:

```<code>DELIMITER $$ CREATE TRIGGER `ai_test2_test1` AFTER INSERT ON `test2`
FOR EACH ROW
BEGIN INSERT INTO test1 (vtest1) VALUES (new.vtest2)
END$$
DELIMITER ;
</code>```

Thanks.

Edit:

The infinite loop can't be resolved. Triggers can't be bidirectional... I think that i must be use a PROCEDURE...

Title: MySQL bidirectional trigger

Body:
I have to do two triggers, first one, after insert in test1 table, to insert in test2 table another row. All right, the problem is that i have to do same trigger in reverse form, after insert row in test2 table, insert new row on test1. I know that trigger can't insert in a table when a trigger is firing, but i need resolve this. I don't have a lot experience with triggers, i hope that this could be resolved.

DELIMITER $$ CREATE TRIGGER `ai_test1_test2` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN INSERT INTO test2 (vtest2) VALUES (new.vtest1)
END$$
DELIMITER ;

Bidirectional trigger:

DELIMITER $$ CREATE TRIGGER `ai_test2_test1` AFTER INSERT ON `test2`
FOR EACH ROW
BEGIN INSERT INTO test1 (vtest1) VALUES (new.vtest2)
END$$
DELIMITER ;

Thanks.

Edit:

The infinite loop can't be resolved. Triggers can't be bidirectional... I think that i must be use a PROCEDURE...


问:
service not working between two controllers getting undefined
I am showing employee record using AngularJS. I am using two  views to show data, I am using two views emp-box.htm and its respective controller(empController) and in this controller employeeBoxController I am fetching data from service, I want the result which is obtained in employeeBoxController to be used in empController and show in view (emp-list.htm), I created a service eService

```<code>app.service('dataService',function() {

  var s = {};

  this.setData = function(data,key) {
    s[key]=data;
  },
  this.getData = function(key) {
    return s[key];
  }
  this.hello = function() {
    return 'hello';
  }
})
</code>```

for fetching result and setting data in employeeBoxController and getting in empController but when I fetch the data using console.log(dataService.getData('result')); in empController i get undefined

The employeeBoxController is

```<code>app.controller("employeeBoxController", ['$scope', 'employeeService',
  'dataService', function($scope, employeeService, dataService) {
  $scope.getEmployeeDetails = function(eid) {
    $scope.isLoading = false;
    employeeService.getDetails($scope.eid).then(function(result) {
      dataService.setData(result, 'result');
      $scope.isLoading = true;
      console.log(dataService.getData('result'));
    })
  }
}])
</code>```

The empController is :-

```<code>app.controller("empController", ['$scope', 'employeeService', 'dataService',
  function($scope, employeeService, dataService) {

    $scope.result = dataService.getData('result');
    //console.log(dataService.hello());

    console.log(dataService.getData('result'));

    console.log(dataService.hello());
  }
])
</code>```

The service class  employeeService is :-

```<code>  app.config(["employeeServiceProvider",function(employeeServiceProvider){
      employeeServiceProvider.config('http://localhost:8080/pos');
  }]);

  app.provider("employeeService",function(){
    var myurl='';

    this.config=function(eurl){
      myurl=eurl;
    }

    this.$get=['$http','$log',function($http,$log){
      var employeeobj={};
      employeeobj.getDetails=function(eid){
        return $http.get(myurl+'/getEmployees/'+eid);
    }

  return employeeobj;
    }];
  });
</code>```

emp-box.htm is:-

```<code>    <div>
  Enter the id: <input type="text" ng-model="eid"/>
  <button ng-click="getEmployeeDetails()">show</button>
   </div>
   emp-list.htm is:-
       <div class="panel panel-primary">
       <div class="panel-body" style="text-align:center; margin:0 auto">
      <h3>Employee Data</h3>
      </div>
     </div>
      <div class="panel panel-primary">
        <div class="panel-body">
      <!--  <div ng-show="!isLoading" style="color:red">
      <span class="glyphicon glyphicon-time"></span>Loading...
      </div>-->
     <table class="table table-hover">
     <thead>
      <tr>
      <th>ID</th>
      <th>Name</th>
      <th>empno</th>
      <th>salary</th>
      </tr>
    </thead>
     <tbody>
      <tr ng-repeat="oemp in result.data">

      <td>{{oemp.eid}}</td>
      <td>{{oemp.name}}</td>
      <td>{{oemp.empno}}</td>
      <td>{{oemp.sal}}</td>
    </tr>
  </tbody>

    </table>
  </div>
  </div>
</code>```

答:
$http.get will return a promise.
To correctly set data to dataService:

```<code> employeeService.getDetails($scope.eid).then(function(result) {
      dataService.setData(result.data, 'result'); // note .data
      $scope.isLoading = true;
      console.log(dataService.getData('result'));
    })
</code>```

Storing the promise in your "cache" service is not the best option.

I expect getEmployeeDetails() function is going to route to empController, so if you still store $promise in your service as you stated, you can do.

```<code>    dataService.getData('result').then(function(result){
        $scope.result = result.data;
  });
</code>```

When $scope.result is set to $scope,  ng-repeat will start iterating over.

With the first change suggested, you just don't need to touch empController but just the ng-repeat directive  emp-list.html with:

```<code><tr ng-repeat="oemp in result">
</code>```

Refactor the http call with factory recipe and $resource.
https://docs.angularjs.org/api/ngResource/service/$resource

That is easier and quicker than writing providers.

Body:
I am showing employee record using AngularJS. I am using two  views to show data, I am using two views emp-box.htm and its respective controller(empController) and in this controller employeeBoxController I am fetching data from service, I want the result which is obtained in employeeBoxController to be used in empController and show in view (emp-list.htm), I created a service eService

app.service('dataService',function() {

  var s = {};

  this.setData = function(data,key) {
    s[key]=data;
  },
  this.getData = function(key) {
    return s[key];
  }
  this.hello = function() {
    return 'hello';
  }
})

for fetching result and setting data in employeeBoxController and getting in empController but when I fetch the data using console.log(dataService.getData('result')); in empController i get undefined

The employeeBoxController is

app.controller("employeeBoxController", ['$scope', 'employeeService',
  'dataService', function($scope, employeeService, dataService) {
  $scope.getEmployeeDetails = function(eid) {
    $scope.isLoading = false;
    employeeService.getDetails($scope.eid).then(function(result) {
      dataService.setData(result, 'result');
      $scope.isLoading = true;
      console.log(dataService.getData('result'));
    })
  }
}])

The empController is :-

app.controller("empController", ['$scope', 'employeeService', 'dataService',
  function($scope, employeeService, dataService) {

    $scope.result = dataService.getData('result');
    //console.log(dataService.hello());

    console.log(dataService.getData('result'));

    console.log(dataService.hello());
  }
])

The service class  employeeService is :-

  app.config(["employeeServiceProvider",function(employeeServiceProvider){
      employeeServiceProvider.config('http://localhost:8080/pos');
  }]);

  app.provider("employeeService",function(){
    var myurl='';

    this.config=function(eurl){
      myurl=eurl;
    }

    this.$get=['$http','$log',function($http,$log){
      var employeeobj={};
      employeeobj.getDetails=function(eid){
        return $http.get(myurl+'/getEmployees/'+eid);
    }

  return employeeobj;
    }];
  });

emp-box.htm is:-

  Enter the id: <input type="text" ng-model="eid"/>
  <button ng-click="getEmployeeDetails()">show</button>

   emp-list.htm is:-

Employee Data

      ID
      Name
      empno
      salary

      {{oemp.eid}}
      {{oemp.name}}
      {{oemp.empno}}
      {{oemp.sal}}

Body:
$http.get will return a promise.
To correctly set data to dataService:

 employeeService.getDetails($scope.eid).then(function(result) {
      dataService.setData(result.data, 'result'); // note .data
      $scope.isLoading = true;
      console.log(dataService.getData('result'));
    })

Storing the promise in your "cache" service is not the best option.

I expect getEmployeeDetails() function is going to route to empController, so if you still store $promise in your service as you stated, you can do.

    dataService.getData('result').then(function(result){
        $scope.result = result.data;
  });

When $scope.result is set to $scope,  ng-repeat will start iterating over.

With the first change suggested, you just don't need to touch empController but just the ng-repeat directive  emp-list.html with:

<tr ng-repeat="oemp in result">

Refactor the http call with factory recipe and $resource.
https://docs.angularjs.org/api/ngResource/service/$resource

That is easier and quicker than writing providers.


问:
Loss function for class imbalanced binary classifier in Tensor flow
I am trying to apply deep learning for a binary classification problem with high class imbalance between target classes (500k, 31K). I want to write a custom loss function which should be like:
minimize(100-((predicted_smallerclass)/(total_smallerclass))*100)

Appreciate any pointers on how I can build this logic.

答:
You can check the guides at tensorflow https://www.tensorflow.org/api_guides/python/contrib.losses

...

While specifying a scalar loss rescales the loss over the entire batch, we sometimes want to rescale the loss per batch sample. For example, if we have certain examples that matter more to us to get correctly, we might want to have a higher loss that other samples whose mistakes matter less. In this case, we can provide a weight vector of length batch_size which results in the loss for each sample in the batch being scaled by the corresponding weight element. For example, consider the case of a classification problem where we want to maximize our accuracy but we especially interested in obtaining high accuracy for a specific class:

```<code>inputs, labels = LoadData(batch_size=3)
logits = MyModelPredictions(inputs)

# Ensures that the loss for examples whose ground truth class is `3` is 5x
# higher than the loss for all other examples.
weight = tf.multiply(4, tf.cast(tf.equal(labels, 3), tf.float32)) + 1

onehot_labels = tf.one_hot(labels, num_classes=5)
tf.contrib.losses.softmax_cross_entropy(logits, onehot_labels, weight=weight)
</code>```

Body:
You can check the guides at tensorflow https://www.tensorflow.org/api_guides/python/contrib.losses

...

While specifying a scalar loss rescales the loss over the entire batch, we sometimes want to rescale the loss per batch sample. For example, if we have certain examples that matter more to us to get correctly, we might want to have a higher loss that other samples whose mistakes matter less. In this case, we can provide a weight vector of length batch_size which results in the loss for each sample in the batch being scaled by the corresponding weight element. For example, consider the case of a classification problem where we want to maximize our accuracy but we especially interested in obtaining high accuracy for a specific class:

inputs, labels = LoadData(batch_size=3)
logits = MyModelPredictions(inputs)

# Ensures that the loss for examples whose ground truth class is `3` is 5x
# higher than the loss for all other examples.
weight = tf.multiply(4, tf.cast(tf.equal(labels, 3), tf.float32)) + 1

onehot_labels = tf.one_hot(labels, num_classes=5)
tf.contrib.losses.softmax_cross_entropy(logits, onehot_labels, weight=weight)


问:
How can you use multiple input streams for input parameters?
I want to run a command line script that requires several parameters.  Specifically:

perl prinseq-lite.pl -fastq file1.fq.gz -fastq2 file2.fq.gz

\ -out_good goodfile.out -out_bad badfile.out -log prin.log

\ -ns_max_n 5 ... more_params ...

The problem is that the files are zipped, and must be processed without first unzipping and storing them, because the unzipped file sizes are very large and this command will be run on a large number of files.

So what I need to do is to unzip the input on the fly.  Previously, user l0b0, suggested that multiple input streams might be a solution.  I have tried the following, but seem to be passing an empty input stream here as the program claims the input files are empty.

perl prinseq-lite.pl -fastq <(zcat f1.gz) -fastq2 <(zcat f2.gz) ...

perl prinseq-lite.pl -fastq 1< <(zcat f1.gz) -fastq2 2< <(zcat f2.gz) ...

So what I need to do, in short, is provide unzipped input for multiple parameters to this program.

Can someone tell me the proper way to do this, and/or what I'm doing wrong with my current attempts?  Thanks in advance for your input.

答:
Well, I think the easiest might be to make named pipes for the output of gzunip, then use those names pipes in the command:

```<code>mkfifo file1.fq file2.fq file3.fq ...
gunzip -c file1.fq.gz > file1.fq &
gunzip -c file2.fq.gz > file2.fq &
gunzip -c file3.fq.gz > file3.fq &
</code>```

Then call your program with those pipes as file names:

```<code>perl prinseq-lite.pl -fastq file1.fq -fastq2 file2.fq -fastq3 file3.fq ...
</code>```

Body:
Well, I think the easiest might be to make named pipes for the output of gzunip, then use those names pipes in the command:

mkfifo file1.fq file2.fq file3.fq ...
gunzip -c file1.fq.gz > file1.fq &
gunzip -c file2.fq.gz > file2.fq &
gunzip -c file3.fq.gz > file3.fq &

Then call your program with those pipes as file names:

perl prinseq-lite.pl -fastq file1.fq -fastq2 file2.fq -fastq3 file3.fq ...


问:
How to render custom label colors for different xAxis labels?
I'm creating a chart using Charts library to draw a combined chart in  my app.

I succeeded in drawing the graph. Now I want to change the xAxis label text color of specific labels. The example was shown in the pic.

As in the picture I want to change the color of specific values for example 03/06 & 06/06. When I referred the library on github they told me to override the drawValues() function to achieve this. As I'm newbie to swift programming I don't know how to achieve this. Please guide me on how to achieve this task. Thanks in advance.

答:
Inside the XAxisRenderer.swift (not the XAxisRendererHorizontalBarChart like the other answer suggested) add this list with your colors above the drawLabels function:

```<code> let labelTextColorList = [UIColor.black, UIColor.red, UIColor.blue, UIColor.brown, UIColor.cyan, UIColor.black, UIColor.black, UIColor.black, UIColor.black, UIColor.black, UIColor.black, UIColor.black]
</code>```

then replace the drawLabels function with this code:

```<code> /// draws the x-labels on the specified y-position
open func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
{
    guard
        let xAxis = self.axis as? XAxis,
        let viewPortHandler = self.viewPortHandler,
        let transformer = self.transformer
        else { return }

    #if os(OSX)
        let paraStyle = NSParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
    #else
        let paraStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
    #endif
    paraStyle.alignment = .center

    //label attrs moved from here
    /*            let labelAttrs = [NSFontAttributeName: xAxis.labelFont,
     NSForegroundColorAttributeName: xAxis.labelTextColor,
     NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]
     */

    let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD

    let centeringEnabled = xAxis.isCenterAxisLabelsEnabled

    let valueToPixelMatrix = transformer.valueToPixelMatrix

    var position = CGPoint(x: 0.0, y: 0.0)

    var labelMaxSize = CGSize()

    if xAxis.isWordWrapEnabled
    {
        labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
    }

    let entries = xAxis.entries

    for i in stride(from: 0, to: entries.count, by: 1)
    {

        //label attrs moved to here
        let labelAttrs: [String: NSObject]!

        if(i<labelTextColorList.count) {
            labelAttrs = [NSFontAttributeName: xAxis.labelFont,
                                  NSForegroundColorAttributeName: labelTextColorList[i],
                                  NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]
        }
        else {
            labelAttrs = [NSFontAttributeName: xAxis.labelFont,
                          NSForegroundColorAttributeName: xAxis.labelTextColor,
                          NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]

        }
        if centeringEnabled
        {
            position.x = CGFloat(xAxis.centeredEntries[i])
        }
        else
        {
            position.x = CGFloat(entries[i])
        }

        position.y = 0.0
        position = position.applying(valueToPixelMatrix)

        if viewPortHandler.isInBoundsX(position.x)
        {
            let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis) ?? ""

            let labelns = label as NSString

            if xAxis.isAvoidFirstLastClippingEnabled
            {
                // avoid clipping of the last
                if i == xAxis.entryCount - 1 && xAxis.entryCount > 1
                {
                    let width = labelns.boundingRect(with: labelMaxSize, options: .usesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width

                    if width > viewPortHandler.offsetRight * 2.0
                        && position.x + width > viewPortHandler.chartWidth
                    {
                        position.x -= width / 2.0
                    }
                }
                else if i == 0
                { // avoid clipping of the first
                    let width = labelns.boundingRect(with: labelMaxSize, options: .usesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
                    position.x += width / 2.0
                }
            }

            drawLabel(context: context,
                      formattedLabel: label,
                      x: position.x,
                      y: pos,
                      attributes: labelAttrs,
                      constrainedToSize: labelMaxSize,
                      anchor: anchor,
                      angleRadians: labelRotationAngleRadians)
        }
    }
}
</code>```

result:

Body:
Inside the XAxisRenderer.swift (not the XAxisRendererHorizontalBarChart like the other answer suggested) add this list with your colors above the drawLabels function:

 let labelTextColorList = [UIColor.black, UIColor.red, UIColor.blue, UIColor.brown, UIColor.cyan, UIColor.black, UIColor.black, UIColor.black, UIColor.black, UIColor.black, UIColor.black, UIColor.black]

then replace the drawLabels function with this code:

 /// draws the x-labels on the specified y-position
open func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
{
    guard
        let xAxis = self.axis as? XAxis,
        let viewPortHandler = self.viewPortHandler,
        let transformer = self.transformer
        else { return }

    #if os(OSX)
        let paraStyle = NSParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
    #else
        let paraStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
    #endif
    paraStyle.alignment = .center

    //label attrs moved from here
    /*            let labelAttrs = [NSFontAttributeName: xAxis.labelFont,
     NSForegroundColorAttributeName: xAxis.labelTextColor,
     NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]
     */

    let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD

    let centeringEnabled = xAxis.isCenterAxisLabelsEnabled

    let valueToPixelMatrix = transformer.valueToPixelMatrix

    var position = CGPoint(x: 0.0, y: 0.0)

    var labelMaxSize = CGSize()

    if xAxis.isWordWrapEnabled
    {
        labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
    }

    let entries = xAxis.entries

    for i in stride(from: 0, to: entries.count, by: 1)
    {

        //label attrs moved to here
        let labelAttrs: [String: NSObject]!

        if(i<labelTextColorList.count) {
            labelAttrs = [NSFontAttributeName: xAxis.labelFont,
                                  NSForegroundColorAttributeName: labelTextColorList[i],
                                  NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]
        }
        else {
            labelAttrs = [NSFontAttributeName: xAxis.labelFont,
                          NSForegroundColorAttributeName: xAxis.labelTextColor,
                          NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]

        }
        if centeringEnabled
        {
            position.x = CGFloat(xAxis.centeredEntries[i])
        }
        else
        {
            position.x = CGFloat(entries[i])
        }

        position.y = 0.0
        position = position.applying(valueToPixelMatrix)

        if viewPortHandler.isInBoundsX(position.x)
        {
            let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis) ?? ""

            let labelns = label as NSString

            if xAxis.isAvoidFirstLastClippingEnabled
            {
                // avoid clipping of the last
                if i == xAxis.entryCount - 1 && xAxis.entryCount > 1
                {
                    let width = labelns.boundingRect(with: labelMaxSize, options: .usesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width

                    if width > viewPortHandler.offsetRight * 2.0
                        && position.x + width > viewPortHandler.chartWidth
                    {
                        position.x -= width / 2.0
                    }
                }
                else if i == 0
                { // avoid clipping of the first
                    let width = labelns.boundingRect(with: labelMaxSize, options: .usesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
                    position.x += width / 2.0
                }
            }

            drawLabel(context: context,
                      formattedLabel: label,
                      x: position.x,
                      y: pos,
                      attributes: labelAttrs,
                      constrainedToSize: labelMaxSize,
                      anchor: anchor,
                      angleRadians: labelRotationAngleRadians)
        }
    }
}

result:


问:
Python: Image resizing: keep proportion - add white background
I would like to create a Python script to resize images, but not changing its proportions, just by adding a white background

(So, a : 500*700 px  image would transform to a 700*700 px image by adding 100 px of a white band on each side)

The three image types I use are .PNG, .JPG and .GIF. I am not even sure it is possible for Gifs, PNG and JPG would already be awesome.

In my case, they have to be squares. But if any of you manage to do it for adaptable to any proportion, it would benefit the maximum number of people that see this thread and you would be even more awesome !

I saw same threads for other languages but not python, do you guys know how you do this ?

PS : I am using Python 3

What I tried :

Combining 3 images together.

If we take our 500*700 px image :
Creating two white images of 100*700px and put one on each side of the image. Inspired by :

Combine several images horizontally with Python

But, I am kind of new on python, and I haven't succeded.

答:
Finally did it :

```<code>def Reformat_Image(ImageFilePath):

    from PIL import Image
    image = Image.open(ImageFilePath, 'r')
    image_size = image.size
    width = image_size[0]
    height = image_size[1]

    if(width != height):
        bigside = width if width > height else height

        background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255))
        offset = (int(round(((bigside - width) / 2), 0)), int(round(((bigside - height) / 2),0)))

        background.paste(image, offset)
        background.save('out.png')
        print("Image has been resized !")

    else:
        print("Image is already a square, it has not been resized !")
</code>```

Thanks to @Blotosmetek for the suggestion, pasting a centered image is definitely simpler than creating images and combining them !

PS : If you don't have PIL yet, the library's name to install it with pip is "pillow", not PIL. But still, you use it as PIL in the code.

Body:
Finally did it :

def Reformat_Image(ImageFilePath):

    from PIL import Image
    image = Image.open(ImageFilePath, 'r')
    image_size = image.size
    width = image_size[0]
    height = image_size[1]

    if(width != height):
        bigside = width if width > height else height

        background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255))
        offset = (int(round(((bigside - width) / 2), 0)), int(round(((bigside - height) / 2),0)))

        background.paste(image, offset)
        background.save('out.png')
        print("Image has been resized !")

    else:
        print("Image is already a square, it has not been resized !")

Thanks to @Blotosmetek for the suggestion, pasting a centered image is definitely simpler than creating images and combining them !

PS : If you don't have PIL yet, the library's name to install it with pip is "pillow", not PIL. But still, you use it as PIL in the code.


问:
H20 - R (Time is parsed incorrectly when importing from CSV)
I'm uploading a .csv file in R-H2o using h2o.importFile. However, the date values are parsed incorrectly.

For example, with date time format YYYY-MM-DD hh:mm:ss, (e.g. 2016-06-16 12:30:00), the result is always 1466073000000, which is incorrect.

答:
This is an odd combinations of data import artifacts:

This is an epoch time, which is in number of seconds from January 1, 1970.

If you use this code:

```<code>numDate <- 1466073000 #notice I removed three zeros
as.POSIXct(numDate, origin="1970-01-01")
</code>```

You get the following output:

```<code>"2016-06-16 06:30:00 EDT"
</code>```

So, it is in miliseconds.
Also, the time is incorrect, by 6 hours.

Chances are it is giving you Greenwich mean time adjustment for your systems time zone (which if you work in a corporate system could be different than your current time zone depending on where the actual processor is located and how your system is set up)

You have options:

Run the analysis on epoch time
or
Convert using:

as.POSIXct( 1466073000000/1000, origin="1970-01-01")

try to coerce h2o to bring it in the way you want.

As long as this time (with your zone adjustment) IS correct there is no reason to change it unless you need to be able to read it correctly. I would change the output after the analysis was run to make it human readable.

Body:
This is an odd combinations of data import artifacts:

This is an epoch time, which is in number of seconds from January 1, 1970.

If you use this code:

numDate <- 1466073000 #notice I removed three zeros
as.POSIXct(numDate, origin="1970-01-01")

You get the following output:

"2016-06-16 06:30:00 EDT"

So, it is in miliseconds.
Also, the time is incorrect, by 6 hours.

Chances are it is giving you Greenwich mean time adjustment for your systems time zone (which if you work in a corporate system could be different than your current time zone depending on where the actual processor is located and how your system is set up)

You have options:

Run the analysis on epoch time
or
Convert using:

as.POSIXct( 1466073000000/1000, origin="1970-01-01")

try to coerce h2o to bring it in the way you want.

As long as this time (with your zone adjustment) IS correct there is no reason to change it unless you need to be able to read it correctly. I would change the output after the analysis was run to make it human readable.


问:
Xgettext on php file in French issue with accented chars
I am using xgettext on a php file with source text in French, hence with accented chars.
Such chars are not correctly interpreted, and in the .po file produced: them all appear as little square.
As a result, these are not matched anymore by gettext (after producing the .mo file)
Any suggestion?
Thanks. </p>

答: Have you tried using --from-code=utf-8? xgettext defaults to ASCII encoding</p>


问:
Not getting output for simple java program to find greatest prime factor
```<code>class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}
</code>```

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

答:
int maximum value is 2147483647 which is smaller than 600851475143/2

when index i reaches max value it will wrap around and start with negative number (-2147483648)

you should make your index i a long value

Body:
class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?


问:
Redirect standard input (read-host) to a Powershell script
Here's a sample powershell script:

```<code>$in = read-host -prompt "input"
write-host $in
</code>```

Here's a sample 'test.txt' file:

```<code>hello
</code>```

And we want to pass piped input to it from powershell.  Here's some I have tried:

```<code>.\test.ps1 < test.txt
.\test.ps1 < .\test.txt
.\test.ps1 | test.txt
.\test.ps1 | .\test.txt
test.txt | .\test.ps1
.\test.txt | .\test.ps1
get-content .\test.txt | .\test.ps1
</code>```

even just trying to echo input doesn't work either:

```<code>echo hi | \.test.ps1
</code>```

Every example above that doesn't produce an error always prompts the user instead of accepting the piped input.

Note: My powershell version table says 4.0.-1.-1

Thanks

Edit/Result: To those looking for a solution, you cannot pipe input to a powershell script.  You have to update your PS file.  See the snippets below.

答:
The issue is that your script \.test.ps1 is not expecting the value.

Try this:

```<code>param(
    [parameter(ValueFromPipeline)]$string
)

# Edit: added if statement
if($string){
    $in = "$string"
}else{
    $in = read-host -prompt "input"
}

Write-Host $in
</code>```

Alternatively, you can use the magic variable $input without a param part (I don't fully understand this so can't really recommend it):

```<code>Write-Host $input
</code>```

Body:
Here's a sample powershell script:

$in = read-host -prompt "input"
write-host $in

Here's a sample 'test.txt' file:

hello

And we want to pass piped input to it from powershell.  Here's some I have tried:

.\test.ps1 < test.txt
.\test.ps1 < .\test.txt
.\test.ps1 | test.txt
.\test.ps1 | .\test.txt
test.txt | .\test.ps1
.\test.txt | .\test.ps1
get-content .\test.txt | .\test.ps1

even just trying to echo input doesn't work either:

echo hi | \.test.ps1

Every example above that doesn't produce an error always prompts the user instead of accepting the piped input.

Note: My powershell version table says 4.0.-1.-1

Thanks

Edit/Result: To those looking for a solution, you cannot pipe input to a powershell script.  You have to update your PS file.  See the snippets below.

Body:
The issue is that your script \.test.ps1 is not expecting the value.

Try this:

param(
    [parameter(ValueFromPipeline)]$string
)

# Edit: added if statement
if($string){
    $in = "$string"
}else{
    $in = read-host -prompt "input"
}

Write-Host $in

Alternatively, you can use the magic variable $input without a param part (I don't fully understand this so can't really recommend it):

Write-Host $input


问:
What is the best way to cast from ArrayList to List in .Net 2.0
I have a ArrayList of type BookingData to List<BookingData> ?

I am using .net 2.0 so i cannot use arrayList.Cast<int>().ToList() , and I dont want to make here foreach loop , do you have better ideas ?

Thanks.

答:
You have to use foreach:

```<code>        foreach (Object item in list1)
        {
            list2.Add((BookingData)item);
        }
</code>```

Body:
You have to use foreach:

        foreach (Object item in list1)
        {
            list2.Add((BookingData)item);
        }


问:
Angular - How to sort by last name pipe
For my Angular project, I want to display the EmpID values in a combo box and have them sorted by the last name.

Here's an html snippet where I'm trying to implement the pipe.

    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{emp.EmpID | orderByLast}}</option>
    </select>
```

<p>and here's  my orderByLast.pipe.ts :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
    transform(array: Array<string>): Array<string> {
        array.sort((a: any, b: any) => {
            if (a < b) {
                return -1;
            }
            else if (a > b) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return array;
    }
}</code>```

and here's my emp-info.ts array:

export class EmpInfo {
    EmpKey: number;
    EmpID: string;
    Firstname: string;
    LastName: string;
    EmpStat: string;
    StartDate: Date;
    AdjustedStart: Date;
    Anniversary: number;
    PTOYear: number;
    STDLTD: number;
    Uncharged: number;
    ETOEarned: number;
    ETORequests: number;
    ETORemaining: number;
    PTOBase: number;
    PTOCarry: number;
    PTOBorrowed: number;
    PTOBalance: number;
    PTORequests: number;
    PTORemaining: number;
}```

答:
See this example. I implemented this orderBy pipe few months ago in my own app.
https://stackoverflow.com/a/39650432/5556177

Title: Angular - How to sort by last name pipe

Body:
For my Angular project, I want to display the EmpID values in a combo box and have them sorted by the last name.

Here's an html snippet where I'm trying to implement the pipe.

    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{emp.EmpID | orderByLast}}</option>
    </select>

and here's  my orderByLast.pipe.ts :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
    transform(array: Array<string>): Array<string> {
        array.sort((a: any, b: any) => {
            if (a  b) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return array;
    }
}

and here's my emp-info.ts array:

export class EmpInfo {
    EmpKey: number;
    EmpID: string;
    Firstname: string;
    LastName: string;
    EmpStat: string;
    StartDate: Date;
    AdjustedStart: Date;
    Anniversary: number;
    PTOYear: number;
    STDLTD: number;
    Uncharged: number;
    ETOEarned: number;
    ETORequests: number;
    ETORemaining: number;
    PTOBase: number;
    PTOCarry: number;
    PTOBorrowed: number;
    PTOBalance: number;
    PTORequests: number;
    PTORemaining: number;
}


问:
NaN when trying to retrieve date from a SharePoint list using JavaScript
I've found partial solutions but retrieving the date from a SharePoint list adds one more level of fun. The code I've got which is returning NaN is:

```<code>var LifeCycleStart = new Date(item.DeviceAvailableFrom);
</code>```

Obviously the SharePoint column is DeviceAvailableFrom.

答: I'm not familiar with Sharepoint, but I'd first check that the value of item.DeviceAvailableFrom is either a positive integer, or a string containing a date that Date's constructor is able to parse.

Body:
I've found partial solutions but retrieving the date from a SharePoint list adds one more level of fun. The code I've got which is returning NaN is:

var LifeCycleStart = new Date(item.DeviceAvailableFrom);

Obviously the SharePoint column is DeviceAvailableFrom.


问:
pyocr with tesseract runs out of memory
I made a script to batch-process pdf scans into text with the help of tesseract and pyocr. The code is below. Problem is, when processing lots of files, like 20+, at some moment the script just runs out of memory and fails with OSError. I currently made it so that it can catch up smoothly at where it crashed after manual restart, but these manual restarts are tedious.

Since pyocr is basically a black box to me, I tried wrapping the script into other Python scripts that would restart it on crash, but they all seem to go down on that error, only freeing the memory when every related script terminates.

The only other solution I can think of, is to make a completely external wrapper, that would check if the script is running and restart it if not AND there are still unprocessed files.

But maybe there is a better solution? Or maybe I made lame code that can be improved to avoid these memory crashes? (Other then that I know it is lame, but works good enough :) ).

```<code>from io import BytesIO
from wand.image import Image
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import os
import os.path
import ast

def daemon_ocr(tool, img, lang):
    txt = tool.image_to_string(
        PI.open(BytesIO(img)),
        lang=lang,
        builder=pyocr.builders.TextBuilder()
    )
    return txt

def daemon_wrap(image_pdf, tool, lang, iteration):
    print(iteration)
    req_image = []
    final_text = ''
    image_pdf_bckp = image_pdf
    image_jpeg = image_pdf.convert('jpeg')

    for img in image_jpeg.sequence:
        img_page = Image(image=img)
        req_image.append(img_page.make_blob('jpeg'))

    for img in req_image:
        txt = daemon_ocr(tool, img, lang)
        final_text += txt + '\n '
    if 'работ' not in final_text and 'фактура' not in final_text and 'Аренда' not in final_text and 'Сумма' not in final_text\
            and 'аренде' not in final_text and 'товара' not in final_text:
        if iteration < 5:
            iteration += 1
            image_pdf = image_pdf.rotate(90)
            final_text = daemon_wrap(image_pdf_bckp, tool, lang, iteration)
    return final_text

def daemon_pyocr(food):
    tool = pyocr.get_available_tools()[0]
    lang = tool.get_available_languages()[0]
    iteration = 1
    image_pdf = Image(filename='{doc_name}'.format(doc_name=food), resolution=300)
    final_text = daemon_wrap(image_pdf, tool, lang, iteration)
    return final_text

files = [f for f in os.listdir('.') if os.path.isfile(f)]
output = {}
print(files)
path = os.path.dirname(os.path.abspath(__file__))
if os.path.exists('{p}/output'.format(p=path)):
    text_file = open("output", "a")
    first = False
else:
    text_file = open("output", "w")
    first = True

for f in files:
    if f != 'ocr.py' and f != 'output':
        try:
            output[f] = daemon_pyocr(f)
            print('{f} done'.format(f=f))
            if first:
                text_file.write(str(output)[1:-1])
                first = False
            else:
                text_file.write(', {d}'.format(d=str(output)[1:-1]))
            output = {}
            os.rename('{p}/{f}'.format(p=path, f=f), "{p}/done/{f}".format(p=path, f=f))
        except OSError:
            print('{f} failed: not enough memory.'.format(f=f))
</code>```

答:
I was also having the same issue, finally sorted it out.
The real problem is not with pyocr, but with sequence of wand.image.Image.

You can use the destroy() method of Image object to free memory. Always use with statement while dealing with wand.

There are already questions on this topic here and here

Here is the my code, which converts a pdf to image blob, if it helps you

```<code>def convert_pdf_to_image_blob(pdf):
    req_image = []
    with WI(filename=pdf, resolution=150) as image_jpeg:
        image_jpeg.compression_quality = 99
        image_jpeg = image_jpeg.convert('jpeg')

        for img in image_jpeg.sequence:
            with WI(image=img) as img_page:
                req_image.append(img_page.make_blob('jpeg'))
    image_jpeg.destroy()  # frees memory used by Image object.
    return req_image
</code>```

Thanks

Title: pyocr with tesseract runs out of memory

Body:
I made a script to batch-process pdf scans into text with the help of tesseract and pyocr. The code is below. Problem is, when processing lots of files, like 20+, at some moment the script just runs out of memory and fails with OSError. I currently made it so that it can catch up smoothly at where it crashed after manual restart, but these manual restarts are tedious.

Since pyocr is basically a black box to me, I tried wrapping the script into other Python scripts that would restart it on crash, but they all seem to go down on that error, only freeing the memory when every related script terminates.

The only other solution I can think of, is to make a completely external wrapper, that would check if the script is running and restart it if not AND there are still unprocessed files.

But maybe there is a better solution? Or maybe I made lame code that can be improved to avoid these memory crashes? (Other then that I know it is lame, but works good enough :) ).

from io import BytesIO
from wand.image import Image
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import os
import os.path
import ast

def daemon_ocr(tool, img, lang):
    txt = tool.image_to_string(
        PI.open(BytesIO(img)),
        lang=lang,
        builder=pyocr.builders.TextBuilder()
    )
    return txt

def daemon_wrap(image_pdf, tool, lang, iteration):
    print(iteration)
    req_image = []
    final_text = ''
    image_pdf_bckp = image_pdf
    image_jpeg = image_pdf.convert('jpeg')

    for img in image_jpeg.sequence:
        img_page = Image(image=img)
        req_image.append(img_page.make_blob('jpeg'))

    for img in req_image:
        txt = daemon_ocr(tool, img, lang)
        final_text += txt + '\n '
    if 'работ' not in final_text and 'фактура' not in final_text and 'Аренда' not in final_text and 'Сумма' not in final_text\
            and 'аренде' not in final_text and 'товара' not in final_text:
        if iteration < 5:
            iteration += 1
            image_pdf = image_pdf.rotate(90)
            final_text = daemon_wrap(image_pdf_bckp, tool, lang, iteration)
    return final_text

def daemon_pyocr(food):
    tool = pyocr.get_available_tools()[0]
    lang = tool.get_available_languages()[0]
    iteration = 1
    image_pdf = Image(filename='{doc_name}'.format(doc_name=food), resolution=300)
    final_text = daemon_wrap(image_pdf, tool, lang, iteration)
    return final_text

files = [f for f in os.listdir('.') if os.path.isfile(f)]
output = {}
print(files)
path = os.path.dirname(os.path.abspath(__file__))
if os.path.exists('{p}/output'.format(p=path)):
    text_file = open("output", "a")
    first = False
else:
    text_file = open("output", "w")
    first = True

for f in files:
    if f != 'ocr.py' and f != 'output':
        try:
            output[f] = daemon_pyocr(f)
            print('{f} done'.format(f=f))
            if first:
                text_file.write(str(output)[1:-1])
                first = False
            else:
                text_file.write(', {d}'.format(d=str(output)[1:-1]))
            output = {}
            os.rename('{p}/{f}'.format(p=path, f=f), "{p}/done/{f}".format(p=path, f=f))
        except OSError:
            print('{f} failed: not enough memory.'.format(f=f))

Body:
I was also having the same issue, finally sorted it out.
The real problem is not with pyocr, but with sequence of wand.image.Image.

You can use the destroy() method of Image object to free memory. Always use with statement while dealing with wand.

There are already questions on this topic here and here

Here is the my code, which converts a pdf to image blob, if it helps you

def convert_pdf_to_image_blob(pdf):
    req_image = []
    with WI(filename=pdf, resolution=150) as image_jpeg:
        image_jpeg.compression_quality = 99
        image_jpeg = image_jpeg.convert('jpeg')

        for img in image_jpeg.sequence:
            with WI(image=img) as img_page:
                req_image.append(img_page.make_blob('jpeg'))
    image_jpeg.destroy()  # frees memory used by Image object.
    return req_image

Thanks


问:
Select most recent increase in value column by ID
I am attempting a simple subset but am having a little trouble with simultaneously applying both of my conditions. I am looking to select, for each unique ID, the most recent record where the value column increased. For example, here is a simplified version of my data.

```<code>ID| Date | Value
A  1/1/17  100
A  1/2/17  185
A  1/3/17  40
A  1/4/17  100
A  1/5/17  30
B  1/3/17  40
B  1/4/17  30
B  1/5/17  65
B  1/6/17  80
B  1/7/17  0
B  1/8/17  0
</code>```

While my desired output would be the row where the last increase of Value took place for each ID

```<code>ID| Date | Value
A  1/4/17  100
A  1/6/17  80
</code>```

Does anybody have some insight on how I can achieve my desired output? Thanks.

答:
You can try this.</p>

```<code>select id,dt,value
from (select t1.*
      ,max(case when t2.value<t1.value then t1.dt end) over(partition by t1.id) as max_dt
      from (select t.*,min(dt) over(partition by id order by dt rows between 1 preceding and 1 preceding) as prev_dt
            from t
           ) t1
      join t t2 on t1.prev_dt=t2.dt and t1.id=t2.id
     ) t
where max_dt=dt
</code>```

Body:
I am attempting a simple subset but am having a little trouble with simultaneously applying both of my conditions. I am looking to select, for each unique ID, the most recent record where the value column increased. For example, here is a simplified version of my data.

ID| Date | Value
A  1/1/17  100
A  1/2/17  185
A  1/3/17  40
A  1/4/17  100
A  1/5/17  30
B  1/3/17  40
B  1/4/17  30
B  1/5/17  65
B  1/6/17  80
B  1/7/17  0
B  1/8/17  0

While my desired output would be the row where the last increase of Value took place for each ID

ID| Date | Value
A  1/4/17  100
A  1/6/17  80

Does anybody have some insight on how I can achieve my desired output? Thanks.

Body:
You can try this.

select id,dt,value
from (select t1.*
      ,max(case when t2.value<t1.value then t1.dt end) over(partition by t1.id) as max_dt
      from (select t.*,min(dt) over(partition by id order by dt rows between 1 preceding and 1 preceding) as prev_dt
            from t
           ) t1
      join t t2 on t1.prev_dt=t2.dt and t1.id=t2.id
     ) t
where max_dt=dt


问:
Replace special charachter '´' in C
I have a string to parse and it maybe contains the symbol "& acute;" depends on user data. So i want to eliminate this symbole and replace it with '.
Example :

Before --> Won´t Get Fooled Again
After  --> Won't Get Fooled Again

This is my try but it dosen't work in any way ..

```<code>int main()
{

  char* permenant="Won´t Get Fooled Again";
  char* s=permenant;
  for ( ; *s && *s != '&'; s++) ;
  printf("found '&' character \n"); // ---> OK
  printf("s=%s \n",s);              // ---> OK
  if (*(s+1) == 'a' && *(s+2) == 'c' && *(s+3) == 'u' && *(s+4) == 't'  && *(s+5) == 'e'  && *(s+6) == ';') // ---> OK
  {
     *s='\'';   //---> NO also if *s='a'; segmentation fault !!
     while(*(s+7)!='\0')
     {
          *(s+1)=*(s+7);
          s++;
          printf("the next character is -> %c \n", *(s+7));
     }// ---> Segmentation fault also if i remove *s='\''

   }
  printf("permenant=%s \n",permenant);

return 0;

}
</code>```

答:
Okay, your code has several issues which have been pointed out already.

To recap:

You can't modify a string expressed like that, you need a character array.

You should use strstr() to find sub-strings, not hand-written comparison chains.

You should use memmove() to compact the string when doing the replacement.

Here's my attempt:

```<code>void replaceShorten(char *s, const char *what, const char *withWhat)
{
  char *hit;
  const size_t wLen = strlen(what);
  const size_t wwLen = strlen(withWhat);
  if(wwLen >= wLen)
    return;
  while((hit = strstr(s, what)) != NULL)
  {
    memcpy(hit, withWhat, wwLen);
    memmove(hit + wwLen, hit + wLen, strlen(hit + wLen) + 1);
    s = hit + wwLen;
  }
}
</code>```

This is not optimized for maximum speed (it could use fewer calls to strlen()) but perhaps somewhat clear. It seems to work, when used like this:

```<code>char s[] = "Don´t do it!";
replaceShorten(s, "´", "'");
</code>```

Note that it must shorten the string when doing the replacement, as the name implies. Arbitrary replacement is not supported.

Title: Replace special charachter '´' in C

Body:
I have a string to parse and it maybe contains the symbol "& acute;" depends on user data. So i want to eliminate this symbole and replace it with '.
Example :

Before --> Won´t Get Fooled Again
After  --> Won't Get Fooled Again

This is my try but it dosen't work in any way ..

int main()
{

  char* permenant="Won´t Get Fooled Again";
  char* s=permenant;
  for ( ; *s && *s != '&'; s++) ;
  printf("found '&' character \n"); // ---> OK
  printf("s=%s \n",s);              // ---> OK
  if (*(s+1) == 'a' && *(s+2) == 'c' && *(s+3) == 'u' && *(s+4) == 't'  && *(s+5) == 'e'  && *(s+6) == ';') // ---> OK
  {
     *s='\'';   //---> NO also if *s='a'; segmentation fault !!
     while(*(s+7)!='\0')
     {
          *(s+1)=*(s+7);
          s++;
          printf("the next character is -> %c \n", *(s+7));
     }// ---> Segmentation fault also if i remove *s='\''

   }
  printf("permenant=%s \n",permenant);

return 0;

}

Body:
Okay, your code has several issues which have been pointed out already.

To recap:

You can't modify a string expressed like that, you need a character array.

You should use strstr() to find sub-strings, not hand-written comparison chains.

You should use memmove() to compact the string when doing the replacement.

Here's my attempt:

void replaceShorten(char *s, const char *what, const char *withWhat)
{
  char *hit;
  const size_t wLen = strlen(what);
  const size_t wwLen = strlen(withWhat);
  if(wwLen >= wLen)
    return;
  while((hit = strstr(s, what)) != NULL)
  {
    memcpy(hit, withWhat, wwLen);
    memmove(hit + wwLen, hit + wLen, strlen(hit + wLen) + 1);
    s = hit + wwLen;
  }
}

This is not optimized for maximum speed (it could use fewer calls to strlen()) but perhaps somewhat clear. It seems to work, when used like this:

char s[] = "Don&acute;t do it!";
replaceShorten(s, "&acute;", "'");

Note that it must shorten the string when doing the replacement, as the name implies. Arbitrary replacement is not supported.


问:
Required attribute with tag select doesn't work
I tried with required="true" and with th:required="required" and using only required(this throws an error since i am using thymeleaf), added the empty value value="",but still doesn't work.I tried added value="dumb" and value="" for the second option tag, same...doesn't work and tried using bootstrap validator.When I submit the form I have an pop-up, if I press OK then form is submitted.
I am using chrome and I have another form where I am using input + required and there it's working.
Any help will be appreciated. Thanks!

```<code><form th:action="@{/appointment/create}" method="post" id="appointmentForm">
<div class="form-group">
                <label for="location">Alege institutia:</label>

                <select class="form-control" required="required"
                th:value="${appointment.institutie}"name="institutie"
                id="institutie">

                 <option value="" disabled="disabled" selected="selected" >
                 -- alege institutia --</option>
                 <option th:each="institutie : ${institutieList}"
               th:text="${institutie.numeInstitutie}" ></option>

               </select>
</div></form>

            var confirm = function() {
            bootbox.confirm({
                title : "Confirmare programare",
                message : "Doriti sa creeati programarea?",
                buttons : {
                    cancel : {
                        label : '<i class="fa fa-times"></i> Nu'
                    },
                    confirm : {
                        label : '<i class="fa fa-check"></i> Da'
                    }
                },
                callback : function(result) {
                    if (result == true) {
                        $('#appointmentForm').submit();
                    } else {
                        console.log("Confirmare anulata.");
                    }
                }
            });
        };
</code>```

UPDATE
The controller which takes care to populate the "institutieList"

```<code>@RequestMapping(value="/create", method=RequestMethod.GET)
public String createAppointmentPost(Model model, @ModelAttribute("city")
City city, @ModelAttribute("agency") Agency agency, Principal principal){

    User user = userService.findByUsername(principal.getName());
    Appointment appointment=new Appointment();
    model.addAttribute("appointment", appointment);
    model.addAttribute("dateString", "");
    model.addAttribute("cities", cityService.findAll());
    model.addAttribute("institutieList", instituteService.findAll());
    model.addAttribute("myFiles", userService.listAllUploadedFiles(user));
    return "appointment";
}
</code>```

UPDATE 2:
The problem was with the submit button, I've forgot type="submit".

答:
The correct usage for required isn't required="true" but only required, like so:</p>

```<code><select class="form-control" required
            th:value="${appointment.institutie}"name="institutie"
            id="institutie">
</code>```

Body:
I tried with required="true" and with th:required="required" and using only required(this throws an error since i am using thymeleaf), added the empty value value="",but still doesn't work.I tried added value="dumb" and value="" for the second option tag, same...doesn't work and tried using bootstrap validator.When I submit the form I have an pop-up, if I press OK then form is submitted.
I am using chrome and I have another form where I am using input + required and there it's working.
Any help will be appreciated. Thanks!

<form th:action="@{/appointment/create}" method="post" id="appointmentForm">

                Alege institutia:

                <select class="form-control" required="required"
                th:value="${appointment.institutie}"name="institutie"
                id="institutie">

                 <option value="" disabled="disabled" selected="selected" >
                 -- alege institutia --</option>
                 <option th:each="institutie : ${institutieList}"
               th:text="${institutie.numeInstitutie}" ></option>

               </select>

</form>

            var confirm = function() {
            bootbox.confirm({
                title : "Confirmare programare",
                message : "Doriti sa creeati programarea?",
                buttons : {
                    cancel : {
                        label : ' Nu'
                    },
                    confirm : {
                        label : ' Da'
                    }
                },
                callback : function(result) {
                    if (result == true) {
                        $('#appointmentForm').submit();
                    } else {
                        console.log("Confirmare anulata.");
                    }
                }
            });
        };

UPDATE
The controller which takes care to populate the "institutieList"

@RequestMapping(value="/create", method=RequestMethod.GET)
public String createAppointmentPost(Model model, @ModelAttribute("city")
City city, @ModelAttribute("agency") Agency agency, Principal principal){

    User user = userService.findByUsername(principal.getName());
    Appointment appointment=new Appointment();
    model.addAttribute("appointment", appointment);
    model.addAttribute("dateString", "");
    model.addAttribute("cities", cityService.findAll());
    model.addAttribute("institutieList", instituteService.findAll());
    model.addAttribute("myFiles", userService.listAllUploadedFiles(user));
    return "appointment";
}

UPDATE 2:
The problem was with the submit button, I've forgot type="submit".

Body:
The correct usage for required isn't required="true" but only required, like so:

<select class="form-control" required
            th:value="${appointment.institutie}"name="institutie"
            id="institutie">


问:
Cython bytes to C char*
I am trying to write a Cython extension to CPython to wrap the mcrypt library, so that I can use it with Python 3.  However, I am running into a problem where I segfault while trying to use one of the mcrypt APIs.

The code that is failing is:

```<code>def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval
</code>```

Now, the way I understand the Cython documentation, the assignment on line 3 should copy the contents of the buffer (a  object in Python 3) to the C string pointer.  I would figure that this would also mean that it would allocate the memory, but when I made this modification:

```<code>def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = <char *>malloc(src_len)
    ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval
</code>```

it still crashed with a segfault.  It's crashing inside of mcrypt_generic, but when I use plain C code I am able to make it work just fine, so there has to be something that I am not quite understanding about how Cython is working with C data here.

Thanks for any help!

ETA:  The problem was a bug on my part.  I was working on this after being awake for far too many hours (isn't that something we've all done at some point?) and missed something stupid.  The code that I now have, which works, is:

```<code>def _real_encrypt(self, source):
    src_len = len(source)
    cdef char *ciphertext = <char *>malloc(src_len)
    cmc.strncpy(ciphertext, source, src_len)
    cmc.mcrypt_generic_init(self._mcStream, <void *>self._key,
                            len(self._key), NULL)
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext,
                       src_len)

    retval = ciphertext[:src_len]
    cmc.mcrypt_generic_deinit(self._mcStream)
    return retval
</code>```

It's probably not the most efficient code in the world, as it makes a copy to do the encryption and then a second copy to the return value.  I'm not sure if it is possible to avoid that, though, since I'm not sure if it is possible to take a newly-allocated buffer and return it to Python in-place as a bytestring.  But now that I have a working function, I'm going to implement a block-by-block method as well, so that one can provide an iterable of blocks for encryption or decryption, and be able to do it without having the entire source and destination all in memory all at once---that way, it'd be possible to encrypt/decrypt huge files without having to worry about holding up to three copies of it in memory at any one point...

Thanks for the help, everyone!

答: The first one is pointing the char* at the Python string. The second allocates memory, but then re-points the pointer to the Python string and ignores the newly allocated memory. You should be invoking the C library function strcpy from Cython, presumably; but I don't know the details.

Title: Cython bytes to C char*

Body:
I am trying to write a Cython extension to CPython to wrap the mcrypt library, so that I can use it with Python 3.  However, I am running into a problem where I segfault while trying to use one of the mcrypt APIs.

The code that is failing is:

def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval

Now, the way I understand the Cython documentation, the assignment on line 3 should copy the contents of the buffer (a  object in Python 3) to the C string pointer.  I would figure that this would also mean that it would allocate the memory, but when I made this modification:

def _real_encrypt(self, source):
    src_len = len(source)
    cdef char* ciphertext = <char *>malloc(src_len)
    ciphertext = source
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext, src_len)
    retval = source[:src_len]
    return retval

it still crashed with a segfault.  It's crashing inside of mcrypt_generic, but when I use plain C code I am able to make it work just fine, so there has to be something that I am not quite understanding about how Cython is working with C data here.

Thanks for any help!

ETA:  The problem was a bug on my part.  I was working on this after being awake for far too many hours (isn't that something we've all done at some point?) and missed something stupid.  The code that I now have, which works, is:

def _real_encrypt(self, source):
    src_len = len(source)
    cdef char *ciphertext = <char *>malloc(src_len)
    cmc.strncpy(ciphertext, source, src_len)
    cmc.mcrypt_generic_init(self._mcStream, <void *>self._key,
                            len(self._key), NULL)
    cmc.mcrypt_generic(self._mcStream, <void *>ciphertext,
                       src_len)

    retval = ciphertext[:src_len]
    cmc.mcrypt_generic_deinit(self._mcStream)
    return retval

It's probably not the most efficient code in the world, as it makes a copy to do the encryption and then a second copy to the return value.  I'm not sure if it is possible to avoid that, though, since I'm not sure if it is possible to take a newly-allocated buffer and return it to Python in-place as a bytestring.  But now that I have a working function, I'm going to implement a block-by-block method as well, so that one can provide an iterable of blocks for encryption or decryption, and be able to do it without having the entire source and destination all in memory all at once---that way, it'd be possible to encrypt/decrypt huge files without having to worry about holding up to three copies of it in memory at any one point...

Thanks for the help, everyone!


问:
SSH Key authorization for user
Scenario :
There are multiple users who need SSH into a server. What I'm following is

Create user1 , user2 in the server (Ubuntu 14.04 Server) running in AWS EC2.

Add each user public key (id_rsa.pub) into server /home/$USER/.ssh/authorized_keys file

Problem is I only can SSH to ubuntu (Default user)  with the private key of the user. But I can not SSH into user1 user.

Sample

```<code>[root@rubi-pc Downloads]# ssh -i ~/.ssh/id_rsa ruwan@DummyIP -v
OpenSSH_7.5p1, OpenSSL 1.1.0e  16 Feb 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to DummyIP [DummyIP] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.5
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8
debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to DummyIP:22 as 'ruwan'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:0kqNAt37ILO4cCP8ioiLN9j9x9badLOGL+etIvSYzfs
debug1: Host 'DummyIP' is known and matches the ECDSA host key.
debug1: Found key in /root/.ssh/known_hosts:2
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

Please do let me know if any details requeired .

答:
You have got the filename wrong. It is not

```<code>/home/$USER/.ssh/authorize_key
</code>```

but

```<code>/home/$USER/.ssh/authorized_keys
</code>```

Title: SSH Key authorization for user

Body:
Scenario :
There are multiple users who need SSH into a server. What I'm following is

Create user1 , user2 in the server (Ubuntu 14.04 Server) running in AWS EC2.

Add each user public key (id_rsa.pub) into server /home/$USER/.ssh/authorized_keys file

Problem is I only can SSH to ubuntu (Default user)  with the private key of the user. But I can not SSH into user1 user.

Sample

[root@rubi-pc Downloads]# ssh -i ~/.ssh/id_rsa ruwan@DummyIP -v
OpenSSH_7.5p1, OpenSSL 1.1.0e  16 Feb 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to DummyIP [DummyIP] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.5
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8
debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to DummyIP:22 as 'ruwan'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:0kqNAt37ILO4cCP8ioiLN9j9x9badLOGL+etIvSYzfs
debug1: Host 'DummyIP' is known and matches the ECDSA host key.
debug1: Found key in /root/.ssh/known_hosts:2
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

Please do let me know if any details requeired .

Body:
You have got the filename wrong. It is not

/home/$USER/.ssh/authorize_key

but

/home/$USER/.ssh/authorized_keys


问:
I upgraded Unity from 5.3 to 5.6 and now I get null reference exceptions
Ok the problem is that whenever I want to use the UI text I need to convert my int values to string, so I made a method that simply took the Text variable and gave it the value of the Int variable I had so it could be used by the UI text object.

It looks like this:

```<code>void setText(Text textVar, int valueVar)
{

    textVar.text = valueVar.ToString();

}
</code>```

pretty simple right? well.. im getting the error:

```<code>NullReferenceException: Object reference not set to an instance of an object
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.setText (UnityEngine.UI.Text textVar, Int32 valueVar) (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:1617)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.generateRandomStat (Int32 stat) (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:318)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.charCram () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:221)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.Start () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:1715)
</code>```

So it seems the problem is generated in the method where I create random values, although like I said this used to work well before, here is the code snippet for the stat generator:

```<code>    //method to generate a random stat from 3 to 18
    public void generateRandomStat(int stat)
    {
        int rng = Random.Range(3, 18);
        switch (stat)
        {
            case 0:
                strength = rng;
                setText(strengthText, strength);
                print(strength);
                break;
            case 1:
                dexterity = rng;
                setText(dexterityText, dexterity);
                print(dexterity);
                break;
            case 2:
                intelligence = rng;
                setText(intelligenceText, intelligence);
                print(intelligence);
                break;
            case 3:
                wisdom = rng;
                setText(wisdomText, wisdom);
                print(wisdom);
                break;
            case 4:
                constitution = rng;
                setText(constitutionText, constitution);
                print(constitution);
                break;
            case 5:
                charisma = rng;
                setText(charismaText, charisma);
                print(charisma);
                break;
            case 6:
                luck = rng;
                setText(luckText, luck);
                print(luck);
                break;
            case 7:
                willpower = rng;
                setText(willpowerText, willpower);
                print(willpower);
                break;

        }
    }
</code>```

The print() at the end of each case was used to first test in the console before using the UI elements, whenever I compile the game it doesnt even print the stats in the console.

Someone asked if I had assigned values to the Text variables, no I havent, all I did was initialize them as following:

```<code>public Text strengthText;
public Text dexterityText;
</code>```

And so on, do I need to make them = to something to avoid errors?

答:
Sometimes when upgrading your project, you lose references in your scene. In this case, it looks like you lost the Text reference that is connected to textVar variable. Simply re-drag the Text component from the Editor the textVar slot.

I usually do that from script so that updating will not cause any of these problems:

```<code>textVar = GameObject.Find("YourTextObject").GetComponent<Text>();
</code>```

EDIT:

With  your edited question, it's still the-same problem. Re-assign all your Text variables from the Editor such as strengthText, dexterityText, intelligenceText, wisdomText.... They lost their reference after updating. You can also do that in the Start function with the code above.

Body:
Ok the problem is that whenever I want to use the UI text I need to convert my int values to string, so I made a method that simply took the Text variable and gave it the value of the Int variable I had so it could be used by the UI text object.

It looks like this:

void setText(Text textVar, int valueVar)
{

    textVar.text = valueVar.ToString();

}

pretty simple right? well.. im getting the error:

NullReferenceException: Object reference not set to an instance of an object
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.setText (UnityEngine.UI.Text textVar, Int32 valueVar) (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:1617)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.generateRandomStat (Int32 stat) (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:318)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.charCram () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:221)
UnityStandardAssets.Characters.FirstPerson.FirstPersonController.Start () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:1715)

So it seems the problem is generated in the method where I create random values, although like I said this used to work well before, here is the code snippet for the stat generator:

    //method to generate a random stat from 3 to 18
    public void generateRandomStat(int stat)
    {
        int rng = Random.Range(3, 18);
        switch (stat)
        {
            case 0:
                strength = rng;
                setText(strengthText, strength);
                print(strength);
                break;
            case 1:
                dexterity = rng;
                setText(dexterityText, dexterity);
                print(dexterity);
                break;
            case 2:
                intelligence = rng;
                setText(intelligenceText, intelligence);
                print(intelligence);
                break;
            case 3:
                wisdom = rng;
                setText(wisdomText, wisdom);
                print(wisdom);
                break;
            case 4:
                constitution = rng;
                setText(constitutionText, constitution);
                print(constitution);
                break;
            case 5:
                charisma = rng;
                setText(charismaText, charisma);
                print(charisma);
                break;
            case 6:
                luck = rng;
                setText(luckText, luck);
                print(luck);
                break;
            case 7:
                willpower = rng;
                setText(willpowerText, willpower);
                print(willpower);
                break;

        }
    }

The print() at the end of each case was used to first test in the console before using the UI elements, whenever I compile the game it doesnt even print the stats in the console.

Someone asked if I had assigned values to the Text variables, no I havent, all I did was initialize them as following:

public Text strengthText;
public Text dexterityText;

And so on, do I need to make them = to something to avoid errors?

Body:
Sometimes when upgrading your project, you lose references in your scene. In this case, it looks like you lost the Text reference that is connected to textVar variable. Simply re-drag the Text component from the Editor the textVar slot.

I usually do that from script so that updating will not cause any of these problems:

textVar = GameObject.Find("YourTextObject").GetComponent<Text>();

EDIT:

With  your edited question, it's still the-same problem. Re-assign all your Text variables from the Editor such as strengthText, dexterityText, intelligenceText, wisdomText.... They lost their reference after updating. You can also do that in the Start function with the code above.


问:
How to manually slide to specific item in TTTabStrip (put selected to the center or make content offset)
So question is: How to manually slide to specific item in TTTabStrip (put selected to the center or make content offset)

```<code>@interface TTT : NSObject {
  TTTabStrip* _slider;
}
</code>```

```<code>@implementation TTT

_slider.selectedTabIndex = index;
</code>```

//This will select item in TTTabStrip view, and if item is out of screen, it wount be shown on _slider view display. What is need is to set content offset to the internal scroll view.

So main strategy is to offset selected item to the center of _slider view.

答:
Other way is take subviews from TTTabStrip and if it is UIScrollView then it is our object.</p>

```<code>@interface SomeClass : UIViewController <UIScrollViewDelegate> {
   TTTabStrip*    _slider;
   UIScrollView*  _sliderScrollView;
}

@property (nonatomic, retain) IBOutlet TTTabBar* slider;

@end

@implementation SomeClass
@synthesize slider = _slider;

.......

- (void) someMethod {
        for (UIView* internalView in self.slider.subviews) {
                if ([internalView isKindOfClass:[UIScrollView class]]) {
                        _sliderScrollView = [internalView retain];
                        _sliderScrollView.delegate = self;
                }
        }
}

@end
</code>```

Body:
So question is: How to manually slide to specific item in TTTabStrip (put selected to the center or make content offset)

@interface TTT : NSObject {
  TTTabStrip* _slider;
}

@implementation TTT

_slider.selectedTabIndex = index;

//This will select item in TTTabStrip view, and if item is out of screen, it wount be shown on _slider view display. What is need is to set content offset to the internal scroll view.

So main strategy is to offset selected item to the center of _slider view.

Body:
Other way is take subviews from TTTabStrip and if it is UIScrollView then it is our object.

@interface SomeClass : UIViewController <UIScrollViewDelegate> {
   TTTabStrip*    _slider;
   UIScrollView*  _sliderScrollView;
}

@property (nonatomic, retain) IBOutlet TTTabBar* slider;

@end

@implementation SomeClass
@synthesize slider = _slider;

.......

- (void) someMethod {
        for (UIView* internalView in self.slider.subviews) {
                if ([internalView isKindOfClass:[UIScrollView class]]) {
                        _sliderScrollView = [internalView retain];
                        _sliderScrollView.delegate = self;
                }
        }
}

@end


问:
WooCommerce - Change customer order after it has been placed and paid
Using three plugins:
WooCommerce
Subscriptio
WooEvents

I have created a product which allows for a customer to pay for an event over five instalments.

A customer has placed an order and made their first of the five payments via PayPal and has then contacted me to advise they have booked the wrong event.

The correct event is exactly the same except the dates are a month sooner.

I have added the following snippet to be able to edit 'processing' orders:

```<code>add_filter( 'wc_order_is_editable', 'wc_make_processing_orders_editable', 10, 2 );
function wc_make_processing_orders_editable( $is_editable, $order ) {
    if ( $order->get_status() == 'processing' ) {
        $is_editable = true;
    }

    return $is_editable;
}
</code>```

From the order screen within the back-end of WordPress I can see that the the order can be edit by way of removing the product from the order or editing the meta data and cost.

The correct product that should have been ordered has a different product/variation ID.

My question is simply:

Should I remove the incorrectly ordered product from the order and add the correct product (both have the same properties with the exception of the courses dates); or
Should I just change the meta data and increase the stock levels for the incorrectly product back to X and reduce the stock level for the correct product?

答: Your second option is much better. Change the meta from database if its accessible and then manage the stock accordingly. </p>

Body:
Using three plugins:
WooCommerce
Subscriptio
WooEvents

I have created a product which allows for a customer to pay for an event over five instalments.

A customer has placed an order and made their first of the five payments via PayPal and has then contacted me to advise they have booked the wrong event.

The correct event is exactly the same except the dates are a month sooner.

I have added the following snippet to be able to edit 'processing' orders:

add_filter( 'wc_order_is_editable', 'wc_make_processing_orders_editable', 10, 2 );
function wc_make_processing_orders_editable( $is_editable, $order ) {
    if ( $order->get_status() == 'processing' ) {
        $is_editable = true;
    }

    return $is_editable;
}

From the order screen within the back-end of WordPress I can see that the the order can be edit by way of removing the product from the order or editing the meta data and cost.

The correct product that should have been ordered has a different product/variation ID.

My question is simply:

Should I remove the incorrectly ordered product from the order and add the correct product (both have the same properties with the exception of the courses dates); or
Should I just change the meta data and increase the stock levels for the incorrectly product back to X and reduce the stock level for the correct product?


问:
Twilio <Gather> Speech Recognition support in twilio python package
Need some help in Twilio. Twilio Gather verb supports input="speech" which recognizes speech as mentioned in their site. Does the Twilio python package support this speech recognition yet? Couldn't find any help documentation regarding this.

答:
Twilio developer evangelist here.

It seems that the latest Python package only implemented partial support for input="speech" and the related TwiML attributes which makes it unusable at the moment.

I am raising a bug internally and will get this fixed as soon as possible. I will notify you here when it is ready.