问:
Particle system design using Three.js and Shader
I'm very new to this community. As i'm asking question if there is something i claim not right, please correct me.

Now to the point, i'm design a particle system using Three.js library, particularly i'm using THREE.Geometry() and control the vertex using shader. I want my particle movement restricted inside a box, which means when a particle crosses over a face of the box, it new position will be at the opposite side of that face.

Here's how i approach, in the vertex shader:

uniform float elapsedTime;

        void main() {
            gl_PointSize = 3.2;
            vec3 pos = position;

            pos.y -= elapsedTime*2.1;

            if( pos.y < -100.0) {
                pos.y = 100.0;
            }

            gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0 );
        }
```

The ellapsedTime is sent from javascript animation loop via uniform. And the y position of each vertex will be update corresponding to the time. As a test, i want if a particle is lower than the bottom plane ( y = -100) it will move to the top plane. That was my plan. And this is the result after they all reach the bottom:

Start to fall

After reach the bottom

So, what am i missing here?

答:
You can not change state in a shader. vertex shaders only output is gl_Position (to generate points/lines/triangles) and varyings that get passed to the fragment shader. Fragment shader's only output is gl_FragColor (in general). So trying to change pos.y will do nothing. The moment the shader exits your change is forgotten.

For your particle code though you could make the position a repeating function of the time

```<code>       const float duration = 5.0;
       float t = fract(elapsedTime / duration);
       pos.y = mix(-100.0, 100.0, t);
</code>```

Assuming elapsedTime is in seconds then pos.y will go from -100 to 100 over 5 seconds and repeat.

Note in this case all the particles will fall at the same time. You could add an attribute to give them each a different time offsets or you could work their position into your own formula. Related to that you might find this article useful.

You could also do the particle movement in JavaScript like this example and this one, updating the positions in the Geometry (or better, BufferGeometry)

Yet another solution is to do the movement in a separate shader by storing the positions in a texture and updating them to a new texture. Then using that texture as input another set of shaders that draws particles.

Body:
I'm very new to this community. As i'm asking question if there is something i claim not right, please correct me.

Now to the point, i'm design a particle system using Three.js library, particularly i'm using THREE.Geometry() and control the vertex using shader. I want my particle movement restricted inside a box, which means when a particle crosses over a face of the box, it new position will be at the opposite side of that face.

Here's how i approach, in the vertex shader:

uniform float elapsedTime;

        void main() {
            gl_PointSize = 3.2;
            vec3 pos = position;

            pos.y -= elapsedTime*2.1;

            if( pos.y < -100.0) {
                pos.y = 100.0;
            }

            gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0 );
        }

The ellapsedTime is sent from javascript animation loop via uniform. And the y position of each vertex will be update corresponding to the time. As a test, i want if a particle is lower than the bottom plane ( y = -100) it will move to the top plane. That was my plan. And this is the result after they all reach the bottom:

Start to fall

After reach the bottom

So, what am i missing here?

Body:
You can not change state in a shader. vertex shaders only output is gl_Position (to generate points/lines/triangles) and varyings that get passed to the fragment shader. Fragment shader's only output is gl_FragColor (in general). So trying to change pos.y will do nothing. The moment the shader exits your change is forgotten.

For your particle code though you could make the position a repeating function of the time

       const float duration = 5.0;
       float t = fract(elapsedTime / duration);
       pos.y = mix(-100.0, 100.0, t);

Assuming elapsedTime is in seconds then pos.y will go from -100 to 100 over 5 seconds and repeat.

Note in this case all the particles will fall at the same time. You could add an attribute to give them each a different time offsets or you could work their position into your own formula. Related to that you might find this article useful.

You could also do the particle movement in JavaScript like this example and this one, updating the positions in the Geometry (or better, BufferGeometry)

Yet another solution is to do the movement in a separate shader by storing the positions in a texture and updating them to a new texture. Then using that texture as input another set of shaders that draws particles.


来源: stackexchange

问:
Folder Listing in Python
I had a question regarding how to list only the folders, not the files within the folders, in Python. I currently have this few lines of code which will join every file in ever folder into one list. If I have 50 folders, I want to make 50 different lists instead of one large one.

```<code>Folder_files = []
for dirName, subdirList, fileList in os.walk(Path):
    for filename in fileList:
        if "A_0" in dirName:
            if ".xml" in filename.lower():
                Folder_files.append(os.path.join(dirName,filename))
</code>```

I know I have Folder_files as my only list at the moment, however I expect to experiment by using a for loop to have different lists.

I am just in need of help finding out how to read up to the folder A_0 before selecting the .xml files.

Before appending the files to the list. I attached a sample code of what I am thinking it will look like below:

```<code>    for dirName, subdirList, fileList in os.walk(Path):
        for filename in fileList:
            if "A_0" in dirName:
                #for loop in here
                    #Set up all folders
                        if ".xml" in filename.lower():
                           #Add files in folder to the appropriate file list
</code>```

答:
```<code>import os

dirs= next(os.walk(r'/home/sirmagid/public_html/ts/'))[1]
for name in dirs:
    print name
</code>```

ContentLicense: CC BY-SA 3.0

Title: Folder Listing in Python

Body:
I had a question regarding how to list only the folders, not the files within the folders, in Python. I currently have this few lines of code which will join every file in ever folder into one list. If I have 50 folders, I want to make 50 different lists instead of one large one.

Folder_files = []
for dirName, subdirList, fileList in os.walk(Path):
    for filename in fileList:
        if "A_0" in dirName:
            if ".xml" in filename.lower():
                Folder_files.append(os.path.join(dirName,filename))

I know I have Folder_files as my only list at the moment, however I expect to experiment by using a for loop to have different lists.

I am just in need of help finding out how to read up to the folder A_0 before selecting the .xml files.

Before appending the files to the list. I attached a sample code of what I am thinking it will look like below:

    for dirName, subdirList, fileList in os.walk(Path):
        for filename in fileList:
            if "A_0" in dirName:
                #for loop in here
                    #Set up all folders
                        if ".xml" in filename.lower():
                           #Add files in folder to the appropriate file list

ContentLicense: CC BY-SA 4.0


问:
Is this well defined code?
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it.

I see a slight difference in the generated assembly when I compare it to:

```<code>*d = ~(*d);
d++;
</code>```

Assembly:

```<code>*d++ = ~(*d);
0x83384    LDR           R3,[R0 <d>,4]        <<diff
0x83388    ADD           R1 <c>, R1 <c>, 1
0x8338c    MVN           R3, R3
0x83390    STR           R3,[R0 <d>],4
</code>```

vs

```<code>*d = ~(*d);
d++;
0x83384   LDR           R3,[R0 <d>]
0x83388   ADD           R1 <c>, R1 <c>, 1
0x8338c   MVN           R3, R3
0x83390   STR           R3,[R0 <d>],4
</code>```

Thanks!

答:
```<code>*d++ = ~(*d);
</code>```

In this expression no object is having a new value stored to it more that once. The value of d + 1 is stored to d as a side effect of the incremement operator (d++) and the value of the object pointed to by d before this increment is written to by the assignment operator.

The issue is that d is read, not merely to determine the value to be written back to it (i.e. d + 1) but is also read to determine the address to read from in the right hand side sub-expression ~(*d).

This violates the third sentence of ISO/IEC 14882:2003 5 [expr] / 4 (first sentence omitted for brevity):

[...] Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.  Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

Title: Is this well defined code?

Body:
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it.

I see a slight difference in the generated assembly when I compare it to:

*d = ~(*d);
d++;

Assembly:

*d++ = ~(*d);
0x83384    LDR           R3,[R0 <d>,4]        <<diff
0x83388    ADD           R1 <c>, R1 <c>, 1
0x8338c    MVN           R3, R3
0x83390    STR           R3,[R0 <d>],4

vs

*d = ~(*d);
d++;
0x83384   LDR           R3,[R0 <d>]
0x83388   ADD           R1 <c>, R1 <c>, 1
0x8338c   MVN           R3, R3
0x83390   STR           R3,[R0 <d>],4

Thanks!

Body:
*d++ = ~(*d);

In this expression no object is having a new value stored to it more that once. The value of d + 1 is stored to d as a side effect of the incremement operator (d++) and the value of the object pointed to by d before this increment is written to by the assignment operator.

The issue is that d is read, not merely to determine the value to be written back to it (i.e. d + 1) but is also read to determine the address to read from in the right hand side sub-expression ~(*d).

This violates the third sentence of ISO/IEC 14882:2003 5 [expr] / 4 (first sentence omitted for brevity):

[...] Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.  Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.


问:
How to know total pages of pagination in codeigniter 4
I am using codeigniter 4, I created pagination in view and its display the results fine. But I want to know total page for this results. The view code for pagination is -</p>

```<code><?php if ($pager) :?>
   <?php $pagi_path=getenv('pagi_path').'search'; ?>
   <?php $pager->setPath($pagi_path); ?>
   <?= $pager->links() ?>
