问:
sort_values() got an unexpected keyword argument 'by'
```<code>for i in str_list:   #str_list is a set contain some strings
    df.loc[i].sort_values(by = 'XXX')
**TypeError**: sort_values() got an unexpected keyword argument 'by' ".
>>> type(df.loc[i])
>>> pandas.core.frame.DataFrame
</code>```

But it works outside the for loop!

```<code>df.loc['string'].sort_values(by = 'XXX')
>>> type(df.loc['string'])
>>> pandas.core.frame.DataFrame
</code>```

I'm confused.

答:
To add to the answer,
why is it returning a series in one case and a data frame in another?

.loc function is returning a Series in the first case

for i in str_list:   #str_list is a set contain some strings

df.loc[i].sort_values(by = 'XXX')

because the argument i appears only once in the DataFrame.

in the second case, the 'string' is duplicated and therefore will return a DataFrame.

df.loc['string'].sort_values(by = 'XXX')

If the 'string' argument is not duplicated then
note that there are also some differences if the argument in .loc is on a list.
for example.

df.loc['string']   -> returns a Series

df.loc[['string']] -> returns a DataFrame

Maybe in the second case you are giving ['string'] as the argument instead of 'string' ?

Hope this helps.

Body:
for i in str_list:   #str_list is a set contain some strings
    df.loc[i].sort_values(by = 'XXX')
**TypeError**: sort_values() got an unexpected keyword argument 'by' ".
>>> type(df.loc[i])
>>> pandas.core.frame.DataFrame

But it works outside the for loop!

df.loc['string'].sort_values(by = 'XXX')
>>> type(df.loc['string'])
>>> pandas.core.frame.DataFrame

I'm confused.


来源: stackexchange

问:
Create json file for many to many fields in django
I need to create json to insert data using inside both models, for tags I have created the json but I don't get how to create json for Question model to insert data directly from it.

model.py

```<code>class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

class Question(models.Model):
    name = models.CharField(max_length=255)
    Tag_name = models.ManyToManyField(Tag)
</code>```

Tag json look like:

```<code>[
  { "name": "a" },
  { "name": "b" }
]
</code>```

Since Tag_name is many to many field it create 2 tables in sqlite but I want to add data using one json only.How to make a json so that data in both table get inserted ?

答:
You could opt for the builtin management command, ./manage.py loaddata. I think it's easier.

You only need a json fixture for the tag model... the fixture, tags.json, could look like:

```<code>[
    {
    "model":"yourapp.tag",
    "pk":1,
    "fields":{"name": "a" }
},
  {
    "model":"yourapp.tag",
    "pk":2,
    "fields":{"name": "b" }
}
]
</code>```

Store your tags.json inside a folder called fixtures inside your app. Finally, run ./manage.py loaddata tags.json. It will prepopulate the Tag model. Hope it helps...

ContentLicense: CC BY-SA 4.0

Body:
I need to create json to insert data using inside both models, for tags I have created the json but I don't get how to create json for Question model to insert data directly from it.

model.py

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

class Question(models.Model):
    name = models.CharField(max_length=255)
    Tag_name = models.ManyToManyField(Tag)

Tag json look like:

[
  { "name": "a" },
  { "name": "b" }
]

Since Tag_name is many to many field it create 2 tables in sqlite but I want to add data using one json only.How to make a json so that data in both table get inserted ?

Body:
You could opt for the builtin management command, ./manage.py loaddata. I think it's easier.

You only need a json fixture for the tag model... the fixture, tags.json, could look like:

[
    {
    "model":"yourapp.tag",
    "pk":1,
    "fields":{"name": "a" }
},
  {
    "model":"yourapp.tag",
    "pk":2,
    "fields":{"name": "b" }
}
]

Store your tags.json inside a folder called fixtures inside your app. Finally, run ./manage.py loaddata tags.json. It will prepopulate the Tag model. Hope it helps...


问:
Google Script version of VLookup (More Efficient Method?)
I'm trying to put together a function that will allow me to pull a column's info from one sheet to another based on a key column. This would work similar to an index match or vlookup in excel/google.

Sample Data:

What I've tried:

```<code>function vlookup(importFromSht, importToSht, importFromCompCol, importToCompCol,importFromCol, importToCol){
  var lastImportFromRN = importFromSht.getLastRow();
  var lastImportToRN = importToSht.getLastRow();
  var importFromCompArr =  importFromSht.getRange(2, importFromCompCol, lastImportFromRN, 1).getValues();
  var importToCompArr =  importToSht.getRange(2, importToCompCol, lastImportToRN, 1).getValues();
  var importFromArr =  importFromSht.getRange(2, importFromCol, lastImportFromRN, 1).getValues();
  var importToArr = [];

  for (var i in importToCompArr) {
    for (var j in importFromCompArr){
      if (importToCompArr[i].toString() == importFromCompArr[j].toString()) {
        importToArr.push(importFromArr[j]);
      }
    }
  }

  //Paste to column
  importToSht.getRange(2,importToCol,importToArr.length,1).setValues(importToArr);
}
</code>```

Parameters Defined

importFromSht - Sheet we are grabbing values from.

importToSht - Sheet values will be copied to.

importFromCompCol - Column (number) that has values to match on.

importToCompCol - Column (number) that has values to match on.

importFromCol - Column (number) that contains value that needs to be copied.

importToCol - Column (number) to copy value to.

Requirements:

There are over 6K rows minimum and could be many more thousand. Speed of execution is important. Is my approach the correct approach or are there more efficient methods? My script added about 30 seconds to my execution time.

Would like to call it as a function as I can see myself using this in other areas of this projects and other projects.

答:
Unfortunately I am afraid there is no built-in function for this in Apps Script.

However, I have tried your custom function with 100 values and it took <3 seconds to run. I also ran it with 1000 values and my running time was around 40 seconds. It is not ideal but it works consistently. Here is the code I have used:

    var sheet = SpreadsheetApp.getActiveSpreadsheet();
    var importFromSht = SpreadsheetApp.getActive().getSheetByName('Sheet1'); //sheet we are grabbing the values of
    var importToSht = SpreadsheetApp.getActive().getSheetByName('Sheet2');  //sheet we are pasting our values
    var importFromCompCol = 2; // Column (number) that has values to match on.
    var importToCompCol = 2; // Column (number) that has values to match on.
    var importFromCol = 1; // Column (number) that contains value that needs to be copied.
    var importToCol = 1; // Column (number) to copy value to.

    function customVlookup (){
      var lastImportFromRN = importFromSht.getLastRow();
      var lastImportToRN = importToSht.getLastRow();
      var importFromCompArr =  importFromSht.getRange(1, importFromCompCol, lastImportFromRN, 1).getValues();
      var importToCompArr =  importToSht.getRange(1, importToCompCol, lastImportToRN, 1).getValues();
      var importFromArr =  importFromSht.getRange(1, importFromCol, lastImportFromRN, 1).getValues();
      var importToArr = [];

      for (var i in importToCompArr) {
        for (var j in importFromCompArr){
          if (importToCompArr[i].toString() == importFromCompArr[j].toString()) {
            importToArr.push(importFromArr[j]);
          }
        }
      }
      //Paste to column
      importToSht.getRange(1,importToCol,importToArr.length,1).setValues(importToArr);
    }```

A different and more efficient approach is to use IMPORTRANGE(URL of first sheet) to an intermediate sheet swapping the columns of the first sheet to then do a VLOOKUP on your second sheet. This would be way more efficient than doing it in Apps Script as it does not run in the memory and you avoid the issue of exceeding the execution time of a custom function.

In case you want to keep it as an Apps Script custom function Here are some suggestions on the documentation on how to improve your function’s efficiency.

Body:
I'm trying to put together a function that will allow me to pull a column's info from one sheet to another based on a key column. This would work similar to an index match or vlookup in excel/google.

Sample Data:

What I've tried:

function vlookup(importFromSht, importToSht, importFromCompCol, importToCompCol,importFromCol, importToCol){
  var lastImportFromRN = importFromSht.getLastRow();
  var lastImportToRN = importToSht.getLastRow();
  var importFromCompArr =  importFromSht.getRange(2, importFromCompCol, lastImportFromRN, 1).getValues();
  var importToCompArr =  importToSht.getRange(2, importToCompCol, lastImportToRN, 1).getValues();
  var importFromArr =  importFromSht.getRange(2, importFromCol, lastImportFromRN, 1).getValues();
  var importToArr = [];

  for (var i in importToCompArr) {
    for (var j in importFromCompArr){
      if (importToCompArr[i].toString() == importFromCompArr[j].toString()) {
        importToArr.push(importFromArr[j]);
      }
    }
  }

  //Paste to column
  importToSht.getRange(2,importToCol,importToArr.length,1).setValues(importToArr);
}

Parameters Defined

importFromSht - Sheet we are grabbing values from.

importToSht - Sheet values will be copied to.

importFromCompCol - Column (number) that has values to match on.

importToCompCol - Column (number) that has values to match on.

importFromCol - Column (number) that contains value that needs to be copied.

importToCol - Column (number) to copy value to.

Requirements:

There are over 6K rows minimum and could be many more thousand. Speed of execution is important. Is my approach the correct approach or are there more efficient methods? My script added about 30 seconds to my execution time.

Would like to call it as a function as I can see myself using this in other areas of this projects and other projects.

Body:
Unfortunately I am afraid there is no built-in function for this in Apps Script.

However, I have tried your custom function with 100 values and it took <3 seconds to run. I also ran it with 1000 values and my running time was around 40 seconds. It is not ideal but it works consistently. Here is the code I have used:

    var sheet = SpreadsheetApp.getActiveSpreadsheet();
    var importFromSht = SpreadsheetApp.getActive().getSheetByName('Sheet1'); //sheet we are grabbing the values of
    var importToSht = SpreadsheetApp.getActive().getSheetByName('Sheet2');  //sheet we are pasting our values
    var importFromCompCol = 2; // Column (number) that has values to match on.
    var importToCompCol = 2; // Column (number) that has values to match on.
    var importFromCol = 1; // Column (number) that contains value that needs to be copied.
    var importToCol = 1; // Column (number) to copy value to.

    function customVlookup (){
      var lastImportFromRN = importFromSht.getLastRow();
      var lastImportToRN = importToSht.getLastRow();
      var importFromCompArr =  importFromSht.getRange(1, importFromCompCol, lastImportFromRN, 1).getValues();
      var importToCompArr =  importToSht.getRange(1, importToCompCol, lastImportToRN, 1).getValues();
      var importFromArr =  importFromSht.getRange(1, importFromCol, lastImportFromRN, 1).getValues();
      var importToArr = [];

      for (var i in importToCompArr) {
        for (var j in importFromCompArr){
          if (importToCompArr[i].toString() == importFromCompArr[j].toString()) {
            importToArr.push(importFromArr[j]);
          }
        }
      }
      //Paste to column
      importToSht.getRange(1,importToCol,importToArr.length,1).setValues(importToArr);
    }

A different and more efficient approach is to use IMPORTRANGE(URL of first sheet) to an intermediate sheet swapping the columns of the first sheet to then do a VLOOKUP on your second sheet. This would be way more efficient than doing it in Apps Script as it does not run in the memory and you avoid the issue of exceeding the execution time of a custom function.

In case you want to keep it as an Apps Script custom function Here are some suggestions on the documentation on how to improve your function’s efficiency.


问:
Jquery div strobe
I would like to have a div act like a strobe light with jquery. Basicly change the background color from black to white every 500 milliseconds.

How can I do that?

```<code><div id="strobe"></div>
</code>```

Thank you!

答:
You can use jQuery for both checking the background color of the element and for setting the interval at which it flickers with the $.css() method which gets or sets the style of an element and the setInterval() method which sets up a reoccurring method call.

```<code>function toggle(){
    var strobe = $('#strobe');
    if(strobe.css('background-color') == '#FFFFFF'){
        strobe.css('background-color', '#000000');
    }else{
        strobe.css('background-color', '#FFFFFF');
    }
}

