问:
Hide no-data template until after data loads via Axios
I have a typical Vue data-table with a template section that displays an alert if no records are found.  Problem is, that displays right away, even before my Axios method has a chance to go out and get records.

How can I prevent the flash of red warning message before the actual data loads?

```<code><template>
  <div>
    <v-card>
      <v-card-title>
        <h1>Locations</h1>
      </v-card-title>

      <v-data-table :headers="headers" :items="locations" :search="search" :fixed-header="true" :loading="true" class="elevation-1">
        <template v-slot:items="location">
          <td>{{ location.item.id }}</td>
          <td>{{ location.item.company }}</td>
          <td>{{ location.item.category }}</td>
          <td>{{ location.item.name }}</td>
          <td>{{ location.item.city }}, {{ location.item.state }}</td>
        </template>
        <template v-slot:no-data>
          <v-alert :value="true" color="error" icon="warning">Sorry, no locations found.</v-alert>
        </template>
      </v-data-table>
    </v-card>
  </div>
</template>

<script>
import { HTTP } from "@/utils/http-common";

export default {
  name: 'LocationsList',
  data() {
    return {
      headers: [
        { text: "Id", value: "id" },
        { text: "Company", value: "company" },
        { text: "Category", value: "category" },
        { text: "Name", value: "name" },
        { text: "City, State", value: "city" },
      ],
      locations: [],
      errors: []
    };
  },
  created: function() {
    this.getAllLocations();
  },
  methods: {
    getAllLocations() {
      HTTP.get("locations")
        .then(response => {
          this.locations = response.data;
        })
        .catch(err => {
          this.errors.push(err);
        });
    },
  }
};
</script>
</code>```

答:
Add a loading state to data, and set it to true

Set the loading state when the call is finished (.finally promise)

Set the v-if on in your template to show when it's not anymore loading

See code below.

<template>

    <v-card>
      <v-card-title>

Locations

      </v-card-title>

      <v-data-table :headers="headers" :items="locations" :search="search" :fixed-header="true" :loading="true" class="elevation-1">
        <template v-slot:items="location">
          {{ location.item.id }}
          {{ location.item.company }}
          {{ location.item.category }}
          {{ location.item.name }}
          {{ location.item.city }}, {{ location.item.state }}
        </template>
        <template v-slot:no-data>
          <v-alert v-if="!loading" :value="true" color="error" icon="warning">Sorry, no locations found.</v-alert>
        </template>
      </v-data-table>
    </v-card>

</template>

```

Body:
I have a typical Vue data-table with a template section that displays an alert if no records are found.  Problem is, that displays right away, even before my Axios method has a chance to go out and get records.

How can I prevent the flash of red warning message before the actual data loads?

<template>

    <v-card>
      <v-card-title>

Locations

      </v-card-title>

      <v-data-table :headers="headers" :items="locations" :search="search" :fixed-header="true" :loading="true" class="elevation-1">
        <template v-slot:items="location">
          {{ location.item.id }}
          {{ location.item.company }}
          {{ location.item.category }}
          {{ location.item.name }}
          {{ location.item.city }}, {{ location.item.state }}
        </template>
        <template v-slot:no-data>
          <v-alert :value="true" color="error" icon="warning">Sorry, no locations found.</v-alert>
        </template>
      </v-data-table>
    </v-card>

</template>

Body:
Add a loading state to data, and set it to true

Set the loading state when the call is finished (.finally promise)

Set the v-if on in your template to show when it's not anymore loading

See code below.

<template>
  <div>
    <v-card>
      <v-card-title>
        <h1>Locations</h1>
      </v-card-title>

      <v-data-table :headers="headers" :items="locations" :search="search" :fixed-header="true" :loading="true" class="elevation-1">
        <template v-slot:items="location">
          <td>{{ location.item.id }}</td>
          <td>{{ location.item.company }}</td>
          <td>{{ location.item.category }}</td>
          <td>{{ location.item.name }}</td>
          <td>{{ location.item.city }}, {{ location.item.state }}</td>
        </template>
        <template v-slot:no-data>
          <v-alert v-if="!loading" :value="true" color="error" icon="warning">Sorry, no locations found.</v-alert>
        </template>
      </v-data-table>
    </v-card>
  </div>
</template>

<script>
import { HTTP } from "@/utils/http-common";

export default {
  name: 'LocationsList',
  data() {
    return {
      headers: [
        { text: "Id", value: "id" },
        { text: "Company", value: "company" },
        { text: "Category", value: "category" },
        { text: "Name", value: "name" },
        { text: "City, State", value: "city" },
      ],
      locations: [],
      errors: [],
      loading: true
    };
  },
  created: function() {
    this.getAllLocations();
  },
  methods: {
    getAllLocations() {
      HTTP.get("locations")
        .then(response => {
          this.locations = response.data;
        })
        .catch(err => {
          this.errors.push(err);
        })
        .finally(() => {
          this.loading = false;
        })
    },
  }
};
</script>


来源: stackexchange

问:
Android: ListView Problem While changing the image next to text in TextView
I am developing a soundboard application which extends ListActivity. I have a play button image and the text next to it. Now when the user clicks on a textview, I change the play image to pause image using the following code.

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  try
    {
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, Sounds));
     final ListView lv = getListView();
     lv.setTextFilterEnabled(true);
     lv.setCacheColorHint(Color.WHITE);
     lv.setSoundEffectsEnabled(false);
     lv.setFastScrollEnabled(true);
     lv.setFocusableInTouchMode(true);
     lv.setBackgroundColor(Color.WHITE);
  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
           int position, long id) {
          TextView tv1 = (TextView) view;
           int u = (int)meMap.get(position+1); // meMap--> HashMap which contains corresponding resids
           playSample(u,tv1);

       }
     });
}
private void playSample(int resid,TextView ttvv)
{
final Resources res = getBaseContext().getResources();
    final Drawable myImage = res.getDrawable(R.drawable.pause);
  //  myImage.
    final Drawable myImage1 = res.getDrawable(R.drawable.play);

    MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener(){
  public void onCompletion(MediaPlayer mp) {
 // tv --> (TextView) view; From onItemClick(AdapterView<?> parent, View view,int position, long id)
     tv.setCompoundDrawablesWithIntrinsicBounds(myImage1, null, null, null);

      }
    };
</code>```

This code works, but with a small error which I noted. Suppose if I select third row in my list, the play image changes to pause image and if I scroll my list while it is playing, I can see that the third row of the second scroll page, the third row of the third scroll page and so on gets affected i.e they also change to pause image. Why is this happening? Am I doing something wrong? I hope you understand my question. Your help is appreciated. Thanks.

答:
I have a similar UI (play/pause in a list view). I avoided the issues you are talking about by using ToggleButtons in my list view and setting the background to an xml drawable like this:
Create a file drawable/play_pause_toggle.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_enabled="false"
           android:drawable="@drawable/pause"/>
     <item android:state_checked="true"
           android:drawable="@drawable/pause" />
     <item android:state_focused="true"
           android:drawable="@drawable/pause" />
     <item android:drawable="@drawable/play" />
 </selector>