<?php endif ?>
</code>```

答:
$pager->getPageCount() - gives you total count of pages

Class is located in system/Pager/Pager.php , you can look it's methods for even more 'extras'

Body:
I am using codeigniter 4, I created pagination in view and its display the results fine. But I want to know total page for this results. The view code for pagination is -

<?php if ($pager) :?>
   <?php $pagi_path=getenv('pagi_path').'search'; ?>
   <?php $pager->setPath($pagi_path); ?>
   <?= $pager->links() ?>
<?php endif ?>


问:
Create-react-app apple touch icon not working
Im trying to add an apple touch icon

ive tried several things and nothing seems to work. when I add the website to my favorites I only see a default touch icon not the one im specifyin.

```<code>//index.html

 <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
 <link rel="apple-touch-icon" href="%PUBLIC_URL%/apple-touch-icon.png" />
 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

//manifest.json

{
  "short_name": "ICAD",
  "name": "ICAD | Vinyl Banners, Graphics, Vehicle Wraps | Boston MA",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "apple-touch-icon.png",
      "type": "image/png"
    }
  ],
  "start_url": ".",
  "display": "standalone"
}

</code>```

im expecting to see this icon when i save the website as a favorite on my safari browser

答:
Use Helmet</p>

```<code>      <Helmet>
        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href="%PUBLIC_URL%/apple-touch-icon.png"
        />
      </Helmet>
</code>```

Body:
Im trying to add an apple touch icon

ive tried several things and nothing seems to work. when I add the website to my favorites I only see a default touch icon not the one im specifyin.

//index.html

 <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
 <link rel="apple-touch-icon" href="%PUBLIC_URL%/apple-touch-icon.png" />
 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

//manifest.json

{
  "short_name": "ICAD",
  "name": "ICAD | Vinyl Banners, Graphics, Vehicle Wraps | Boston MA",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "apple-touch-icon.png",
      "type": "image/png"
    }
  ],
  "start_url": ".",
  "display": "standalone"
}

im expecting to see this icon when i save the website as a favorite on my safari browser

Body:
Use Helmet

      <Helmet>
        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href="%PUBLIC_URL%/apple-touch-icon.png"
        />
      </Helmet>


问:
How to remove the separator between the header and the first row in a grouped tableView
I am creating a static tableView. My goal is to have a single view that displays a tableView with 3 rows (get support, send feedback, participation terms), and a header + footer.

Right now, it all works fine EXCEPT the fact that there are two extra separators (one between the header and the first cell and the other between the last cell and the footer) that I cannot seem to get rid of.

Here is my code:

```<code>final class viewController: UITableViewController {

    private let headerContainer = UIView()
    private let footerContainer = UIView()

    private let tableData = ["Get Support", "Send Feedback", "Participation Terms"]

    override func viewDidLoad() {
        super.viewDidLoad()

        setupHeaderAndFooter()
        setupTableView()
    }

    func setupHeaderAndFooter() {
        /* setup code here (not relevant to this question) */

    func setupTableView() {
        // reinitializing tableView so that we can change its style to grouped
       tableView = UITableView(frame: CGRect.zero, style: .grouped)
       tableView.delegate = self
       tableView.separatorStyle = .singleLine
    }

    //MARK: UITableView Methods

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerContainer
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 150
    }

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return footerContainer
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 200
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        cell.textLabel!.text = tableData[indexPath.row]
        return cell
    }
}
</code>```

答:
You have to set clipsToBounds to true on your header view.

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = //Get your header here
    header.clipsToBounds = true
    return header
}
</code>```

Before:

After:

Body:
I am creating a static tableView. My goal is to have a single view that displays a tableView with 3 rows (get support, send feedback, participation terms), and a header + footer.

Right now, it all works fine EXCEPT the fact that there are two extra separators (one between the header and the first cell and the other between the last cell and the footer) that I cannot seem to get rid of.

Here is my code:

final class viewController: UITableViewController {

    private let headerContainer = UIView()
    private let footerContainer = UIView()

    private let tableData = ["Get Support", "Send Feedback", "Participation Terms"]

    override func viewDidLoad() {
        super.viewDidLoad()

        setupHeaderAndFooter()
        setupTableView()
    }

    func setupHeaderAndFooter() {
        /* setup code here (not relevant to this question) */

    func setupTableView() {
        // reinitializing tableView so that we can change its style to grouped
       tableView = UITableView(frame: CGRect.zero, style: .grouped)
       tableView.delegate = self
       tableView.separatorStyle = .singleLine
    }

    //MARK: UITableView Methods

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerContainer
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 150
    }

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return footerContainer
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 200
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        cell.textLabel!.text = tableData[indexPath.row]
        return cell
    }
}

Body:
You have to set clipsToBounds to true on your header view.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = //Get your header here
    header.clipsToBounds = true
    return header
}

Before:

After:


问:
Sort pandas csv list with string date
I have read a couple of similar post regarding the issue before, but none of the solutions worked for me. so I got the followed csv :

```<code>
    Score    date       term
0      72   3 Feb ·      1
1      47   1 Feb ·      1
2     119   6 Feb ·      1
8     101   7 hrs ·      1
9     536  11 min ·      1
10     53   2 hrs ·      1
11     20  11 Feb ·      3
3      15   1 hrs ·      2
4      33   7 Feb ·      1
5     153   4 Feb ·      3
6      34   3 min ·      2
7      26   3 Feb ·      3
</code>```

I want to sort the csv by date. What's the easiest way to do that ?

答:
You can create 2 helper columns - one for datetimes created by to_datetime and second for timedeltas created by to_timedelta, only necessary format HH:MM:SS, so added Series.replace by regexes, so last is possible sorting by 2 columns by DataFrame.sort_values:

```<code>df['date1'] = pd.to_datetime(df['date'], format='%d %b', errors='coerce')
times = df['date'].replace({'(\d+)\s+min': '00:\\1:00',
                             '\s+hrs': ':00:00'}, regex=True)
df['times'] = pd.to_timedelta(times, errors='coerce')

df = df.sort_values(['times','date1'])
print (df)

    Score    date  term      date1    times
6      34   3 min     2        NaT 00:03:00
9     536  11 min     1        NaT 00:11:00
3      15   1 hrs     2        NaT 01:00:00
10     53   2 hrs     1        NaT 02:00:00
8     101   7 hrs     1        NaT 07:00:00
1      47   1 Feb     1 1900-02-01      NaT
0      72   3 Feb     1 1900-02-03      NaT
7      26   3 Feb     3 1900-02-03      NaT
5     153   4 Feb     3 1900-02-04      NaT
2     119   6 Feb     1 1900-02-06      NaT
4      33   7 Feb     1 1900-02-07      NaT
11     20  11 Feb     3 1900-02-11      NaT
</code>```

Title: Sort pandas csv list with string date

Body:
I have read a couple of similar post regarding the issue before, but none of the solutions worked for me. so I got the followed csv :

    Score    date       term
0      72   3 Feb ·      1
1      47   1 Feb ·      1
2     119   6 Feb ·      1
8     101   7 hrs ·      1
9     536  11 min ·      1
10     53   2 hrs ·      1
11     20  11 Feb ·      3
3      15   1 hrs ·      2
4      33   7 Feb ·      1
5     153   4 Feb ·      3
6      34   3 min ·      2
7      26   3 Feb ·      3

I want to sort the csv by date. What's the easiest way to do that ?

Body:
You can create 2 helper columns - one for datetimes created by to_datetime and second for timedeltas created by to_timedelta, only necessary format HH:MM:SS, so added Series.replace by regexes, so last is possible sorting by 2 columns by DataFrame.sort_values:

df['date1'] = pd.to_datetime(df['date'], format='%d %b', errors='coerce')
times = df['date'].replace({'(\d+)\s+min': '00:\\1:00',
                             '\s+hrs': ':00:00'}, regex=True)
df['times'] = pd.to_timedelta(times, errors='coerce')

df = df.sort_values(['times','date1'])
print (df)

    Score    date  term      date1    times
