问:
How to wait for an Async function to finish before doing anything?
I am using a login API to log into my app and from the response i get from the Login API, I want to call another API that will populate data on the Home Page.

However when I attempt to make the second API call and then move to home page. It moves to second page before the API is finished and gives null values. (The second API call is working properly and gives req data, just after some time)

How can i resolve this? Thank you.

My Login Page

```<code>import .....

class Login extends StatefulWidget{

  final void Function(UserCredentials) onSignedIn;

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {

  var response;

  //To save data from  FIRST API to shared Pref
  Future<bool> saveNamedPreference(String ID, String authid) async {

    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("ID", ID );
    prefs.setString("authID", authid );

    return await prefs.setBool("iDExist", true);
  }

  //
  //To save data from  SECOND API to shared Pref
  Future<bool> saveUserPreference(String name, String role) async {

    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("name", name);
    prefs.setString("role", role );

    return await prefs.setBool("UserExists", true);
  }

  @override
  Widget build(BuildContext context){

    //SECOND API CALL
    Future<int> saveUserDetails(String userID, String authID) async{

      getUser(userID, authID).then((value){

        final json = value;
        if(json!="Error"){
          User user = userFromJson(json);
          saveUserPreference(user.username, user.role);
          print('set the other values too ');
          return 1;
        }
        else{
          print('dint get proper json data ');
          return 0;
        }
      });

    }

    //LOGIN API
    Future<Map<String, dynamic>> getData() async {
      var client = http.Client();

      var response = await client
          .post(
          Uri.encodeFull(
              '{url}'),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      if(response.statusCode <200 || response.statusCode > 400){
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){

        saveNamedPreference(res["userId"], res["id"]);;
        UserCredentials uc = userCredentialsFromJson(response.body);

//Using then so that it shifts to Home only after func completion however its not happening
        saveUserDetails(uc.userId, uc.id).then((value){
          widget.onSignedIn(uc); //gives call back to root page to move to HOME
        });
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }
;

    Stack stack = Stack(
      ...... );

    return Scaffold(
        resizeToAvoidBottomPadding: false,
      body: stack
    );
  }
}

</code>```

In my Home page, in the init method, I am accessing the values from Shared Pref (using the same async then method )and then updating the value using setState however it still gives null value.

答:
First, move all these methods with api calls to outside of your build method.

Maybe the problem it's here:
saveNamedPreference(res["userId"], res["id"]);

You aren't awaiting until this method returns.
When you're working asynchronous methods and want to wait for the response, you need to use await.

I think this code looks much better...

```<code>import .....

class Login extends StatefulWidget {

  final void Function(UserCredentials) onSignedIn;

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  var response;

  //To save data from  FIRST API to shared Pref
  Future<bool> saveNamedPreference(String ID, String authid) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("ID", ID);
    prefs.setString("authID", authid);

    return await prefs.setBool("iDExist", true);
  }

  //To save data from  SECOND API to shared Pref
  Future<bool> saveUserPreference(String name, String role) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("name", name);
    prefs.setString("role", role);

    return await prefs.setBool("UserExists", true);
  }

  //SECOND API CALL
  Future<int> saveUserDetails(String userID, String authID) async {
    final json = await getUser(userID, authID);

    if (json != "Error") {
      User user = userFromJson(json);
      saveUserPreference(user.username, user.role);
      print('set the other values too ');
      return 1;
    } else {
      print('dint get proper json data ');
      return 0;
    }
  }

  //LOGIN API
  Future<Map<String, dynamic>> getData() async {
    var client = http.Client();

    var response = await client
        .post(
        Uri.encodeFull('{url}'),
        body: {"email": "$username", "password": "$password"}
    );

    var res = json.decode(response.body);

    if (response.statusCode < 200 || response.statusCode > 400) {
      print("Error");
      throwError();
    }

    if (response.statusCode == 200) {
      await saveNamedPreference(res["userId"], res["id"]);
      UserCredentials uc = userCredentialsFromJson(response.body);

      //Using then so that it shifts to Home only after func completion however its not happening
      await saveUserDetails(uc.userId, uc.id);
      widget.onSignedIn(uc); //gives call back to root page to move to HOME
    }

    if (!mounted) {
      return {'success': false};
    }

    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        body: _buildStack(),
    );
  }

  Widget _buildStack(){
    return Stack(
      ......
    );
  }
}
</code>```

Body:
I am using a login API to log into my app and from the response i get from the Login API, I want to call another API that will populate data on the Home Page.

However when I attempt to make the second API call and then move to home page. It moves to second page before the API is finished and gives null values. (The second API call is working properly and gives req data, just after some time)

How can i resolve this? Thank you.

My Login Page

import .....

class Login extends StatefulWidget{

  final void Function(UserCredentials) onSignedIn;

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {

  var response;

  //To save data from  FIRST API to shared Pref
  Future<bool> saveNamedPreference(String ID, String authid) async {

    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("ID", ID );
    prefs.setString("authID", authid );

    return await prefs.setBool("iDExist", true);
  }

  //
  //To save data from  SECOND API to shared Pref
  Future<bool> saveUserPreference(String name, String role) async {

    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("name", name);
    prefs.setString("role", role );

    return await prefs.setBool("UserExists", true);
  }

  @override
  Widget build(BuildContext context){

    //SECOND API CALL
    Future<int> saveUserDetails(String userID, String authID) async{

      getUser(userID, authID).then((value){

        final json = value;
        if(json!="Error"){
          User user = userFromJson(json);
          saveUserPreference(user.username, user.role);
          print('set the other values too ');
          return 1;
        }
        else{
          print('dint get proper json data ');
          return 0;
        }
      });

    }

    //LOGIN API
    Future<Map<String, dynamic>> getData() async {
      var client = http.Client();

      var response = await client
          .post(
          Uri.encodeFull(
              '{url}'),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      if(response.statusCode <200 || response.statusCode > 400){
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){

        saveNamedPreference(res["userId"], res["id"]);;
        UserCredentials uc = userCredentialsFromJson(response.body);

//Using then so that it shifts to Home only after func completion however its not happening
        saveUserDetails(uc.userId, uc.id).then((value){
          widget.onSignedIn(uc); //gives call back to root page to move to HOME
        });
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }
;

    Stack stack = Stack(
      ...... );

    return Scaffold(
        resizeToAvoidBottomPadding: false,
      body: stack
    );
  }
}

In my Home page, in the init method, I am accessing the values from Shared Pref (using the same async then method )and then updating the value using setState however it still gives null value.

Body:
First, move all these methods with api calls to outside of your build method.

Maybe the problem it's here:
saveNamedPreference(res["userId"], res["id"]);

You aren't awaiting until this method returns.
When you're working asynchronous methods and want to wait for the response, you need to use await.

I think this code looks much better...

import .....

class Login extends StatefulWidget {

  final void Function(UserCredentials) onSignedIn;

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  var response;

  //To save data from  FIRST API to shared Pref
  Future<bool> saveNamedPreference(String ID, String authid) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("ID", ID);
    prefs.setString("authID", authid);

    return await prefs.setBool("iDExist", true);
  }

  //To save data from  SECOND API to shared Pref
  Future<bool> saveUserPreference(String name, String role) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString("name", name);
    prefs.setString("role", role);

    return await prefs.setBool("UserExists", true);
  }

  //SECOND API CALL
  Future<int> saveUserDetails(String userID, String authID) async {
    final json = await getUser(userID, authID);

    if (json != "Error") {
      User user = userFromJson(json);
      saveUserPreference(user.username, user.role);
      print('set the other values too ');
      return 1;
    } else {
      print('dint get proper json data ');
      return 0;
    }
  }

  //LOGIN API
  Future<Map<String, dynamic>> getData() async {
    var client = http.Client();

    var response = await client
        .post(
        Uri.encodeFull('{url}'),
        body: {"email": "$username", "password": "$password"}
    );

    var res = json.decode(response.body);

    if (response.statusCode < 200 || response.statusCode > 400) {
      print("Error");
      throwError();
    }

    if (response.statusCode == 200) {
      await saveNamedPreference(res["userId"], res["id"]);
      UserCredentials uc = userCredentialsFromJson(response.body);

      //Using then so that it shifts to Home only after func completion however its not happening
      await saveUserDetails(uc.userId, uc.id);
      widget.onSignedIn(uc); //gives call back to root page to move to HOME
    }

    if (!mounted) {
      return {'success': false};
    }

    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        body: _buildStack(),
    );
  }

  Widget _buildStack(){
    return Stack(
      ......
    );
  }
}


来源: stackexchange

问:
Why is this BindingAdapter not working in Kotlin?
I have a ViewModel with:

```<code>val imageUrl = ObservableField<String>()
</code>```

My layout XML has:

```<code><ImageView
    ...
    app:url="@{viewModel.imageUrl}"
    .../>
</code>```

I have a BindingAdapters file with a top level function:

```<code>@BindingAdapter("url")
fun loadImage(view: ImageView, url: String?) {
    ...
}
</code>```

I'm getting the following error:

```<code>data binding error msg:Cannot find the setter for attribute 'app:url' with parameter type android.databinding.ObservableField<java.lang.String> on android.widget.ImageView.
</code>```

Any idea why this would be? This is pretty much identical to how I set up binding adapters in Java, minus the static function.

答:
I've had a different problem. This may not be the solution for your problem, but maybe others will benefit from it. What I did in plus was to add a placeholder and an error drawable as well to my load image function like this:

```<code>@JvmStatic
@BindingAdapter("imageUrl", "error", "placeholder")
fun ImageView.setImageFromUrl(imageUrl: String, error: Drawable?, placeholder: Drawable?) {
    Picasso.get()
            .load(imageUrl)
            .placeholder(placeholder
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_placeholder)!!)
            .error(error
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_error)!!)
            .into(this)
}
</code>```

