问:
Sorting Coordinate System
I am inputting a x and y in two separate arraylist and putting them together like a (x,y) coordinate system into a different arraylist. And then trying to sort out that new arraylist into least to greatest using Collections.sort(arraylist); However the moment that I put double digits such as(10,11) it recognizes that smaller than (6, 7)

```<code>for(int x = 0; x <=5; x ++) {
    System.out.print("Enter X coordinate: ");
    int playerturnColumn = playerinput.nextInt();
    System.out.print("Enter Y Coordinate: ");
    int playerturnRow  = playerinput.nextInt();
    playerturnCoordinate.add(playerturnColumn + "," + playerturnRow);
}
    Collections.sort(playerturnCoordinate);
    System.out.println(playerturnCoordinate);
</code>```

Your Turn
Enter X coordinate: 10
Enter Y Coordinate: 11
Enter X coordinate: 2
Enter Y Coordinate: 1
Enter X coordinate: 3
Enter Y Coordinate: 5
Enter X coordinate: 2
Enter Y Coordinate: 8
Enter X coordinate: 0
Enter Y Coordinate: 1
Enter X coordinate: 9
Enter Y Coordinate: 7
[0,1, 10,11, 2,1, 2,8, 3,5, 9,7]

答:
You could create a Coordinate class that implements Comparable:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

class Coordinate implements Comparable<Coordinate> {
  private final int x;
  private final int y;

  public Coordinate(int x, int y) {
    this.x = x;
    this.y = y;
  }

  public int getX() {
    return this.x;
  }

  public int getY() {
    return this.y;
  }

  public String toString() {
    return String.format("[%d, %d]", getX(), getY());
  }

  public double distanceFromOrigin(Coordinate c) {
    return Math.sqrt(Math.pow(c.getX(), 2) + Math.pow(c.getY(), 2));
  }

  public int compareTo(Coordinate other) {
    return Double.compare(distanceFromOrigin(this), distanceFromOrigin(other));
  }
}

class Test {
  public static void main(String[] args) {
    List<Coordinate> playerTurnCoordinates = new ArrayList<>();
    playerTurnCoordinates.add(new Coordinate(10, 11));
    playerTurnCoordinates.add(new Coordinate(2, 1));
    playerTurnCoordinates.add(new Coordinate(3, 5));
    playerTurnCoordinates.add(new Coordinate(2, 8));
    playerTurnCoordinates.add(new Coordinate(0, 1));
    playerTurnCoordinates.add(new Coordinate(9, 7));
    playerTurnCoordinates.add(new Coordinate(6, 7));
    System.out.println("Before sorting: " + playerTurnCoordinates);
    Collections.sort(playerTurnCoordinates);
    System.out.println("After sorting: " + playerTurnCoordinates);
  }
}
</code>```

Output:

```<code>Before sorting: [[10, 11], [2, 1], [3, 5], [2, 8], [0, 1], [9, 7], [6, 7]]
After sorting: [[0, 1], [2, 1], [3, 5], [2, 8], [6, 7], [9, 7], [10, 11]]
</code>```

Title: Sorting Coordinate System

Body:
I am inputting a x and y in two separate arraylist and putting them together like a (x,y) coordinate system into a different arraylist. And then trying to sort out that new arraylist into least to greatest using Collections.sort(arraylist); However the moment that I put double digits such as(10,11) it recognizes that smaller than (6, 7)

for(int x = 0; x <=5; x ++) {
    System.out.print("Enter X coordinate: ");
    int playerturnColumn = playerinput.nextInt();
    System.out.print("Enter Y Coordinate: ");
    int playerturnRow  = playerinput.nextInt();
    playerturnCoordinate.add(playerturnColumn + "," + playerturnRow);
}
    Collections.sort(playerturnCoordinate);
    System.out.println(playerturnCoordinate);

Your Turn
Enter X coordinate: 10
Enter Y Coordinate: 11
Enter X coordinate: 2
Enter Y Coordinate: 1
Enter X coordinate: 3
Enter Y Coordinate: 5
Enter X coordinate: 2
Enter Y Coordinate: 8
Enter X coordinate: 0
Enter Y Coordinate: 1
Enter X coordinate: 9
Enter Y Coordinate: 7
[0,1, 10,11, 2,1, 2,8, 3,5, 9,7]

Body:
You could create a Coordinate class that implements Comparable:

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

class Coordinate implements Comparable<Coordinate> {
  private final int x;
  private final int y;

  public Coordinate(int x, int y) {
    this.x = x;
    this.y = y;
  }

  public int getX() {
    return this.x;
  }

  public int getY() {
    return this.y;
  }

  public String toString() {
    return String.format("[%d, %d]", getX(), getY());
  }

  public double distanceFromOrigin(Coordinate c) {
    return Math.sqrt(Math.pow(c.getX(), 2) + Math.pow(c.getY(), 2));
  }

  public int compareTo(Coordinate other) {
    return Double.compare(distanceFromOrigin(this), distanceFromOrigin(other));
  }
}

class Test {
  public static void main(String[] args) {
    List<Coordinate> playerTurnCoordinates = new ArrayList<>();
    playerTurnCoordinates.add(new Coordinate(10, 11));
    playerTurnCoordinates.add(new Coordinate(2, 1));
    playerTurnCoordinates.add(new Coordinate(3, 5));
    playerTurnCoordinates.add(new Coordinate(2, 8));
    playerTurnCoordinates.add(new Coordinate(0, 1));
    playerTurnCoordinates.add(new Coordinate(9, 7));
    playerTurnCoordinates.add(new Coordinate(6, 7));
    System.out.println("Before sorting: " + playerTurnCoordinates);
    Collections.sort(playerTurnCoordinates);
    System.out.println("After sorting: " + playerTurnCoordinates);
  }
}

Output:

Before sorting: [[10, 11], [2, 1], [3, 5], [2, 8], [0, 1], [9, 7], [6, 7]]
After sorting: [[0, 1], [2, 1], [3, 5], [2, 8], [6, 7], [9, 7], [10, 11]]


来源: stackexchange

问:
How to sort map without using comparable and Comparator Interface? How to write Custom Sorting?
Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.

I have created class Studnt

```<code>public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter
}
</code>```

Main class

```<code>public class StudentData {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enetr the number of Student");
        int totalStudent = sc.nextInt();
        Map<Integer,Student> map = new TreeMap<Integer,Student>();
        for(int i =0;i<totalStudent;i++) {
            Student ss = new Student();
            System.out.println("Enter the Student roll number");
            ss.setRollNumber(sc.nextInt());
            System.out.println("Enter the Student Name");
            ss.setName(sc.next());
            System.out.println("Enter the m1 marks ");
            ss.setM1(sc.nextInt());
            System.out.println("Enetr the m2 marks ");
            ss.setM2(sc.nextInt());
            System.out.println("Enter the m3 marks ");
            ss.setM3(sc.nextInt());
            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

            map.put(ss.getTotMarks(),ss);
            ss=null;
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<Integer,Student> m :map.entrySet()) {
            System.out.println(m);
        }

    }
}
</code>```

Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate

output

6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]

9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]

the only unique totMarks stored in the map

答:
Instead of storing the values as student store them as a map of (name, student), so that when a student with the same marks is encountered, it is added to the map. </p>

```<code>public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enetr the number of Student");
    int totalStudent = sc.nextInt();
    Map<Integer, Map<String, Student>> map = new TreeMap<>();
    for(int i =0;i<totalStudent;i++) {
        Student ss = new Student();
        System.out.println("Enter the Student roll number");
        ss.setRollNumber(sc.nextInt());
        System.out.println("Enter the Student Name");
        ss.setName(sc.next());
        System.out.println("Enter the m1 marks ");
        ss.setM1(sc.nextInt());
        System.out.println("Enetr the m2 marks ");
        ss.setM2(sc.nextInt());
        System.out.println("Enter the m3 marks ");
        ss.setM3(sc.nextInt());
        ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

        Integer key = ss.getTotMarks();
        if (map.get(key) == null){  // if this is a new key in the map, then create a new TreeMap and put it
            final TreeMap<String, Student> nameAndStudentMap = new TreeMap<>();
            nameAndStudentMap.put(ss.getName(), ss);
            map.put(key, nameAndStudentMap);
        }else { // if the key already existed, then get the map stored and add to it.
            map.get(key).put(ss.getName(), ss);
        }

    }
    //stdList.forEach(System.out::print);
    for(Map.Entry<Integer,Map<String, Student>> m :map.entrySet()) {
        for (Map.Entry<String, Student> nameAndStudent : m.getValue().entrySet()) {
            System.out.println(m.getKey() + " = " + nameAndStudent.getValue());
        }
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.

I have created class Studnt

public class Student {
    private String name;
    private Integer rollNumber;
    private int m1;
    private int m2;
    private int m3;
    private int totMarks;
    //Getter setter
}

Main class

public class StudentData {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enetr the number of Student");
        int totalStudent = sc.nextInt();
        Map<Integer,Student> map = new TreeMap<Integer,Student>();
        for(int i =0;i<totalStudent;i++) {
            Student ss = new Student();
            System.out.println("Enter the Student roll number");
            ss.setRollNumber(sc.nextInt());
            System.out.println("Enter the Student Name");
            ss.setName(sc.next());
            System.out.println("Enter the m1 marks ");
            ss.setM1(sc.nextInt());
            System.out.println("Enetr the m2 marks ");
            ss.setM2(sc.nextInt());
            System.out.println("Enter the m3 marks ");
            ss.setM3(sc.nextInt());
            ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

            map.put(ss.getTotMarks(),ss);
            ss=null;
        }
        //stdList.forEach(System.out::print);
        for(Map.Entry<Integer,Student> m :map.entrySet()) {
            System.out.println(m);
        }

    }
}

Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate

output

6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]

9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]

the only unique totMarks stored in the map