6      34   3 min     2        NaT 00:03:00
9     536  11 min     1        NaT 00:11:00
3      15   1 hrs     2        NaT 01:00:00
10     53   2 hrs     1        NaT 02:00:00
8     101   7 hrs     1        NaT 07:00:00
1      47   1 Feb     1 1900-02-01      NaT
0      72   3 Feb     1 1900-02-03      NaT
7      26   3 Feb     3 1900-02-03      NaT
5     153   4 Feb     3 1900-02-04      NaT
2     119   6 Feb     1 1900-02-06      NaT
4      33   7 Feb     1 1900-02-07      NaT
11     20  11 Feb     3 1900-02-11      NaT


问:
Comparing two lists in python and only keeping matches and non matches
I am attempting to iterate over two lists of tuples and am looking for matches. I want to generate two lists of tuples as output: one containing matches (tuples whose first value appears in both lists) and one with non-matches (tuples whose first value appears in one list, but not in the other).

I tried implementing this by iterating over the two lists in a nested loop and comparing the tuples there. However, when I do that, the resulting "no match" list also contains tuples that do match, and also appear in the "match" list.

I'm trying to avoid this. There must be a better way to do this. Any help would be appreciated.

Below is an example:

data1 = [
    ("Aaden", "3"),
    ("Aamir", "3"),
    ("Aarav", "3"),
    ("aaren", "3"),
    ("aarika", "3"),
    ("Adad", "3")
]

data2 = [
    ("Aaden", "3"),
    ("Aamir", "3"),
    ("Aarav", "3"),
    ("aaren", "3"),
    ("aarika", "3"),
    ("Aaron", "3"),
    ("Abaddon", "3"),
    ("abagael", "3"),
    ("abagail", "3"),
    ("Abatu", "3"),
    ("abbe", "3"),
    ("abbey", "3"),
    ("abbi", "3"),
    ("abbie", "3"),
    ("Abbot", "3"),
    ("Abbott", "3"),
    ("abby", "3"),
    ("abbye", "3"),
    ("Abdel", "3"),
    ("Abdiel", "3"),
    ("Abdul", "3"),
    ("Abdulkarim", "3"),
    ("Abdullah", "3"),
    ("Abduxuel", "3"),
    ("Abe", "3"),
    ("Abel", "3"),
    ("Abelard", "1"),
    ("abigael", "3"),
    ("abigail", "3"),
    ("abigale", "3"),
    ("Abigar", "3"),
    ("Abigor", "3"),
    ("Abner", "4"),
    ("abra", "3"),
    ("Abraham", "3"),
    ("Abram", "3"),
    ("Acacia", "3"),
    ("Ace", "3"),
    ("Achilles", "3"),
    ("Aclahayr", "3"),
    ("ada", "6"),
    ("awdad", "3"),
    ("awad", "3"),
    ("Ainiond", "3"),
    ("Adww", "3"),
    ("james","3")
]

match = []
no_match = []

for item1 in data1:
    for item2 in data2:
        if item1[0] == item2[0]:
            match.append(item1)
        else:
            no_match.append(item1)

print('First List Count: {}'.format(len(data1)))
print('Second List Count: {}'.format(len(data2)))

print('Match Count: {}'.format(len(match)))
print('No Match Count: {}'.format(len(no_match)))
```

<p>Output:</p>

```First List Count: 6
Second List Count: 46
Match Count: 5
No Match Count: 271
```

答:
Match and Non-Match items from First List as comparing with Second List

```<code>match_items1=[]
no_match_items1=[]

for temp_data1 in data1:
    for temp_data2 in data2:
        if temp_data2[0].strip() == temp_data1[0].strip():
            match_items1.append(temp_data1)
            break
    else:
        no_match_items1.append(temp_data1)

output: For Match items [('Aaden', '3'), ('Aamir', '3'), ('Aarav', '3'), ('aaren', '3'), ('aarika', '3')]
        For Non-Match items [('Adad', '3')]
</code>```

Match and Non-Match items from Second List as comparing with First List

```<code>match_items2=[]
no_match_items2=[]

for temp_data2 in data2:
    for temp_data1 in data1:
        if temp_data1[0].strip() == temp_data2[0].strip():
            match_items2.append(temp_data2)
            break
    else:
        no_match_items2.append(temp_data2)

output: For Match items [('Aaden', '3'), ('Aamir', '3'), ('Aarav', '3'), ('aaren', '3'), ('aarika', '3')]
        For Non-Match items [('Aaron', '3'), ('Abaddon', '3'), ('abagael', '3'), ('abagail', '3'), ('Abatu', '3'), ('abbe', '3'), ('abbey', '3'), ('abbi', '3'), ('abbie', '3'), ('Abbot', '3'), ('Abbott', '3'), ('abby', '3'), ('abbye', '3'), ('Abdel', '3'), ('Abdiel', '3'), ('Abdul', '3'), ('Abdulkarim', '3'), ('Abdullah', '3'), ('Abduxuel', '3'), ('Abe', '3'), ('Abel', '3'), ('Abelard', '1'), ('abigael', '3'), ('abigail', '3'), ('abigale', '3'), ('Abigar', '3'), ('Abigor', '3'), ('Abner', '4'), ('abra', '3'), ('Abraham', '3'), ('Abram', '3'), ('Acacia', '3'), ('Ace', '3'), ('Achilles', '3'), ('Aclahayr', '3'), ('ada', '6'), ('awdad', '3'), ('awad', '3'), ('Ainiond', '3'), ('Adww', '3'), ('james', '3')]