setInterval(toggle, 500);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery div strobe

Body:
I would like to have a div act like a strobe light with jquery. Basicly change the background color from black to white every 500 milliseconds.

How can I do that?

Thank you!

Body:
You can use jQuery for both checking the background color of the element and for setting the interval at which it flickers with the $.css() method which gets or sets the style of an element and the setInterval() method which sets up a reoccurring method call.

function toggle(){
    var strobe = $('#strobe');
    if(strobe.css('background-color') == '#FFFFFF'){
        strobe.css('background-color', '#000000');
    }else{
        strobe.css('background-color', '#FFFFFF');
    }
}

setInterval(toggle, 500);


问:
Why LRU caches use doubly link list and not singly link list?
I have been trying to understand why LRU caches use doubly link list and not singly link list?

If i go by the time complexities they both have same for insertion , updation and deletion.
Here is the Cheat sheet

Is it because the two ways pointers in DLL is used for easier move of nodes to rear or front ??

答:
The idea behind LRU cache implementation using list (DLL/SLL) is to move the recently used page(node) to the front.

This involves a lot of shifting, say the node is in the middle of the list (DLL/SLL), you'd have to remove the node, rearrange the next pointer of the previous node.

Now in this case, if we use Singly Linked List we'd have to maintain the previous node of the most recently accessed node.

This operation is not necessary if we use Doubly Linked List as it already maintains the previous and next pointer.

The catch here is accessing that latest node, for which we use a hashtable giving us access to that node in O(1).


问:
How to use virtualbox in a Windows 10 azure virtual machine
I've been reading about it, and I don't know if there is anyway of doing it.

I want to create a Virtualbox virtual machine inside another virtual machine I created in azure, and I don't have Hyper-V activated.

My virtual machine doesn't have a BIOS to access and enable it, and I read that not all virtual machines in azure allow nested virtualization.

The virtual machine I have right now is a B1ms standard and what I read is that I need a V3 machine to virtualize a virtual machine inside  the azure one. Is that true? I don't want to spend money just creating it and then not beeing able to do it.

Thanks :)

答:
Although you can use Nested Virtualization it might be better to just convert your VirtualBox images to Azure VHDs. This is relatively straightforward:

vboxmanage clonehd SOMETHING.vdi SOMETHING.vhd --format VHD
```

Afterwards you can use Azure Storage Explorer (or the CLI) to upload the VHD and use this to deploy a Native Virtual Machine on Azure.

Body:
Although you can use Nested Virtualization it might be better to just convert your VirtualBox images to Azure VHDs. This is relatively straightforward:

vboxmanage clonehd SOMETHING.vdi SOMETHING.vhd --format VHD

Afterwards you can use Azure Storage Explorer (or the CLI) to upload the VHD and use this to deploy a Native Virtual Machine on Azure.


问:
How to rectify code from zero division error:
I am writing a program to find the cube root of a number. I am getting a division by zero error. I have changed all values to float but still getting the error.

Here is the code.

```<code>def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)
</code>```

This is the error that I am getting

```<code>ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-53-7ad3ad630bd7> in <module>
----> 1 cube_root(16)

<ipython-input-52-46121e93a109> in cube_root(num)
      3     g = random.randint(1,num+1)
      4     new_g = float(num/(g*g))
----> 5     check_ifclose(g,new_g,num)
      6
      7 def check_ifclose(g,new_g,num):

<ipython-input-52-46121e93a109> in check_ifclose(g, new_g, num)
     12         g = float(new_g)
     13         new_g = float(num/(g*g))
---> 14         check_ifclose(g,new_g,num)

ZeroDivisionError: float division by zero
</code>```

答:
in new_g = float(num/(g*g)), g*g is floating number. which have decimals more the 308 which leads the value to 0.0.

for finding cube root you can try num**1/3

Body:
I am writing a program to find the cube root of a number. I am getting a division by zero error. I have changed all values to float but still getting the error.

Here is the code.

def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)

This is the error that I am getting

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-53-7ad3ad630bd7> in <module>
----> 1 cube_root(16)

<ipython-input-52-46121e93a109> in cube_root(num)
      3     g = random.randint(1,num+1)
      4     new_g = float(num/(g*g))
----> 5     check_ifclose(g,new_g,num)
      6
      7 def check_ifclose(g,new_g,num):

<ipython-input-52-46121e93a109> in check_ifclose(g, new_g, num)
     12         g = float(new_g)
     13         new_g = float(num/(g*g))
---> 14         check_ifclose(g,new_g,num)

ZeroDivisionError: float division by zero


问:
Display better error messages for the user
```<code>
     private boolean relatedCommand(String input) {
            // make sure the split afterwards has at least size one
            if (input.matches(" .*")) {
                return false;
            }
            final String command = input.split(" ".toString())[0];
            return COMMAND_PACKAGE
                    .keySet()
                    .stream()
                    .map(Pattern::toString)
                    .anyMatch(patternText -> patternText.startsWith(command + " "));
      }

    public Command getCommand(final String input) throws InvalidInputException {
            if (relatedCommand(input)) {
                Terminal.printError("test");
                throw new InvalidInputException("invalid arguments");
            } else {
                throw new InvalidInputException("unknown command");
            }
            ...
     }

</code>```

I am having trouble with giving the user a more specific error message. For example I have the commands add track <argument1> and add switch <argument1>. If the user just types in "add" he shouldn't get the error message "invalid arguments". Instead it should be "invalid command: either use add track or add switch). Since relatedCommand() is a boolean. How do I implement this efficiently?

答:
As you mentioned, currently the method returns a boolean, which is a two-state outcome. At the same time you are seeking for three-state outcome:

command is known

command is unknown

there are several commands known for the prefix.

For the question given in regards to the way of returning the proper result, one option would be to return the collection of possible commands, which can represent the required three states:

the collection consists of one element

the collection is empty

the collection consists of more than one element.

The changes to your original code can be like these:

```<code>private Collection<String> relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return Collections.emptyList();
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .filter(patternText -> patternText.startsWith(comman))
                .collect(Collectors.toList());
  }

public Command getCommand(final String input) throws InvalidInputException {
        Collection<String> commands = relatedCommand(input)
        if (commands.size() == 1) {
            Terminal.printError("test");
            throw new InvalidInputException("invalid arguments");
        } else if (commands.isEmpty()) {
            throw new InvalidInputException("unknown command");
        } else {
            ...
        }
 }
