问:
How do I write a "formula" in the Google Sheets filter widget?
I know I can do this with formulas, but I'd like to understand how to do it using the popup filter tool (since I'm constantly changing it).

This thing, for reference:

Ordinarily, I can get away with entering the string I want in the "Value or formula" window, like so...

The above works AS LONG AS the exact string I type matches a sub-string in the cell. However, every now and then I want to do something like this...

But that doesn't work.

I've tried all sorts of "formulas", like "foo" && "bar" or ="foo" + "bar"

But of course those don't work either... It doesn't seem to make sense to use the =filter(...) formula, as that requires a range that is already defined by the filter widget itself. I haven't had any luck with that either.

Can anyone give me an example of (or a link to) an AND search 'formula' I can type into that window that would actually include all of the following 'cells':

```<code>foo bar
foo banana bar
bar foo
this foo that bar
</code>```

And in case others find this question, it might be nice to see an OR search formula as well

答:
Custom Formula:

```<code>=REGEXMATCH(A1,"(?iU)(foo.*bar)|(bar.*foo)")
</code>```

Apply to A1:A5

Click here

Body:
I know I can do this with formulas, but I'd like to understand how to do it using the popup filter tool (since I'm constantly changing it).

This thing, for reference:

Ordinarily, I can get away with entering the string I want in the "Value or formula" window, like so...

The above works AS LONG AS the exact string I type matches a sub-string in the cell. However, every now and then I want to do something like this...

But that doesn't work.

I've tried all sorts of "formulas", like "foo" && "bar" or ="foo" + "bar"

But of course those don't work either... It doesn't seem to make sense to use the =filter(...) formula, as that requires a range that is already defined by the filter widget itself. I haven't had any luck with that either.

Can anyone give me an example of (or a link to) an AND search 'formula' I can type into that window that would actually include all of the following 'cells':

foo bar
foo banana bar
bar foo
this foo that bar

And in case others find this question, it might be nice to see an OR search formula as well

Body:
Custom Formula:

=REGEXMATCH(A1,"(?iU)(foo.*bar)|(bar.*foo)")

Apply to A1:A5

Click here


来源: stackexchange

问:
GET request is atomic but POST not in Sails.js DB Transaction
I noticed something in my Sails.js App which I can't explain:

The Client sends a GET request to the UserController, the UserController creates a new record in the TransactionTable for this User if its account is greater than 0 and updates its account to 0:

```<code>User.findOne(currentUser.id, function foundUser(err, foundUser) {
     if(foundUser.account > 0){
         //update the foundUsers account to 0
         User.update(foundUser.id, {account:0}, function updateUser(err, updatedUser) {
              //if error rollback;
             //save the User to the Transactions Table:
             Transactions.create(foundUser, function(){
                //if error rollback;
                return res.json("You will get Money!");

              })
         })
      }else{
         return res.json("Sorry you don't have enough Coins");
      }
})
</code>```

I did a loop(5repeats) on the Clientside for the GET request and it created only 1 Transaction and the other 4 got the log that foundUser.account is 0.
So the output was:

You will get Money!

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

I did the same loop with POST and it created 5 Transactions in the Table.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

So: Is GET atomic and POST not in a Sail.js Application? And is this way safe for production?

Edit:
GET request is idempotent - I tested the same loop with GET but this time I added a different value for each request for an argument and got 5 Transactions.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

How does this idempotent work? It has nothing to do with caching right? Because when it would just cache the response for the already known request like in the first GET example, the first example would also return 5 times the same response? But it actually "change" the resource on the server and delivers different responses. strange.

How can I fix this problem? So that in the time one transaction is written no other client can make a request?

答:
I really like sails, however in my googling, I always run across this article about it's shortcomings: https://kev.inburke.com/kevin/dont-use-sails-or-waterline/

Two things mentioned in the article may have relevance to your question:

No support for transactions - preventing race conditions in database updates, etc. You seem to want to hold off a more recent READ operation until a prior WRITE is complete - this is what transactions would provide (but sails waterline doesn't)

50ms delay on every POST request

I have never investigated the second problem, but maybe it means that post requests received within the same 50ms interval are gathered up and delivered all at once?

ContentLicense: CC BY-SA 3.0

Body:
I noticed something in my Sails.js App which I can't explain:

The Client sends a GET request to the UserController, the UserController creates a new record in the TransactionTable for this User if its account is greater than 0 and updates its account to 0:

User.findOne(currentUser.id, function foundUser(err, foundUser) {
     if(foundUser.account > 0){
         //update the foundUsers account to 0
         User.update(foundUser.id, {account:0}, function updateUser(err, updatedUser) {
              //if error rollback;
             //save the User to the Transactions Table:
             Transactions.create(foundUser, function(){
                //if error rollback;
                return res.json("You will get Money!");

              })
         })
      }else{
         return res.json("Sorry you don't have enough Coins");
      }
})

I did a loop(5repeats) on the Clientside for the GET request and it created only 1 Transaction and the other 4 got the log that foundUser.account is 0.
So the output was:

You will get Money!

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

I did the same loop with POST and it created 5 Transactions in the Table.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

So: Is GET atomic and POST not in a Sail.js Application? And is this way safe for production?

Edit:
GET request is idempotent - I tested the same loop with GET but this time I added a different value for each request for an argument and got 5 Transactions.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

How does this idempotent work? It has nothing to do with caching right? Because when it would just cache the response for the already known request like in the first GET example, the first example would also return 5 times the same response? But it actually "change" the resource on the server and delivers different responses. strange.

How can I fix this problem? So that in the time one transaction is written no other client can make a request?


问:
Simplest way to encrypt a text file in java
For my School project I had to show that I can utilize file handling within a program. For this I made a very simple login process that you can create an account on that writes a username and password to a text file located in the resource folder. Obviously this has no security at all as it wasn't designed to be secure just to showcase file handling however my teacher has said that I should attempt to add some encryption to the file as well to get a better grade.

I have done some research and many people are recommending DES.

The problem I'm having is I don't have much time left for my project and need to finish it asap. Using DES seems like it would take a while to implement all the extra code.

In my program I am using a simple lineNumberReader to read the files line by line. To write to the files I am using a BufferedWriter.

Is there anyway to encrypt this data very simply? It doesn't have to be very secure but I need to show that I have atleast attempted to encrypt the data. The encryption and decryption would all be completed on the same application as data isn't being transferred.

Potentially a way I can create a very simple encryption and decryption algorithm myself?

答:
```<code>public class CryptoUtils {

    public static void encrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
    }

    public static void decrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
    }

    private static void doCrypto(int cipherMode, String key, File inputFile,
            File outputFile) throws CryptoException {
        try {
            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);

            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);

            byte[] outputBytes = cipher.doFinal(inputBytes);

            FileOutputStream outputStream = new FileOutputStream(outputFile);
            outputStream.write(outputBytes);

            inputStream.close();
            outputStream.close();

        } catch (NoSuchPaddingException | NoSuchAlgorithmException
                | InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | IOException ex) {
            throw new CryptoException("Error encrypting/decrypting file", ex);
        }
    }
}
</code>```

<hr>

```<code>package net.codejava.crypto;

import java.io.File;

public class CryptoException extends Exception {

    public CryptoException() {
    }

    public CryptoException(String message, Throwable throwable) {
        super(message, throwable);
    }

    public static void main(String[] args) {
        String key = "Mary has one cat1";
        File inputFile = new File("document.txt");
        File encryptedFile = new File("document.encrypted");
        File decryptedFile = new File("document.decrypted");

        try {
            CryptoUtils.encrypt(key, inputFile, encryptedFile);
            CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
        } catch (CryptoException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}
</code>```

Body:
public class CryptoUtils {

    public static void encrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
    }

    public static void decrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
    }

    private static void doCrypto(int cipherMode, String key, File inputFile,
            File outputFile) throws CryptoException {
        try {
            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);

            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);

            byte[] outputBytes = cipher.doFinal(inputBytes);

            FileOutputStream outputStream = new FileOutputStream(outputFile);
            outputStream.write(outputBytes);

            inputStream.close();
            outputStream.close();

        } catch (NoSuchPaddingException | NoSuchAlgorithmException
                | InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | IOException ex) {
            throw new CryptoException("Error encrypting/decrypting file", ex);
        }
    }
}

package net.codejava.crypto;

import java.io.File;

public class CryptoException extends Exception {

    public CryptoException() {
    }

    public CryptoException(String message, Throwable throwable) {
        super(message, throwable);
    }