</code>```

Body:
I am attempting to iterate over two lists of tuples and am looking for matches. I want to generate two lists of tuples as output: one containing matches (tuples whose first value appears in both lists) and one with non-matches (tuples whose first value appears in one list, but not in the other).

I tried implementing this by iterating over the two lists in a nested loop and comparing the tuples there. However, when I do that, the resulting "no match" list also contains tuples that do match, and also appear in the "match" list.

I'm trying to avoid this. There must be a better way to do this. Any help would be appreciated.

Below is an example:

data1 = [
    ("Aaden", "3"),
    ("Aamir", "3"),
    ("Aarav", "3"),
    ("aaren", "3"),
    ("aarika", "3"),
    ("Adad", "3")
]

data2 = [
    ("Aaden", "3"),
    ("Aamir", "3"),
    ("Aarav", "3"),
    ("aaren", "3"),
    ("aarika", "3"),
    ("Aaron", "3"),
    ("Abaddon", "3"),
    ("abagael", "3"),
    ("abagail", "3"),
    ("Abatu", "3"),
    ("abbe", "3"),
    ("abbey", "3"),
    ("abbi", "3"),
    ("abbie", "3"),
    ("Abbot", "3"),
    ("Abbott", "3"),
    ("abby", "3"),
    ("abbye", "3"),
    ("Abdel", "3"),
    ("Abdiel", "3"),
    ("Abdul", "3"),
    ("Abdulkarim", "3"),
    ("Abdullah", "3"),
    ("Abduxuel", "3"),
    ("Abe", "3"),
    ("Abel", "3"),
    ("Abelard", "1"),
    ("abigael", "3"),
    ("abigail", "3"),
    ("abigale", "3"),
    ("Abigar", "3"),
    ("Abigor", "3"),
    ("Abner", "4"),
    ("abra", "3"),
    ("Abraham", "3"),
    ("Abram", "3"),
    ("Acacia", "3"),
    ("Ace", "3"),
    ("Achilles", "3"),
    ("Aclahayr", "3"),
    ("ada", "6"),
    ("awdad", "3"),
    ("awad", "3"),
    ("Ainiond", "3"),
    ("Adww", "3"),
    ("james","3")
]

match = []
no_match = []

for item1 in data1:
    for item2 in data2:
        if item1[0] == item2[0]:
            match.append(item1)
        else:
            no_match.append(item1)

print('First List Count: {}'.format(len(data1)))
print('Second List Count: {}'.format(len(data2)))

print('Match Count: {}'.format(len(match)))
print('No Match Count: {}'.format(len(no_match)))

Output:

First List Count: 6
Second List Count: 46
Match Count: 5
No Match Count: 271

Body:
Match and Non-Match items from First List as comparing with Second List

match_items1=[]
no_match_items1=[]

for temp_data1 in data1:
    for temp_data2 in data2:
        if temp_data2[0].strip() == temp_data1[0].strip():
            match_items1.append(temp_data1)
            break
    else:
        no_match_items1.append(temp_data1)

output: For Match items [('Aaden', '3'), ('Aamir', '3'), ('Aarav', '3'), ('aaren', '3'), ('aarika', '3')]
        For Non-Match items [('Adad', '3')]

Match and Non-Match items from Second List as comparing with First List

match_items2=[]
no_match_items2=[]

for temp_data2 in data2:
    for temp_data1 in data1:
        if temp_data1[0].strip() == temp_data2[0].strip():
            match_items2.append(temp_data2)
            break
    else:
        no_match_items2.append(temp_data2)

output: For Match items [('Aaden', '3'), ('Aamir', '3'), ('Aarav', '3'), ('aaren', '3'), ('aarika', '3')]
        For Non-Match items [('Aaron', '3'), ('Abaddon', '3'), ('abagael', '3'), ('abagail', '3'), ('Abatu', '3'), ('abbe', '3'), ('abbey', '3'), ('abbi', '3'), ('abbie', '3'), ('Abbot', '3'), ('Abbott', '3'), ('abby', '3'), ('abbye', '3'), ('Abdel', '3'), ('Abdiel', '3'), ('Abdul', '3'), ('Abdulkarim', '3'), ('Abdullah', '3'), ('Abduxuel', '3'), ('Abe', '3'), ('Abel', '3'), ('Abelard', '1'), ('abigael', '3'), ('abigail', '3'), ('abigale', '3'), ('Abigar', '3'), ('Abigor', '3'), ('Abner', '4'), ('abra', '3'), ('Abraham', '3'), ('Abram', '3'), ('Acacia', '3'), ('Ace', '3'), ('Achilles', '3'), ('Aclahayr', '3'), ('ada', '6'), ('awdad', '3'), ('awad', '3'), ('Ainiond', '3'), ('Adww', '3'), ('james', '3')]


问:
Get the Text of AutoCAD AcDbText object with python

What is the best way, in python, to get the text of an AcDbText object?

I am working in python, win32com, and autoCAD.  I would like to be able to do the following, via a python program:

Place objects into a selection set

Determine which are AcDbText objects

From those, extract the text and then delete.

I can do the first two things just fine. However, assuming textObj is the correct type of object, the following achieves half the remaining-- t will contain the text desired as a str:

```<code>t = textObj.copy().fieldcode()
</code>```

Problem 1:  As the code implies, this creates a copy of the object, right there in the drawing, and does not seem to provide a way to identify it later for deletion.

Problem 2:  The original object resists deletion from the selection set.  If selection is the selection set, then no variation of selection.clear(), selection.delete(), or selection.erase() does anything.  (I have checked the length of selection set before and after the fieldcode() invocation-- the number of objects remains the same.)

I am puzzled that there does not seem to be a way to prize the text out of the object without copying it.  What am I missing?

Per question in comments to an answer, the output of pprint(dir(textObj)) is:

```<code>['AddRef',
'Application',
'ArrayPolar',
'ArrayRectangular',
'Copy',
'Database',
'Delete',
'Document',
'EntityName',
'EntityTransparency',
'EntityType',
'Erase',
'GetBoundingBox',
'GetExtensionDictionary',
'GetIDsOfNames',
'GetTypeInfo',
'GetTypeInfoCount',
'GetXData',
'Handle',
'HasExtensionDictionary',
'Highlight',
'Hyperlinks',
'IntersectWith',
'Invoke',
'Layer',
'Linetype',
'LinetypeScale',
'Lineweight',
'Material',
'Mirror',
'Mirror3D',
'Move',
'ObjectID',
'ObjectName',
'OwnerID',
'PlotStyleName',
'QueryInterface',
'Release',
'Rotate',
'Rotate3D',
'ScaleEntity',
'SetXData',
'TransformBy',
'TrueColor',
'Update',
'Visible',
'_AddRef',
'_GetIDsOfNames',
'_GetTypeInfo',
'_IAcadEntity__com_ArrayPolar',
'_IAcadEntity__com_ArrayRectangular',
'_IAcadEntity__com_Copy',
'_IAcadEntity__com_GetBoundingBox',
'_IAcadEntity__com_Highlight',
'_IAcadEntity__com_IntersectWith',
'_IAcadEntity__com_Mirror',
'_IAcadEntity__com_Mirror3D',
'_IAcadEntity__com_Move',
'_IAcadEntity__com_Rotate',
'_IAcadEntity__com_Rotate3D',
'_IAcadEntity__com_ScaleEntity',
'_IAcadEntity__com_TransformBy',
'_IAcadEntity__com_Update',
'_IAcadEntity__com__get_EntityName',
'_IAcadEntity__com__get_EntityTransparency',
'_IAcadEntity__com__get_EntityType',
'_IAcadEntity__com__get_Hyperlinks',
'_IAcadEntity__com__get_Layer',
'_IAcadEntity__com__get_Linetype',
'_IAcadEntity__com__get_LinetypeScale',
'_IAcadEntity__com__get_Lineweight',
'_IAcadEntity__com__get_Material',
'_IAcadEntity__com__get_PlotStyleName',
'_IAcadEntity__com__get_TrueColor',
'_IAcadEntity__com__get_Visible',
'_IAcadEntity__com__get_color',
'_IAcadEntity__com__set_EntityTransparency',
'_IAcadEntity__com__set_Layer',
'_IAcadEntity__com__set_Linetype',
'_IAcadEntity__com__set_LinetypeScale',
'_IAcadEntity__com__set_Lineweight',
'_IAcadEntity__com__set_Material',
'_IAcadEntity__com__set_PlotStyleName',
'_IAcadEntity__com__set_TrueColor',
'_IAcadEntity__com__set_Visible',
'_IAcadEntity__com__set_color',
'_IAcadObject__com_Delete',
'_IAcadObject__com_Erase',
'_IAcadObject__com_GetExtensionDictionary',
'_IAcadObject__com_GetXData',
'_IAcadObject__com_SetXData',
'_IAcadObject__com__get_Application',
'_IAcadObject__com__get_Database',
'_IAcadObject__com__get_Document',
'_IAcadObject__com__get_Handle',
'_IAcadObject__com__get_HasExtensionDictionary',
'_IAcadObject__com__get_ObjectID',
'_IAcadObject__com__get_ObjectName',
'_IAcadObject__com__get_OwnerID',
'_IDispatch__com_GetIDsOfNames',
'_IDispatch__com_GetTypeInfo',
'_IDispatch__com_GetTypeInfoCount',
'_IDispatch__com_Invoke',
'_IUnknown__com_AddRef',
'_IUnknown__com_QueryInterface',
'_IUnknown__com_Release',
'_Invoke',
'_QueryInterface',
'_Release',
'__bool__',
'__class__',
'__cmp__',
'__com_interface__',
'__ctypes_from_outparam__',
'__del__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattr__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__map_case__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setstate__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_b_base_',
'_b_needsfree_',
'_case_insensitive_',
'_compointer_base__get_value',
'_idlflags_',
'_iid_',
'_invoke',
'_methods_',
'_needs_com_addref_',
'_objects',
'_type_',
'color',
'from_param',
'value']
</code>```

答:
Assuming textObj is either a single-line text object (AcDbText) or multiline text object (AcDbMText), then you should be able to obtain the text content using the TextString property, e.g.:

```<code>t = textObj.TextString
</code>```

Note that the methods clear() & delete() when invoked on an ActiveX SelectionSet object do not delete the objects it contains, but rather remove the objects from the SelectionSet and delete the SelectionSet object respectively. Though, the erase() method should successfully erase all objects contained in the SelectionSet.

Though, to delete an object, you would typically just invoke the delete() method on the object itself, e.g.:

```<code>textObj.Delete()
</code>```

Body:
What is the best way, in python, to get the text of an AcDbText object?

I am working in python, win32com, and autoCAD.  I would like to be able to do the following, via a python program:

Place objects into a selection set

Determine which are AcDbText objects

From those, extract the text and then delete.

I can do the first two things just fine. However, assuming textObj is the correct type of object, the following achieves half the remaining-- t will contain the text desired as a str:

t = textObj.copy().fieldcode()

Problem 1:  As the code implies, this creates a copy of the object, right there in the drawing, and does not seem to provide a way to identify it later for deletion.

Problem 2:  The original object resists deletion from the selection set.  If selection is the selection set, then no variation of selection.clear(), selection.delete(), or selection.erase() does anything.  (I have checked the length of selection set before and after the fieldcode() invocation-- the number of objects remains the same.)

I am puzzled that there does not seem to be a way to prize the text out of the object without copying it.  What am I missing?

Per question in comments to an answer, the output of pprint(dir(textObj)) is:

['AddRef',
'Application',
'ArrayPolar',
'ArrayRectangular',
'Copy',
'Database',
'Delete',
'Document',
'EntityName',
'EntityTransparency',
'EntityType',
'Erase',
'GetBoundingBox',
'GetExtensionDictionary',
'GetIDsOfNames',
'GetTypeInfo',
'GetTypeInfoCount',
'GetXData',
'Handle',
'HasExtensionDictionary',
'Highlight',
'Hyperlinks',
'IntersectWith',
'Invoke',
'Layer',
'Linetype',
'LinetypeScale',
'Lineweight',
'Material',
'Mirror',
'Mirror3D',
'Move',
'ObjectID',
'ObjectName',
'OwnerID',
'PlotStyleName',
'QueryInterface',
'Release',
'Rotate',
'Rotate3D',
'ScaleEntity',
'SetXData',
'TransformBy',
'TrueColor',
'Update',
'Visible',
'_AddRef',
'_GetIDsOfNames',
'_GetTypeInfo',
'_IAcadEntity__com_ArrayPolar',
'_IAcadEntity__com_ArrayRectangular',
'_IAcadEntity__com_Copy',
'_IAcadEntity__com_GetBoundingBox',
'_IAcadEntity__com_Highlight',
'_IAcadEntity__com_IntersectWith',
'_IAcadEntity__com_Mirror',
'_IAcadEntity__com_Mirror3D',
'_IAcadEntity__com_Move',
'_IAcadEntity__com_Rotate',
'_IAcadEntity__com_Rotate3D',
'_IAcadEntity__com_ScaleEntity',
'_IAcadEntity__com_TransformBy',
'_IAcadEntity__com_Update',
'_IAcadEntity__com__get_EntityName',
'_IAcadEntity__com__get_EntityTransparency',
'_IAcadEntity__com__get_EntityType',
'_IAcadEntity__com__get_Hyperlinks',
'_IAcadEntity__com__get_Layer',
'_IAcadEntity__com__get_Linetype',
'_IAcadEntity__com__get_LinetypeScale',
'_IAcadEntity__com__get_Lineweight',
'_IAcadEntity__com__get_Material',
'_IAcadEntity__com__get_PlotStyleName',
'_IAcadEntity__com__get_TrueColor',
'_IAcadEntity__com__get_Visible',
'_IAcadEntity__com__get_color',
'_IAcadEntity__com__set_EntityTransparency',
'_IAcadEntity__com__set_Layer',
'_IAcadEntity__com__set_Linetype',
'_IAcadEntity__com__set_LinetypeScale',
'_IAcadEntity__com__set_Lineweight',
'_IAcadEntity__com__set_Material',
'_IAcadEntity__com__set_PlotStyleName',
'_IAcadEntity__com__set_TrueColor',
'_IAcadEntity__com__set_Visible',
'_IAcadEntity__com__set_color',
'_IAcadObject__com_Delete',
'_IAcadObject__com_Erase',
'_IAcadObject__com_GetExtensionDictionary',
'_IAcadObject__com_GetXData',
'_IAcadObject__com_SetXData',
'_IAcadObject__com__get_Application',
'_IAcadObject__com__get_Database',
'_IAcadObject__com__get_Document',
'_IAcadObject__com__get_Handle',
'_IAcadObject__com__get_HasExtensionDictionary',
'_IAcadObject__com__get_ObjectID',
'_IAcadObject__com__get_ObjectName',
'_IAcadObject__com__get_OwnerID',
'_IDispatch__com_GetIDsOfNames',
'_IDispatch__com_GetTypeInfo',
'_IDispatch__com_GetTypeInfoCount',
'_IDispatch__com_Invoke',
'_IUnknown__com_AddRef',
'_IUnknown__com_QueryInterface',
'_IUnknown__com_Release',
'_Invoke',
'_QueryInterface',
'_Release',
'__bool__',
'__class__',
'__cmp__',
'__com_interface__',
'__ctypes_from_outparam__',
'__del__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattr__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__map_case__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setstate__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_b_base_',
'_b_needsfree_',
'_case_insensitive_',
'_compointer_base__get_value',
'_idlflags_',
'_iid_',
'_invoke',
'_methods_',
'_needs_com_addref_',
'_objects',
'_type_',
'color',
'from_param',
'value']

Body:
Assuming textObj is either a single-line text object (AcDbText) or multiline text object (AcDbMText), then you should be able to obtain the text content using the TextString property, e.g.:

t = textObj.TextString

Note that the methods clear() & delete() when invoked on an ActiveX SelectionSet object do not delete the objects it contains, but rather remove the objects from the SelectionSet and delete the SelectionSet object respectively. Though, the erase() method should successfully erase all objects contained in the SelectionSet.

Though, to delete an object, you would typically just invoke the delete() method on the object itself, e.g.:

textObj.Delete()


问:
Duplicate/Copy Planner Plan within same Team
I have a template for a plan that my team uses for new events all year around. I need a way to duplicate this Planner plan as a new Planner tab in Teams.

Using Planner's own Copy/Duplicate feature will create a NEW group and a new Team.

Looking at Microsoft Teams and Planners UserVoice I can see that it is currently not possible:

https://microsoftteams.uservoice.com/forums/555103-public/suggestions/35387329-add-a-planner-tab-using-an-existing-plan-problem

https://planner.uservoice.com/forums/330525-microsoft-planner-feedback-forum/suggestions/37078834-copy-plan-to-existing-group

答:
Using Power Automate (Microsoft Flow) we can create a listener for a new message in a team channel that checks for a specific message. If this message contains a notification about the creation of a new tab, and use a prefix for this new tab to designate the planner template we can automatically fill a new empty planner tab with the contents of a template plan.

Usage:

Create a Planner template plan directly in Planner

Import the Power Automate script in your Power Automate (this works with free Power Automations)

Set the Power Automate Script first variable to the prefix of your tabs (i.e. "Event:")

Make sure all the correct variables in the Power Automate script reference the correct Teams channel, and the correct reference for the Planner Template plan.

Goto the teams channel that you want to work with and create a new tab with a new Planner Plan, make sure

That you start the tab/plan name with your selected prefix ("Event:")

That you select "Post to channel about the creation of this Tab"

Notice how the plan is automatically populated with the tasks and buckets from the template plan after a few moments.

The PowerAutomate script can be downloaded here: https://content.zeal.global/shared/AutomaticCopyTeamsPlanner_20200215111249.zip


问:
Is it true that in multiprocessing, each process gets it's own GIL in CPython? How different is that from creating new runtimes?
Are there any caveats to it? I have a few questions related to it.

How costly is it to create more GILs? Is it any different from creating a separate python runtime? Once a new GIL is created, will it create everything (objects, variables, stack, heap) from scratch as required in that process or a copy of everything in the present heap and the stack is created? (Garbage collection would malfunction if they are working on same objects.) Are the pieces of code being executed also copied to new CPU cores? Also can i relate one GIL to one CPU core?

Now copying things is a fairly CPU intensive task (correct me if I am wrong), what would be the threshold to decide whether to go for multiprocessing?

PS: I am talking about CPython but please feel free to extend the answer to whatever you feel is necessary.

答:
The short answer to the first title question is: Yes. Each process has its own Global Interpret Lock. After that, it gets complicated and not really as much a Python matter as it is a question for your underlying OS.

On Linux, it should be cheaper to spawn new processes through multiprocessing rather than starting a new Python interpreter (from scratch):

you fork() the parent process (side note: clone() is actually used these days), the child already has your code and starts with a copy of parents address space -> since you are actually spawning another instance of your running process no need to execve() (and all the overhead associated with that) and repopulate its content.

actually when we say copy of the address space, it actually does not get all copied, but would rather use copy-on-write; so unless you modified it, you do not need to copy it at all.

For that reason  my gut feeling would be, multiprocessing would almost always be more efficient than starting a completely new Python interpreter from scratch. After all, even you started a new interpreter (presumably from the running process), it first performs the fork()/clone() including "copy" of the parent's address space before moving onto execve().

But really this may vary and depends on how your underlying OS handles creation of new processes as well as its memory management.


问:
Maven 3 and JUnit 4 compilation problem: package org.junit does not exist
I am trying to build a simple Java project with Maven. In my pom-file I declare JUnit 4.8.2 as the only dependency. Still Maven insists on using JUnit version 3.8.1. How do I fix it?

The problem manifests itself in a compilation failure: "package org.junit does not exist". This is because of the import statement in my source code. The correct package name in JUnit 4.* is org.junit.* while in version 3.* it is junit.framework.*

I think I have found documentation on the root of the problem on http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html but the advice there seems to be meant for Maven experts. I did not understand what to do.

答: @Dennis Roberts: You were absolutely right: My test class was located in src/main/java. Also the value of the "scope" element in the POM for JUnit was "test", although that is how it is supposed to be. The problem was that I had been sloppy when creating the test class in Eclipse, resulting in it being created in src/main/java insted of src/test/java. This became easier to see in Eclipse's Project Explorer view after running "mvn eclipse:eclipse", but your comment was what made me see it first. Thanks.</p>


问:
How to increment a variable in assembly?
I need to create an assembly program that prints:
0
01
012
0123
...
0123456789
It seems like I need to create a variable that I can increment that stops the code once I get to it so I can go back and start again, this is my attempt so far. I can already get it to print 0123456789 ten times but it's getting it to count up is the problem.
Here is that code

```<code>.MODEL MEDIUM
.STACK
.DATA
number DB 1
.CODE
.STARTUP
 mov bl,10