</code>```

Body:
     private boolean relatedCommand(String input) {
            // make sure the split afterwards has at least size one
            if (input.matches(" .*")) {
                return false;
            }
            final String command = input.split(" ".toString())[0];
            return COMMAND_PACKAGE
                    .keySet()
                    .stream()
                    .map(Pattern::toString)
                    .anyMatch(patternText -> patternText.startsWith(command + " "));
      }

    public Command getCommand(final String input) throws InvalidInputException {
            if (relatedCommand(input)) {
                Terminal.printError("test");
                throw new InvalidInputException("invalid arguments");
            } else {
                throw new InvalidInputException("unknown command");
            }
            ...
     }

I am having trouble with giving the user a more specific error message. For example I have the commands add track <argument1> and add switch <argument1>. If the user just types in "add" he shouldn't get the error message "invalid arguments". Instead it should be "invalid command: either use add track or add switch). Since relatedCommand() is a boolean. How do I implement this efficiently?

Body:
As you mentioned, currently the method returns a boolean, which is a two-state outcome. At the same time you are seeking for three-state outcome:

command is known

command is unknown

there are several commands known for the prefix.

For the question given in regards to the way of returning the proper result, one option would be to return the collection of possible commands, which can represent the required three states:

the collection consists of one element

the collection is empty

the collection consists of more than one element.

The changes to your original code can be like these:

private Collection<String> relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return Collections.emptyList();
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .filter(patternText -> patternText.startsWith(comman))
                .collect(Collectors.toList());
  }

public Command getCommand(final String input) throws InvalidInputException {
        Collection<String> commands = relatedCommand(input)
        if (commands.size() == 1) {
            Terminal.printError("test");
            throw new InvalidInputException("invalid arguments");
        } else if (commands.isEmpty()) {
            throw new InvalidInputException("unknown command");
        } else {
            ...
        }
 }


问:
jQuery - How to read xml data if both child and parent tag has the same name
I'm having trouble with getting the data from an XML file because the parent and child nodes has the same name.

XML CODE: file name restaurant_reviews.xml

<restaurants>
  <restaurant>
    <name>Laughing Man</name>
    <logo>
      <name>Visit the Laughing Man</name>
      <imagefile>laughing-man.gif</imagefile>
      <width unit="px">50</width>
      <height unit="px">200</height>
    </logo>
    <location>
      <street>2100 Lakeview Road</street>
      <city>Ottawa</city>
      <provstate>ON</provstate>
      <postalzipcode>K2K 2K2</postalzipcode>
    </location>
    <phone>613-123-4567</phone>
    <rating>4</rating>
    <date>2020-01-07</date>
    <reviewer>Hunter S. Thompson</reviewer>
    Laughing Man Inn is a completely restored Victorian hotel, and offers a warm and elegant atmosphere and gracious service.
    <appetizers>
      <menuitem>
        <description>Crab cakes with a creamy dill sauce served with crispy herbed fries.</description>
        <price currency="cad">23</price>
      </menuitem>
      <menuitem>
        <description>Garden vegetable soup with chocolate sauce.</description>
        <price currency="cad">15</price>
      </menuitem>
    </appetizers>
    <entrees>
      <menuitem>
        <description>Braised jumbo sea scallops on a sun-dried roast tomato base.</description>
        <price currency="cad">39</price>
      </menuitem>
      <menuitem>
        <description>Free-range chicken breast stuffed with morels in a brandy sauce.</description>
        <price currency="cad">31</price>
      </menuitem>
      <menuitem>
        <description>Roast pork loin on a bed of garlic ginger apple slaw.</description>
        <price currency="cad">34</price>
      </menuitem>
    </entrees>
  </restaurant>
  <restaurant>
    <name>Gong’s Asian Cuisine</name>
    <logo>
      <name/>
      <imagefile>gong-asian-cuisine.gif</imagefile>
      <width unit="px">150</width>
      <height unit="px">250</height>
    </logo>
    <location>
      <street>1385 Woodroffe Avenue</street>
      <city>Ottawa</city>
      <provstate>ON</provstate>
      <postalzipcode>K2G 1V8</postalzipcode>
    </location>
    <phone>613-727-4723</phone>
    <rating>3</rating>
    <date>2020-01-10</date>
    <reviewer>Brenda P. Smith</reviewer>
    The food is always consistent. A good variety of dim sum, sushi, Chinese and even Vietnamese dishes. The service is quick and the food is plentiful. We sat down last night and within seconds of turning in our first order, the plates were on the table! The teriyaki dishes had the right amount of sauce and weren't sickeningly sweet. The chicken, fish, and beef were perfectly cooked. The maki-rolls were neatly rolled, cut properly and seasoned well. Loved the General Tao chicken, the steamed BBQ pork buns, the eel sushi and the lovely eggplant. We will be going back again! I would highly recommend it.
    <appetizers>
      <menuitem>
        <description>Egg Roll</description>
        <price currency="cad" quantity="12">15</price>
        <price currency="cad">1.5</price>
      </menuitem>
      <menuitem>
        <description>Spring Roll</description>
        <price currency="cad" quantity="12">15</price>
        <price currency="cad">1.5</price>
      </menuitem>
      <menuitem>
        <description>Shrimp Chips</description>
        <price currency="cad">2.5</price>
      </menuitem>
      <menuitem>
        <description>Fried Noodles</description>
        <price currency="cad">1</price>
      </menuitem>
      <menuitem>
        <description>Sweet & Sour Fried Wonton Skin</description>
        <price currency="cad" quantity="12">3.50</price>
      </menuitem>
    </appetizers>
    <entrees>
      <menuitem>
        <description>Scallops with Vegetables</description>
        <price currency="cad">14.95</price>
      </menuitem>
      <menuitem>
        <description>Sweet and Sour Fish Cantonese Style</description>
        <price currency="cad">13.95</price>
      </menuitem>
      <menuitem>
        <description>Shrimps with Vegetables</description>
        <price currency="cad">12.95</price>
      </menuitem>
      <menuitem>
        <description>Beef with Mushroom</description>
        <price currency="cad">10.25</price>
      </menuitem>
      <menuitem>
        <description>Beef with Tomato</description>
        <price currency="cad">10.25</price>
      </menuitem>
      <menuitem>
        <description>Beef with Broccoli</description>
        <price currency="cad">10.25</price>
      </menuitem>
    </entrees>
  </restaurant>
</restaurants>```
</div>
</div>
</p>

<p>Now to retrieve the data I have used the following Code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$.ajax({
            type: "GET",
            url: "./restaurant_reviews.xml",
            dataType: "xml",
            success: function(xml){
                $(xml).find("restaurant").each(function () {
                    alert($(this).find("name").text());
                    if($(this).find("name").text()=='Laughing Man'){
                        $(this).find("location").each(function () {
                            $("input[name=txtStreetAddress]").val($(this).find("street").text());
                        });
                    }
                 });
            }
        });</code>```

when I run this code the name becomes Laughing ManVisit the Laughing Man which means it's returning both parent and child node data.

Can anyone help?

答:
Use children selector instead of find.

```<code>$(xml).find("restaurant").each(function () {
                    alert($(this).children("name").text());
                    if($(this).children("name").text()=='Laughing Man'){
                        $(this).find("location").each(function () {
                            $("input[name=txtStreetAddress]").val($(this).find("street").text());
                        });
                    }
                 });
</code>```

Demo here

Body:
I'm having trouble with getting the data from an XML file because the parent and child nodes has the same name.

XML CODE: file name restaurant_reviews.xml

<restaurants>
  <restaurant>
    <name>Laughing Man</name>
    <logo>
      <name>Visit the Laughing Man</name>
      <imagefile>laughing-man.gif</imagefile>
      <width unit="px">50</width>
      <height unit="px">200</height>
    </logo>
    <location>
      <street>2100 Lakeview Road</street>
      <city>Ottawa</city>
      <provstate>ON</provstate>
      <postalzipcode>K2K 2K2</postalzipcode>
    </location>
    <phone>613-123-4567</phone>
    <rating>4</rating>
    <date>2020-01-07</date>
    <reviewer>Hunter S. Thompson</reviewer>
    Laughing Man Inn is a completely restored Victorian hotel, and offers a warm and elegant atmosphere and gracious service.
    <appetizers>
      <menuitem>
        <description>Crab cakes with a creamy dill sauce served with crispy herbed fries.</description>
        <price currency="cad">23</price>
      </menuitem>
      <menuitem>
        <description>Garden vegetable soup with chocolate sauce.</description>
        <price currency="cad">15</price>
      </menuitem>
    </appetizers>
    <entrees>
      <menuitem>
        <description>Braised jumbo sea scallops on a sun-dried roast tomato base.</description>
        <price currency="cad">39</price>
      </menuitem>
      <menuitem>
        <description>Free-range chicken breast stuffed with morels in a brandy sauce.</description>
        <price currency="cad">31</price>
      </menuitem>
      <menuitem>
        <description>Roast pork loin on a bed of garlic ginger apple slaw.</description>
        <price currency="cad">34</price>
      </menuitem>
    </entrees>
  </restaurant>
  <restaurant>
    <name>Gong’s Asian Cuisine</name>
    <logo>
      <name/>
      <imagefile>gong-asian-cuisine.gif</imagefile>
      <width unit="px">150</width>
      <height unit="px">250</height>
    </logo>
    <location>
      <street>1385 Woodroffe Avenue</street>
      <city>Ottawa</city>
      <provstate>ON</provstate>
      <postalzipcode>K2G 1V8</postalzipcode>
    </location>
    <phone>613-727-4723</phone>
    <rating>3</rating>
    <date>2020-01-10</date>
    <reviewer>Brenda P. Smith</reviewer>
    The food is always consistent. A good variety of dim sum, sushi, Chinese and even Vietnamese dishes. The service is quick and the food is plentiful. We sat down last night and within seconds of turning in our first order, the plates were on the table! The teriyaki dishes had the right amount of sauce and weren't sickeningly sweet. The chicken, fish, and beef were perfectly cooked. The maki-rolls were neatly rolled, cut properly and seasoned well. Loved the General Tao chicken, the steamed BBQ pork buns, the eel sushi and the lovely eggplant. We will be going back again! I would highly recommend it.
    <appetizers>
      <menuitem>
        <description>Egg Roll</description>
        <price currency="cad" quantity="12">15</price>
        <price currency="cad">1.5</price>
      </menuitem>
      <menuitem>
        <description>Spring Roll</description>
        <price currency="cad" quantity="12">15</price>
        <price currency="cad">1.5</price>
      </menuitem>
      <menuitem>
        <description>Shrimp Chips</description>
        <price currency="cad">2.5</price>
      </menuitem>
      <menuitem>
        <description>Fried Noodles</description>
        <price currency="cad">1</price>
      </menuitem>
      <menuitem>
        <description>Sweet & Sour Fried Wonton Skin</description>
        <price currency="cad" quantity="12">3.50</price>
      </menuitem>
    </appetizers>
    <entrees>
      <menuitem>
        <description>Scallops with Vegetables</description>
        <price currency="cad">14.95</price>
      </menuitem>
      <menuitem>
        <description>Sweet and Sour Fish Cantonese Style</description>
        <price currency="cad">13.95</price>
      </menuitem>
      <menuitem>
        <description>Shrimps with Vegetables</description>
        <price currency="cad">12.95</price>
      </menuitem>
      <menuitem>
        <description>Beef with Mushroom</description>
        <price currency="cad">10.25</price>
      </menuitem>
      <menuitem>
        <description>Beef with Tomato</description>
        <price currency="cad">10.25</price>
      </menuitem>
      <menuitem>
        <description>Beef with Broccoli</description>
        <price currency="cad">10.25</price>
      </menuitem>
    </entrees>
  </restaurant>
</restaurants>

Now to retrieve the data I have used the following Code:

$.ajax({
            type: "GET",
            url: "./restaurant_reviews.xml",
            dataType: "xml",
            success: function(xml){
                $(xml).find("restaurant").each(function () {
                    alert($(this).find("name").text());
                    if($(this).find("name").text()=='Laughing Man'){
                        $(this).find("location").each(function () {
                            $("input[name=txtStreetAddress]").val($(this).find("street").text());
                        });
                    }
                 });
            }
        });

when I run this code the name becomes Laughing ManVisit the Laughing Man which means it's returning both parent and child node data.

Can anyone help?

Body:
Use children selector instead of find.

$(xml).find("restaurant").each(function () {
                    alert($(this).children("name").text());
                    if($(this).children("name").text()=='Laughing Man'){
                        $(this).find("location").each(function () {
                            $("input[name=txtStreetAddress]").val($(this).find("street").text());
                        });
                    }
                 });

Demo here


问:
AlertDialog negative button is not handled
I have an alert dialog with 2 buttons, positive an negative.
Positive button's handler works as it should be, but negative button click doesn't invoke its handler.
Doee anybody know what's wrong here? Thank you. </p>

```<code>protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case DOWNLOAD_DIALOG_ID:
            return new AlertDialog.Builder(this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.download_videos_title_msg)
                .setMessage(R.string.download_videos_main_msg)
                .setPositiveButton(R.string.download_videos_download_btn,
                    _downloadVideoContent)
                .setNegativeButton(R.string.download_videos_ask_later_btn,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id)
                        {
                            Editor prefEditor = PreferenceManager.
                                getDefaultSharedPreferences(_context).edit();
                            prefEditor.putBoolean(DOWNLOAD_DECLINED_FLAG, true);
                            prefEditor.commit();
                        }
                })
                //.setNegativeButton(R.string.download_videos_ask_later_btn,
                //  _cancelDialogListener)
                .create();
    }
    return null;
}
</code>```

答:
Sorry guys,
break point was set at "Editor prefEditor = PreferenceManager." line, because line breaks eclipse didn't stop at that line. Break point at next line worked.</p>

Body:
I have an alert dialog with 2 buttons, positive an negative.
Positive button's handler works as it should be, but negative button click doesn't invoke its handler.
Doee anybody know what's wrong here? Thank you.

protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case DOWNLOAD_DIALOG_ID:
            return new AlertDialog.Builder(this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.download_videos_title_msg)
                .setMessage(R.string.download_videos_main_msg)
                .setPositiveButton(R.string.download_videos_download_btn,
                    _downloadVideoContent)
                .setNegativeButton(R.string.download_videos_ask_later_btn,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id)
                        {
                            Editor prefEditor = PreferenceManager.
                                getDefaultSharedPreferences(_context).edit();
                            prefEditor.putBoolean(DOWNLOAD_DECLINED_FLAG, true);
                            prefEditor.commit();
                        }
                })
                //.setNegativeButton(R.string.download_videos_ask_later_btn,
                //  _cancelDialogListener)
                .create();
    }
    return null;
}


问:
Why Ansible get_url gives error about checksums?
I have a task in my ansible playbook, that downloads a java archive from a github url.
The task is here:

```<code>- name: Download Jar Plugin
  get_url:
    url: https://GitHub-URL/plugins-1.0.5.jar
    dest: /app/plugins/