I tought that putting the ? to the end of the Drawables was enough and in the layout I could just provide the image URL with app:imageUrl, if I didn't want to provide any specific error and placeholder images. But I was wrong, I kept getting the same error as you, Cannot find setter... After a few hours of clearing the cache, deleting every build folder, restarting android studio a few times, I found the solution in a google provided guide. You need to specify inside the @BindingAdapter if all of the attributes are required or not. So I modified my code like this and it worked:

```<code>@JvmStatic
@BindingAdapter(value = ["imageUrl", "error", "placeholder"], requireAll = false)
fun ImageView.setImageFromUrl(imageUrl: String, error: Drawable?, placeholder: Drawable?) {
    Picasso.get()
            .load(imageUrl)
            .placeholder(placeholder
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_placeholder)!!)
            .error(error
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_error)!!)
            .into(this)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a ViewModel with:

val imageUrl = ObservableField<String>()

My layout XML has:

<ImageView
    ...
    app:url="@{viewModel.imageUrl}"
    .../>

I have a BindingAdapters file with a top level function:

@BindingAdapter("url")
fun loadImage(view: ImageView, url: String?) {
    ...
}

I'm getting the following error:

data binding error msg:Cannot find the setter for attribute 'app:url' with parameter type android.databinding.ObservableField<java.lang.String> on android.widget.ImageView.

Any idea why this would be? This is pretty much identical to how I set up binding adapters in Java, minus the static function.

Body:
I've had a different problem. This may not be the solution for your problem, but maybe others will benefit from it. What I did in plus was to add a placeholder and an error drawable as well to my load image function like this:

@JvmStatic
@BindingAdapter("imageUrl", "error", "placeholder")
fun ImageView.setImageFromUrl(imageUrl: String, error: Drawable?, placeholder: Drawable?) {
    Picasso.get()
            .load(imageUrl)
            .placeholder(placeholder
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_placeholder)!!)
            .error(error
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_error)!!)
            .into(this)
}

I tought that putting the ? to the end of the Drawables was enough and in the layout I could just provide the image URL with app:imageUrl, if I didn't want to provide any specific error and placeholder images. But I was wrong, I kept getting the same error as you, Cannot find setter... After a few hours of clearing the cache, deleting every build folder, restarting android studio a few times, I found the solution in a google provided guide. You need to specify inside the @BindingAdapter if all of the attributes are required or not. So I modified my code like this and it worked:

@JvmStatic
@BindingAdapter(value = ["imageUrl", "error", "placeholder"], requireAll = false)
fun ImageView.setImageFromUrl(imageUrl: String, error: Drawable?, placeholder: Drawable?) {
    Picasso.get()
            .load(imageUrl)
            .placeholder(placeholder
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_placeholder)!!)
            .error(error
                    ?: ContextCompat.getDrawable(context, R.drawable.ic_general_error)!!)
            .into(this)
}


问:
Make a queryset in which the children meet a condition
I am building an API with Django Rest Framework and in one of my endpoints I need to return the father and the children that meet the condition active = True

These are my models:

```<code>class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True)

class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products')
    active = models.BooleanField(default=True)
</code>```

And this is my queryset:

```<code>queryset = Category.objects.filter(products__active=True)
</code>```

I have the serializer configured to return the categories along with their products.

I would like the response to be all the categories with the only active products but it returns all the categories with the active and inactive products

Any suggestions?

Thank you very much

答:
Your query has nothing to do with the rest framework and is purely Django. From the model that you have posted, neither Category nor Product has a field name active. If they have, please update your question. But assuming that they don't have, this should be your model:

```<code>class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True) # or False

class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products')
    active = models.BooleanField(default=True) # or False
</code>```

This way, the ones that are active will be in your query.

Update:
You can get active products this way:

```<code> products = Product.objects.filter(active=true)
</code>```

You can get Categories with an active product this way:

```<code>categories = Category.objects.filter(product__active=True)
</code>```

Update 2:
I am not quite sure what you are planning to do with the data but from comments, if you want to loop through active products of every category, this is the way:

```<code>for c in categories:
    active_products = Product.objects.filter(active=True, category=c)
    for p in active_products:
        print(p.title) # or anything else you want
</code>```

Body:
I am building an API with Django Rest Framework and in one of my endpoints I need to return the father and the children that meet the condition active = True

These are my models:

class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True)

class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products')
    active = models.BooleanField(default=True)

And this is my queryset:

queryset = Category.objects.filter(products__active=True)

I have the serializer configured to return the categories along with their products.

I would like the response to be all the categories with the only active products but it returns all the categories with the active and inactive products

Any suggestions?

Thank you very much

Body:
Your query has nothing to do with the rest framework and is purely Django. From the model that you have posted, neither Category nor Product has a field name active. If they have, please update your question. But assuming that they don't have, this should be your model:

class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True) # or False

class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products')
    active = models.BooleanField(default=True) # or False

This way, the ones that are active will be in your query.

Update:
You can get active products this way:

 products = Product.objects.filter(active=true)

You can get Categories with an active product this way:

categories = Category.objects.filter(product__active=True)

Update 2:
I am not quite sure what you are planning to do with the data but from comments, if you want to loop through active products of every category, this is the way:

for c in categories:
    active_products = Product.objects.filter(active=True, category=c)
    for p in active_products:
        print(p.title) # or anything else you want


问:
Store integers as integers and not as floats
I do the following:

```<code>import pandas as pd

df_texts = pd.read_csv('data_texts.csv', keep_default_na=True)

for index, row in df_texts.iterrows():

    list_of_words = row['text'].split()

    df_texts.loc[index, '#_words'] = len(list_of_words)

    list_of_unique_words = set(list_of_words)

    df_texts.loc[index, '#_unique_words'] = len(list_of_unique_words)
</code>```

The problem is that the numbers at the #_words and at the #_unique_words columns are stored as floats even though they are integers.

Just to clarify that these two columns do not pre-exist in the .csv which I read (pd.read_csv) but I create them in the for loop.

How can I directly store them as integers?

答:
You can apply int function to needed column:</p>

```<code>df= pd.DataFrame({
    'n':[1.12, 1.2345, 5.234]
})
df['n'] = df['n'].apply(lambda x: int(x))
df
</code>```

```<code>    n
0   1
1   1
2   5
</code>```

Body:
I do the following:

import pandas as pd

df_texts = pd.read_csv('data_texts.csv', keep_default_na=True)

for index, row in df_texts.iterrows():

    list_of_words = row['text'].split()

    df_texts.loc[index, '#_words'] = len(list_of_words)

    list_of_unique_words = set(list_of_words)

    df_texts.loc[index, '#_unique_words'] = len(list_of_unique_words)

The problem is that the numbers at the #_words and at the #_unique_words columns are stored as floats even though they are integers.

Just to clarify that these two columns do not pre-exist in the .csv which I read (pd.read_csv) but I create them in the for loop.

How can I directly store them as integers?

Body:
You can apply int function to needed column:

df= pd.DataFrame({
    'n':[1.12, 1.2345, 5.234]
})
df['n'] = df['n'].apply(lambda x: int(x))
df

    n
0   1
1   1
2   5


问:
(JavaScript) Compare function with == always returning false
I have made my function that takes user input and outputs it as true if it is the same number and false if it isn't. Now my application always outputs it as false. Sorry if this is bad code, I am a noob.

I have tried to replace "== NaN" with "< 0" with no success.

function compare(a, b) {
  if (a == b) {
    var valid = true;
  } else {
    var valid = false;
  }
  return valid;
}

function test(first, second) {
  if (!isNaN(first) && !isNaN(second)) {
    alert(compare(first, second));
  } else {
    alert('TRY AGAIN');
  }
}

var firstStr = prompt('Enter first Number:');
var first = new Number(firstStr);

var secondStr = prompt('Enter second Number:');
var second = new Number(secondStr);

test(first, second);```

I have not got any error messages however I got it stuck always on false, if there is anything else bad with my code please let me know.

答:
When you use new Number(firstStr) you're creating an object that holds more than just its value.

If you want to have just the plain integer, remove the word new and it will return only its value.

If you plan on keep the new, you need to check for a.valueOf()and b.valueOf() on your compare function.

Body:
I have made my function that takes user input and outputs it as true if it is the same number and false if it isn't. Now my application always outputs it as false. Sorry if this is bad code, I am a noob.

I have tried to replace "== NaN" with "< 0" with no success.

function compare(a, b) {
  if (a == b) {
    var valid = true;
  } else {
    var valid = false;
  }
  return valid;
}

function test(first, second) {
  if (!isNaN(first) && !isNaN(second)) {
    alert(compare(first, second));
  } else {
    alert('TRY AGAIN');
  }
}

var firstStr = prompt('Enter first Number:');
var first = new Number(firstStr);

var secondStr = prompt('Enter second Number:');
var second = new Number(secondStr);

test(first, second);

I have not got any error messages however I got it stuck always on false, if there is anything else bad with my code please let me know.


问:
All data not getting imported from website to excel
I want to import restaurant data like Restaurant name, phone number & website to excel but unfortunately I am getting only one page (first page) however I want data from any range which I define like page-1 to page-3 or page-2 to page-5 in separate sheets for each page. Sample output file is attached of what output I am getting for the time being.

```<code>    Sub Webscraping()
        'Declaration
     Dim ie As InternetExplorer
     Dim ht As HTMLDocument
    'Initialization
     Set ie = New InternetExplorer
     ie.Visible = True

'Open a url
ie.navigate ("https://www.yellowpages.com/atlanta-ga/restaurants")

'Set ht = ie.document
'MsgBox ht.getElementsByClassName("ot_lrp_bname_free_center")

'Alternative Approach for wait

Do Until ie.readyState = READYSTATE_COMPLETE
    DoEvents
Loop

'Initialize the document

Set ht = ie.document

'Set elems = ht.getElementsByClassName("list-title")
Set elems = ht.getElementsByClassName("business-name")
'Set elems = ht.getElementsByClassName("website-lrp icon-link ot_lrp_website_text_free_center")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 1).Value = elem.innerText
    i = i + 1

    'Debug.Print (elem.innerText)
Next

Set elems = ht.getElementsByClassName("phone primary")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 2).Value = elem.innerText
    i = i + 1

   'Debug.Print (elem.innerText)
Next
Set elems = ht.getElementsByClassName("links")
i = 1
For Each elem In elems

    Set link = elem.ChildNodes.Item(0)
    Sheet1.Cells(i, 3).Value = link.href
    i = i + 1
Next

'Set internetdata = ie.document
'Set div_result = internetdata.getElementById("ctl00_gvMain_ctl03_hlTitle")
'Set header_links = div_result.getElementsByTagName("a")
'For Each h In header_links
'Set link = h.ChildNodes.Item(0)
'Worksheets("Stocks").Cells(Range("L" & Rows.Count).End(xlUp).Row + 1, 12) = link.href
 End Sub
</code>```