</code>```

Then set your ToggleButton background to @drawable/play_pause_toggle. It will change automatically each time the ToggleButtons isChecked state changes

ContentLicense: CC BY-SA 2.5

Body:
I am developing a soundboard application which extends ListActivity. I have a play button image and the text next to it. Now when the user clicks on a textview, I change the play image to pause image using the following code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  try
    {
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, Sounds));
     final ListView lv = getListView();
     lv.setTextFilterEnabled(true);
     lv.setCacheColorHint(Color.WHITE);
     lv.setSoundEffectsEnabled(false);
     lv.setFastScrollEnabled(true);
     lv.setFocusableInTouchMode(true);
     lv.setBackgroundColor(Color.WHITE);
  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
           int position, long id) {
          TextView tv1 = (TextView) view;
           int u = (int)meMap.get(position+1); // meMap--> HashMap which contains corresponding resids
           playSample(u,tv1);

       }
     });
}
private void playSample(int resid,TextView ttvv)
{
final Resources res = getBaseContext().getResources();
    final Drawable myImage = res.getDrawable(R.drawable.pause);
  //  myImage.
    final Drawable myImage1 = res.getDrawable(R.drawable.play);

    MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener(){
  public void onCompletion(MediaPlayer mp) {
 // tv --> (TextView) view; From onItemClick(AdapterView<?> parent, View view,int position, long id)
     tv.setCompoundDrawablesWithIntrinsicBounds(myImage1, null, null, null);

      }
    };

This code works, but with a small error which I noted. Suppose if I select third row in my list, the play image changes to pause image and if I scroll my list while it is playing, I can see that the third row of the second scroll page, the third row of the third scroll page and so on gets affected i.e they also change to pause image. Why is this happening? Am I doing something wrong? I hope you understand my question. Your help is appreciated. Thanks.

Body:
I have a similar UI (play/pause in a list view). I avoided the issues you are talking about by using ToggleButtons in my list view and setting the background to an xml drawable like this:
Create a file drawable/play_pause_toggle.xml:

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_enabled="false"
           android:drawable="@drawable/pause"/>
     <item android:state_checked="true"
           android:drawable="@drawable/pause" />
     <item android:state_focused="true"
           android:drawable="@drawable/pause" />
     <item android:drawable="@drawable/play" />
 </selector>

Then set your ToggleButton background to @drawable/play_pause_toggle. It will change automatically each time the ToggleButtons isChecked state changes

ContentLicense: CC BY-SA 3.0


问:
Django model validate a ManyToMany field before adding
I have a model that looks somewhat like this:

```<code>class Passenger(models.Model):
    name = models.CharField(max_length=50)
    surname = models.CharField(max_length=50)

class Flight(models.Model):
    capacity = models.IntegerField()
    passengers = models.ManyToManyField(Passenger)
</code>```

Before adding a new passenger to the flight I would like to validate whether the number of passengers is not going to exceed the capacity. I was wondering what would be the best way to go about this.

Obviously I could manually check the number of passengers before adding a new one, but maybe there is some support in django? I tried writing a validator, but wasn't sure how to do it.

答:
According to Django docs you can listen to the m2m_changed signal, which will trigger pre_add and post_add actions.

Using add() with a many-to-many relationship, however, will not call
  any save() methods (the bulk argument doesn’t exist), but rather
  create the relationships using QuerySet.bulk_create(). If you need to
  execute some custom logic when a relationship is created, listen to
  the m2m_changed signal, which will trigger pre_add and post_add
  actions.

ContentLicense: CC BY-SA 4.0

Body:
I have a model that looks somewhat like this:

class Passenger(models.Model):
    name = models.CharField(max_length=50)
    surname = models.CharField(max_length=50)

class Flight(models.Model):
    capacity = models.IntegerField()
    passengers = models.ManyToManyField(Passenger)

Before adding a new passenger to the flight I would like to validate whether the number of passengers is not going to exceed the capacity. I was wondering what would be the best way to go about this.

Obviously I could manually check the number of passengers before adding a new one, but maybe there is some support in django? I tried writing a validator, but wasn't sure how to do it.


问:
Abstract parent class calls derived class method
So I was wondering about how classes instances are built.

```<code>public abstract class test {

    int count;

    public test(){
        count();
        count();
        System.out.println("test" + this.count);
    }
    abstract void count();
}

public class derive extends test{

    int count;

    public derive(){
        System.out.println("derive");
    }
    @Override
    public void count(){
        count++;
    }
}
    public static void main(String[] args) {
    derived o = new derived();
}
</code>```

The output is:

test0

derive

How come count = 0? and not 2?

答: Because you have two variables named count. One that is visible in test (but shadowed) by the one that is in derive. Remove int count from derive and mark it protected in test.

Body:
So I was wondering about how classes instances are built.

public abstract class test {

    int count;

    public test(){
        count();
        count();
        System.out.println("test" + this.count);
    }
    abstract void count();
}

public class derive extends test{

    int count;

    public derive(){
        System.out.println("derive");
    }
    @Override
    public void count(){
        count++;
    }
}
    public static void main(String[] args) {
    derived o = new derived();
}

The output is:

test0

derive

How come count = 0? and not 2?


问:
Regular expression misses match at beginning of string
I have strings of as and bs. I want to extract all overlapping subsequences, where a subsequence is a single a surrounding by any number of bs. This is the regex I wrote:

```<code>import re

pattern = """(?=            # inside lookahead for overlapping results
             (?:a|^)        # match at beginning of str or after a
             (b* (?:a) b*)  # one a between any number of bs
             (?:a|$))       # at end of str or before next a
          """
a_between_bs = re.compile(pattern, re.VERBOSE)
</code>```

It seems to work as expected, except when the very first character in the string is an a, in which case this subsequence is missed:

```<code>a_between_bs.findall("bbabbba")
# ['bbabbb', 'bbba']
a_between_bs.findall("abbabb")
# ['bbabb']
</code>```

I don't understand what is happening. If I change the order of how a potential match could start, the results also change:

```<code>pattern = """(?=
             (?:^|a)        # a and ^ swapped
             (b* (?:a) b*)
             (?:a|$))
          """
a_between_bs = re.compile(pattern, re.VERBOSE)

a_between_bs.findall("abbabb")
# ['abb']
</code>```

I would have expected this to be symmetric, so that strings ending in an a might also be missed, but this doesn't appear to be the case. What is going on?

Edit:

I assumed that solutions to the toy example above would translate to my full problem, but that doesn't seem to be the case, so I'm elaborating now (sorry about that). I am trying to extract "syllables" from transcribed words. A "syllable" is a vowel or a diphtongue, preceded and followed by any number of consonants. This is my regular expression to extract them:

```<code>vowels = 'æɑəɛiɪɔuʊʌ'
diphtongues = "|".join(('aj', 'aw', 'ej', 'oj', 'ow'))
consonants = 'θwlmvhpɡŋszbkʃɹdnʒjtðf'

pattern = f"""(?=
          (?:[{vowels}]|^|{diphtongues})
          ([{consonants}]* (?:[{vowels}]|{diphtongues}) [{consonants}]*)
          (?:[{vowels}]|$|{diphtongues})
          )
          """