</code>```

There's no mention of checksum, yet it gives this error:

```<code>fatal: [host]: FAILED! => {"changed": false, "msg": "attempted to take checksum of directory: /app/plugins/plugins-1.0.5.jar"}
</code>```

anyone has any idea about this? Is there any workaround to make it download this java archive?

答:
First of all GitHub is not the right location to keep binaries. Github does not allow us to store a single file greater than 100 MB in most cases. You you should have binaries kept in either a physical server or any cloud storage and pull it from there.

Now, if you are really inclined to follow this bad practise I suggest you to create an equivalent unix curl first to do that. If you have an existing curl command to do that share that with us or simply use ansible shell module as a starting point. You can also try increasing timeouts as default is 10 secs only. Here's a snippet where timeout is set to 200 seconds.

```<code>- name: Download Jar Plugin
  get_url:
    url: https://GitHub-URL/plugins-1.0.5.jar
    dest: /app/plugins/
    timeout: 200
</code>```

Body:
I have a task in my ansible playbook, that downloads a java archive from a github url.
The task is here:

- name: Download Jar Plugin
  get_url:
    url: https://GitHub-URL/plugins-1.0.5.jar
    dest: /app/plugins/

There's no mention of checksum, yet it gives this error:

fatal: [host]: FAILED! => {"changed": false, "msg": "attempted to take checksum of directory: /app/plugins/plugins-1.0.5.jar"}

anyone has any idea about this? Is there any workaround to make it download this java archive?

Body:
First of all GitHub is not the right location to keep binaries. Github does not allow us to store a single file greater than 100 MB in most cases. You you should have binaries kept in either a physical server or any cloud storage and pull it from there.

Now, if you are really inclined to follow this bad practise I suggest you to create an equivalent unix curl first to do that. If you have an existing curl command to do that share that with us or simply use ansible shell module as a starting point. You can also try increasing timeouts as default is 10 secs only. Here's a snippet where timeout is set to 200 seconds.

- name: Download Jar Plugin
  get_url:
    url: https://GitHub-URL/plugins-1.0.5.jar
    dest: /app/plugins/
    timeout: 200


问:
How to add selected by option in VIS network graph?
I wanted to highlight all neighbors of the selected node (highlightNearest)

I am not able to achieve the same with javascript

Srackblitz link

答:
This example on the vis.js website demonstrates how to implement the functionality: https://visjs.github.io/vis-network/examples/network/exampleApplications/neighbourhoodHighlight.html

JSFiddle link

Codepen link


问:
ViewModelProviders is deprecated in 1.1.0
Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:

```<code>val model = ViewModelProviders.of(this).get(MyViewModel::class.java)
</code>```

When using the latest dependency android.arch.lifecycle:extensions:1.1.1 there is no such class ViewModelProviders.

Going to the documentation for ViewModelProviders, I saw a comment saying:

This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory

The problem is, when trying to use ViewModelProvider.AndroidViewModelFactory, cannot find an equivalent of method to get the instance of the ViewModel.

What i tried doing:

```<code>ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PlayerViewHolder::class.java)
</code>```

Hence the name of the method create, I get a new instance of the ViewModel every-time I call it, which is not what I am after.

Any ideas what is the replacement of deprecated code above?

答:
I'm no expert but i have a line of code that solved my problem in Java. Hope this helps someone.

```<code>viewModel =
new ViewModelProvider
.AndroidViewModelFactory(getApplication())
.create(ViewModel.class);
</code>```

As i said i would love to provide more details, but this fixed this problem for me.

Body:
Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:

val model = ViewModelProviders.of(this).get(MyViewModel::class.java)

When using the latest dependency android.arch.lifecycle:extensions:1.1.1 there is no such class ViewModelProviders.

Going to the documentation for ViewModelProviders, I saw a comment saying:

This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory

The problem is, when trying to use ViewModelProvider.AndroidViewModelFactory, cannot find an equivalent of method to get the instance of the ViewModel.

What i tried doing:

ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PlayerViewHolder::class.java)

Hence the name of the method create, I get a new instance of the ViewModel every-time I call it, which is not what I am after.

Any ideas what is the replacement of deprecated code above?

Body:
I'm no expert but i have a line of code that solved my problem in Java. Hope this helps someone.

viewModel =
new ViewModelProvider
.AndroidViewModelFactory(getApplication())
.create(ViewModel.class);

As i said i would love to provide more details, but this fixed this problem for me.


问:
How to show some progress animation in my textbox
I want to show some progress animation in my textbox. Becoz when i click on save button .Records added to the gridview are inserted in the database which return a unique id. This id i want to display in the textbox. But this process takes some time meanwhile i want to show some progress animation inside the textbox. what is the simplest way that i have?</p>

答:
you can give the progress bar as background image

< input  type="text" style="background-image:url(image path)" />

On clicking the save button just change the background image as the loader image and after getting the unique id change the background image as none and then bind the unique id to textbox


问:
Writing "enum: int64_t" value to std::ostringstream truncates it to int
This code behaves in an unexpected way with MSVC compiler (v141 toolset, /std:c++17):

```<code>#include <iostream>
#include <limits>
#include <sstream>
#include <stdint.h>

int main() {
    std::ostringstream ss;
    enum Enum : int64_t {muchos_digitos = std::numeric_limits<int64_t>::max() - 1000};
    ss << muchos_digitos;
    std::cout << ss.str();
    return 0;
}
</code>```

Specifically, it prints "-1001". It is only after much head scratching and enabling /W4 warning level that I discovered the cause:

warning C4305: 'argument': truncation from 'main::Enum' to 'int'

But why does it happen? Indeed, the debugger confirms that int overload is called instead of long long, but why? And how can I circumvent this in generic code? I could cast muchos_digitos to int64_t, but I receive the value as typename T. I can figure out that it's an enum, but how can I know that it's a strongly typed enum, and can I find out its underlying type? I don't think it's directly possible...

The output is correct under GCC, but I need the code to work with all three of GCC, clang and MSVC.

Online demo

P. S. It was a mistake that /W4 was not set for my project in the first place. I recommend everyone to use this level with MSVC and -pedantic-errors with GCC / clang, it really saves you time with bizzare errors and surprising behavior when you notice it at compile time as you write the code.

答: This was confirmed to be a bug by the Microsoft team and it's now fixed in VS 2019: https://developercommunity.visualstudio.com/content/problem/475488/wrong-ostringstreamoperator-overload-selected-for.html</p>

Body:
This code behaves in an unexpected way with MSVC compiler (v141 toolset, /std:c++17):

#include <iostream>
#include <limits>
#include <sstream>
#include <stdint.h>

int main() {
    std::ostringstream ss;
    enum Enum : int64_t {muchos_digitos = std::numeric_limits<int64_t>::max() - 1000};
    ss << muchos_digitos;
    std::cout << ss.str();
    return 0;
}

Specifically, it prints "-1001". It is only after much head scratching and enabling /W4 warning level that I discovered the cause:

warning C4305: 'argument': truncation from 'main::Enum' to 'int'

But why does it happen? Indeed, the debugger confirms that int overload is called instead of long long, but why? And how can I circumvent this in generic code? I could cast muchos_digitos to int64_t, but I receive the value as typename T. I can figure out that it's an enum, but how can I know that it's a strongly typed enum, and can I find out its underlying type? I don't think it's directly possible...

The output is correct under GCC, but I need the code to work with all three of GCC, clang and MSVC.

Online demo

P. S. It was a mistake that /W4 was not set for my project in the first place. I recommend everyone to use this level with MSVC and -pedantic-errors with GCC / clang, it really saves you time with bizzare errors and surprising behavior when you notice it at compile time as you write the code.


问:
SQLBuilder ForeignKeyConstraint - set cascade
Using the API SQL Builder com.healthmarketscience.sqlbuilder.

```<code>DbForeignKeyConstraint constraint = dbTable.foreignKey("fk_" + tableName + "_" + foreignTableName,
        columnList.toArray(new String[0]),
        foreignTableName,
        foreignColumnList.toArray(new String[0]));