This is the work which have been done but struggling to get the required ouput

答:
The only way to do this with VBA is to check for the existence of a "Next" button and to click it, if it is there:

This is the HTML for it:

```<code><a class="next ajax-page" href="/atlanta-ga/restaurants?page=2" data-page="2" data-analytics="{"click_id":132}" data-remote="true" data-impressed="1">Next</a>
</code>```

This is not "science fiction" to be done with VBA, however, there are commercial RPA solutions, which give "out of the box" functionalities exactly for this task - UiPath, AutomationAnywhere, BluePrism. Python's "beautiful soup" would do a rather good job as well.

Body:
I want to import restaurant data like Restaurant name, phone number & website to excel but unfortunately I am getting only one page (first page) however I want data from any range which I define like page-1 to page-3 or page-2 to page-5 in separate sheets for each page. Sample output file is attached of what output I am getting for the time being.

    Sub Webscraping()
        'Declaration
     Dim ie As InternetExplorer
     Dim ht As HTMLDocument
    'Initialization
     Set ie = New InternetExplorer
     ie.Visible = True

'Open a url
ie.navigate ("https://www.yellowpages.com/atlanta-ga/restaurants")

'Set ht = ie.document
'MsgBox ht.getElementsByClassName("ot_lrp_bname_free_center")

'Alternative Approach for wait

Do Until ie.readyState = READYSTATE_COMPLETE
    DoEvents
Loop

'Initialize the document

Set ht = ie.document

'Set elems = ht.getElementsByClassName("list-title")
Set elems = ht.getElementsByClassName("business-name")
'Set elems = ht.getElementsByClassName("website-lrp icon-link ot_lrp_website_text_free_center")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 1).Value = elem.innerText
    i = i + 1

    'Debug.Print (elem.innerText)
Next

Set elems = ht.getElementsByClassName("phone primary")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 2).Value = elem.innerText
    i = i + 1

   'Debug.Print (elem.innerText)
Next
Set elems = ht.getElementsByClassName("links")
i = 1
For Each elem In elems

    Set link = elem.ChildNodes.Item(0)
    Sheet1.Cells(i, 3).Value = link.href
    i = i + 1
Next

'Set internetdata = ie.document
'Set div_result = internetdata.getElementById("ctl00_gvMain_ctl03_hlTitle")
'Set header_links = div_result.getElementsByTagName("a")
'For Each h In header_links
'Set link = h.ChildNodes.Item(0)
'Worksheets("Stocks").Cells(Range("L" & Rows.Count).End(xlUp).Row + 1, 12) = link.href
 End Sub

This is the work which have been done but struggling to get the required ouput

Body:
The only way to do this with VBA is to check for the existence of a "Next" button and to click it, if it is there:

This is the HTML for it:

<a class="next ajax-page" href="/atlanta-ga/restaurants?page=2" data-page="2" data-analytics="{&quot;click_id&quot;:132}" data-remote="true" data-impressed="1">Next</a>

This is not "science fiction" to be done with VBA, however, there are commercial RPA solutions, which give "out of the box" functionalities exactly for this task - UiPath, AutomationAnywhere, BluePrism. Python's "beautiful soup" would do a rather good job as well.


问:
Assign Message Policy does not work on Error responses
In Apigee, the Assign Message Policy only seems to work on successful responses. If the server responds with an error code, say, 403 Forbidden, the policy does not change the response. Is there any other way to modify error responses in Apigee.

This is my policy.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Assign-Message-1">
    <DisplayName>Assign Message-1</DisplayName>
    <Properties/>
    <Remove>
        <Headers>
            <Header name="Server"/>
        </Headers>
    </Remove>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
</code>```

答:
You can modify error responses in Apigee using FaultRules. You can take a look at Apigee's documentation about Fault handling .

The reason your AssignMessage policy is not executed is, that the error happens before your policy is being executed, thus being skipped.

You can either move your AssignMessage policy to be executed earlier in the flow or catch the error using fault handling logic and throw the error when you have executed all the desired logic.

Body:
In Apigee, the Assign Message Policy only seems to work on successful responses. If the server responds with an error code, say, 403 Forbidden, the policy does not change the response. Is there any other way to modify error responses in Apigee.

This is my policy.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Assign-Message-1">
    <DisplayName>Assign Message-1</DisplayName>
    <Properties/>
    <Remove>
        <Headers>

        </Headers>
    </Remove>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>


答:
The following regex should do what you want:

```<code>^\d+\t(?:[^\d]+|[\d]+(?!\t))*
</code>```

This will match some number of digits followed by a tab, and then any number of non-digits or digits that are not followed by a tab.

```<code>my @matches = $data =~ /^\d+\t(?:[^\d]+|[\d]+(?!\t))*/mg;
</code>```

edit: Okay this one should work!

ContentLicense: CC BY-SA 3.0

Title: Regex - match up to next match

Body:
I would like to iterate matches over a text, the blocks I want to match start with a number then a tab character.

My beginning match is ^\d+\t, but is there a way to indicate that I want all text including this match up until the next match?

Input data:

1       111.111.111.111
111.111.111.111
                    Host IP     111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
2       111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
3       111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow
4       111.111.111.111
111.111.111.111
111.111.111.111
111.111.111.111         Host IP     111.111.111.111
111.111.111.111         Host IP     TCP             app     11111, 11111, 11111, 11111      Allow

I'm using Perl.

Body:
The following regex should do what you want:

^\d+\t(?:[^\d]+|[\d]+(?!\t))*

This will match some number of digits followed by a tab, and then any number of non-digits or digits that are not followed by a tab.

my @matches = $data =~ /^\d+\t(?:[^\d]+|[\d]+(?!\t))*/mg;

edit: Okay this one should work!


答:
You are using new Number() which will result in {} thats why it is always false

function compare(a, b) {
console.log(a,b)
    if (a == b) {
        var valid = true;
    } else {
        var valid = false;
    }
    return valid;
}

function test(first, second) {
    if(!isNaN(first) && !isNaN(second)){
        alert(compare(first, second));
    } else {
        alert('TRY AGAIN');
    }
}

var firstStr = prompt('Enter first Number:');
var first = Number(firstStr);

var secondStr = prompt('Enter second Number:');
var second = Number(secondStr);

test(first, second);```

Title: (JavaScript) Compare function with == always returning false


问:
Inconsistentency in deserealizing objects with Jackson streaming API
I am trying to use Jackson streaming API to deserialize huge objects from XML. The idea is to combine streaming API and ObjectMapper to parse XML(or JSON) by small chunks.  However I see some inconsistent behavior with XML Parser.
With this code snippet:

```<code> try {
  String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo></foo>";
  String xml2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo><bar></bar></foo>";
  XmlFactory xmlFactory = new XmlFactory();
  JsonParser jp = xmlFactory.createParser(new ByteArrayInputStream(xml1.getBytes()));
  JsonToken token = jp.nextToken();
  while (token != null) {
    System.out.println("xml1 token=" + token);
    token = jp.nextToken();
  }

  jp = xmlFactory.createParser(new ByteArrayInputStream(xml2.getBytes()));
  token = jp.nextToken();
  while (token != null) {
    System.out.println("xml2 token=" + token);
    token = jp.nextToken();
  }

} catch (IOException e) {
  e.printStackTrace();
}
</code>```

I am getting:

xml1 token=START_OBJECT

xml1 token=END_OBJECT

xml2 token=START_OBJECT

xml2 token=FIELD_NAME

xml2 token=VALUE_NULL

xml2 token=END_OBJECT

Why is the FIELD_NAME token missing for xml1? Why is there just one START_OBJECT token for the second xml? Is there any setting that would allow me to see FIELD_NAME of outer tag?

答:
A kid with a hammer...

I don't know much about Jackson; in fact, I just started using it, thinking of using JSON or YAML instead of XML. But for XML, we have been using XStream with success.

```<code>//Consumer side
    FileInputStream fis = new FileInputStream(filename);
    XStream xs = new XStream();
    Object obj = xs.fromXML(fis);
    fis.close();
</code>```

Also, if the case is that you are also originating the serialization and it is from Java, you could use Java serialization altogether for a lower footprint and faster operation.

```<code>//producer side
    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos));
    oos.writeObject(yourVeryComplexObjectStructure); //I am writing a list of ten 1MB objects
    oos.flush();
    oos.close();
    fos.close();

//Consumer side
    final FileInputStream fin = new FileInputStream(filename);
    final ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fin));
    @SuppressWarnings("unchecked")
    final YourVeryComplexObjectStructureType object = (YourVeryComplexObjectStructureType) ois.readObject();
    ois.close();
    fin.close();
</code>```

Body:
I am trying to use Jackson streaming API to deserialize huge objects from XML. The idea is to combine streaming API and ObjectMapper to parse XML(or JSON) by small chunks.  However I see some inconsistent behavior with XML Parser.
With this code snippet:

 try {
  String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo></foo>";
  String xml2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo><bar></bar></foo>";
  XmlFactory xmlFactory = new XmlFactory();
  JsonParser jp = xmlFactory.createParser(new ByteArrayInputStream(xml1.getBytes()));
  JsonToken token = jp.nextToken();
  while (token != null) {
    System.out.println("xml1 token=" + token);
    token = jp.nextToken();
  }

  jp = xmlFactory.createParser(new ByteArrayInputStream(xml2.getBytes()));
  token = jp.nextToken();
  while (token != null) {
    System.out.println("xml2 token=" + token);
    token = jp.nextToken();
  }

} catch (IOException e) {
  e.printStackTrace();
}