Body:
Instead of storing the values as student store them as a map of (name, student), so that when a student with the same marks is encountered, it is added to the map.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enetr the number of Student");
    int totalStudent = sc.nextInt();
    Map<Integer, Map<String, Student>> map = new TreeMap<>();
    for(int i =0;i<totalStudent;i++) {
        Student ss = new Student();
        System.out.println("Enter the Student roll number");
        ss.setRollNumber(sc.nextInt());
        System.out.println("Enter the Student Name");
        ss.setName(sc.next());
        System.out.println("Enter the m1 marks ");
        ss.setM1(sc.nextInt());
        System.out.println("Enetr the m2 marks ");
        ss.setM2(sc.nextInt());
        System.out.println("Enter the m3 marks ");
        ss.setM3(sc.nextInt());
        ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());

        Integer key = ss.getTotMarks();
        if (map.get(key) == null){  // if this is a new key in the map, then create a new TreeMap and put it
            final TreeMap<String, Student> nameAndStudentMap = new TreeMap<>();
            nameAndStudentMap.put(ss.getName(), ss);
            map.put(key, nameAndStudentMap);
        }else { // if the key already existed, then get the map stored and add to it.
            map.get(key).put(ss.getName(), ss);
        }

    }
    //stdList.forEach(System.out::print);
    for(Map.Entry<Integer,Map<String, Student>> m :map.entrySet()) {
        for (Map.Entry<String, Student> nameAndStudent : m.getValue().entrySet()) {
            System.out.println(m.getKey() + " = " + nameAndStudent.getValue());
        }
    }

}


问:
binding to input blob imperatively
How do we imperatively bind to an input blob?

I'd like to be able to read blobs inside of my azure function. One way to do this is to add a parameter like this one:

```<code>[Blob("%MyInputBlob%/{FileName}", FileAccess.Read)]  Stream input
</code>```

However, this won't work for me because I will need to read multiple blobs, and they have different {filenames}.

I understand there's an imperative binding solution to write to an output like so:

```<code>        var attributes = new Attribute[]
        {
                new BlobAttribute(path),
                new StorageAccountAttribute(connection)
        };
        using (var writer = await binder.BindAsync<TextWriter>(attributes))
        {
            writer.Write(payload);
        }
</code>```

Is there a similar binding capability for INPUT blobs?

答:
For dynamic input binding, you could just change the binding type as follows:

```<code>var blobString = await binder.BindAsync<string>(attributes);
</code>```

Here is a similar issue you could refer to.

Title: binding to input blob imperatively

Body:
How do we imperatively bind to an input blob?

I'd like to be able to read blobs inside of my azure function. One way to do this is to add a parameter like this one:

[Blob("%MyInputBlob%/{FileName}", FileAccess.Read)]  Stream input

However, this won't work for me because I will need to read multiple blobs, and they have different {filenames}.

I understand there's an imperative binding solution to write to an output like so:

        var attributes = new Attribute[]
        {
                new BlobAttribute(path),
                new StorageAccountAttribute(connection)
        };
        using (var writer = await binder.BindAsync<TextWriter>(attributes))
        {
            writer.Write(payload);
        }

Is there a similar binding capability for INPUT blobs?

Body:
For dynamic input binding, you could just change the binding type as follows:

var blobString = await binder.BindAsync<string>(attributes);

Here is a similar issue you could refer to.


问:
"Invalid input syntax for integer " error on Express response.redirect
I'm getting the below error when I've run a PUT query into Postgres via Express.

error: invalid input syntax for integer: "all-calls"

It appears to be referring to this snippet of code in the router.put function
response.redirect('all-calls'). The data is updating in the database fine.

This is the first POST request I've created. All other redirects have been POST and the response.redirect('all-calls') has worked perfectly fine on them.

Problematic PUT route:

```<code>router.put('/update-call-simple/:id', (request, response, next) => {
  console.log(request.body)
  const { id } = request.params;
  const { organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor } = request.body;
  pool.query('UPDATE calls SET id_organisation=($1), caller_name=($2), call_contents=($3), support_agent=($4), priority=($5), category=($6), id_vendor=($7) WHERE calls_id=($8)',
    [organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor, id],
    (err, res) => {
      if (err) return next(err);
      response.redirect('all-calls');
    })
})
</code>```

Example of PUT route that works perfectly fine:

```<code>router.post('/new-call-simple', (request, response, next) => {
  const { organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor } = request.body;
  pool.query('INSERT INTO calls (id_organisation, caller_name, call_contents, support_agent, priority, category, id_vendor, date_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)',
    [organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor, Date.now()],
    (err, res) => {
      if (err) return next(err);
      response.redirect('all-calls');
    }
  )
})
</code>```

答:
You're using relative path and express is unable to resolve all-calls path relative to /update-call-simple/:id. Unless you've a route /update-call-simple/:id/all-calls the redirect is not going to work. And express is probably assuming this is a status-code input.

Use the / to make your path relative to root.

For example in you've a route:

```<code>router.put('/path/to/somewhere' ...
</code>```

And redirecting to this page in your code elsewhere:

```<code>...
res.redirect('/path/to/somewhere')
</code>```

Body:
I'm getting the below error when I've run a PUT query into Postgres via Express.

error: invalid input syntax for integer: "all-calls"

It appears to be referring to this snippet of code in the router.put function
response.redirect('all-calls'). The data is updating in the database fine.

This is the first POST request I've created. All other redirects have been POST and the response.redirect('all-calls') has worked perfectly fine on them.

Problematic PUT route:

router.put('/update-call-simple/:id', (request, response, next) => {
  console.log(request.body)
  const { id } = request.params;
  const { organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor } = request.body;
  pool.query('UPDATE calls SET id_organisation=($1), caller_name=($2), call_contents=($3), support_agent=($4), priority=($5), category=($6), id_vendor=($7) WHERE calls_id=($8)',
    [organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor, id],
    (err, res) => {
      if (err) return next(err);
      response.redirect('all-calls');
    })
})

Example of PUT route that works perfectly fine:

router.post('/new-call-simple', (request, response, next) => {
  const { organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor } = request.body;
  pool.query('INSERT INTO calls (id_organisation, caller_name, call_contents, support_agent, priority, category, id_vendor, date_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)',
    [organisation_id, caller_name, call_contents, support_agent, priority, category, id_vendor, Date.now()],
    (err, res) => {
      if (err) return next(err);
      response.redirect('all-calls');
    }
  )
})

Body:
You're using relative path and express is unable to resolve all-calls path relative to /update-call-simple/:id. Unless you've a route /update-call-simple/:id/all-calls the redirect is not going to work. And express is probably assuming this is a status-code input.

Use the / to make your path relative to root.

For example in you've a route:

router.put('/path/to/somewhere' ...

And redirecting to this page in your code elsewhere:

...
res.redirect('/path/to/somewhere')


问:
XNA C# Problem reading directory content
I've started developing of card game  with XNA but I had problems reading all the cards inside the Cards directory which is inside a Content.

I've tried following code:

```<code>string[] nomeCartas = Directory.GetFiles(@"Cards");
</code>```

But with that I retrieved an error saying it could not be possible to find part of the path:

Não foi possível encontrar uma parte
  do caminho
  'C:\Users\Serafim\Documents\Visual
  Studio
  2010\Projects\JogoSuecaOnline\JogoSuecaOnline\JogoSuecaOnline\bin\x86\Debug\Cards\'.

I checked that path and it's wrong, the correct path should be:

C:\Users\Serafim\Documents\Visual
  Studio
  2010\Projects\JogoSuecaOnline\JogoSuecaOnline\JogoSuecaOnline\bin\x86\Debug\Content\Cards\

Is there any other way to read the Directory Content with XNA or how can I fix this?

答:
```<code>string[] nomeCartas = Directory.GetFiles(
        Path.Combine(Content.RootDirectory, @"Cards"), @"*.xnb");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've started developing of card game  with XNA but I had problems reading all the cards inside the Cards directory which is inside a Content.

I've tried following code:

string[] nomeCartas = Directory.GetFiles(@"Cards");

But with that I retrieved an error saying it could not be possible to find part of the path:

Não foi possível encontrar uma parte
  do caminho
  'C:\Users\Serafim\Documents\Visual
  Studio
  2010\Projects\JogoSuecaOnline\JogoSuecaOnline\JogoSuecaOnline\bin\x86\Debug\Cards\'.

I checked that path and it's wrong, the correct path should be:

C:\Users\Serafim\Documents\Visual
  Studio
  2010\Projects\JogoSuecaOnline\JogoSuecaOnline\JogoSuecaOnline\bin\x86\Debug\Content\Cards\

Is there any other way to read the Directory Content with XNA or how can I fix this?


问:
RegEx for removing whitespace in a string
Trying to make a very simple HTML minifier that only removes white space between tags?

I think the best way is with a JavaScript Regular Expression? but can never work out how to do them correctly.

```<code><p>leave white spaces</p> <p>leave white spaces</p>
</code>```

After  minify:

```<code> <p>leave white space</p><p>leave white space</p>
</code>```

trying to target the space bewtween > here <

答:
If here we wish to or have to use regular expressions, we can add a non-capturing group (?:\s+) in between the open and close tags and replace it with an empty string using an expression such as:

```<code><\/[a-z]+>(?:\s+)<[a-z]+>
</code>```

We can add additional boundaries to this expression, however if our inputs would be just similar to the one exampled in the question, this would suffice.

For instance, for h1 tags, we would be expanding our char list:

```<code><\/[a-z0-9]+>(?:\s+)<[a-z0-9]+>
</code>```

For, uppercase instances, if any, we would be adding an i flag.

TEST

const regex = /<\/[a-z]+>(?:\s+)<[a-z]+>/gm;
const str = `
leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

leave white spaces

`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
Trying to make a very simple HTML minifier that only removes white space between tags?

I think the best way is with a JavaScript Regular Expression? but can never work out how to do them correctly.

leave white spaces

leave white spaces

After  minify:

leave white space

leave white space

trying to target the space bewtween > here <

Body:
If here we wish to or have to use regular expressions, we can add a non-capturing group (?:\s+) in between the open and close tags and replace it with an empty string using an expression such as:

<\/[a-z]+>(?:\s+)<[a-z]+>

We can add additional boundaries to this expression, however if our inputs would be just similar to the one exampled in the question, this would suffice.

For instance, for h1 tags, we would be expanding our char list:

<\/[a-z0-9]+>(?:\s+)<[a-z0-9]+>

For, uppercase instances, if any, we would be adding an i flag.

TEST

const regex = /<\/[a-z]+>(?:\s+)<[a-z]+>/gm;
const str = `<p>leave white spaces</p>   <p>leave white spaces</p>    <p>leave white spaces</p>   <p>leave white spaces</p><p>leave white spaces</p>   <p>leave white spaces</p>    <p>leave white spaces</p>   <p>leave white spaces</p>
<p>leave white spaces</p>   <p>leave white spaces</p>    <p>leave white spaces</p>   <p>leave white spaces</p><p>leave white spaces</p>   <p>leave white spaces</p>    <p>leave white spaces</p>   <p>leave white spaces</p>
<p>leave white spaces</p>   <p>leave white spaces</p>    <p>leave white spaces</p>   <p>leave white spaces</p><p>leave white spaces</p>   <p>leave white spaces</p>    <p>leave white spaces</p>   <p>leave white spaces</p>

`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
ImportError: Couldn't import Django
I've already configured virtualenv in pycharm, when using the python manage.py command, this is error shown:

```<code>E:\video course\Python\code\web_worker\MxOnline>python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
</code>```

How should I fix it, I've installed django.

答:
Instead of creating a new virtual environment, you just have to access to your initially created virtual environment when you started the project.

You just have to do the following in your command line:

1)pipenv shell to access the backend virtual environment that you have initially created.

2) Then, python manage.py runserver

Let me know if it works for you or not.

Title: ImportError: Couldn't import Django

Body:
I've already configured virtualenv in pycharm, when using the python manage.py command, this is error shown:

E:\video course\Python\code\web_worker\MxOnline>python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

How should I fix it, I've installed django.


问:
How to end game in hangman if ALL letters in the secret word are in guessed_letters list
Im trying to create a for loop end game by doing for "every letter in my secret word if All letters are in gussed_letters then end game."

Ive tried to make a correct_letters list and see if all the letters in my secret word are in my correct_letters list then end the game but i cant seem to get it to work.

```<code>import random

words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
  return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function

#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []

def dashshow(guess_letters): #takes in guess_letters
  for letter in chosenword: #checks each letter in chosenword
    if letter in guess_letters: #if letter in guess_letters print that letter
      print(letter)
    else: #or else print a dash
      print('-')

def playgame(tries):# Takes tries
  while  tries != 0: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    dashshow(guess_letters) # last call the dashshow function

randomword(words)
playgame(tries)
</code>```

答:
you can create variable is list letters of secret word, remove letter if it similars guess

Try this

def playgame(tries):# Takes tries
  chosenword_ = list(chosenword)
  while  tries != 0 and chosenword_: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
      try:
        chosenword_.remove(guess)
      except ValueError:
        pass
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    dashshow(guess_letters) # last call the dashshow function
```

Body:
Im trying to create a for loop end game by doing for "every letter in my secret word if All letters are in gussed_letters then end game."

Ive tried to make a correct_letters list and see if all the letters in my secret word are in my correct_letters list then end the game but i cant seem to get it to work.

import random

words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
  return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function

#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []

def dashshow(guess_letters): #takes in guess_letters
  for letter in chosenword: #checks each letter in chosenword
    if letter in guess_letters: #if letter in guess_letters print that letter
      print(letter)
    else: #or else print a dash
      print('-')

def playgame(tries):# Takes tries
  while  tries != 0: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    dashshow(guess_letters) # last call the dashshow function

randomword(words)
playgame(tries)


问:
SQL Server Select Query Is Slow
I have approx 820,000 records in my SQL Server table and it is taking 5 seconds to select the data from the table. The table has one clustered index on a  time column that could be NULL (as of now it does not contain any NULL value). Why is it taking 5 to 6 seconds to fetch only this much records? </p>

答:
I recomend you this:</p>

```<code>1.Check if you are using Clustered and Non-Clustered in you columns (best way I think with a sp_help NameTable).
2.When you using comand "select" specific always all name columns (never use Select * From ..... ).
3.If you are using SSMS check in tools SQL Execution Plan , with this tool you can make simple review your TSQL (you can see cost
each query you make.
4.Dont use "convert(...." in clause WHERE , for example .. Where Convert(int,NameColum)=100.
</code>```

Title: SQL Server Select Query Is Slow

Body:
I recomend you this:

1.Check if you are using Clustered and Non-Clustered in you columns (best way I think with a sp_help NameTable).
2.When you using comand "select" specific always all name columns (never use Select * From ..... ).
3.If you are using SSMS check in tools SQL Execution Plan , with this tool you can make simple review your TSQL (you can see cost
each query you make.
4.Dont use "convert(...." in clause WHERE , for example .. Where Convert(int,NameColum)=100.


问:
validates vs db check up in rails 3.1 for field presence
In rails 3.1, we can validate presence of a field in model with:

```<code>validates :name, :presence => true
</code>```

In db migration file, we also can do

```<code>t.string :name, :null => false
</code>```

It seems that validates checks the data integrity before saving which is better. However db check up only happens during the saving process which may have started actual saving before aborting. Is validates in model better? Thanks so much.

答:
This is an old question but I stumbled across it today and I think the answer is the same whether you are using Rails 3.1 or Rails 6: it depends.

Both database constraints and model validations exist for a reason. In addition to those two, I think it's also worth considering where client-side checks fit in.

My short answer is:

always write model validations

in most cases back them up with database constraints

sometimes add on client-side checks

As with most things, stick with these simple rules while you're learning and you won't go far wrong. Later on you can start to break these rules, once you know why you're breaking them.

I wrote up my longer ("it depends") answer (and my reasons for the rules above) in a post on my blog.

Body:
In rails 3.1, we can validate presence of a field in model with:

validates :name, :presence => true

In db migration file, we also can do

t.string :name, :null => false

It seems that validates checks the data integrity before saving which is better. However db check up only happens during the saving process which may have started actual saving before aborting. Is validates in model better? Thanks so much.


问:
Can I put the _satellite.pageBottom(); on a JS file?
Normally, you will put the _satellite.pageBottom() method as much as you can on lowest part of the html, just like:

```<code>...
<script type="text/javascript">_satellite.pageBottom();</script>
</body>
</html>
</code>```

But I am getting errors in the browser that either is blocked in loading because of too much bandwidth or the browser just prevent it from loading or delay it from loading resulting to a _satellite undefined error

So what I did is to put it in a JS file and add defer="defer" attribute

```<code>...
<script src="/js/satellite.js?t=153664965811" defer="defer"></script>
</body>
</html>
</code>```

So this worked fine now, as long as the browser do not block a tracking JS API.

So is this fine to do?

答:
Summary

Officially, you should not do this sort of thing.

Details

The documentation states the following:

Important: For a successful implementation, it is critical that you
  follow these instructions as they appear in Adobe Help. Specifically,
  you must place the header code in the  section of your document
  templates. Also, you must place the footer code just before the
  closing  tag. Placing either of these embed codes elsewhere in
  your markup, or using asynchronous methods to append the embed codes,
  or wrapping the embed codes in any way, are not a supported
  implementations of dynamic tag management. The embed codes must be
  implemented exactly as provided.

An unsupported implementation will yield unexpected results and
  prevent Customer Care and Engineering from assisting with your
  implementation.

So, before I say anything else, the official answer is no, you should not do this sort of thing. Losing support from Adobe is generally a bad idea, even if the implementation is not the current best practice.

Unofficially..

Okay firstly, you mentioned getting error(s) when you attempted to do this sort of thing. Firstly, I'm a little unclear about the errors you mentioned. In particular, the _satellite undefined error. To me, this sounds like you attempted to load the Header script async and/or deferred, and the DTM library was not loaded in time before the Footer snippet (the _satellite.pageBottom()) was called. But you did not mention this in your question; you only mentioned issues with the Footer snippet.

Again, officially, you cannot do this sort of thing to either of the snippets. But even if you decide to deviate from the documentation, you definitely need to ensure the Header snippet is loaded before the Footer, or else you will get "_satellite is undefined" type errors, because the Header script is where _satellite is defined. So if you want to dabble in making both async and/or deferred, you should look into promise chains, or wrapping the Footer script in some logic that looks for _satellite and if not found, setTimeout to try again for a number of times. Or..

On DOM ready, if _satellite.pageBottom() has not yet executed, DTM will internally call it on its own. So, you technically don't even need to include the Footer script on your site if you're going for a full async/deferred implementation.

On that note.. going for a fully async/deferred DTM implementation means that you have to ensure everything you deploy via DTM is also async. I have no idea what all you have deployed through DTM, but in practice, at a minimum, you almost certainly have the Experience Cloud ID Service (ECIDS) and Adobe Analytics (AA) deployed via DTM, and DTM does not currently support deploying those in an async manner (ECIDS needs to be loaded before AA).  And that's just one tag/tool example.

So at a minimum, you should probably at least respect the documentation for the Header tag. The Footer tag is a lot more forgiving / doable for pretty much anything else, though, if you ensure that you only deploy things on DOM ready / async. But again, officially, you should follow the documentation for both, and that is my official answer.

An alternative...

You should consider migrating from Adobe DTM to Adobe Launch. Launch is Adobe's latest tag management solution. DTM is being phased out. Launch can be deployed with a Header and Footer tag the same as DTM, where timing can be enforced, but unlike DTM, Launch also has official asynchronous deployment option. The Header tag can be loaded async, and there is no Footer tag (for the async deployment). Launch does some magic tricks to ensure order of operations for the Adobe tools (e.g. the ECIDS vs. AA mentioned above). There is also promise chain support in the works, for other tags deployed via Launch.

The only real sticking point is if you use Adobe Target. Target does have an async library version, but most people avoid it, as it is at odds with how UX fundamentally works. Namely, the async causes "flicker" effects as it is loaded, as the default page content is removed and the browser is waiting for the response to load it. This is generally frowned upon as bad UX that hurts the integrity of AB/MV testing efforts.  So if you use Target, or plan on doing AB/MV testing in general, you should stick with the normal deployment.  But all this is kind of getting sidetracked from your original question.

Body:
Normally, you will put the _satellite.pageBottom() method as much as you can on lowest part of the html, just like:

...

But I am getting errors in the browser that either is blocked in loading because of too much bandwidth or the browser just prevent it from loading or delay it from loading resulting to a _satellite undefined error

So what I did is to put it in a JS file and add defer="defer" attribute

...

So this worked fine now, as long as the browser do not block a tracking JS API.

So is this fine to do?

Body:
Summary

Officially, you should not do this sort of thing.

Details

The documentation states the following:

Important: For a successful implementation, it is critical that you
  follow these instructions as they appear in Adobe Help. Specifically,
  you must place the header code in the <head> section of your document
  templates. Also, you must place the footer code just before the
  closing </body> tag. Placing either of these embed codes elsewhere in
  your markup, or using asynchronous methods to append the embed codes,
  or wrapping the embed codes in any way, are not a supported
  implementations of dynamic tag management. The embed codes must be
  implemented exactly as provided.

An unsupported implementation will yield unexpected results and
  prevent Customer Care and Engineering from assisting with your
  implementation.

So, before I say anything else, the official answer is no, you should not do this sort of thing. Losing support from Adobe is generally a bad idea, even if the implementation is not the current best practice.

Unofficially..

Okay firstly, you mentioned getting error(s) when you attempted to do this sort of thing. Firstly, I'm a little unclear about the errors you mentioned. In particular, the _satellite undefined error. To me, this sounds like you attempted to load the Header script async and/or deferred, and the DTM library was not loaded in time before the Footer snippet (the _satellite.pageBottom()) was called. But you did not mention this in your question; you only mentioned issues with the Footer snippet.

Again, officially, you cannot do this sort of thing to either of the snippets. But even if you decide to deviate from the documentation, you definitely need to ensure the Header snippet is loaded before the Footer, or else you will get "_satellite is undefined" type errors, because the Header script is where _satellite is defined. So if you want to dabble in making both async and/or deferred, you should look into promise chains, or wrapping the Footer script in some logic that looks for _satellite and if not found, setTimeout to try again for a number of times. Or..

On DOM ready, if _satellite.pageBottom() has not yet executed, DTM will internally call it on its own. So, you technically don't even need to include the Footer script on your site if you're going for a full async/deferred implementation.

On that note.. going for a fully async/deferred DTM implementation means that you have to ensure everything you deploy via DTM is also async. I have no idea what all you have deployed through DTM, but in practice, at a minimum, you almost certainly have the Experience Cloud ID Service (ECIDS) and Adobe Analytics (AA) deployed via DTM, and DTM does not currently support deploying those in an async manner (ECIDS needs to be loaded before AA).  And that's just one tag/tool example.

So at a minimum, you should probably at least respect the documentation for the Header tag. The Footer tag is a lot more forgiving / doable for pretty much anything else, though, if you ensure that you only deploy things on DOM ready / async. But again, officially, you should follow the documentation for both, and that is my official answer.

An alternative...

You should consider migrating from Adobe DTM to Adobe Launch. Launch is Adobe's latest tag management solution. DTM is being phased out. Launch can be deployed with a Header and Footer tag the same as DTM, where timing can be enforced, but unlike DTM, Launch also has official asynchronous deployment option. The Header tag can be loaded async, and there is no Footer tag (for the async deployment). Launch does some magic tricks to ensure order of operations for the Adobe tools (e.g. the ECIDS vs. AA mentioned above). There is also promise chain support in the works, for other tags deployed via Launch.

The only real sticking point is if you use Adobe Target. Target does have an async library version, but most people avoid it, as it is at odds with how UX fundamentally works. Namely, the async causes "flicker" effects as it is loaded, as the default page content is removed and the browser is waiting for the response to load it. This is generally frowned upon as bad UX that hurts the integrity of AB/MV testing efforts.  So if you use Target, or plan on doing AB/MV testing in general, you should stick with the normal deployment.  But all this is kind of getting sidetracked from your original question.


问:
Get Unicode character from String representing Unicode code point in python?
I am trying to convert the string, representing a Unicode code point, Ex. '03A9', into the corresponding unicode character, Ex. Ω (Greek Omega, U+03A9). The code point is meant to be able to vary so I cannot hard code the value.  Is there any way this can be done?

Body:
Try:-

>> chr(int("03A9",  base=16))


问:
Trigger email when a new record is created in DynamoDB
We have an automated process to create records in a DynamoDB table. I want to receive an email when a new records/object gets created. How can I do this?

I tried using Zapier and they have a bug in the DynamoDB Zap so it does not work

答:
From DynamoDB Streams and AWS Lambda Triggers:

Amazon DynamoDB is integrated with AWS Lambda so that you can create triggers—pieces of code that automatically respond to events in DynamoDB Streams. With triggers, you can build applications that react to data modifications in DynamoDB tables.

If you enable DynamoDB Streams on a table, you can associate the stream ARN with a Lambda function that you write. Immediately after an item in the table is modified, a new record appears in the table's stream. AWS Lambda polls the stream and invokes your Lambda function synchronously when it detects new stream records.

So, you can:

Configure DynamoDB to generate a DynamoDB stream

Create an AWS Lambda function that is triggered by the stream

Write code in the Lambda function that sends an email via Amazon Simple Email Service (SES). Your code could filter the records so that you are only notified about specific updates of interest.

Actually, it can be a little complex to configure Amazon SES, so instead of "sending an email", I would recommend sending a message to Amazon Simple Notification Service (SNS). You can then subscribe email addresses to the Amazon SNS topic. All subscribers will receive the notification via email (or SMS if you prefer!).


问:
Getting vue typeerror cannot read property 'name' of undefined
I know this type of questions are every where, but I am having problem to find a good answer(I am new to VueJS).I am sorry about that.

I am trying to pass data using vform.

What I am trying to do is adding user details through vform to a table.

Here is my Users.vue code

```<code><div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="addNew" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Add New</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </div>

          <div class="modal-body">
              <div class="form-group">
              <input v-model="form.name" type="text" name="name"
              class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
              <has-error :form="form" field="name"></has-error>
             </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save changes</button>
          </div>

        </div>
      </div>
    </div>

<script>
    export default {
    data(){

        return{

            form: new Form({
                name: ''

            })
        }
    },
 }
</script>
</code>```

Here is my app.js

```<code> require('./bootstrap');

    window.Vue = require('vue');

    import { Form, HasError, AlertError } from 'vform';

    window.form = Form;

    Vue.component(HasError.name, HasError)
    Vue.component(AlertError.name, AlertError)

    import VueRouter from 'vue-router'
    Vue.use(VueRouter)

    let routes = [
      { path: '/dashboard', component: require('./components/Dashboard.vue') },
      { path: '/profile', component: require('./components/Profile.vue') },
      { path: '/users', component: require('./components/Users.vue') }
    ]

    const router = new VueRouter({
      mode: 'history',
      routes // short for `routes: routes`
    })
</code>```

答:
The issue you have is most likely on the line with this:

<input v-model="form.name" type="text" name="name"
```

<p>You can see it's the only place where <code>.name</code> is called. Which means your <code>form</code> object is <code>undefined</code> and the code is trying to call the attribute <code>name</code> on it which throws you an error.</p>

<p>If you look at the vform README, you will see that the <code>import</code> statement is actually inside the component. The issue with your code is that the import inside <code>app.js</code> doesn't magically appear inside your component so you cannot do <code>new Form()</code> in the Vue component. While you do assign it to the <code>window</code> object in <code>app.js</code>, you don't re-use it later on and IMO, it's better to import your dependencies explicitly. </p>

<p>So in conclusion, what you need to do is: Add this import statement right after the opening <code><script></code> tag in your Vue component</p>

<pre class="lang-js prettyprint-override"><code>import { Form } from 'vform';
</code>```

Body:
I know this type of questions are every where, but I am having problem to find a good answer(I am new to VueJS).I am sorry about that.

I am trying to pass data using vform.

What I am trying to do is adding user details through vform to a table.

Here is my Users.vue code

Add New

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

              <input v-model="form.name" type="text" name="name"
              class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
              <has-error :form="form" field="name"></has-error>

            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save changes</button>

Here is my app.js

 require('./bootstrap');

    window.Vue = require('vue');

    import { Form, HasError, AlertError } from 'vform';

    window.form = Form;

    Vue.component(HasError.name, HasError)
    Vue.component(AlertError.name, AlertError)

    import VueRouter from 'vue-router'
    Vue.use(VueRouter)

    let routes = [
      { path: '/dashboard', component: require('./components/Dashboard.vue') },
      { path: '/profile', component: require('./components/Profile.vue') },
      { path: '/users', component: require('./components/Users.vue') }
    ]

    const router = new VueRouter({
      mode: 'history',
      routes // short for `routes: routes`
    })

Body:
The issue you have is most likely on the line with this:

<input v-model="form.name" type="text" name="name"

You can see it's the only place where .name is called. Which means your form object is undefined and the code is trying to call the attribute name on it which throws you an error.

If you look at the vform README, you will see that the import statement is actually inside the component. The issue with your code is that the import inside app.js doesn't magically appear inside your component so you cannot do new Form() in the Vue component. While you do assign it to the window object in app.js, you don't re-use it later on and IMO, it's better to import your dependencies explicitly.

So in conclusion, what you need to do is: Add this import statement right after the opening <script> tag in your Vue component

import { Form } from 'vform';


问:
XSLT grouping recursive problem
guys, recursion with grouping is not working. I am using XSLT 1.0.
I need some help to figure this out. Thanks in Advance.

Background:
I have 3 different Types (common, category, & complex) in the xml. My goal is to.

1 - Group xml nodes based on Types.
2 - Create a sub-group for complex under Type=common.
3 - For Type=complex create a number of collections depending upon the source xml. In each collection it should list only 4 elements where Name='A' or 'B' or 'C' or 'D'.
This is where I'm having the problem. Grouping and sub-grouping is working fine. However, when I try to create a collection using recursion then it is not giving me the intending output. For reference please see the expected out xml sample.

Source XML:

```<code><?xml version="1.0" encoding="Windows-1252"?>
<XML>
  <Attributes>
    <Attribute>
      <Name>Buyer ID</Name>
      <Type>common</Type>
      <Value>Lee</Value>
    </Attribute>
    <Attribute>
      <Name>Enviornment</Name>
      <Type>common</Type>
      <Value>Dev</Value>
    </Attribute>
    <Attribute>
      <Name>Retail</Name>
      <Type>common</Type>
      <Value></Value>
    </Attribute>
    <Attribute>
      <Name>Gender</Name>
      <Type>category</Type>
      <Value>M</Value>
    </Attribute>
    <Attribute>
      <Name>Collection</Name>
      <Type>Complex</Type>
      <Value>ing</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>A</Name>
      <Type>Complex</Type>
      <Value>Testing</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>B</Name>
      <Type>Complex</Type>
      <Value>Yellow</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>C</Name>
      <Type>Complex</Type>
      <Value>10</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>D</Name>
      <Type>Complex</Type>
      <Value>MA</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>A</Name>
      <Type>Complex</Type>
      <Value>24a</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>B</Name>
      <Type>Complex</Type>
      <Value>Green</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>C</Name>
      <Type>Complex</Type>
      <Value>22</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>D</Name>
      <Type>Complex</Type>
      <Value>AM</Value>
      <Path />
    </Attribute>
  </Attributes>
</XML>
</code>```

Expected Output:

```<code><?xml version="1.0" encoding="utf-8"?>
<Data Schema="XML A">
  <Items>
    <Item>
      <Attributes type="common">
        <Attr name="Buyer ID" value="Lee" />
        <Attr name="Enviornment" value="Dev" />
        <Attr name="Retail" value="" />
        <Collection name="Collection" >
          <Complex>
            <Attr name="A" value="Testing" />
            <Attr name="B" value="Yellow" />
            <Attr name="C" value="10" />
            <Attr name="D" value="MA" />
          </Complex>
          <Complex>
            <Attr name="A" value="24a" />
            <Attr name="B" value="Green" />
            <Attr name="C" value="22" />
            <Attr name="D" value="AM" />
          </Complex>
        </Collection>
      </Attributes>
      <Attributes type="category">
        <Attr name="Gender" value="M" />
      </Attributes>
      <errorCodes>
        <errorCode>value for Retail is missing.</errorCode>
      </errorCodes>
    </Item>
  </Items>
</Data>
</code>```

Here is the XSLT

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="type" match="Attribute" use="Type"/>
    <xsl:variable name="group" select="4"/>
    <xsl:template match="/">
        <Data Schema="XML A">
            <Items>
                <Item>
                    <xsl:apply-templates select="XML/Attributes/Attribute[generate-id() = generate-id(key('type', Type)[1])]">
                        <xsl:sort select="Type" order="descending"/>
                    </xsl:apply-templates>
                    <errorCodes>
                        <xsl:apply-templates select="XML/Attributes/Attribute" mode="errors"/>
                    </errorCodes>
                </Item>
            </Items>
        </Data>
    </xsl:template>
    <xsl:template match="Attribute">
        <xsl:variable name="compType" select="count(/XML/Attributes/Attribute[Type='Complex' and Name!='Collection'])"/>
        <xsl:if test="Type!='Complex'">
            <Attributes type="{Type}">
                <xsl:apply-templates select="key('type',Type)" mode="out"/>
                <xsl:if test="Type='common'">
                    <Collection>
                        <xsl:for-each select="/XML/Attributes/Attribute[Type='Complex']">
                            <xsl:choose>
                                <xsl:when test="(Name='A' or Name='B' or Name='C' or Name='D')">
                                    <xsl:if test="(($compType > 0) and (Name!='Collection'))">
                                        <xsl:apply-templates select="key('type','Complex')" mode="out"/>
                                    </xsl:if>
                                </xsl:when>
                                <xsl:otherwise>
                                    <Complex>
                                        <Attr id="" name="A" value="Default" />
                                        <Attr id="" name="B" value="Default" />
                                        <Attr id="" name="C" value="Default" />
                                        <Attr id="" name="D" value="" />
                                    </Complex>
                                </xsl:otherwise>
                            </xsl:choose>
                        </xsl:for-each>
                    </Collection>
                </xsl:if>
            </Attributes>
        </xsl:if>
    </xsl:template>
    <xsl:template match="Attribute" mode="out">
        <Collection>
            <Attr name="{Name}" value="{Value}"/>
        </Collection>
    </xsl:template>
    <xsl:template match="Attribute[Type='Complex']" mode="out">
        <xsl:apply-templates select="XML/Attributes/Attribute[not(Name='Collection')]
                                                [position() mod $group = 1]" mode="group"/>
    </xsl:template>
    <xsl:template match="Name" mode="group">
        <xsl:if test="Name!='Collection'">
            <Attr name="{Name}" value="{Value}"/>
        </xsl:if>
    </xsl:template>
    <xsl:template match="Attribute">
        <Complex>
            <xsl:apply-templates
                select=".|following-sibling::Attribute[position() < $group]" mode="inner" />
        </Complex>
    </xsl:template>
    <xsl:template match="Attribute" mode="errors">
        <xsl:if test="(Name='Retail' or Name='Product Description') and Value=''">
            <errorCode>value for <xsl:value-of select="Name"/> is missing.</errorCode>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
I am not sure I understand all your requirements but the following sample

```<code><xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:data="http://example.com/data"
  exclude-result-prefixes="data"
  version="1.0">

  <xsl:output indent="yes"/>

  <xsl:key name="att-by-type" match="Attributes/Attribute" use="Type"/>

  <xsl:variable name="complex" select="key('att-by-type', 'Complex')"/>

  <xsl:template match="XML">
    <Data Schema="XML A">
      <Items>
        <Item>
          <xsl:apply-templates select="Attributes/Attribute[Type = 'common' or Type = 'category'][generate-id() = generate-id(key('att-by-type', Type)[1])]" mode="group"/>
        </Item>
      </Items>
    </Data>
  </xsl:template>

  <xsl:template match="Attribute" mode="group">
    <Attributes type="{Type}">
      <xsl:apply-templates select="key('att-by-type', Type)"/>
      <xsl:if test="Type = 'common'">
        <Collection name="Collection">
          <xsl:apply-templates select="$complex[Name = 'A']" mode="comp-group"/>
        </Collection>
      </xsl:if>
    </Attributes>
  </xsl:template>

  <xsl:template match="Attribute" mode="comp-group">
    <Complex>
      <xsl:variable name="pos" select="position()"/>
      <xsl:apply-templates select="$complex[Name = 'A'][position() = $pos] |
                                   $complex[Name = 'B'][position() = $pos] |
                                   $complex[Name = 'C'][position() = $pos] |
                                   $complex[Name = 'D'][position() = $pos]"/>
    </Complex>
  </xsl:template>

  <xsl:template match="Attribute">
    <Attr name="{Name}" value="{Value}"/>
  </xsl:template>

</xsl:stylesheet>
</code>```

produces the output you posted (with the exception of the errorCodes, I left that out as it seemed unrelated to the other problem).

Title: XSLT grouping recursive problem

Body:
guys, recursion with grouping is not working. I am using XSLT 1.0.
I need some help to figure this out. Thanks in Advance.

Background:
I have 3 different Types (common, category, & complex) in the xml. My goal is to.

1 - Group xml nodes based on Types.
2 - Create a sub-group for complex under Type=common.
3 - For Type=complex create a number of collections depending upon the source xml. In each collection it should list only 4 elements where Name='A' or 'B' or 'C' or 'D'.
This is where I'm having the problem. Grouping and sub-grouping is working fine. However, when I try to create a collection using recursion then it is not giving me the intending output. For reference please see the expected out xml sample.

Source XML:

<?xml version="1.0" encoding="Windows-1252"?>
<XML>
  <Attributes>
    <Attribute>
      <Name>Buyer ID</Name>
      <Type>common</Type>
      <Value>Lee</Value>
    </Attribute>
    <Attribute>
      <Name>Enviornment</Name>
      <Type>common</Type>
      <Value>Dev</Value>
    </Attribute>
    <Attribute>
      <Name>Retail</Name>
      <Type>common</Type>
      <Value></Value>
    </Attribute>
    <Attribute>
      <Name>Gender</Name>
      <Type>category</Type>
      <Value>M</Value>
    </Attribute>
    <Attribute>
      <Name>Collection</Name>
      <Type>Complex</Type>
      <Value>ing</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>A</Name>
      <Type>Complex</Type>
      <Value>Testing</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>B</Name>
      <Type>Complex</Type>
      <Value>Yellow</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>C</Name>
      <Type>Complex</Type>
      <Value>10</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>D</Name>
      <Type>Complex</Type>
      <Value>MA</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>A</Name>
      <Type>Complex</Type>
      <Value>24a</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>B</Name>
      <Type>Complex</Type>
      <Value>Green</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>C</Name>
      <Type>Complex</Type>
      <Value>22</Value>
      <Path />
    </Attribute>
    <Attribute>
      <Name>D</Name>
      <Type>Complex</Type>
      <Value>AM</Value>
      <Path />
    </Attribute>
  </Attributes>
</XML>

Expected Output:

<?xml version="1.0" encoding="utf-8"?>
<Data Schema="XML A">
  <Items>
    <Item>
      <Attributes type="common">
        <Attr name="Buyer ID" value="Lee" />
        <Attr name="Enviornment" value="Dev" />
        <Attr name="Retail" value="" />
        <Collection name="Collection" >
          <Complex>
            <Attr name="A" value="Testing" />
            <Attr name="B" value="Yellow" />
            <Attr name="C" value="10" />
            <Attr name="D" value="MA" />
          </Complex>
          <Complex>
            <Attr name="A" value="24a" />
            <Attr name="B" value="Green" />
            <Attr name="C" value="22" />
            <Attr name="D" value="AM" />
          </Complex>
        </Collection>
      </Attributes>
      <Attributes type="category">
        <Attr name="Gender" value="M" />
      </Attributes>
      <errorCodes>
        <errorCode>value for Retail is missing.</errorCode>
      </errorCodes>
    </Item>
  </Items>
</Data>

Here is the XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="type" match="Attribute" use="Type"/>
    <xsl:variable name="group" select="4"/>
    <xsl:template match="/">
        <Data Schema="XML A">
            <Items>
                <Item>
                    <xsl:apply-templates select="XML/Attributes/Attribute[generate-id() = generate-id(key('type', Type)[1])]">
                        <xsl:sort select="Type" order="descending"/>
                    </xsl:apply-templates>
                    <errorCodes>
                        <xsl:apply-templates select="XML/Attributes/Attribute" mode="errors"/>
                    </errorCodes>
                </Item>
            </Items>
        </Data>
    </xsl:template>
    <xsl:template match="Attribute">
        <xsl:variable name="compType" select="count(/XML/Attributes/Attribute[Type='Complex' and Name!='Collection'])"/>
        <xsl:if test="Type!='Complex'">
            <Attributes type="{Type}">
                <xsl:apply-templates select="key('type',Type)" mode="out"/>
                <xsl:if test="Type='common'">
                    <Collection>
                        <xsl:for-each select="/XML/Attributes/Attribute[Type='Complex']">
                            <xsl:choose>
                                <xsl:when test="(Name='A' or Name='B' or Name='C' or Name='D')">
                                    <xsl:if test="(($compType > 0) and (Name!='Collection'))">
                                        <xsl:apply-templates select="key('type','Complex')" mode="out"/>
                                    </xsl:if>
                                </xsl:when>
                                <xsl:otherwise>
                                    <Complex>
                                        <Attr id="" name="A" value="Default" />
                                        <Attr id="" name="B" value="Default" />
                                        <Attr id="" name="C" value="Default" />
                                        <Attr id="" name="D" value="" />
                                    </Complex>
                                </xsl:otherwise>
                            </xsl:choose>
                        </xsl:for-each>
                    </Collection>
                </xsl:if>
            </Attributes>
        </xsl:if>
    </xsl:template>
    <xsl:template match="Attribute" mode="out">
        <Collection>
            <Attr name="{Name}" value="{Value}"/>
        </Collection>
    </xsl:template>
    <xsl:template match="Attribute[Type='Complex']" mode="out">
        <xsl:apply-templates select="XML/Attributes/Attribute[not(Name='Collection')]
                                                [position() mod $group = 1]" mode="group"/>
    </xsl:template>
    <xsl:template match="Name" mode="group">
        <xsl:if test="Name!='Collection'">
            <Attr name="{Name}" value="{Value}"/>
        </xsl:if>
    </xsl:template>
    <xsl:template match="Attribute">
        <Complex>
            <xsl:apply-templates
                select=".|following-sibling::Attribute[position() < $group]" mode="inner" />
        </Complex>
    </xsl:template>
    <xsl:template match="Attribute" mode="errors">
        <xsl:if test="(Name='Retail' or Name='Product Description') and Value=''">
            <errorCode>value for <xsl:value-of select="Name"/> is missing.</errorCode>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Body:
I am not sure I understand all your requirements but the following sample

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:data="http://example.com/data"
  exclude-result-prefixes="data"
  version="1.0">

  <xsl:output indent="yes"/>

  <xsl:key name="att-by-type" match="Attributes/Attribute" use="Type"/>

  <xsl:variable name="complex" select="key('att-by-type', 'Complex')"/>

  <xsl:template match="XML">
    <Data Schema="XML A">
      <Items>
        <Item>
          <xsl:apply-templates select="Attributes/Attribute[Type = 'common' or Type = 'category'][generate-id() = generate-id(key('att-by-type', Type)[1])]" mode="group"/>
        </Item>
      </Items>
    </Data>
  </xsl:template>

  <xsl:template match="Attribute" mode="group">
    <Attributes type="{Type}">
      <xsl:apply-templates select="key('att-by-type', Type)"/>
      <xsl:if test="Type = 'common'">
        <Collection name="Collection">
          <xsl:apply-templates select="$complex[Name = 'A']" mode="comp-group"/>
        </Collection>
      </xsl:if>
    </Attributes>
  </xsl:template>

  <xsl:template match="Attribute" mode="comp-group">
    <Complex>
      <xsl:variable name="pos" select="position()"/>
      <xsl:apply-templates select="$complex[Name = 'A'][position() = $pos] |
                                   $complex[Name = 'B'][position() = $pos] |
                                   $complex[Name = 'C'][position() = $pos] |
                                   $complex[Name = 'D'][position() = $pos]"/>
    </Complex>
  </xsl:template>

  <xsl:template match="Attribute">
    <Attr name="{Name}" value="{Value}"/>
  </xsl:template>

</xsl:stylesheet>

produces the output you posted (with the exception of the errorCodes, I left that out as it seemed unrelated to the other problem).


问:
Publishing Left and Right video feeds in ROS using a MYNTEYE stereo camera
I'm new to ROS and OpenCV and am trying to figure things out. It seems to do anything with vision the camera needs to be calibrated. I found what looks to be a simple method of calibration in the ROS tutorials here: https://wiki.ros.org/camera_calibration/Tutorials/StereoCalibration

However one of the tutorial's assumptions is "a stereo camera publishing left and right images over ROS." I have no idea how to do this. Thanks to anyone that can help me.

This might be a separate issue but when I use the stereo camera in OpenCV it only recognizes it in one index (my built in webcam on my laptop would be 0 and the MYNTEYE would be 1). When it does display it puts both lens views in the same window so it looks like the camera is cross-eyed.

答:
Use MYNT-EYE-ROS-Wrapper for using it

https://github.com/slightech/MYNT-EYE-ROS-Wrapper

Call

```<code>roslaunch mynteye_ros_wrapper mynt_camera_display.launch
</code>```

to run the wrapper

The modified the published topic from minteye node to feed into stereo calibration node accordingly

Body:
Use MYNT-EYE-ROS-Wrapper for using it

https://github.com/slightech/MYNT-EYE-ROS-Wrapper

Call

roslaunch mynteye_ros_wrapper mynt_camera_display.launch

to run the wrapper

The modified the published topic from minteye node to feed into stereo calibration node accordingly


问:
unzipper ignores empty directory
I am a Japanese Web Developer.

I am not good at English, sorry.

https://www.npmjs.com/package/unzipper

I am using this library.

Here is my code.

```<code>// unzip module
import fs from 'fs-extra'
import unzipper from 'unzipper'
import Promise from 'bluebird'

export default ({ inputFilePath, outputFilePath }) => {
  return new Promise(async (resolve, reject, onCancel) => {
    try {
      await streamPromise(fs.createReadStream(inputFilePath).pipe(unzipper.Extract({ path: outputFilePath })))
        .then(resolve)
    } catch (error) {
      reject(error)
    }
  })
}

const streamPromise = (stream) => {
  return new Promise((resolve, reject) => {
    stream.on('end', () => {
      resolve('end')
    })
    stream.on('finish', () => {
      resolve('finish')
    })
    stream.on('error', (error) => {
      reject(error)
    })
  })
}
</code>```

But directory which has no file inside, won't be copied.

Any way to fix this?

答:
You want to unzip a zip file using unzipper.

You want to also export the directories without files.

If my understanding is correct, how about this modification? I think that there are several answers for your situation. So please think of this as just one of them.

Modification point:

In this modification, when the file type is "Directory", a new Directory is created. By this, the directory without files can be exported.

Modified script:

Please modify as follows.

```<code>// unzip module
import fs from 'fs-extra'
import unzipper from 'unzipper'
import Promise from 'bluebird'
import path from 'path' // Added

// Modified
export default ({ inputFilePath, outputFilePath }) => {
  return new Promise(async (resolve, reject, onCancel) => {
    try {
      await streamPromise(fs.createReadStream(inputFilePath).pipe(unzipper.Parse()), outputFilePath)
        .then(resolve)
    } catch (error) {
      reject(error)
    }
  })
}

// Modified
const streamPromise = (stream, outputFilePath) => {
  return new Promise((resolve, reject) => {
    stream.on("entry", entry => {
      const fileName = entry.path;
      const type = entry.type;
      if (type == "Directory") {
        fs.mkdirSync(path.join(outputFilePath, fileName));
      } else if (type == "File") {
        entry.pipe(fs.createWriteStream(path.join(outputFilePath, fileName)));
      }
    });
    stream.on("end", () => {
      resolve("end");
    });
    stream.on("finish", () => {
      resolve("finish");
    });
    stream.on("error", error => {
      reject(error);
    });
  });
};
</code>```

Reference:

unzipper

In my environment, I could confirm that the modified script worked. But in your environment, the script didn't work, I apologize.

Title: unzipper ignores empty directory

Body:
I am a Japanese Web Developer.

I am not good at English, sorry.

https://www.npmjs.com/package/unzipper

I am using this library.

Here is my code.

// unzip module
import fs from 'fs-extra'
import unzipper from 'unzipper'
import Promise from 'bluebird'

export default ({ inputFilePath, outputFilePath }) => {
  return new Promise(async (resolve, reject, onCancel) => {
    try {
      await streamPromise(fs.createReadStream(inputFilePath).pipe(unzipper.Extract({ path: outputFilePath })))
        .then(resolve)
    } catch (error) {
      reject(error)
    }
  })
}

const streamPromise = (stream) => {
  return new Promise((resolve, reject) => {
    stream.on('end', () => {
      resolve('end')
    })
    stream.on('finish', () => {
      resolve('finish')
    })
    stream.on('error', (error) => {
      reject(error)
    })
  })
}

But directory which has no file inside, won't be copied.

Any way to fix this?

Body:
You want to unzip a zip file using unzipper.

You want to also export the directories without files.

If my understanding is correct, how about this modification? I think that there are several answers for your situation. So please think of this as just one of them.

Modification point:

In this modification, when the file type is "Directory", a new Directory is created. By this, the directory without files can be exported.

Modified script:

Please modify as follows.

// unzip module
import fs from 'fs-extra'
import unzipper from 'unzipper'
import Promise from 'bluebird'
import path from 'path' // Added

// Modified
export default ({ inputFilePath, outputFilePath }) => {
  return new Promise(async (resolve, reject, onCancel) => {
    try {
      await streamPromise(fs.createReadStream(inputFilePath).pipe(unzipper.Parse()), outputFilePath)
        .then(resolve)
    } catch (error) {
      reject(error)
    }
  })
}

// Modified
const streamPromise = (stream, outputFilePath) => {
  return new Promise((resolve, reject) => {
    stream.on("entry", entry => {
      const fileName = entry.path;
      const type = entry.type;
      if (type == "Directory") {
        fs.mkdirSync(path.join(outputFilePath, fileName));
      } else if (type == "File") {
        entry.pipe(fs.createWriteStream(path.join(outputFilePath, fileName)));
      }
    });
    stream.on("end", () => {
      resolve("end");
    });
    stream.on("finish", () => {
      resolve("finish");
    });
    stream.on("error", error => {
      reject(error);
    });
  });
};

Reference:

unzipper

In my environment, I could confirm that the modified script worked. But in your environment, the script didn't work, I apologize.


问:
EXCEL VBA: Editing a Column of Strings with a Function
I work with reports every day that list the results for each initiative we handle in a range of about 40 possible outcomes. I have created 4 groups which each of these outcomes could fall into to reduce the required comprehension, and would like my code to replace each individual outcome in column B with its assigned outcome group. This is my first time creating my own function in VBA, so please forgive any obvious errors.

I have created a simple Sub that should (hopefully) find the last row of column B, then loop up each row in the column passing the contained string to a function I've created. The should accept a string, perform a "select case" to ascertain which Outcome Group the string would be assigned to, then return the Outcome Group to the Sub for the current cell to be edited to. The select case options in my code have been reduced for readability. Additionally, the Function is stored in a separate VBA module to the sub.

```<code>Sub fixOutcomeColumn()

    Dim lastRow As Long
    Dim rng As Range, col As Range
    Dim val As String

    lastRow = Cells(Rows.Count, 2).End(xlUp).Row
    val = "test"
    Set col = ActiveWorkbook.ActiveSheet.Range("B1" & lastRow)
    Set rng = ActiveWorkbook.ActiveSheet.Range("B1")

    For Each rng In col.Cells
        val = rng.Value
        rng = changeOutcomesToOG(val)
    Next rng

End Sub

Public Function changeOutcomesToOG(str As String) As String

    Select Case str
        Case "a"
            changeOutcomesToOG = "A"
        Case "b"
            changeOutcomesToOG = "B"
        Case "c"
            changeOutcomesToOG = "C"
        Case "d"
            changeOutcomesToOG = "D"
        Case "e"
            changeOutcomesToOG = "E"
        Case Else
            changeOutcomesToOG = str
    End Select

End Function
</code>```

Stepping through the code in the editor while reading the Locals window shows me that my rng variable isn't being populated by any values when the code is run. Additionally, the code is not looping through each cell in the column, and runs the for loop once instead. I imagine I've made a pretty basic error, but can't figure it out for the life of me!

答:
Can you try this:</p>

```<code>Sub fixOutcomeColumn()

    Dim lastRow As Long
    Dim rng As Range, col As Range
    Dim val As String

    lastRow = Cells(Rows.Count, 2).End(xlUp).Row
    val = "test"
    Set col = ActiveWorkbook.ActiveSheet.Range("B1:B" & lastRow)
    'Set rng = ActiveWorkbook.ActiveSheet.Range("B1")

    For Each rng In col.Cells
        val = rng.Value
        rng.Value = changeOutcomesToOG(val)
    Next rng

End Sub

Public Function changeOutcomesToOG(str As String) As String

    Select Case str
        Case "a"
            changeOutcomesToOG = "A"
        Case "b"
            changeOutcomesToOG = "B"
        Case "c"
            changeOutcomesToOG = "C"
        Case "d"
            changeOutcomesToOG = "D"
        Case "e"
            changeOutcomesToOG = "E"
        Case Else
            changeOutcomesToOG = str
    End Select

End Function
</code>```

Body:
I work with reports every day that list the results for each initiative we handle in a range of about 40 possible outcomes. I have created 4 groups which each of these outcomes could fall into to reduce the required comprehension, and would like my code to replace each individual outcome in column B with its assigned outcome group. This is my first time creating my own function in VBA, so please forgive any obvious errors.

I have created a simple Sub that should (hopefully) find the last row of column B, then loop up each row in the column passing the contained string to a function I've created. The should accept a string, perform a "select case" to ascertain which Outcome Group the string would be assigned to, then return the Outcome Group to the Sub for the current cell to be edited to. The select case options in my code have been reduced for readability. Additionally, the Function is stored in a separate VBA module to the sub.

Sub fixOutcomeColumn()

    Dim lastRow As Long
    Dim rng As Range, col As Range
    Dim val As String

    lastRow = Cells(Rows.Count, 2).End(xlUp).Row
    val = "test"
    Set col = ActiveWorkbook.ActiveSheet.Range("B1" & lastRow)
    Set rng = ActiveWorkbook.ActiveSheet.Range("B1")

    For Each rng In col.Cells
        val = rng.Value
        rng = changeOutcomesToOG(val)
    Next rng

End Sub

Public Function changeOutcomesToOG(str As String) As String

    Select Case str
        Case "a"
            changeOutcomesToOG = "A"
        Case "b"
            changeOutcomesToOG = "B"
        Case "c"
            changeOutcomesToOG = "C"
        Case "d"
            changeOutcomesToOG = "D"
        Case "e"
            changeOutcomesToOG = "E"
        Case Else
            changeOutcomesToOG = str
    End Select

End Function

Stepping through the code in the editor while reading the Locals window shows me that my rng variable isn't being populated by any values when the code is run. Additionally, the code is not looping through each cell in the column, and runs the for loop once instead. I imagine I've made a pretty basic error, but can't figure it out for the life of me!

Body:
Can you try this:

Sub fixOutcomeColumn()

    Dim lastRow As Long
    Dim rng As Range, col As Range
    Dim val As String

    lastRow = Cells(Rows.Count, 2).End(xlUp).Row
    val = "test"
    Set col = ActiveWorkbook.ActiveSheet.Range("B1:B" & lastRow)
    'Set rng = ActiveWorkbook.ActiveSheet.Range("B1")

    For Each rng In col.Cells
        val = rng.Value
        rng.Value = changeOutcomesToOG(val)
    Next rng

End Sub

Public Function changeOutcomesToOG(str As String) As String

    Select Case str
        Case "a"
            changeOutcomesToOG = "A"
        Case "b"
            changeOutcomesToOG = "B"
        Case "c"
            changeOutcomesToOG = "C"
        Case "d"
            changeOutcomesToOG = "D"
        Case "e"
            changeOutcomesToOG = "E"
        Case Else
            changeOutcomesToOG = str
    End Select

End Function


问:
How to loop through two "div" with different data on each?
i am trying to build timeline feature  in my web application, i have two different divs each with different data, i am trying to use  foreach loop but it is not working as expected, can please anyone help me to achieve this , will be much appreciated

These are the two divs where i want the loo to be executed.

```<code>    <div class="row timeline-movement">
 <?php foreach ($events as $eve): ?>
    <div class="timeline-badge">
        <span class="timeline-balloon-date-day"><?php echo substr($eve->time,8, -8); ?></span>
        <span class="timeline-balloon-date-month " style="font-size: 20px;"><b><?php echo substr($eve->time,5, -12); ?></b></span>
    </div>
</code>```

This is the first div

```<code>    <div class="col-sm-6  timeline-item">
        <div class="row">
            <div class="col-sm-11">
                <div class="timeline-panel credits">
                    <ul class="timeline-panel-ul">
                        <li><span class="importo"><?php echo $eve->title;?></span></li>
                        <li><span class="causale"><?php echo $eve->description;?></span> </li>
                        <li><p><small class="text-muted"><i class="glyphicon glyphicon-time"></i><?php echo $eve->time;?></small></p> </li>
                    </ul>
                </div>

            </div>
        </div>
    </div>

</code>```

This is the second div

```<code>
    <div class="col-sm-6  timeline-item">
        <div class="row">
            <div class="col-sm-11">
                <div class="timeline-panel debits">
                    <ul class="timeline-panel-ul">
                        <li><span class="importo"><?php echo $eve->title;?></span></li>
                        <li><span class="causale"><?php echo $eve->description;?></span> </li>
                        <li><p><small class="text-muted"><i class="glyphicon glyphicon-time"></i><?php echo $eve->time;?></small></p> </li>
                    </ul>
                </div>

            </div>
        </div>
    </div>
<?php endforeach ?>

</code>```

This is the modal file for getting value from database

```<code> public function view_timeline($id){

    $this->db->select("*");
  $this->db->from('timeline');
    $this->db->where('projectID' ,$id);
    $this->db->order_by("time", "DESC");
  //$this->db->join('client', 'client.Client_id = projects.Client_id');
  $query = $this->db->get();

  return $query->result();
 }
</code>```

This is where i created $event variable to get values

```<code>    $data['events'] = $this->client_model->view_timeline($id);
</code>```

My expected output will be like this bootsnip
https://bootsnipp.com/snippets/ODzE

答:
In a proper & consolidated way, Here you can use odd & even formula to get your expected output

```<code><?php
$i=1;
foreach ($events as $eve){
    if($i%2){
      $div_class = "credits";
    }else{
      $div_class = "debits";
    }
?>
<div class="col-sm-6  timeline-item">
        <div class="row">
            <div class="col-sm-11">
                <div class="timeline-panel <?php echo $div_class; ?>">
                    <ul class="timeline-panel-ul">
                        <li><span class="importo"><?php echo $eve->title;?></span></li>
                        <li><span class="causale"><?php echo $eve->description;?></span> </li>
                        <li><p><small class="text-muted"><i class="glyphicon glyphicon-time"></i><?php echo $eve->time;?></small></p> </li>
                    </ul>
                </div>

            </div>
        </div>
 </div>
<?php $i++;} ?>
</code>```

Body:
i am trying to build timeline feature  in my web application, i have two different divs each with different data, i am trying to use  foreach loop but it is not working as expected, can please anyone help me to achieve this , will be much appreciated

These are the two divs where i want the loo to be executed.

 <?php foreach ($events as $eve): ?>

        <?php echo substr($eve->time,8, -8); ?>
        <?php echo substr($eve->time,5, -12); ?>

This is the first div

<?php echo $eve->title;?>

<?php echo $eve->description;?>

<?php echo $eve->time;?>

This is the second div

<?php echo $eve->title;?>

<?php echo $eve->description;?>

<?php echo $eve->time;?>

<?php endforeach ?>

This is the modal file for getting value from database

 public function view_timeline($id){

    $this->db->select("*");
  $this->db->from('timeline');
    $this->db->where('projectID' ,$id);
    $this->db->order_by("time", "DESC");
  //$this->db->join('client', 'client.Client_id = projects.Client_id');
  $query = $this->db->get();

  return $query->result();
 }

This is where i created $event variable to get values

    $data['events'] = $this->client_model->view_timeline($id);

My expected output will be like this bootsnip
https://bootsnipp.com/snippets/ODzE

Body:
In a proper & consolidated way, Here you can use odd & even formula to get your expected output

<?php
$i=1;
foreach ($events as $eve){
    if($i%2){
      $div_class = "credits";
    }else{
      $div_class = "debits";
    }
?>
<div class="col-sm-6  timeline-item">
        <div class="row">
            <div class="col-sm-11">
                <div class="timeline-panel <?php echo $div_class; ?>">
                    <ul class="timeline-panel-ul">
                        <li><span class="importo"><?php echo $eve->title;?></span></li>
                        <li><span class="causale"><?php echo $eve->description;?></span> </li>
                        <li><p><small class="text-muted"><i class="glyphicon glyphicon-time"></i><?php echo $eve->time;?></small></p> </li>
                    </ul>
                </div>

            </div>
        </div>
 </div>
<?php $i++;} ?>


问:
Bi-direction port connection with signal in SystemC
In module hierarchy, on connecting inout port with sc_signal it shows error, So is there any other type of signal I  need to connect with inout (bidirectional port) ?

Error: (E115) sc_signal cannot have more than one driver:
 signal Dha.signal_0' (sc_signal)
 first driverDha.Memory.port_4'  (sc_inout)
 second driver `Dha.Alloc.port_3' (sc_inout)

答: You need sc_signal_rv. Check example here http://www.asic-world.com/systemc/ports_signals4.html#Example_:_Resolved_Vector_Signals</p>


问:
jquery with xml/html data behaves different in internet explorer
I have collected form data into a hidden field as the html fragments generated from textarea/tinymce sandwiched between section elements. This is stored into database as php/htmlentities encoded. When retrieved and examined with jquery, count of elements varies for same data between Internet explorer (reports more elements) and other browsers like firefox, chrome (reports 4 elements as expected) and so the dependent operations go haywire. sample data is below.

```<code><section id='data1'>html data
generated by tinymce instance
1</section> <section id='data2'>html
data generated by tinymce instance
2</section> <section id='data3'>html
data generated by tinymce instance
3</section> <section id='data4'>html
data generated by tinymce instance
4</section>
</code>```

I have checked for clash/interference because tinymce. It can be safely ruled out as same code is working in firefox/chrome. Can some one help me fix this, Please?

With regards.

答:
Internet Explorer normally sees whitespace as empty elements, but I thought jquery fixed (or worked around) that. Maybe you should only count the section elements instead of all elements.

edit: I tried this in jsfiddle: http://jsfiddle.net/9aEsh/
IE7 returns 8 instead of 4 in this example, so define the elements you want to count! IE <9 counts textnodes as elements. IE9 does not have this problem.

Body:
I have collected form data into a hidden field as the html fragments generated from textarea/tinymce sandwiched between section elements. This is stored into database as php/htmlentities encoded. When retrieved and examined with jquery, count of elements varies for same data between Internet explorer (reports more elements) and other browsers like firefox, chrome (reports 4 elements as expected) and so the dependent operations go haywire. sample data is below.

html data
generated by tinymce instance
1

html
data generated by tinymce instance
2

html
data generated by tinymce instance
3

html
data generated by tinymce instance
4

I have checked for clash/interference because tinymce. It can be safely ruled out as same code is working in firefox/chrome. Can some one help me fix this, Please?

With regards.


问:
GetType return Int instead of System.Int32
GetType().ToString() returns the FullName of the object. I want the name that you usually use to instantiate that object, i.e, int instead of Int32. Is there a way to do this? </p>

答:
C# has a number of 'types' that are actually keyword aliases to .NET CLR Types.  In this case, int is a C# alias for System.Int32, but the same is true of other C# types like string which is an alias to System.String.

This means that when you get under the hood with reflection and start looking at the CLR Type objects you won't find int, string or any of the other C# type aliases because .NET and the CLR don't know about them... and nor should they.

If you want to translate from the CLR type to a C# alias you'll have to do it yourself via lookup.  Something like this:

```<code>// This is the set of types from the C# keyword list.
static Dictionary<Type, string> _typeAlias = new Dictionary<Type, string>
{
    { typeof(bool), "bool" },
    { typeof(byte), "byte" },
    { typeof(char), "char" },
    { typeof(decimal), "decimal" },
    { typeof(double), "double" },
    { typeof(float), "float" },
    { typeof(int), "int" },
    { typeof(long), "long" },
    { typeof(object), "object" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(string), "string" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    // Yes, this is an odd one.  Technically it's a type though.
    { typeof(void), "void" }
};

static string TypeNameOrAlias(Type type)
{
    // Lookup alias for type
    if (_typeAlias.TryGetValue(type, out string alias))
        return alias;

    // Default to CLR type name
    return type.Name;
}
</code>```

For simple types that will work fine.  Generics, arrays and Nullable take a bit more work.  Arrays and Nullable values are handled recursively like this:

```<code>static string TypeNameOrAlias(Type type)
{
    // Handle nullable value types
    var nullbase = Nullable.GetUnderlyingType(type);
    if (nullbase != null)
        return TypeNameOrAlias(nullbase) + "?";

    // Handle arrays
    if (type.BaseType == typeof(System.Array))
        return TypeNameOrAlias(type.GetElementType()) + "[]";

    // Lookup alias for type
    if (_typeAlias.TryGetValue(type, out string alias))
        return alias;

    // Default to CLR type name
    return type.Name;
}
</code>```

This will handle things like:

```<code>Console.WriteLine(TypeNameOrAlias(typeof(int?[][])));
</code>```

Generics, if you need them, are a bit more involved basically the same process.  Scan through the generic parameter list and run the types recursively through the process.

Nested Types

When you run TypeNameOrAlias on a nested type the result is only the name of the specific type, not the full path you'd need to specify to use it from outside the type that declares it:

```<code>public class Outer
{
    public class Inner
    {
    }
}
// TypeNameOrAlias(typeof(Outer.Inner)) == "Inner"
</code>```

This resolves the issue:

```<code>static string GetTypeName(Type type)
{
    string name = TypeNameOrAlias(type);
    if (type.DeclaringType is Type dec)
    {
        return $"{GetTypeName(dec)}.{name}";
    }
    return name;
}
// GetTypeName(typeof(Outer.Inner)) == "Outer.Inner"
</code>```

Generics

Generics in the .NET type system are interesting.  It's relatively easy to handle things like List<int> or Dictionary<int, string> or similar.  Insert this at the top of TypeNameOrAlias:

```<code>    // Handle generic types
    if (type.IsGenericType)
    {
        string name = type.Name.Split('`').FirstOrDefault();
        IEnumerable<string> parms =
            type.GetGenericArguments()
            .Select(a => type.IsConstructedGenericType ? TypeNameOrAlias(a) : a.Name);
        return $"{name}<{string.Join(",", parms)}>";
    }
</code>```

Now you'll get correct results for things like TypeNameOrAlias(typeof(Dictionary<int, string>)) and so on.  It also deals with generic type definitions: TypeNameOrAlias(typeof(Dictionary<,>)) will return Dictionary<TKey,TValue>.

Where things get difficult is when you nest classes inside generics.  Try GetTypeName(typeof(Dictionary<int, string>.KeyCollection)) for an interesting result.

Body:
C# has a number of 'types' that are actually keyword aliases to .NET CLR Types.  In this case, int is a C# alias for System.Int32, but the same is true of other C# types like string which is an alias to System.String.

This means that when you get under the hood with reflection and start looking at the CLR Type objects you won't find int, string or any of the other C# type aliases because .NET and the CLR don't know about them... and nor should they.

If you want to translate from the CLR type to a C# alias you'll have to do it yourself via lookup.  Something like this:

// This is the set of types from the C# keyword list.
static Dictionary<Type, string> _typeAlias = new Dictionary<Type, string>
{
    { typeof(bool), "bool" },
    { typeof(byte), "byte" },
    { typeof(char), "char" },
    { typeof(decimal), "decimal" },
    { typeof(double), "double" },
    { typeof(float), "float" },
    { typeof(int), "int" },
    { typeof(long), "long" },
    { typeof(object), "object" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(string), "string" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    // Yes, this is an odd one.  Technically it's a type though.
    { typeof(void), "void" }
};

static string TypeNameOrAlias(Type type)
{
    // Lookup alias for type
    if (_typeAlias.TryGetValue(type, out string alias))
        return alias;

    // Default to CLR type name
    return type.Name;
}

For simple types that will work fine.  Generics, arrays and Nullable take a bit more work.  Arrays and Nullable values are handled recursively like this:

static string TypeNameOrAlias(Type type)
{
    // Handle nullable value types
    var nullbase = Nullable.GetUnderlyingType(type);
    if (nullbase != null)
        return TypeNameOrAlias(nullbase) + "?";

    // Handle arrays
    if (type.BaseType == typeof(System.Array))
        return TypeNameOrAlias(type.GetElementType()) + "[]";

    // Lookup alias for type
    if (_typeAlias.TryGetValue(type, out string alias))
        return alias;

    // Default to CLR type name
    return type.Name;
}

This will handle things like:

Console.WriteLine(TypeNameOrAlias(typeof(int?[][])));

Generics, if you need them, are a bit more involved basically the same process.  Scan through the generic parameter list and run the types recursively through the process.

Nested Types

When you run TypeNameOrAlias on a nested type the result is only the name of the specific type, not the full path you'd need to specify to use it from outside the type that declares it:

public class Outer
{
    public class Inner
    {
    }
}
// TypeNameOrAlias(typeof(Outer.Inner)) == "Inner"

This resolves the issue:

static string GetTypeName(Type type)
{
    string name = TypeNameOrAlias(type);
    if (type.DeclaringType is Type dec)
    {
        return $"{GetTypeName(dec)}.{name}";
    }
    return name;
}
// GetTypeName(typeof(Outer.Inner)) == "Outer.Inner"

Generics

Generics in the .NET type system are interesting.  It's relatively easy to handle things like List<int> or Dictionary<int, string> or similar.  Insert this at the top of TypeNameOrAlias:

    // Handle generic types
    if (type.IsGenericType)
    {
        string name = type.Name.Split('`').FirstOrDefault();
        IEnumerable<string> parms =
            type.GetGenericArguments()
            .Select(a => type.IsConstructedGenericType ? TypeNameOrAlias(a) : a.Name);
        return $"{name}<{string.Join(",", parms)}>";
    }

Now you'll get correct results for things like TypeNameOrAlias(typeof(Dictionary<int, string>)) and so on.  It also deals with generic type definitions: TypeNameOrAlias(typeof(Dictionary<,>)) will return Dictionary<TKey,TValue>.

Where things get difficult is when you nest classes inside generics.  Try GetTypeName(typeof(Dictionary<int, string>.KeyCollection)) for an interesting result.


问:
making column vector from the rows of a data frame
I have a data frame with 12 columns and Five Rows. I need to convert this into a column vector with each row being successively pasted one below other.

For example
1 2 3 A a b c B d e f C g h i I need the final output as A1 a b c d e f g h i

答:
We can transpose the dataset, concatenate it to a vector and create a single column data.frame

```<code>out <- data.frame(col1 = c(t(df1)))
</code>```

Body:
We can transpose the dataset, concatenate it to a vector and create a single column data.frame

out <- data.frame(col1 = c(t(df1)))