</code>```

how to set the constraint so that it does ON UPDATE CASCADE and ON DELETE CASCADE?

答:
To the best of my understanding, the library you're using (com.healthmarketscience.sqlbuilder) doesn't allow to declare a foreign key constraint with ON UPDATE/DELETE CASCADE. I've checked the code, and this functionality isn't implemented.

The reason for this could be that the authors of the library have not implemented this functionality yet, or that they don't intend to implement it for some reason. You should be able to reproduce the functionality with a TRIGGER, but again the llibrary doesn't seem to support those.

If this functionality is crucial to your application, you should probably switch to a library that allows for it.

Body:
Using the API SQL Builder com.healthmarketscience.sqlbuilder.

DbForeignKeyConstraint constraint = dbTable.foreignKey("fk_" + tableName + "_" + foreignTableName,
        columnList.toArray(new String[0]),
        foreignTableName,
        foreignColumnList.toArray(new String[0]));

how to set the constraint so that it does ON UPDATE CASCADE and ON DELETE CASCADE?


问:
How do i programmatically find common lines in files and write them into new file c#
How do I programmatically find common lines in files and write them into a new file in c#?

What I am trying to achieve is directory contains 3 files. file1.txt, file2.txt, file3.txt
Load the files and write all common lines into file_common.txt

答:
In the easiest case when

Order of lines doesn't matter

Duplicates are ignored

i.e. if we have

```<code>file1    file2    file3
-----    -----    -----
    A        B        A    # A / B order doesn't matter
    A        A        A    # A duplicates doesn't matter (A appears twice in each file)
    B        A        B
    C        D        B
                      E
</code>```

the expected outcome is

```<code>A
B
</code>```

you can put it as simple as

```<code>   using System.IO;
   using System.Linq;

   ...

   var result = File
     .ReadLines("file1.txt")
     .Intersect(File.ReadLines("file2.txt"))
     .Intersect(File.ReadLines("file3.txt"));

   File.WriteLines("file_common.txt", result);
</code>```

Body:
In the easiest case when

Order of lines doesn't matter

Duplicates are ignored

i.e. if we have

file1    file2    file3
-----    -----    -----
    A        B        A    # A / B order doesn't matter
    A        A        A    # A duplicates doesn't matter (A appears twice in each file)
    B        A        B
    C        D        B
                      E

the expected outcome is

A
B

you can put it as simple as

   using System.IO;
   using System.Linq;

   ...

   var result = File
     .ReadLines("file1.txt")
     .Intersect(File.ReadLines("file2.txt"))
     .Intersect(File.ReadLines("file3.txt"));

   File.WriteLines("file_common.txt", result);


问:
How to download javadocs and sources for jar using Gradle 2.0?
I am using Gradle 2.0. What should I write in build.gradle so that the javadocs and sources are also downloaded along with the jars?

答:
In addition to previous question, here is Gradle Kotlin DSL version:</p>

```<code>plugins {
    id("idea")
}

idea {
    module {
        isDownloadJavadoc = true
        isDownloadSources = true
    }
}
</code>```

Body:
In addition to previous question, here is Gradle Kotlin DSL version:

plugins {
    id("idea")
}

idea {
    module {
        isDownloadJavadoc = true
        isDownloadSources = true
    }
}


问:
how to count the number of elements in XML?
I'm looking to get basic metadata about the data within a database.  Specifically, the number of line elements which are surrouned by the root text element.

Analogous to what I'd expect COUNT to return in SQL -- a single integer.

the database:

```<code>thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open people
Database 'people' was opened in 225.24 ms.
>
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 215.13 ms.
>
> exit
See you.
thufir@dur:~/flwor/group$
</code>```

Counting the lines:

```<code>thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex each.xq
1
2
3
4
5
6
7
8
9
10
11
12
13thufir@dur:~/flwor/group$
</code>```

code:

```<code>xquery version "3.0";

for $line in db:open("people")
for $index at $count in $line/text/line
return $count
</code>```

答:
From Martin's answer I see it's easy from within basex itself:

```<code>thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open people
Database 'people' was opened in 208.33 ms.
>
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 237.69 ms.
>
> xquery count(/text/line)
13
Query executed in 20.55 ms.
>
> exit
See you.
thufir@dur:~/flwor/group$
</code>```

but I was also looking to run it from an xq file:

```<code>xquery version "3.0";

count(
for $line in db:open("people")
return $line/text/line)
</code>```

Body:
I'm looking to get basic metadata about the data within a database.  Specifically, the number of line elements which are surrouned by the root text element.

Analogous to what I'd expect COUNT to return in SQL -- a single integer.

the database:

thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open people
Database 'people' was opened in 225.24 ms.
>
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 215.13 ms.
>
> exit
See you.
thufir@dur:~/flwor/group$

Counting the lines:

thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex each.xq
1
2
3
4
5
6
7
8
9
10
11
12
13thufir@dur:~/flwor/group$

code:

xquery version "3.0";

for $line in db:open("people")
for $index at $count in $line/text/line
return $count

Body:
From Martin's answer I see it's easy from within basex itself:

thufir@dur:~/flwor/group$
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
>
> open people
Database 'people' was opened in 208.33 ms.
>
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 237.69 ms.
>
> xquery count(/text/line)
13
Query executed in 20.55 ms.
>
> exit
See you.
thufir@dur:~/flwor/group$

but I was also looking to run it from an xq file:

xquery version "3.0";

count(
for $line in db:open("people")
return $line/text/line)


问:
Using http get with body in angular
Is it possible to send body using angular http GET? So I could have  API that requires query params and body at the same time?
So i have "dateReadyFrom" and "dateReadyTo" as queryParam and array of string "Products" as a body.

答:
you can do something like this:</p>

```<code>dataReadyFormEnconde=encode(dateReadyFrom);
dateReadyToEncode=encode(dateReadyTo);

GET
/services?dateReadyFrom=dataReadyFormEnconde&dateReadTo=dateReadyToEncode
</code>```

Title: Using http get with body in angular

Body:
you can do something like this:

dataReadyFormEnconde=encode(dateReadyFrom);
dateReadyToEncode=encode(dateReadyTo);

GET
/services?dateReadyFrom=dataReadyFormEnconde&dateReadTo=dateReadyToEncode


答:
Why don't you print the values during each iteration? You'll see what happens, you can then try to debug it and re-think your solution

Just do:

```<code>def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    print("g", g, "new_g", new_g, "num", num)
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    print("g", g, "new_g", new_g, "num", num)
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)
</code>```

Then for cube_root(16) you'll get the output:

```<code>>>> cube_root(16)
g 2 new_g 4.0 num 16
g 2 new_g 4.0 num 16
g 4.0 new_g 1.0 num 16
g 1.0 new_g 16.0 num 16
g 16.0 new_g 0.0625 num 16
g 0.0625 new_g 4096.0 num 16
g 4096.0 new_g 9.5367431640625e-07 num 16
g 9.5367431640625e-07 new_g 17592186044416.0 num 16
g 17592186044416.0 new_g 5.169878828456423e-26 num 16
g 5.169878828456423e-26 new_g 5.986310706507379e+51 num 16
g 5.986310706507379e+51 new_g 4.464794497196387e-103 num 16
g 4.464794497196387e-103 new_g 8.02633041618099e+205 num 16
g 8.02633041618099e+205 new_g 0.0 num 16
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in cube_root
  File "<stdin>", line 9, in check_ifclose
  File "<stdin>", line 9, in check_ifclose
  File "<stdin>", line 9, in check_ifclose
  [Previous line repeated 8 more times]
  File "<stdin>", line 8, in check_ifclose
ZeroDivisionError: float division by zero
</code>```

As you can see, it's like Razmik said about the small numbers.

But why?

Because your solution is flawed. Are you sure you should calculate new_g like that? If you look here, it goes haywire - very small, then very big, then again small... Why don't you try e.g. setting new_g as average of old and current new to balance it?

EDIT: Decided to check my last suggestion, it works fine now.

```<code>def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    print("g", g, "new_g", new_g, "num", num)
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    print("g", g, "new_g", new_g, "num", num)
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = (g+float(num/(g*g)))/2
        check_ifclose(g,new_g,num)