I am getting:

xml1 token=START_OBJECT

xml1 token=END_OBJECT

xml2 token=START_OBJECT

xml2 token=FIELD_NAME

xml2 token=VALUE_NULL

xml2 token=END_OBJECT

Why is the FIELD_NAME token missing for xml1? Why is there just one START_OBJECT token for the second xml? Is there any setting that would allow me to see FIELD_NAME of outer tag?

Body:
A kid with a hammer...

I don't know much about Jackson; in fact, I just started using it, thinking of using JSON or YAML instead of XML. But for XML, we have been using XStream with success.

//Consumer side
    FileInputStream fis = new FileInputStream(filename);
    XStream xs = new XStream();
    Object obj = xs.fromXML(fis);
    fis.close();

Also, if the case is that you are also originating the serialization and it is from Java, you could use Java serialization altogether for a lower footprint and faster operation.

//producer side
    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos));
    oos.writeObject(yourVeryComplexObjectStructure); //I am writing a list of ten 1MB objects
    oos.flush();
    oos.close();
    fos.close();

//Consumer side
    final FileInputStream fin = new FileInputStream(filename);
    final ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fin));
    @SuppressWarnings("unchecked")
    final YourVeryComplexObjectStructureType object = (YourVeryComplexObjectStructureType) ois.readObject();
    ois.close();
    fin.close();


问:
Update android SDK Tools - android studio?
I am updating Android SDK Tools :

but get me bellow error :

```<code>java.io.FileNotFoundException: C:\Users\asheq\AppData\Local\Temp\PackageOperation02\sdk-tools-windows-3859397.zip (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:339)
    at com.intellij.util.io.RequestBuilder.lambda$saveToFile$1(RequestBuilder.java:64)
    at com.intellij.util.io.HttpRequests.doProcess(HttpRequests.java:389)
    at com.intellij.util.io.HttpRequests.process(HttpRequests.java:383)
    at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:56)
    at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:244)
    at com.intellij.util.io.RequestBuilder.saveToFile(RequestBuilder.java:64)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:86)
    at com.android.repository.impl.installer.BasicInstaller.doPrepare(BasicInstaller.java:71)
    at com.android.repository.impl.installer.AbstractPackageOperation.prepare(AbstractPackageOperation.java:243)
    at com.android.tools.idea.sdk.wizard.InstallTask.preparePackages(InstallTask.java:191)
    at com.android.tools.idea.sdk.wizard.InstallTask.run(InstallTask.java:98)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:635)
    at com.intellij.openapi.progress.impl.CoreProgressManager$3.run(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:494)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:443)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:155)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:128)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
2017-05-01 10:06:14,208 [  66494]   INFO - ectedPackagesStep$CustomLogger - "Install Android SDK Tools (revision: 26.0.1)" failed.
2017-05-01 10:06:14,208 [  66494]   INFO - ectedPackagesStep$CustomLogger - Preparing "Install Android Emulator (revision: 26.0.0)".
2017-05-01 10:06:14,259 [  66545]   INFO - ectedPackagesStep$CustomLogger - Downloading https://dl.google.com/android/repository/emulator-windows-3833124.zip
2017-05-01 10:06:14,261 [  66547]   WARN - ectedPackagesStep$CustomLogger - An error occurred while preparing SDK package Android Emulator: C:\Users\asheq\AppData\Local\Temp\PackageOperation03\emulator-windows-3833124.zip (The system cannot find the path specified).
java.io.FileNotFoundException: C:\Users\asheq\AppData\Local\Temp\PackageOperation03\emulator-windows-3833124.zip (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:339)
    at com.intellij.util.io.RequestBuilder.lambda$saveToFile$1(RequestBuilder.java:64)
    at com.intellij.util.io.HttpRequests.doProcess(HttpRequests.java:389)
    at com.intellij.util.io.HttpRequests.process(HttpRequests.java:383)
    at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:56)
    at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:244)
    at com.intellij.util.io.RequestBuilder.saveToFile(RequestBuilder.java:64)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:86)
    at com.android.repository.impl.installer.BasicInstaller.doPrepare(BasicInstaller.java:71)
    at com.android.repository.impl.installer.AbstractPackageOperation.prepare(AbstractPackageOperation.java:243)
    at com.android.tools.idea.sdk.wizard.InstallTask.preparePackages(InstallTask.java:191)
    at com.android.tools.idea.sdk.wizard.InstallTask.run(InstallTask.java:98)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:635)
    at com.intellij.openapi.progress.impl.CoreProgressManager$3.run(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:494)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:443)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:155)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:128)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
2017-05-01 10:06:14,264 [  66550]   INFO - ectedPackagesStep$CustomLogger - "Install Android Emulator (revision: 26.0.0)" failed.
2017-05-01 10:06:14,266 [  66552]   INFO - ectedPackagesStep$CustomLogger - Failed packages:
2017-05-01 10:06:14,266 [  66552]   INFO - ectedPackagesStep$CustomLogger - - Android SDK Tools (tools)
2017-05-01 10:06:14,266 [  66552]   INFO - ectedPackagesStep$CustomLogger - - Android Emulator (emulator)
</code>```

答: Simply Run Your Android Studio as Administrator and then attempt to make the update again

Body:
I am updating Android SDK Tools :

but get me bellow error :

java.io.FileNotFoundException: C:\Users\asheq\AppData\Local\Temp\PackageOperation02\sdk-tools-windows-3859397.zip (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:339)
    at com.intellij.util.io.RequestBuilder.lambda$saveToFile$1(RequestBuilder.java:64)
    at com.intellij.util.io.HttpRequests.doProcess(HttpRequests.java:389)
    at com.intellij.util.io.HttpRequests.process(HttpRequests.java:383)
    at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:56)
    at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:244)
    at com.intellij.util.io.RequestBuilder.saveToFile(RequestBuilder.java:64)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:86)
    at com.android.repository.impl.installer.BasicInstaller.doPrepare(BasicInstaller.java:71)
    at com.android.repository.impl.installer.AbstractPackageOperation.prepare(AbstractPackageOperation.java:243)
    at com.android.tools.idea.sdk.wizard.InstallTask.preparePackages(InstallTask.java:191)
    at com.android.tools.idea.sdk.wizard.InstallTask.run(InstallTask.java:98)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:635)
    at com.intellij.openapi.progress.impl.CoreProgressManager$3.run(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:494)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:443)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:155)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:128)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
2017-05-01 10:06:14,208 [  66494]   INFO - ectedPackagesStep$CustomLogger - "Install Android SDK Tools (revision: 26.0.1)" failed.
2017-05-01 10:06:14,208 [  66494]   INFO - ectedPackagesStep$CustomLogger - Preparing "Install Android Emulator (revision: 26.0.0)".
2017-05-01 10:06:14,259 [  66545]   INFO - ectedPackagesStep$CustomLogger - Downloading https://dl.google.com/android/repository/emulator-windows-3833124.zip
2017-05-01 10:06:14,261 [  66547]   WARN - ectedPackagesStep$CustomLogger - An error occurred while preparing SDK package Android Emulator: C:\Users\asheq\AppData\Local\Temp\PackageOperation03\emulator-windows-3833124.zip (The system cannot find the path specified).
java.io.FileNotFoundException: C:\Users\asheq\AppData\Local\Temp\PackageOperation03\emulator-windows-3833124.zip (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:339)
    at com.intellij.util.io.RequestBuilder.lambda$saveToFile$1(RequestBuilder.java:64)
    at com.intellij.util.io.HttpRequests.doProcess(HttpRequests.java:389)
    at com.intellij.util.io.HttpRequests.process(HttpRequests.java:383)
    at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:56)
    at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:244)
    at com.intellij.util.io.RequestBuilder.saveToFile(RequestBuilder.java:64)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:86)
    at com.android.repository.impl.installer.BasicInstaller.doPrepare(BasicInstaller.java:71)
    at com.android.repository.impl.installer.AbstractPackageOperation.prepare(AbstractPackageOperation.java:243)
    at com.android.tools.idea.sdk.wizard.InstallTask.preparePackages(InstallTask.java:191)
    at com.android.tools.idea.sdk.wizard.InstallTask.run(InstallTask.java:98)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:635)
    at com.intellij.openapi.progress.impl.CoreProgressManager$3.run(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:494)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:443)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:155)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:128)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
2017-05-01 10:06:14,264 [  66550]   INFO - ectedPackagesStep$CustomLogger - "Install Android Emulator (revision: 26.0.0)" failed.
2017-05-01 10:06:14,266 [  66552]   INFO - ectedPackagesStep$CustomLogger - Failed packages:
2017-05-01 10:06:14,266 [  66552]   INFO - ectedPackagesStep$CustomLogger - - Android SDK Tools (tools)
2017-05-01 10:06:14,266 [  66552]   INFO - ectedPackagesStep$CustomLogger - - Android Emulator (emulator)


问:
How to retrieve field from custom master object?
I am trying to write a custom object and have to retrieve one custom related field from custom object Course Master(master) to detail object Training deals. This code is showing error</p>

```<code> List<List<String>> strList = new List<List<String>>();
    List<Training_deal__c> td = [select name,   Course_master__r.course__c from Training_deal__c];

    for(Training_deal__c t : td){
        List<String> tempList = new List<String>();
        tempList.add('Training Deals');
        tempList.add(t.name);
        tempList.add(t.course__c);
        strList.add(tempList);
    }
</code>```

答:
I tried to like this and it is working properly</p>

```<code>List<List<String>> strList = new List<List<String>>();
List<Training_deal__c> td = [select name,   Course_master__r.course__c from Training_deal__c];

for(Training_deal__c t : td){
    List<String> tempList = new List<String>();
    tempList.add('Training Deals');
    tempList.add(t.name);
    tempList.add(t.Course_master__r.course__c);
    strList.add(tempList);
}
</code>```