nextline: mov dl,'0' ; '0' is ASCII 48
nextchar: mov ah,02h ; print ASCII char in dl
 int 021h
 inc dl
 cmp dl,':';‘:' is ASCII for 10
 jnz nextchar

 push dx ; save value of dl and dh on stack
 mov ah,02h ; print ASCII char in dl
 mov dl,13 ; carriage return (move to start of line)
 int 021h
 mov dl,10 ; line feed (next line)
int 021h
 pop dx ; restore value in dl (and dh)
 dec bl
 jnz nextline
 .EXIT
END
</code>```

And here is my attempt at making it count up, perhaps I don't fully understand how variables work yet

```<code>.MODEL MEDIUM
.STACK
.DATA
number DB '1' ;changed from 1 to '1'
.CODE
.STARTUP
 mov bl,10
nextline: mov dl,'0' ; '0' is ASCII 48
nextchar: mov ah,02h ; print ASCII char in dl
 int 021h
 inc dl
 cmp dl,number;‘:' is ASCII for 10
 jnz nextchar

 push dx ; save value of dl and dh on stack
 mov ah,02h ; print ASCII char in dl
 mov dl,13 ; carriage return (move to start of line)
 int 021h
 mov dl,10 ; line feed (next line)
int 021h
 pop dx ; restore value in dl (and dh)
 dec bl
 add number,1 ;moved to outer loop
 jnz nextline
 .EXIT