</code>```
```<code>>>> cube_root(16)
g 3 new_g 1.7777777777777777 num 16
g 3 new_g 1.7777777777777777 num 16
g 1.7777777777777777 new_g 3.420138888888889 num 16
g 3.420138888888889 new_g 2.3939850310351836 num 16
g 2.3939850310351836 new_g 2.592869433541053 num 16
g 2.592869433541053 new_g 2.4863846555355664 num 16
g 2.4863846555355664 new_g 2.537249169224923 num 16
g 2.537249169224923 new_g 2.51131729000868 num 16
g 2.51131729000868 new_g 2.524147960725603 num 16
g 2.524147960725603 new_g 2.517700180896523 num 16
g 2.517700180896523 new_g 2.52091579334918 num 16
g 2.52091579334918 new_g 2.519305938864469 num 16
g 2.519305938864469 new_g 2.520110351423893 num 16
g 2.520110351423893 new_g 2.51970801680198 num 16
g 2.51970801680198 new_g 2.5199091519863974 num 16
g 2.5199091519863974 new_g 2.5198085763676823 num 16
g 2.5198085763676823 new_g 2.519858862169772 num 16
g 2.519858862169772 new_g 2.519833718766991 num 16
g 2.519833718766991 new_g 2.5198462903429375 num 16
g 2.5198462903429375 new_g 2.519840004523604 num 16
g 2.519840004523604 new_g 2.519843147425431 num 16
g 2.519843147425431 new_g 2.519841575972557 num 16
g 2.519841575972557 new_g 2.519842361698504 num 16
g 2.519842361698504 new_g 2.519841968835408 num 16
g 2.519841968835408 new_g 2.5198421652669256 num 16
g 2.5198421652669256 new_g 2.519842067051159 num 16
The cube root of  16 is  2.519842067051159
</code>```

Title: How to rectify code from zero division error:

Body:
I am writing a program to find the cube root of a number. I am getting a division by zero error. I have changed all values to float but still getting the error.

Here is the code.

def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)

This is the error that I am getting

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-53-7ad3ad630bd7> in <module>
----> 1 cube_root(16)

<ipython-input-52-46121e93a109> in cube_root(num)
      3     g = random.randint(1,num+1)
      4     new_g = float(num/(g*g))
----> 5     check_ifclose(g,new_g,num)
      6
      7 def check_ifclose(g,new_g,num):

<ipython-input-52-46121e93a109> in check_ifclose(g, new_g, num)
     12         g = float(new_g)
     13         new_g = float(num/(g*g))
---> 14         check_ifclose(g,new_g,num)

ZeroDivisionError: float division by zero

Body:
Why don't you print the values during each iteration? You'll see what happens, you can then try to debug it and re-think your solution

Just do:

def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    print("g", g, "new_g", new_g, "num", num)
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    print("g", g, "new_g", new_g, "num", num)
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = float(num/(g*g))
        check_ifclose(g,new_g,num)

Then for cube_root(16) you'll get the output:

>>> cube_root(16)
g 2 new_g 4.0 num 16
g 2 new_g 4.0 num 16
g 4.0 new_g 1.0 num 16
g 1.0 new_g 16.0 num 16
g 16.0 new_g 0.0625 num 16
g 0.0625 new_g 4096.0 num 16
g 4096.0 new_g 9.5367431640625e-07 num 16
g 9.5367431640625e-07 new_g 17592186044416.0 num 16
g 17592186044416.0 new_g 5.169878828456423e-26 num 16
g 5.169878828456423e-26 new_g 5.986310706507379e+51 num 16
g 5.986310706507379e+51 new_g 4.464794497196387e-103 num 16
g 4.464794497196387e-103 new_g 8.02633041618099e+205 num 16
g 8.02633041618099e+205 new_g 0.0 num 16
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in cube_root
  File "<stdin>", line 9, in check_ifclose
  File "<stdin>", line 9, in check_ifclose
  File "<stdin>", line 9, in check_ifclose
  [Previous line repeated 8 more times]
  File "<stdin>", line 8, in check_ifclose
ZeroDivisionError: float division by zero

As you can see, it's like Razmik said about the small numbers.

But why?

Because your solution is flawed. Are you sure you should calculate new_g like that? If you look here, it goes haywire - very small, then very big, then again small... Why don't you try e.g. setting new_g as average of old and current new to balance it?

EDIT: Decided to check my last suggestion, it works fine now.

def cube_root(num):
    import random
    g = random.randint(1,num+1)
    new_g = float(num/(g*g))
    print("g", g, "new_g", new_g, "num", num)
    check_ifclose(g,new_g,num)

def check_ifclose(g,new_g,num):
    from math import isclose
    print("g", g, "new_g", new_g, "num", num)
    if isclose(g, new_g, abs_tol=0.0000001):
        print("The cube root of ",num,"is ",float(new_g))
    else:
        g = float(new_g)
        new_g = (g+float(num/(g*g)))/2
        check_ifclose(g,new_g,num)

>>> cube_root(16)
g 3 new_g 1.7777777777777777 num 16
g 3 new_g 1.7777777777777777 num 16
g 1.7777777777777777 new_g 3.420138888888889 num 16
g 3.420138888888889 new_g 2.3939850310351836 num 16
g 2.3939850310351836 new_g 2.592869433541053 num 16
g 2.592869433541053 new_g 2.4863846555355664 num 16
g 2.4863846555355664 new_g 2.537249169224923 num 16
g 2.537249169224923 new_g 2.51131729000868 num 16
g 2.51131729000868 new_g 2.524147960725603 num 16
g 2.524147960725603 new_g 2.517700180896523 num 16
g 2.517700180896523 new_g 2.52091579334918 num 16
g 2.52091579334918 new_g 2.519305938864469 num 16
g 2.519305938864469 new_g 2.520110351423893 num 16
g 2.520110351423893 new_g 2.51970801680198 num 16
g 2.51970801680198 new_g 2.5199091519863974 num 16
g 2.5199091519863974 new_g 2.5198085763676823 num 16
g 2.5198085763676823 new_g 2.519858862169772 num 16
g 2.519858862169772 new_g 2.519833718766991 num 16
g 2.519833718766991 new_g 2.5198462903429375 num 16
g 2.5198462903429375 new_g 2.519840004523604 num 16
g 2.519840004523604 new_g 2.519843147425431 num 16
g 2.519843147425431 new_g 2.519841575972557 num 16
g 2.519841575972557 new_g 2.519842361698504 num 16
g 2.519842361698504 new_g 2.519841968835408 num 16
g 2.519841968835408 new_g 2.5198421652669256 num 16
g 2.5198421652669256 new_g 2.519842067051159 num 16
The cube root of  16 is  2.519842067051159


问:
I cannot open a Mac OS Mojave on VM Ware virtual machine, and it has data files on it that I need to recover
I'm Working on Mac OS Mojave on VM Ware Workstation 14 player but today suddenly my Computer shutdown due to power issue and i couldn't shut down mac. Now when i try to open Mac OS it's crashed every time and it has data files on it that I need to recover. I'm looking for suggestions that might help.

答:
You should be able to list and extract files from a VMware virtual machine VMDK image using 7-zip:

E.g.:

```<code>7z l WindowsXP.vmdk
</code>```

Sample Output:

```<code>7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,12 CPUs x64)

Scanning the drive for archives:
1 file, 14452195328 bytes (14 GiB)

Listing archive: WindowsXP.vmdk

--
Path = WindowsXP.vmdk
Type = VMDK
Physical Size = 14452195328
Method = "monolithicSparse"
Cluster Size = 65536
Headers Size = 2162688
ID = 3f1fc1e8
Name = Windows XP SP3-disk2.vmdk
Comment = # Disk DescriptorFile
version=1
CID=3f1fc1e8
parentCID=ffffffff
createType="monolithicSparse"

# Extent description
RW 33554432 SPARSE "Windows XP SP3-disk2.vmdk"

# The disk Data Base
#DDB

ddb.virtualHWVersion = "4"
ddb.adapterType="ide"
ddb.geometry.cylinders="16383"
ddb.geometry.heads="16"
ddb.geometry.sectors="63"
ddb.geometry.biosCylinders="1024"
ddb.geometry.biosHeads="255"
ddb.geometry.biosSectors="63"
ddb.uuid.image="32b5b00e-2b8f-4101-8c78-afdd93487d01"
ddb.uuid.parent="00000000-0000-0000-0000-000000000000"
ddb.uuid.modification="91a31d3b-53a1-45f6-a271-56d7935a473d"
ddb.uuid.parentmodification="00000000-0000-0000-0000-000000000000"
ddb.comment=""