syllables = re.compile(pattern, re.VERBOSE)
</code>```

The tricky bit is that the diphtongues end in consonants (j or w), which I don't want to be included in the next syllable. So replacing the first non-capturing group by a double negative (?<![{consonants}]) doesn't work. I tried to instead replace that group by a positive lookahead (?<=[{vowels}]|^|{diphtongues}), but regex won't accept different lengths (even removing the diphtongues doesn't work, apparently ^ is of a different length).

So this is the problematic case with the pattern above:

```<code>syllables.findall('æbə')
# ['bə']
# should be: ['æb', 'bə']
</code>```

Edit 2:
I've switched to using regex, which allows variable-width lookbehinds, which solves the problem. To my surprise, it even appears to be faster than the re module in the standard library. I'd still like to know how to get this working with the re module, though. (:

答:
I suggest fixing this with a double negation:

```<code>(?=         # inside lookahead for overlapping results
 (?<![^a])  # match at beginning of str or after a
 (b*ab*)    # one a between any number of bs
 (?![^a])   # at end of str or before next a
)
</code>```

See the regex demo

Note I replaced the grouping constructs with lookarounds: (?:a|^) with (?<![^a]) and  (?:a|$) with (?![^a]). The latter is not really important, but the first is very important here.

The (?:a|^) at the beginning of the outer lookahead pattern matches a or start of the string, whatever comes first. If a is at the start, it is matched and when the input is abbabb, you get bbabb since it matches the capturing group pattern and there is an end of string position right after. The next iteration starts after the first a, and cannot find any match since the only a left in the string has no a after bs.

Note that order of alternative matters. If you change to (?:^|a), the match starts at the start of the string, b* matches empty string, ab* grabs the first abb in abbabb, and since there is a right after, you get abb as a match. There is no way to match anything after the first a.

Body:
I have strings of as and bs. I want to extract all overlapping subsequences, where a subsequence is a single a surrounding by any number of bs. This is the regex I wrote:

import re

pattern = """(?=            # inside lookahead for overlapping results
             (?:a|^)        # match at beginning of str or after a
             (b* (?:a) b*)  # one a between any number of bs
             (?:a|$))       # at end of str or before next a
          """
a_between_bs = re.compile(pattern, re.VERBOSE)

It seems to work as expected, except when the very first character in the string is an a, in which case this subsequence is missed:

a_between_bs.findall("bbabbba")
# ['bbabbb', 'bbba']
a_between_bs.findall("abbabb")
# ['bbabb']

I don't understand what is happening. If I change the order of how a potential match could start, the results also change:

pattern = """(?=
             (?:^|a)        # a and ^ swapped
             (b* (?:a) b*)
             (?:a|$))
          """
a_between_bs = re.compile(pattern, re.VERBOSE)

a_between_bs.findall("abbabb")
# ['abb']

I would have expected this to be symmetric, so that strings ending in an a might also be missed, but this doesn't appear to be the case. What is going on?

Edit:

I assumed that solutions to the toy example above would translate to my full problem, but that doesn't seem to be the case, so I'm elaborating now (sorry about that). I am trying to extract "syllables" from transcribed words. A "syllable" is a vowel or a diphtongue, preceded and followed by any number of consonants. This is my regular expression to extract them:

vowels = 'æɑəɛiɪɔuʊʌ'
diphtongues = "|".join(('aj', 'aw', 'ej', 'oj', 'ow'))
consonants = 'θwlmvhpɡŋszbkʃɹdnʒjtðf'

pattern = f"""(?=
          (?:[{vowels}]|^|{diphtongues})
          ([{consonants}]* (?:[{vowels}]|{diphtongues}) [{consonants}]*)
          (?:[{vowels}]|$|{diphtongues})
          )
          """
syllables = re.compile(pattern, re.VERBOSE)

The tricky bit is that the diphtongues end in consonants (j or w), which I don't want to be included in the next syllable. So replacing the first non-capturing group by a double negative (?<![{consonants}]) doesn't work. I tried to instead replace that group by a positive lookahead (?<=[{vowels}]|^|{diphtongues}), but regex won't accept different lengths (even removing the diphtongues doesn't work, apparently ^ is of a different length).

So this is the problematic case with the pattern above:

syllables.findall('æbə')
# ['bə']
# should be: ['æb', 'bə']

Edit 2:
I've switched to using regex, which allows variable-width lookbehinds, which solves the problem. To my surprise, it even appears to be faster than the re module in the standard library. I'd still like to know how to get this working with the re module, though. (:

Body:
I suggest fixing this with a double negation:

(?=         # inside lookahead for overlapping results
 (?<![^a])  # match at beginning of str or after a
 (b*ab*)    # one a between any number of bs
 (?![^a])   # at end of str or before next a
)

See the regex demo

Note I replaced the grouping constructs with lookarounds: (?:a|^) with (?<![^a]) and  (?:a|$) with (?![^a]). The latter is not really important, but the first is very important here.

The (?:a|^) at the beginning of the outer lookahead pattern matches a or start of the string, whatever comes first. If a is at the start, it is matched and when the input is abbabb, you get bbabb since it matches the capturing group pattern and there is an end of string position right after. The next iteration starts after the first a, and cannot find any match since the only a left in the string has no a after bs.

Note that order of alternative matters. If you change to (?:^|a), the match starts at the start of the string, b* matches empty string, ab* grabs the first abb in abbabb, and since there is a right after, you get abb as a match. There is no way to match anything after the first a.


问:
Regular Expressions- Match Anything
How do I make an expression to match absolutely anything (including whitespaces)?
Example:

Regex:   I bought _____ sheep.

Matches: I bought sheep. I bought a sheep. I bought five sheep.

I tried using (.*), but that doesn't seem to be working.

答:
I recommend use /(?=.*...)/g

Example

```<code>const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true

const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true

const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true