END
</code>```

答:
First off, do yourself a favour and change the name of your variable from number to character since that's what it is now that you've followed the advice by others.

With the help of Michael you've already fixed a few things to your code. What's still posing problems is next part of the code:

```<code>add character,1 ;moved to outer loop
jnz nextline
</code>```

As written, the outer loop will stop when the byte-sized character increments from the value 255 to 0.

You need to limit the raising of character; up to a maximum of '9'.

You can use the cmp instruction for that:

```<code>add character, 1
cmp character, '9'
jbe nextline
</code>```

The jbe instruction will keep jumping back (looping) for as long as the character is below or equal to '9'.

It also avoids using ugly constructs like:

```<code>‘:' is ASCII for 10
</code>```

There's no more need for a counter in BL and preserving DX around the newline part is redundant.

This is your revised code:

```<code>.MODEL MEDIUM
.STACK
.DATA
character DB '0'
.CODE
.STARTUP
 mov ah, 02h         ; print ASCII char in dl
nextline:
 mov dl, '0'
nextchar:
 int 21h
 inc dl
 cmp dl, character
 jbe nextchar

 mov dl, 13          ; carriage return
 int 21h
 mov dl, 10          ; line feed
 int 21h
 add character, 1
 cmp character, '9'
 jbe nextline
.EXIT
END
</code>```

Take note that character now starts at '0' (and not '1').

Body:
I need to create an assembly program that prints:
0
01
012
0123
...
0123456789
It seems like I need to create a variable that I can increment that stops the code once I get to it so I can go back and start again, this is my attempt so far. I can already get it to print 0123456789 ten times but it's getting it to count up is the problem.
Here is that code

.MODEL MEDIUM
.STACK
.DATA
number DB 1
.CODE
.STARTUP
 mov bl,10
nextline: mov dl,'0' ; '0' is ASCII 48
nextchar: mov ah,02h ; print ASCII char in dl
 int 021h
 inc dl
 cmp dl,':';‘:' is ASCII for 10
 jnz nextchar

 push dx ; save value of dl and dh on stack
 mov ah,02h ; print ASCII char in dl
 mov dl,13 ; carriage return (move to start of line)
 int 021h
 mov dl,10 ; line feed (next line)
int 021h
 pop dx ; restore value in dl (and dh)
 dec bl
 jnz nextline
 .EXIT
END

And here is my attempt at making it count up, perhaps I don't fully understand how variables work yet

.MODEL MEDIUM
.STACK
.DATA
number DB '1' ;changed from 1 to '1'
.CODE
.STARTUP
 mov bl,10
nextline: mov dl,'0' ; '0' is ASCII 48
nextchar: mov ah,02h ; print ASCII char in dl
 int 021h
 inc dl
 cmp dl,number;‘:' is ASCII for 10
 jnz nextchar

 push dx ; save value of dl and dh on stack
 mov ah,02h ; print ASCII char in dl
 mov dl,13 ; carriage return (move to start of line)
 int 021h
 mov dl,10 ; line feed (next line)
int 021h
 pop dx ; restore value in dl (and dh)
 dec bl
 add number,1 ;moved to outer loop
 jnz nextline
 .EXIT
END

Body:
First off, do yourself a favour and change the name of your variable from number to character since that's what it is now that you've followed the advice by others.

With the help of Michael you've already fixed a few things to your code. What's still posing problems is next part of the code:

add character,1 ;moved to outer loop
jnz nextline

As written, the outer loop will stop when the byte-sized character increments from the value 255 to 0.

You need to limit the raising of character; up to a maximum of '9'.

You can use the cmp instruction for that:

add character, 1
cmp character, '9'
jbe nextline

The jbe instruction will keep jumping back (looping) for as long as the character is below or equal to '9'.

It also avoids using ugly constructs like:

‘:' is ASCII for 10

There's no more need for a counter in BL and preserving DX around the newline part is redundant.

This is your revised code:

.MODEL MEDIUM
.STACK
.DATA
character DB '0'
.CODE
.STARTUP
 mov ah, 02h         ; print ASCII char in dl
nextline:
 mov dl, '0'
nextchar:
 int 21h
 inc dl
 cmp dl, character
 jbe nextchar

 mov dl, 13          ; carriage return
 int 21h
 mov dl, 10          ; line feed
 int 21h
 add character, 1
 cmp character, '9'
 jbe nextline
.EXIT
END

Take note that character now starts at '0' (and not '1').


问:
how to use @oneToMany when i need to use two column
i cannot succeed to work it out when i trying to do something like that:

```<code>    @OneToMany(mappedBy = "company", fetch = FetchType.EAGER)
private List<Coupon> coupons;
@OneToMany(mappedBy = "company", fetch = FetchType.EAGER)
private List<Employee> employes;
</code>```

i keep getting this error massage:

```<code>WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'companyDBDAO': Unsatisfied dependency expressed through field 'getlocalSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getLocalSessionFactory' defined in config.SpringConfig: Invocation of init method failed; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [beans.Company.coupons, beans.Company.employes]
</code>```

i am new to this and its only work if i delete one of them..

答: Remove fetchType = FetchType.EAGER and place @LazyCollection(LazyCollectionOption.FALSE) on both collections.

Body:
i cannot succeed to work it out when i trying to do something like that:

    @OneToMany(mappedBy = "company", fetch = FetchType.EAGER)
private List<Coupon> coupons;
@OneToMany(mappedBy = "company", fetch = FetchType.EAGER)
private List<Employee> employes;

i keep getting this error massage:

WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'companyDBDAO': Unsatisfied dependency expressed through field 'getlocalSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getLocalSessionFactory' defined in config.SpringConfig: Invocation of init method failed; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [beans.Company.coupons, beans.Company.employes]

i am new to this and its only work if i delete one of them..


问:
Python Regex - Replace specific word (without hash) with another word
I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

```<code>x = "112-224"
y = "hello"
z = "This is the number 112-224 not #112-224"
</code>```

When I do re.sub(r'\b' + x + r'\b', y, z) I am getting 'This is the number hello not #hello'. So basically doesn't work with this regex. I am really not good with this regex stuff. What's the right way to do that? so, i can get This is the number hello not #112-224.

答:
How about this:

```<code>pattern = r'(?<=[\w\s\n\r\^])'+x+r'(?=[\w\s\n\r$])'
</code>```

With the complete code being:

```<code>x = "112-234"
y = "hello"
z = "112-234this is 112-234 not #112-234"

