问:
Trying to regex for strings longer than 22 characters
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

```<code>$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
</code>```

And here is the regex that I have come up with so far, which doesn't seem to work at all

```<code>'[A-Za-z]{20,40}'
</code>```

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

答:
I couldn't resist using the good ol' strlen.

```<code>foreach ($profiles as $id => $data) {
    if (strlen($data['name']) >= 22)
        unset($profiles[$id]);
}
</code>```

Body:
I have a very long array of data, and I need to quickly whizz through it and make sure that none of the names are longer than 22 characters. I understand that I could truncate it on the display side, but I would rather tackle this with a proper solution, of just removing them :)

This is my sample

$profiles[257] = array('name'=>'FedupKissingFrogs', 'age'=>27, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[260] = array('name'=>'Lil_Greta_90', 'age'=>20, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[262] = array('name'=>'lOOkfOrme86', 'age'=>24, 'sex'=>'F', 'location'=>'XXXXXXXXXX');
$profiles[259] = array('name'=>'youvefoundME', 'age'=>21, 'sex'=>'F', 'location'=>'XXXXXXXXXX');

And here is the regex that I have come up with so far, which doesn't seem to work at all

'[A-Za-z]{20,40}'

My plan is that I can use the regex to mark the lines and then I can delete them from within my IDE. There is no programming allowed ;)

-- Edit --

Thanks for all the replies! The idea behind this was a quick and automated way to just scan a flat PHP file containing an array to see if all the names where shorter than 22 characters, as a name longer than that will break the layout, and I've been asked to remove them. I wanted to just search in my IDE and remove the lines.

Matching the characters isn't important as such, any characters are allowable, even space, \ / ~ and * etc. I'm looking more to match length of the string but contained in the =>'$name' container.

Body:
I couldn't resist using the good ol' strlen.

foreach ($profiles as $id => $data) {
    if (strlen($data['name']) >= 22)
        unset($profiles[$id]);
}


来源: stackexchange

问:
Convert struct array to cell of structs and vice versa
I often have to work with struct arrays and cells containing scalar structs with identical fieldnames which I call an "unpacked struct array" and I wonder if there aren't already functions in Matlab and/or GNU Octave which helps converting between those two representations.

A struct array:

```<code>foo(1).a = 3;
foo(1).b = pi;
foo(2).a = 5;
foo(2).b = 2.718;
</code>```

Apparently num2cell works in one way in GNU Octave (although it isn't mentioned in the docs):

```<code>ret = num2cell (foo)
ret =
{
  [1,1] =

    scalar structure containing the fields:

      a =  3
      b =  3.1416

  [1,2] =

    scalar structure containing the fields:

      a =  5
      b =  2.7180

}
</code>```

But I'm looking for the reverse part, converting ret back to foo.

答:
This seems to do what you want:

```<code>foo2 = [ret{:}]; % or equivalently foo2 = horzcat(ret{:});
</code>```

That is, just concatenate the cell array's contents horizontally.

Check:

```<code>>> foo(1).a = 3;
foo(1).b = pi;
foo(2).a = 5;
foo(2).b = 2.718;
>> ret = num2cell (foo);
>> foo2 = [ret{:}];
>> isequal(foo, foo2)
ans =
  logical
   1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I often have to work with struct arrays and cells containing scalar structs with identical fieldnames which I call an "unpacked struct array" and I wonder if there aren't already functions in Matlab and/or GNU Octave which helps converting between those two representations.

A struct array:

foo(1).a = 3;
foo(1).b = pi;
foo(2).a = 5;
foo(2).b = 2.718;

Apparently num2cell works in one way in GNU Octave (although it isn't mentioned in the docs):

ret = num2cell (foo)
ret =
{
  [1,1] =

    scalar structure containing the fields:

      a =  3
      b =  3.1416

  [1,2] =

    scalar structure containing the fields:

      a =  5
      b =  2.7180

}

But I'm looking for the reverse part, converting ret back to foo.

Body:
This seems to do what you want:

foo2 = [ret{:}]; % or equivalently foo2 = horzcat(ret{:});

That is, just concatenate the cell array's contents horizontally.

Check:

>> foo(1).a = 3;
foo(1).b = pi;
foo(2).a = 5;
foo(2).b = 2.718;
>> ret = num2cell (foo);
>> foo2 = [ret{:}];
>> isequal(foo, foo2)
ans =
  logical
   1


问:
State set in WillMount() not accessible in DidMount()
I have a component that requires an API get request to retrieve some information on componentDidMount(). That get request relies on information stored in state that I am setting through functions called, on ComponentWillMount().

My willMount() runs, then I hit my render() method, but the state has not been set, and so then it hits didMount() but fails because the data is not in state yet. Where am I going wrong?

Edit: all functions are bound in the constructor (not shown)

```<code>componentWillMount() {
    this.enforceEmployeeAuth();
    this.loadEmployeeInfo();
  }

  componentDidMount() {
    this.fetchSurveyFields();
  }

  // Initial check to confirm if the user should be allowed to access any information.
  enforceEmployeeAuth() {
    // Get request to confirm that the current user is of type EMPLOYEE
    API.get("user/employee_auth", {}, (res) => {
      // Employee Auth: True if employee, else false
      this.setState({
        employee_auth: res.employee_auth,
      });
    });
  }

  // Load up relevant information for currentUser/employee
  loadEmployeeInfo() {
    API.get("client/currentEmployee", {}, function(res) {
      this.setState({
        employee              : res.employee,
        employee_company      : res.employee_company,
      })
    }.bind(this));
  }

  fetchSurveyFields() {
    debugger
    API.get('client/survey', {
      survey: this.state.employee_company.survey_name
    }, function(res) {
      debugger
    })
  }

  render() {

    debugger

    return (
      <h2 className="text-charcoal text-left">Employee Rubric</h2>
    )
  }
</code>```

答:
Your functions rely on asynchronous requests, which mean they set the state with requests' results after they've returned, if that makes sense.

In you render method, check for the validity of your state and return null if it's not valid. The render method will be called again next time the state is set (i.e. when your requests succeed because the state is set in their callbacks).

Body:
I have a component that requires an API get request to retrieve some information on componentDidMount(). That get request relies on information stored in state that I am setting through functions called, on ComponentWillMount().

My willMount() runs, then I hit my render() method, but the state has not been set, and so then it hits didMount() but fails because the data is not in state yet. Where am I going wrong?

Edit: all functions are bound in the constructor (not shown)

componentWillMount() {
    this.enforceEmployeeAuth();
    this.loadEmployeeInfo();
  }

  componentDidMount() {
    this.fetchSurveyFields();
  }

  // Initial check to confirm if the user should be allowed to access any information.
  enforceEmployeeAuth() {
    // Get request to confirm that the current user is of type EMPLOYEE
    API.get("user/employee_auth", {}, (res) => {
      // Employee Auth: True if employee, else false
      this.setState({
        employee_auth: res.employee_auth,
      });
    });
  }

  // Load up relevant information for currentUser/employee
  loadEmployeeInfo() {
    API.get("client/currentEmployee", {}, function(res) {
      this.setState({
        employee              : res.employee,
        employee_company      : res.employee_company,
      })
    }.bind(this));
  }

  fetchSurveyFields() {
    debugger
    API.get('client/survey', {
      survey: this.state.employee_company.survey_name
    }, function(res) {
      debugger
    })
  }

  render() {

    debugger

    return (

Employee Rubric

    )
  }


问:
In Android O, how to get any action on Success call back intent while pinning widget shortcut programmatically?
I am trying the API given in android O for pinning widget shortcut as given in

https://developer.android.com/guide/topics/appwidgets/index.html#Pinning

The sample code given is:

```<code>AppWidgetManager mAppWidgetManager = context.getSystemService(AppWidgetManager.class);
ComponentName myProvider = new ComponentName(context, MyAppWidgetProvider.class);

if (mAppWidgetManager.isRequestPinAppWidgetSupported()) {
    // Create the PendingIntent object only if your app needs to be notified
    // that the user allowed the widget to be pinned. Note that, if the pinning
    // operation fails, your app isn't notified.
    Intent pinnedWidgetCallbackIntent = new Intent( ... );

    // Configure the intent so that your app's broadcast receiver gets
    // the callback successfully. This callback receives the ID of the
    // newly-pinned widget (EXTRA_APPWIDGET_ID).
    PendingIntent successCallback = PendingIntent.createBroadcast(context, 0,
            pinnedWidgetCallbackIntent);

    mAppWidgetManager.requestPinAppWidget(myProvider, null, successCallback);
}
</code>```

In the above, if I am trying to get any activity through success Callback intent i.e the activity should open just after pinning shortcut, I am not getting it. Can anyone help?

答:
I have ran into this as well. Intent you are passing in should be for your implementation of BroadcastReceiver.

```<code>val callbackIntent = Intent(context, DemoWidgetPinnedReceiver::class.java)
val successCallback = PendingIntent.getBroadcast(
       context, 0, callbackIntent, PendingIntent.FLAG_UPDATE_CURRENT)
appWidgetManager.requestPinAppWidget(provider, null, successCallback)
</code>```

After widget is added successfully, you will get EXTRA_APPWIDGET_ID in the onReceive method of your BroadcastReceiver, and you can then save the ID. You shouldn't need to launch configuration activity after widget is pinned, as you can pass any values you want to save for the widget to into the callback intent.

I have written a blog post about this and also created a demo app, hope this helps!
https://medium.com/wearebase/android-oreo-widget-pinning-in-kotlin-398d529eab28
https://github.com/sigute/WidgetsDemo

Body:
I am trying the API given in android O for pinning widget shortcut as given in

https://developer.android.com/guide/topics/appwidgets/index.html#Pinning

The sample code given is:

AppWidgetManager mAppWidgetManager = context.getSystemService(AppWidgetManager.class);
ComponentName myProvider = new ComponentName(context, MyAppWidgetProvider.class);

if (mAppWidgetManager.isRequestPinAppWidgetSupported()) {
    // Create the PendingIntent object only if your app needs to be notified
    // that the user allowed the widget to be pinned. Note that, if the pinning
    // operation fails, your app isn't notified.
    Intent pinnedWidgetCallbackIntent = new Intent( ... );

    // Configure the intent so that your app's broadcast receiver gets
    // the callback successfully. This callback receives the ID of the
    // newly-pinned widget (EXTRA_APPWIDGET_ID).
    PendingIntent successCallback = PendingIntent.createBroadcast(context, 0,
            pinnedWidgetCallbackIntent);

    mAppWidgetManager.requestPinAppWidget(myProvider, null, successCallback);
}

In the above, if I am trying to get any activity through success Callback intent i.e the activity should open just after pinning shortcut, I am not getting it. Can anyone help?

Body:
I have ran into this as well. Intent you are passing in should be for your implementation of BroadcastReceiver.

val callbackIntent = Intent(context, DemoWidgetPinnedReceiver::class.java)
val successCallback = PendingIntent.getBroadcast(
       context, 0, callbackIntent, PendingIntent.FLAG_UPDATE_CURRENT)
appWidgetManager.requestPinAppWidget(provider, null, successCallback)

After widget is added successfully, you will get EXTRA_APPWIDGET_ID in the onReceive method of your BroadcastReceiver, and you can then save the ID. You shouldn't need to launch configuration activity after widget is pinned, as you can pass any values you want to save for the widget to into the callback intent.

I have written a blog post about this and also created a demo app, hope this helps!
https://medium.com/wearebase/android-oreo-widget-pinning-in-kotlin-398d529eab28
https://github.com/sigute/WidgetsDemo


问:
Binary tree traversal tree doesn't complete
I have made an Binary tree program for my presentation trying to make a postorder traversal using file input, turned out when the insertion step start the tree has only 1 node and then repeat until it read to the end of the file.
Any ideas what's went wrong here ?

this is the data i use in txt

5709611981  N   0623sweet@gmail.com A

5909680109  N   35563@bodin.ac.th   A

5909680059  N   a.supitcha@hotmail.com  A

5909610114  N   aladen009@hotmail.com   A

5909610031  N   aomsin3475@gmail.com    A

5909520024  N   apisittest@hotmail.com  A

5909680018  N   apstaan@gmail.com   A

5709650567  S   apuonn_ap@hotmail.com   A

5709650062  S   athachai-riders@hotmail.com A

5909610064  N   babe-anusorn@hotmail.com    A

5909650193  S   baifeern@gmail.com  A

5709650021  S   ball.bus@hotmail.com    A

5909610460  N   bambee18341@gmail.com   A

5909650011  S   bell12546789@gmail.com  A

5809650798  S   big__007@hotmail.com    A

Code:

```<code>class Person{
private:
    string id;
    string section;
    string status;
    string email;
public:
    Person();
    Person(string id,string section,string email,string status);
    string getID();
    string getSection();
    string getStatus();
    string getEmail();
    void setID(string newid);
    void setEmail(string newEmail);
    void setSection(string newsection);
    void setStatus(string newstatus);
    };

    class BinarySearchTree
    {
private:
    struct tree_node
    {
        tree_node* left;
        tree_node* right;
        Person data;
    };
    tree_node* root;

public:
    BinarySearchTree()
    {
        root = NULL;
    }

    bool isEmpty() const { return root == NULL;}
    void print_postorder();
    void postorder(tree_node*);
    void print_preorder();
    void preorder(tree_node*);
    void insert(Person);
    void remove(string);
    void search(string key);
    void changeStatus(string key,string newstatus);
    };

    Person::Person()
    {

    }

    Person::Person(string newid,string newsection,string newemail,string newstatus){
id = newid;
section = newsection;
email = newemail;
status = newstatus;
     }
     string Person::getID(){
return id;
       }
     string Person::getSection(){
return section;
       }
     string Person::getEmail(){
return email;
       }
     string Person::getStatus(){
return status;
       }
     void Person::setStatus(string newstatus){
status = newstatus;
       }
     void Person::setID(string newid){
status = newid;
       }
     void Person::setEmail(string newemail){
status = newemail;
       }
     void Person::setSection(string newsection){
status = newsection;
       }
       void BinarySearchTree::insert(Person p){
tree_node* t = new tree_node;
tree_node* parent;
t->data = p;
t->left = NULL;
t->right = NULL;
parent = NULL;

if(isEmpty()) root = t;
else{
    tree_node* curr;
    curr = root;
    while(curr)
    {
        parent = curr;
        if(t->data.getID() > curr->data.getID()){
        curr=curr->right;
        }
        else{
            curr = curr->left;
        }
    }

    if(t->data.getID() < parent->data.getID()){
        parent->left = t;
    }
    else{
        parent->right = t;
            }
         }
      }

              void BinarySearchTree::print_postorder(){
    postorder(root);
}

void BinarySearchTree::postorder(tree_node* p)
{
    if(p != NULL)
    {
        if(p->left){
            postorder(p->left);
        }
        if(p->right){
            postorder(p->right);
        }
        cout<<" "<<p->data.getID() << " " << endl ;
    }
    else {
    cout<<" NULL P " << endl ;
    return;
    }
}

void BinarySearchTree::search(string key){
    bool found = false;

    tree_node* curr;
    tree_node* parent;
    curr = root;
    while(curr != NULL){
        if(curr->data.getID() == key){
            found = true ;
            cout << "Contact Email : " << curr->data.getEmail() << endl;
        }
        else
        {
            parent = curr;
            if(key>curr->data.getID()){
                curr = curr->right;
            }
            else curr = curr->left;
        }
    }
    if(!found){
        cout<<" This student is not in this class. " << endl;
        return;
    }

}

void fillTree(BinarySearchTree b)
{
ifstream file;
file.open("classlist60.txt");
if(!file){
    cout << "File error." << endl;
}

string id;
string section;
string email;
string status;
Person p;
int count = 0;
int halt = 0 ;
while(file >> id >> section >> email >> status)
{
    p.setID(id);
    p.setSection(section);
    p.setEmail(email);
    p.setStatus(status);
    count++;
    if(status == "W"){
        halt++;
    }
    b.insert(p);
}
b.print_postorder();

cout << endl <<  " Total registered students :" << count << endl;
cout <<  " Num of withdrawal Students :" << halt << endl;
file.close();
}

int main(){
BinarySearchTree b;
string id;
string email;
fillTree(b);

cout << endl << " Search Email for student ID : " ;
cin >> id;
b.search(id);

return 0;
}
</code>```

The result is:

The result supposed to be all the detail of students in Postorder and can be search via Input turned out tree is almost empty

答:
In your insert function, you link the parent to the node t, but you don't link the node t to the node it's replacing. So you end up losing what the parent was pointing to. You need to insert the new node between the parent and its child.

The idea is the same as inserting into a linked list. Before you insert, you have:

```<code>          parent
          /    \
       child  child
</code>```

Your code is doing this:

```<code>          parent
          /    \
       child    t
</code>```

But what you want is this:

```<code>          parent
          /    \
       child    t
                 \
               child
</code>```

That's a simple modification to your code:

```<code>if(t->data.getID() < parent->data.getID()){
    t->left = parent->left;  // link to parent's previous child
    parent->left = t;
}
else{
    t->right = parent->right;  // link to parent's previous child
    parent->right = t;
        }
     }
  }