const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text
</code>```

Use regex101  to test

Title: Regular Expressions- Match Anything

Body:
I recommend use /(?=.*...)/g

Example

const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true

const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true

const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true

const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text

Use regex101  to test


问:
How to redeclare variables with the same name but belonging to different files in javascript?
I am loading two js files within an HTML page where both files contain the declaration of variables with the same name. I would like to know if there is a way to declare two variables with the same name other than using closures in javascript? </p>

答:
Your only option is to store them inside objects - variables with the same name in the same scope will be overridden every time. Change that in your JS files.

Instead of:

```<code>var aVariable = 42;
</code>```

Do this:

```<code>var contents = { aVariable, anotherVariable, /* ...All the variables which have the same names */ };
</code>```

And make sure the name contents is unique for each file.

Body:
Your only option is to store them inside objects - variables with the same name in the same scope will be overridden every time. Change that in your JS files.

Instead of:

var aVariable = 42;

Do this:

var contents = { aVariable, anotherVariable, /* ...All the variables which have the same names */ };

And make sure the name contents is unique for each file.


问:
Javascript/Form call timing
I have a form that I use for login purposes here:

```<code><form id = "membershipInfo" method = "post" action = "Login.aspx">
</code>```

with an submit button that I want to do a post method and a javascript onclick method like this:

```<code><input type ="submit" id = "submitInfo" class = "MemberInfo" value = "Take Me There!" onclick = "authorize(accept, reject)"/>
</code>```

The method in the onclick is an facebook authorize method that will pull information from the user (access token). I need this token to have the user proceed in my program. The issue is that when this button is clicked the post method will happen before the onclick is finished, which means that the access token will never be passed with the form.

To get the access token to the page load method I use a hidden input in the form:

```<code><input type = "hidden" id = "hiddenAccessToken"  name = "accessToken" value = "<%=accessToken %>" />
</code>```

and in the Facebook method I get the access token like this:

```<code>function authorize(successCallback, failureCallback) {
FB.getLoginStatus(function (response) {
    if (response.session) {
        // logged in and connected user, carry on
        session = response.session;
        //Set access token
        accessToken = response.session.access_token;
        //Call success callback
        successCallback();
    } else {
        // no user session available, Lets ask for perms
        FB.ui(
        {
            method: 'permissions.request',
            perms:  permissionString
        },
        function (response) {
            if (response && response.session != null) {
                //Get session
                session = response.session;
                //Set access token
                accessToken = response.session.access_token;
                //Call success callback
                successCallback();
            } else {
                //Call failure callback
                failureCallback();
            }
        });
    }
});
//Method hit on successCallback
function accept() {
   //Add access token to hidden input
   $('#hiddenAccessToken').val(accessToken);
}
</code>```

I don't want to use a time out (and I don't think that will work anyways), but I need to slow the page load down until these js methods are complete. Any suggestions?

答:
Why don't you do the form submit with js, like this:

```<code><input type ="button" id = "submitInfo" class = "MemberInfo" value = "Take Me There!" onclick = "authorize(accept, reject)"/>
</code>```

And then:

```<code>function accept() {
   //Add access token to hidden input
   $('#hiddenAccessToken').val(accessToken);
   $('#membershipInfo').submit();
}
</code>```

Title: Javascript/Form call timing

Body:
I have a form that I use for login purposes here:

<form id = "membershipInfo" method = "post" action = "Login.aspx">

with an submit button that I want to do a post method and a javascript onclick method like this:

<input type ="submit" id = "submitInfo" class = "MemberInfo" value = "Take Me There!" onclick = "authorize(accept, reject)"/>

The method in the onclick is an facebook authorize method that will pull information from the user (access token). I need this token to have the user proceed in my program. The issue is that when this button is clicked the post method will happen before the onclick is finished, which means that the access token will never be passed with the form.

To get the access token to the page load method I use a hidden input in the form:

<input type = "hidden" id = "hiddenAccessToken"  name = "accessToken" value = "<%=accessToken %>" />

and in the Facebook method I get the access token like this:

function authorize(successCallback, failureCallback) {
FB.getLoginStatus(function (response) {
    if (response.session) {
        // logged in and connected user, carry on
        session = response.session;
        //Set access token
        accessToken = response.session.access_token;
        //Call success callback
        successCallback();
    } else {
        // no user session available, Lets ask for perms
        FB.ui(
        {
            method: 'permissions.request',
            perms:  permissionString
        },
        function (response) {
            if (response && response.session != null) {
                //Get session
                session = response.session;
                //Set access token
                accessToken = response.session.access_token;
                //Call success callback
                successCallback();
            } else {
                //Call failure callback
                failureCallback();
            }
        });
    }
});
//Method hit on successCallback
function accept() {
   //Add access token to hidden input
   $('#hiddenAccessToken').val(accessToken);
}

I don't want to use a time out (and I don't think that will work anyways), but I need to slow the page load down until these js methods are complete. Any suggestions?

Body:
Why don't you do the form submit with js, like this:

<input type ="button" id = "submitInfo" class = "MemberInfo" value = "Take Me There!" onclick = "authorize(accept, reject)"/>

And then:

function accept() {
   //Add access token to hidden input
   $('#hiddenAccessToken').val(accessToken);
   $('#membershipInfo').submit();
}


问:
Elasticsearch 7: Cant parse date
I have an elasticsearch index with a mapping that has a date field

```<code>"datetime": {
                "type": "date",
                "format": "date_optional_time"
            }
</code>```

but when i try to pass in

'05/09/2019 11:43:09 AM'

and index it, i get

```<code>elasticsearch.exceptions.RequestError: RequestError(400, u'mapper_parsing_exception', u"failed to parse field [datetime] of type [date] in document with id 'VhhGBWsBeH-i3pqE8QBW'")
</code>```

i tried

```<code>"datetime": {
               "type": "text"
            }
</code>```

and this works of course.

What am i doing wrong? Which date format should i use for dates like 05/09/2019 11:43:09 AM?

@Kamal

Thanks a lot for your help. just one more thing, the above format fails for '05/09/2019 01:00:37 PM' or for any value with PM. i tried

```<code>"datetime": {
                "type": "date",
                "format": "MM/dd/yyyy HH:mm:ss a||MM/dd/yyyy HH:mm:ss p"
            }
</code>```

but i get

"Invalid format: [MM/dd/yyyy HH:mm:ss p]: Pad letter 'p' must be followed by valid pad pattern: MM/dd/yyyy HH:mm:ss p"

if i try

```<code>"datetime": {
                "type": "date",
                "format": "MM/dd/yyyy HH:mm:ss aa"
            }
</code>```

i get

```<code>elasticsearch.exceptions.RequestError: RequestError(400, u'illegal_argument_exception', u'Invalid format: [MM/dd/yyyy HH:mm:ss aa]: Too many pattern letters: a')
</code>```

答:
That's because the format you've mentioned for your date doesn't adhere to the date_optional_time, which is based on ISO 8601 standards.

From the elasticsearch link related to date_optional_time, it mentions the below comment:

date_optional_time or strict_date_optional_time

A generic ISO datetime parser where the date is mandatory and the time is optional.

Based on ISO 8601, below are some of the valid values:

yyyy-MM-ddTHH:mm:ss

yyyy-MM-ddTHH:mm

yyyy-MM-ddTHH:mm:ss.SSSSSSSSS.

Also note that ISO 8601 uses 24 hours date format.

So looking at your sample, the below date value would work for this.

```<code>POST <your_index_name>/_doc/1
{
  "datetime": "2019-05-09T13:30:00"
}
</code>```

Solution:

The format you are looking for is MM/dd/yyyy hh:mm:ss a OR dd/MM/yyyy hh:mm:ss a (I leave it to you based on your requirements both formats would work).

Below is how your mapping would be.

```<code>PUT <your_index_name>
{
   "mappings":{
      "properties":{
         "datetime":{
            "type":"date",
            "format":"date_optional_time||MM/dd/yyyy hh:mm:ss a"
         }
      }
   }
}
</code>```

The below would now work:

```<code>POST <your_index_name>/_doc/1
{
  "datetime": "05/09/2019 11:43:09 AM"
}
</code>```

Hope that helps!

Title: Elasticsearch 7: Cant parse date

Body:
I have an elasticsearch index with a mapping that has a date field

"datetime": {
                "type": "date",
                "format": "date_optional_time"
            }

but when i try to pass in

'05/09/2019 11:43:09 AM'

and index it, i get

elasticsearch.exceptions.RequestError: RequestError(400, u'mapper_parsing_exception', u"failed to parse field [datetime] of type [date] in document with id 'VhhGBWsBeH-i3pqE8QBW'")

i tried

"datetime": {
               "type": "text"
            }

and this works of course.

What am i doing wrong? Which date format should i use for dates like 05/09/2019 11:43:09 AM?

@Kamal

Thanks a lot for your help. just one more thing, the above format fails for '05/09/2019 01:00:37 PM' or for any value with PM. i tried

"datetime": {
                "type": "date",
                "format": "MM/dd/yyyy HH:mm:ss a||MM/dd/yyyy HH:mm:ss p"
            }

but i get

"Invalid format: [MM/dd/yyyy HH:mm:ss p]: Pad letter 'p' must be followed by valid pad pattern: MM/dd/yyyy HH:mm:ss p"

if i try

"datetime": {
                "type": "date",
                "format": "MM/dd/yyyy HH:mm:ss aa"
            }

i get

elasticsearch.exceptions.RequestError: RequestError(400, u'illegal_argument_exception', u'Invalid format: [MM/dd/yyyy HH:mm:ss aa]: Too many pattern letters: a')

Body:
That's because the format you've mentioned for your date doesn't adhere to the date_optional_time, which is based on ISO 8601 standards.

From the elasticsearch link related to date_optional_time, it mentions the below comment:

date_optional_time or strict_date_optional_time

A generic ISO datetime parser where the date is mandatory and the time is optional.

Based on ISO 8601, below are some of the valid values:

yyyy-MM-ddTHH:mm:ss

yyyy-MM-ddTHH:mm

yyyy-MM-ddTHH:mm:ss.SSSSSSSSS.

Also note that ISO 8601 uses 24 hours date format.

So looking at your sample, the below date value would work for this.

POST <your_index_name>/_doc/1
{
  "datetime": "2019-05-09T13:30:00"
}

Solution:

The format you are looking for is MM/dd/yyyy hh:mm:ss a OR dd/MM/yyyy hh:mm:ss a (I leave it to you based on your requirements both formats would work).

Below is how your mapping would be.

PUT <your_index_name>
{
   "mappings":{
      "properties":{
         "datetime":{
            "type":"date",
            "format":"date_optional_time||MM/dd/yyyy hh:mm:ss a"
         }
      }
   }
}

The below would now work:

POST <your_index_name>/_doc/1
{
  "datetime": "05/09/2019 11:43:09 AM"
}

Hope that helps!


问:
How can I access methods inside a class from outside of class
I have a couple questions regarding Class files. I have the below Class

```<code>class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }
</code>```

my problem is how can I go and access the doSomeQuery function from outside the class file? Inside there is no issue accessing the function but I need to be able to call it from outside.
I tried something like this

```<code>const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController
</code>```

doing so newTest never exposes the doSomeQuery method.

Also what are the limitations of a method ? Can it only be a simple one or can it be async and use promises etc ?

答:
I figured it out after some forth and back, part of my problem was the fact that for some reason visual studio code did not show me the method which threw me off. Manually typing made it ultimately avail.

Here is my Class and i actually moved the config and couchbase itself into the class file so no need to pass it anymore.

```<code>const couchbase = require("couchbase")
const config = require("../config/config")

 class CouchController {
    constructor() {
        // You may either pass couchbase and config as params, or import directly into the controller
        this.cluster = new couchbase.Cluster(config.cluster);
        this.cluster.authenticate(config.userid, config.password);
        this.bucket = this.cluster.openBucket(config.bucket);
        this.N1qlQuery = couchbase.N1qlQuery;
      }

            getDoc2(docID){
                return new Promise((resolve,reject)=>{
                  this.bucket.get(docID ,(err, result)=>{
                    if(err) return reject(err);
                    return resolve({docID,result});
                  });
                });
              }

      }

     module.exports = CouchController
</code>```

And here is how i call my Class now and connect to the backend to fetch my data.

```<code>const CouchController = require("./controllers/CouchController")
let newTest = new CouchController