pattern = r'(?<=[\w\s\n\r\^])'+x+r'(?=[\w\s\n\r$])'
</code>```

Here, I'm using a positive lookbehind and a positive lookahead in regex, which you can learn more about here

The regex states the match should be preceded by a word character, space, newline or the start of the line, and should be followed by a space, word character newline or the end of the line.

Note: Don't forget to escape out the carat ^ in the lookbehind, otherwise you'll end up negating everything in the square brackets.

Body:
I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

x = "112-224"
y = "hello"
z = "This is the number 112-224 not #112-224"

When I do re.sub(r'\b' + x + r'\b', y, z) I am getting 'This is the number hello not #hello'. So basically doesn't work with this regex. I am really not good with this regex stuff. What's the right way to do that? so, i can get This is the number hello not #112-224.

Body:
How about this:

pattern = r'(?<=[\w\s\n\r\^])'+x+r'(?=[\w\s\n\r$])'

With the complete code being:

x = "112-234"
y = "hello"
z = "112-234this is 112-234 not #112-234"

pattern = r'(?<=[\w\s\n\r\^])'+x+r'(?=[\w\s\n\r$])'

Here, I'm using a positive lookbehind and a positive lookahead in regex, which you can learn more about here

The regex states the match should be preceded by a word character, space, newline or the start of the line, and should be followed by a space, word character newline or the end of the line.

Note: Don't forget to escape out the carat ^ in the lookbehind, otherwise you'll end up negating everything in the square brackets.


问:
How do i increase the integer field when comment is liked
I have a comment model, i want to increase an integer field when a comment is liked. How do i create a comment like for each comment made by user. I attached an image of what i tried, but still do not increase the integer field.

enter image description here

```<code>class Comments (models.Model):
    comment_post = models.TextField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
    commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments', null=True, blank=True)
    comment_likes = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