</code>```

Body:
I have made an Binary tree program for my presentation trying to make a postorder traversal using file input, turned out when the insertion step start the tree has only 1 node and then repeat until it read to the end of the file.
Any ideas what's went wrong here ?

this is the data i use in txt

5709611981  N   0623sweet@gmail.com A

5909680109  N   35563@bodin.ac.th   A

5909680059  N   a.supitcha@hotmail.com  A

5909610114  N   aladen009@hotmail.com   A

5909610031  N   aomsin3475@gmail.com    A

5909520024  N   apisittest@hotmail.com  A

5909680018  N   apstaan@gmail.com   A

5709650567  S   apuonn_ap@hotmail.com   A

5709650062  S   athachai-riders@hotmail.com A

5909610064  N   babe-anusorn@hotmail.com    A

5909650193  S   baifeern@gmail.com  A

5709650021  S   ball.bus@hotmail.com    A

5909610460  N   bambee18341@gmail.com   A

5909650011  S   bell12546789@gmail.com  A

5809650798  S   big__007@hotmail.com    A

Code:

class Person{
private:
    string id;
    string section;
    string status;
    string email;
public:
    Person();
    Person(string id,string section,string email,string status);
    string getID();
    string getSection();
    string getStatus();
    string getEmail();
    void setID(string newid);
    void setEmail(string newEmail);
    void setSection(string newsection);
    void setStatus(string newstatus);
    };

    class BinarySearchTree
    {
private:
    struct tree_node
    {
        tree_node* left;
        tree_node* right;
        Person data;
    };
    tree_node* root;

public:
    BinarySearchTree()
    {
        root = NULL;
    }

    bool isEmpty() const { return root == NULL;}
    void print_postorder();
    void postorder(tree_node*);
    void print_preorder();
    void preorder(tree_node*);
    void insert(Person);
    void remove(string);
    void search(string key);
    void changeStatus(string key,string newstatus);
    };

    Person::Person()
    {

    }

    Person::Person(string newid,string newsection,string newemail,string newstatus){
id = newid;
section = newsection;
email = newemail;
status = newstatus;
     }
     string Person::getID(){
return id;
       }
     string Person::getSection(){
return section;
       }
     string Person::getEmail(){
return email;
       }
     string Person::getStatus(){
return status;
       }
     void Person::setStatus(string newstatus){
status = newstatus;
       }
     void Person::setID(string newid){
status = newid;
       }
     void Person::setEmail(string newemail){
status = newemail;
       }
     void Person::setSection(string newsection){
status = newsection;
       }
       void BinarySearchTree::insert(Person p){
tree_node* t = new tree_node;
tree_node* parent;
t->data = p;
t->left = NULL;
t->right = NULL;
parent = NULL;

if(isEmpty()) root = t;
else{
    tree_node* curr;
    curr = root;
    while(curr)
    {
        parent = curr;
        if(t->data.getID() > curr->data.getID()){
        curr=curr->right;
        }
        else{
            curr = curr->left;
        }
    }

    if(t->data.getID() < parent->data.getID()){
        parent->left = t;
    }
    else{
        parent->right = t;
            }
         }
      }

              void BinarySearchTree::print_postorder(){
    postorder(root);
}

void BinarySearchTree::postorder(tree_node* p)
{
    if(p != NULL)
    {
        if(p->left){
            postorder(p->left);
        }
        if(p->right){
            postorder(p->right);
        }
        cout<<" "<
data.getID() << " " << endl ;
    }
    else {
    cout<<" NULL P " << endl ;
    return;
    }
}

void BinarySearchTree::search(string key){
    bool found = false;

    tree_node* curr;
    tree_node* parent;
    curr = root;
    while(curr != NULL){
        if(curr->data.getID() == key){
            found = true ;
            cout << "Contact Email : " << curr->data.getEmail() << endl;
        }
        else
        {
            parent = curr;
            if(key>curr->data.getID()){
                curr = curr->right;
            }
            else curr = curr->left;
        }
    }
    if(!found){
        cout<<" This student is not in this class. " << endl;
        return;
    }

}

void fillTree(BinarySearchTree b)
{
ifstream file;
file.open("classlist60.txt");
if(!file){
    cout << "File error." << endl;
}

string id;
string section;
string email;
string status;
Person p;
int count = 0;
int halt = 0 ;
while(file >> id >> section >> email >> status)
{
    p.setID(id);
    p.setSection(section);
    p.setEmail(email);
    p.setStatus(status);
    count++;
    if(status == "W"){
        halt++;
    }
    b.insert(p);
}
b.print_postorder();

cout << endl <<  " Total registered students :" << count << endl;
cout <<  " Num of withdrawal Students :" << halt << endl;
file.close();
}

int main(){
BinarySearchTree b;
string id;
string email;
fillTree(b);

cout << endl << " Search Email for student ID : " ;
cin >> id;
b.search(id);

return 0;
}

The result is:

The result supposed to be all the detail of students in Postorder and can be search via Input turned out tree is almost empty

Body:
In your insert function, you link the parent to the node t, but you don't link the node t to the node it's replacing. So you end up losing what the parent was pointing to. You need to insert the new node between the parent and its child.

The idea is the same as inserting into a linked list. Before you insert, you have:

          parent
          /    \
       child  child

Your code is doing this:

          parent
          /    \
       child    t

But what you want is this:

          parent
          /    \
       child    t
                 \
               child

That's a simple modification to your code:

if(t->data.getID() < parent->data.getID()){
    t->left = parent->left;  // link to parent's previous child
    parent->left = t;
}
else{
    t->right = parent->right;  // link to parent's previous child
    parent->right = t;
        }
     }
  }


答: How about you pass the authorization token as a prop from a parent component, and then use componentWillReceiveProps hook to fire off the request to the API?</p>

Title: State set in WillMount() not accessible in DidMount()


问:
rxjs: how to order responses via Observables

I am using socket.io to send a series of responses to my front-end. The responses are intended to be sequential, but depending on the connection created by socket.io they're not always guaranteed to come in the correct order (https://github.com/josephg/ShareJS/issues/375).

Assuming each response had a sequence field that held a number (shown as the number in the picture above), the observable should emit these responses in order.

If a response is received out of order and a certain amount of time (n) passes without getting any response, I would like for my observable to emit an error, to signal to my front-end to reset the connection.

答:
A really nice problem. Below a snippet with most important parts commented.

// mock ordered values
const mockMessages = Rx.Observable.fromEvent(document.querySelector('#emit'), 'click')
  .map((e, index) => ({
    index,
    timestamp: e.timeStamp
  }))
  .delayWhen(() => Rx.Observable.timer(Math.random() * 2000)) // distort order

// there is a lot of mutability in `keepOrder`, but all of it
// is sealed and does not leak to outside environment
const keepOrder = timeoutMs => stream =>
  Rx.Observable.defer(() => // need defer to support retries on error
    stream.scan((acc, v) => {
      acc.buffer.push(v)
      acc.buffer.sort((v1, v2) => v1.index - v2.index)
      return acc
    }, {
      lastEmitted: -1,
      buffer: []
    })
    .mergeMap(info => {
      const emission = []
      while (info.buffer.length && info.lastEmitted + 1 === info.buffer[0].index) {
        emission.push(info.buffer.shift())
        info.lastEmitted += 1
      }
      return Rx.Observable.of(emission)
    })
    .switchMap(emissions => {
      if (!emissions.length) { // this condition indicates out of order
        return Rx.Observable.timer(timeoutMs)
          .mergeMapTo(Rx.Observable
            .throw(new Error('ORDER_TIMEOUT')))
      } else {
        return Rx.Observable.from(emissions)
      }
    })
  )

mockMessages
  .do(x => console.log('mocked', x.index))
  .let(keepOrder(1000)) // decrease timeoutMs to increase error probablity
  .do(x => console.log('ORDERED', x.index))
  .retryWhen(es => es
    .do(e => console.warn('ERROR', e)))
  .subscribe()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>

<button id="emit">EMIT</button></code>```