    public static void main(String[] args) {
        String key = "Mary has one cat1";
        File inputFile = new File("document.txt");
        File encryptedFile = new File("document.encrypted");
        File decryptedFile = new File("document.decrypted");

        try {
            CryptoUtils.encrypt(key, inputFile, encryptedFile);
            CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
        } catch (CryptoException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}


问:
Undefined Columns Selected (when using order function)
I have searched for answers to my question and can't seem to find any answer. I am trying to sort my data so that I can first sort by year of birth and then by last name. Here is my code:

```<code>ResidentsBD_99_2015_clean < ResidentsBD_99_2015_clean[order(ResidentsBD_99_2015_clean[, birthdate_year],
                                                            ResidentsBD_99_2015_clean[, "surname"],
                                                            decreasing = FALSE), ]
</code>```

When I run this code, this is the error message that I recieve:

```<code>Error in `[.data.frame`(ResidentsBD_99_2015_clean, , birthdate_year) :
  undefined columns selected
</code>```

答:
You might just be stuck with typos in your code. birthdate_year should be quoted. It also looks like you have a typo in the assign-operator (<-).

In a more general sense, I prefer ordering with dplyr.

```<code>library(dplyr)
ResidentsBD_99_2015_clean <- arrange(ResidentsBD_99_2015_clean, birthdate_year, surname)
</code>```

Body:
I have searched for answers to my question and can't seem to find any answer. I am trying to sort my data so that I can first sort by year of birth and then by last name. Here is my code:

ResidentsBD_99_2015_clean < ResidentsBD_99_2015_clean[order(ResidentsBD_99_2015_clean[, birthdate_year],
                                                            ResidentsBD_99_2015_clean[, "surname"],
                                                            decreasing = FALSE), ]

When I run this code, this is the error message that I recieve:

Error in `[.data.frame`(ResidentsBD_99_2015_clean, , birthdate_year) :
  undefined columns selected

Body:
You might just be stuck with typos in your code. birthdate_year should be quoted. It also looks like you have a typo in the assign-operator (<-).

In a more general sense, I prefer ordering with dplyr.

library(dplyr)
ResidentsBD_99_2015_clean <- arrange(ResidentsBD_99_2015_clean, birthdate_year, surname)


问:
Content type is not saved when altering the node add form
Here, I have alter the add content type form as follows:

```<code>function hc_listings_form_alter(&$form, &$form_state, $form_id)
{
//    print_r($form_id);
    if($form_id =='home_care_popular_search_region_node_form'){
        dpm($form,'form');
        $selected_states=hc_listings_load_agecare_regions();
//        dpm($selected_states,'selected');
        reset($selected_states);
        $first_state = key($selected_states);

//        dpm($first_state,'$first_state');

  $form['field_popular_state']=array(
        '#type' => 'select',
        '#default_value' => array_shift($selected_states),
        '#title' => t('Popular State'),
        '#description' => t('Home Care Popular State'),
        '#options'=>hc_listings_load_agecare_regions(),
        '#ajax'=>array(
            'callback'=> 'hc_popular_region_form_ajax',
            'wrapper'=> 'regions_list',
            'event'=>'change',
            'method'=>'replace',
        ),
        '#required' => TRUE,
  );
 $form['field_popular_region']=array(
     '#type' => 'container',
     '#tree'=>TRUE,
     '#prefix'=>'<div id="regions_list">',
     '#suffix'=>'</div>'

 );
 $form['field_popular_region']['list']=array(
    '#type' => 'checkboxes',
    '#title' => t('Popular Search Regions'),
    '#description' => t('Home Care Popular Search Regions'),
    '#options'=>get_popular_regions($first_state),
    '#required' => TRUE,

 );

  }
}
</code>```

And the ajax Callback function is as follows:

```<code>function hc_popular_region_form_ajax($form, &$form_state){

  if(isset($form_state['values']['field_popular_state'])){
    $state=$form_state['values']['field_popular_state'];
    hc_my_log($state);

    $form['field_popular_region']['list']=array(
      '#type'=>'checkboxes',
      '#title'=>'Popular Search Regions',
      '#description'=>'Home Care Popular Search Regions',
      '#options'=>get_popular_regions($state)
    );

    hc_my_log($form['field_popular_region']['list']);

    $form['field_popular_region']['list']=form_process_checkboxes($form['field_popular_region']['list']);

 }

//    $form_state['rebuild'] = true;
    return $form['field_popular_region'];

}
</code>```

This works but when the ajax callback is called it will execute the dpm($form,'form') (line:5) too. What is the reason for this?

And after that when I am submitting the form by clicking the default Save button in the node add form both popular regions and popular states values are not saved. What will be the cause of that? Should I have to alter the submission of the node too ?

答:
Here ,I have altered the form fields in a wrong way so in the form submission it alerts me with errors saying that the form structure has been changed in my altering.

The error is that it is not directly targetting the specific form field..so it should be corrected as follows:

```<code> if($form_id =='home_care_popular_search_regions_node_form'){

        $selected_states=hc_get_states();
        reset($selected_states);
        $first_state = key($selected_states);
        dpm($first_state,'$first_state');
        $state= (isset($form_state['values']['field_popular_state']['und'][0]['tid']))?$form_state['values']['field_popular_state']['und'][0]['tid']:$first_state;

        //popular states field altering
        $form['field_popular_state']['und']['#default_value']=$selected_states[$first_state];
        $form['field_popular_state']['und']['#options']=$selected_states;
        $form['field_popular_state']['und']['#ajax']['callback']='hc_popular_region_form_ajax';
        $form['field_popular_state']['und']['#ajax']['wrapper']='regions_list';
        $form['field_popular_state']['und']['#ajax']['method']='replace';
        $form['field_popular_state']['und']['#ajax']['event']='change';

        //popular regions field altering
        $form['field_popular_region']['und']['#prefix']='<div id="regions_list">';
        $form['field_popular_region']['und']['#suffix']='</div>';
        $form['field_popular_region']['und']['#options']=hc_get_popular_regions($state);
}
</code>```

Ajax callback is as follows:

```<code>function hc_popular_region_form_ajax($form, &$form_state){
  return $form['field_popular_region'];
}
</code>```

Note: the method hc_listings_load_agecare_regions() has been changed to hc_get_states()

Body:
Here, I have alter the add content type form as follows:

function hc_listings_form_alter(&$form, &$form_state, $form_id)
{
//    print_r($form_id);
    if($form_id =='home_care_popular_search_region_node_form'){
        dpm($form,'form');
        $selected_states=hc_listings_load_agecare_regions();
//        dpm($selected_states,'selected');
        reset($selected_states);
        $first_state = key($selected_states);

//        dpm($first_state,'$first_state');

  $form['field_popular_state']=array(
        '#type' => 'select',
        '#default_value' => array_shift($selected_states),
        '#title' => t('Popular State'),
        '#description' => t('Home Care Popular State'),
        '#options'=>hc_listings_load_agecare_regions(),
        '#ajax'=>array(
            'callback'=> 'hc_popular_region_form_ajax',
            'wrapper'=> 'regions_list',
            'event'=>'change',
            'method'=>'replace',
        ),
        '#required' => TRUE,
  );
 $form['field_popular_region']=array(
     '#type' => 'container',
     '#tree'=>TRUE,
     '#prefix'=>'
',
     '#suffix'=>'
'

 );
 $form['field_popular_region']['list']=array(
    '#type' => 'checkboxes',
    '#title' => t('Popular Search Regions'),
    '#description' => t('Home Care Popular Search Regions'),
    '#options'=>get_popular_regions($first_state),
    '#required' => TRUE,

 );

  }
}

And the ajax Callback function is as follows:

function hc_popular_region_form_ajax($form, &$form_state){

  if(isset($form_state['values']['field_popular_state'])){
    $state=$form_state['values']['field_popular_state'];
    hc_my_log($state);

    $form['field_popular_region']['list']=array(
      '#type'=>'checkboxes',
      '#title'=>'Popular Search Regions',
      '#description'=>'Home Care Popular Search Regions',
      '#options'=>get_popular_regions($state)
    );

    hc_my_log($form['field_popular_region']['list']);

    $form['field_popular_region']['list']=form_process_checkboxes($form['field_popular_region']['list']);

 }

//    $form_state['rebuild'] = true;
    return $form['field_popular_region'];

}

This works but when the ajax callback is called it will execute the dpm($form,'form') (line:5) too. What is the reason for this?

And after that when I am submitting the form by clicking the default Save button in the node add form both popular regions and popular states values are not saved. What will be the cause of that? Should I have to alter the submission of the node too ?

Body:
Here ,I have altered the form fields in a wrong way so in the form submission it alerts me with errors saying that the form structure has been changed in my altering.

The error is that it is not directly targetting the specific form field..so it should be corrected as follows:

 if($form_id =='home_care_popular_search_regions_node_form'){

        $selected_states=hc_get_states();
        reset($selected_states);
        $first_state = key($selected_states);
        dpm($first_state,'$first_state');
        $state= (isset($form_state['values']['field_popular_state']['und'][0]['tid']))?$form_state['values']['field_popular_state']['und'][0]['tid']:$first_state;

        //popular states field altering
        $form['field_popular_state']['und']['#default_value']=$selected_states[$first_state];
        $form['field_popular_state']['und']['#options']=$selected_states;
        $form['field_popular_state']['und']['#ajax']['callback']='hc_popular_region_form_ajax';
        $form['field_popular_state']['und']['#ajax']['wrapper']='regions_list';
        $form['field_popular_state']['und']['#ajax']['method']='replace';
        $form['field_popular_state']['und']['#ajax']['event']='change';

        //popular regions field altering
        $form['field_popular_region']['und']['#prefix']='<div id="regions_list">';
        $form['field_popular_region']['und']['#suffix']='</div>';
        $form['field_popular_region']['und']['#options']=hc_get_popular_regions($state);
}

Ajax callback is as follows:

function hc_popular_region_form_ajax($form, &$form_state){
  return $form['field_popular_region'];
}

Note: the method hc_listings_load_agecare_regions() has been changed to hc_get_states()


问:
Ngrx: current value not received in Subject upon subscription
In a component, I subscribe a Subject to some part of my state using the store. From then on, when that part of the state changes, I will start receiving updates and my component will reflect this state. So far so good.

However, I also want my component to initialize correctly based on the current value of this state. So as soon as I subscribe, I also want the current value to get emitted - so, e.g., my view can initialize correctly.

Example with an Angular component:

my.component.ts

```<code>export class MyComponent implements OnInit {
  constructor(private store: Store<State>) { }

  // As soon as I subscribe, I want this to also emit the current
  // value, e.g. so my view can correctly reflect the current state.
  public mode$ = new Subject<ApplicationMode>();

  ngOnInit() {
    this.store.select(getApplicationState)
       .select(s => s.applicationMode).subscribe(this.mode$);
  }
}
</code>```

my.component.html

```<code>{{ mode$ | async }}
</code>```

I believe that what I would like/expect is that this part of my store would return a BehaviorSubject or a ReplaySubject(1). But selecting anything from the store always returns a Store<T> which is obviously some sort of subject, but doesn't seem to emit the current value upon subscription?

What might work, I guess, is to subscribe to this piece of state on application initialization, and then pass that value on through all its child components, all the way down to this one, so this component turns into a dumb one instead of selecting from the store itself. Is that perhaps the way to go? Or is there something basic I'm missing to make this work?

答:
Ngrx does act like a BehaviorSubject where you get the current value when you first subscribe.

The issue is probably that you are pushing the value from a behavior subject (store) into a normal subject (mode$) before that subject is subscribed to. This would mean that you push the initial value into your subject (mode$) and it would have no subscriber to notify so it fizzles. When the subscriber subscribes to mode$ it is subscribing to a normal subject so it doesn't get the current value but it would get all future values.

What I would suggest is cutting out the middle-man and to expose the observable returned from the store directly to the view like so:

```<code>this.mode$ = this.store.select(...);
</code>```

This way you are exposing an observable that will provide the current value on subscribe to any subscribers.

I am finding it hard to find specific documentation on where in the component lifecycle that the async pipe subscribes. So I put together a test where I publish to a subject in every lifecycle hook and subscribe to it via the async pipe.

The code:

```<code>import {
  Component,
  OnChanges,
  OnInit,
  DoCheck,
  AfterContentInit,
  AfterContentChecked,
  AfterViewInit,
  AfterViewChecked,
  OnDestroy,
} from '@angular/core';

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/do';

@Component({
  selector: 'app-test',
  template: '{{ data$ | async }}'
})
export class TestComponent implements
  OnChanges,
  OnInit,
  DoCheck,
  AfterContentInit,
  AfterContentChecked,
  AfterViewInit,
  AfterViewChecked,
  OnDestroy {
    public get data$() {
      return this.data.asObservable().do(x => console.log('event: ', x));
    }
    public data: Subject<string> = new Subject<string>();

  ngOnChanges() {
    this.data.next('ngOnChanges');
  }

  ngOnInit() {
    this.data.next('ngOnInit');
  }

  ngDoCheck() {
    this.data.next('ngDoCheck');
  }

  ngAfterContentInit() {
    this.data.next('ngAfterContentInit');
  }

  ngAfterContentChecked() {
    this.data.next('ngAfterContentChecked');
  }

  ngAfterViewInit() {
    this.data.next('ngAfterViewInit');
  }

  ngAfterViewChecked() {
    this.data.next('ngAfterViewChecked');
  }

  ngOnDestroy() {
    this.data.next('ngOnDestroy');
  }
}
</code>```

The results:

```<code>event:  ngAfterViewInit
event:  ngAfterViewChecked
event:  ngDoCheck
event:  ngAfterContentChecked
event:  ngAfterViewChecked
</code>```

The results indicate that the async pipe first executes after ngOnInit which is where you first subscribed. This would explain why you missed it.

Body:
In a component, I subscribe a Subject to some part of my state using the store. From then on, when that part of the state changes, I will start receiving updates and my component will reflect this state. So far so good.

However, I also want my component to initialize correctly based on the current value of this state. So as soon as I subscribe, I also want the current value to get emitted - so, e.g., my view can initialize correctly.

Example with an Angular component:

my.component.ts

export class MyComponent implements OnInit {
  constructor(private store: Store<State>) { }

  // As soon as I subscribe, I want this to also emit the current
  // value, e.g. so my view can correctly reflect the current state.
  public mode$ = new Subject<ApplicationMode>();

  ngOnInit() {
    this.store.select(getApplicationState)
       .select(s => s.applicationMode).subscribe(this.mode$);
  }
}

my.component.html

{{ mode$ | async }}

I believe that what I would like/expect is that this part of my store would return a BehaviorSubject or a ReplaySubject(1). But selecting anything from the store always returns a Store<T> which is obviously some sort of subject, but doesn't seem to emit the current value upon subscription?

What might work, I guess, is to subscribe to this piece of state on application initialization, and then pass that value on through all its child components, all the way down to this one, so this component turns into a dumb one instead of selecting from the store itself. Is that perhaps the way to go? Or is there something basic I'm missing to make this work?

Body:
Ngrx does act like a BehaviorSubject where you get the current value when you first subscribe.

The issue is probably that you are pushing the value from a behavior subject (store) into a normal subject (mode$) before that subject is subscribed to. This would mean that you push the initial value into your subject (mode$) and it would have no subscriber to notify so it fizzles. When the subscriber subscribes to mode$ it is subscribing to a normal subject so it doesn't get the current value but it would get all future values.

What I would suggest is cutting out the middle-man and to expose the observable returned from the store directly to the view like so:

this.mode$ = this.store.select(...);

This way you are exposing an observable that will provide the current value on subscribe to any subscribers.

I am finding it hard to find specific documentation on where in the component lifecycle that the async pipe subscribes. So I put together a test where I publish to a subject in every lifecycle hook and subscribe to it via the async pipe.

The code:

import {
  Component,
  OnChanges,
  OnInit,
  DoCheck,
  AfterContentInit,
  AfterContentChecked,
  AfterViewInit,
  AfterViewChecked,
  OnDestroy,
} from '@angular/core';

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/do';

@Component({
  selector: 'app-test',
  template: '{{ data$ | async }}'
})
export class TestComponent implements
  OnChanges,
  OnInit,
  DoCheck,
  AfterContentInit,
  AfterContentChecked,
  AfterViewInit,
  AfterViewChecked,
  OnDestroy {
    public get data$() {
      return this.data.asObservable().do(x => console.log('event: ', x));
    }
    public data: Subject<string> = new Subject<string>();

  ngOnChanges() {
    this.data.next('ngOnChanges');
  }

  ngOnInit() {
    this.data.next('ngOnInit');
  }

  ngDoCheck() {
    this.data.next('ngDoCheck');
  }

  ngAfterContentInit() {
    this.data.next('ngAfterContentInit');
  }

  ngAfterContentChecked() {
    this.data.next('ngAfterContentChecked');
  }

  ngAfterViewInit() {
    this.data.next('ngAfterViewInit');
  }

  ngAfterViewChecked() {
    this.data.next('ngAfterViewChecked');
  }

  ngOnDestroy() {
    this.data.next('ngOnDestroy');
  }
}

The results:

event:  ngAfterViewInit
event:  ngAfterViewChecked
event:  ngDoCheck
event:  ngAfterContentChecked
event:  ngAfterViewChecked

The results indicate that the async pipe first executes after ngOnInit which is where you first subscribed. This would explain why you missed it.


问:
Specifications of SQL CE?
i hope this is not a repeated question

does anyone have an idea about the specs of CE SQL for example max size, max concurrent users.
how is it different from SQL express

答:
The Microsoft SQL Server site has extensive documentation on all versions of SQL server, including specs and comparisons.

The most significant difference between SQL Server Express and Compact editions is that CE runs in-process. That is, it is part of your application, web page, service, or whatever. Your application has total control of the data and nothing else typically has access unless it goes through your code. CE can be installed and run under a User account, and databases are standalone files that can be copied, emailed, deleted, or whatever from Windows Explorer.

SQL Express is a service typically installed by an administrator. It is a separate process that your application makes requests to; your application does not control it or the data.

There are other differences, but this is the major one. Yes, you can do things to allow multiple access to SQL CE files or install Express with your app and run it when your app launches, but this problematic and not advised.

ContentLicense: CC BY-SA 2.5

Title: Specifications of SQL CE?


问:
How to speed up importing dataframes into pandas
I understand that one of the reasons why pandas can be relatively slow importing csv files is that it needs to scan the entire content of a column before guessing the type (see the discussions around the mostly deprecated low_memory option for pandas.read_csv). Is my understanding correct?

If it is, what would be a good format in which to store a dataframe, and which explicitly specifies data types, so pandas doesn't have to guess (SQL is not an option for now)?

Any option in particular from those listed here?

My dataframes have floats, integers, dates, strings and Y/N, so formats supporting numeric values only won't do.

答:
One option is to use numpy.genfromtxt
with delimiter=',', names=True, then to initialize the pandas dataframe with the numpy array. The numpy array will be structured and the pandas constructor should automatically set the field names.

In my experience this performs well.

ContentLicense: CC BY-SA 4.0


问:
Multiple messageListener with Spring and RabbitMQ and DirectMessageListenerContainer
Following code given:

```<code>    DirectMessageListenerContainer container = new DirectMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(queues);
    container.setMessageListener(listenerAdapter);
</code>```

How can I have one listenerAdapter PER queue? Which means multiple adapters for multithreading. In case of setting a breakpoint at one listener, the other queues should continue to work.

Regards

答: OK it seems i have to use setChannelAwareMessageListener()</p>

Body:
Following code given:

    DirectMessageListenerContainer container = new DirectMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(queues);
    container.setMessageListener(listenerAdapter);

How can I have one listenerAdapter PER queue? Which means multiple adapters for multithreading. In case of setting a breakpoint at one listener, the other queues should continue to work.

Regards


答:
From what I can see from your code, it might just be the missing - in the assignment and some small syntax problem. Try this:

```<code>ResidentsBD_99_2015_clean<- ResidentsBD_99_2015_clean[order(ResidentsBD_99_2015_clean$birthdate_year, ResidentsBD_99_2015_clean$surname),]
</code>```

Title: Undefined Columns Selected (when using order function)

Body:
From what I can see from your code, it might just be the missing - in the assignment and some small syntax problem. Try this:

ResidentsBD_99_2015_clean<- ResidentsBD_99_2015_clean[order(ResidentsBD_99_2015_clean$birthdate_year, ResidentsBD_99_2015_clean$surname),]


问:
How to select all elements whose id contains a particular substring?
I want to select all elements whose id contains a particular substring. For example for these:

```<code><div id="foobootoo"><div>
<div id="foowoohoo"><div>
<div id="foodoowoo"><div>
<div id="soobootoo"><div>
</code>```

I want to get elements that has foo in the id.

答:
If you want to select multiple elements, just give the elements the same class.</p>

```<code><div id="foobootoo" class="foo"><div>
<div id="foowoohoo" class="foo"><div>
<div id="foodoowoo" class="foo"><div>
<div id="soobootoo" class="foo"><div>
</code>```

Body:
I want to select all elements whose id contains a particular substring. For example for these:

I want to get elements that has foo in the id.

Body:
If you want to select multiple elements, just give the elements the same class.

<div id="foobootoo" class="foo"><div>
<div id="foowoohoo" class="foo"><div>
<div id="foodoowoo" class="foo"><div>
<div id="soobootoo" class="foo"><div>


问:
free(): invalid pointer only after zerocopy DMA driver access
I have a driver that does a DMA transfer to a memory thats malloc'ed in a userspace application and then handed down to the kernel (get_user_pages...).

Problem: I get the "invalid pointer" message when calling free(). I print both pointer values, they are equal, not changed. The error does NOT happen when I use posix_memalign() instead malloc(). In case of posix_memalign() I get always page aligned pointers ( 0x....000). With malloc() its often unaligned addresses.

I tried already skipping the Driver DMA transfer call completely, basically just doing malloc() and free() in the application - it then always works!

That tells me that somehow the kernel seem to think the pages are still "locked" or so in kernel space.

I digged already through some drivers, especially the drivers/media/pci/ivtv/ivtv-udma.c and ivtv-yuv.c look interesting since they seem to do exactly the same.

There I found the function "put_page" which I tried already in my driver, but it didnt help, more, the driver then stuck.

Can someone point me in the right direction or an information source how the correct handling of such user pages in kernel space is ?

Here the relevant code.
The order is basically:
get_user_pages -> dma_map_page -> kick off HW DMA (in our FPGA) -> dma_unmap_page -> SetPageDirty -> put_page

But still same error as below occurs for non-aligned addresses.

```<code>perform_user_dma_func(..)
{
[...]

    rv = get_user_pages( current, current->mm, uaddr, nr_pages, (direction == DMA_FROM_DEVICE), 0, pages, NULL);
    if( rv < nr_pages )
        goto CLEANUP;

    /*--- build scatter/gather list ---*/
    offset = uaddr & ~PAGE_MASK;
#ifdef VME4L_DBG_DMA_DATA
    initOffs = offset;
#endif

    for ( i = 0; i < nr_pages; ++i, sgList++ ) {
        struct page *page = pages[i];
        sgList->dmaLength = PAGE_SIZE - offset;
        dmaAddr = dma_map_page( pDev, page, 0x0, PAGE_SIZE, direction );
        if ( dma_mapping_error( pDev, dmaAddr ) ) {
            printk( KERN_ERR "error mapping DMA space with dma_map_page\n" );
            goto CLEANUP;
        } else {
            sgList->dmaDataAddress = dmaAddr + offset; /* Add offset between page begin and payload data, often > 0 */
            sgList->dmaPageAddress = dmaAddr; /* store page address for later dma_unmap_page */
        }

        if( totlen + sgList->dmaLength > count )
            sgList->dmaLength = count - totlen;

        VME4LDBG(" sglist %d: pageAddr=%p off=0x%lx dmaAddr=%p length=0x%x\n", i, page_address(page), offset, dmaAddr, sgList->dmaLength);
        totlen += sgList->dmaLength;
        offset = 0;
    }

    /*--- now do DMA in HW (device touches memory) ---*/
    rv = vme4l_perform_zc_dma( spc, sgListStart, nr_pages, blk->direction, blk->vmeAddr, swapMode );

CLEANUP:

    /*--- free pages ---*/
    sgList = sgListStart;
    for (i = 0; i < nr_pages; i++, sgList++) {
        dma_unmap_page( pDev, sgList->dmaPageAddress, PAGE_SIZE, direction );
    }

    /* mark pages as dirty */
    if( blk->direction == READ ) {
        for (i = 0; i < nr_pages; i++ ) {
            if ( !PageReserved( pages[i] ))
                SetPageDirty( pages[i] );
        }
    }

    sgList = sgListStart;
    for (i = 0; i < nr_pages; i++, sgList++) {
        /* __free_page( pages[i] ); */
        put_page( pages[i] );
    }
[...]
}
</code>```

The error message when usimg malloc buffer (unaligned memory):

```<code>*** Error in `vme4l_rwex': free(): invalid pointer: 0x00000000008e4010 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fe0a34367e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fe0a343f37a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fe0a344353c]
vme4l_rwex[0x4010f8]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fe0a33df830]
vme4l_rwex[0x401419]
======= Memory map: ========
00400000-00402000 r-xp 00000000 08:15 931122                             /usr/local/bin/vme4l_rwex
00601000-00602000 r--p 00001000 08:15 931122                             /usr/local/bin/vme4l_rwex
00602000-00603000 rw-p 00002000 08:15 931122                             /usr/local/bin/vme4l_rwex
008e4000-00906000 rw-p 00000000 00:00 0                                  [heap]
7fe09c000000-7fe09c021000 rw-p 00000000 00:00 0
7fe09c021000-7fe0a0000000 ---p 00000000 00:00 0
7fe0a31a9000-7fe0a31bf000 r-xp 00000000 08:15 1035123                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe0a31bf000-7fe0a33be000 ---p 00016000 08:15 1035123                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe0a33be000-7fe0a33bf000 rw-p 00015000 08:15 1035123                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe0a33bf000-7fe0a357f000 r-xp 00000000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a357f000-7fe0a377f000 ---p 001c0000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a377f000-7fe0a3783000 r--p 001c0000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a3783000-7fe0a3785000 rw-p 001c4000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a3785000-7fe0a3789000 rw-p 00000000 00:00 0
7fe0a3789000-7fe0a378b000 r-xp 00000000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a378b000-7fe0a398a000 ---p 00002000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a398a000-7fe0a398b000 r--p 00001000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a398b000-7fe0a398c000 rw-p 00002000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a398c000-7fe0a398e000 r-xp 00000000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a398e000-7fe0a3b8e000 ---p 00002000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a3b8e000-7fe0a3b8f000 r--p 00002000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a3b8f000-7fe0a3b90000 rw-p 00003000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a3b90000-7fe0a3bb6000 r-xp 00000000 08:15 1045455                    /lib/x86_64-linux-gnu/ld-2.23.so
7fe0a3da6000-7fe0a3da9000 rw-p 00000000 00:00 0
7fe0a3db2000-7fe0a3db5000 rw-p 00000000 00:00 0
7fe0a3db5000-7fe0a3db6000 r--p 00025000 08:15 1045455                    /lib/x86_64-linux-gnu/ld-2.23.so
7fe0a3db6000-7fe0a3db7000 rw-p 00026000 08:15 1045455                    /lib/x86_64-linux-gnu/ld-2.23.so
7fe0a3db7000-7fe0a3db8000 rw-p 00000000 00:00 0
7ffd66125000-7ffd66146000 rw-p 00000000 00:00 0                          [stack]
7ffd661b4000-7ffd661b6000 r--p 00000000 00:00 0                          [vvar]
7ffd661b6000-7ffd661b8000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted
</code>```

答:
Solved it myself.

turned out that mapping with dma_map_page() makes the whole transferred data visible correctly in RAM, but every other data in that page is overwritten (including malloc's pointer management data right before and after the transferred data, which leads to the libc error prompt), the caching somehow doesn't work like expected. Upon dma_unmap_page() the data were visible only every several call to the function.

With dma_map_single() things look better. I do get_user_pages_fast(), then dma_map_single() the pages virtual address plus the offset - works fine and DMA debug functions in the kernel don't complain. See code below.

```<code>    for (i = 0; i < nr_pages; ++i, sgList++) {
            struct page *page = pages[i];
            sgList->dmaLength  = PAGE_SIZE - offset;
            pVirtAddr = ((unsigned char*)(page_address( page ))) + offset;

            if( totlen + sgList->dmaLength > count )
                sgList->dmaLength = count - totlen;

            dmaAddr = dma_map_single( pDev, pVirtAddr, sgList->dmaLength, direction );
            if ( dma_mapping_error( pDev, dmaAddr ) ) {
                   printk( KERN_ERR "*** error mapping DMA space!\n" );
                   goto CLEANUP;
            } else {
                   sgList->dmaAddress = dmaAddr;
            }

            VME4LDBG(" sglist %d: pageAddr=%p off=0x%04lx dmaAddr=%p length=0x%04x\n", i, page_address(page), offset, dmaAddr, sgList->dmaLength);
            totlen += sgList->dmaLength;
            offset = 0;
       }

       /*--- now do DMA in HW (device touches memory) ---*/
       rv = vme4l_perform_zc_dma( spc, sgListStart, nr_pages, blk->direction, blk->vmeAddr, swapMode );

CLEANUP:
       /*--- free pages ---*/
       if( locked ) {
             sgList = sgListStart;
             for (i = 0; i < nr_pages; i++, sgList++) {
                 dma_unmap_single( pDev, sgList->dmaAddress, sgList->dmaLength , direction );
                 put_page( pages[i] ); /* release pages locked with get_user_pages */
             }
   }
</code>```

Body:
I have a driver that does a DMA transfer to a memory thats malloc'ed in a userspace application and then handed down to the kernel (get_user_pages...).

Problem: I get the "invalid pointer" message when calling free(). I print both pointer values, they are equal, not changed. The error does NOT happen when I use posix_memalign() instead malloc(). In case of posix_memalign() I get always page aligned pointers ( 0x....000). With malloc() its often unaligned addresses.

I tried already skipping the Driver DMA transfer call completely, basically just doing malloc() and free() in the application - it then always works!

That tells me that somehow the kernel seem to think the pages are still "locked" or so in kernel space.

I digged already through some drivers, especially the drivers/media/pci/ivtv/ivtv-udma.c and ivtv-yuv.c look interesting since they seem to do exactly the same.

There I found the function "put_page" which I tried already in my driver, but it didnt help, more, the driver then stuck.

Can someone point me in the right direction or an information source how the correct handling of such user pages in kernel space is ?

Here the relevant code.
The order is basically:
get_user_pages -> dma_map_page -> kick off HW DMA (in our FPGA) -> dma_unmap_page -> SetPageDirty -> put_page

But still same error as below occurs for non-aligned addresses.

perform_user_dma_func(..)
{
[...]

    rv = get_user_pages( current, current->mm, uaddr, nr_pages, (direction == DMA_FROM_DEVICE), 0, pages, NULL);
    if( rv < nr_pages )
        goto CLEANUP;

    /*--- build scatter/gather list ---*/
    offset = uaddr & ~PAGE_MASK;
#ifdef VME4L_DBG_DMA_DATA
    initOffs = offset;
#endif

    for ( i = 0; i < nr_pages; ++i, sgList++ ) {
        struct page *page = pages[i];
        sgList->dmaLength = PAGE_SIZE - offset;
        dmaAddr = dma_map_page( pDev, page, 0x0, PAGE_SIZE, direction );
        if ( dma_mapping_error( pDev, dmaAddr ) ) {
            printk( KERN_ERR "error mapping DMA space with dma_map_page\n" );
            goto CLEANUP;
        } else {
            sgList->dmaDataAddress = dmaAddr + offset; /* Add offset between page begin and payload data, often > 0 */
            sgList->dmaPageAddress = dmaAddr; /* store page address for later dma_unmap_page */
        }

        if( totlen + sgList->dmaLength > count )
            sgList->dmaLength = count - totlen;

        VME4LDBG(" sglist %d: pageAddr=%p off=0x%lx dmaAddr=%p length=0x%x\n", i, page_address(page), offset, dmaAddr, sgList->dmaLength);
        totlen += sgList->dmaLength;
        offset = 0;
    }

    /*--- now do DMA in HW (device touches memory) ---*/
    rv = vme4l_perform_zc_dma( spc, sgListStart, nr_pages, blk->direction, blk->vmeAddr, swapMode );

CLEANUP:

    /*--- free pages ---*/
    sgList = sgListStart;
    for (i = 0; i < nr_pages; i++, sgList++) {
        dma_unmap_page( pDev, sgList->dmaPageAddress, PAGE_SIZE, direction );
    }

    /* mark pages as dirty */
    if( blk->direction == READ ) {
        for (i = 0; i < nr_pages; i++ ) {
            if ( !PageReserved( pages[i] ))
                SetPageDirty( pages[i] );
        }
    }

    sgList = sgListStart;
    for (i = 0; i < nr_pages; i++, sgList++) {
        /* __free_page( pages[i] ); */
        put_page( pages[i] );
    }
[...]
}

The error message when usimg malloc buffer (unaligned memory):

*** Error in `vme4l_rwex': free(): invalid pointer: 0x00000000008e4010 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fe0a34367e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fe0a343f37a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fe0a344353c]
vme4l_rwex[0x4010f8]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fe0a33df830]
vme4l_rwex[0x401419]
======= Memory map: ========
00400000-00402000 r-xp 00000000 08:15 931122                             /usr/local/bin/vme4l_rwex
00601000-00602000 r--p 00001000 08:15 931122                             /usr/local/bin/vme4l_rwex
00602000-00603000 rw-p 00002000 08:15 931122                             /usr/local/bin/vme4l_rwex
008e4000-00906000 rw-p 00000000 00:00 0                                  [heap]
7fe09c000000-7fe09c021000 rw-p 00000000 00:00 0
7fe09c021000-7fe0a0000000 ---p 00000000 00:00 0
7fe0a31a9000-7fe0a31bf000 r-xp 00000000 08:15 1035123                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe0a31bf000-7fe0a33be000 ---p 00016000 08:15 1035123                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe0a33be000-7fe0a33bf000 rw-p 00015000 08:15 1035123                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe0a33bf000-7fe0a357f000 r-xp 00000000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a357f000-7fe0a377f000 ---p 001c0000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a377f000-7fe0a3783000 r--p 001c0000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a3783000-7fe0a3785000 rw-p 001c4000 08:15 1045483                    /lib/x86_64-linux-gnu/libc-2.23.so
7fe0a3785000-7fe0a3789000 rw-p 00000000 00:00 0
7fe0a3789000-7fe0a378b000 r-xp 00000000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a378b000-7fe0a398a000 ---p 00002000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a398a000-7fe0a398b000 r--p 00001000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a398b000-7fe0a398c000 rw-p 00002000 08:15 905612                     /usr/local/lib/libusr_utl.so
7fe0a398c000-7fe0a398e000 r-xp 00000000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a398e000-7fe0a3b8e000 ---p 00002000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a3b8e000-7fe0a3b8f000 r--p 00002000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a3b8f000-7fe0a3b90000 rw-p 00003000 08:15 905739                     /usr/local/lib/libvme4l_api.so
7fe0a3b90000-7fe0a3bb6000 r-xp 00000000 08:15 1045455                    /lib/x86_64-linux-gnu/ld-2.23.so
7fe0a3da6000-7fe0a3da9000 rw-p 00000000 00:00 0
7fe0a3db2000-7fe0a3db5000 rw-p 00000000 00:00 0
7fe0a3db5000-7fe0a3db6000 r--p 00025000 08:15 1045455                    /lib/x86_64-linux-gnu/ld-2.23.so
7fe0a3db6000-7fe0a3db7000 rw-p 00026000 08:15 1045455                    /lib/x86_64-linux-gnu/ld-2.23.so
7fe0a3db7000-7fe0a3db8000 rw-p 00000000 00:00 0
7ffd66125000-7ffd66146000 rw-p 00000000 00:00 0                          [stack]
7ffd661b4000-7ffd661b6000 r--p 00000000 00:00 0                          [vvar]
7ffd661b6000-7ffd661b8000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted

Body:
Solved it myself.

turned out that mapping with dma_map_page() makes the whole transferred data visible correctly in RAM, but every other data in that page is overwritten (including malloc's pointer management data right before and after the transferred data, which leads to the libc error prompt), the caching somehow doesn't work like expected. Upon dma_unmap_page() the data were visible only every several call to the function.

With dma_map_single() things look better. I do get_user_pages_fast(), then dma_map_single() the pages virtual address plus the offset - works fine and DMA debug functions in the kernel don't complain. See code below.

    for (i = 0; i < nr_pages; ++i, sgList++) {
            struct page *page = pages[i];
            sgList->dmaLength  = PAGE_SIZE - offset;
            pVirtAddr = ((unsigned char*)(page_address( page ))) + offset;

            if( totlen + sgList->dmaLength > count )
                sgList->dmaLength = count - totlen;

            dmaAddr = dma_map_single( pDev, pVirtAddr, sgList->dmaLength, direction );
            if ( dma_mapping_error( pDev, dmaAddr ) ) {
                   printk( KERN_ERR "*** error mapping DMA space!\n" );
                   goto CLEANUP;
            } else {
                   sgList->dmaAddress = dmaAddr;
            }

            VME4LDBG(" sglist %d: pageAddr=%p off=0x%04lx dmaAddr=%p length=0x%04x\n", i, page_address(page), offset, dmaAddr, sgList->dmaLength);
            totlen += sgList->dmaLength;
            offset = 0;
       }

       /*--- now do DMA in HW (device touches memory) ---*/
       rv = vme4l_perform_zc_dma( spc, sgListStart, nr_pages, blk->direction, blk->vmeAddr, swapMode );

CLEANUP:
       /*--- free pages ---*/
       if( locked ) {
             sgList = sgListStart;
             for (i = 0; i < nr_pages; i++, sgList++) {
                 dma_unmap_single( pDev, sgList->dmaAddress, sgList->dmaLength , direction );
                 put_page( pages[i] ); /* release pages locked with get_user_pages */
             }
   }


问:
Property 'withServerTransition' does not exist on type 'typeof BrowserModule'.)
Am Using the angular universal 1.0.0-alpha.universal.3

I have created the new app using the angular universal cli.

ung new test-app --universal

package.json

```
{
  "name": "test-app",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ung serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ung test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.2.3",
    "@angular/compiler": "2.2.3",
    "@angular/core": "2.2.3",
    "@angular/forms": "2.2.3",
    "@angular/http": "2.2.3",
    "@angular/platform-browser": "^2.2.3",
    "@angular/platform-browser-dynamic": "2.2.3",
    "@angular/platform-server": "^2.2.3",
    "@angular/router": "3.2.3",
    "@ngx-universal/state-transfer": "^4.0.1",
    "angular2-express-engine": "2.1.0-rc.1",
    "angular2-flash-messages": "^1.0.8",
    "angular2-jwt": "^0.2.3",
    "angular2-platform-node": "2.1.0-rc.1",
    "angular2-universal": "2.1.0-rc.1",
    "angular2-universal-polyfills": "2.1.0-rc.1",
    "bcryptjs": "^2.4.3",
    "bootstrap": "^3.3.7",
    "compression": "1.6.2",
    "core-js": "^2.4.1",
    "cors": "^2.8.4",
    "express": "^4.14.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.1",
    "jsonwebtoken": "^8.1.0",
    "mongoose": "^4.13.1",
    "passport": "^0.4.0",
    "passport-jwt": "^3.0.0",
    "passport-local": "^1.0.0",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@angular/compiler-cli": "2.2.3",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "@types/body-parser": "0.0.29",
    "@types/compression": "0.0.29",
    "@types/cookie-parser": "^1.3.29",
    "@types/express": "^4.0.29",
    "@types/express-serve-static-core": "^4.0.29",
    "@types/mime": "0.0.28",
    "@types/serve-static": "^1.7.27",
    "universal-cli": "1.0.0-alpha.universal.3",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3"
  }
}

```

I would like to add the below browserModule on my app.browser.module.ts file

BrowserModule.withServerTransition({ appId: 'test-app' })

After adding this script am getting below error.

```
Uncaught Error: Module build failed: Error: E:/projects/Angular2/test-app/src/app/app.browser.module.ts (32,19): Property 'withServerTransition' does not exist on type 'typeof BrowserModule'.)
    at _checkDiagnostics (E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:115:15)
    at E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:140:17
    at
    at _checkDiagnostics (E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:115:15)
    at E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:140:17
    at
    at Object.433 (http://localhost:4200/client.bundle.js:83:7)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.334 (http://localhost:4200/client.bundle.js:29:82)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.624 (http://localhost:4200/client.bundle.js:171:18)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at webpackJsonpCallback (http://localhost:4200/inline.bundle.js:24:23)
    at http://localhost:4200/client.bundle.js:1:1
```

link: https://github.com/angular/angular-cli/issues/8476

答:
I think WithServerTransition was added in angular 4. Upgrade to angular 4 or 5 if you are starting a new project

v2 docs
https://v2.angular.io/docs/ts/latest/api/platform-browser/index/BrowserModule-class.html

v4 docs https://v4.angular.io/api/platform-browser/BrowserModule

Body:
Am Using the angular universal 1.0.0-alpha.universal.3

I have created the new app using the angular universal cli.

ung new test-app --universal

package.json

{
  "name": "test-app",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ung serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ung test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.2.3",
    "@angular/compiler": "2.2.3",
    "@angular/core": "2.2.3",
    "@angular/forms": "2.2.3",
    "@angular/http": "2.2.3",
    "@angular/platform-browser": "^2.2.3",
    "@angular/platform-browser-dynamic": "2.2.3",
    "@angular/platform-server": "^2.2.3",
    "@angular/router": "3.2.3",
    "@ngx-universal/state-transfer": "^4.0.1",
    "angular2-express-engine": "2.1.0-rc.1",
    "angular2-flash-messages": "^1.0.8",
    "angular2-jwt": "^0.2.3",
    "angular2-platform-node": "2.1.0-rc.1",
    "angular2-universal": "2.1.0-rc.1",
    "angular2-universal-polyfills": "2.1.0-rc.1",
    "bcryptjs": "^2.4.3",
    "bootstrap": "^3.3.7",
    "compression": "1.6.2",
    "core-js": "^2.4.1",
    "cors": "^2.8.4",
    "express": "^4.14.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.1",
    "jsonwebtoken": "^8.1.0",
    "mongoose": "^4.13.1",
    "passport": "^0.4.0",
    "passport-jwt": "^3.0.0",
    "passport-local": "^1.0.0",
    "rxjs": "5.0.0-beta.12",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@angular/compiler-cli": "2.2.3",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "@types/body-parser": "0.0.29",
    "@types/compression": "0.0.29",
    "@types/cookie-parser": "^1.3.29",
    "@types/express": "^4.0.29",
    "@types/express-serve-static-core": "^4.0.29",
    "@types/mime": "0.0.28",
    "@types/serve-static": "^1.7.27",
    "universal-cli": "1.0.0-alpha.universal.3",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3"
  }
}

