问:
ddev exec: command not found (.bash_aliases)
In a local ddev instance, I have added a few aliases and functions to .ddev/homeadditions/bash_aliases.

For example: alias ll="ls -lhA"

While ddev ssh and then ll will work, ddev exec ll returns

```<code>bash: ll: command not found
Failed to execute command ll: exit status 127
</code>```

Why?

答:
It's really about how bash works, not about how ddev works. The .bashrc (and thus .bash_aliases, which gets loaded by .bashrc) is only loaded by interactive shells (contexts like ddev ssh). Here'a an Stack Overflow answer on it: Why aliases in a non-interactive Bash shell do not work

ddev exec just does a bash -c "<your command>", and bash -c is noninteractive by design.

You might consider adding ddev custom web commands for things you can't live without.

A ddev ll custom command could work like this. Create a file named "ll" in .ddev/commands/web with the contents

```<code>#!/bin/bash

## Description: Run ls -l inside web container
## Usage: ll [flags] [arguments]
## Example: "ddev ll"  or `ddev ll /tmp`

ls -l $@
</code>```

Body:
In a local ddev instance, I have added a few aliases and functions to .ddev/homeadditions/bash_aliases.

For example: alias ll="ls -lhA"

While ddev ssh and then ll will work, ddev exec ll returns

bash: ll: command not found
Failed to execute command ll: exit status 127

Why?

Body:
It's really about how bash works, not about how ddev works. The .bashrc (and thus .bash_aliases, which gets loaded by .bashrc) is only loaded by interactive shells (contexts like ddev ssh). Here'a an Stack Overflow answer on it: Why aliases in a non-interactive Bash shell do not work

ddev exec just does a bash -c "<your command>", and bash -c is noninteractive by design.

You might consider adding ddev custom web commands for things you can't live without.

A ddev ll custom command could work like this. Create a file named "ll" in .ddev/commands/web with the contents

#!/bin/bash

## Description: Run ls -l inside web container
## Usage: ll [flags] [arguments]
## Example: "ddev ll"  or `ddev ll /tmp`

ls -l $@


来源: stackexchange

问:
Not getting correct path from root node to point
I am trying to find a path from the root node to a given point but ends up in getting an empty array.In the output I should get List of string of path id's from root to the given point. Please check below link for detailed description about problem.

Problem Statement

I have tried below code to get string id's.

```<code>public static List<String> findPathToNode(Node rootNode, Point toFind) {
    // @ToDo Implement this routine
    List<String> nodeList = new ArrayList<>();

    return getAllNodesForPoint(rootNode, toFind, nodeList);   }

  //Recursive function to loop through all nodes of tree and return empty LinkedList   // if point not found or NOT Empty with the path to the point, if point is found

  static List<String> getAllNodesForPoint(Node n, Point p, List<String> list) {
    list.add(n.getId());
    for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list = new LinkedList<>();
        list.add(n.getId());
      }
    }
    list = new ArrayList<>();
    return list;   }

  static boolean isContained(Node e, Point p){
    Point topLeft = new Point(e.getLeft(), e.getTop());
    Point topRight = new Point(e.getLeft()+e.getWidth(), e.getTop());
    Point bottomLeft = new Point(e.getLeft(), e.getTop()+e.getHeight());
    Point bottomRight = new Point(e.getLeft()+e.getWidth(), e.getTop()+e.getHeight());
    if(topLeft.getX()<p.getX()
            &&p.getX()<topRight.getX()
            &&topLeft.getY()<p.getY()
            &&bottomLeft.getY()>p.getY()){
      return true;
    }
    else{
      return false;
    }   }
</code>```

Thank you in advanced!!!

答:
There is error in your this part of code fragment

```<code>for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list = new LinkedList<>();
        list.add(n.getId());
      }
    }
    list = new ArrayList<>();
    return list;
</code>```

We can use example given in your problem statement to explain the same.

Example :

```<code>{"id": "root" ,
"left": 0 ,
"top": 0 ,
"width": 33 ,
"height": 23 ,
"children": [{
               "id": "child-0" ,
                "left": 5 ,
                 “top": 5 ,
                 "width": 20 ,
                 "height": 10 ,
                  "children": []},
               {"id": "child-1" ,
                "left": 10 ,
                "top": 10 ,
                 "width": 20 ,
                  "height": 10 ,
                  "children": []
                }
      ]}
</code>```

It starts with root node and in its children array there are two childs child-0 and child-1 . Because of this it will go in this part of code

```<code>for (Node temp : n.getChildren())
</code>```

Now this for loop will run 2 times , since there are two children of root node.

But each  child children array is empty so it will fail to go in this fragement of code:

```<code>if (temp.getChildren().size() > 0)
</code>```

instead, it will go in the else part.
But first issue is over here. Here, you are initializing an array list every time and adding this children Id.
So, when the loop runs the first time for child-1 it will create a new list by this

```<code>list = new LinkedList<>();
</code>```

and add child-1 to it.
and next time it will again run for child-2 and reinitialize the list and add child-2 to it.

So, at the end of for loop in our list we will have only 1 entry of child-2.

But you are getting empty list as result because after ending for loop you have again reinitialized the list and you are returning empty list.This is the second issue.

```<code>list = new ArrayList<>();
return list;
</code>```

The corrected code of getAllNodesForPoint is

```<code>list.add(n.getId());
    for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list.add(temp.getId());
      }
    }
    return list;   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to find a path from the root node to a given point but ends up in getting an empty array.In the output I should get List of string of path id's from root to the given point. Please check below link for detailed description about problem.

Problem Statement

I have tried below code to get string id's.

public static List<String> findPathToNode(Node rootNode, Point toFind) {
    // @ToDo Implement this routine
    List<String> nodeList = new ArrayList<>();

    return getAllNodesForPoint(rootNode, toFind, nodeList);   }

  //Recursive function to loop through all nodes of tree and return empty LinkedList   // if point not found or NOT Empty with the path to the point, if point is found

  static List<String> getAllNodesForPoint(Node n, Point p, List<String> list) {
    list.add(n.getId());
    for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list = new LinkedList<>();
        list.add(n.getId());
      }
    }
    list = new ArrayList<>();
    return list;   }

  static boolean isContained(Node e, Point p){
    Point topLeft = new Point(e.getLeft(), e.getTop());
    Point topRight = new Point(e.getLeft()+e.getWidth(), e.getTop());
    Point bottomLeft = new Point(e.getLeft(), e.getTop()+e.getHeight());
    Point bottomRight = new Point(e.getLeft()+e.getWidth(), e.getTop()+e.getHeight());
    if(topLeft.getX()<p.getX()
            &&p.getX()<topRight.getX()
            &&topLeft.getY()
p.getY()){
      return true;
    }
    else{
      return false;
    }   }

Thank you in advanced!!!

Body:
There is error in your this part of code fragment

for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list = new LinkedList<>();
        list.add(n.getId());
      }
    }
    list = new ArrayList<>();
    return list;

We can use example given in your problem statement to explain the same.

Example :

{"id": "root" ,
"left": 0 ,
"top": 0 ,
"width": 33 ,
"height": 23 ,
"children": [{
               "id": "child-0" ,
                "left": 5 ,
                 “top": 5 ,
                 "width": 20 ,
                 "height": 10 ,
                  "children": []},
               {"id": "child-1" ,
                "left": 10 ,
                "top": 10 ,
                 "width": 20 ,
                  "height": 10 ,
                  "children": []
                }
      ]}

It starts with root node and in its children array there are two childs child-0 and child-1 . Because of this it will go in this part of code

for (Node temp : n.getChildren())

Now this for loop will run 2 times , since there are two children of root node.

But each  child children array is empty so it will fail to go in this fragement of code:

if (temp.getChildren().size() > 0)

instead, it will go in the else part.
But first issue is over here. Here, you are initializing an array list every time and adding this children Id.
So, when the loop runs the first time for child-1 it will create a new list by this

list = new LinkedList<>();

and add child-1 to it.
and next time it will again run for child-2 and reinitialize the list and add child-2 to it.

So, at the end of for loop in our list we will have only 1 entry of child-2.

But you are getting empty list as result because after ending for loop you have again reinitialized the list and you are returning empty list.This is the second issue.

list = new ArrayList<>();
return list;

The corrected code of getAllNodesForPoint is

list.add(n.getId());
    for (Node temp : n.getChildren()) {
      if (temp.getChildren().size() > 0) {
        if (isContained(temp, p)) {
          list.add(temp.getId());
          return list;
        } else {
          getAllNodesForPoint(temp, p, list);
        }
      } else {
        list.add(temp.getId());
      }
    }
    return list;   }


问:
Lotusscript forall loop failing to set variable
This is probably something easy but I've been pounding my head against the wall trying to figure out what I'm doing wrong.  The program is reading one document in a local db, getting a list stored in a field, looping through each entry in the list and searching for the name on a view in another db, once it finds it, it updates document and saves it.  The problem I am seeing is that pdoc (bolded below) never gets set to a value which causes the rest of the program to fail to update any documents.  </p>

```<code>Sub Initialize

    Dim db As NotesDatabase
    Dim s As New NotesSession
    Dim pview As NotesView
    Dim ldoc As NotesDocument, pdoc As NotesDocument
    Dim lgroup As Variant, pgroup As Variant, errors As Variant
    Dim collection As NotesDocumentCollection

    Dim nab As New NotesDatabase ("","")
    Call nab.Open( "xxxx/xxx", "names.nsf" )

    Set db = s.currentdatabase
    Set collection = db.unprocesseddocuments
    Set ldoc = collection.getfirstdocument

    Set pview = nab.GetView ("gfmm")

    While Not(ldoc Is Nothing)

        On Error Resume Next

        lgroup = ldoc.groups(0)

        ForAll g In lgroup
            **Set pdoc = pview.GetDocumentByKey( g )**

            pgroup = pdoc.ListName(0)

            If lgroup = pgroup Then
                pdoc.GroupType = "0"
                Call pdoc.Save(True, True)
            Else
                errors = errors + g
            End If

        End ForAll

        ldoc.errors = errors
        ldoc.status = "Complete"
        Call ldoc.save(True, True)

        Set ldoc = collection.getnextdocument(ldoc)

    Wend