----
Size = 17179869184
Packed Size = 14450032640
--
Path = WindowsXP.mbr
Type = MBR
Physical Size = 17179869184
----
Path = 0.ntfs
Size = 17179836928
File System = NTFS
Offset = 32256
Primary = +
Begin CHS = 0-1-1
End CHS = 1023-254-63
--
Path = 0.ntfs
Type = NTFS
WARNINGS:
There are data after the end of archive
Physical Size = 17179832320
Tail Size = 4608
File System = NTFS 3.1
Cluster Size = 4096
Sector Size = 512
Record Size = 1024
Created = 2013-05-03 12:33:03
ID = 9572501234667689776

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2013-05-03 12:33:03 ..HS.     43679744     43679744  [SYSTEM]/$MFT
2013-05-03 12:33:03 ..HS.         4096         4096  [SYSTEM]/$MFTMirr
2013-05-03 12:33:03 ..HS.     23527424     23527424  [SYSTEM]/$LogFile
2013-05-03 12:33:03 ..HS.            0            0  [SYSTEM]/$Volume
2013-05-03 12:33:03 ..HS.         2560         4096  [SYSTEM]/$AttrDef
2015-11-08 11:50:22 D.HS.                            [SYSTEM]/.
2013-05-03 12:33:03 ..HS.       524288       524288  [SYSTEM]/$Bitmap
2013-05-03 12:33:03 ..HS.         8192         8192  [SYSTEM]/$Boot
2013-05-03 12:33:03 ..HS.            0            0  [SYSTEM]/$BadClus
2013-05-03 12:33:03 ..HS.            0            0  [SYSTEM]/$Secure
2013-05-03 12:33:03 ..HS.       131072       131072  [SYSTEM]/$UpCase
2013-05-03 12:33:03 D.HS.                            [SYSTEM]/$Extend
2013-05-03 12:33:03 ..HSA            0            0  [SYSTEM]/$Extend/$Quota
2013-05-03 12:33:03 ..HSA            0            0  [SYSTEM]/$Extend/$ObjId
2013-05-03 12:33:03 ..HSA            0            0  [SYSTEM]/$Extend/$Reparse
2014-05-09 10:46:47 ....A        86144        90112  Documents and Settings/Person/Application Data/Dropbox/instance1/l/536cb1a7
2013-05-29 23:37:50 D....                            WINDOWS
2015-11-07 15:25:40 D....                            WINDOWS/system32
2013-05-03 12:05:12 D....                            WINDOWS/system32/config
2015-06-01 17:41:13 D....                            WINDOWS/system32/drivers
2013-05-03 12:41:52 D....                            WINDOWS/system
2013-05-03 12:35:48 D....                            WINDOWS/system32/ras
2013-05-03 12:00:39 D....                            WINDOWS/system32/spool
2013-05-03 12:33:10 D....                            WINDOWS/system32/spool/drivers
2013-05-03 12:33:10 D....                            WINDOWS/system32/spool/drivers/w32x86
</code>```

Body:
You should be able to list and extract files from a VMware virtual machine VMDK image using 7-zip:

E.g.:

7z l WindowsXP.vmdk

Sample Output:

7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,12 CPUs x64)

Scanning the drive for archives:
1 file, 14452195328 bytes (14 GiB)

Listing archive: WindowsXP.vmdk

--
Path = WindowsXP.vmdk
Type = VMDK
Physical Size = 14452195328
Method = "monolithicSparse"
Cluster Size = 65536
Headers Size = 2162688
ID = 3f1fc1e8
Name = Windows XP SP3-disk2.vmdk
Comment = # Disk DescriptorFile
version=1
CID=3f1fc1e8
parentCID=ffffffff
createType="monolithicSparse"

# Extent description
RW 33554432 SPARSE "Windows XP SP3-disk2.vmdk"

# The disk Data Base
#DDB

ddb.virtualHWVersion = "4"
ddb.adapterType="ide"
ddb.geometry.cylinders="16383"
ddb.geometry.heads="16"
ddb.geometry.sectors="63"
ddb.geometry.biosCylinders="1024"
ddb.geometry.biosHeads="255"
ddb.geometry.biosSectors="63"
ddb.uuid.image="32b5b00e-2b8f-4101-8c78-afdd93487d01"
ddb.uuid.parent="00000000-0000-0000-0000-000000000000"
ddb.uuid.modification="91a31d3b-53a1-45f6-a271-56d7935a473d"
ddb.uuid.parentmodification="00000000-0000-0000-0000-000000000000"
ddb.comment=""

----
Size = 17179869184
Packed Size = 14450032640
--
Path = WindowsXP.mbr
Type = MBR
Physical Size = 17179869184
----
Path = 0.ntfs
Size = 17179836928
File System = NTFS
Offset = 32256
Primary = +
Begin CHS = 0-1-1
End CHS = 1023-254-63
--
Path = 0.ntfs
Type = NTFS
WARNINGS:
There are data after the end of archive
Physical Size = 17179832320
Tail Size = 4608
File System = NTFS 3.1
Cluster Size = 4096
Sector Size = 512
Record Size = 1024
Created = 2013-05-03 12:33:03
ID = 9572501234667689776

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2013-05-03 12:33:03 ..HS.     43679744     43679744  [SYSTEM]/$MFT
2013-05-03 12:33:03 ..HS.         4096         4096  [SYSTEM]/$MFTMirr
2013-05-03 12:33:03 ..HS.     23527424     23527424  [SYSTEM]/$LogFile
2013-05-03 12:33:03 ..HS.            0            0  [SYSTEM]/$Volume
2013-05-03 12:33:03 ..HS.         2560         4096  [SYSTEM]/$AttrDef
2015-11-08 11:50:22 D.HS.                            [SYSTEM]/.
2013-05-03 12:33:03 ..HS.       524288       524288  [SYSTEM]/$Bitmap
2013-05-03 12:33:03 ..HS.         8192         8192  [SYSTEM]/$Boot
2013-05-03 12:33:03 ..HS.            0            0  [SYSTEM]/$BadClus
2013-05-03 12:33:03 ..HS.            0            0  [SYSTEM]/$Secure
2013-05-03 12:33:03 ..HS.       131072       131072  [SYSTEM]/$UpCase
2013-05-03 12:33:03 D.HS.                            [SYSTEM]/$Extend
2013-05-03 12:33:03 ..HSA            0            0  [SYSTEM]/$Extend/$Quota
2013-05-03 12:33:03 ..HSA            0            0  [SYSTEM]/$Extend/$ObjId
2013-05-03 12:33:03 ..HSA            0            0  [SYSTEM]/$Extend/$Reparse
2014-05-09 10:46:47 ....A        86144        90112  Documents and Settings/Person/Application Data/Dropbox/instance1/l/536cb1a7
2013-05-29 23:37:50 D....                            WINDOWS
2015-11-07 15:25:40 D....                            WINDOWS/system32
2013-05-03 12:05:12 D....                            WINDOWS/system32/config
2015-06-01 17:41:13 D....                            WINDOWS/system32/drivers
2013-05-03 12:41:52 D....                            WINDOWS/system
2013-05-03 12:35:48 D....                            WINDOWS/system32/ras
2013-05-03 12:00:39 D....                            WINDOWS/system32/spool
2013-05-03 12:33:10 D....                            WINDOWS/system32/spool/drivers
2013-05-03 12:33:10 D....                            WINDOWS/system32/spool/drivers/w32x86


问:
how to change the size of the image retrived from the oracle db
Hi:
In our oracle db,there is a blob column used to save the images.

Now I have to display them in the web page,so I create a Image.aspx,which will read the binary blob data and write them to the response so I can insert this image using :

```<code><img src="Image.aspx?id=xx />
</code>```

However the size(16k,12M?) and the resoution(800x600,4000x1299?) is not sure,so somethime the image may so large,it will cost much time to download,also some images's resolution is more than 2000x2000,so I want to zoom in them to a small scale.

That's to say I have read the image binary and chagne them to a "Image" object,read its size and change it?

How to make it?

答:
You can use Oracle built-ins to rescale/size the image
But you'd have to use the BLOB in a constructor for an ORDImage. Then get the Ordimage properties which might be a bit of a strain.</p>

Body:
Hi:
In our oracle db,there is a blob column used to save the images.

Now I have to display them in the web page,so I create a Image.aspx,which will read the binary blob data and write them to the response so I can insert this image using :

However the size(16k,12M?) and the resoution(800x600,4000x1299?) is not sure,so somethime the image may so large,it will cost much time to download,also some images's resolution is more than 2000x2000,so I want to zoom in them to a small scale.

That's to say I have read the image binary and chagne them to a "Image" object,read its size and change it?

How to make it?


问:
Using Wordpress Theme customizer or not?
I’m trying to create my own theme for a multisite WP and I stumble upon the following issue regarding the customization of the theme (via the admin).

Overview

I own three websites on the same multisite,

I want to use the one theme for my three websites,

I want my user to be able to customized said theme (per domain) as they see fit,

Those options should be build-in in the theme.

There will be enough options for my websites to look entirely differents.

Use case

In the admin I want my user to be able to do lots of things:

1 | Classical actions

Change logos (regular and retina)

Change favicon

2 | Components

In the design, we’ll have multiple versions of one components.
Meaning that I’m giving a choice to my user, such as:

Do you want to display header option 1, option 2 or option 3 ?

Would you want this CTA to look like option 1, option 2, or option 3 ?

You get the gist of it and this will also be applied to footers, shortcodes, etc.

Styling & Colors

Theme style: fullwidth version of the theme, centered...

Header, Body and footer's colors (background, text, links…)

etc.

I wanted to clarify the context before asking my question, I hope it’s clear for you.

The question

Is it better to use Wordpress Theme Customizer OR to create my own custom theme section in the admin ?

And most importantly, why ?

I found out few articles about this matter and my understanding of the Customizer, is that it is convenient because:

Options are all in one place

Live preview

Documentation

But I also saw a lot of premium themes with custom section, which seems more user-friendly, there’s more space for the interface, tabs...

Can you give me your take on this ? I don't want to start my developpement without any clue.
If you have articles on this subject I would be grateful !

Thanks in advance.

答: If (like you said in the Use Case) you want your users to change logos and favicons, while also changing header, body and footer's colors. I would advise you to create your own custom theme section in the admin. It is more convenient and you have the freedom to give the user the choices you desire.</p>


问:
creating new column values according to filters
I applied these conditions to my dataframe. If all these conditions are TRUE, I want to create an integer column with the value 1, but I don't know how to create this final step.

my final goal is having something in the style of case when in SQL

```<code>df.loc[df['AREA'].isin([8,22,19,27,22]) | (df['AREA']==4) & (~df['REGION'].isin([53,65,86])) | (df['AREA']==1) & (df['company']==1)]

</code>```

答:
I suggest create each masks separately and pass to numpy.select:

```<code>m1 = df['AREA'].isin([8,22,19,27,22])
m2 = (df['AREA']==4) & (~df['REGION'].isin([53,65,86]))
m3 = (df['AREA']==1) & (df['company']==1)