I would like to add the below browserModule on my app.browser.module.ts file

BrowserModule.withServerTransition({ appId: 'test-app' })

After adding this script am getting below error.

Uncaught Error: Module build failed: Error: E:/projects/Angular2/test-app/src/app/app.browser.module.ts (32,19): Property 'withServerTransition' does not exist on type 'typeof BrowserModule'.)
    at _checkDiagnostics (E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:115:15)
    at E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:140:17
    at
    at _checkDiagnostics (E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:115:15)
    at E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:140:17
    at
    at Object.433 (http://localhost:4200/client.bundle.js:83:7)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.334 (http://localhost:4200/client.bundle.js:29:82)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.624 (http://localhost:4200/client.bundle.js:171:18)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at webpackJsonpCallback (http://localhost:4200/inline.bundle.js:24:23)
    at http://localhost:4200/client.bundle.js:1:1

link: https://github.com/angular/angular-cli/issues/8476


问:
Sorting Struct array in Swift 4
I've got the below struct and would like to sort the items within sessions by startTime field. I'm completely lost on how to do this.

I tried:

```<code>let sortedArray = sessionsData?.items.sorted{ ($0["startTime"] as! String) < ($1["startTime"] as! String) }
</code>```

but that just gives me an error about no subscript members?

Any pointers would really be appreciated, thank you.

```<code>public struct sessions: Decodable {
  let status: String?
  let start: Int?
  let count: Int?
  let items: [sessionInfo]?
  let itemsCount: Int?
  let multipart: Bool?
  let startTime: Int?
  let endTime: Int?
}

public struct sessionInfo: Decodable {
  let name: String?
  let datalist: String?
  let sessionType: Int?
  let status: Int?
  let backupType: Int?
  let startTime: Int?
  let endTime: Int?
  let owner: String?
  let numOfErrors: Int?
  let numOfWarnings: Int?
  let flags: Int?
}
</code>```

I tried the below, but get an error:

```<code>var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in
        return lhs.startTime < rhs.startTime
    })
</code>```

error:

```<code>Binary operator '<' cannot be applied to two 'Int?' operands
</code>```

答:
You could write this (tested in playground) :

```<code>var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in return (lhs.startTime ?? 0) < (rhs.startTime ?? 0) })
</code>```

If one is optional, you do not crash, even though result of comparison is meaningless

Title: Sorting Struct array in Swift 4

Body:
I've got the below struct and would like to sort the items within sessions by startTime field. I'm completely lost on how to do this.

I tried:

let sortedArray = sessionsData?.items.sorted{ ($0["startTime"] as! String) < ($1["startTime"] as! String) }

but that just gives me an error about no subscript members?

Any pointers would really be appreciated, thank you.

public struct sessions: Decodable {
  let status: String?
  let start: Int?
  let count: Int?
  let items: [sessionInfo]?
  let itemsCount: Int?
  let multipart: Bool?
  let startTime: Int?
  let endTime: Int?
}

public struct sessionInfo: Decodable {
  let name: String?
  let datalist: String?
  let sessionType: Int?
  let status: Int?
  let backupType: Int?
  let startTime: Int?
  let endTime: Int?
  let owner: String?
  let numOfErrors: Int?
  let numOfWarnings: Int?
  let flags: Int?
}

I tried the below, but get an error:

var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in
        return lhs.startTime < rhs.startTime
    })