Body:
A really nice problem. Below a snippet with most important parts commented.

// mock ordered values
const mockMessages = Rx.Observable.fromEvent(document.querySelector('#emit'), 'click')
  .map((e, index) => ({
    index,
    timestamp: e.timeStamp
  }))
  .delayWhen(() => Rx.Observable.timer(Math.random() * 2000)) // distort order

// there is a lot of mutability in `keepOrder`, but all of it
// is sealed and does not leak to outside environment
const keepOrder = timeoutMs => stream =>
  Rx.Observable.defer(() => // need defer to support retries on error
    stream.scan((acc, v) => {
      acc.buffer.push(v)
      acc.buffer.sort((v1, v2) => v1.index - v2.index)
      return acc
    }, {
      lastEmitted: -1,
      buffer: []
    })
    .mergeMap(info => {
      const emission = []
      while (info.buffer.length && info.lastEmitted + 1 === info.buffer[0].index) {
        emission.push(info.buffer.shift())
        info.lastEmitted += 1
      }
      return Rx.Observable.of(emission)
    })
    .switchMap(emissions => {
      if (!emissions.length) { // this condition indicates out of order
        return Rx.Observable.timer(timeoutMs)
          .mergeMapTo(Rx.Observable
            .throw(new Error('ORDER_TIMEOUT')))
      } else {
        return Rx.Observable.from(emissions)
      }
    })
  )

mockMessages
  .do(x => console.log('mocked', x.index))
  .let(keepOrder(1000)) // decrease timeoutMs to increase error probablity
  .do(x => console.log('ORDERED', x.index))
  .retryWhen(es => es
    .do(e => console.warn('ERROR', e)))
  .subscribe()

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>

<button id="emit">EMIT</button>