Body:
I am trying to write a custom object and have to retrieve one custom related field from custom object Course Master(master) to detail object Training deals. This code is showing error

 List<List<String>> strList = new List<List<String>>();
    List<Training_deal__c> td = [select name,   Course_master__r.course__c from Training_deal__c];

    for(Training_deal__c t : td){
        List<String> tempList = new List<String>();
        tempList.add('Training Deals');
        tempList.add(t.name);
        tempList.add(t.course__c);
        strList.add(tempList);
    }

Body:
I tried to like this and it is working properly

List<List<String>> strList = new List<List<String>>();
List<Training_deal__c> td = [select name,   Course_master__r.course__c from Training_deal__c];

for(Training_deal__c t : td){
    List<String> tempList = new List<String>();
    tempList.add('Training Deals');
    tempList.add(t.name);
    tempList.add(t.Course_master__r.course__c);
    strList.add(tempList);
}


问:
No executable code found at line inside Observer - Android Studio gradle breakpoint
I am trying to debug inside of a LiveData Observer but the debugger says that there is

No executable code found at line ...

The following screenshot shows what it looks like after I have removed and replaced the breakpoints at the offending lines.

I have already tried the following:

The answers on this question: Android studio gradle breakpoint No
   executable code found at line

removing .gradle, .iml, app/build and .idea and restarting

invalidating caches and restarting

adb kill-server and adb start-server

cleaning project and resyncing gradle

attaching the debugger to the running process again

uninstalling the app from the device and reinstalling

I am using Android Studio 3.2.1

Any other ideas?

答:
In my case, I was using the observer inside the fragment onActivityCreated Method.
After moving code to onCreate method activity, it is started working.</p>


问:
Column name checking null still giving null error
I want to insert values in a table. So I have written the below code for that.

```<code>create or replace PROCEDURE NEIQC_DATA_DUMP_MST AS
BEGIN

execute immediate 'truncate table TBL_NEIQC_WF_SITE_MST_NEW';

INSERT INTO TBL_NEIQC_WF_SITE_MST_NEW

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    --SERVICE_CODE,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2    ,
    PLACEMENT_DATE,
    SITE_TYPE
)

SELECT

    OBJECTID                      ,
    RJ_SAPID ,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    CASE when RJ_SAPID LIKE '%ENB%' THEN 'SITE' ELSE 'OTHERS' end as INVENTORY_TYPE,
    TYPE_NAME                     ,
    4,
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    --APP_FIBERINV.FUNC_SC(RJ_SAPID),
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2          ,
    PLACEMENT_DATE,
    REGEXP_SUBSTR(TO_CHAR(RJ_SAPID),'[^-]+', 1, 4) AS SITE_TYPE

 from APP_FTTX.ne_structures WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL;

COMMIT;

END NEIQC_DATA_DUMP_MST;
</code>```

But the issue is, even after checking the null condition for OBJECTID I am still getting error as

ORA-01400: cannot insert NULL into ("APP_FIBERINV"."TBL_NEIQC_WF_SITE_MST_NEW"."OBJECTID")

Please suggest what may be wrong here.

答:
i think your where condition should be improved. add '()' around your or condition </p>

```<code>WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL;
</code>```

Body:
I want to insert values in a table. So I have written the below code for that.

create or replace PROCEDURE NEIQC_DATA_DUMP_MST AS
BEGIN

execute immediate 'truncate table TBL_NEIQC_WF_SITE_MST_NEW';

INSERT INTO TBL_NEIQC_WF_SITE_MST_NEW

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    --SERVICE_CODE,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2    ,
    PLACEMENT_DATE,
    SITE_TYPE
)

SELECT

    OBJECTID                      ,
    RJ_SAPID ,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    CASE when RJ_SAPID LIKE '%ENB%' THEN 'SITE' ELSE 'OTHERS' end as INVENTORY_TYPE,
    TYPE_NAME                     ,
    4,
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    --APP_FIBERINV.FUNC_SC(RJ_SAPID),
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2          ,
    PLACEMENT_DATE,
    REGEXP_SUBSTR(TO_CHAR(RJ_SAPID),'[^-]+', 1, 4) AS SITE_TYPE

 from APP_FTTX.ne_structures WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL;

COMMIT;

END NEIQC_DATA_DUMP_MST;

But the issue is, even after checking the null condition for OBJECTID I am still getting error as

ORA-01400: cannot insert NULL into ("APP_FIBERINV"."TBL_NEIQC_WF_SITE_MST_NEW"."OBJECTID")

Please suggest what may be wrong here.

Body:
i think your where condition should be improved. add '()' around your or condition

WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL;


问:
Monitor the start and end time of transferring files
Is it possible to automate transferring files from one computer to other computer and monitor the start time and end time and it can simultaneously transfer multiple files files(multi threading)? Is this possible thru automation anywhere metabot or any scripts i can run thru automation anywhere? </p>

答: As far as transfer of files goes, Yes, it's possible in a few ways. Actually, easiest way is with a simple task, metabots would be a bit of overkill for this unless you use a 3rd party application to access the other computer. Regarding the multi-thread, it depends on the way you implement the transfer. If you're just scripting it in then the bot will run the script from atmx line by line so no multi-thread there; you can do this type of multi-thread if you open 2 instance windows for transfer then just use tasks to actually start the transfer. (i.e. 2 putty windows where you set the command in each then loop back to execute it for each window. This is a crude example but it will give you the idea).</p>


答:
This is probably down to operator precedence; AND has higher precedence than OR. So your condition:

```<code>WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL
</code>```

is interpreted as

```<code>WHERE RJ_SAPID IS NOT NULL OR (RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL)
</code>```

If you have a source row where OBJECTID is null then it will still pass than condition, and fail on insertion, if RJ_SAPID is anything except 'NA', including if that is null.

I believe you want:

```<code>WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL
</code>```

so you need to include those parentheses in your statement.

Title: Column name checking null still giving null error

Body:
This is probably down to operator precedence; AND has higher precedence than OR. So your condition:

WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL

is interpreted as

WHERE RJ_SAPID IS NOT NULL OR (RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL)

If you have a source row where OBJECTID is null then it will still pass than condition, and fail on insertion, if RJ_SAPID is anything except 'NA', including if that is null.

I believe you want:

WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL

so you need to include those parentheses in your statement.


问:
Error 500 Call to undefined function thrive_get_theme_options() when trying to get to customize in WP
My site uninstalled all plugins so I reactivated and since then I have been greeted by Error 500 everytime I try to get to Customise (WP).

I checked out error_log and it's pointing to the funtions.php line 659 (starts 3rd line down):

```<code>function thrive_exclude_category($query)
{
    $hide_cat_option = thrive_get_theme_options('hide_cats_from_blog');

    if (!is_string($hide_cat_option)) {
        $hide_cat_option = "";
    }

    $hide_categories = is_array(json_decode($hide_cat_option)) ? json_decode($hide_cat_option) : array();
    $temp_query_string_part = "";
    foreach ($hide_categories as $temp_cat_id) {
        $temp_query_string_part .= "-" . $temp_cat_id . " ";
    }
</code>```

This is probably simple stuff, however, I suck. I have been lumbered with maintaining the sites and really have no say in the matter. Thanks in advance

答:
In one of the projects I found this problem too. After study logs and debug project I find this function don't know about another function which used in theme PHP message: PHP Fatal error:  Uncaught Error: Call to undefined function thrive_get_theme_options(). The main problem here in filter which running before all files will be included in theme. So function thrive_exclude_category don't find where declared thrive_get_theme_options because pre_get_posts running before we included files:

add_filter('pre_get_posts', 'thrive_exclude_category')

We need run this filter after use after_setup_theme

```<code>function run_func(){
   add_filter('pre_get_posts', 'thrive_exclude_category', 999);
}
add_action('after_setup_theme', 'run_func`);
</code>```

After this you not get any error and you can use your filter.

Body:
My site uninstalled all plugins so I reactivated and since then I have been greeted by Error 500 everytime I try to get to Customise (WP).

I checked out error_log and it's pointing to the funtions.php line 659 (starts 3rd line down):

function thrive_exclude_category($query)
{
    $hide_cat_option = thrive_get_theme_options('hide_cats_from_blog');

    if (!is_string($hide_cat_option)) {
        $hide_cat_option = "";
    }

    $hide_categories = is_array(json_decode($hide_cat_option)) ? json_decode($hide_cat_option) : array();
    $temp_query_string_part = "";
    foreach ($hide_categories as $temp_cat_id) {
        $temp_query_string_part .= "-" . $temp_cat_id . " ";
    }

This is probably simple stuff, however, I suck. I have been lumbered with maintaining the sites and really have no say in the matter. Thanks in advance

Body:
In one of the projects I found this problem too. After study logs and debug project I find this function don't know about another function which used in theme PHP message: PHP Fatal error:  Uncaught Error: Call to undefined function thrive_get_theme_options(). The main problem here in filter which running before all files will be included in theme. So function thrive_exclude_category don't find where declared thrive_get_theme_options because pre_get_posts running before we included files:

add_filter('pre_get_posts', 'thrive_exclude_category')

We need run this filter after use after_setup_theme

function run_func(){
   add_filter('pre_get_posts', 'thrive_exclude_category', 999);
}
add_action('after_setup_theme', 'run_func`);

After this you not get any error and you can use your filter.


问:
Need to list all triggers in SQL Server database with table name and table's schema
I need to list all triggers in SQL Server database with table name and table's schema.

I'm almost there with this:

```<code>SELECT trigger_name = name, trigger_owner = USER_NAME(uid),table_schema = , table_name = OBJECT_NAME(parent_obj),
  isupdate = OBJECTPROPERTY( id, 'ExecIsUpdateTrigger'), isdelete = OBJECTPROPERTY( id, 'ExecIsDeleteTrigger'),
  isinsert = OBJECTPROPERTY( id, 'ExecIsInsertTrigger'), isafter = OBJECTPROPERTY( id, 'ExecIsAfterTrigger'),
  isinsteadof = OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger'),
  [disabled] = OBJECTPROPERTY(id, 'ExecIsTriggerDisabled')
FROM sysobjects INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE type = 'TR'
</code>```