const test= async()=>{
    let { docID, result } = await newTest.getDoc2("grid_info::20b05192-79e9-4e9d-94c9-91a4fc0a2765")

    console.log(docID)
    console.log(result)
}
</code>```

Body:
I have a couple questions regarding Class files. I have the below Class

class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }

my problem is how can I go and access the doSomeQuery function from outside the class file? Inside there is no issue accessing the function but I need to be able to call it from outside.
I tried something like this

const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController

doing so newTest never exposes the doSomeQuery method.

Also what are the limitations of a method ? Can it only be a simple one or can it be async and use promises etc ?

Body:
I figured it out after some forth and back, part of my problem was the fact that for some reason visual studio code did not show me the method which threw me off. Manually typing made it ultimately avail.

Here is my Class and i actually moved the config and couchbase itself into the class file so no need to pass it anymore.

const couchbase = require("couchbase")
const config = require("../config/config")

 class CouchController {
    constructor() {
        // You may either pass couchbase and config as params, or import directly into the controller
        this.cluster = new couchbase.Cluster(config.cluster);
        this.cluster.authenticate(config.userid, config.password);
        this.bucket = this.cluster.openBucket(config.bucket);
        this.N1qlQuery = couchbase.N1qlQuery;
      }

            getDoc2(docID){
                return new Promise((resolve,reject)=>{
                  this.bucket.get(docID ,(err, result)=>{
                    if(err) return reject(err);
                    return resolve({docID,result});
                  });
                });
              }

      }

     module.exports = CouchController

And here is how i call my Class now and connect to the backend to fetch my data.

const CouchController = require("./controllers/CouchController")
let newTest = new CouchController

const test= async()=>{
    let { docID, result } = await newTest.getDoc2("grid_info::20b05192-79e9-4e9d-94c9-91a4fc0a2765")

    console.log(docID)
    console.log(result)
}


问:
Searching for a value in pyrebase

I have check pyrebase and i want to search for the IDNumber of each user.

i have tried using

```<code>db.child("Users").order_by_child("IDNumber").equal_to(2011445392).get()
</code>```

But it gave me an error related to index not defined.
Is there a way to search for IDNumber similar to SQL?

答:
Your query is correct. The error about index not defined occurs because you haven't set any rule on IDNumber.

You need to configure rules on your indexes like this :

```<code>{
  "rules": {
    "Users": {
      ".indexOn": ["IDNumber"]
    }
  }
}
</code>```

https://firebase.google.com/docs/database/security#section-defining-indexes

Title: Searching for a value in pyrebase

Body:
I have check pyrebase and i want to search for the IDNumber of each user.

i have tried using

db.child("Users").order_by_child("IDNumber").equal_to(2011445392).get()

But it gave me an error related to index not defined.
Is there a way to search for IDNumber similar to SQL?

Body:
Your query is correct. The error about index not defined occurs because you haven't set any rule on IDNumber.

You need to configure rules on your indexes like this :

{
  "rules": {
    "Users": {
      ".indexOn": ["IDNumber"]
    }
  }
}

https://firebase.google.com/docs/database/security#section-defining-indexes


问:
Teradara SQL - Operation with max-min dates
suppose I have the following data frame in Reradata SQL.
How can I get the variation between the highest and lowest date, at user level? Regards</p>

```<code>Initial table
   user    date   price
    1       1-1       10
    1       2-1       20
    1       3-1       30
    2       1-1       12
    2       2-1       22
    2       3-1       32
    3       1-1       13
    3       2-1       23
    3       3-1       33

 Final table

user   var_price
1       30/10-1
2       32/12-1
3       33/13-1
</code>```

答:
Is this what you want?

```<code>select user, max(price) / min(price) - 1
from t
group by user;
</code>```

Your values are monotonically increasing, so max() and min() seems like the simplest solution.

EDIT:

You can use window functions:

```<code>select user, max(last_price) / max(first_price) - 1
from (select t.*,
             first_value(price) over (partition by user order by date rows between unbounded preceding and current_row) as first_price,
             first_value(price) over (partition by user order by date desc rows between unbounded preceding and current_row) as last_price
      from t
     ) t
group by user;
</code>```

Body:
suppose I have the following data frame in Reradata SQL.
How can I get the variation between the highest and lowest date, at user level? Regards

Initial table
   user    date   price
    1       1-1       10
    1       2-1       20
    1       3-1       30
    2       1-1       12
    2       2-1       22
    2       3-1       32
    3       1-1       13
    3       2-1       23
    3       3-1       33

 Final table

user   var_price
1       30/10-1
2       32/12-1
3       33/13-1

Body:
Is this what you want?

select user, max(price) / min(price) - 1
from t
group by user;

Your values are monotonically increasing, so max() and min() seems like the simplest solution.

EDIT:

You can use window functions:

select user, max(last_price) / max(first_price) - 1
from (select t.*,
             first_value(price) over (partition by user order by date rows between unbounded preceding and current_row) as first_price,
             first_value(price) over (partition by user order by date desc rows between unbounded preceding and current_row) as last_price
      from t
     ) t
group by user;


问:
How to upload and display image django 2?
I tried to hardcode path and nothing worked. What's wrong with my code? I'm getting 404 error and image isn't showing up.

settings.py

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static/')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'blog/media')
</code>```

models.py

```<code>image = models.ImageField(upload_to = 'media/', blank = True)
</code>```

urls.py

```<code>urlpatterns = [...] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

forms.py
    class PostForm(forms.ModelForm):

```<code>    class Meta:

        model = Post
        fields = ('author','title', 'text','image')

        widgets = {
            'title': forms.TextInput(attrs={'class': 'textinputclass'}),
            'text': forms.Textarea(attrs={'class': 'editable medium-editor-textarea postcontent'}),
        }
</code>```

html

```<code>        <img src="{{post.image.url}}">
</code>```

答:
```<code>static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

from what I understand you are trying to make the django serve static files with this, static-files and media are separate, that line you have serves statics like css, js etc which resides in STATIC_ROOT while you need to serve MEDIA_ROOT so

```<code>static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

adding this part should work, but I highly discourage using this in the actual deployment, media files should be handled by a web server like nginx and not an application server.

Body:
I tried to hardcode path and nothing worked. What's wrong with my code? I'm getting 404 error and image isn't showing up.

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static/')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'blog/media')

models.py

image = models.ImageField(upload_to = 'media/', blank = True)

urls.py

urlpatterns = [...] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

forms.py
    class PostForm(forms.ModelForm):

    class Meta:

        model = Post
        fields = ('author','title', 'text','image')

        widgets = {
            'title': forms.TextInput(attrs={'class': 'textinputclass'}),
            'text': forms.Textarea(attrs={'class': 'editable medium-editor-textarea postcontent'}),
        }

html

Body:
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

from what I understand you are trying to make the django serve static files with this, static-files and media are separate, that line you have serves statics like css, js etc which resides in STATIC_ROOT while you need to serve MEDIA_ROOT so

static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

adding this part should work, but I highly discourage using this in the actual deployment, media files should be handled by a web server like nginx and not an application server.


问:
Regex to match all parameters in application packets
I have a list of parameters in many packets that I need to catch them all using regex.
Each parameter will start with = and will close with &
Example: addonName=CatchMe1&
All the parameters are variables and I cant know what they will contain (String, Integer etc.)

Thank You.

```<code>POST /stringos.txt?addonName=CatchMe1&application=CatchMe2&platform=CatchMe3&platformVersion=CatchMe4&lastVersion=CatchMe5&downloadCount=CatchMe6 HTTP/1.1
Host: Host.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: close