问:
Origins of the most popular file serving pattern in web
Most modern file upload/sharing services, apart from having lots of ads and constantly offering you to buy a subscription, also share the same design pattern: when you are ready to download a file they typically write something like "Your download should start automatically in 5 seconds. Click here to download manually."

What rationale stands behind this behavior? Where did it come from? Why don't they just send a redirect or open a temporary link in another window (via target="_blank")? TIA

答: They probably sell premium ads on those pages, because most people will be looking at the ads while they wait for their download to finish. Guaranteed viewage is gold.</p>

ContentLicense: CC BY-SA 2.5


问:
Can I share a service between Angular and Node?
I have a standard utility service in my Angular5 Typescript app.
I want to share that with my node application, which is serving the app.

I can't find any info around it but I see issues as:

Using require() to import a TS file, and if the generated js file
lives in the same place

Ignoring the @Injectable which is a decorator
used on the angular service.

I assume it's possible as that's a major benefit of using full stack Javascript, but how can it be done?

I've  tried the following in NodeJs, which throws an error:

```<code>const utilService = require('../../src/app/services/util/util.service');
</code>```

答:
You can't, typescript it's not valid javascript.

For that to work you would also have to compile your node code, basically having two different typescript configs, one targeting browsers, and another one with a different entry point, targeting node.

If you do that, then you will be able to share some code between your backend and front end. Although services that use the @injectable() decorator, won't work. Why? there isn't any Injector available to handle your dependency injections.

Body:
I have a standard utility service in my Angular5 Typescript app.
I want to share that with my node application, which is serving the app.

I can't find any info around it but I see issues as:

Using require() to import a TS file, and if the generated js file
lives in the same place

Ignoring the @Injectable which is a decorator
used on the angular service.

I assume it's possible as that's a major benefit of using full stack Javascript, but how can it be done?

I've  tried the following in NodeJs, which throws an error:

const utilService = require('../../src/app/services/util/util.service');