I just need to get the table's schema also.

答:
Necromancing. <br />
Just posting because all solutions so far fall a bit short of completeness. </p>

```<code>SELECT
     sch.name AS trigger_table_schema
    ,systbl.name AS trigger_table_name
    ,systrg.name AS trigger_name
    ,sysm.definition AS trigger_definition
    ,systrg.is_instead_of_trigger

    -- https://stackoverflow.com/questions/5340638/difference-between-a-for-and-after-triggers
    -- Difference between a FOR and AFTER triggers?
    -- CREATE TRIGGER trgTable on dbo.Table FOR INSERT,UPDATE,DELETE
    -- Is the same as
    -- CREATE TRIGGER trgTable on dbo.Table AFTER INSERT,UPDATE,DELETE
    -- An INSTEAD OF trigger is different, and fires before and instead of the insert
    -- and can be used on views, in order to insert the appropriate values into the underlying tables.
    -- AFTER specifies that the DML trigger is fired only when all operations
    -- specified in the triggering SQL statement have executed successfully.
    -- All referential cascade actions and constraint checks also must succeed before this trigger fires.
    -- AFTER is the default when FOR is the only keyword specified.
    ,CASE WHEN systrg.is_instead_of_trigger = 1 THEN 0 ELSE 1 END AS is_after_trigger

    ,systrg.is_not_for_replication
    ,systrg.is_disabled
    ,systrg.create_date
    ,systrg.modify_date

    ,CASE WHEN systrg.parent_class = 1 THEN 'TABLE' WHEN systrg.parent_class = 0 THEN 'DATABASE' END trigger_class

    ,CASE
        WHEN systrg.[type] = 'TA' then 'Assembly (CLR) trigger'
        WHEN systrg.[type] = 'TR' then 'SQL trigger'
        ELSE ''
    END AS trigger_type

    -- https://dataedo.com/kb/query/sql-server/list-triggers
    -- ,(CASE WHEN objectproperty(systrg.object_id, 'ExecIsUpdateTrigger') = 1
    --      THEN 'UPDATE ' ELSE '' END
    -- + CASE WHEN objectproperty(systrg.object_id, 'ExecIsDeleteTrigger') = 1
    --      THEN 'DELETE ' ELSE '' END
    -- + CASE WHEN objectproperty(systrg.object_id, 'ExecIsInsertTrigger') = 1
    --      THEN 'INSERT' ELSE '' END
    -- ) AS trigger_event

    ,
    (
        STUFF
        (
            (
                SELECT
                    ', ' + type_desc AS [text()]
                    -- STRING_AGG(type_desc, ', ') AS foo
                FROM sys.events AS syse
                WHERE syse.object_id = systrg.object_id
                FOR XML PATH(''), TYPE
                -- GROUP BY syse.object_id
            ).value('.[1]', 'nvarchar(MAX)')
            , 1, 2, ''
        )
    ) AS trigger_event_groups

    -- ,CASE WHEN systrg.parent_class = 1 THEN 'TABLE' WHEN systrg.parent_class = 0 THEN 'DATABASE' END trigger_class

    ,'DROP TRIGGER "' + sch.name + '"."' + systrg.name + '"; ' AS sql
    -- ,systrg.*
FROM sys.triggers AS systrg

LEFT JOIN sys.sql_modules AS sysm
    ON sysm.object_id = systrg.object_id

-- sys.objects for view triggers
-- LEFT JOIN sys.objects AS systbl ON systbl.object_id = systrg.object_id

-- inner join if you only want table-triggers
LEFT JOIN sys.tables AS systbl ON systbl.object_id = systrg.parent_id

LEFT JOIN sys.schemas AS sch
    ON sch.schema_id = systbl.schema_id

WHERE (1=1)

-- AND sch.name IS NOT NULL
-- AND sch.name IS NULL
-- AND sch.name = 'dbo'
-- And here, exclude some triggers with a certain naming schema
/*
AND
(
    -- systbl.name IS NULL
    -- OR
    NOT
    (
        systrg.name = 'TRG_' + systbl.name  + '_INSERT_History'
        OR
        systrg.name = 'TRG_' + systbl.name  + '_UPDATE_History'
        OR
        systrg.name = 'TRG_' + systbl.name  + '_DELETE_History'
    )
)
*/

ORDER BY
     sch.name
    ,systbl.name
    ,systrg.name
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to list all triggers in SQL Server database with table name and table's schema.

I'm almost there with this:

SELECT trigger_name = name, trigger_owner = USER_NAME(uid),table_schema = , table_name = OBJECT_NAME(parent_obj),
  isupdate = OBJECTPROPERTY( id, 'ExecIsUpdateTrigger'), isdelete = OBJECTPROPERTY( id, 'ExecIsDeleteTrigger'),
  isinsert = OBJECTPROPERTY( id, 'ExecIsInsertTrigger'), isafter = OBJECTPROPERTY( id, 'ExecIsAfterTrigger'),
  isinsteadof = OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger'),
  [disabled] = OBJECTPROPERTY(id, 'ExecIsTriggerDisabled')
FROM sysobjects INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE type = 'TR'

I just need to get the table's schema also.

Body:
Necromancing.

Just posting because all solutions so far fall a bit short of completeness.

SELECT
     sch.name AS trigger_table_schema
    ,systbl.name AS trigger_table_name
    ,systrg.name AS trigger_name
    ,sysm.definition AS trigger_definition
    ,systrg.is_instead_of_trigger

    -- https://stackoverflow.com/questions/5340638/difference-between-a-for-and-after-triggers
    -- Difference between a FOR and AFTER triggers?
    -- CREATE TRIGGER trgTable on dbo.Table FOR INSERT,UPDATE,DELETE
    -- Is the same as
    -- CREATE TRIGGER trgTable on dbo.Table AFTER INSERT,UPDATE,DELETE
    -- An INSTEAD OF trigger is different, and fires before and instead of the insert
    -- and can be used on views, in order to insert the appropriate values into the underlying tables.
    -- AFTER specifies that the DML trigger is fired only when all operations
    -- specified in the triggering SQL statement have executed successfully.
    -- All referential cascade actions and constraint checks also must succeed before this trigger fires.
    -- AFTER is the default when FOR is the only keyword specified.
    ,CASE WHEN systrg.is_instead_of_trigger = 1 THEN 0 ELSE 1 END AS is_after_trigger

    ,systrg.is_not_for_replication
    ,systrg.is_disabled
    ,systrg.create_date
    ,systrg.modify_date

    ,CASE WHEN systrg.parent_class = 1 THEN 'TABLE' WHEN systrg.parent_class = 0 THEN 'DATABASE' END trigger_class

    ,CASE
        WHEN systrg.[type] = 'TA' then 'Assembly (CLR) trigger'
        WHEN systrg.[type] = 'TR' then 'SQL trigger'
        ELSE ''
    END AS trigger_type

    -- https://dataedo.com/kb/query/sql-server/list-triggers
    -- ,(CASE WHEN objectproperty(systrg.object_id, 'ExecIsUpdateTrigger') = 1
    --      THEN 'UPDATE ' ELSE '' END
    -- + CASE WHEN objectproperty(systrg.object_id, 'ExecIsDeleteTrigger') = 1
    --      THEN 'DELETE ' ELSE '' END
    -- + CASE WHEN objectproperty(systrg.object_id, 'ExecIsInsertTrigger') = 1
    --      THEN 'INSERT' ELSE '' END
    -- ) AS trigger_event

    ,
    (
        STUFF
        (
            (
                SELECT
                    ', ' + type_desc AS [text()]
                    -- STRING_AGG(type_desc, ', ') AS foo
                FROM sys.events AS syse
                WHERE syse.object_id = systrg.object_id
                FOR XML PATH(''), TYPE
                -- GROUP BY syse.object_id
            ).value('.[1]', 'nvarchar(MAX)')
            , 1, 2, ''
        )
    ) AS trigger_event_groups

    -- ,CASE WHEN systrg.parent_class = 1 THEN 'TABLE' WHEN systrg.parent_class = 0 THEN 'DATABASE' END trigger_class

    ,'DROP TRIGGER "' + sch.name + '"."' + systrg.name + '"; ' AS sql
    -- ,systrg.*
FROM sys.triggers AS systrg

LEFT JOIN sys.sql_modules AS sysm
    ON sysm.object_id = systrg.object_id

-- sys.objects for view triggers
-- LEFT JOIN sys.objects AS systbl ON systbl.object_id = systrg.object_id

-- inner join if you only want table-triggers
LEFT JOIN sys.tables AS systbl ON systbl.object_id = systrg.parent_id

LEFT JOIN sys.schemas AS sch
    ON sch.schema_id = systbl.schema_id

WHERE (1=1)

-- AND sch.name IS NOT NULL
-- AND sch.name IS NULL
-- AND sch.name = 'dbo'
-- And here, exclude some triggers with a certain naming schema
/*
AND
(
    -- systbl.name IS NULL
    -- OR
    NOT
    (
        systrg.name = 'TRG_' + systbl.name  + '_INSERT_History'
        OR
        systrg.name = 'TRG_' + systbl.name  + '_UPDATE_History'
        OR
        systrg.name = 'TRG_' + systbl.name  + '_DELETE_History'
    )
)
*/

ORDER BY
     sch.name
    ,systbl.name
    ,systrg.name


问:
Using openCV template matcher, in the absence of the desired object, in any case, finds a match. How to get an exception?
I need to check the logo on the bank card. Is it possible to fix my code in such a way that when the logo doesn't match, the system does not search for a similar element, but throws out the exception?

I'm trying to change the variables in the threshold method, but with no result.

```<code>  private static void isTemplateImageExist(String sourceScreenshotPath,
                                                 String sourceScreenshot,
                                                 String templateScreenshotPath,
                                                 String templateImage,
                                                 String resultImage){
            CustomLogger.info("Getting images for comparing");
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
            Mat source = Highgui.imread(sourceScreenshotPath + sourceScreenshot, Highgui.CV_LOAD_IMAGE_COLOR);
            Mat template = Highgui.imread(templateScreenshotPath + templateImage);
            Mat outputImage = new Mat();
            int machMethod = Imgproc.TM_CCOEFF;
            CustomLogger.info("Comparing images");
            //Template matching method
            Imgproc.threshold(source, outputImage, 1, 250, Imgproc.THRESH_TOZERO);
            Imgproc.matchTemplate(source, template, outputImage, machMethod);
            drawRectangleOnResultImage(outputImage,source,template,sourceScreenshotPath,resultImage);
        }