error:

Binary operator '<' cannot be applied to two 'Int?' operands

Body:
You could write this (tested in playground) :

var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in return (lhs.startTime ?? 0) < (rhs.startTime ?? 0) })

If one is optional, you do not crash, even though result of comparison is meaningless


问:
Choreogrpher Issues
I have problems with my app. It gives me the warning: I/Choreographer: Skipped 43 frames!  The application may be doing too much work on its main thread.

My app has 2 very simple activities in fact one of them I do not write its code. 1 of them is a splash screen with a progressBar and the other only show some elements.

SplashScreen.java

```<code>   public class SplashScreen extends AppCompatActivity {

    //Variables declaration
    private ProgressBar progressBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        //Fill in variables
        TextView textView = findViewById(R.id.text_splash);
        progressBar = findViewById(R.id.splash_screen_progress_bar);

        //Change the textView font
        Typeface face = Typeface.createFromAsset(getAssets(),"fonts/ExpletusSans-BoldItalic.ttf");
        textView.setTypeface(face);

        //Call to the background execution
        new UpdateProgressBar().execute();
    }

    /* Auxiliary class to operate in background:
    * First parameter: in data type of function doInBackground()
    * Second parameter: data type of function onProgressUpdate()
    * Third parameter: out data type of function doInBackground()
    * */
    public class UpdateProgressBar extends AsyncTask<Void, Integer, Void> {

        //Execution in background (in a different thread)
        @Override
        protected Void doInBackground(Void... params) {
            //I want to show splashScreen for 4 seconds
            for(int i = 1; i <= 4 ; i++){
                oneSecond();
                publishProgress(i*25);
                if(isCancelled()){
                    break;
                }
            }
            return null;
        }

        //It executes in the main thread, when I call publishProgress() in doInBackground().
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
        }

        //Execute after doInBackground() in the main thread.
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Intent change_screen = new Intent(SplashScreen.this, MeasureScreenActivity.class);
            startActivity(change_screen);
            //Effect of transition
            overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
            finish();
        }
    }

    //Auxiliary method to simulate one second
    public void oneSecond(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

splash_screen.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/app_background">

    <TextView
        android:id="@+id/text_splash"
        android:layout_width="match_parent"
        android:layout_height="60sp"
        android:layout_alignParentStart="true"
        android:gravity="center"
        android:layout_marginTop="35dp"
        android:text="Breath Frequecy"
        android:textColor="#fff"
        android:textSize="30sp" />

    <ImageView
        android:id="@+id/splash_screen_image"
        android:layout_width="match_parent"
        android:layout_height="300sp"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:src="@drawable/img_loadpage" />

    <ProgressBar
        android:id="@+id/splash_screen_progress_bar"
        android:layout_centerHorizontal="true"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="350dp"
        android:layout_height="25dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:progressDrawable="@drawable/custom_progressbar_horizontal"/>

</RelativeLayout>
</code>```