问:
Notice: Undefined property: DOMDocument::$documentElement
I recently re-opened an old (1 year) Symfony project and I am having an error on every page (I don't remember having this issue a year ago) :

```<code>[exception] 500 | Internal Server Error | Symfony\Component\Config\Exception\FileLoaderLoadException
/var/www/[...]/wdt.xml

ContextErrorException: Notice: Undefined property: DOMDocument::$documentElement
</code>```

If I clear the cache, the error disappear but as soon as I edit and save a file, the error is showing up again.
The project was using Symfony 2.8 and I updated to Symfony 3.2 but it didn't solve the issue.

I don't think the problem is related to the wdt.xml file and I think it might be related to my laptop config.

I don't really know where to start to investigate so any suggestion is welcome!

Edit 1 :

I am actually having the same problem with another project I created few days ago. The project don't use any additional bundles and I just created 5 entities and generated the MySQL database.

Edit 2 :

After some more researched, I decided to create a new Ubuntu VM and test a new Symfony project and it just work perfectly so it must be something to do with the configuration on my laptop.

Edit 3 :

After some more tests, here is what I get when I add a print_r($dom); in the file XmlUtils.php (vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php) line 59 :

Ubuntu VM (no error) :

```<code>DOMDocument Object ( [doctype] => [implementation] => (object value omitted) [documentElement] => (object value omitted) [actualEncoding] => [encoding] => [xmlEncoding] => [standalone] => 1 [xmlStandalone] => 1 [version] => 1.0 [xmlVersion] => 1.0 [strictErrorChecking] => 1 [documentURI] => /var/www/my_project/web/ [config] => [formatOutput] => [validateOnParse] => 1 [resolveExternals] => [preserveWhiteSpace] => 1 [recover] => [substituteEntities] => [nodeName] => #document [nodeValue] => [nodeType] => 9 [parentNode] => [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => [attributes] => [ownerDocument] => [namespaceURI] => [prefix] => [localName] => [baseURI] => /var/www/my_project/web/ [textContent] => %kernel.charset% %kernel.default_locale% )
</code>```

Ubuntu laptop (error) :

```<code>DOMDocument Object ( [validateOnParse] => 1 [nodeName] => #document [nodeValue] => [nodeType] => 9 [parentNode] => [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => [attributes] => [ownerDocument] => [namespaceURI] => [prefix] => [localName] => [baseURI] => /var/www/lab/symfony/booklib/web/ [textContent] => %kernel.charset% %kernel.default_locale% )
</code>```

It looks like there is some missing information on my laptop...

So basically, the function $dom->loadXML doesn't return the same value on my laptop environment and inside the VM... any idea why?

答: I solved the problem by disabling xdebug for the cli</p>

Body:
I recently re-opened an old (1 year) Symfony project and I am having an error on every page (I don't remember having this issue a year ago) :

[exception] 500 | Internal Server Error | Symfony\Component\Config\Exception\FileLoaderLoadException
/var/www/[...]/wdt.xml

ContextErrorException: Notice: Undefined property: DOMDocument::$documentElement

If I clear the cache, the error disappear but as soon as I edit and save a file, the error is showing up again.
The project was using Symfony 2.8 and I updated to Symfony 3.2 but it didn't solve the issue.

I don't think the problem is related to the wdt.xml file and I think it might be related to my laptop config.

I don't really know where to start to investigate so any suggestion is welcome!

Edit 1 :

I am actually having the same problem with another project I created few days ago. The project don't use any additional bundles and I just created 5 entities and generated the MySQL database.

Edit 2 :

After some more researched, I decided to create a new Ubuntu VM and test a new Symfony project and it just work perfectly so it must be something to do with the configuration on my laptop.

Edit 3 :

After some more tests, here is what I get when I add a print_r($dom); in the file XmlUtils.php (vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php) line 59 :

Ubuntu VM (no error) :

DOMDocument Object ( [doctype] => [implementation] => (object value omitted) [documentElement] => (object value omitted) [actualEncoding] => [encoding] => [xmlEncoding] => [standalone] => 1 [xmlStandalone] => 1 [version] => 1.0 [xmlVersion] => 1.0 [strictErrorChecking] => 1 [documentURI] => /var/www/my_project/web/ [config] => [formatOutput] => [validateOnParse] => 1 [resolveExternals] => [preserveWhiteSpace] => 1 [recover] => [substituteEntities] => [nodeName] => #document [nodeValue] => [nodeType] => 9 [parentNode] => [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => [attributes] => [ownerDocument] => [namespaceURI] => [prefix] => [localName] => [baseURI] => /var/www/my_project/web/ [textContent] => %kernel.charset% %kernel.default_locale% )

Ubuntu laptop (error) :

DOMDocument Object ( [validateOnParse] => 1 [nodeName] => #document [nodeValue] => [nodeType] => 9 [parentNode] => [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => [attributes] => [ownerDocument] => [namespaceURI] => [prefix] => [localName] => [baseURI] => /var/www/lab/symfony/booklib/web/ [textContent] => %kernel.charset% %kernel.default_locale% )

It looks like there is some missing information on my laptop...

So basically, the function $dom->loadXML doesn't return the same value on my laptop environment and inside the VM... any idea why?


答:
You should save the promises returned by both api calls. And then on resolution of those in componentDidMount, you should make api call for fetchSurveyFields. Like this</p>

```<code>  componentWillMount() {
    this.promises = [];

    this.promises.push(this.enforceEmployeeAuth());
    this.promises.push(this.loadEmployeeInfo());
  }

  componentDidMount() {
    Promise.all(this.promises)
      .then(([resp1, resp2]) => {
         //You can see here if you still wanna set state.
         this.fetchSurveyFields();
      });

  }

  // Initial check to confirm if the user should be allowed to access any information.
  enforceEmployeeAuth() {
    // Get request to confirm that the current user is of type EMPLOYEE
    API.get("user/employee_auth", {}, (res) => {
      // Employee Auth: True if employee, else false
      this.setState({
        employee_auth: res.employee_auth,
      });
    });
  }

  // Load up relevant information for currentUser/employee
  loadEmployeeInfo() {
    API.get("client/currentEmployee", {}, function(res) {
      this.setState({
        employee              : res.employee,
        employee_company      : res.employee_company,
      })
    }.bind(this));
  }

  fetchSurveyFields() {
    debugger
    API.get('client/survey', {
      survey: this.state.employee_company.survey_name
    }, function(res) {
      debugger
    })
  }

  render() {

    debugger

    return (
      <h2 className="text-charcoal text-left">Employee Rubric</h2>
    )
  }
</code>```

Body:
You should save the promises returned by both api calls. And then on resolution of those in componentDidMount, you should make api call for fetchSurveyFields. Like this

  componentWillMount() {
    this.promises = [];

    this.promises.push(this.enforceEmployeeAuth());
    this.promises.push(this.loadEmployeeInfo());
  }

  componentDidMount() {
    Promise.all(this.promises)
      .then(([resp1, resp2]) => {
         //You can see here if you still wanna set state.
         this.fetchSurveyFields();
      });

  }

  // Initial check to confirm if the user should be allowed to access any information.
  enforceEmployeeAuth() {
    // Get request to confirm that the current user is of type EMPLOYEE
    API.get("user/employee_auth", {}, (res) => {
      // Employee Auth: True if employee, else false
      this.setState({
        employee_auth: res.employee_auth,
      });
    });
  }

  // Load up relevant information for currentUser/employee
  loadEmployeeInfo() {
    API.get("client/currentEmployee", {}, function(res) {
      this.setState({
        employee              : res.employee,
        employee_company      : res.employee_company,
      })
    }.bind(this));
  }

  fetchSurveyFields() {
    debugger
    API.get('client/survey', {
      survey: this.state.employee_company.survey_name
    }, function(res) {
      debugger
    })
  }

  render() {

    debugger

    return (
      <h2 className="text-charcoal text-left">Employee Rubric</h2>
    )
  }


问:
setlocale and strftime not translating month
My code:

```<code>setlocale(LC_TIME, 'ca_ES');
echo strftime("%#d %B", strtotime($ticket->date_created));
</code>```

outputs something like:

```<code>28 August
</code>```

instead of my expectation:

```<code>28 Agost
</code>```

I expect "Agost" because that is Catalan language (set through setlocale()).

Is this how setlocale and strftime is supposed to work?

FYI: My local development machine is Windows 7, set to locale: en-PH

答:
On Debian 9 setlocale(LC_TIME, 'fr_FR.UTF8'); did the job for me to get nicely french formatted day/month display. Make sure to have the locales installed with the following sequence:

apt-get install locales

dpkg-reconfigure locales

Body:
My code:

setlocale(LC_TIME, 'ca_ES');
echo strftime("%#d %B", strtotime($ticket->date_created));

outputs something like:

28 August

instead of my expectation:

28 Agost

I expect "Agost" because that is Catalan language (set through setlocale()).

Is this how setlocale and strftime is supposed to work?

FYI: My local development machine is Windows 7, set to locale: en-PH


问:
Excel 2016 insert copies cells is incredibly slow
I have a rather large sheet (approx 60K rows by 50 cols). I'm trying to copy several (2 to 8) rows into clipboard and then insert copied cells. This operation takes more than a minute to complete!

I've tried disabling automatic calculations, initiating this operation from VBA, like this:

```<code>Range("A1").Insert xlShiftDown
</code>```

to no available. If I paste (Ctrl-V) rather than insert it works like a snap.

Any ideas how to work around this issue?

答:
Since you can paste the data quickly enough use that instead of inserting, then sort the rows:

In an empty column on the first row of data type the number of rows you want to insert plus 1 (e.g. to insert 3 rows type 4)

Add the next number in the next row, then select both cells and autocomplete the column so that each row has an increasing number

Paste the new data at the end of the old data, immediately after the last row

Number the first row pasted as 1, the 2nd as 2 etc

Sort the sheet ascending on the number column then delete the column

Body:
I have a rather large sheet (approx 60K rows by 50 cols). I'm trying to copy several (2 to 8) rows into clipboard and then insert copied cells. This operation takes more than a minute to complete!

I've tried disabling automatic calculations, initiating this operation from VBA, like this:

Range("A1").Insert xlShiftDown

to no available. If I paste (Ctrl-V) rather than insert it works like a snap.

Any ideas how to work around this issue?


问:
How to get image name from UIImagePickerControllerPHAsset taken with library or camera?
I want to get the file name from UIImagePickerControllerPHAsset in ios 11.0.3. unable to get picked image file name using this code. please help on this?

```<code>  if #available(iOS 11.0, *) {
                let asset = info[UIImagePickerControllerPHAsset] as? PHAsset
                fileName = ((asset?.value(forKey: "filename")) as? String)!
            } else {
                // Fallback on earlier versions
                let url = info[UIImagePickerControllerReferenceURL] as! URL
                let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
                fileName = PHAssetResource.assetResources(for: assets.firstObject!).first!.originalFilename
            }
</code>```

Getting crashes on fileName = ((asset?.value(forKey: "filename")) as? String)!

答:
It seems like Apple has not added the new iOS 11 key to the info dictionary. Therefore the iOS 11 code will no work as it keeps returning nil. See this open radar http://www.openradar.me/34404703

Only solution I found so far is to use the iOS 10 code block even in iOS 11 and just ignore the UIImagePickerControllerReferenceURL deprecated message (the key still exists and works in iOS 11)

Hope this helps

Body:
I want to get the file name from UIImagePickerControllerPHAsset in ios 11.0.3. unable to get picked image file name using this code. please help on this?

  if #available(iOS 11.0, *) {
                let asset = info[UIImagePickerControllerPHAsset] as? PHAsset
                fileName = ((asset?.value(forKey: "filename")) as? String)!
            } else {
                // Fallback on earlier versions
                let url = info[UIImagePickerControllerReferenceURL] as! URL
                let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
                fileName = PHAssetResource.assetResources(for: assets.firstObject!).first!.originalFilename
            }

Getting crashes on fileName = ((asset?.value(forKey: "filename")) as? String)!


问:
Phalcon framework Assets manager : "/index.php" is always prepended in the assets path when ouput
I'm new to phalcon framework but it seems great!

Recently I decided to use assets manager in my project but an issue occurred.
when I try to output the added assets, it prints the path with '/index.php' prepended...

I put this code into controller's indexAction:

```<code>$this->assets
   ->collection("commonJs")
   ->addJs('js/draggable.js')
   ->addJs('js/common.js')
   ->addFilter( new Phalcon\Assets\Filters\Jsmin()  );

$this->assets
    ->collection('commonCss')
    ->addCss('css/material-icons.css',true,false)
    ->addcss('css/common.css',true,true)
    ->addFilter(new Phalcon\Assets\Filters\Cssmin());
</code>```

and use this inside volt to ouput the assets:

```<code> <head>
 ....
 {{ assets.outputJs('commonJs')}}
 </head>
 <body>
 ...
 {{ assets.outputJs('commoCss')}}
 </body>
</code>```

but the printed output seems a little wierd:

I think it should prints the path like

```<code><link rel="stylesheet" type='text/css'  href='css/common.css'>
</code>```

or

```<code> <script type='text/javascript' src='js/common.js'>
</code>```

but it actually outputs like this:

```<code> <link rel="stylesheet" type='text/css'  href='/index.phpcss/common.css'>
..
 <script type='text/javascript' src='/index.phpjs/common.js'>
</code>```

or if i set the path in the addJs like '/js/...' instead of 'js/...'
then output is :

```<code> <script type='text/javascript' src='/index.php/js/...'>
</code>```

I'm new to phalcon and I don't know what I'm doing wrong and how to remove prepended index.php in the output path.

Could someone please help me on this?

FYI, I'm using nginx with php7.1 & fpm and my nginx-site.conf is like below, which is almost same as phalcon documentation :

```<code>server {
         listen       80;
         root /var/www2/public;
         index index.html index.htm index.php;

         # Make site accessible from http://localhost/
         server_name tpnew.dev;

     error_log  /usr/local/var/log/nginx/newtp.error.log; #debug;
     log_not_found off;

     location / {
         try_files $uri $uri/ /index.php?_url=$uri&$args;
     #   try_files $uri $uri/ @rewrite;
     }

 location ~ \.php$ {
     try_files      $uri = 404;
     fastcgi_pass   127.0.0.1:9000; # php71
     fastcgi_index  /index.php;
     fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include        fastcgi_params;

     fastcgi_split_path_info  ^(.+\.php)(/.+)$;
     fastcgi_param PATH_INFO       $fastcgi_path_info;
     fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
     fastcgi_param SERVER_NAME $server_name;
 }
     location ~ /\.ht {
         deny all;
     }

 }
</code>```

答: In yout Nginx configuration, try to change this line fastcgi_index /index.php; to fastcgi_index /;.

Body:
I'm new to phalcon framework but it seems great!

Recently I decided to use assets manager in my project but an issue occurred.
when I try to output the added assets, it prints the path with '/index.php' prepended...

I put this code into controller's indexAction:

$this->assets
   ->collection("commonJs")
   ->addJs('js/draggable.js')
   ->addJs('js/common.js')
   ->addFilter( new Phalcon\Assets\Filters\Jsmin()  );

$this->assets
    ->collection('commonCss')
    ->addCss('css/material-icons.css',true,false)
    ->addcss('css/common.css',true,true)
    ->addFilter(new Phalcon\Assets\Filters\Cssmin());

and use this inside volt to ouput the assets:

 ....
 {{ assets.outputJs('commonJs')}}

 ...
 {{ assets.outputJs('commoCss')}}

but the printed output seems a little wierd:

I think it should prints the path like

<link rel="stylesheet" type='text/css'  href='css/common.css'>

or


问:
How to change local time for testing purposes?
I'm writing a script, that is based on the current time and it works fine, but I don't want to wait, so I can see, if the script works tomorrow, in 2, 3, 4 days, or a year.

Is there a way to trick the apache server (using php preferred) into thinking that it's a different time? :-)

And if so, is it easy to fix back withnout any perpament consequences?

答:
Agree with middaparka - changing the local time is all well and good if you're running your script locally, but what about when it's running on a server because it depends on a data/session/something else?

The answer is to just set a variable at the top of your script called $time and set it to time(), then use $time throughout your script instead of time().  Then, when you want to change the time for testing purposes, you only need to change that one line.


问:
AngularJs - .success is not a function after minification
I'm using angularJS(v1.5.7) in my MVC application. During the development, we used the syntax bellow to make ajax calling::

$http({
  method: 'GET',
  url: "",
  params: { }
}).success(function (data) {
  ...
}).finally(function () {
  ...
});```

When I published my application on the server, I'm using bundle to minify my javascript files.

After that, I'm geting the error: ".success is not a function"

Does anybody knows why this issue happen only when I minify the files?

答:
In AngularJS (v1.5.7) there is no any  .success event so instead of that in your version use .then for RESTAPI call

```<code>$http({
  method: 'GET',
  url: '/Url'
}).then(function successCallback(response) {

  }, function errorCallback(response) {

  });
</code>```

For more details you can visit this page
https://docs.angularjs.org/api/ng/service/$http

Body:
I'm using angularJS(v1.5.7) in my MVC application. During the development, we used the syntax bellow to make ajax calling::

$http({
  method: 'GET',
  url: "",
  params: { }
}).success(function (data) {
  ...
}).finally(function () {
  ...
});

When I published my application on the server, I'm using bundle to minify my javascript files.

After that, I'm geting the error: ".success is not a function"

Does anybody knows why this issue happen only when I minify the files?

Body:
In AngularJS (v1.5.7) there is no any  .success event so instead of that in your version use .then for RESTAPI call

$http({
  method: 'GET',
  url: '/Url'
}).then(function successCallback(response) {

  }, function errorCallback(response) {

  });

For more details you can visit this page
https://docs.angularjs.org/api/ng/service/$http


问:
What is better: WHERE n = 0 or WHERE n != 1
I'm making a lot of times a query which have almost always a condition for "hidden" status in Mysql DB.

A piece is this:

```<code>...
WHERE `price` >= '7500'
AND `ads`.`subcat_id` = '22'
AND `recycle_bin` != 1
AND `hidden` =0
...
</code>```

So, an idea came into my mind... what's most optimal?
This:

```<code>AND `recycle_bin` != 1
</code>```

or this:

```<code>AND `recycle_bin` = 0
</code>```

or both?

答: In my opinion it makes no difference  , both options are as optimal and as efficient , I think it's more of a personal preference</p>

Body:
I'm making a lot of times a query which have almost always a condition for "hidden" status in Mysql DB.

A piece is this:

...
WHERE `price` >= '7500'
AND `ads`.`subcat_id` = '22'
AND `recycle_bin` != 1
AND `hidden` =0
...

So, an idea came into my mind... what's most optimal?
This:

AND `recycle_bin` != 1

or this:

AND `recycle_bin` = 0

or both?


问:
Push notifications from Azure Notification Hub (Xamarin.iOS)
I have tried Android and Windows push notifications and all works fine. However, on the iOS side, something wrong.

I am trying to add push notifications to my Xamarin.iOS app using these tutorials

https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-ios-push-notification-apns-get-started

https://blog.xamarin.com/push-notifications-ios-azure-notification-hubs/

From Azure Test Send I got "Message was successfully sent, but there were no matching targets."

I have followed all the steps as it is but when I put a breakpoint,  I always get "IsRegistered =false":

AppDelegate.cs

```<code>private SBNotificationHub Hub { get; set; }
    public const string ConnectionString = "Endpoint=sb://...";
    public const string NotificationHubPath = "NotificationHubName...";

     public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
            {
                // Set our preferred notification settings for the app
                var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet());

                // Register for notifications
                UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
                bool IsRegistered = UIApplication.SharedApplication.IsRegisteredForRemoteNotifications;

                return true;
            }
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            Hub = new SBNotificationHub(ConnectionString, NotificationHubPath);
            Hub.UnregisterAllAsync(deviceToken, (error) =>
            {
                if (error != null)
                {
                    // Error unregistering
                    return;
                }
                // Register this device with the notification hub
                Hub.RegisterNativeAsync(deviceToken, null, (registerError) =>
                {
                    if (registerError != null)
                    {
                        // Error registering
                    }
                });
            });
        }

        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            if (null != userInfo && userInfo.ContainsKey(new NSString("aps")))
            {
                // Get the aps dictionary from the alert payload
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
            }
        }