</code>```

I want to see an exception if logo doesn't match.

答: Use outputImage to get min and max values. Check if max value is greater than some desired threshold. If max value is not greater than that threshold throw an exception.

Body:
I need to check the logo on the bank card. Is it possible to fix my code in such a way that when the logo doesn't match, the system does not search for a similar element, but throws out the exception?

I'm trying to change the variables in the threshold method, but with no result.

  private static void isTemplateImageExist(String sourceScreenshotPath,
                                                 String sourceScreenshot,
                                                 String templateScreenshotPath,
                                                 String templateImage,
                                                 String resultImage){
            CustomLogger.info("Getting images for comparing");
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
            Mat source = Highgui.imread(sourceScreenshotPath + sourceScreenshot, Highgui.CV_LOAD_IMAGE_COLOR);
            Mat template = Highgui.imread(templateScreenshotPath + templateImage);
            Mat outputImage = new Mat();
            int machMethod = Imgproc.TM_CCOEFF;
            CustomLogger.info("Comparing images");
            //Template matching method
            Imgproc.threshold(source, outputImage, 1, 250, Imgproc.THRESH_TOZERO);
            Imgproc.matchTemplate(source, template, outputImage, machMethod);
            drawRectangleOnResultImage(outputImage,source,template,sourceScreenshotPath,resultImage);
        }

I want to see an exception if logo doesn't match.


问:
Homemade USB HID pen device only works on Windows 7 / Linux
I've made (with a STM32F4 microcontroller) a USB HID Pen device. My device works really good on Windows 7, or Debian 7 (Linux).

The problem is => It doesn't work on Windows 8, 8.1, 10, ...

My device is recognized as a "HID Stylus", usb view give me no error, the pipe is Open, but my cursor won't move.
Worse, I don't see any packets coming IN or OUT with UsbLyzer !

EDIT:

```<code> On windows 7 = PowerDevice = stay @ D0
 On windows 8 = PowerDevice = D0 1s an then = D3
</code>```

Here is how my device is seen by the computer (usbview) :

```<code>    Device Descriptor:
    bcdUSB:             0x0200
    bDeviceClass:         0x00
    bDeviceSubClass:      0x00
    bDeviceProtocol:      0x00
    bMaxPacketSize0:      0x40 (64)
    idVendor:           0xFFFF
    idProduct:          0x0001
    bcdDevice:          0x0200
    iManufacturer:        0x01
    0x0409: "homemade"
    iProduct:             0x02
    0x0409: "Homemade usb pen device"
    iSerialNumber:        0x03
    0x0409: "00000000050C"
    bNumConfigurations:   0x01

    ConnectionStatus: DeviceConnected
    Current Config Value: 0x01
    Device Bus Speed:     Full
    Device Address:       0x0D
    Open Pipes:              1

    Endpoint Descriptor:
    bEndpointAddress:     0x81  IN
    Transfer Type:   Interrupt
    wMaxPacketSize:     0x000B (11)
    bInterval:            0x0A

    Configuration Descriptor:
    wTotalLength:       0x0022
    bNumInterfaces:       0x01
    bConfigurationValue:  0x01
    iConfiguration:       0x00
    bmAttributes:         0x80 (Bus Powered )
    MaxPower:             0xFA (500 Ma)

    Interface Descriptor:
    bInterfaceNumber:     0x00
    bAlternateSetting:    0x00
    bNumEndpoints:        0x01
    bInterfaceClass:      0x03 (HID)
    bInterfaceSubClass:   0x01
    bInterfaceProtocol:   0x02
    iInterface:           0x00

    HID Descriptor:
    bcdHID:             0x0111
    bCountryCode:         0x00
    bNumDescriptors:      0x01
    bDescriptorType:      0x22
    wDescriptorLength:  0x0092

    Endpoint Descriptor:
    bEndpointAddress:     0x81  IN
    Transfer Type:   Interrupt
    wMaxPacketSize:     0x000B (11)
    bInterval:            0x0A
</code>```

And here is my device HID descriptor :

```<code>0x05, 0x0d,                         // USAGE_PAGE (Digitizers)
0x09, 0x02,                         // USAGE (Pen)

0xa1, 0x01,                         // COLLECTION (Application)
0x09, 0x02,                         //   USAGE (pen)

0xa1, 0x00,                         //   COLLECTION (Physical)

0x09, 0x42,                         //     USAGE (Tip Switch)
0x15, 0x00,                         //     LOGICAL_MINIMUM (0)
0x25, 0x01,                         //     LOGICAL_MAXIMUM (1)
0x75, 0x01,                         //     REPORT_SIZE (1)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x95, 0x03,                         //     REPORT_COUNT (3)
0x81, 0x03,                         //     INPUT (Cnst,Ary,Abs)

0x09, 0x32,                         //     USAGE (In Range)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x95, 0x03,                         //     REPORT_COUNT (3)
0x81, 0x03,                         //     INPUT (Cnst,Ary,Abs)

0x09, 0x56,                         //     USAGE (Scan time)
0x16, 0x00, 0x00,                   //     LOGICAL_MINIMUM (0)
0x26, 0xff, 0x00,                   //     LOGICAL_MAXIMUM (255)
0x75, 0x08,                         //     REPORT_SIZE (8)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x81, 0x02,                         //     INPUT (Data,Ary,Abs)

// X TILT
0x09, 0x3d,                         //     USAGE (X tilt)
0x16, 0xd8, 0xdc,                   //     LOGICAL_MINIMUM (-9000)
0x26, 0x28, 0x23,                   //     LOGICAL_MAXIMUM (9000)
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0E,                         //     UNIT_EXPONENT (-2)
0x65, 0x14,                         //     UNIT (en dg)
0x36, 0xd8, 0xdc,                   //     PHYSICAL_MINIMUM (-9000)
0x46, 0x28, 0x23,                   //     PHYSICAL_MAXIMUM (9000)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