End Sub
</code>```

答:
The error is quite simple: lgroups is not an array but a scalar value. This line

```<code>lgroup = ldoc.groups(0)
</code>```

Just gets the first value of the item groups in ldoc, not all values. Just change it to

```<code>lgroup = ldoc.groups
</code>```

Then you will have an array that you can loop through. Same is true for pgroup a view lines below.

Body:
This is probably something easy but I've been pounding my head against the wall trying to figure out what I'm doing wrong.  The program is reading one document in a local db, getting a list stored in a field, looping through each entry in the list and searching for the name on a view in another db, once it finds it, it updates document and saves it.  The problem I am seeing is that pdoc (bolded below) never gets set to a value which causes the rest of the program to fail to update any documents.

Sub Initialize

    Dim db As NotesDatabase
    Dim s As New NotesSession
    Dim pview As NotesView
    Dim ldoc As NotesDocument, pdoc As NotesDocument
    Dim lgroup As Variant, pgroup As Variant, errors As Variant
    Dim collection As NotesDocumentCollection

    Dim nab As New NotesDatabase ("","")
    Call nab.Open( "xxxx/xxx", "names.nsf" )

    Set db = s.currentdatabase
    Set collection = db.unprocesseddocuments
    Set ldoc = collection.getfirstdocument

    Set pview = nab.GetView ("gfmm")

    While Not(ldoc Is Nothing)

        On Error Resume Next

        lgroup = ldoc.groups(0)

        ForAll g In lgroup
            **Set pdoc = pview.GetDocumentByKey( g )**

            pgroup = pdoc.ListName(0)

            If lgroup = pgroup Then
                pdoc.GroupType = "0"
                Call pdoc.Save(True, True)
            Else
                errors = errors + g
            End If

        End ForAll

        ldoc.errors = errors
        ldoc.status = "Complete"
        Call ldoc.save(True, True)

        Set ldoc = collection.getnextdocument(ldoc)

    Wend

End Sub

Body:
The error is quite simple: lgroups is not an array but a scalar value. This line

lgroup = ldoc.groups(0)

Just gets the first value of the item groups in ldoc, not all values. Just change it to

lgroup = ldoc.groups

Then you will have an array that you can loop through. Same is true for pgroup a view lines below.


问:
php, how to run a link when check box checked?
```<code><input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';
</code>```

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

```<code>if ($('#checket:checked').val() !== undefined) {
</code>```

// Insert code here.
}

答:
The way I see it you have a couple options.

1) Open the link in a new window using javascript and an onclick

http://wpcult.com/open-external-links-in-a-new-window/

2) Set a cookie that stores the data and check for the existence of the cookie

http://www.w3schools.com/php/php_cookies.asp

3) Store the data in the session variable

http://www.w3schools.com/php/php_sessions.asp

ContentLicense: CC BY-SA 3.0

Body:
<input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

if ($('#checket:checked').val() !== undefined) {

// Insert code here.
}


问:
Passing data between a method and an event function
Hello I have been struggling trying to get the event to trigger based on the object that it is passed.... I am not sure if that's how it should be worded but you guys can take a look at the book and give me some insight

I am making a datagrid form, inside this form, there's a function

```<code>private void (List<string> listProducts>
{
    foreach (aProduct in listProducts)
            {
                // reset row data
                rowProduct = new string[10];
                // add the row
                this.dataDisplay.Tables["ProductData"].Rows.Add(rowProduct);
                double checkingresult;
                checkingresult = checkDiameter(aProduct);
}

</code>```

Inside this form there's a function that would check the validity of the test product, so checkingresult would return 0 or 1

Then I created an event button to click on to change the color of the cell in the datagrid when it is clicked

```<code>
     private void bttnChecking_Click(object sender, EventArgs e)
        {

            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.Font = new Font(datagridProductData.Font, FontStyle.Bold);
            style.BackColor = Color.Red;
            style.ForeColor = Color.White;

            foreach (aProduct in ListProducts)
            {

            }
                for (int i = 0; i < RowCount - 1; i++)
            {
                Rows[i].Cells[5].Style = style;

            }
        }
    }

</code>```

my question is, how do I pass the "checkingresult" into the event to change the color when it returns 0 or 1. Pls halp

答:
without seeing the function I am assuming that it returns the value of either 1 or 0. If it does then check for the result before this line:

```<code>DataGridViewCellStyle style = new DataGridViewCellStyle();
</code>```

something like this:

```<code> string result = foo(null);
 DataGridViewCellStyle style = new DataGridViewCellStyle();
</code>```

Provided your function returns a value as I am only assuming.

```<code> static string foo(string Status)
{
   {
    string result = "0";
    return result;
   }
}
</code>```

Body:
Hello I have been struggling trying to get the event to trigger based on the object that it is passed.... I am not sure if that's how it should be worded but you guys can take a look at the book and give me some insight

I am making a datagrid form, inside this form, there's a function

private void (List<string> listProducts>
{
    foreach (aProduct in listProducts)
            {
                // reset row data
                rowProduct = new string[10];
                // add the row
                this.dataDisplay.Tables["ProductData"].Rows.Add(rowProduct);
                double checkingresult;
                checkingresult = checkDiameter(aProduct);
}

Inside this form there's a function that would check the validity of the test product, so checkingresult would return 0 or 1

Then I created an event button to click on to change the color of the cell in the datagrid when it is clicked

     private void bttnChecking_Click(object sender, EventArgs e)
        {

            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.Font = new Font(datagridProductData.Font, FontStyle.Bold);
            style.BackColor = Color.Red;
            style.ForeColor = Color.White;

            foreach (aProduct in ListProducts)
            {

            }
                for (int i = 0; i < RowCount - 1; i++)
            {
                Rows[i].Cells[5].Style = style;

            }
        }
    }

my question is, how do I pass the "checkingresult" into the event to change the color when it returns 0 or 1. Pls halp

Body:
without seeing the function I am assuming that it returns the value of either 1 or 0. If it does then check for the result before this line:

DataGridViewCellStyle style = new DataGridViewCellStyle();

something like this:

 string result = foo(null);
 DataGridViewCellStyle style = new DataGridViewCellStyle();

Provided your function returns a value as I am only assuming.

 static string foo(string Status)
{
   {
    string result = "0";
    return result;
   }
}


问:
How to find functions which are not executed?
I have a MS Visual Studio 2005 workspace, all C code. I want to find all the functions in that code, which are not called/executed when a certain test case is executed.

What is the way to get that using

1.) MS VS 2005 itself or MSVC6.0 ?

2.) Using some other tool?

-AD

答: Use a code profiler.  Any good code profiler should include coverage tools to give you an idea of what was called and what was not called.</p>

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: plinth


问:
Most efficient/accurate way to download/upload with progress and speed in C#?
Uploading and downloading a file is easy enough. Doing so while displaying progress and a transfer rate has me questioning the best way to do it. I'm looking for that one perfect way. The method that's easy to use, accurate, and light weight. Tried and true.

The situation I'm talking about is, for example, downloading a file from a WebResponse or some other stream based transfer. Downloading it is as simple as (4.0 here):

```<code>HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream bufferedresponse = new BufferedStream(response.GetResponseStream());
bufferedresponse.CopyTo(TargetStream);
bufferedresponse.Close();
</code>```

You can't find a transfer rate until after it's done downloading, and even that is just an average. I'm thinking a touch more instantaneous. I don't always need an entire WebBrowser object, especially in REST API wrappers (where this particular sample is from), besides, doesn't WebBrowser also attempt to parse DOM and render it's content?

Are there binding techniques or simple multi-threaded approaches to this? Are there attributes/events of a stream class I'm overlooking? Another class entirely?

答:
You need to create an "ObservableStream" that will fire subscribable events that you can handle by incrementing a progress bar and updating telemetry.

Try this implementation, using the Reactive Extensions library: http://staceyw.posterous.com/observe-a-network-stream-using-rx

Body:
Uploading and downloading a file is easy enough. Doing so while displaying progress and a transfer rate has me questioning the best way to do it. I'm looking for that one perfect way. The method that's easy to use, accurate, and light weight. Tried and true.

The situation I'm talking about is, for example, downloading a file from a WebResponse or some other stream based transfer. Downloading it is as simple as (4.0 here):

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream bufferedresponse = new BufferedStream(response.GetResponseStream());
bufferedresponse.CopyTo(TargetStream);
bufferedresponse.Close();

You can't find a transfer rate until after it's done downloading, and even that is just an average. I'm thinking a touch more instantaneous. I don't always need an entire WebBrowser object, especially in REST API wrappers (where this particular sample is from), besides, doesn't WebBrowser also attempt to parse DOM and render it's content?

Are there binding techniques or simple multi-threaded approaches to this? Are there attributes/events of a stream class I'm overlooking? Another class entirely?


问:
loop in python for two text files
this is my first time here and i wish i get your help.
i'm new to python and i need your help

i have two .txt files
here an Example
file1.txt

```<code>customer1.com
customer2.com
customer3.com
customer4.com
customer5.com
customer6.com
customer7.com
customer8.com
customer9.com
</code>```

file2.txt

```<code>service1
service2
service3
</code>```

i want to loop the file2.txt on the file1.txt =>
like the following example

```<code>customer1.com/service1
customer1.com/service2
customer1.com/service3

customer2.com/service1
customer2.com/service2
customer2.com/service3

customer3.com/service1
customer3.com/service2
customer3.com/service3
</code>```

AND GOES ON  TILL  file1.txt is done.

also i need to make IF statment
for example let's say the customer number3 has the service number 2 (file found i mean)

customer3.com/service2 [service found]

i need the loop for customer3 to stop looking for services and save the output (customer3.com/service2) in a new file called file3.txt
and the loop go on with other customers and every customer has the service found, the output save in file3.txt

i hope you understand what i mean.
thanks.

答:
Loop task is easy. you need to read every file and to save data as list. then write a file with that loop order. See example. But I do not understand that black line and that service found logic. Is to general. Be more specific.

Example:

```<code>list1, list2 = [], []

with open("file1.txt", "r") as f1:
    line = f1.readline()
    while line:
        line = line.strip()
        list1.append(line)
        line = f1.readline()
with open("file2.txt", "r") as f2:
    line = f2.readline()
    while line:
        line = line.strip()
        list2.append(line)
        line = f2.readline()
with open("file3.txt", "w") as f3:
    for i in list1:
        for j in list2:
            f3.write(f"{i}/{j}\n")
        f3.write("\n") # just for that black line
</code>```

Title: loop in python for two text files

Body:
this is my first time here and i wish i get your help.
i'm new to python and i need your help

i have two .txt files
here an Example
file1.txt

customer1.com
customer2.com
customer3.com
customer4.com
customer5.com
customer6.com
customer7.com
customer8.com
customer9.com

file2.txt

service1
service2
service3

i want to loop the file2.txt on the file1.txt =>
like the following example

customer1.com/service1
customer1.com/service2
customer1.com/service3

customer2.com/service1
customer2.com/service2
customer2.com/service3

customer3.com/service1
customer3.com/service2
customer3.com/service3

AND GOES ON  TILL  file1.txt is done.

also i need to make IF statment
for example let's say the customer number3 has the service number 2 (file found i mean)

customer3.com/service2 [service found]

i need the loop for customer3 to stop looking for services and save the output (customer3.com/service2) in a new file called file3.txt
and the loop go on with other customers and every customer has the service found, the output save in file3.txt

i hope you understand what i mean.
thanks.

Body:
Loop task is easy. you need to read every file and to save data as list. then write a file with that loop order. See example. But I do not understand that black line and that service found logic. Is to general. Be more specific.

Example:

list1, list2 = [], []

with open("file1.txt", "r") as f1:
    line = f1.readline()
    while line:
        line = line.strip()
        list1.append(line)
        line = f1.readline()
with open("file2.txt", "r") as f2:
    line = f2.readline()
    while line:
        line = line.strip()
        list2.append(line)
        line = f2.readline()
with open("file3.txt", "w") as f3:
    for i in list1:
        for j in list2:
            f3.write(f"{i}/{j}\n")
        f3.write("\n") # just for that black line


问:
Is it possible to batch delete contacts using google people api?
I found there is batch operation in Contact API. But it's XML form and I prefer to use JSON form in People API. Is it possible?</p>

答:
It could be done by using a contactGroup:

Create a temporary group with contactGroup.create.

Add all the members to delete in the group with
contactGroup.members.modify.

Delete the temporary group with contactGroup.delete and
using deleteContacts=true.


问:
Is possible to add NUMBER value return in Js?
I am using Javascript. In success function, I am getting some results and storing in var say "baldet" in JS-CODE.

example:

```<code>success: function (result) {
        baldet = result;

        console.log(baldet[0].cleavebalance);

        if (openmon == 1){
        $("#clvbalance").val(baldet[0].cleavebalance);
    }
    }
</code>```

from baldet[0].cleavebalance I am getting 2. My condition is if openmon == 1 then I want to add number 1 in it.

NOTE: add means SUM, not CONCAT()

So that i could get, 2 (from "baldet[0].cleavebalance" + 1 (number i want to add)) i.e. 2 + 1 = 3.

and show in $("#clvbalance").val("3"); // value 3 is after getting SUM RESULT

Currently, I am getting "21" instead of "3"

I hope I made my query clear. Any help will be appreciated.

答:
You need to parse from string to number like below

console.log("2" + 1); // dose not parse

console.log(parseInt("2") + 1)```

Body:
I am using Javascript. In success function, I am getting some results and storing in var say "baldet" in JS-CODE.

example:

success: function (result) {
        baldet = result;

        console.log(baldet[0].cleavebalance);

        if (openmon == 1){
        $("#clvbalance").val(baldet[0].cleavebalance);
    }
    }

from baldet[0].cleavebalance I am getting 2. My condition is if openmon == 1 then I want to add number 1 in it.

NOTE: add means SUM, not CONCAT()

So that i could get, 2 (from "baldet[0].cleavebalance" + 1 (number i want to add)) i.e. 2 + 1 = 3.

and show in $("#clvbalance").val("3"); // value 3 is after getting SUM RESULT

Currently, I am getting "21" instead of "3"

I hope I made my query clear. Any help will be appreciated.


问:
DB Schema design Parent Children grand children
Hi i am researching a way to create a relation db with a structure as follows

```<code>Parent
 -Child 1
  -Grand Child 1
 -Child 2
  -Grand child 2
</code>```

But grand child 2 can be also part of child 1

If a parent can have n children and the child can have n grand children that is fine it is pretty simple using RMDBS.

The problem comes up when you want to go 'n' deeper with grand grand children and grand children can be part of multiple children.

A good example is ebay categorization of their products.

What is the right way to create a dynamic tree/web like this in the database?

答:
From my answer to a similar question:

In a more complex model, e.g. different car models sharing the same
  motor model (and it's not clear whether you are talking about car
  models, or specific cars), the ParentEntityId column would be replaced
  by a relation table:

```<code>TABLE Entity (Id, Name, EntityTypeId)
TABLE EntityHierarchy (Id, ParentEntityId, ChildEntityId)
</code>```

The entries in the EntityHierarchy table would be constrained (on
  application level) by the tree of EntityTypes

Body:
Hi i am researching a way to create a relation db with a structure as follows

Parent
 -Child 1
  -Grand Child 1
 -Child 2
  -Grand child 2

But grand child 2 can be also part of child 1

If a parent can have n children and the child can have n grand children that is fine it is pretty simple using RMDBS.

The problem comes up when you want to go 'n' deeper with grand grand children and grand children can be part of multiple children.

A good example is ebay categorization of their products.

What is the right way to create a dynamic tree/web like this in the database?

Body:
From my answer to a similar question:

In a more complex model, e.g. different car models sharing the same
  motor model (and it's not clear whether you are talking about car
  models, or specific cars), the ParentEntityId column would be replaced
  by a relation table:

TABLE Entity (Id, Name, EntityTypeId)
TABLE EntityHierarchy (Id, ParentEntityId, ChildEntityId)

The entries in the EntityHierarchy table would be constrained (on
  application level) by the tree of EntityTypes


问:
How to update mesh data via blender python script?
I can create a mesh in blender with this script:

```<code>mesh = bpy.data.meshes.new("mymesh")
obj = bpy.data.objects.new("myobj", mesh)
bpy.context.scene.collection.objects.link(obj)
mesh.from_pydata([[0, 0, 0], [1, 0, 0], [1, 1, 0]], [], [[0, 1, 2]])
</code>```

However, if I try to update the mesh data with from_pydata again, it results in an error:

```<code>RuntimeError: internal error setting the array
</code>```

Is there a way to update the mesh data after the mesh has been created?

(I'm trying to avoid deleting the object and creating it again with new data.)

答:
The from_pydata function takes lists of data and creates a mesh data block. Once you have the mesh data block you can adjust the mesh properties directly. These can be found in the vertices, edges and polygons properties of the mesh data.

```<code>obj.data.vertices[0].co.x = 1.25
</code>```

Mostly this data should not be directly altered, any changes made while in edit mode will get overwritten as the edit mesh is stored as bmesh data. The bmesh module provides faster access and methods to alter mesh data and can also update the mesh while in edit mode.

Body:
I can create a mesh in blender with this script:

mesh = bpy.data.meshes.new("mymesh")
obj = bpy.data.objects.new("myobj", mesh)
bpy.context.scene.collection.objects.link(obj)
mesh.from_pydata([[0, 0, 0], [1, 0, 0], [1, 1, 0]], [], [[0, 1, 2]])

However, if I try to update the mesh data with from_pydata again, it results in an error:

RuntimeError: internal error setting the array

Is there a way to update the mesh data after the mesh has been created?

(I'm trying to avoid deleting the object and creating it again with new data.)

Body:
The from_pydata function takes lists of data and creates a mesh data block. Once you have the mesh data block you can adjust the mesh properties directly. These can be found in the vertices, edges and polygons properties of the mesh data.

obj.data.vertices[0].co.x = 1.25

Mostly this data should not be directly altered, any changes made while in edit mode will get overwritten as the edit mesh is stored as bmesh data. The bmesh module provides faster access and methods to alter mesh data and can also update the mesh while in edit mode.


问:
Why can Razor not see ViewBag, Url.Content, etc. when the layout page is outside ~/Views/Shared?
I'm working on a CSS framework that I can drop in to other projects as a NuGet package.

To keep things clean, the entire framework - views, styles, images, and master pages / layout pages - is actually stored under ~/CssThing/

Works perfectly with the WebForms view engine, but when I move the _layout.cshtml file into ~/CssThing/ and then modify my Razor page to say:

```<code>@{
Layout = "~/CssThing/_layout.cshtml";
}
</code>```

it starts complaining that ViewBag is not defined, or that The name 'Url' does not exist in the current context, or various other bits of weirdness that suggest the view is no longer inheriting from the proper base class.

How can I get this to work?

NOTE: The reason everything's split out like this is there's no way to force NuGet to overwrite existing code, and there's no way to spin up an empty MVC3 web application without picking up all the jQuery, etc. references, so rather than risk my framework getting half-deployed because half the files were already present, I'm keeping everything completely seperate.

答:
Check you have a web.config in the new views directory. It's best to copy the one created by the default project in Views.
This web.config defines Razor's settings like default page base class and what namespaces are implicitly available. Those namespaces define what HTML helpers you can use.</p>

Body:
I'm working on a CSS framework that I can drop in to other projects as a NuGet package.

To keep things clean, the entire framework - views, styles, images, and master pages / layout pages - is actually stored under ~/CssThing/

Works perfectly with the WebForms view engine, but when I move the _layout.cshtml file into ~/CssThing/ and then modify my Razor page to say:

@{
Layout = "~/CssThing/_layout.cshtml";
}

it starts complaining that ViewBag is not defined, or that The name 'Url' does not exist in the current context, or various other bits of weirdness that suggest the view is no longer inheriting from the proper base class.

How can I get this to work?

NOTE: The reason everything's split out like this is there's no way to force NuGet to overwrite existing code, and there's no way to spin up an empty MVC3 web application without picking up all the jQuery, etc. references, so rather than risk my framework getting half-deployed because half the files were already present, I'm keeping everything completely seperate.


问:
How to do this as mysql query
I need help with a mysql query. I have a table like this
I have "type" 1 to 15. I would like help with a query to automatically change the "type"</p>

答:
I wouldn't do it as an update, because you're saying that points determine type, and you want points AND type in the table, which means they must always be kept in sync. Of the two, points is more fine grained - points can be used to determine type but not the other way round - so we can devise a strategy to determine the type from the current points, and we can let points increase and the type will change automatically upon querying:

make another table with the type, lower and upper bound for points and then join it in to find the type:

```<code>CREATE TABLE  TypeRanges (
  playerType INT,
  fromPoints INT,
  toPoints INT
)

INSERT INTO TypeRanges VALUES(1, 0, 1599)
...

SELECT * FROM
  username p
  INNER JOIN typeRanges t ON p.points BETWEEN t.fromPoints AND t.toPoints
</code>```

Remember that BETWEEN is inclusive at both ends so for < 1600 points you want the end to be 1599, for 1600 to 14000 you probably want 1600 and 13999 etc

If you want, you can make a view out of this query and then use that view anywhere you want to know the points and the type together. See the comments for a bit more on what a view is /used for

Footnote on dynamism/ performance considerations:

Every time you run this query it will calculate the type from the points. Calculating the type when you run the query rather than updating the type when the points change means you can easily redefine the bounds or add to them just by altering the points range table. Because we are calculating every time it's highly responsive to data updating but it would be a few nanoseconds slower than having type stored and retrieved simply; in most cases the benefits of recalculating outweigh this but if you're going to be querying it thousands of times per second and updating it once a year (as an extreme example) it may make sense to store the type instead. In most typical use cases I would go the route of calculating the type from the points and only look to optimize it if it proves to be a problem when scaled to large numbers of users and lots of activity. It would be a premature optimization to assume that lookup will make things unusably slow and seeking to store it - databases are engineered towards rapid data joining and retrieval. If you did determine that storing it would be better you can make the sync transparent by using a trigger to import the type upon each update

Side note; seek to avoid using reserved/keywords like TYPE as column names - while they can be quoted etc it usually does more good to find a more descriptive label for the column that doesn't need to be quoted in queries and treated specially in front end languages

Title: How to do this as mysql query

Body:
I wouldn't do it as an update, because you're saying that points determine type, and you want points AND type in the table, which means they must always be kept in sync. Of the two, points is more fine grained - points can be used to determine type but not the other way round - so we can devise a strategy to determine the type from the current points, and we can let points increase and the type will change automatically upon querying:

make another table with the type, lower and upper bound for points and then join it in to find the type:

CREATE TABLE  TypeRanges (
  playerType INT,
  fromPoints INT,
  toPoints INT
)

INSERT INTO TypeRanges VALUES(1, 0, 1599)
...

SELECT * FROM
  username p
  INNER JOIN typeRanges t ON p.points BETWEEN t.fromPoints AND t.toPoints

Remember that BETWEEN is inclusive at both ends so for < 1600 points you want the end to be 1599, for 1600 to 14000 you probably want 1600 and 13999 etc

If you want, you can make a view out of this query and then use that view anywhere you want to know the points and the type together. See the comments for a bit more on what a view is /used for

Footnote on dynamism/ performance considerations:

Every time you run this query it will calculate the type from the points. Calculating the type when you run the query rather than updating the type when the points change means you can easily redefine the bounds or add to them just by altering the points range table. Because we are calculating every time it's highly responsive to data updating but it would be a few nanoseconds slower than having type stored and retrieved simply; in most cases the benefits of recalculating outweigh this but if you're going to be querying it thousands of times per second and updating it once a year (as an extreme example) it may make sense to store the type instead. In most typical use cases I would go the route of calculating the type from the points and only look to optimize it if it proves to be a problem when scaled to large numbers of users and lots of activity. It would be a premature optimization to assume that lookup will make things unusably slow and seeking to store it - databases are engineered towards rapid data joining and retrieval. If you did determine that storing it would be better you can make the sync transparent by using a trigger to import the type upon each update

Side note; seek to avoid using reserved/keywords like TYPE as column names - while they can be quoted etc it usually does more good to find a more descriptive label for the column that doesn't need to be quoted in queries and treated specially in front end languages


问:
Reading Excel file is magnitudes slower using openpyxl compared to xlrd
I have an Excel spreadsheet that I need to import into SQL Server on a daily basis. The spreadsheet will contain around 250,000 rows across around 50 columns. I have tested both using openpyxl and xlrd using nearly identical code.

Here's the code I'm using (minus debugging statements):

```<code>import xlrd
import openpyxl

def UseXlrd(file_name):
    workbook = xlrd.open_workbook(file_name, on_demand=True)
    worksheet = workbook.sheet_by_index(0)
    first_row = []
    for col in range(worksheet.ncols):
        first_row.append(worksheet.cell_value(0,col))
    data = []
    for row in range(1, worksheet.nrows):
        record = {}
        for col in range(worksheet.ncols):
            if isinstance(worksheet.cell_value(row,col), str):
                record[first_row[col]] = worksheet.cell_value(row,col).strip()
            else:
                record[first_row[col]] = worksheet.cell_value(row,col)
        data.append(record)
    return data

def UseOpenpyxl(file_name):
    wb = openpyxl.load_workbook(file_name, read_only=True)
    sheet = wb.active
    first_row = []
    for col in range(1,sheet.max_column+1):
        first_row.append(sheet.cell(row=1,column=col).value)
    data = []
    for r in range(2,sheet.max_row+1):
        record = {}
        for col in range(sheet.max_column):
            if isinstance(sheet.cell(row=r,column=col+1).value, str):
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value.strip()
            else:
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value
        data.append(record)
    return data

xlrd_results = UseXlrd('foo.xls')
openpyxl_resuts = UseOpenpyxl('foo.xls')
</code>```

Passing the same Excel file containing 3500 rows gives drastically different run times. Using xlrd I can read the entire file into a list of dictionaries in under 2 second. Using openpyxl I get the following results:

```<code>Reading Excel File...
Read 100 lines in 114.14509415626526 seconds
Read 200 lines in 471.43183994293213 seconds
Read 300 lines in 982.5288782119751 seconds
Read 400 lines in 1729.3348784446716 seconds
Read 500 lines in 2774.886833190918 seconds
Read 600 lines in 4384.074863195419 seconds
Read 700 lines in 6396.7723388671875 seconds
Read 800 lines in 7998.775000572205 seconds
Read 900 lines in 11018.460735321045 seconds
</code>```

While I can use xlrd in the final script, I will have to hard code a lot of formatting because of various issues (i.e. int reads as float, date reads as int, datetime reads as float). Being that I need to reuse this code for a few more imports, it doesn't make sense to try and hard code specific columns to format them properly and have to maintain similar code across 4 different scripts.

Any advice on how to proceed?

答:
You call several times of "sheet.max_column" or "sheet.max_row". Don't do that. Just call it once.
If you call it on for loop, each time it will calculate once max_column or max_row.

I modify as below for your reference:

```<code>def UseOpenpyxl(file_name):
    wb = openpyxl.load_workbook(file_name, read_only=True)
    sheet = wb.active
    max_col = sheet.max_column
    max_row = sheet.max_row
    first_row = []
    for col in range(1,max_col +1):
        first_row.append(sheet.cell(row=1,column=col).value)
    data = []
    for r in range(2,max_row +1):
        record = {}
        for col in range(max_col):
            if isinstance(sheet.cell(row=r,column=col+1).value, str):
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value.strip()
            else:
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value
        data.append(record)
    return data
</code>```

Body:
I have an Excel spreadsheet that I need to import into SQL Server on a daily basis. The spreadsheet will contain around 250,000 rows across around 50 columns. I have tested both using openpyxl and xlrd using nearly identical code.

Here's the code I'm using (minus debugging statements):

import xlrd
import openpyxl

def UseXlrd(file_name):
    workbook = xlrd.open_workbook(file_name, on_demand=True)
    worksheet = workbook.sheet_by_index(0)
    first_row = []
    for col in range(worksheet.ncols):
        first_row.append(worksheet.cell_value(0,col))
    data = []
    for row in range(1, worksheet.nrows):
        record = {}
        for col in range(worksheet.ncols):
            if isinstance(worksheet.cell_value(row,col), str):
                record[first_row[col]] = worksheet.cell_value(row,col).strip()
            else:
                record[first_row[col]] = worksheet.cell_value(row,col)
        data.append(record)
    return data

def UseOpenpyxl(file_name):
    wb = openpyxl.load_workbook(file_name, read_only=True)
    sheet = wb.active
    first_row = []
    for col in range(1,sheet.max_column+1):
        first_row.append(sheet.cell(row=1,column=col).value)
    data = []
    for r in range(2,sheet.max_row+1):
        record = {}
        for col in range(sheet.max_column):
            if isinstance(sheet.cell(row=r,column=col+1).value, str):
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value.strip()
            else:
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value
        data.append(record)
    return data

xlrd_results = UseXlrd('foo.xls')
openpyxl_resuts = UseOpenpyxl('foo.xls')

Passing the same Excel file containing 3500 rows gives drastically different run times. Using xlrd I can read the entire file into a list of dictionaries in under 2 second. Using openpyxl I get the following results:

Reading Excel File...
Read 100 lines in 114.14509415626526 seconds
Read 200 lines in 471.43183994293213 seconds
Read 300 lines in 982.5288782119751 seconds
Read 400 lines in 1729.3348784446716 seconds
Read 500 lines in 2774.886833190918 seconds
Read 600 lines in 4384.074863195419 seconds
Read 700 lines in 6396.7723388671875 seconds
Read 800 lines in 7998.775000572205 seconds
Read 900 lines in 11018.460735321045 seconds

While I can use xlrd in the final script, I will have to hard code a lot of formatting because of various issues (i.e. int reads as float, date reads as int, datetime reads as float). Being that I need to reuse this code for a few more imports, it doesn't make sense to try and hard code specific columns to format them properly and have to maintain similar code across 4 different scripts.

Any advice on how to proceed?

Body:
You call several times of "sheet.max_column" or "sheet.max_row". Don't do that. Just call it once.
If you call it on for loop, each time it will calculate once max_column or max_row.

I modify as below for your reference:

def UseOpenpyxl(file_name):
    wb = openpyxl.load_workbook(file_name, read_only=True)
    sheet = wb.active
    max_col = sheet.max_column
    max_row = sheet.max_row
    first_row = []
    for col in range(1,max_col +1):
        first_row.append(sheet.cell(row=1,column=col).value)
    data = []
    for r in range(2,max_row +1):
        record = {}
        for col in range(max_col):
            if isinstance(sheet.cell(row=r,column=col+1).value, str):
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value.strip()
            else:
                record[first_row[col]] = sheet.cell(row=r,column=col+1).value
        data.append(record)
    return data


问:
How can I find all of rows which are selected by CSS in JS?
I want to find which the rows are selected by CSS using Javascript. I hava some lines and the code from some reference in other threads. See at the down below :

```<code>...
var trs = document.getElementsByTagName('tr');

for (var i = 2; i < trs.length; i++)
...
</code>```

For reference, this is what I've got from some other threads :

```<code>...
var totSelect = document.querySelectorAll("input[id$='inpt']:checked").length;
...
</code>```

CSS
...
   table tbody .selected tr {
        background-color: #E74C3C;
   }

How to implement the code above as a references to get and find all of rows selected by CSS in Javascript?

答:
If I understand you correctly, you're trying to select the same elements using javascript which are selected by your CSS.

If that's correct, just use the same selector in your JS.

```<code>var totSelect = document.querySelectorAll(`table tbody .selected tr`);
</code>```

This will return an array containing all the same elements which received the background-color: #E74C3C;

Body:
I want to find which the rows are selected by CSS using Javascript. I hava some lines and the code from some reference in other threads. See at the down below :

...
var trs = document.getElementsByTagName('tr');

for (var i = 2; i < trs.length; i++)
...

For reference, this is what I've got from some other threads :

...
var totSelect = document.querySelectorAll("input[id$='inpt']:checked").length;
...

CSS
...
   table tbody .selected tr {
        background-color: #E74C3C;
   }

How to implement the code above as a references to get and find all of rows selected by CSS in Javascript?

Body:
If I understand you correctly, you're trying to select the same elements using javascript which are selected by your CSS.

If that's correct, just use the same selector in your JS.

var totSelect = document.querySelectorAll(`table tbody .selected tr`);

This will return an array containing all the same elements which received the background-color: #E74C3C;


问:
Error: The permission type field is required when creating permission using Google Drive API
I'm trying to share a file using the Google Drive API. I have the file ID and the email to share the file to, but I keep getting an error "The permission type field is required". I've followed all the instructions on the API guide, but nothing seemed to fix this.

I'm calling the following function, and I can't tell why this isn't working. Can someone see what I'm doing wrong please?

```<code>function shareFile(id, email) {
    gdapi.permissions.create({
        fileId: id,
        resources: {
            role: "reader",
            type: "anyone",
            emailAddress: email
        }
    });
}
</code>```

Thanks!

答:
You want to create a permission with role: "reader" and type: "anyone" using googleapis of Node.js.

You have already been able to get and put values for files in Google Drive using Drive API.

gdapi in your script can be used for creating the permission to the file in Google Drive.

If my understanding is correct, how about this answer?

Modification points:

resources is not used. Please modify resources to resource or requestBody.

If you want to use role: "reader" and type: "anyone", please remove emailAddress: email.

When above points are reflected to your script, it becomes as follows.

Modified script:

```<code>function shareFile(id, email) {
    gdapi.permissions.create({
        fileId: id,
        resource: {  // Modified
            role: "reader",
            type: "anyone",
            // emailAddress: email  // Modified
        }
    });
}
</code>```

Note:

In this case, plese use the latest version of googleapis. In the current stage, the latest version is googleapis@47.0.0.

If you want to give role: "reader" to emailAddress: email, please modify as follows.

```<code>function shareFile(id, email) {
    gdapi.permissions.create({
        fileId: id,
        resource: {  // Modified
            role: "reader",
            type: "user",  // Modified
            emailAddress: email
        }
    });
}
</code>```

References:

Permissions: create

googleapis for Node.js

If I misunderstood your question and this was not the direction you want, I apologize.

Body:
I'm trying to share a file using the Google Drive API. I have the file ID and the email to share the file to, but I keep getting an error "The permission type field is required". I've followed all the instructions on the API guide, but nothing seemed to fix this.

I'm calling the following function, and I can't tell why this isn't working. Can someone see what I'm doing wrong please?

function shareFile(id, email) {
    gdapi.permissions.create({
        fileId: id,
        resources: {
            role: "reader",
            type: "anyone",
            emailAddress: email
        }
    });
}

Thanks!

Body:
You want to create a permission with role: "reader" and type: "anyone" using googleapis of Node.js.

You have already been able to get and put values for files in Google Drive using Drive API.

gdapi in your script can be used for creating the permission to the file in Google Drive.

If my understanding is correct, how about this answer?

Modification points:

resources is not used. Please modify resources to resource or requestBody.

If you want to use role: "reader" and type: "anyone", please remove emailAddress: email.

When above points are reflected to your script, it becomes as follows.

Modified script:

function shareFile(id, email) {
    gdapi.permissions.create({
        fileId: id,
        resource: {  // Modified
            role: "reader",
            type: "anyone",
            // emailAddress: email  // Modified
        }
    });
}

Note:

In this case, plese use the latest version of googleapis. In the current stage, the latest version is googleapis@47.0.0.

If you want to give role: "reader" to emailAddress: email, please modify as follows.

function shareFile(id, email) {
    gdapi.permissions.create({
        fileId: id,
        resource: {  // Modified
            role: "reader",
            type: "user",  // Modified
            emailAddress: email
        }
    });
}

References:

Permissions: create

googleapis for Node.js

If I misunderstood your question and this was not the direction you want, I apologize.


问:
How can I extract the upper 32 bits and lower 32 bits of a 64 bit integer in assembly?
I want to separate the upper and lower half of a 64 bit integer and put them into two registers. </p>

答:
Your question is really not clear. You should at least state whether you are using x86 or x64, and whether the source is in a register or in memory.

From a variable in memory

```<code>        ; .u64 --> EDI:ESI
.u64    DQ      0x0123456789ABCDEF
        MOV     ESI, [.u64]
        MOV     EDI, [.u64 + 4]
</code>```

x64, from a register

```<code>        ; RBX --> EDI:ESI
        MOV     ESI, EBX
        MOV     RDI, RBX
        SHR     RDI, 32
</code>```

x86, from a pair of registers

```<code>        ; 64-bit numbers are stored in register pairs, usually EDX:EAX
        ; EDX:EAX --> EDI:ESI
        MOV     EDI, EDX
        MOV     ESI, EAX
</code>```

Body:
Your question is really not clear. You should at least state whether you are using x86 or x64, and whether the source is in a register or in memory.

From a variable in memory

        ; .u64 --> EDI:ESI
.u64    DQ      0x0123456789ABCDEF
        MOV     ESI, [.u64]
        MOV     EDI, [.u64 + 4]

x64, from a register

        ; RBX --> EDI:ESI
        MOV     ESI, EBX
        MOV     RDI, RBX
        SHR     RDI, 32

x86, from a pair of registers

        ; 64-bit numbers are stored in register pairs, usually EDX:EAX
        ; EDX:EAX --> EDI:ESI
        MOV     EDI, EDX
        MOV     ESI, EAX


问:
Scraping with Rvest and Glue packages in R specifically
I'm trying to scrape multiple pages of sports data using rvest and glue packages. I'm having trouble with the nesting and I think it's because the table from the website has a two line header (some headers are one line some are two). Here's the code I have started with. I checked to make sure the site allowed scraping with python and all good there.

```<code>library(tidyverse)
library(rvest) # interacting with html and webcontent
library(glue)
</code>```

webpage: https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1

Function to scrape a selected week 1:17 and position 1:4:

```<code>salary_scrape_19 <- function(week, position) {

Sys.sleep(3)

cat(".")

url <- glue("https://fantasy.nfl.com/research/scoringleaders?position={position}&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek={week}")
read_html(url) %>%
    html_nodes("table") %>%
    html_table() %>%
    purrr::flatten_df() %>%
    #set_names(need to clean headers before I can set this)
}

scraped_df <- scaffold %>%
mutate(data = map2(week, position, ~salary_scrape_19(.x, .y)))

scraped_df
</code>```

Ultimately, I want to build a scrape function to get all the positions with the same columns which are QB, RB, WR, and TE for all weeks in 2019. (want to add a third variable to glue {year} eventually, but need to get this first.

Again, I think the issue has to do with the wonky headers of the table on the site as some are one row and other headings are two rows.

答:
We can paste 1st row as column names to original columns and then remove that row.

```<code>library(tidyverse)
library(rvest)

salary_scrape_19 <- function(week, position) {

  url <- glue::glue("https://fantasy.nfl.com/research/scoringleaders?position={position}&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek={week}")
  read_html(url) %>%
    html_nodes("table") %>%
    html_table() %>%
    .[[1]] %>%
    set_names(paste0(names(.), .[1, ])) %>%
    slice(-1)
}
</code>```

We can then use map2 to scrape the data for different week and position.

Trying it on sample data

```<code>scaffold <- data.frame(week = c(1, 2), position = c(1, 2))
scraped_df <- scaffold %>% mutate(data = map2(week, position, salary_scrape_19))
</code>```

Body:
I'm trying to scrape multiple pages of sports data using rvest and glue packages. I'm having trouble with the nesting and I think it's because the table from the website has a two line header (some headers are one line some are two). Here's the code I have started with. I checked to make sure the site allowed scraping with python and all good there.

library(tidyverse)
library(rvest) # interacting with html and webcontent
library(glue)

webpage: https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1

Function to scrape a selected week 1:17 and position 1:4:

salary_scrape_19 <- function(week, position) {

Sys.sleep(3)

cat(".")

url <- glue("https://fantasy.nfl.com/research/scoringleaders?position={position}&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek={week}")
read_html(url) %>%
    html_nodes("table") %>%
    html_table() %>%
    purrr::flatten_df() %>%
    #set_names(need to clean headers before I can set this)
}

scraped_df <- scaffold %>%
mutate(data = map2(week, position, ~salary_scrape_19(.x, .y)))

scraped_df

Ultimately, I want to build a scrape function to get all the positions with the same columns which are QB, RB, WR, and TE for all weeks in 2019. (want to add a third variable to glue {year} eventually, but need to get this first.

Again, I think the issue has to do with the wonky headers of the table on the site as some are one row and other headings are two rows.

Body:
We can paste 1st row as column names to original columns and then remove that row.

library(tidyverse)
library(rvest)

salary_scrape_19 <- function(week, position) {

  url <- glue::glue("https://fantasy.nfl.com/research/scoringleaders?position={position}&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek={week}")
  read_html(url) %>%
    html_nodes("table") %>%
    html_table() %>%
    .[[1]] %>%
    set_names(paste0(names(.), .[1, ])) %>%
    slice(-1)
}

We can then use map2 to scrape the data for different week and position.

Trying it on sample data

scaffold <- data.frame(week = c(1, 2), position = c(1, 2))
scraped_df <- scaffold %>% mutate(data = map2(week, position, salary_scrape_19))


问:
Using set as a way to reorder iterable
I have two tuples a and b and also a dictionary d

```<code>a=('C', 'G')
b=('G', 'C')
d={('G', 'C'): 'T'}
</code>```

I want d[a] and d[b] to return 'T'.

For that I used set() because I thought that set() was fixing the order of the elements of a iterable object (and removing the duplicates but I don't care about that).

So I did:

```<code>tuple(set(a)) in d  # return True
tuple(set(b)) in d  # return True
# I did tuple(set()) because set() alone is not hashable and so cannot be used directly
</code>```

This works, until it doesn't. And so I discover than sometimes

```<code>set(('C', 'G'))
{'C', 'G'}
</code>```

and sometimes it does not

```<code>set(('C', 'G'))
{'G', 'C'}
</code>```

I understand that set() orders the element as it wants but I expected that the order would always be the same with a given set of elements.

So my questions are:

Why it's not the case?

How can I solve my initial problem?

答:
One solution is to normalize the keys by sorting them. When we look up, we also sort the keys before looking up.

import collections.abc

def _normalize(key):
    """ Normalize a key (tuple) by sorting """
    key = tuple(sorted(key))
    return key

class TupleKeyDict(collections.abc.MutableMapping):
    def __init__(self, *args, **kwargs):
        temp_dict = dict(*args, **kwargs)
        self.dict = {
            _normalize(key): value
            for key, value in temp_dict.items()
        }

    def __getitem__(self, key):
        value = self.dict[_normalize(key)]
        return value

    def __setitem__(self, key, value):
        self.dict[_normalize(key)] = value

    def __delitem__(self, key):
        del self.dict[_normalize(key)]

    def __iter__(self):
        return iter(self.dict)

    def __len__(self):
        return len(self.dict)

    def __repr__(self):
        return repr(self.dict)
```

<pre class="lang-py prettyprint-override"><code>>>> tkd = TupleKeyDict(d)
>>> tkd
{('C', 'G'): 'T'}

>>> tkd['C', 'G']
'T'

>>> tkd['G', 'C']
'T'

>>> tkd.get(('X', 'Y')) is None
True

>>> tkd['X', 'C'] = 'cx'
>>> tkd['C', 'X']
'cx'
</code>```

Discussion

We cannot use sets as the keys before sets are mutable (changeable) therefore does not have a constant hash--a requirement for being a key. My approach is to create a specialized dictionary where the keys are sorted tuples which make looking up easier.

The __init__ method takes in everything that you can pass into dict(). The __repr__ method aids debugging. All other methods are there to fulfill the collections.abc.MutableMapping requirements.

Title: Using set as a way to reorder iterable

Body:
I have two tuples a and b and also a dictionary d

a=('C', 'G')
b=('G', 'C')
d={('G', 'C'): 'T'}

I want d[a] and d[b] to return 'T'.

For that I used set() because I thought that set() was fixing the order of the elements of a iterable object (and removing the duplicates but I don't care about that).

So I did:

tuple(set(a)) in d  # return True
tuple(set(b)) in d  # return True
# I did tuple(set()) because set() alone is not hashable and so cannot be used directly

This works, until it doesn't. And so I discover than sometimes

set(('C', 'G'))
{'C', 'G'}

and sometimes it does not

set(('C', 'G'))
{'G', 'C'}

I understand that set() orders the element as it wants but I expected that the order would always be the same with a given set of elements.

So my questions are:

Why it's not the case?

How can I solve my initial problem?

Body:
One solution is to normalize the keys by sorting them. When we look up, we also sort the keys before looking up.

import collections.abc

def _normalize(key):
    """ Normalize a key (tuple) by sorting """
    key = tuple(sorted(key))
    return key

class TupleKeyDict(collections.abc.MutableMapping):
    def __init__(self, *args, **kwargs):
        temp_dict = dict(*args, **kwargs)
        self.dict = {
            _normalize(key): value
            for key, value in temp_dict.items()
        }

    def __getitem__(self, key):
        value = self.dict[_normalize(key)]
        return value

    def __setitem__(self, key, value):
        self.dict[_normalize(key)] = value

    def __delitem__(self, key):
        del self.dict[_normalize(key)]

    def __iter__(self):
        return iter(self.dict)

    def __len__(self):
        return len(self.dict)

    def __repr__(self):
        return repr(self.dict)

>>> tkd = TupleKeyDict(d)
>>> tkd
{('C', 'G'): 'T'}

>>> tkd['C', 'G']
'T'

>>> tkd['G', 'C']
'T'

>>> tkd.get(('X', 'Y')) is None
True

>>> tkd['X', 'C'] = 'cx'
>>> tkd['C', 'X']
'cx'

Discussion

We cannot use sets as the keys before sets are mutable (changeable) therefore does not have a constant hash--a requirement for being a key. My approach is to create a specialized dictionary where the keys are sorted tuples which make looking up easier.

The __init__ method takes in everything that you can pass into dict(). The __repr__ method aids debugging. All other methods are there to fulfill the collections.abc.MutableMapping requirements.


问:
how to make animation inactive for some time period in jQuery
here the jsfiddle link to my problem http://jsfiddle.net/XnnvD/35/ (not quite working)

I'll try explaining what the problem is, I have 3 sets of animation in jQuery

1- Image bounces and fades away after  some TimePeriod as below:

```<code>$('#homePageImage').animate(
                    { top: '50px' },
                    { queue: false, duration: 1000, easing: 'easeOutBounce' });
$('#homePageImage').delay(3000).effect('drop', { direction: "right" });
</code>```

2- Set of images .fadeIn() randomly as below:

```<code>randNumArray = shuffle(randNumArray);
for (var i = 0; i < 9; i++)
{ $('#fs' + randNumArray[i]).delay(j += 200).fadeIn(j); }
</code>```

3- Hovering over these images, will enlarge them as below:

```<code>$(function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        });
</code>```

The Problem:
If the user hovers before the 1st set of animation is complete, the images don't .fadeIn() completely, and hence are partially/not visible

What I want:
I want the 3rd set (hovering to enlarge) to remain inactive till my 1st and 2nd set of animations are complete, how can I do this?

Thanks

答:
Put your Hover function in a SetTimeOut function like this

```<code>setTimeout((function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        }), *Put time in miliseconds*);
</code>```

So this will ensure that the hover doesn't happen till the specified time period!

Body:
here the jsfiddle link to my problem http://jsfiddle.net/XnnvD/35/ (not quite working)

I'll try explaining what the problem is, I have 3 sets of animation in jQuery

1- Image bounces and fades away after  some TimePeriod as below:

$('#homePageImage').animate(
                    { top: '50px' },
                    { queue: false, duration: 1000, easing: 'easeOutBounce' });
$('#homePageImage').delay(3000).effect('drop', { direction: "right" });

2- Set of images .fadeIn() randomly as below:

randNumArray = shuffle(randNumArray);
for (var i = 0; i < 9; i++)
{ $('#fs' + randNumArray[i]).delay(j += 200).fadeIn(j); }

3- Hovering over these images, will enlarge them as below:

$(function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        });

The Problem:
If the user hovers before the 1st set of animation is complete, the images don't .fadeIn() completely, and hence are partially/not visible

What I want:
I want the 3rd set (hovering to enlarge) to remain inactive till my 1st and 2nd set of animations are complete, how can I do this?

Thanks

Body:
Put your Hover function in a SetTimeOut function like this

setTimeout((function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        }), *Put time in miliseconds*);

So this will ensure that the hover doesn't happen till the specified time period!


问:
Python code to check repetition in a string
I'm trying to build logic in programming. I need to write a python function that takes string as input and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise. I have searched online and found several examples related to it. I wrote the code and it seemed fine initially but then I realized my mistake and now I'm not getting how should I go about it. Please guide</p>

```<code>def repfree(S):
    for char in S:
        if S.count(char) > 1:
            return True
    return False
</code>```

答:
How about you use a set

def repfree(s):
    char_set = set()
    for c in s:
         char_set.append(c)
     return len(char_set) == len(s)
```

Body:
I'm trying to build logic in programming. I need to write a python function that takes string as input and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise. I have searched online and found several examples related to it. I wrote the code and it seemed fine initially but then I realized my mistake and now I'm not getting how should I go about it. Please guide

def repfree(S):
    for char in S:
        if S.count(char) > 1:
            return True
    return False


问:
What response code to return for insecure POST not acceptable?
If somebody accesses my server via http (i. e. not https) then I redirect GET requests to the https version.

But I don't know what to do with POST and PUT because I cannot redirect them (the browser does a GET on redirect I believe).

I should return an error code.  What HTTP error code should I return?

答:
Technically right answer is to use 403.4 but substatuses it's a IIS only feature and nginx doesn't support it.

So I've prefer to return 418 "I'm a teapot" or 451 "Unavailable For Legal Reasons" (because it's not legal to use plain-text http anymore, haha, just joking :)), this statuses quite exotic and should trigger client to figure out what going on.

nginx has an option to return status with text like

```<code># cat /etc/nginx/conf.d/default.conf
server {
    listen       80 default_server;

    location / {
        add_header Content-Type text/plain;
        return 418 "TLS REQUIRED";
    }
}

# curl -v  http://localhost/
* About to connect() to localhost port 80 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost
> Accept: */*
>
< HTTP/1.1 418
< Server: nginx/1.16.1
< Date: Sat, 15 Feb 2020 07:13:20 GMT
< Content-Type: application/octet-stream
< Content-Length: 12
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
TLS REQUIRED
</code>```

But browsers like Chrome or Firefox can't handle this right, Chrome says ERR_INVALID_RESPONSE and Firefox says "File not found" and this behavior doesn't solve our goal.

So I've stay with just returning status 418.

Body:
Technically right answer is to use 403.4 but substatuses it's a IIS only feature and nginx doesn't support it.

So I've prefer to return 418 "I'm a teapot" or 451 "Unavailable For Legal Reasons" (because it's not legal to use plain-text http anymore, haha, just joking :)), this statuses quite exotic and should trigger client to figure out what going on.

nginx has an option to return status with text like

# cat /etc/nginx/conf.d/default.conf
server {
    listen       80 default_server;

    location / {
        add_header Content-Type text/plain;
        return 418 "TLS REQUIRED";
    }
}

# curl -v  http://localhost/
* About to connect() to localhost port 80 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost
> Accept: */*
>
< HTTP/1.1 418
< Server: nginx/1.16.1
< Date: Sat, 15 Feb 2020 07:13:20 GMT
< Content-Type: application/octet-stream
< Content-Length: 12
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
TLS REQUIRED

But browsers like Chrome or Firefox can't handle this right, Chrome says ERR_INVALID_RESPONSE and Firefox says "File not found" and this behavior doesn't solve our goal.

So I've stay with just returning status 418.


问:
How to set Selenium webdriver.gecko.driver setting in C#
Straight out of the box I can't get selenium grid to work.  I have selenium server 3.4.0 and the following code produces the error shown

Error received

```<code>An unhandled exception of type 'System.InvalidOperationException' occurred in WebDriver.dll

Additional information: The path to the driver executable must be set by the
webdriver.gecko.driver system property; for more information, see
https://github.com/mozilla/geckodriver. The latest version can be downloaded
from https://github.com/mozilla/geckodriver/releases
</code>```

Simple code

```<code>using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Remote;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = new Uri("http://10.6.122.49:5555/wd/hub");

            var options = new FirefoxOptions();
            options.SetPreference("webdriver.gecko.driver", @"D:\geckodriver.exe");

            var driver = new RemoteWebDriver(url, options.ToCapabilities());

            driver.Navigate().GoToUrl("http://www.google.com");
        }
    }
}
</code>```

Update

答:
in C#

 Environment.SetEnvironmentVariable("webdriver.gecko.driver", @"C:\full\path\to\geckodriver.exe");
```

Body:
Straight out of the box I can't get selenium grid to work.  I have selenium server 3.4.0 and the following code produces the error shown

Error received

An unhandled exception of type 'System.InvalidOperationException' occurred in WebDriver.dll

Additional information: The path to the driver executable must be set by the
webdriver.gecko.driver system property; for more information, see
https://github.com/mozilla/geckodriver. The latest version can be downloaded
from https://github.com/mozilla/geckodriver/releases

Simple code

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Remote;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = new Uri("http://10.6.122.49:5555/wd/hub");

            var options = new FirefoxOptions();
            options.SetPreference("webdriver.gecko.driver", @"D:\geckodriver.exe");

            var driver = new RemoteWebDriver(url, options.ToCapabilities());

            driver.Navigate().GoToUrl("http://www.google.com");
        }
    }
}

Update


答:
You can try on the following code.

```<code>def rep_free(text):
    return len(text) != len(set(text))
</code>```

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)

From python doc

Title: Python code to check repetition in a string

Body:
You can try on the following code.

def rep_free(text):
    return len(text) != len(set(text))

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)

From python doc


问:
How to disable selection or grey out the for particular value in List of value items of drop down list (<ng-selectize> or <options> ) in anguarl 7
I have scenario where i need to populate list of values for a dropdown list in angular 7 app. But i should grey out the particular value from that list based on condition or flag.

Eg: I am populating alphabets in UI with drop down list (a to z letters)-> among them i need to disable letter "N" when user try to select that .

Can any one suggest me how we can do in angular 7

答:
```<code><ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                {{item.name}}
            </ng-option>
</code>```

Used this Code

Body:
<ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                {{item.name}}
            </ng-option>

Used this Code


问:
JUnit NoClassDefFoundError with JAR file
I have developed an Android application which I am now creating unit tests for.
I have created a second project (suffixed with ".test" as the projectname) and selected the original project as the target.

My original project includes a few external JAR files.

I cannot access all methods from my tests without referencing these JAR files in my test project's build path as well.
As an example, I get this error:

```<code>The type com.j256.ormlite.android.apptools.OrmLiteBaseService cannot be resolved. It is indirectly referenced from required .class files
</code>```

Tests do work correctly though (when not accessing those methods).

If I include the required JAR files in the test project's build path, I get this error however:

```<code>05-16 15:59:03.732: INFO/TestRunner(1222): java.lang.NoClassDefFoundError: sw6.visualschedule.persistence.DatabaseHelper
05-16 15:59:03.732: INFO/TestRunner(1222):     at sw6.visualschedule.test.ScheduleActivityTest.setUp(ScheduleActivityTest.java:22)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestCase.runBare(TestCase.java:125)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestResult$1.protect(TestResult.java:106)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestResult.runProtected(TestResult.java:124)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestResult.run(TestResult.java:109)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestCase.run(TestCase.java:118)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
</code>```

How can I resolve the NoClassDefFoundError?
I am really confused since it refers to a class inside my project, and it works when the external JAR file isn't included in the build path.

Im using Eclipse on OSX, if that has any influence.

答: Export those libs to test project, but refer them in the test project</p>

Body:
I have developed an Android application which I am now creating unit tests for.
I have created a second project (suffixed with ".test" as the projectname) and selected the original project as the target.

My original project includes a few external JAR files.

I cannot access all methods from my tests without referencing these JAR files in my test project's build path as well.
As an example, I get this error:

The type com.j256.ormlite.android.apptools.OrmLiteBaseService cannot be resolved. It is indirectly referenced from required .class files

Tests do work correctly though (when not accessing those methods).

If I include the required JAR files in the test project's build path, I get this error however:

05-16 15:59:03.732: INFO/TestRunner(1222): java.lang.NoClassDefFoundError: sw6.visualschedule.persistence.DatabaseHelper
05-16 15:59:03.732: INFO/TestRunner(1222):     at sw6.visualschedule.test.ScheduleActivityTest.setUp(ScheduleActivityTest.java:22)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestCase.runBare(TestCase.java:125)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestResult$1.protect(TestResult.java:106)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestResult.runProtected(TestResult.java:124)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestResult.run(TestResult.java:109)
05-16 15:59:03.732: INFO/TestRunner(1222):     at junit.framework.TestCase.run(TestCase.java:118)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
05-16 15:59:03.732: INFO/TestRunner(1222):     at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

How can I resolve the NoClassDefFoundError?
I am really confused since it refers to a class inside my project, and it works when the external JAR file isn't included in the build path.

Im using Eclipse on OSX, if that has any influence.


问:
Pandas: DeprecationWarning: elementwise comparison failed
I'm trying to apply an expanding function to a pandas dataframe by group, but first filtering out all zeroes as well as the last value of each group. The code below does exactly what I need, but is a bit too slow:

```<code>df.update(df.loc[~df.index.isin(df.groupby('group')['value'].tail(1).index)&
            (df['value']!= 0)].iloc[::-1].groupby('group')[
            'value'].expanding().min().reset_index(level=0, drop=True))
</code>```

I found a faster way doing this using below code:

```<code>df.update(df.iloc[::-1].groupby('group')[
            'value'].expanding().min().reset_index(level=0, drop=True),
             filter_func = lambda x: (x!=0)&(x[-1]==False))
</code>```

However, with the dataset I am currently working on, I receive a warning ("C:...\anaconda3\lib\site-packages\ipykernel_launcher.py:22: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.").

Strangely enough, I don't get an error using small dummy datasets such as this:

```<code>data = {'group':['A', 'A', 'A', 'A', 'A', 'B', 'B',
                'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'],
                 'value':[3, 0, 8, 7, 0, -1, 0, 9, -2, 0, 0, 2, 0, 5, 0, 1]}
df = pd.DataFrame(data)
df

  group  value
0   A      3
1   A      0
2   A      8
3   A      7
4   A      0
5   B     -1
6   B      0
7   B      9
8   B     -2
9   B      0
10  B      0
11  C      2
12  C      0
13  C      5
14  C      0
15  C      1
</code>```

Grateful if someone can help me understand why this error is coming up and how to avoid it.

答:
I believe your fist code should be improved by DataFrame.duplicated for better performance, second code not working for me:

```<code>m = df.duplicated('group', keep='last') & (df['value']!= 0)
s = df[m].iloc[::-1].groupby('group')['value'].expanding().min().reset_index(level=0,drop=True)
df.update(s)
#alternative, not sure if faster
#df['value'] = s.reindex(df.index, fill_value=0)
print (df)
   group  value
0      A    3.0
1      A    0.0
2      A    7.0
3      A    7.0
4      A    0.0
5      B   -2.0
6      B    0.0
7      B   -2.0
8      B   -2.0
9      B    0.0
10     B    0.0
11     C    2.0
12     C    0.0
13     C    5.0
14     C    0.0
15     C    1.0
</code>```

Body:
I'm trying to apply an expanding function to a pandas dataframe by group, but first filtering out all zeroes as well as the last value of each group. The code below does exactly what I need, but is a bit too slow:

df.update(df.loc[~df.index.isin(df.groupby('group')['value'].tail(1).index)&
            (df['value']!= 0)].iloc[::-1].groupby('group')[
            'value'].expanding().min().reset_index(level=0, drop=True))

I found a faster way doing this using below code:

df.update(df.iloc[::-1].groupby('group')[
            'value'].expanding().min().reset_index(level=0, drop=True),
             filter_func = lambda x: (x!=0)&(x[-1]==False))

However, with the dataset I am currently working on, I receive a warning ("C:...\anaconda3\lib\site-packages\ipykernel_launcher.py:22: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.").

Strangely enough, I don't get an error using small dummy datasets such as this:

data = {'group':['A', 'A', 'A', 'A', 'A', 'B', 'B',
                'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'],
                 'value':[3, 0, 8, 7, 0, -1, 0, 9, -2, 0, 0, 2, 0, 5, 0, 1]}
df = pd.DataFrame(data)
df

  group  value
0   A      3
1   A      0
2   A      8
3   A      7
4   A      0
5   B     -1
6   B      0
7   B      9
8   B     -2
9   B      0
10  B      0
11  C      2
12  C      0
13  C      5
14  C      0
15  C      1

Grateful if someone can help me understand why this error is coming up and how to avoid it.

Body:
I believe your fist code should be improved by DataFrame.duplicated for better performance, second code not working for me:

m = df.duplicated('group', keep='last') & (df['value']!= 0)
s = df[m].iloc[::-1].groupby('group')['value'].expanding().min().reset_index(level=0,drop=True)
df.update(s)
#alternative, not sure if faster
#df['value'] = s.reindex(df.index, fill_value=0)
print (df)
   group  value
0      A    3.0
1      A    0.0
2      A    7.0
3      A    7.0
4      A    0.0
5      B   -2.0
6      B    0.0
7      B   -2.0
8      B   -2.0
9      B    0.0
10     B    0.0
11     C    2.0
12     C    0.0
13     C    5.0
14     C    0.0
15     C    1.0


问:
LU decomposition python with vector pivot
The LU decomposition function provided by scipy returns a permutation matrix P

```<code>P,L,U = scipy.linalg.lu(A)
</code>```

Where A is a rectangular matrix. However the size of my problem do not allow to store P (even temporary) due to its size, I really need a function that computes a permutation vector (like [L,U,P] = lu(A,'vector') in Matlab). I found a lapack function

```<code>LU,p,info = scipy.linalg.lapack.dgetrf(A)
</code>```

which seems to return a vector p but I learned this latter is not an actual permutation vector since it contains twice the same value (https://software.intel.com/en-us/forums/intel-math-kernel-library/topic/780655). I am thus looking for another function (which may be from another library) to perform this LU decomposition with pivoting. Since the computation time is also very important, I don't think implementing the decomposition myself will be efficient.

答: Yes, it's a pivot vector, which is a standard LAPACK return. So you'll need to convert it into whatever other form you want yourself (and this is much easier then reimplementing the factorization).</p>

Body:
The LU decomposition function provided by scipy returns a permutation matrix P

P,L,U = scipy.linalg.lu(A)

Where A is a rectangular matrix. However the size of my problem do not allow to store P (even temporary) due to its size, I really need a function that computes a permutation vector (like [L,U,P] = lu(A,'vector') in Matlab). I found a lapack function

LU,p,info = scipy.linalg.lapack.dgetrf(A)

which seems to return a vector p but I learned this latter is not an actual permutation vector since it contains twice the same value (https://software.intel.com/en-us/forums/intel-math-kernel-library/topic/780655). I am thus looking for another function (which may be from another library) to perform this LU decomposition with pivoting. Since the computation time is also very important, I don't think implementing the decomposition myself will be efficient.


问:
Trying to use multiple images in opencv imread function but not getting

import pprint as pp

original_img = cv2.imread("/content/drive/My Drive/images/image1.jpg") #here i want to use multiple images atleast 250 images.

original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
```

答:
I guess all your images are in the folder images. So you can use os to gett all their filenames.

```<code>import os
pth = "/content/drive/My Drive/images" # make sure it is correct
images = os.listdir(pth)
for image in images:
    image_path = os.path.join(pth, image)
    original_img = cv2.imread(image_path)
    original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
    results = tfnet2.return_predict(original_img)
    print(results)
</code>```

Body:
I guess all your images are in the folder images. So you can use os to gett all their filenames.

import os
pth = "/content/drive/My Drive/images" # make sure it is correct
images = os.listdir(pth)
for image in images:
    image_path = os.path.join(pth, image)
    original_img = cv2.imread(image_path)
    original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
    results = tfnet2.return_predict(original_img)
    print(results)


问:
loop in python for two text files
this is my first time here and i wish i get your help.
i'm new to python and i need your help

i have two .txt files
here an Example
file1.txt

```<code>customer1.com
customer2.com
customer3.com
customer4.com
customer5.com
customer6.com
customer7.com
customer8.com
customer9.com
</code>```

file2.txt

```<code>service1
service2
service3
</code>```

i want to loop the file2.txt on the file1.txt =>
like the following example

```<code>customer1.com/service1
customer1.com/service2
customer1.com/service3

customer2.com/service1
customer2.com/service2
customer2.com/service3

customer3.com/service1
customer3.com/service2
customer3.com/service3
</code>```

AND GOES ON  TILL  file1.txt is done.

also i need to make IF statment
for example let's say the customer number3 has the service number 2 (file found i mean)

customer3.com/service2 [service found]

i need the loop for customer3 to stop looking for services and save the output (customer3.com/service2) in a new file called file3.txt
and the loop go on with other customers and every customer has the service found, the output save in file3.txt

i hope you understand what i mean.
thanks.

答:
you could use itertools.product to get a cartesian product of the lines from each file to get every URL combination:

```<code>from itertools import product

with open("file1.txt") as f1, open("file2.txt") as f2, open(
    "file3.txt", mode="w"
) as out:
    for x, y in product(f1, f2):
        out.write("%s/%s\n" % (x.strip(), y.strip()))
</code>```

file3.txt

```<code>customer1.com/service1
customer1.com/service2
customer1.com/service3
customer2.com/service1
customer2.com/service2
customer2.com/service3
customer3.com/service1
customer3.com/service2
...
</code>```

Title: loop in python for two text files

Body:
this is my first time here and i wish i get your help.
i'm new to python and i need your help

i have two .txt files
here an Example
file1.txt

customer1.com
customer2.com
customer3.com
customer4.com
customer5.com
customer6.com
customer7.com
customer8.com
customer9.com

file2.txt

service1
service2
service3

i want to loop the file2.txt on the file1.txt =>
like the following example

customer1.com/service1
customer1.com/service2
customer1.com/service3

customer2.com/service1
customer2.com/service2
customer2.com/service3

customer3.com/service1
customer3.com/service2
customer3.com/service3

AND GOES ON  TILL  file1.txt is done.

also i need to make IF statment
for example let's say the customer number3 has the service number 2 (file found i mean)

customer3.com/service2 [service found]

i need the loop for customer3 to stop looking for services and save the output (customer3.com/service2) in a new file called file3.txt
and the loop go on with other customers and every customer has the service found, the output save in file3.txt

i hope you understand what i mean.
thanks.

Body:
you could use itertools.product to get a cartesian product of the lines from each file to get every URL combination:

from itertools import product

with open("file1.txt") as f1, open("file2.txt") as f2, open(
    "file3.txt", mode="w"
) as out:
    for x, y in product(f1, f2):
        out.write("%s/%s\n" % (x.strip(), y.strip()))

file3.txt

customer1.com/service1
customer1.com/service2
customer1.com/service3
customer2.com/service1
customer2.com/service2
customer2.com/service3
customer3.com/service1
customer3.com/service2
...


问:
php, how to run a link when check box checked?
```<code><input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';
</code>```

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

```<code>if ($('#checket:checked').val() !== undefined) {
</code>```

// Insert code here.
}

答:
you can only do it on the client side</p>

```<code><input type="checkbox" name="checket" id="checket" onclick="location.href='test.com'"/>
</code>```

Body:
<input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

if ($('#checket:checked').val() !== undefined) {

// Insert code here.
}

Body:
you can only do it on the client side

<input type="checkbox" name="checket" id="checket" onclick="location.href='test.com'"/>


答:
Try this to read line by line and use the accordingly.</p>

```<code>file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')
lines1 = file1.readlines()
lines2 = file2.readlines()
for line_from_1 in lines1:
    for line_from_2 in lines2:
        print(line_from_1 + '/' + line_from_2)
</code>```

Title: loop in python for two text files

Body:
Try this to read line by line and use the accordingly.

file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')
lines1 = file1.readlines()
lines2 = file2.readlines()
for line_from_1 in lines1:
    for line_from_2 in lines2:
        print(line_from_1 + '/' + line_from_2)