MeasureScreenActivity.java

```<code>public class MeasureScreenActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.measure_screen);
    }
}
</code>```

measure_screen.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.appsgarci.prueba.MeasureScreenActivity"
    android:orientation="vertical"
    android:background="@drawable/app_background">

    <TextView
        android:id="@+id/text_measure"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:paddingEnd="10dp"
        android:paddingStart="10dp"
        android:text="Elija la actividad que ha realizado:"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="25sp" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="350dp"
        android:layout_height="50dp"
        android:layout_alignStart="@+id/spinner_measure"
        android:layout_alignBottom="@+id/spinner_measure"
        android:background="@drawable/stroke_spinner_selected"
        android:id="@+id/linearLayout"
        android:visibility="visible"/>

    <Spinner
        android:id="@+id/spinner_measure"
        android:layout_width="350dp"
        android:layout_height="50dp"
        android:layout_below="@+id/text_measure"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp" />

    <Button
        android:id="@+id/button_measure"
        android:layout_width="140sp"
        android:layout_height="140sp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center"
        android:layout_marginBottom="50dp"
        android:background="@drawable/action_button_shape"
        android:text="Iniciar"
        android:textStyle="bold"
        android:textSize="20dp"
        android:visibility="visible"/>

 </RelativeLayout>
</code>```

Only with this code I already have the problem with Choreographer and I do not know why, because it only has one operation, that is upgrade the progressBar.

My drawable folder has this:

action_button_shape.xml (v24)

app_background.webp

boton_measurement.webp (v24)

boton_measurement_pressed.webp (v24)

custom_progressbar.xml (v24)

custom_progressbar_horizontal.xml

img_loader.webp

I do not know the difference between drawable and drawable-24.

I have done several tests:

In android studio emulator works perfectly (nexus_5x API 24)

In my mobile phone gives me choreographer issue with and without drawable-24 elements(xiaomi mi max API 24)

In another mobile phone I can't use drawable-24 but changing to drawable, it works fine (xiaomi redmi 3s API 23)

What could be happening in my mobile?

答:
As mentioned here The application may be doing too much work on its main thread. You should also check the size of your drawables.

Try reducing size of images (@drawable/app_background @drawable/img_loadpage) or move them to drawable-xxxhdpi for now.

Title: Choreogrpher Issues

Body:
I have problems with my app. It gives me the warning: I/Choreographer: Skipped 43 frames!  The application may be doing too much work on its main thread.

My app has 2 very simple activities in fact one of them I do not write its code. 1 of them is a splash screen with a progressBar and the other only show some elements.

SplashScreen.java

   public class SplashScreen extends AppCompatActivity {

    //Variables declaration
    private ProgressBar progressBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        //Fill in variables
        TextView textView = findViewById(R.id.text_splash);
        progressBar = findViewById(R.id.splash_screen_progress_bar);

        //Change the textView font
        Typeface face = Typeface.createFromAsset(getAssets(),"fonts/ExpletusSans-BoldItalic.ttf");
        textView.setTypeface(face);

        //Call to the background execution
        new UpdateProgressBar().execute();
    }

    /* Auxiliary class to operate in background:
    * First parameter: in data type of function doInBackground()
    * Second parameter: data type of function onProgressUpdate()
    * Third parameter: out data type of function doInBackground()
    * */
    public class UpdateProgressBar extends AsyncTask<Void, Integer, Void> {

        //Execution in background (in a different thread)
        @Override
        protected Void doInBackground(Void... params) {
            //I want to show splashScreen for 4 seconds
            for(int i = 1; i <= 4 ; i++){
                oneSecond();
                publishProgress(i*25);
                if(isCancelled()){
                    break;
                }
            }
            return null;
        }

        //It executes in the main thread, when I call publishProgress() in doInBackground().
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
        }

        //Execute after doInBackground() in the main thread.
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Intent change_screen = new Intent(SplashScreen.this, MeasureScreenActivity.class);
            startActivity(change_screen);
            //Effect of transition
            overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
            finish();
        }
    }

    //Auxiliary method to simulate one second
    public void oneSecond(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

splash_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/app_background">

    <TextView
        android:id="@+id/text_splash"
        android:layout_width="match_parent"
        android:layout_height="60sp"
        android:layout_alignParentStart="true"
        android:gravity="center"
        android:layout_marginTop="35dp"
        android:text="Breath Frequecy"
        android:textColor="#fff"
        android:textSize="30sp" />

    <ImageView
        android:id="@+id/splash_screen_image"
        android:layout_width="match_parent"
        android:layout_height="300sp"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:src="@drawable/img_loadpage" />

    <ProgressBar
        android:id="@+id/splash_screen_progress_bar"
        android:layout_centerHorizontal="true"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="350dp"
        android:layout_height="25dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:progressDrawable="@drawable/custom_progressbar_horizontal"/>

</RelativeLayout>

MeasureScreenActivity.java

public class MeasureScreenActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.measure_screen);
    }
}

measure_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.appsgarci.prueba.MeasureScreenActivity"
    android:orientation="vertical"
    android:background="@drawable/app_background">

    <TextView
        android:id="@+id/text_measure"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:paddingEnd="10dp"
        android:paddingStart="10dp"
        android:text="Elija la actividad que ha realizado:"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="25sp" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="350dp"
        android:layout_height="50dp"
        android:layout_alignStart="@+id/spinner_measure"
        android:layout_alignBottom="@+id/spinner_measure"
        android:background="@drawable/stroke_spinner_selected"
        android:id="@+id/linearLayout"
        android:visibility="visible"/>

    <Spinner
        android:id="@+id/spinner_measure"
        android:layout_width="350dp"
        android:layout_height="50dp"
        android:layout_below="@+id/text_measure"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp" />

    <Button
        android:id="@+id/button_measure"
        android:layout_width="140sp"
        android:layout_height="140sp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center"
        android:layout_marginBottom="50dp"
        android:background="@drawable/action_button_shape"
        android:text="Iniciar"
        android:textStyle="bold"
        android:textSize="20dp"
        android:visibility="visible"/>

 </RelativeLayout>

Only with this code I already have the problem with Choreographer and I do not know why, because it only has one operation, that is upgrade the progressBar.

My drawable folder has this:

action_button_shape.xml (v24)

app_background.webp

boton_measurement.webp (v24)

boton_measurement_pressed.webp (v24)

custom_progressbar.xml (v24)

custom_progressbar_horizontal.xml

img_loader.webp

I do not know the difference between drawable and drawable-24.

I have done several tests:

In android studio emulator works perfectly (nexus_5x API 24)

In my mobile phone gives me choreographer issue with and without drawable-24 elements(xiaomi mi max API 24)

In another mobile phone I can't use drawable-24 but changing to drawable, it works fine (xiaomi redmi 3s API 23)

What could be happening in my mobile?


问:
High-Quality Text-To-Speech engine for personal use
I'm looking for a high-quality TTS engine that I can afford (let's say less than 1000$). So far, I've tried flite and festival with default voices. However, while the results are certainly understandable, technical texts are hard to follow.

Commercial TTS solutions from Loquendo and Readspeaker sound way better. However, these companies don't seem to be willing to sell their product to mere mortals - I can't find a price on either's homepage.

So, what are good TTS solutions for personal use?

答: I've used AT&T Natural Voices, they seem to sound most human to me.</p>


问:
Max(set) in function gives type error in Jupyter
Running this function in Jupyther notebook to get the max value of a collatz sequence

```<code>def collatz_max(i, seq = set()):
    seq.add(i)
    if i == 1:
        return max(seq)
    else:
        if i%2 == 0:
            return collatz_max(i/2, seq)
        else:
            return collatz_max(3*i + 1, seq)