</code>```

My questions are;

Why am I not registering?

How can I learn why am I not registering?

Is Xamarin support iOS 11.0 push notification from Azure Notification Hub?

Note: I am using

Visual Studio 2017 (Version 15.4.0) on Windows 10

Mac OS High Siera Version 10.13

Xcode Version 9.0.1

VS for Mac Community Version 7.2 (build 636)

Testing on iPhone 5S, iPhone 6, iPhone 6S, iPhone 7, iPhone 8 - iOS11.0

答:
Solved it by using physical iPhone device.

"The simulator does not do Push Notifications. And to push from a server, you have to have device(s) to push to as well as your app on that device."

"The iPhone Simulator is unable to receive push notifications or successfully register for them."

Body:
I have tried Android and Windows push notifications and all works fine. However, on the iOS side, something wrong.

I am trying to add push notifications to my Xamarin.iOS app using these tutorials

https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-ios-push-notification-apns-get-started

https://blog.xamarin.com/push-notifications-ios-azure-notification-hubs/

From Azure Test Send I got "Message was successfully sent, but there were no matching targets."

I have followed all the steps as it is but when I put a breakpoint,  I always get "IsRegistered =false":

AppDelegate.cs

private SBNotificationHub Hub { get; set; }
    public const string ConnectionString = "Endpoint=sb://...";
    public const string NotificationHubPath = "NotificationHubName...";

     public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
            {
                // Set our preferred notification settings for the app
                var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet());

                // Register for notifications
                UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
                bool IsRegistered = UIApplication.SharedApplication.IsRegisteredForRemoteNotifications;

                return true;
            }
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            Hub = new SBNotificationHub(ConnectionString, NotificationHubPath);
            Hub.UnregisterAllAsync(deviceToken, (error) =>
            {
                if (error != null)
                {
                    // Error unregistering
                    return;
                }
                // Register this device with the notification hub
                Hub.RegisterNativeAsync(deviceToken, null, (registerError) =>
                {
                    if (registerError != null)
                    {
                        // Error registering
                    }
                });
            });
        }

        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            if (null != userInfo && userInfo.ContainsKey(new NSString("aps")))
            {
                // Get the aps dictionary from the alert payload
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
            }
        }

My questions are;

Why am I not registering?

How can I learn why am I not registering?

Is Xamarin support iOS 11.0 push notification from Azure Notification Hub?

Note: I am using

Visual Studio 2017 (Version 15.4.0) on Windows 10

Mac OS High Siera Version 10.13

Xcode Version 9.0.1

VS for Mac Community Version 7.2 (build 636)

Testing on iPhone 5S, iPhone 6, iPhone 6S, iPhone 7, iPhone 8 - iOS11.0


问:
minimize js files in gradle build while creating a war
I am completely new to gradle and I am manage to create war through gradle-4.2.1 by following scripts :

```<code>apply plugin: 'war'
archivesBaseName = "idcapture"
version = '1.0'
webAppDirName = 'WebContent'
buildDir = 'gradle_Build'

 sourceSets {
  main {
     java {
          srcDir 'src'
     }
     resources {
       srcDir 'conf'
     }
  }
}

dependencies {
  compile fileTree(dir: "WebContent/WEB-INF/lib", include: '*.jar')
   }
</code>```

I can able to create an war file by above code but my intention the war file should have minimized version of JS files. Hence I have tried n number of places.
I tried erwin js plugin and I am unable to implement:

fyr, https://github.com/eriwen/gradle-js-plugin

Especially I  am not able to point the js file paths and minimize function my script. The errors are various and I am not sure where to place that in my script!!
Fyr, my application folder structure attached

any help would be appreciated. Thanks

答:
I found it, if we add following erwil libs on any place of the build. it works fine:</p>

```<code>    plugins {
    id 'com.eriwen.gradle.js' version '2.14.1'
}