// Y TILT
0x09, 0x3e,                         //     USAGE (Y tilt)
0x16, 0xd8, 0xdc,                   //     LOGICAL_MINIMUM (-9000)
0x26, 0x28, 0x23,                   //     LOGICAL_MAXIMUM (9000)
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0E,                         //     UNIT_EXPONENT (-2)
0x65, 0x14,                         //     UNIT (en dg)
0x36, 0xd8, 0xdc,                   //     PHYSICAL_MINIMUM (-9000)
0x46, 0x28, 0x23,                   //     PHYSICAL_MAXIMUM (9000)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x05, 0x01,                         //     USAGE_PAGE (Generic Desktop)
0x15, 0x00,                         //     LOGICAL_MINIMUM (0)
0x26, 0x08, 0x52,                   //     LOGICAL_MAXIMUM (21000) /// 0x08, 0x52, = 21000
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0d,                         //     UNIT_EXPONENT (-3)
0x65, 0x11,                         //     UNIT (en cm)
0x09, 0x30,                         //     USAGE (X)
0x35, 0x00,                         //     PHYSICAL_MINIMUM (0)
0x46, 0x08, 0x52,                   //     PHYSICAL_MAXIMUM (21000)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x15, 0x00,                         //     LOGICAL_MINIMUM (0)
0x26, 0xd0, 0x39,                   //     LOGICAL_MAXIMUM (14800) /// 0xd0, 0x39, = 14800
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0d,                         //     UNIT_EXPONENT (-3)
0x65, 0x11,                         //     UNIT (en cm)
0x09, 0x31,                         //     USAGE (Y)
0x35, 0x00,                         //     PHYSICAL_MINIMUM (0)
0x46, 0xd0, 0x39,                   //     PHYSICAL_MAXIMUM (14800)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0xc0,                               //   END_COLLECTION
0xc0,                               // END_COLLECTION
</code>```

答: do you have the steps which you followed in running the linux on your stm32f4 board mentioned anywhere or any sort of b</p>

Body:
I've made (with a STM32F4 microcontroller) a USB HID Pen device. My device works really good on Windows 7, or Debian 7 (Linux).

The problem is => It doesn't work on Windows 8, 8.1, 10, ...

My device is recognized as a "HID Stylus", usb view give me no error, the pipe is Open, but my cursor won't move.
Worse, I don't see any packets coming IN or OUT with UsbLyzer !

EDIT:

 On windows 7 = PowerDevice = stay @ D0
 On windows 8 = PowerDevice = D0 1s an then = D3

Here is how my device is seen by the computer (usbview) :

    Device Descriptor:
    bcdUSB:             0x0200
    bDeviceClass:         0x00
    bDeviceSubClass:      0x00
    bDeviceProtocol:      0x00
    bMaxPacketSize0:      0x40 (64)
    idVendor:           0xFFFF
    idProduct:          0x0001
    bcdDevice:          0x0200
    iManufacturer:        0x01
    0x0409: "homemade"
    iProduct:             0x02
    0x0409: "Homemade usb pen device"
    iSerialNumber:        0x03
    0x0409: "00000000050C"
    bNumConfigurations:   0x01

    ConnectionStatus: DeviceConnected
    Current Config Value: 0x01
    Device Bus Speed:     Full
    Device Address:       0x0D
    Open Pipes:              1

    Endpoint Descriptor:
    bEndpointAddress:     0x81  IN
    Transfer Type:   Interrupt
    wMaxPacketSize:     0x000B (11)
    bInterval:            0x0A

    Configuration Descriptor:
    wTotalLength:       0x0022
    bNumInterfaces:       0x01
    bConfigurationValue:  0x01
    iConfiguration:       0x00
    bmAttributes:         0x80 (Bus Powered )
    MaxPower:             0xFA (500 Ma)

    Interface Descriptor:
    bInterfaceNumber:     0x00
    bAlternateSetting:    0x00
    bNumEndpoints:        0x01
    bInterfaceClass:      0x03 (HID)
    bInterfaceSubClass:   0x01
    bInterfaceProtocol:   0x02
    iInterface:           0x00

    HID Descriptor:
    bcdHID:             0x0111
    bCountryCode:         0x00
    bNumDescriptors:      0x01
    bDescriptorType:      0x22
    wDescriptorLength:  0x0092

    Endpoint Descriptor:
    bEndpointAddress:     0x81  IN
    Transfer Type:   Interrupt
    wMaxPacketSize:     0x000B (11)
    bInterval:            0x0A

And here is my device HID descriptor :

0x05, 0x0d,                         // USAGE_PAGE (Digitizers)
0x09, 0x02,                         // USAGE (Pen)

0xa1, 0x01,                         // COLLECTION (Application)
0x09, 0x02,                         //   USAGE (pen)

0xa1, 0x00,                         //   COLLECTION (Physical)

0x09, 0x42,                         //     USAGE (Tip Switch)
0x15, 0x00,                         //     LOGICAL_MINIMUM (0)
0x25, 0x01,                         //     LOGICAL_MAXIMUM (1)
0x75, 0x01,                         //     REPORT_SIZE (1)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x95, 0x03,                         //     REPORT_COUNT (3)
0x81, 0x03,                         //     INPUT (Cnst,Ary,Abs)

0x09, 0x32,                         //     USAGE (In Range)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x95, 0x03,                         //     REPORT_COUNT (3)
0x81, 0x03,                         //     INPUT (Cnst,Ary,Abs)

0x09, 0x56,                         //     USAGE (Scan time)
0x16, 0x00, 0x00,                   //     LOGICAL_MINIMUM (0)
0x26, 0xff, 0x00,                   //     LOGICAL_MAXIMUM (255)
0x75, 0x08,                         //     REPORT_SIZE (8)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x81, 0x02,                         //     INPUT (Data,Ary,Abs)

// X TILT
0x09, 0x3d,                         //     USAGE (X tilt)
0x16, 0xd8, 0xdc,                   //     LOGICAL_MINIMUM (-9000)
0x26, 0x28, 0x23,                   //     LOGICAL_MAXIMUM (9000)
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0E,                         //     UNIT_EXPONENT (-2)
0x65, 0x14,                         //     UNIT (en dg)
0x36, 0xd8, 0xdc,                   //     PHYSICAL_MINIMUM (-9000)
0x46, 0x28, 0x23,                   //     PHYSICAL_MAXIMUM (9000)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

// Y TILT
0x09, 0x3e,                         //     USAGE (Y tilt)
0x16, 0xd8, 0xdc,                   //     LOGICAL_MINIMUM (-9000)
0x26, 0x28, 0x23,                   //     LOGICAL_MAXIMUM (9000)
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0E,                         //     UNIT_EXPONENT (-2)
0x65, 0x14,                         //     UNIT (en dg)
0x36, 0xd8, 0xdc,                   //     PHYSICAL_MINIMUM (-9000)
0x46, 0x28, 0x23,                   //     PHYSICAL_MAXIMUM (9000)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x05, 0x01,                         //     USAGE_PAGE (Generic Desktop)
0x15, 0x00,                         //     LOGICAL_MINIMUM (0)
0x26, 0x08, 0x52,                   //     LOGICAL_MAXIMUM (21000) /// 0x08, 0x52, = 21000
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0d,                         //     UNIT_EXPONENT (-3)
0x65, 0x11,                         //     UNIT (en cm)
0x09, 0x30,                         //     USAGE (X)
0x35, 0x00,                         //     PHYSICAL_MINIMUM (0)
0x46, 0x08, 0x52,                   //     PHYSICAL_MAXIMUM (21000)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0x15, 0x00,                         //     LOGICAL_MINIMUM (0)
0x26, 0xd0, 0x39,                   //     LOGICAL_MAXIMUM (14800) /// 0xd0, 0x39, = 14800
0x75, 0x10,                         //     REPORT_SIZE (16)
0x95, 0x01,                         //     REPORT_COUNT (1)
0x55, 0x0d,                         //     UNIT_EXPONENT (-3)
0x65, 0x11,                         //     UNIT (en cm)
0x09, 0x31,                         //     USAGE (Y)
0x35, 0x00,                         //     PHYSICAL_MINIMUM (0)
0x46, 0xd0, 0x39,                   //     PHYSICAL_MAXIMUM (14800)
0x81, 0x02,                         //     INPUT (Data,Var,Abs)

0xc0,                               //   END_COLLECTION
0xc0,                               // END_COLLECTION


问:
How to specify LOD bias in Metal?
I'm rewriting an OpenGL filter from the Android version of the app I'm currently working at in Metal. It uses the following texture lookup function:
vec4 texture2D(sampler2D sampler, vec2 coord, float bias)

Assuming my filter kernel function looks like this:

```<code>float4 fname(sampler src) {
    ...
}
</code>```

The texture lookup call would be the following:

```<code>src.sample(coord)
</code>```

But how can I pass the bias parameter? (the sample function takes only 1 argument)

答:
I'm afraid Core Image only supports 2D textures – no mipmapping and LOD selection. Only bilinear sampling is available.

If you need different LODs, you need to pass different samplers to your kernel and do the interpolation yourself.

Title: How to specify LOD bias in Metal?

Body:
I'm rewriting an OpenGL filter from the Android version of the app I'm currently working at in Metal. It uses the following texture lookup function:
vec4 texture2D(sampler2D sampler, vec2 coord, float bias)

Assuming my filter kernel function looks like this:

float4 fname(sampler src) {
    ...
}

The texture lookup call would be the following:

src.sample(coord)

But how can I pass the bias parameter? (the sample function takes only 1 argument)


问:
array of pointers
Consider the following code:

```<code>#include <stdio.h>

int main()
{
  static int a[]={0,1,2,3,4};
  int *p[]={a,a+1,a+2,a+3};            /* clear up to this extent */
  printf(("%u\n%u\n%u",p,*p,*(*p)));   /* how does this statement work? */
  return 0;
}
</code>```

Also is it necessary to get the value of addresses through %u,or we can use %d also?

答:
Do you have an extra pair of parens in your printf statement?

Anyway, you can think of this statement:

```<code>printf("%u\n%u\n%u",p,*p,*(*p));
</code>```

like following a trail of pointers.

p is the pointer itself, printing it should print out the pointer's value which is the address of what it points to. In your case its an array of (int *)'s.

*p is a dereferencing operation. It allows access to the object that p points to. In the other answers you see notes made about *p being equivalent to p[0]. That's because p is pointing to the beginning of your structure, which is the start of the array.

**p is a dereferencing operation on the pointer object that p points to. Extending the example in the previous point, you can say that **p is equivalent to *(p[0]) which is equivalent to *(a) which is equivalent to a[0].

One tip that might help you when trying to decipher these sorts of statements is that keep in mind the precedence rules of C and insert parens between expressions in the statement to break up the statement. For the **p, inserting parens would do this: *(*p) which makes it clear that what you're doing is to follow two pointers to the final destination.

Title: array of pointers

Body:
Consider the following code:

#include <stdio.h>

int main()
{
  static int a[]={0,1,2,3,4};
  int *p[]={a,a+1,a+2,a+3};            /* clear up to this extent */
  printf(("%u\n%u\n%u",p,*p,*(*p)));   /* how does this statement work? */
  return 0;
}

Also is it necessary to get the value of addresses through %u,or we can use %d also?

Body:
Do you have an extra pair of parens in your printf statement?

Anyway, you can think of this statement:

printf("%u\n%u\n%u",p,*p,*(*p));

like following a trail of pointers.

p is the pointer itself, printing it should print out the pointer's value which is the address of what it points to. In your case its an array of (int *)'s.

*p is a dereferencing operation. It allows access to the object that p points to. In the other answers you see notes made about *p being equivalent to p[0]. That's because p is pointing to the beginning of your structure, which is the start of the array.

**p is a dereferencing operation on the pointer object that p points to. Extending the example in the previous point, you can say that **p is equivalent to *(p[0]) which is equivalent to *(a) which is equivalent to a[0].

One tip that might help you when trying to decipher these sorts of statements is that keep in mind the precedence rules of C and insert parens between expressions in the statement to break up the statement. For the **p, inserting parens would do this: *(*p) which makes it clear that what you're doing is to follow two pointers to the final destination.


答:
Just remove new Number()</p>

```<code>// same code ...

var firstStr = prompt('Enter first Number:');
var first = firstStr; // remove new Number()

var secondStr = prompt('Enter second Number:');
var second = secondStr; // remove new Number()

test(first, second);
</code>```

Body:
I have made my function that takes user input and outputs it as true if it is the same number and false if it isn't. Now my application always outputs it as false. Sorry if this is bad code, I am a noob.

I have tried to replace "== NaN" with "< 0" with no success.

function compare(a, b) {
  if (a == b) {
    var valid = true;
  } else {
    var valid = false;
  }
  return valid;
}

function test(first, second) {
  if (!isNaN(first) && !isNaN(second)) {
    alert(compare(first, second));
  } else {
    alert('TRY AGAIN');
  }
}

var firstStr = prompt('Enter first Number:');
var first = new Number(firstStr);

var secondStr = prompt('Enter second Number:');
var second = new Number(secondStr);

test(first, second);

I have not got any error messages however I got it stuck always on false, if there is anything else bad with my code please let me know.

Body:
Just remove new Number()

// same code ...

var firstStr = prompt('Enter first Number:');
var first = firstStr; // remove new Number()

var secondStr = prompt('Enter second Number:');
var second = secondStr; // remove new Number()

test(first, second);