collatz_max(7)
</code>```

yields

```<code>    <ipython-input-64-2d2324774edf> in collatz_max(i, seq)
      6     seq.add(i)
      7     if i == 1:
----> 8         return max(seq)
      9     else:
     10         if i%2 == 0:

TypeError: 'dict' object is not callable
</code>```

However, there was no error when I ran this in PyCharm, so I am not sure why exactly  it is there?

答: Somewhere you have defined a dictionary with the name max. Rename the dictionary to a name that's not already taken by a builtin.

Body:
Running this function in Jupyther notebook to get the max value of a collatz sequence

def collatz_max(i, seq = set()):
    seq.add(i)
    if i == 1:
        return max(seq)
    else:
        if i%2 == 0:
            return collatz_max(i/2, seq)
        else:
            return collatz_max(3*i + 1, seq)

collatz_max(7)

yields

    <ipython-input-64-2d2324774edf> in collatz_max(i, seq)
      6     seq.add(i)
      7     if i == 1:
----> 8         return max(seq)
      9     else:
     10         if i%2 == 0:

TypeError: 'dict' object is not callable

However, there was no error when I ran this in PyCharm, so I am not sure why exactly  it is there?


问:
Korean sentences being split randomly
I'm facing a problem here: I have a text in Korean decimal Unicode and the text is displayed in 4 columns and many rows (as it's the answers of a language test). The problem is that because the width of each answer is 20%, the sentence splits randomly in the middle of the word when it doesn't fit, instead of in the spaces between words. I don't know how to treat this, since this text is loaded and displayed automatically from a database.

The HTML code for each one of the 4 columns is like this:

```<code><table class="courses" border="0" cellpadding="2" cellspacing="2" width="100%" style="font-size:13px;">
  <tbody>
    <td width="20%">
     <p align="center">
       <input name="a[X]" value=1" type="radio">
       <br>
       <?php echo "바쁘면 가지 마세요" ?> // this comes from a DB, its the unicodes of the korean characters<br>
    </p>
   </td>