import com.eriwen.gradle.js.tasks.MinifyJsTask
task minifyJS << {
    println "lets minify"
  fileTree('WebContent/js').eachWithIndex { file, index ->
    def dynamicTask = "minify$index"
    task "$dynamicTask" (type: MinifyJsTask) {
      source = file
      dest = file
    }
    tasks."$dynamicTask".execute()
  }
}
</code>```

Body:
I am completely new to gradle and I am manage to create war through gradle-4.2.1 by following scripts :

apply plugin: 'war'
archivesBaseName = "idcapture"
version = '1.0'
webAppDirName = 'WebContent'
buildDir = 'gradle_Build'

 sourceSets {
  main {
     java {
          srcDir 'src'
     }
     resources {
       srcDir 'conf'
     }
  }
}

dependencies {
  compile fileTree(dir: "WebContent/WEB-INF/lib", include: '*.jar')
   }

I can able to create an war file by above code but my intention the war file should have minimized version of JS files. Hence I have tried n number of places.
I tried erwin js plugin and I am unable to implement:

fyr, https://github.com/eriwen/gradle-js-plugin

Especially I  am not able to point the js file paths and minimize function my script. The errors are various and I am not sure where to place that in my script!!
Fyr, my application folder structure attached

any help would be appreciated. Thanks

Body:
I found it, if we add following erwil libs on any place of the build. it works fine:

    plugins {
    id 'com.eriwen.gradle.js' version '2.14.1'
}

import com.eriwen.gradle.js.tasks.MinifyJsTask
task minifyJS << {
    println "lets minify"
  fileTree('WebContent/js').eachWithIndex { file, index ->
    def dynamicTask = "minify$index"
    task "$dynamicTask" (type: MinifyJsTask) {
      source = file
      dest = file
    }
    tasks."$dynamicTask".execute()
  }
}


问:
An error occurred while loading the web debug toolbar (404: not found)?
Hi I'm using Symfony (Swiftmailer) to send an emails, the problem that I have is:

An error occurred while loading the web debug toolbar (404: not found)
  Do you want to open the profiler?

Screenshot

The emails were sent successfully but the problem is I can't render any *.html.twig.

I tried != solution like command php bin/console debug:event-dispatcher and the .htacces like

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /app.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>
</code>```

But all the solutions proposed on the net do not work for me, thanks for helping.

答:
when i look in the config_dev.yml i found the folow code :

```<code>web_profiler:
    toolbar: true
    intercept_redirects: false
</code>```

i turn the toolbar value to false, it work correctly like

```<code>web_profiler:
    toolbar: false
    intercept_redirects: false
</code>```

are this solution touche others file and cause me other problems?

Body:
Hi I'm using Symfony (Swiftmailer) to send an emails, the problem that I have is:

An error occurred while loading the web debug toolbar (404: not found)
  Do you want to open the profiler?

Screenshot

The emails were sent successfully but the problem is I can't render any *.html.twig.

I tried != solution like command php bin/console debug:event-dispatcher and the .htacces like

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /app.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

But all the solutions proposed on the net do not work for me, thanks for helping.

Body:
when i look in the config_dev.yml i found the folow code :

web_profiler:
    toolbar: true
    intercept_redirects: false

i turn the toolbar value to false, it work correctly like

web_profiler:
    toolbar: false
    intercept_redirects: false

are this solution touche others file and cause me other problems?


问:
Generating depth map with panda3d
I need to generate test data for 3d reconstruction code. For this I decided to use panda3d. I am able to create simple app and see the scene. Now I need to create depth map for the scene, i.e. for each pixel on the screen I need to calculate depth, i.e. distance from camera to the closest object in the 3d space (moving perpendicularly to camera plane). What API functions are more suitable for that? </p>

答:
This is in principle similar to shadow mapping, as demonstrated in the advanced shadow sample.  You will need to create an offscreen buffer and camera to render the depth buffer.  Note that unless you use an orthographic lens, the resulting depth values will not be linear and will need to be transformed to a linear value using the near and far values of the lens.  The near and far distances should be configured such as to get the desired range of depth values.

Alternatively, you can use a shader to write the appropriate distance values into the colour buffer, which is particularly useful if you want to store distance values of a perspective camera without having to undo the perspective projection later, or if you want to store the original world-space positions.

If you want to be able to access the values on the CPU, you will need to use the RTM_copy_ram value instead of RTM_bind_or_copy when binding your texture to tell Panda3D to transfer the results of rendering the buffer to CPU-accessible memory.

Title: Generating depth map with panda3d


问:
rpm %config(noreplace) override with %config
In my rpm I have a full directory that I want to tag with %config(noreplace).  There is a file in that directory that I want to replace on every install with the latest from the rpm, using the semantics from %config.

Using the guide here: http://www-uxsup.csx.cam.ac.uk/~jw35/docs/rpm_config.html, I tried the following:

```<code>%files
%config(noreplace) /my/saved/dir/*
%config /my/saved/dir/file1
</code>```

and

```<code>%files
%config /my/saved/dir/file1
%config(noreplace) /my/saved/dir/*
</code>```

hoping that the specific command would override the glob, but it didn't work.  Is there any RPM like command that I can use to force the %config behaviour on a file that's nested under a %config(noreplace) directory?

答:
The assumption is that every file in the package is listed in the %files section (list) of .spec file exactly once. I bet when you were running rpmbuild there was the following line in the output

```<code>warning: File listed twice: /my/saved/dir/file1
</code>```

The solution is to list configuration file (which you want to be always overwritten) only once and with proper directive i.e. %config(noreplace). This is no matter if it is specified directly or indirectly through wildcard character.

The statement referenced in msuchy's answer

There is a restriction to the %config directive, and that restriction
  is that no more than one filename may follow the %config.

must be from distant past for there are examples of spec files using wildcard characters in %config directive as early as in year 2008.

The problem is not in using wildcard characters per se. The problem is that one and the same file is listed twice (once directly, and once indirectly as a result of usage of wildcard character) with different %config directives (once with plain %config and once with %config(noreplace)). Your test – changing order of these two declarations – and the result you observe suggests that rpm merges these two declarations into one %config(noreplace). This would explain why the order of declarations does not matter. However, as I wrote above, the assumption is that every file is listed exactly once and this could be the reason I couldn't find any information on what is supposed to happen when some file is listed more than once.

Please note, that the file specified with %config(noreplace) must have changed – in the package – between the version already installed and the newer version being installed for .rpmnew files to be written – see .rpmnew file not created on package upgrade?

Please be also aware that installation of newer version of some package is not treated like updating the package – see Unexpected RPM conflict on %config(noreplace) files

Below are spec files for those wanting to try themselves.

mypackage-old.spec:

```<code>Summary: old version
Name: mypackage
Version: 1
Release: 1
License: BSD

%description
https://stackoverflow.com/questions/32610487/

%prep

%build

%install
rm -rf %{buildroot}
mkdir -p %{buildroot}/foo
echo 'replace' > %{buildroot}/foo/replace
echo 'noreplace' > %{buildroot}/foo/noreplace

%clean
rm -rf %{buildroot}

%files
%defattr(-,root,root,-)
%config /foo/replace
%config(noreplace) /foo/*
</code>```

mypackage-new.spec:

```<code>Summary: new version
Name: mypackage
Version: 2
Release: 1
License: BSD

%description
https://stackoverflow.com/questions/32610487/

%prep

%build

%install
rm -rf %{buildroot}
mkdir -p %{buildroot}/foo
echo 'new replace' > %{buildroot}/foo/replace
echo 'new noreplace' > %{buildroot}/foo/noreplace

%clean
rm -rf %{buildroot}

%files
%defattr(-,root,root,-)
# declaration A
%config /foo/replace
# declaration B
%config(noreplace) /foo/*
</code>```

The result with RPM version 4.14.0 is the same no matter what order we place declarations A and B above:

```<code>% rpmbuild -ba ./mypackge-old.spec
% rpmbuild -ba ./mypackge-new.spec
% sudo rpm -i ~/rpmbuild/RPMS/x86_64/mypackage-1-1.x86_64.rpm
% echo modified >> /foo/replace
% echo modified >> /foo/noreplace
% sudo rpm -U ~/rpmbuild/RPMS/x86_64/mypackage-2-1.x86_64.rpm
warning: /foo/noreplace created as /foo/noreplace.rpmnew
warning: /foo/replace created as /foo/replace.rpmnew
</code>```

Body:
In my rpm I have a full directory that I want to tag with %config(noreplace).  There is a file in that directory that I want to replace on every install with the latest from the rpm, using the semantics from %config.

Using the guide here: http://www-uxsup.csx.cam.ac.uk/~jw35/docs/rpm_config.html, I tried the following:

%files
%config(noreplace) /my/saved/dir/*
%config /my/saved/dir/file1

and

%files
%config /my/saved/dir/file1
%config(noreplace) /my/saved/dir/*

hoping that the specific command would override the glob, but it didn't work.  Is there any RPM like command that I can use to force the %config behaviour on a file that's nested under a %config(noreplace) directory?

Body:
The assumption is that every file in the package is listed in the %files section (list) of .spec file exactly once. I bet when you were running rpmbuild there was the following line in the output

warning: File listed twice: /my/saved/dir/file1

The solution is to list configuration file (which you want to be always overwritten) only once and with proper directive i.e. %config(noreplace). This is no matter if it is specified directly or indirectly through wildcard character.

The statement referenced in msuchy's answer

There is a restriction to the %config directive, and that restriction
  is that no more than one filename may follow the %config.

must be from distant past for there are examples of spec files using wildcard characters in %config directive as early as in year 2008.

The problem is not in using wildcard characters per se. The problem is that one and the same file is listed twice (once directly, and once indirectly as a result of usage of wildcard character) with different %config directives (once with plain %config and once with %config(noreplace)). Your test – changing order of these two declarations – and the result you observe suggests that rpm merges these two declarations into one %config(noreplace). This would explain why the order of declarations does not matter. However, as I wrote above, the assumption is that every file is listed exactly once and this could be the reason I couldn't find any information on what is supposed to happen when some file is listed more than once.

Please note, that the file specified with %config(noreplace) must have changed – in the package – between the version already installed and the newer version being installed for .rpmnew files to be written – see .rpmnew file not created on package upgrade?

Please be also aware that installation of newer version of some package is not treated like updating the package – see Unexpected RPM conflict on %config(noreplace) files

Below are spec files for those wanting to try themselves.

mypackage-old.spec:

Summary: old version
Name: mypackage
Version: 1
Release: 1
License: BSD

%description
https://stackoverflow.com/questions/32610487/

%prep

%build

%install
rm -rf %{buildroot}
mkdir -p %{buildroot}/foo
echo 'replace' > %{buildroot}/foo/replace
echo 'noreplace' > %{buildroot}/foo/noreplace

%clean
rm -rf %{buildroot}

%files
%defattr(-,root,root,-)
%config /foo/replace
%config(noreplace) /foo/*

mypackage-new.spec:

Summary: new version
Name: mypackage
Version: 2
Release: 1
License: BSD

%description
https://stackoverflow.com/questions/32610487/

%prep

%build

%install
rm -rf %{buildroot}
mkdir -p %{buildroot}/foo
echo 'new replace' > %{buildroot}/foo/replace
echo 'new noreplace' > %{buildroot}/foo/noreplace

%clean
rm -rf %{buildroot}

%files
%defattr(-,root,root,-)
# declaration A
%config /foo/replace
# declaration B
%config(noreplace) /foo/*

The result with RPM version 4.14.0 is the same no matter what order we place declarations A and B above:

% rpmbuild -ba ./mypackge-old.spec
% rpmbuild -ba ./mypackge-new.spec
% sudo rpm -i ~/rpmbuild/RPMS/x86_64/mypackage-1-1.x86_64.rpm
% echo modified >> /foo/replace
% echo modified >> /foo/noreplace
% sudo rpm -U ~/rpmbuild/RPMS/x86_64/mypackage-2-1.x86_64.rpm
warning: /foo/noreplace created as /foo/noreplace.rpmnew
warning: /foo/replace created as /foo/replace.rpmnew


问:
PowerMockIgnore all package except one class
Is there any way to annotate @PowerMockIgnore to ignore the whole package except just one class inside this package?

I was hoping to do something like for example:

```<code>@PowerMockIgnore({ "foo.bar.ignore*\DoNotIgnoreClass"})
</code>```

答:
Use the @PrepareForTest annotation:

e.g.

```<code>@PrepareForTest(DoNotIgnoreClass.class)
</code>```

or for multiple classes:

```<code>@PrepareForTest({DoNotIgnoreClass.class, Another.class})
</code>```

Body:
Is there any way to annotate @PowerMockIgnore to ignore the whole package except just one class inside this package?

I was hoping to do something like for example:

@PowerMockIgnore({ "foo.bar.ignore*\DoNotIgnoreClass"})

Body:
Use the @PrepareForTest annotation:

e.g.

@PrepareForTest(DoNotIgnoreClass.class)

or for multiple classes:

@PrepareForTest({DoNotIgnoreClass.class, Another.class})


问:
Java. Array, save previous values
Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array.
Console has to display something like this:

: Jump 1, direction Left

: Jump 2, direction Right

In my code below, when I print array elements,  int jump always equals to 0;

I tried many variations, sometimes I got (for example):

```<code>jump();

jump();

jump();

jump();
</code>```

And it prints: {0,0,0,4} , instead of {1,2,3,4};

```<code>public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;

public void jump() {
    jump++;
    if (jump > 50) {
        System.out.println("need a rest");
        return;
    } else {

        for (int i = 0; i < jumpArray.length; i++) {
            jumpArray[i] = new Jump();
        }
    }
    jumpArray[jump].storeJump = jump;
    jumpArray[jump].storeDirection = direction;

}

public static void main(String[] args) {
    Jump jumper = new Jump();
    jumper.jump();
    jumper.jump();

    for (int i = 0; i < jumper.jump; i++) {
        System.out.println(jumper.jumpArray[i].jump);

    }

}

}
</code>```

答:
I think it would make more sense to move the jumpArray into main():

```<code>public class Jump {
    String direction;
    //int storeJump;   Not sure what this is for
    //String storeDirection;    Or this

    @Override
    public String toString() {
        return direction;
    }

    // Static function that creates an initializes a Jump object
    public static Jump jump(String direction) {
        Jump jump = new Jump();
        jump.direction = direction;
        return jump;
    }

    public static void main (String[] args)
    {
        Jump[] jumpArray = new Jump[100];
        int numJumps = 0;

        // A list of directions for testing
        String [] path = new String[]{"north", "south", "east", "west"};

        // Create a bunch of jumps
        for (String dir : path) {
            if (numJumps > 50) {
                System.out.println("need a rest");
                break;
            }
            // Create a new jump and add to the array
            jumpArray[numJumps++] = Jump.jump(dir);
        }

        // Print the jumps
        for (int i = 0; i < numJumps; i++) {
            System.out.println(i + " " + jumpArray[i]);
        }
    }
}
</code>```

Title: Java. Array, save previous values

Body:
Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array.
Console has to display something like this:

: Jump 1, direction Left

: Jump 2, direction Right

In my code below, when I print array elements,  int jump always equals to 0;

I tried many variations, sometimes I got (for example):

jump();

jump();

jump();

jump();

And it prints: {0,0,0,4} , instead of {1,2,3,4};

public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;

public void jump() {
    jump++;
    if (jump > 50) {
        System.out.println("need a rest");
        return;
    } else {

        for (int i = 0; i < jumpArray.length; i++) {
            jumpArray[i] = new Jump();
        }
    }
    jumpArray[jump].storeJump = jump;
    jumpArray[jump].storeDirection = direction;

}

public static void main(String[] args) {
    Jump jumper = new Jump();
    jumper.jump();
    jumper.jump();

    for (int i = 0; i < jumper.jump; i++) {
        System.out.println(jumper.jumpArray[i].jump);

    }

}

}

Body:
I think it would make more sense to move the jumpArray into main():

public class Jump {
    String direction;
    //int storeJump;   Not sure what this is for
    //String storeDirection;    Or this

    @Override
    public String toString() {
        return direction;
    }

    // Static function that creates an initializes a Jump object
    public static Jump jump(String direction) {
        Jump jump = new Jump();
        jump.direction = direction;
        return jump;
    }

    public static void main (String[] args)
    {
        Jump[] jumpArray = new Jump[100];
        int numJumps = 0;

        // A list of directions for testing
        String [] path = new String[]{"north", "south", "east", "west"};

        // Create a bunch of jumps
        for (String dir : path) {
            if (numJumps > 50) {
                System.out.println("need a rest");
                break;
            }
            // Create a new jump and add to the array
            jumpArray[numJumps++] = Jump.jump(dir);
        }

        // Print the jumps
        for (int i = 0; i < numJumps; i++) {
            System.out.println(i + " " + jumpArray[i]);
        }
    }
}


问:
serialize only one property of a class
I have a class which have about 20 members. I need to serialize my the object of this  class in a XML. But condition is I need only one member in the XML.

How can I do this.

EDIT : But at some time, I would like to serialize all the members. So I can't use [XMLIgnore] attribute.

答:
You could explicitly implement the IXmlSerializable interface and control the reading/writing of the fields yourself, based on some external parameter, i.e.

```<code>class CustomXml: IXmlSerializable
{
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        //
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        if (SerializationParameter.FullSerialization)
           //deserialize everything
        else
           //deserialize one field only
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        if (SerializationParameter.FullSerialization)
           //serialize everything
        else
           //serialize one field only
    }
}
</code>```

where SerializationParameter.FullSerialization is an example of how you could control what is serialized when.

Title: serialize only one property of a class

Body:
You could explicitly implement the IXmlSerializable interface and control the reading/writing of the fields yourself, based on some external parameter, i.e.

class CustomXml: IXmlSerializable
{
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        //
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        if (SerializationParameter.FullSerialization)
           //deserialize everything
        else
           //deserialize one field only
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        if (SerializationParameter.FullSerialization)
           //serialize everything
        else
           //serialize one field only
    }
}

where SerializationParameter.FullSerialization is an example of how you could control what is serialized when.


问:
Preserve function context in Python
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

```<code>def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines
</code>```

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

答:
Dirty hack: add variable to function object and store value there.</p>

```<code>def is_in_file(element, path):
    if not hasattr(is_in_file, "__lines__"):
        with open(path, 'r') as f:
            setattr(is_in_file, "__lines__", [line.strip() for line in f.readlines()])
    return element in is_in_file.__lines__
</code>```

Title: Preserve function context in Python

Body:
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

Body:
Dirty hack: add variable to function object and store value there.

def is_in_file(element, path):
    if not hasattr(is_in_file, "__lines__"):
        with open(path, 'r') as f:
            setattr(is_in_file, "__lines__", [line.strip() for line in f.readlines()])
    return element in is_in_file.__lines__