addonName=CatchMe1&application=CatchMe2&platform=CatchMe3&platformVersion=CatchMe4&lastVersion=CatchMe5&downloadCount=CatchMe6
</code>```

Body:
I have a list of parameters in many packets that I need to catch them all using regex.
Each parameter will start with = and will close with &
Example: addonName=CatchMe1&
All the parameters are variables and I cant know what they will contain (String, Integer etc.)

Thank You.

POST /stringos.txt?addonName=CatchMe1&application=CatchMe2&platform=CatchMe3&platformVersion=CatchMe4&lastVersion=CatchMe5&downloadCount=CatchMe6 HTTP/1.1
Host: Host.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: close

addonName=CatchMe1&application=CatchMe2&platform=CatchMe3&platformVersion=CatchMe4&lastVersion=CatchMe5&downloadCount=CatchMe6

Body:
For now I managed to use this regex for my problem.

.*?=(.*?)&.*?=(.*?)&.*?=(.*?)&.*?=(.*?)&.*?=(.*?)&.*?=(.*?) HTTP/1.1

Thanks.


问:
How to fix Excel.Application error that occurs randomly when instantiating the Excel.Application object
I have a c# program that opens an excel worksheet, populates it with some data, and retrieves some information from the worksheet before closing the sheet.  This happens several times inside of a loop.  The program executes for some time completing the loop and then fails at random times during the loop with the following error:

System.Runtime.InteropServicdes.COMException (0x80080005): Retrieving
  the COM class factor for component with CLSID {xxx} failed due to the
  following error: 80080005 Server execution failed [Exception from
  HRESULT:0x80080005 (CO_E_SERVER_EXCEC_FAILURE)).

I have checked my reference for Microsoft.Office.Interop.Excel and it is the Microsoft Excel 16.0 Object Library version 1.9.0.0 and I have Excel 2016 installed.  The code that is causing the problem is similar to the following:

```<code>for (int i = 0; i < 100; i++)
{
     Excel.Application xlApp;
     Excel.Workbooks xlWorkBooks;
     Excel.Workbook xlWorkBook;
     Excel.Sheets xlWorksheets;
     Excel.Worksheet xlWorkSheet;
     object misValue = System.Reflection.Missing.Value;

     xlApp = new Excel.Application(); //line that causes error

     xlApp.Visible = false;
     xlApp.ScreenUpdating = false;
     xlWorkBooks = xlApp.Workbooks;
     xlWorkBook = xlWorkBooks.Open(IIHSTemplate.Text, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
     xlWorksheets = xlWorkBook.Worksheets;
     xlWorkSheet = xlWorksheets["Automatic-Data-Analysis"];
     IIHSDemerit = Convert.ToDouble((xlWorkSheet.Cells[30, 14] as Excel.Range).Value2);

      xlWorkBook.Close(false, misValue, misValue);
      xlApp.Quit();

      releaseObject(xlWorksheets);
      releaseObject(xlWorkSheet);
      releaseObject(xlWorkBooks);
      releaseObject(xlWorkBook);
      releaseObject(xlApp);
}

private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

</code>```

My program writes the results of the excel data to a text file and executes several times with no errors.  After a random number of iterations (number is different each time I run the program) the program will fail with the error listed above.  Any ideas on what is causing the error and how to correct it?

答: Solution was to move the instantiation and releasing of the Excel app object out of the loop since I only needed to be opening and closing workbooks inside the loop.  Thanks to @SmrtGrunt for pointing that out in comments.  </p>

Body:
I have a c# program that opens an excel worksheet, populates it with some data, and retrieves some information from the worksheet before closing the sheet.  This happens several times inside of a loop.  The program executes for some time completing the loop and then fails at random times during the loop with the following error:

System.Runtime.InteropServicdes.COMException (0x80080005): Retrieving
  the COM class factor for component with CLSID {xxx} failed due to the
  following error: 80080005 Server execution failed [Exception from
  HRESULT:0x80080005 (CO_E_SERVER_EXCEC_FAILURE)).

I have checked my reference for Microsoft.Office.Interop.Excel and it is the Microsoft Excel 16.0 Object Library version 1.9.0.0 and I have Excel 2016 installed.  The code that is causing the problem is similar to the following:

for (int i = 0; i < 100; i++)
{
     Excel.Application xlApp;
     Excel.Workbooks xlWorkBooks;
     Excel.Workbook xlWorkBook;
     Excel.Sheets xlWorksheets;
     Excel.Worksheet xlWorkSheet;
     object misValue = System.Reflection.Missing.Value;

     xlApp = new Excel.Application(); //line that causes error

     xlApp.Visible = false;
     xlApp.ScreenUpdating = false;
     xlWorkBooks = xlApp.Workbooks;
     xlWorkBook = xlWorkBooks.Open(IIHSTemplate.Text, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
     xlWorksheets = xlWorkBook.Worksheets;
     xlWorkSheet = xlWorksheets["Automatic-Data-Analysis"];
     IIHSDemerit = Convert.ToDouble((xlWorkSheet.Cells[30, 14] as Excel.Range).Value2);

      xlWorkBook.Close(false, misValue, misValue);
      xlApp.Quit();

      releaseObject(xlWorksheets);
      releaseObject(xlWorkSheet);
      releaseObject(xlWorkBooks);
      releaseObject(xlWorkBook);
      releaseObject(xlApp);
}

private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

My program writes the results of the excel data to a text file and executes several times with no errors.  After a random number of iterations (number is different each time I run the program) the program will fail with the error listed above.  Any ideas on what is causing the error and how to correct it?


问:
Why Laravel 5.8 makes repeated queries to the database when working with the session
In Laravel 5.8, when working with a session, two extra queries to the database are performed compared to Laravel 5.7.

Laravel 5.7

```<code>select * from `sessions` where `id` = '00kaQxJLG6roUAp9DaCui7esa31sbthHqEzwW62H' limit 1
</code>```

Laravel 5.8

```<code>select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

update `sessions` set `payload` = 'YTozOntzOjY6Il90b2tlbiI7czo0MDoiQm12QlFHNzVNRVpZcTRkMWZwcmNMS2kwcm12czlvZkpXZUg0cFpEQyI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MTY6Imh0dHA6Ly9kZXYubG9jYWwiO31zOjY6Il9mbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX19', `last_activity` = 1559161593, `user_id` = '', `ip_address` = '127.0.0.1', `user_agent` = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36' where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD'

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1
</code>```

New installation. No packages.

答:
You have written the same query twice.

```<code>select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1
</code>```

You can solve this by initializing this query to a variable and then using the variable whenever you need to.

```<code>$session = select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1;
</code>```

This should remove the duplicates.

The query in eloquent

```<code>$session = Session::query()->where('id','anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD')->take(1)->get();
</code>```

Body:
In Laravel 5.8, when working with a session, two extra queries to the database are performed compared to Laravel 5.7.

Laravel 5.7

select * from `sessions` where `id` = '00kaQxJLG6roUAp9DaCui7esa31sbthHqEzwW62H' limit 1

Laravel 5.8

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

update `sessions` set `payload` = 'YTozOntzOjY6Il90b2tlbiI7czo0MDoiQm12QlFHNzVNRVpZcTRkMWZwcmNMS2kwcm12czlvZkpXZUg0cFpEQyI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MTY6Imh0dHA6Ly9kZXYubG9jYWwiO31zOjY6Il9mbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX19', `last_activity` = 1559161593, `user_id` = '', `ip_address` = '127.0.0.1', `user_agent` = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36' where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD'

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

New installation. No packages.

Body:
You have written the same query twice.

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

You can solve this by initializing this query to a variable and then using the variable whenever you need to.

$session = select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1;

This should remove the duplicates.

The query in eloquent

$session = Session::query()->where('id','anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD')->take(1)->get();


问:
Asynchronous tasks in grunt.registerTask
I need to call two functions within grunt.registerTask, but the second function has to be called after the first function is done.

So I was wondering if we can use callbacks or promises or other asynchronous mechanisms within grunt.registerTask.

(More specifically, I need to launch karma in my first function call, and run karma in the second function call (to execute the initial unit tests). But in order to run karma, I need to launch it first. And that's what I'm missing.)

答:
For the sake of simplicity... having this Grunfile.js

```<code>grunt.registerTask('a', function () {

    let done = this.async();

    setTimeout(function () {
        console.log("a");
        done();
    }, 3000);
});

grunt.registerTask('b', function () {

    let done = this.async();

    console.log("b1");

    setTimeout(function () {
        console.log("b2");
        done();
    }, 3000);

    console.log("b3");
});

grunt.registerTask('c', function () {
    console.log("c");
});

grunt.registerTask("run", ["a", "b", "c"]);
</code>```

and then running run task, will produce the following output

```<code>Running "a" task
a

Running "b" task
b1
b3
b2 <-- take a look here

Running "c" task
c

Done.
</code>```

The command is executed in this order

wait 3000 ms

console.log("a")

console.log("b1")

console.log("b3")

wait 3000 ms

console.log("b2")

console.log("c")

Body:
For the sake of simplicity... having this Grunfile.js

grunt.registerTask('a', function () {

    let done = this.async();

    setTimeout(function () {
        console.log("a");
        done();
    }, 3000);
});

grunt.registerTask('b', function () {

    let done = this.async();

    console.log("b1");

    setTimeout(function () {
        console.log("b2");
        done();
    }, 3000);

    console.log("b3");
});

grunt.registerTask('c', function () {
    console.log("c");
});

grunt.registerTask("run", ["a", "b", "c"]);

and then running run task, will produce the following output

Running "a" task
a

Running "b" task
b1
b3
b2 <-- take a look here

Running "c" task
c

Done.

The command is executed in this order

wait 3000 ms

console.log("a")

console.log("b1")

console.log("b3")

wait 3000 ms

console.log("b2")

console.log("c")


问:
Collaboration of command line and UI widgets
Could I assume that every powerful application would provide a command line/script input?

Even there are many many fancy widgets in current software, but I still think command line input mode in UI is still necessary nowadays, since command line/script input is more straight forward and neat. If application could provide more domain specific script language, that would be more powerful.

Is there some book provide some theory on this? Effective UI?

答:
You ask about books related to the theory of this. The theory is one of separating presentation logic from business logic, or separation of concerns. This goes by many names such as model/view/controller, model/view/presenter, and many others, and there are plenty of books on the subject.

If you design an application this way, the presentation layer (ie: user interface) is a separate entity that can be replaced with another. Thus, you could have a graphical user interface as well as a textual one. Arguably, in a perfect world all apps would work this way, with a desktop UI, a web UI, a command line UI, and so on.

This all comes at a great cost, however. It is difficult to design applications in this way and, because of the loose coupling between the application and the UI there may be performance penalties. To further add to the difficulty, it is inherently difficult to provide a rich command line interface to a complex application. How would you go about creating command line input to Adobe photoshop or Microsoft Excel, for example?

So while it's possible in a theoretical sense, from a practical sense it becomes more difficult as the complexity of the UI goes up. There are many applications that are able to accomplish this, however. For example, many version control systems such as BitKeeper, AccuRev and others have both command line and graphical interfaces.

So, yes, it's possible that most applications could implement both a graphical UI and a command line UI, and it's true that a few of them do, it's not reasonable to expect that all applications will or even can.


问:
How to fix "Bad interface file" during installation of package with stack?
I'm trying to install stylish-haskell package with

```<code>stack install stylish-haskell
</code>```

but I get "Bad interface file" error.

Here's log of installation:

```<code>ptparse-applicative-0.14.3.0.log
Configuring optparse-applicative-0.14.3.0...
Preprocessing library for optparse-applicative-0.14.3.0..
Building library for optparse-applicative-0.14.3.0..
[ 1 of 16] Compiling Options.Applicative.Help.Levenshtein ( Options/Applicative/Help/Levenshtein.hs, .stack-work/dist/x86_64-linux-tinfo6/Cabal-2.4.0.1/build/Options/Applicative/Help/Levenshtein.o )
[ 2 of 16] Compiling Options.Applicative.Help.Pretty ( Options/Applicative/Help/Pretty.hs, .stack-work/dist/x86_64-linux-tinfo6/Cabal-2.4.0.1/build/Options/Applicative/Help/Pretty.o )
Options/Applicative/Help/Pretty.hs:6:1: error:
    Bad interface file: /home/george/.stack/snapshots/x86_64-linux-tinfo6/lts-13.21/8.6.5/lib/x86_64-linux-ghc-8.6.5/ansi-wl-pprint-0.6.8.2-FavuR50rvZs3UXCXkBzL8N/Text/PrettyPrint/ANSI/Leijen.hi
        Data.Binary.getPrim: end of file
  |
6 | import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (<>), columns)
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