df['new'] = np.select([m1, m2, m3], [1,2,3], default=0)
</code>```

Body:
I applied these conditions to my dataframe. If all these conditions are TRUE, I want to create an integer column with the value 1, but I don't know how to create this final step.

my final goal is having something in the style of case when in SQL

df.loc[df['AREA'].isin([8,22,19,27,22]) | (df['AREA']==4) & (~df['REGION'].isin([53,65,86])) | (df['AREA']==1) & (df['company']==1)]

Body:
I suggest create each masks separately and pass to numpy.select:

m1 = df['AREA'].isin([8,22,19,27,22])
m2 = (df['AREA']==4) & (~df['REGION'].isin([53,65,86]))
m3 = (df['AREA']==1) & (df['company']==1)

df['new'] = np.select([m1, m2, m3], [1,2,3], default=0)


问:
AngularJs $http request stays pending and does not return value from the database
I am currently writing a route which allows me to recieve information from a stored procudre I have in a database. I have written a request in AngularJS and a route in NodeJS but I am just recieving a pending request in the chrome Network developer window. I can see that the console.log in the NodeJs app has the data I require so it has retrieved it but there is nothing coming back in any of the console logs in the the AngularJS app.

Here is the code for the both the angularJS app and the Node App:

AnglaurJS:

```<code>checkForReplenishmentEmptyTrolley = async () => {
        LIBRIS.extensions.openLoadingModal();
        console.log('in checkForReplenishmentEmptyTrolley');
        try {
          const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`)
            .then((response) => {
            console.log(response);
            // Request completed successfully
            }, (error) => {
            // Request error
            console.log(error);
            });
          console.log(varPromise.data);
          // 1. check that there are no ghost replenish - lines 1-15
          console.log('in try/catch');
          console.log('promise', varPromise);
        } catch (error) {
          console.log(error);
        }
      },
</code>```

NodeJS code:

```<code>app.get(`${ROUTE}/attachTrolley`, async function(req, res){
  const newRequest = await DB.newRequest();
  console.log('we have made it to the route');
  try {
    console.log('we have made it to the Try/Catch route');
    newRequest.input();
   const record = await newRequest.execute('dbo.usp_STK_CheckForUnattachedTrolley');
    res.json(record)
    console.log(record, 'record');
  } catch (err){
    handleError(res, err);
    console.log(err);
  }
});
</code>```

答:
The problem is that you are doing a .then on a awaited promises and not returning anything from that. You have two choice here

Either return response from then so when you try to access the value here console.log(varPromise.data); it works.

Or remove the .then alltogather as it is not required because you are awaiting it any ways.

Basically just do this

```<code>checkForReplenishmentEmptyTrolley = async () => {
  LIBRIS.extensions.openLoadingModal();
  console.log("in checkForReplenishmentEmptyTrolley");
  try {
    const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`);
    console.log(varPromise.data);
    // 1. check that there are no ghost replenish - lines 1-15
    console.log("in try/catch");
    console.log("promise", varPromise);
  } catch (error) {
    console.log(error);
  }
};
</code>```

Hope this fixes your issue.

Body:
I am currently writing a route which allows me to recieve information from a stored procudre I have in a database. I have written a request in AngularJS and a route in NodeJS but I am just recieving a pending request in the chrome Network developer window. I can see that the console.log in the NodeJs app has the data I require so it has retrieved it but there is nothing coming back in any of the console logs in the the AngularJS app.

Here is the code for the both the angularJS app and the Node App:

AnglaurJS:

checkForReplenishmentEmptyTrolley = async () => {
        LIBRIS.extensions.openLoadingModal();
        console.log('in checkForReplenishmentEmptyTrolley');
        try {
          const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`)
            .then((response) => {
            console.log(response);
            // Request completed successfully
            }, (error) => {
            // Request error
            console.log(error);
            });
          console.log(varPromise.data);
          // 1. check that there are no ghost replenish - lines 1-15
          console.log('in try/catch');
          console.log('promise', varPromise);
        } catch (error) {
          console.log(error);
        }
      },

NodeJS code:

app.get(`${ROUTE}/attachTrolley`, async function(req, res){
  const newRequest = await DB.newRequest();
  console.log('we have made it to the route');
  try {
    console.log('we have made it to the Try/Catch route');
    newRequest.input();
   const record = await newRequest.execute('dbo.usp_STK_CheckForUnattachedTrolley');
    res.json(record)
    console.log(record, 'record');
  } catch (err){
    handleError(res, err);
    console.log(err);
  }
});

Body:
The problem is that you are doing a .then on a awaited promises and not returning anything from that. You have two choice here

Either return response from then so when you try to access the value here console.log(varPromise.data); it works.

Or remove the .then alltogather as it is not required because you are awaiting it any ways.

Basically just do this

checkForReplenishmentEmptyTrolley = async () => {
  LIBRIS.extensions.openLoadingModal();
  console.log("in checkForReplenishmentEmptyTrolley");
  try {
    const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`);
    console.log(varPromise.data);
    // 1. check that there are no ghost replenish - lines 1-15
    console.log("in try/catch");
    console.log("promise", varPromise);
  } catch (error) {
    console.log(error);
  }
};

Hope this fixes your issue.


问:
How to compile and run a single class file cs file?
Sorry if this is trivial, I am new to Visual Studio, I have a single project in which contains  multiple class files (.cs) files, how do I run each one individually. Whenever I go to debug, it selects only a single .cs file. Thanks.

Edit : Coming from a java background using netbeans, it is possible to have a package with several .java files in the package, provided each of the .java files have a main method they can be individually compiled and ran. Is something like this available in Visual Studio?

答:
I am new to dot net world and facing same issue. To practice C# need to write several small small code in diff .cs files but again as per dot net only one Main() can be present.

So if you have 10 .cs file then make sure you update their 'main' method name with small case

```<code> static void main(string[] args){}
</code>```

And the file you want to run should have Main() method with capital M

```<code> static void Main(string[] args){}
</code>```

Also even if your .cs file are in some other folder, you need to run command from root folder only

```<code>dotnet run
</code>```

Body:
I am new to dot net world and facing same issue. To practice C# need to write several small small code in diff .cs files but again as per dot net only one Main() can be present.

So if you have 10 .cs file then make sure you update their 'main' method name with small case

 static void main(string[] args){}

And the file you want to run should have Main() method with capital M

 static void Main(string[] args){}

Also even if your .cs file are in some other folder, you need to run command from root folder only

dotnet run


问:
How to pass class type as property
public class Myclass
{
Public Type type {get;set;}
}

While Json serialisation I am getting error “Could not cast or convert from System.String to System.Type”

Can some one help me out here ?

答:
to support that easiest way (not tested) should be (assuming you are on Newtonsoft.Json):</p>

```<code>public class MyClass
{
  private string _type;

  [JsonIgnore]
  public Type type {get => Assembly.GetType(_type, true, false); set => value.Fullname;}
}
</code>```

Title: How to pass class type as property

Body:
to support that easiest way (not tested) should be (assuming you are on Newtonsoft.Json):

public class MyClass
{
  private string _type;

  [JsonIgnore]
  public Type type {get => Assembly.GetType(_type, true, false); set => value.Fullname;}
}


问:
why this regular does not Match the html using python
the html is :

```<code><div style="background-color:#A7A7A7;text-align:center;">
<span style="color:#FFFFFF;">{{rk_user.name}}のｽﾃｰﾀｽ</span>
</div>
</code>```

my Regular is :

```<code>a = r'''
<div style="background-color:#([a-z0-9]+);text-align:center;">
\s*<span style="color:#(.+?);">(.+)</span>
</div>
'''
</code>```

but this Regular does not Match the html ,

so what is wrong  ?

thanks

答: In addition to what many other people are saying, you may want to use the re.UNICODE flag, since it looks like you have some Japanese characters in there.

Body:
the html is :

{{rk_user.name}}のｽﾃｰﾀｽ

my Regular is :

a = r'''

\s*(.+)

'''

but this Regular does not Match the html ,

so what is wrong  ?

thanks


问:
EJB method being called multiple times
I am developing a JEE8 Application on Payara 5 Server. I have a method in one of my stateless EJBs that I invoke only once (from JSF page) but on the server side it gets called executed multiple times. I have tried the method on Payara5.192, Payara 5.193 and Glassfish 5 as well. But I keep getting the same issue. Code below-

```<code>@Override
    public List<Forum> getForums(int startIndex, int size) {
        TypedQuery<Forum> tQ=em.createQuery("select f from Forum f", Forum.class);
        tQ.setFirstResult(startIndex);
        tQ.setMaxResults(size);
        List<Forum> toReturn=tQ.getResultList();
        LOGGER.info("Forums extracted "+toReturn.size());
        return toReturn;
    }
</code>```

If I start the pagination from the index 0 and with the result size of 5, the LOGGER.info generates the following log, which looks absurd!

```<code>Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5

</code>```

Moreover, the number of times this loops go is not fixed either. It can get executed between 15-30 times. whereas I expect only one log message, obviously.

答:
If you use #{managedBean.forums} as a value of a JSF component your method may be called multiple times, because any time the component needs to access the data it will call the getter.

The way to do this in JSF is implement a method that loads the data and call it from the @PostConstruct method, and every time you need to reload the data. The method used in the value property of the JSF component shoud be a simple getter that only returns the data:

```<code>private List<Forum> forums;

public List<Forum> getForums() {
    return forums;
}

@PostConstruct
private void init() {
    loadForums();
}

public void loadForums() {
    TypedQuery<Forum> tQ=em.createQuery("select f from Forum f", Forum.class);
    tQ.setFirstResult(startIndex);
    tQ.setMaxResults(size);
    forums =tQ.getResultList();
    LOGGER.info("Forums extracted "+forums.size());
}
</code>```

Title: EJB method being called multiple times

Body:
I am developing a JEE8 Application on Payara 5 Server. I have a method in one of my stateless EJBs that I invoke only once (from JSF page) but on the server side it gets called executed multiple times. I have tried the method on Payara5.192, Payara 5.193 and Glassfish 5 as well. But I keep getting the same issue. Code below-

@Override
    public List<Forum> getForums(int startIndex, int size) {
        TypedQuery<Forum> tQ=em.createQuery("select f from Forum f", Forum.class);
        tQ.setFirstResult(startIndex);
        tQ.setMaxResults(size);
        List<Forum> toReturn=tQ.getResultList();
        LOGGER.info("Forums extracted "+toReturn.size());
        return toReturn;
    }

If I start the pagination from the index 0 and with the result size of 5, the LOGGER.info generates the following log, which looks absurd!

Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5
Info:   Forums extracted 5

Moreover, the number of times this loops go is not fixed either. It can get executed between 15-30 times. whereas I expect only one log message, obviously.

Body:
If you use #{managedBean.forums} as a value of a JSF component your method may be called multiple times, because any time the component needs to access the data it will call the getter.

The way to do this in JSF is implement a method that loads the data and call it from the @PostConstruct method, and every time you need to reload the data. The method used in the value property of the JSF component shoud be a simple getter that only returns the data:

private List<Forum> forums;

public List<Forum> getForums() {
    return forums;
}

@PostConstruct
private void init() {
    loadForums();
}

public void loadForums() {
    TypedQuery<Forum> tQ=em.createQuery("select f from Forum f", Forum.class);
    tQ.setFirstResult(startIndex);
    tQ.setMaxResults(size);
    forums =tQ.getResultList();
    LOGGER.info("Forums extracted "+forums.size());
}