def comments(request, id):
    post = get_object_or_404(Image,id=id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.commented_image = post
            comment.save()
            return redirect('site:comments', id=id)
    else:
        form = CommentForm()
    all_comments = Comments.objects.filter(
        author=request.user.id,
        commented_image=post,
    )
    images = Image.objects.filter(
        imageuploader_profile=request.user.id,
        image_caption=post,
    )
    context = {
        'form': form,
        'all_comments': all_comments,
        'images': images,
    }
    return render(request,'comments.html', context)
</code>```

答:
You probably want to build a new endpoint that handles likes of the comment

```<code>/comment/{id}/like
</code>```

include the logic of get get_or_404
once you get the object set it's like count to

```<code>comment.comment_likes +=1
</code>```

you can also fo the unlike with the reversed logic

Body:
I have a comment model, i want to increase an integer field when a comment is liked. How do i create a comment like for each comment made by user. I attached an image of what i tried, but still do not increase the integer field.

enter image description here

class Comments (models.Model):
    comment_post = models.TextField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
    commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments', null=True, blank=True)
    comment_likes = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

def comments(request, id):
    post = get_object_or_404(Image,id=id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.commented_image = post
            comment.save()
            return redirect('site:comments', id=id)
    else:
        form = CommentForm()
    all_comments = Comments.objects.filter(
        author=request.user.id,
        commented_image=post,
    )
    images = Image.objects.filter(
        imageuploader_profile=request.user.id,
        image_caption=post,
    )
    context = {
        'form': form,
        'all_comments': all_comments,
        'images': images,
    }
    return render(request,'comments.html', context)

Body:
You probably want to build a new endpoint that handles likes of the comment

/comment/{id}/like

include the logic of get get_or_404
once you get the object set it's like count to

comment.comment_likes +=1

you can also fo the unlike with the reversed logic


问:
Fixing bad XML file (eg. unescaped & etc.)
I got an XML file from 3rd party that I must import in my app, and XML had elements with unescaped & in inner text, and they don't wont to fix that ! So my question is what is the best way to deal with this problem ?

This XML is pretty big and that fix has to be fast, my first solution is just replace & character with ampersand but really I don't like this "solution" for obvious reasons. I don't know how to use XmlStringReader with such XML because is throws exception on such lines, so I can't use HtmlEncode on inner text. I tried to set XmlTextReader Settings.CheckCharacters to false but no result.

Here is the sample, & is in  element, and in that field can be anything that can be in some company name, so my replace fix maybe don't work for some other company name, I would like to use HtmlEncode somehow, but only on inner text of course.

```<code><komitent ID="001398">
  <sifra>001398</sifra>
  <redni_broj>001398</redni_broj>
  <naziv>LJUBICA & ŽARKO</naziv>
  <adresa1>Odvrtnica 27</adresa1>
  <adresa2></adresa2>
  <drzava>HRVATSKA</drzava>
  <grad>Zagreb</grad>
</komitent>
</code>```

答: Start by changing your mindset. The input is not XML, so don't call it XML. Don't even use "xml" to tag your questions about it. The fact that it isn't XML means that you can't use any XML tools with it, and you can't get any of the benefits of XML data interchange. You're dealing with a proprietary format that comes without a specification and without any tools. Treat it as you would any other proprietary format - try to discover a specification for what you are getting, and write a parser for it.</p>

Body:
I got an XML file from 3rd party that I must import in my app, and XML had elements with unescaped & in inner text, and they don't wont to fix that ! So my question is what is the best way to deal with this problem ?

This XML is pretty big and that fix has to be fast, my first solution is just replace & character with ampersand but really I don't like this "solution" for obvious reasons. I don't know how to use XmlStringReader with such XML because is throws exception on such lines, so I can't use HtmlEncode on inner text. I tried to set XmlTextReader Settings.CheckCharacters to false but no result.

Here is the sample, & is in  element, and in that field can be anything that can be in some company name, so my replace fix maybe don't work for some other company name, I would like to use HtmlEncode somehow, but only on inner text of course.

<komitent ID="001398">
  <sifra>001398</sifra>
  <redni_broj>001398</redni_broj>
  <naziv>LJUBICA & ŽARKO</naziv>
  <adresa1>Odvrtnica 27</adresa1>
  <adresa2></adresa2>
  <drzava>HRVATSKA</drzava>
  <grad>Zagreb</grad>
</komitent>


问:
Recursion Depth Exceeded, pickle and BeautifulSoup
I want to pickle html from websites. I save the html to a list and try to pickle it. An example of one such list is the html from brckhmptn.com/tour. Of course the html from this site is a lot, is that my error? The whole script is there but the error is called in the last few lines. I'm using Python 3.6.1</p>

```<code>Traceback (most recent call last):
  File "./showNotifier.py", line 128, in <module>
    scrape_html(combinedUrls)
  File "./showNotifier.py", line 125, in scrape_html
    pickle.dump(sites, hf)
RecursionError: maximum recursion depth exceeded

#!/home/steph/unix/miniconda3/bin/python
'''
By Stephen Wist
stphnwist@gmail.com
ShowNotifier
---------------------
script takes cmd line args to:
    indiacte URLS to add
default behaviour is checking if new shows were added
'''
import requests
import pickle
import sys
import argparse
import os
import urllib
from bs4 import BeautifulSoup

urlFile = "urls"
htmlFile = "htmls"

# take in cmd line args
parseArgs =  argparse.ArgumentParser(description='Add URLs to cache.')
parseArgs.add_argument('urls', type=str, nargs='*', help='URLs to be added.')

# assign cmd line args to urls.urls
urls = parseArgs.parse_args()

# this function makes sure all files are in place
def status_report():

    # this should be the case only the first time the
    # script is run
    if (os.path.getsize(urlFile) == 0):
        urlFileExists = 0

        # create urlFile if it does not exist
        if (not urls.urls):
            print ("No data in the url file. Run the script again but include url(s) on the command line.\n\
        e.g. ./showNotifier.py www.myfavoriteband.com")
            sys.exit()
    else:
        urlFileExists = 1
    # these file should never be deleted, but just in case
    if (not os.path.isfile(urlFile)):
        f = open("urls","w")
        f.close()
    if (not os.path.isfile(htmlFile)):
        f = open("htmls","w")
        f.close()
    return urlFileExists
urlFileExists = status_report()

# grab the urls in urlFile, or make
# urlFile if it does not exist
def read_urls(urlFileExists):
    print(urlFileExists)

    # assign all urls in urlFile to prevUrls
    if (urlFileExists == 1):
        uf = open(urlFile, "rb")
        prevUrls = pickle.load(uf)
        uf.close()
        return prevUrls
    else:
        return 1
prevUrls = read_urls(urlFileExists)
print("prevUrls: {}\n".format(prevUrls))

# we will need to check if the user has
# entered a url that is already stored
# and ignore it so the contents of the stored
# urls must be known
def compare_urls(prevUrls, newUrls):

    # no urls were stored in urlFile,
    # so just move on with the script
    if (prevUrls == 1):
        return newUrls

    # iterate over all urls given on cmd line
    # check for membership in the set of
    # stored urls and remove them if the
    # test is true
    else:
        for url in newUrls:
            if (url in prevUrls):
                newUrls.remove(url)
                print ("duplicate url {} found, ignoring it.\n".format(url))
        combinedUrls = newUrls + prevUrls
        return combinedUrls
combinedUrls = compare_urls(prevUrls, urls.urls)
print(type(combinedUrls))
print("combinedUrls: {}\n".format(combinedUrls))
print("combo urls[0]: {}\n".format(combinedUrls[0]))
print(type(combinedUrls[0]))

# write all unique urls to file
def write_urls(combinedUrls):
    uf = open(urlFile, "wb")
    pickle.dump(combinedUrls, uf)
    uf.close()
    return 0
write_urls(combinedUrls)

# TODO:

# visit sites, store their HTML in a list (for now)
def scrape_html(combinedUrls):
    sites = []

    # could this loop be shortened to a fancy list comprehension
    # or lambda expression?
    for url in combinedUrls:
        print(url)
        response = urllib.request.urlopen(url)
        html = response.read()
        soup = BeautifulSoup(html, "html.parser")
        sites.append(soup)
    hf = open(htmlFile, "wb")
    pickle.dump(sites, hf)
    hf.close()
    return 0
scrape_html(combinedUrls)
</code>```

答:
The simplest way is to cast soup to a string and then pickle it:

import pickle
from bs4 import BeautifulSoup

# ... now we have soup
# dump
with open('my_soup.pkl', 'wb') as f:
    pickle.dump(str(soup), f)

# load
with open('my_soup.pkl', 'rb') as f:
    str_soup = pickle.load(f)
    re_soup = BeautifulSoup(str_soup, 'lxml')

# check if they are the same

assert soup == re_soup, 'Houston we have a problem'

# we should not see anything if they are the same.

```

Body:
I want to pickle html from websites. I save the html to a list and try to pickle it. An example of one such list is the html from brckhmptn.com/tour. Of course the html from this site is a lot, is that my error? The whole script is there but the error is called in the last few lines. I'm using Python 3.6.1

Traceback (most recent call last):
  File "./showNotifier.py", line 128, in <module>
    scrape_html(combinedUrls)
  File "./showNotifier.py", line 125, in scrape_html
    pickle.dump(sites, hf)
RecursionError: maximum recursion depth exceeded

#!/home/steph/unix/miniconda3/bin/python
'''
By Stephen Wist
stphnwist@gmail.com
ShowNotifier
---------------------
script takes cmd line args to:
    indiacte URLS to add
default behaviour is checking if new shows were added
'''
import requests
import pickle
import sys
import argparse
import os
import urllib
from bs4 import BeautifulSoup

urlFile = "urls"
htmlFile = "htmls"

# take in cmd line args
parseArgs =  argparse.ArgumentParser(description='Add URLs to cache.')
parseArgs.add_argument('urls', type=str, nargs='*', help='URLs to be added.')

# assign cmd line args to urls.urls
urls = parseArgs.parse_args()

# this function makes sure all files are in place
def status_report():

    # this should be the case only the first time the
    # script is run
    if (os.path.getsize(urlFile) == 0):
        urlFileExists = 0

        # create urlFile if it does not exist
        if (not urls.urls):
            print ("No data in the url file. Run the script again but include url(s) on the command line.\n\
        e.g. ./showNotifier.py www.myfavoriteband.com")
            sys.exit()
    else:
        urlFileExists = 1
    # these file should never be deleted, but just in case
    if (not os.path.isfile(urlFile)):
        f = open("urls","w")
        f.close()
    if (not os.path.isfile(htmlFile)):
        f = open("htmls","w")
        f.close()
    return urlFileExists
urlFileExists = status_report()

# grab the urls in urlFile, or make
# urlFile if it does not exist
def read_urls(urlFileExists):
    print(urlFileExists)

    # assign all urls in urlFile to prevUrls
    if (urlFileExists == 1):
        uf = open(urlFile, "rb")
        prevUrls = pickle.load(uf)
        uf.close()
        return prevUrls
    else:
        return 1
prevUrls = read_urls(urlFileExists)
print("prevUrls: {}\n".format(prevUrls))

# we will need to check if the user has
# entered a url that is already stored
# and ignore it so the contents of the stored
# urls must be known
def compare_urls(prevUrls, newUrls):

    # no urls were stored in urlFile,
    # so just move on with the script
    if (prevUrls == 1):
        return newUrls

    # iterate over all urls given on cmd line
    # check for membership in the set of
    # stored urls and remove them if the
    # test is true
    else:
        for url in newUrls:
            if (url in prevUrls):
                newUrls.remove(url)
                print ("duplicate url {} found, ignoring it.\n".format(url))
        combinedUrls = newUrls + prevUrls
        return combinedUrls
combinedUrls = compare_urls(prevUrls, urls.urls)
print(type(combinedUrls))
print("combinedUrls: {}\n".format(combinedUrls))
print("combo urls[0]: {}\n".format(combinedUrls[0]))
print(type(combinedUrls[0]))

# write all unique urls to file
def write_urls(combinedUrls):
    uf = open(urlFile, "wb")
    pickle.dump(combinedUrls, uf)
    uf.close()
    return 0
write_urls(combinedUrls)

# TODO:

# visit sites, store their HTML in a list (for now)
def scrape_html(combinedUrls):
    sites = []

    # could this loop be shortened to a fancy list comprehension
    # or lambda expression?
    for url in combinedUrls:
        print(url)
        response = urllib.request.urlopen(url)
        html = response.read()
        soup = BeautifulSoup(html, "html.parser")
        sites.append(soup)
    hf = open(htmlFile, "wb")
    pickle.dump(sites, hf)
    hf.close()
    return 0
scrape_html(combinedUrls)


问:
How do I bind complex IOptions?
All of the primitive properties are bound correctly, but not the complex property PagerOptions, it's null.

appsettings.json

```<code>{
  "CommonAPISettings": {
    "Id": "I001",
    "Name": "Common.API",
    "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Orders;Application Name=Common.API",
    "PagerOptions": {
      "PageSize": 500,
      "MaxSize": 1000
    }
  }
}
</code>```

CommonAPISettings.cs

public class CommonAPISettings
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string ConnectionString { get; set; }
    public PagerSettings PagerSettings { get; set; }
}

public class PagerSettings
{
    public int PageSize { get; set; }
    public int MaxSize { get; set; }
}
```

<p><strong>Startup.cs</strong></p>

<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<CommonAPISettings>(Configuration.GetSection("CommonAPISettings"));
    ....
}
</code>```

答:
To begin with, JSON in your question is not valid (please apply better formatting in the future). I managed to fix it and noticed that in your model you have PagerSettings property, but in JSON it has name PagingOptions

```<code>{
  "CommonAPISettings": {
    "Id": "I001",
    "Name": "Common.API",
    "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Orders;Application Name=Common.API",
    "PagerSettings": {
      "PageSize": 500,
      "MaxSize": 1000
    }
  }
}
</code>```

Title: How do I bind complex IOptions?

Body:
All of the primitive properties are bound correctly, but not the complex property PagerOptions, it's null.

appsettings.json

{
  "CommonAPISettings": {
    "Id": "I001",
    "Name": "Common.API",
    "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Orders;Application Name=Common.API",
    "PagerOptions": {
      "PageSize": 500,
      "MaxSize": 1000
    }
  }
}

CommonAPISettings.cs

public class CommonAPISettings
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string ConnectionString { get; set; }
    public PagerSettings PagerSettings { get; set; }
}

public class PagerSettings
{
    public int PageSize { get; set; }
    public int MaxSize { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<CommonAPISettings>(Configuration.GetSection("CommonAPISettings"));
    ....
}

Body:
To begin with, JSON in your question is not valid (please apply better formatting in the future). I managed to fix it and noticed that in your model you have PagerSettings property, but in JSON it has name PagingOptions

{
  "CommonAPISettings": {
    "Id": "I001",
    "Name": "Common.API",
    "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Orders;Application Name=Common.API",
    "PagerSettings": {
      "PageSize": 500,
      "MaxSize": 1000
    }
  }
}