答: As duplode has pointed out, this is likely a case of Stack issue #3248. A workaround is stack exec ghc-pkg unregister ansi-wl-pprint-0.6.8.2 followed by stack build, which will trigger a reinstall of the affected package.

Body:
I'm trying to install stylish-haskell package with

stack install stylish-haskell

but I get "Bad interface file" error.

Here's log of installation:

ptparse-applicative-0.14.3.0.log
Configuring optparse-applicative-0.14.3.0...
Preprocessing library for optparse-applicative-0.14.3.0..
Building library for optparse-applicative-0.14.3.0..
[ 1 of 16] Compiling Options.Applicative.Help.Levenshtein ( Options/Applicative/Help/Levenshtein.hs, .stack-work/dist/x86_64-linux-tinfo6/Cabal-2.4.0.1/build/Options/Applicative/Help/Levenshtein.o )
[ 2 of 16] Compiling Options.Applicative.Help.Pretty ( Options/Applicative/Help/Pretty.hs, .stack-work/dist/x86_64-linux-tinfo6/Cabal-2.4.0.1/build/Options/Applicative/Help/Pretty.o )
Options/Applicative/Help/Pretty.hs:6:1: error:
    Bad interface file: /home/george/.stack/snapshots/x86_64-linux-tinfo6/lts-13.21/8.6.5/lib/x86_64-linux-ghc-8.6.5/ansi-wl-pprint-0.6.8.2-FavuR50rvZs3UXCXkBzL8N/Text/PrettyPrint/ANSI/Leijen.hi
        Data.Binary.getPrim: end of file
  |
6 | import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (<>), columns)
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


问:
using the unix command "source" in ansible
I have the following ansible playbooks:

runWithDotSlash.yml

```<code>---
 - hosts: user@myhost.local
   tasks:
   - name: try running a script with dot slash
     command: ./script.sh
</code>```

runWithSource.yml

```<code>---
 - hosts: user@myhost.local
   tasks:
   - name: try running a script with source
     command: source script.sh
</code>```

When I ssh into user@myhost.local I am taken to the home directory of user and I can run script.sh both with dot slash and with source. However only the first playbook works.

I am running the playbooks with the following command:

```<code>ansible-playbook runWithDotSlash.yml
ansible-playbook runWithSource.yml
</code>```

The second gives the following error message:

```<code>FAILED! => {"changed": false, "cmd": "source script.sh", "msg": "[Errno 2] No such file or directory", "rc": 2}
</code>```

Here is script.sh which is in the home directory of user on myhost

```<code>#!/bin/bash
echo $1 > ansible_tempfile
</code>```

Why does source not work? What can I do to make it work?

答: source is a bash command. By default, the command module uses sh. Calling bash -c 'source script.sh' should work.

Body:
I have the following ansible playbooks:

runWithDotSlash.yml

---
 - hosts: user@myhost.local
   tasks:
   - name: try running a script with dot slash
     command: ./script.sh

runWithSource.yml

---
 - hosts: user@myhost.local
   tasks:
   - name: try running a script with source
     command: source script.sh

When I ssh into user@myhost.local I am taken to the home directory of user and I can run script.sh both with dot slash and with source. However only the first playbook works.

I am running the playbooks with the following command:

ansible-playbook runWithDotSlash.yml
ansible-playbook runWithSource.yml

The second gives the following error message:

FAILED! => {"changed": false, "cmd": "source script.sh", "msg": "[Errno 2] No such file or directory", "rc": 2}

Here is script.sh which is in the home directory of user on myhost

#!/bin/bash
echo $1 > ansible_tempfile

Why does source not work? What can I do to make it work?


问:
Call Kotlin function with Lambda parameters in Java
How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

```<code>fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }
</code>```

答:
You can call it with normal Java 8 lambdas, since Kotlin is actually using a single-method interface on the backend.</p>

```<code>myFoo.getToken(tokenUrl, successString -> { ... }, error -> { ... });
</code>```

Body:
How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }

Body:
You can call it with normal Java 8 lambdas, since Kotlin is actually using a single-method interface on the backend.

myFoo.getToken(tokenUrl, successString -> { ... }, error -> { ... });


问:
Application login system not working SQL LOCAL
I'am doing my program and i need login and register system. My register system is working but login not.

I have done register system

```<code>SqlConnection sqlCon = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From UsersConfig where Email='" + textBox1.Text.Trim() + "' and Password='" + textBox2.Text.Trim() + "'", sqlCon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows[0][0].ToString() == "1")
{
    SqlConnection sqlConn = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True");
    SqlDataAdapter sdaa = new SqlDataAdapter("Select Count(*) From UsersConfig where Email='" + textBox1.Text.Trim() + "' and Password='" + textBox2.Text.Trim() + "' and AdminYes='" + "1" + "'", sqlConn);
    DataTable dtbll = new DataTable();
    sdaa.Fill(dtbll);
    if (dtbll.Rows[0][0].ToString() == "1")
    {
        MessageBox.Show("Has admin");
        Form adminpanel = new AdminPanel();
        adminpanel.Show();
        this.Hide();
    }
    else
    {
        MessageBox.Show("Hasn't got admin");
    }
}
else
{
    MessageBox.Show("Not working!");
}
</code>```