</tbody>
</table>
</code>```

What could I do to fix this and, when it doesn't fit, avoid splitting randomly, but do it when a sentence ends? If you notice in the Unicode codes, you can tell there's a space between ;면 &#44032, but it breaks just anywhere, the same for all the text.

(Note that there aren't any encoding problems, the Korean characters are displayed properly. And it doesn't happen with other languages like Swedish or Spanish).

EDIT

Here's a working example.

Note that in the example, the first answer is split in the last two characters, when that word has five characters, so should be split 3 chars before.

答:
I've been looking in to this for a project I'm working on. I think https://www.w3.org/TR/css-text-3/#line-breaking covers this, particularly "Example 5":

As another example, Korean has two styles of line-breaking: between any two Korean syllables (word-break: normal) or, like English, mainly at spaces (word-break: keep-all).

Indeed, the default behavior of Google Chrome (version 61) is that it breaks on the syllables (I assume as I don't speak or read Korean)

Setting word-break: all, seems to override this behavior and put line wraps in on white spaces only.

Title: Korean sentences being split randomly

Body:
I'm facing a problem here: I have a text in Korean decimal Unicode and the text is displayed in 4 columns and many rows (as it's the answers of a language test). The problem is that because the width of each answer is 20%, the sentence splits randomly in the middle of the word when it doesn't fit, instead of in the spaces between words. I don't know how to treat this, since this text is loaded and displayed automatically from a database.

The HTML code for each one of the 4 columns is like this:

       <input name="a[X]" value=1" type="radio">

       <?php echo "바쁘면 가지 마세요" ?> // this comes from a DB, its the unicodes of the korean characters

What could I do to fix this and, when it doesn't fit, avoid splitting randomly, but do it when a sentence ends? If you notice in the Unicode codes, you can tell there's a space between ;면 &#44032, but it breaks just anywhere, the same for all the text.

(Note that there aren't any encoding problems, the Korean characters are displayed properly. And it doesn't happen with other languages like Swedish or Spanish).

EDIT

Here's a working example.

Note that in the example, the first answer is split in the last two characters, when that word has five characters, so should be split 3 chars before.


问:
Hide tabs programmatically in Excel, EPPlus, C#
I would like to hide all the tabs in an excel workbook. I can set a sheet to hidden, but this is not a great solution because I still would like to be able to link that the sheet, which is not possible when I hide the entire sheet.

So, what I'm asking is this: Is there a way to just hide the tabs at the bottom of the workbook, but keep the sheets visible and linkable?

答:
You can find full sample code here</p>

```<code>appExcel.ActiveWindow.DisplayWorkbookTabs = false;
</code>```

Body:
You can find full sample code here

appExcel.ActiveWindow.DisplayWorkbookTabs = false;


问:
Create an array of strings
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

```<code>for i=1:10
Names(i)='Sample Text';
end
</code>```

I don't seem to be able to do it this way.

答:
New features have been added to MATLAB recently:

String arrays were introduced in R2016b (as Budo and gnovice already mentioned):

String arrays store pieces of text and provide a set of functions for
  working with text as data. You can index into, reshape, and
  concatenate strings arrays just as you can with arrays of any other
  type.

In addition, starting in R2017a, you can create a string using double quotes "".

Therefore if your MATLAB version is >= R2017a, the following will do:

```<code>for i = 1:3
    Names(i) = "Sample Text";