I don't have error message

答:
The suggestions from the comments above and the Microsoft link would change the code to be something like this below. Also, using parameters instead of building the string manually is HIGHLY recommended as building the SQL string can lead to SQL injection security vulnerabilities. </p>

<p>NOTE: I do not think this will fix the error you are having, but it may help find the issue. </p>

```<code>string connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True";

using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
    string email = textBox1.Text.Trim();
    string pwd = textBox2.Text.Trim();

    //NOTE: passwords shouldn't be stored in plain text.
    //There should be an hashing step here like:
    pwd = MyCustomPasswordHasher(email, pwd);

    string sql = "Select [AdminYes] From UsersConfig where Email=@user and Password=@password";

    SqlCommand command = new SqlCommand(sql, sqlCon);
    command.Parameters.AddWithValue("@user", email);
    command.Parameters.AddWithValue("@password", pwd);

    try
    {
        command.Connection.Open();
        object result = command.ExecuteScalar();

        if (result == null)
        {
            MessageBox.Show("Invalid credentials!");
        }
        else if (result.ToString() == "1")
        {
            MessageBox.Show("Has admin");
            Form adminpanel = new AdminPanel();
            adminpanel.Show();
            this.Hide();
        }
        else
        {
            MessageBox.Show("Hasn't got admin");
        }
    }
    catch (SqlException ex)
    {
        MessageBox.Show("Database errors!");
    }
}
</code>```

Body:
I'am doing my program and i need login and register system. My register system is working but login not.

I have done register system

SqlConnection sqlCon = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From UsersConfig where Email='" + textBox1.Text.Trim() + "' and Password='" + textBox2.Text.Trim() + "'", sqlCon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows[0][0].ToString() == "1")
{
    SqlConnection sqlConn = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True");
    SqlDataAdapter sdaa = new SqlDataAdapter("Select Count(*) From UsersConfig where Email='" + textBox1.Text.Trim() + "' and Password='" + textBox2.Text.Trim() + "' and AdminYes='" + "1" + "'", sqlConn);
    DataTable dtbll = new DataTable();
    sdaa.Fill(dtbll);
    if (dtbll.Rows[0][0].ToString() == "1")
    {
        MessageBox.Show("Has admin");
        Form adminpanel = new AdminPanel();
        adminpanel.Show();
        this.Hide();
    }
    else
    {
        MessageBox.Show("Hasn't got admin");
    }
}
else
{
    MessageBox.Show("Not working!");
}

I don't have error message

Body:
The suggestions from the comments above and the Microsoft link would change the code to be something like this below. Also, using parameters instead of building the string manually is HIGHLY recommended as building the SQL string can lead to SQL injection security vulnerabilities.

NOTE: I do not think this will fix the error you are having, but it may help find the issue.

string connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True";

using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
    string email = textBox1.Text.Trim();
    string pwd = textBox2.Text.Trim();

    //NOTE: passwords shouldn't be stored in plain text.
    //There should be an hashing step here like:
    pwd = MyCustomPasswordHasher(email, pwd);

    string sql = "Select [AdminYes] From UsersConfig where Email=@user and Password=@password";

    SqlCommand command = new SqlCommand(sql, sqlCon);
    command.Parameters.AddWithValue("@user", email);
    command.Parameters.AddWithValue("@password", pwd);

    try
    {
        command.Connection.Open();
        object result = command.ExecuteScalar();

        if (result == null)
        {
            MessageBox.Show("Invalid credentials!");
        }
        else if (result.ToString() == "1")
        {
            MessageBox.Show("Has admin");
            Form adminpanel = new AdminPanel();
            adminpanel.Show();
            this.Hide();
        }
        else
        {
            MessageBox.Show("Hasn't got admin");
        }
    }
    catch (SqlException ex)
    {
        MessageBox.Show("Database errors!");
    }
}


问:
Kotlin getParcelableArray from intent bundle not able to cast it to custom type
I am running into a weird problem . I have a class A which implements Parcelable interface in kotlin.

I am passing the array of class A from one activity to another no issues here.

```<code> var arrayOfA:Array<A> // just to tell the type assume the array is initialised with the value
 intent.putExtra("array", arrayOfA)
</code>```

But while receiving it in another activity , I am not able to assign it to variable of type Array it is asking me to assign it to Array when A is on type parcelable why I am not able to assign it the variable.

```<code>in second Activity
var arrayOfA:Array<A>?=null

arrayA=intent.get("array") as Array<A> // Problem here. Class cast exception
</code>```

I am not able to understand why. Can some one help me here. I don't want to change the type of variable to Array as it as many inter depedencies.(The class here is just a demonstration)

========================================

```<code>class A(val a:String?,val b:String?):Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString()) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(a)
        parcel.writeString(b)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<A> {
        override fun createFromParcel(parcel: Parcel): A {
            return A(parcel)
        }

        override fun newArray(size: Int): Array<A?> {
            return arrayOfNulls(size)
        }
    }
}
</code>```

答:
I ran into the same problem. This is how I was able to workaround it:

arrayOfA = intent.getParcelableArrayExtra("array").map { it as A }.toTypedArray()

For some reason this does not work:

arrayOfA = intent.getParcelableArrayExtra("array") as Array

That unfortunately exhibits a warning

Unchecked cast: Array<(out) Parcelable!>! to Array)

and runtime exception

java.lang.ClassCastException: android.os.Parcelable[] cannot be cast
  to com.company.app.A[]

Body:
I am running into a weird problem . I have a class A which implements Parcelable interface in kotlin.

I am passing the array of class A from one activity to another no issues here.

 var arrayOfA:Array // just to tell the type assume the array is initialised with the value
 intent.putExtra("array", arrayOfA)

But while receiving it in another activity , I am not able to assign it to variable of type Array it is asking me to assign it to Array when A is on type parcelable why I am not able to assign it the variable.

in second Activity
var arrayOfA:Array?=null

arrayA=intent.get("array") as Array // Problem here. Class cast exception

I am not able to understand why. Can some one help me here. I don't want to change the type of variable to Array as it as many inter depedencies.(The class here is just a demonstration)

========================================

class A(val a:String?,val b:String?):Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString()) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(a)
        parcel.writeString(b)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator {
        override fun createFromParcel(parcel: Parcel): A {
            return A(parcel)
        }

        override fun newArray(size: Int): Array {
            return arrayOfNulls(size)
        }
    }
}

Body:
I ran into the same problem. This is how I was able to workaround it:

arrayOfA = intent.getParcelableArrayExtra("array").map { it as A }.toTypedArray()

For some reason this does not work:

arrayOfA = intent.getParcelableArrayExtra("array") as Array<A>

That unfortunately exhibits a warning

Unchecked cast: Array<(out) Parcelable!>! to Array)

and runtime exception

java.lang.ClassCastException: android.os.Parcelable[] cannot be cast
  to com.company.app.A[]


问:
Use PHP to get xls(Excel files) PHPOffice PHPExcel
Hy guys.

Thank you for your help. The answers in this forum are great!

In my site, i want to see the content from a xls Excel Spreadsheet.
After long searching i found this Project:
https://github.com/PHPOffice/PHPExcel/

I get the classes and tried it. Works great!

It works so good, that i can't believe, that it is free.
Is it free to use?

at the top of my site, i got this error massage:
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in test/Classes/PHPExcel/Shared/OLE.php on line 288

答:
about the first question (if it's free).

Since the author of repository it's under of GNU (in the repo has the link, but if you didn't read it or see it here's -> https://github.com/PHPOffice/PHPExcel/blob/master/license.md).

Second, about your continue 2 error, you need check first which version of PHP you're running, those continues issues are very frequently in some old libraries (mainly this one the last significant update was 6 years ago).

If you check the issues of Github you'll see there's an exact bug issue opened about what you're asking here https://github.com/PHPOffice/PHPExcel/issues/436.

Ok, but what's the solution?!

Well, you have 2 simples solutions:

1 - Use another library or create yours.
2 - Try to fix the issue.

Particularly if I was you I chose the first, and now when you get some new library/plugin I strongly suggest you before download it check the issues in the repository to avoid has those weird bugs in your system.

If you anyway choose for some reason keep going with this one, try to fix it and open a PR.

As per documentation, you can fix easily https://php.net/manual/en/control-structures.continue.php and just compile again the library and it's done.