end
</code>```

Check the output:

```<code>>> Names

Names =

  1×3 string array

    "Sample Text"    "Sample Text"    "Sample Text"
</code>```

No need to deal with cell arrays anymore.

Title: Create an array of strings

Body:
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

for i=1:10
Names(i)='Sample Text';
end

I don't seem to be able to do it this way.

Body:
New features have been added to MATLAB recently:

String arrays were introduced in R2016b (as Budo and gnovice already mentioned):

String arrays store pieces of text and provide a set of functions for
  working with text as data. You can index into, reshape, and
  concatenate strings arrays just as you can with arrays of any other
  type.

In addition, starting in R2017a, you can create a string using double quotes "".

Therefore if your MATLAB version is >= R2017a, the following will do:

for i = 1:3
    Names(i) = "Sample Text";
end

Check the output:

>> Names

Names =

  1×3 string array

    "Sample Text"    "Sample Text"    "Sample Text"

No need to deal with cell arrays anymore.


问:
What is this syntax: "Component.For<IOutput>()"?
I'm finding code examples all over the place in IoC and DI discussions that use < and > in their syntax, usually at the end of what looks like a method call.

Can someone

Tell me what language this is, and

Explain this syntax enough to help me understand the code examples, so I can make sure I understand the underlying principles.

答:
They are part of the generics support in the framework.  They allow you to specify a type as part of the method (or class).  They are referred to as type parameters.

For instance you can have a strongly typed list, which relies upon you telling it what type it should accept:

```<code>List<string> myList;
</code>```

Allows it to accept types of string in the Add function.  The class definition for this would look something like:

```<code>public class List<T>
{
    public void Add(T item)
    {

    }
}
</code>```

When you created the List you told it to expect a type of string.  This is the type parameter T in the above class.  In the method Add it expects an instance of type T (in this instance a string).  Which means when you call Add on a List<string>, Add expects a string to be supplied.

Similarly if you created:

```<code>List<bool> myOtherList;
</code>```

The Add method would expect a bool parameter not a string parameter.

Body:
They are part of the generics support in the framework.  They allow you to specify a type as part of the method (or class).  They are referred to as type parameters.

For instance you can have a strongly typed list, which relies upon you telling it what type it should accept:

List<string> myList;

Allows it to accept types of string in the Add function.  The class definition for this would look something like:

public class List<T>
{
    public void Add(T item)
    {

    }
}

When you created the List you told it to expect a type of string.  This is the type parameter T in the above class.  In the method Add it expects an instance of type T (in this instance a string).  Which means when you call Add on a List<string>, Add expects a string to be supplied.

Similarly if you created:

List<bool> myOtherList;

The Add method would expect a bool parameter not a string parameter.


问:
how to get full servername and port running in mvc 2 by codebehind
hi every body i have a question

example if i have url : http://localhost:8512/bookuser/Create

how to get "http://localhost:8512" by code behind in mvc2 ??

thanks regard

答:
Try:

Request.Url.AbsoluteUri

This contains information about the page being requested.

Also, keep this link for future reference