问:
How to get data once from firebase by ID
Hello im trying to get the user email of each message. (Each message (chat) have an userid).
I get the whole user data throught getUser on the *ngIf. And then just show the email. It works and on the website there isn't any repeat of data, but the tab soon freezes unless I don't pause with debugger. I don't know why but it makes an infinite loop.
It looks like this: https://i.imgur.com/XBku0uc.png It makes thousands of console logs.

This is getUser:

```<code>  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.valueChanges().subscribe(queriedItems => {
      this.userDT=new Usermodel(queriedItems[0].uid,queriedItems[0].email,queriedItems[0].displayName,queriedItems[0].photoURL,queriedItems[0].emailVerified);
    });
    console.log(this.userDT.email)
    return this.userDT;
  }
</code>```

and I get the data in the HTML calling it directly:

```<code><div class="msg_container_other" *ngIf="getUser(chat.uid); let otherUser">
                  {{chat.content}}
                  <span class="msg_time"><i class="fas fa-check-double" style="color: #292929;"></i> {{otherUser.email}}. {{ chat.date | date:'d/M/y H:mm'}}</span>
</div>
</code>```

If you need to see what is chats: https://i.imgur.com/iThi424.png and more context on html:https://i.imgur.com/GRupLAp.png

I've been several days trying things and don't know what else to try.
If I remove the subscription of getUser like this:

```<code>  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));

    console.log(this.userDT.email)
    return this.userDT;
  }
</code>```

Then it doesn't loops, but of course can't get data then.

People have told me that isn't the good way to get data once because im subscribing so I tried this way but have same effect infinite loop.

```<code>    getUser(uid:string){

    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data().email);
            return doc.data().email;
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}
</code>```

This getUser doesn't works either it also makes infinite loop :/ cant believe i cant find how to get a single data by query

```<code>     return this.db.collection('users', ref => ref.where('uid', '==', uid)).snapshotChanges().subscribe(data => {
    return data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as User;
    })
  });
</code>```

EDIT:

Okay I think I tried to do it better, this is how I go throught the chats now:
https://i.imgur.com/oJAJDGA.png

```<code>   db.collection('chats', ref => ref.where('groupId', '==', this.pathId).orderBy('date')).snapshotChanges().subscribe(data => {
  this.chatsList = data.map(e => {
    return {
      id: e.payload.doc.id,
      ...e.payload.doc.data()
    } as Chat;
  })
});
</code>```

And this is the html with new change:

```<code>    <div class="card" *ngIf="authService.userData as user">

        <div id="card-box" class="card-box msg_head" ><!--  #scrollMe [scrollTop]="scrollMe.scrollHeight" DA ERROR  -->

            <div id="card-body" class="card-body msg_card_body">
              <div *ngFor="let chat of chatsList">
</code>```

Still can't make it to get the userdata by userid from chat uid without infinite loop tho

EDIT2:
Okay I think I understand better how the asyncronous thing works and I was trying to build a frankenstein, Ill update this when I build it in another way.

EDIT3:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN:

```<code>getPages(){
  const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
  return item.valueChanges().pipe(
  switchMap(arr => {
   const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
   return combineLatest(...userObservable) .pipe( map((...users) => {
      arr.forEach((author, index) => {
       author['author_avatar'] = users[0][index]['photoURL'];
       author['author_username'] = users[0][index]['displayName'];
      });
      return arr;
      })
      );
    })
    );
   }
</code>```

答:
modify your method to return promise/observable of an item and not to store on this.
like here

```<code>getUser(uid:string){
  return this.firestore
    .collection('users')
    .valueChanges({ idField: uid });
}
and in the template
*ngIf="getUser() | async as otherUser"
</code>```

Body:
Hello im trying to get the user email of each message. (Each message (chat) have an userid).
I get the whole user data throught getUser on the *ngIf. And then just show the email. It works and on the website there isn't any repeat of data, but the tab soon freezes unless I don't pause with debugger. I don't know why but it makes an infinite loop.
It looks like this: https://i.imgur.com/XBku0uc.png It makes thousands of console logs.

This is getUser:

  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.valueChanges().subscribe(queriedItems => {
      this.userDT=new Usermodel(queriedItems[0].uid,queriedItems[0].email,queriedItems[0].displayName,queriedItems[0].photoURL,queriedItems[0].emailVerified);
    });
    console.log(this.userDT.email)
    return this.userDT;
  }

and I get the data in the HTML calling it directly:

                  {{chat.content}}
                   {{otherUser.email}}. {{ chat.date | date:'d/M/y H:mm'}}

If you need to see what is chats: https://i.imgur.com/iThi424.png and more context on html:https://i.imgur.com/GRupLAp.png

I've been several days trying things and don't know what else to try.
If I remove the subscription of getUser like this:

  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));

    console.log(this.userDT.email)
    return this.userDT;
  }

Then it doesn't loops, but of course can't get data then.

People have told me that isn't the good way to get data once because im subscribing so I tried this way but have same effect infinite loop.

    getUser(uid:string){

    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data().email);
            return doc.data().email;
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}

This getUser doesn't works either it also makes infinite loop :/ cant believe i cant find how to get a single data by query

     return this.db.collection('users', ref => ref.where('uid', '==', uid)).snapshotChanges().subscribe(data => {
    return data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as User;
    })
  });

EDIT:

Okay I think I tried to do it better, this is how I go throught the chats now:
https://i.imgur.com/oJAJDGA.png

   db.collection('chats', ref => ref.where('groupId', '==', this.pathId).orderBy('date')).snapshotChanges().subscribe(data => {
  this.chatsList = data.map(e => {
    return {
      id: e.payload.doc.id,
      ...e.payload.doc.data()
    } as Chat;
  })
});

And this is the html with new change:

Still can't make it to get the userdata by userid from chat uid without infinite loop tho

EDIT2:
Okay I think I understand better how the asyncronous thing works and I was trying to build a frankenstein, Ill update this when I build it in another way.

EDIT3:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN:

getPages(){
  const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
  return item.valueChanges().pipe(
  switchMap(arr => {
   const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
   return combineLatest(...userObservable) .pipe( map((...users) => {
      arr.forEach((author, index) => {
       author['author_avatar'] = users[0][index]['photoURL'];
       author['author_username'] = users[0][index]['displayName'];
      });
      return arr;
      })
      );
    })
    );
   }

Body:
modify your method to return promise/observable of an item and not to store on this.
like here

getUser(uid:string){
  return this.firestore
    .collection('users')
    .valueChanges({ idField: uid });
}
and in the template
*ngIf="getUser() | async as otherUser"


来源: stackexchange

问:
Gmail SMTPAuthenticationError when I attempt to send email via django
I'm using django-registration-redux and the forget password reset dialogue is working on my machine but it fails on the server. I get an SMTPAuthenticationError even though the local server is sending mails just fine. What could I be doing wrong?

This is the error I get:

```<code>(534, '5.7.14
<https://accounts.google.com/ContinueSignInsarp=1&scc=1&plt=AKgnsbtwe\n5.7.14 Dz3CKtLMnsuR5AJAalqHTpUCJLECZAJKqbimLhjZ3dzjnEOfMck4BnpTZdlLbVRnkocGVe\n5.7.14 ghl_iEoinCscpmC_RWk8CxJ8MP61MyYKtKljt8gnet-NUj53mRP5ohGJsok8V1z1SWXzGa\n5.7.14 MrBjYMYDHU9MbPFopv5jWzFDQS_4Jop03AACxQAcSD1jGG1uQqFXjULQ2RE-wMPrCcyDKW\n5.7.14 Vq08guBEY2LqcSBp9L3jauD-a9i4>
Please log in via your web browser and\n5.7.14 then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/78754 ra1sm18942520pab.24 - gsmtp')
</code>```

答:
It is because Google blocks sign-in attempts from apps that do not use modern security standards (mentioned on their support page). You can, however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On

https://www.google.com/settings/security/lesssecureapps

Moreover, google blocks your IP when you try to send an email since its an unusual location, so, you can unblock in the next link

https://support.google.com/accounts/answer/6009563

and clicked in

https://accounts.google.com/b/0/DisplayUnlockCaptcha

More info…smtp mail

ContentLicense: CC BY-SA 3.0

Body:
I'm using django-registration-redux and the forget password reset dialogue is working on my machine but it fails on the server. I get an SMTPAuthenticationError even though the local server is sending mails just fine. What could I be doing wrong?

This is the error I get:

(534, '5.7.14
<https://accounts.google.com/ContinueSignInsarp=1&scc=1&plt=AKgnsbtwe\n5.7.14 Dz3CKtLMnsuR5AJAalqHTpUCJLECZAJKqbimLhjZ3dzjnEOfMck4BnpTZdlLbVRnkocGVe\n5.7.14 ghl_iEoinCscpmC_RWk8CxJ8MP61MyYKtKljt8gnet-NUj53mRP5ohGJsok8V1z1SWXzGa\n5.7.14 MrBjYMYDHU9MbPFopv5jWzFDQS_4Jop03AACxQAcSD1jGG1uQqFXjULQ2RE-wMPrCcyDKW\n5.7.14 Vq08guBEY2LqcSBp9L3jauD-a9i4>
Please log in via your web browser and\n5.7.14 then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/78754 ra1sm18942520pab.24 - gsmtp')

ContentLicense: CC BY-SA 4.0


问:
How to create a BMI calculator using JavaScript with options to choose between BMI in Kgs/metters or BMI in Lbs/feet
Good day all,

I am currently coding BMI calculator for my project.
The calculator is already set to work in Lbs/feet, but I would like to add an option where I can be able to choose between Kgs/meters or Lbs/feet.

I have created the html code for it and just need the JavaScript part of it to make it work.

Please note that the formula being used for Lbs is:

```<code>((mass / 2.2046) / ((height/3.28) * (height/3.28))).toFixed(2)
</code>```

And if I wanted to calculate the BMI in Kgs / meters, for formula would be:

```<code>(mass / (height * height)).toFixed(2)
</code>```

Please see below what I have done so far:
Your help is always appreciated.
Thanks in advance.

// BMI Calculator

const myForm     = document.getElementById('my-form');

myForm.oninput = () => {
    myForm.result.value = bmiCalculator(myForm.height.value, myForm.mass.value);

function bmiCalculator(height, mass)  {
    return ((mass / 2.2046) / ((height/3.28) * (height/3.28))).toFixed(2)

    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code> fieldset { margin-top: 1em;
}
 label {
   display: inline-block; width: 10em; text-align: left;
  }
  input {
    font-size: .9em; text-align: left; display: inline-block; width: 10em;
  }
   output::before {
     content: '';
  }
  output {
      font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
  }
  append {
      display: inline-block; width: 10em; text-align: center;
  }</code>```

Body Mass Index Calculator

  <form action="" oninput="return mySubmitFunction(event)" id="my-form">

    <fieldset>
     <legend>Please Choose which BMI you would like to use :</legend>
     <append>BMI in Kgs / Meters <input type="radio" name="bmi" value="bmiInKgs"></append>
     <append>BMI in Lbs / Feet <input type="radio" name="bmi" value="bmiInLbs"></append>
    </fieldset>

    <fieldset>
    <fieldset>
      <legend>Calculate Your BMI :</legend>

     Height in Feet: <input type="number" id="height" name="height" step=any min=0>
      Mass / Weight in lbs: <input type="number" id="mass" class="mass" step=any min=0>
    </fieldset>

    <fieldset>

      <legend>BMI Result  :</legend>
      <output id="result" name="result" value='0'></output>

      <button type="reset">Reset Calculator!</button>
    </fieldset></fieldset>
  </form>```

答:
If I understand all you need is to access the radio value, correct?

```<code>if (myForm.bmi.value == "bmiInKgs")
  // Calculate Kg
else {
  // Calculate Lbs
}
</code>```

// BMI Calculator

const myForm     = document.getElementById('my-form');

myForm.oninput = () => {
if (myForm.bmi.value == "bmiInKgs") {
    myForm.result.value = bmiCalculator(myForm.height.value, myForm.mass.value);
} else {
    myForm.result.value = bmiCalculator(myForm.height.value/3.28, myForm.mass.value/2.2046);
}

function bmiCalculator(height, mass)  {
    return (mass / (height * height)).toFixed(2)
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset { margin-top: 1em;
}
 label {
   display: inline-block; width: 10em; text-align: left;
  }
  input {
    font-size: .9em; text-align: left; display: inline-block; width: 10em;
  }
   output::before {
     content: '';
  }
  output {
      font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
  }
  append {
      display: inline-block; width: 10em; text-align: center;
  }</code>```

Body Mass Index Calculator

  <form action="" oninput="return mySubmitFunction(event)" id="my-form">

    <fieldset>
     <legend>Please Choose which BMI you would like to use :</legend>
     <append>BMI in Kgs / Meters <input type="radio" name="bmi" value="bmiInKgs" checked="checked"></append>
     <append>BMI in Lbs / Feet <input type="radio" name="bmi" value="bmiInLbs"></append>
    </fieldset>

    <fieldset>
    <fieldset>
      <legend>Calculate Your BMI :</legend>

     Height: <input type="number" id="height" name="height" step=any min=0>
      Mass / Weight: <input type="number" id="mass" class="mass" step=any min=0>
    </fieldset>

    <fieldset>

      <legend>BMI Result  :</legend>
      <output id="result" name="result" value='0'></output>

      <button type="reset">Reset Calculator!</button>
    </fieldset></fieldset>
  </form>```

Body:
Good day all,

I am currently coding BMI calculator for my project.
The calculator is already set to work in Lbs/feet, but I would like to add an option where I can be able to choose between Kgs/meters or Lbs/feet.

I have created the html code for it and just need the JavaScript part of it to make it work.

Please note that the formula being used for Lbs is:

((mass / 2.2046) / ((height/3.28) * (height/3.28))).toFixed(2)

And if I wanted to calculate the BMI in Kgs / meters, for formula would be:

(mass / (height * height)).toFixed(2)

Please see below what I have done so far:
Your help is always appreciated.
Thanks in advance.

// BMI Calculator

const myForm     = document.getElementById('my-form');

myForm.oninput = () => {
    myForm.result.value = bmiCalculator(myForm.height.value, myForm.mass.value);

function bmiCalculator(height, mass)  {
    return ((mass / 2.2046) / ((height/3.28) * (height/3.28))).toFixed(2)

    }
}

 fieldset { margin-top: 1em;
}
 label {
   display: inline-block; width: 10em; text-align: left;
  }
  input {
    font-size: .9em; text-align: left; display: inline-block; width: 10em;
  }
   output::before {
     content: '';
  }
  output {
      font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
  }
  append {
      display: inline-block; width: 10em; text-align: center;
  }

Body Mass Index Calculator

  <form action="" oninput="return mySubmitFunction(event)" id="my-form">

    <fieldset>
     <legend>Please Choose which BMI you would like to use :</legend>
     <append>BMI in Kgs / Meters <input type="radio" name="bmi" value="bmiInKgs"></append>
     <append>BMI in Lbs / Feet <input type="radio" name="bmi" value="bmiInLbs"></append>
    </fieldset>

    <fieldset>
    <fieldset>
      <legend>Calculate Your BMI :</legend>

     Height in Feet: <input type="number" id="height" name="height" step=any min=0>
      Mass / Weight in lbs: <input type="number" id="mass" class="mass" step=any min=0>
    </fieldset>

    <fieldset>

      <legend>BMI Result  :</legend>
      <output id="result" name="result" value='0'></output>

      <button type="reset">Reset Calculator!</button>
    </fieldset></fieldset>
  </form>

Body:
If I understand all you need is to access the radio value, correct?

if (myForm.bmi.value == "bmiInKgs")
  // Calculate Kg
else {
  // Calculate Lbs
}

// BMI Calculator

const myForm     = document.getElementById('my-form');

myForm.oninput = () => {
if (myForm.bmi.value == "bmiInKgs") {
    myForm.result.value = bmiCalculator(myForm.height.value, myForm.mass.value);
} else {
    myForm.result.value = bmiCalculator(myForm.height.value/3.28, myForm.mass.value/2.2046);
}

function bmiCalculator(height, mass)  {
    return (mass / (height * height)).toFixed(2)
    }
}

fieldset { margin-top: 1em;
}
 label {
   display: inline-block; width: 10em; text-align: left;
  }
  input {
    font-size: .9em; text-align: left; display: inline-block; width: 10em;
  }
   output::before {
     content: '';
  }
  output {
      font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
  }
  append {
      display: inline-block; width: 10em; text-align: center;
  }

<h2>Body Mass Index Calculator</h2>

  <!-- Used oninput to display the results instantly-->
  <!-- If I wanted to calculate the result on a click, I would use onsubmit-->

  <form action="" oninput="return mySubmitFunction(event)" id="my-form">

    <fieldset>
     <legend>Please Choose which BMI you would like to use :</legend>
     <append>BMI in Kgs / Meters <input type="radio" name="bmi" value="bmiInKgs" checked="checked"></append>
     <append>BMI in Lbs / Feet <input type="radio" name="bmi" value="bmiInLbs"></append>
    </fieldset>

    <fieldset>
    <fieldset>
      <legend><b>Calculate Your BMI :</b></legend>
      <br>
     <label>Height: <input type="number" id="height" name="height" step=any min=0></label>
      <label>Mass / Weight: <input type="number" id="mass" class="mass" step=any min=0></label>
    </fieldset>

    <fieldset><br>
      <legend><b>BMI Result  :</b></legend>
      <output id="result" name="result" value='0'></output>

      <br><br>
      <button type="reset">Reset Calculator!</button>
    </fieldset></fieldset>
  </form>


问:
Escaping ampersand and other special characters in XML using Python
I have to parse a large amount of XML files and write it to a text file. However, some of the XML files contain special/illegal characters. I have tried using different methods such as Escaping strings for use in XML
but I could not get it to work. I know 1 way to solve this is by editing the XML file itself, but there are thousands of files.

```<code>import os
from xml.etree import ElementTree
from xml.sax.saxutils import escape

fileNum = 0;
saveFile = open('NewYork_1.txt','w')

for path, dirs, files in os.walk("NewYork_1"):
   for f in files:
      fileName = os.path.join(path, f)
      with open(fileName,'r', encoding='utf-8') as myFile:
        # print(myFile.read())
        if "&" in myFile:
            myFile = myFile.replace("&", "&") #This does not work.
</code>```

Also, some of the XML files also have unicode in them. There are emojis.

```<code><Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
      <UserID></UserID>
      <Date></Date>
      <icontent></icontent>
   </InitPost>
   <Post>
      <UserID></UserID>
      <Date></Date>
      <rcontent></rcontent>
  </Post>
</Thread>
</code>```

答:
Try this:

```<code>import os
from xml.etree import ElementTree
from xml.sax.saxutils import escape

fileNum = 0;
saveFile = open('NewYork_1.txt','w')
saveFile.close()
for path, dirs, files in os.walk("NewYork_1"):
   for f in files:
       fileName = os.path.join(path, f)
       with open(fileName,'a', encoding='utf-8') as myFile:
           myFile=myFile.read()
           if "&" in myFile:
                myFile = myFile.replace("&", "&")
</code>```

I personally would generate a list of files to read and iterate through that list rather than use os.walk (if you're getting the list from a previous function or a separate script, you could always create a text file with each txt file on a separate line and iterate through lines rather than getting from a variable to save RAM), but to each his own.

As I said, though, I'd discard the whole idea of replacing special characters and use bs4 to open the files, search for which elements you're looking for, and grab from there.

```<code>import bs4
list_of_USER_IDs=[]
with open(fileName,'r', encoding='utf-8') as myFile:
    a=myFile.read()
    b=bs4.beautifulSoup(a)
    for elem in b.findAll('USERID'):
        list_of_USER_IDs.append(elem)
</code>```

That returns the data between the USERID tags, but it'll work for whatever tag you want data from. No need to directly parse xml. It's really not much different than HTML and beautifulSoup is made for that, so why reinvent the wheel?

Body:
I have to parse a large amount of XML files and write it to a text file. However, some of the XML files contain special/illegal characters. I have tried using different methods such as Escaping strings for use in XML
but I could not get it to work. I know 1 way to solve this is by editing the XML file itself, but there are thousands of files.

import os
from xml.etree import ElementTree
from xml.sax.saxutils import escape

fileNum = 0;
saveFile = open('NewYork_1.txt','w')

for path, dirs, files in os.walk("NewYork_1"):
   for f in files:
      fileName = os.path.join(path, f)
      with open(fileName,'r', encoding='utf-8') as myFile:
        # print(myFile.read())
        if "&" in myFile:
            myFile = myFile.replace("&", "&") #This does not work.

Also, some of the XML files also have unicode in them. There are emojis.

<Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
      <UserID></UserID>
      <Date></Date>
      <icontent></icontent>
   </InitPost>
   <Post>
      <UserID></UserID>
      <Date></Date>
      <rcontent></rcontent>
  </Post>
</Thread>

Body:
Try this:

import os
from xml.etree import ElementTree
from xml.sax.saxutils import escape

fileNum = 0;
saveFile = open('NewYork_1.txt','w')
saveFile.close()
for path, dirs, files in os.walk("NewYork_1"):
   for f in files:
       fileName = os.path.join(path, f)
       with open(fileName,'a', encoding='utf-8') as myFile:
           myFile=myFile.read()
           if "&" in myFile:
                myFile = myFile.replace("&", "&#38;")

I personally would generate a list of files to read and iterate through that list rather than use os.walk (if you're getting the list from a previous function or a separate script, you could always create a text file with each txt file on a separate line and iterate through lines rather than getting from a variable to save RAM), but to each his own.

As I said, though, I'd discard the whole idea of replacing special characters and use bs4 to open the files, search for which elements you're looking for, and grab from there.

import bs4
list_of_USER_IDs=[]
with open(fileName,'r', encoding='utf-8') as myFile:
    a=myFile.read()
    b=bs4.beautifulSoup(a)
    for elem in b.findAll('USERID'):
        list_of_USER_IDs.append(elem)

That returns the data between the USERID tags, but it'll work for whatever tag you want data from. No need to directly parse xml. It's really not much different than HTML and beautifulSoup is made for that, so why reinvent the wheel?


问:
Can I use static class for my Logger?
Recently I have been told that static class/methods are evil.

Take for example my class Logger:

```<code>class Logger{
   private static $logs = array();
   public static function add($msg){
      self::$logs[]=$msg;
   }

   public static function echo(){
       print_r(self::$logs);
   }
}
</code>```

I can use whenever i want in my appliaction like this:

```<code>Logger::add('My log 1');
</code>```

But reading this developers:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

That Logger class doesn't seem so good.

So: Can I use it statically or I should avoid it at any cost?

答:
The only problem with static classes is that they are hard to change.
So it's ok here since you're class doesn't do much. </p>

Title: Can I use static class for my Logger?

Body:
Recently I have been told that static class/methods are evil.

Take for example my class Logger:

class Logger{
   private static $logs = array();
   public static function add($msg){
      self::$logs[]=$msg;
   }

   public static function echo(){
       print_r(self::$logs);
   }
}

I can use whenever i want in my appliaction like this:

Logger::add('My log 1');

But reading this developers:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

That Logger class doesn't seem so good.

So: Can I use it statically or I should avoid it at any cost?


问:
Is there a fixed point representation available in C or Assembly
As far as I know, representing a fraction in C relies on floats and doubles which are in floating point representation.

Assume I'm trying to represent 1.5 which is a fixed point number (only one digit to the right of the radix point). Is there a way to represent such number in C or even assembly using a fixed point data type?

Are there even any fixed point instructions on x86 (or other architectures) which would operate on such type?

答:
If the issue here is representing decimal values as fixed point, there's probably a library for this for C, you could try a web search. You could create your own BCD fixed point library in assembly, using the BCD related instructions, AAA (adjusts after addition), AAS (adjusts after subtraction) and AAM (adjusts after multiplication). However, it seems these instructions are invalid in X86 X64 (64 bit) mode, so you'll need to use a 32 bit program, which should be runnable on a 64 bit OS.

Financial institutions in the USA and other countries are required by law to perform decimal based math on currency values, to avoid decimal -> binary -> decimal conversion issues.


答:
What you can do is read the file in as a string.

```<code>file_str = open("xml_file.xml", "r+")
</code>```

Then use the fromString function of xml.etree.ElementTree

```<code>tree = xml.etree.ElementTree.fromString(file_str)
</code>```

Then do stuff with it.

```<code>root = tree.getRoot()
</code>```

This way you don't have to worry about writing code for every emoji, and invalid sign.
If you want to write emojis and special utf-8 characters to xml, you have to add this line to the top.

```<code> <?xml version="1.0" encoding="utf-8" ?>
</code>```

Title: Escaping ampersand and other special characters in XML using Python

Body:
What you can do is read the file in as a string.

file_str = open("xml_file.xml", "r+")

Then use the fromString function of xml.etree.ElementTree

tree = xml.etree.ElementTree.fromString(file_str)

Then do stuff with it.

root = tree.getRoot()

This way you don't have to worry about writing code for every emoji, and invalid sign.
If you want to write emojis and special utf-8 characters to xml, you have to add this line to the top.

 <?xml version="1.0" encoding="utf-8" ?>


问:
How to insert 1 interval numbers between given irregular numbers in python
I've generated index number list what I do find data using for-loop.

That numbers are as follows.

I want to generate 1 interval index numbers between each given numbers

```<code>Int64Index([ 2343,  2913,  5466,  8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700],dtype='int64')
</code>```

for e.g) 2343,2344,2345,2346 ......,2911,2912,2913,2914....5464,5465,5466 some thing like that.

Is there any method that i generate 1 interval numbers do not use for-loop?

答:
Try using the builtin range() function.

First you need to determine start and end number using the min() and max() functions.

```<code>start_num = min(listr)
end_num = max(listr)
</code>```

Then we use range() to create our new list

```<code>new_listr = list(range(start_num, end_num+1))
</code>```

The complete sample code:

```<code>listr = [2343,  2913,  5466,  8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700]
start_num = min(listr)
end_num = max(listr)
new_listr = list(range(start_num, end_num+1))
</code>```

Body:
I've generated index number list what I do find data using for-loop.

That numbers are as follows.

I want to generate 1 interval index numbers between each given numbers

Int64Index([ 2343,  2913,  5466,  8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700],dtype='int64')

for e.g) 2343,2344,2345,2346 ......,2911,2912,2913,2914....5464,5465,5466 some thing like that.

Is there any method that i generate 1 interval numbers do not use for-loop?

Body:
Try using the builtin range() function.

First you need to determine start and end number using the min() and max() functions.

start_num = min(listr)
end_num = max(listr)

Then we use range() to create our new list

new_listr = list(range(start_num, end_num+1))

The complete sample code:

listr = [2343,  2913,  5466,  8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700]
start_num = min(listr)
end_num = max(listr)
new_listr = list(range(start_num, end_num+1))


问:
How to set post tags by some meta keys?
I prepared following code to overwrite post tags following several meta keys.
Now, it works for only one meta key.  How can I apply it to several meta keys?

```<code><?php
global $post;
$post_id = $post->ID;
$tags[] = get_post_meta($post_id, 'aaaaa', $single);
$tags[] = get_post_meta($post_id, 'bbbbb', $single);
$tags[] = get_post_meta($post_id, 'ccccc', $single);
$tags = array_unique( array_filter( $tags ) ); // here, adding array_filter to remove empty get_post_meta results
wp_set_post_tags( $post_id, $tags, false );
?>
</code>```

By above code, meta value of meta key aaaaa only applied as post tag, and meta value of meta key bbbbb and ccccc is ignored.

After I hear advise below, I tried this code too.

```<code><?php
global $post;
$post_id = $post->ID;

$tags = get_post_meta($post_id, 'aaaaa', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'bbbbb', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'ccccc', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

wp_set_post_tags( $post_id, $tags, false );

?>
</code>```

Then, all tag is eliminatd.

答:
Your code looks right, but I suggest that you check if the meta key bbbbb and ccccc does have value or not int he first place. So try to display something like that.

Also, give this a go and try to add one tag in time.
https://developer.wordpress.org/reference/functions/wp_add_post_tags/

Like this:

```<code>    <?php
    global $post;
    $post_id = $post->ID;

    $tag = get_post_meta($post_id, 'aaaaa', $single);
    if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

    $tag = get_post_meta($post_id, 'bbbbb ', $single);
    if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

    $tag = get_post_meta($post_id, 'ccccc', $single);
    if (!empty() ) { wp_add_post_tags( $post_id, $$tag ); }

    ?>
</code>```

Title: How to set post tags by some meta keys?

Body:
I prepared following code to overwrite post tags following several meta keys.
Now, it works for only one meta key.  How can I apply it to several meta keys?

<?php
global $post;
$post_id = $post->ID;
$tags[] = get_post_meta($post_id, 'aaaaa', $single);
$tags[] = get_post_meta($post_id, 'bbbbb', $single);
$tags[] = get_post_meta($post_id, 'ccccc', $single);
$tags = array_unique( array_filter( $tags ) ); // here, adding array_filter to remove empty get_post_meta results
wp_set_post_tags( $post_id, $tags, false );
?>

By above code, meta value of meta key aaaaa only applied as post tag, and meta value of meta key bbbbb and ccccc is ignored.

After I hear advise below, I tried this code too.

<?php
global $post;
$post_id = $post->ID;

$tags = get_post_meta($post_id, 'aaaaa', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'bbbbb', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'ccccc', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

wp_set_post_tags( $post_id, $tags, false );

?>

Then, all tag is eliminatd.

Body:
Your code looks right, but I suggest that you check if the meta key bbbbb and ccccc does have value or not int he first place. So try to display something like that.

Also, give this a go and try to add one tag in time.
https://developer.wordpress.org/reference/functions/wp_add_post_tags/

Like this:

    <?php
    global $post;
    $post_id = $post->ID;

    $tag = get_post_meta($post_id, 'aaaaa', $single);
    if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

    $tag = get_post_meta($post_id, 'bbbbb ', $single);
    if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

    $tag = get_post_meta($post_id, 'ccccc', $single);
    if (!empty() ) { wp_add_post_tags( $post_id, $$tag ); }

    ?>


问:
Not able to move this div left?
Ii am trying to move the searchUserDiv to the left to o create the bellow layout. However everything I have tried has failed so far to move the div to the left. How can I achieve this?

Here is my current code and the resulting layout.

.searchResultsList {
  background-color: lightblue;
}

.searchResultsList li {
  list-style: none;
}
.searchResultsList * {
  background-color: grey;
  /* margin: 13px 0 13px 0; */
  margin-top: 10px;
  margin-bottom: 10px;
  /* margin-left: 0px; */
  cursor: pointer;
}

.searchUserDiv {
  display: flex;
  align-items: center;
  /* background-color: #353258;
  border: 1px solid #4152F1; */
  color: white;
  cursor: pointer;
  padding-left: 10px;
  width: 85%;
  border-radius: 32px;
}
.searchUsername {
  display: flex;
  align-items: center;
  font-size: 18px;
  font: Arial;
  font-family: sans-serif;
  margin-top: 0px;
  padding-left: 10px;
}
.searchUserProfImg {
  padding-left: 5px;
  height: 40px;
  width:40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="searchResultsList" id="searchResultsList">
          <!-- style="display: none;" -->
          <li class="searchUserDiv">
            <img class="searchUserProfImg" id="searchUserProfImg" src="images/defaultProfImg.png">
            <label class="searchUsername" id="searchUsername">username</label>
          </li>
          <li class="searchUserDiv">
            <img class="searchUserProfImg" id="searchUserProfImg" src="images/defaultProfImg.png">
            <label class="searchUsername" id="searchUsername">username</label>
          </li>
          <li class="searchUserDiv">
            <img class="searchUserProfImg" id="searchUserProfImg" src="images/defaultProfImg.png">
            <label class="searchUsername" id="searchUsername">username</label>
          </li>
        </ul></code>```

Thanks for any suggestions or solutions, I very much appreciate it!

答: Your ul.searchResultsList has a left padding of 40px set by the browser because it's a list. Set padding-left: 0.

Title: Not able to move this div left?

Body:
Ii am trying to move the searchUserDiv to the left to o create the bellow layout. However everything I have tried has failed so far to move the div to the left. How can I achieve this?

Here is my current code and the resulting layout.

.searchResultsList {
  background-color: lightblue;
}

.searchResultsList li {
  list-style: none;
}
.searchResultsList * {
  background-color: grey;
  /* margin: 13px 0 13px 0; */
  margin-top: 10px;
  margin-bottom: 10px;
  /* margin-left: 0px; */
  cursor: pointer;
}

.searchUserDiv {
  display: flex;
  align-items: center;
  /* background-color: #353258;
  border: 1px solid #4152F1; */
  color: white;
  cursor: pointer;
  padding-left: 10px;
  width: 85%;
  border-radius: 32px;
}
.searchUsername {
  display: flex;
  align-items: center;
  font-size: 18px;
  font: Arial;
  font-family: sans-serif;
  margin-top: 0px;
  padding-left: 10px;
}
.searchUserProfImg {
  padding-left: 5px;
  height: 40px;
  width:40px;
}

            username

            username

            username

Thanks for any suggestions or solutions, I very much appreciate it!


问:
Explicity show many-to-many tables in Entity Framework
I am attempting to learn Entity Framework to try to move on from Linq to SQL, and my attempt to convert some code over failed on a many-to-many recursive table (a tree structure).  I need to do a full table read and prepare the tree in memory because recursing through the database with a lot of queries is too slow.

I have a database with a Projects table, and another table called ProjectsTree.  With Linq to SQL, I can get access to the ProjectsTree table, but not with Entity Framework.  It puts it in an association in a way that I can't seem to query this table directly.

Here's the code before I attempted to convert Linq to SQL over to Entity Framework, and it worked.  Maybe I should stick with Linq to SQL and not learn something new, and if there is no way to do this, I may go backward, or let the two co-exist.

```<code> Private Class cProjectTree2
      Public Project As PDMVault.Project
      Public ChildTree As List(Of cProjectTree2)

   End Class

   ''' <summary>
   ''' Gets the complete PDM project tree that can be added to a tree node.
   ''' Each node has the description in the node text field and the primary key in the tag.
   ''' </summary>
   ''' <returns></returns>
   Public Function GetPDMProjectTree() As TreeNode
      ' To generate the tree, first read the projects table with a complete table scan, then the ProjectTree with a complete table scan.
      ' Create a dictionary of objects of type cRecursiveProjectTree, but only the project is set on the first pass, with a reference to it based on its key.
      ' After the dictionary is built, then link up children to parent using the dictinary.
      ' Finally, use the created tree to create the node structure for the tree view.

      Dim Diag_Stopwatch As New Stopwatch

      Dim IDtoTree As New Generic.Dictionary(Of Long, cProjectTree2)

      Dim C = New PDMVault.DataContext1
      '  C.Log = Console.Out

      Dim Projects = C.Projects.ToList  ' Database list of trees.

''''''''''''''''''''''This is the line that fails.  ProjectTrees only shows up as an association, and I can't seem to get access to it for a full table scan
          Dim Tree = C.ProjectTrees.ToList   ' Database hierarcy of the projects in the previous statement

'''''''''''''''''''''''''''''''''''''''''''''

      ' Create the dictionary with only the "Project" item set
      For Each P In Projects
         Dim ProjectTreeEntry As New cProjectTree2
         ProjectTreeEntry.ChildTree = New List(Of cProjectTree2)
         ProjectTreeEntry.Project = P
         IDtoTree.Add(P.ProjectID, ProjectTreeEntry)
      Next

      ' Now that the dictionary has been created, the children can be linked to the parent.
      For Each T In Tree
         Dim Parent As cProjectTree2 = Nothing
         Dim Child As cProjectTree2 = Nothing
         IDtoTree.TryGetValue(T.ProjectID, Parent)
         IDtoTree.TryGetValue(T.ChildProject, Child)
         Parent.ChildTree.Add(Child)
      Next

      ' The tree has been built, create the tree view from the tree (using a little recursion)

      Dim GetChildTrees As Func(Of cProjectTree2, TreeNode) =
         Function(P As cProjectTree2) As TreeNode
            Dim Result As New TreeNode
            For Each Child In P.ChildTree.OrderBy(Function(ProjectNode) ProjectNode.Project.Name)
               Dim N = GetChildTrees(Child)
               If N IsNot Nothing Then
                  Result.Nodes.Add(N)
               End If
            Next
            Result.Tag = P.Project.ProjectID
            Result.Text = P.Project.Name
            Return Result
         End Function

      Dim RootProject As cProjectTree2 = Nothing
      If IDtoTree.TryGetValue(1, RootProject) = True Then
         Dim N2 As TreeNode = GetChildTrees(RootProject)
         Return N2
      Else
         Return Nothing
      End If
   End Function
</code>```

答:
I came very close to going backwards and sticking with LINQ to SQL, but this is a new project and I wanted to learn EF before I had significant code investment.  With a little experimenting with Entities Framework, the following handles the recursive tree nicely without me having to get access to the ProjectTrees table.

```<code> Public Function GetPDMProjectTree() As TreeNode
      Dim Diag_Stopwatch As New Stopwatch
      Diag_Stopwatch.Start()

      Dim C = New PDMVault.DataContext1
      C.Configuration.LazyLoadingEnabled = False ' Necessary for the materialization to work in the next line
      Dim MaterializeDatabase = C.Projects.ToList

      C.Database.Log = Sub(Log) Debug.Print(Log) ' Verify that only two table scans occurs and that it's not hitting repeatedly

      Dim RootProject = (From P In C.Projects Where P.ProjectID = 1).SingleOrDefault

      If RootProject Is Nothing Then Return Nothing

      Dim GetTree As Func(Of PDMVault.Project, TreeNode) =
         Function(P As PDMVault.Project) As TreeNode
            Dim Result As New TreeNode
            For Each Child In P.Projects1.OrderBy(Function(ProjectNode) ProjectNode.Name)
               Result.Nodes.Add(GetTree(Child))
            Next
            Result.Tag = P.ProjectID
            Result.Text = P.Name
            Return Result
         End Function

      If RootProject Is Nothing Then Return Nothing
      Debug.Print($"Tree building time={Diag_Stopwatch.ElapsedMilliseconds / 1000:#0.00}")
      Return GetTree(RootProject)

   End Function
</code>```

For the SO archives, here is a former method that did it with two trips to the database (one for the initial dictionary, and one for the root) and used an external dictionary before I learned about turning off lazy loading, probably not as optimal as my final solution.

```<code> Public Function GetPDMProjectTree2() As TreeNode

      Dim Diag_Stopwatch As New Stopwatch

      Dim C = New PDMVault.DataContext1

      C.Database.Log = Sub(Log) Debug.Print(Log) ' Verify that only one table scan occurs and that it isn't an N+1 problem.

      ' Force a complete table scan before starting the recursion below, which will come from cached content

      Dim ProjectTreeFromDatabase = (From P In C.Projects
                                     Select Project = P,
                                            Children = P.Projects1).ToDictionary(Function(F) F.Project.ProjectID)

      Dim GetTree As Func(Of PDMVault.Project, TreeNode) =
         Function(P As PDMVault.Project) As TreeNode
            Dim Result As New TreeNode
            For Each Child In ProjectTreeFromDatabase(P.ProjectID).Children.OrderBy(Function(ProjectNode) ProjectNode.Name)
               Dim N = GetTree(Child)
               If N IsNot Nothing Then
                  Result.Nodes.Add(N)
               End If
            Next
            Result.Tag = P.ProjectID
            Result.Text = P.Name
            Return Result
         End Function

      Dim RootProject = (From P In C.Projects Where P.ProjectID = 1).SingleOrDefault
      If RootProject Is Nothing Then Return Nothing
      Return GetTree(RootProject)

   End Function
</code>```

Both solutions prevent repeated trips to the database.

Body:
I am attempting to learn Entity Framework to try to move on from Linq to SQL, and my attempt to convert some code over failed on a many-to-many recursive table (a tree structure).  I need to do a full table read and prepare the tree in memory because recursing through the database with a lot of queries is too slow.

I have a database with a Projects table, and another table called ProjectsTree.  With Linq to SQL, I can get access to the ProjectsTree table, but not with Entity Framework.  It puts it in an association in a way that I can't seem to query this table directly.

Here's the code before I attempted to convert Linq to SQL over to Entity Framework, and it worked.  Maybe I should stick with Linq to SQL and not learn something new, and if there is no way to do this, I may go backward, or let the two co-exist.

 Private Class cProjectTree2
      Public Project As PDMVault.Project
      Public ChildTree As List(Of cProjectTree2)

   End Class

   '''
   ''' Gets the complete PDM project tree that can be added to a tree node.
   ''' Each node has the description in the node text field and the primary key in the tag.
   '''
   ''' <returns></returns>
   Public Function GetPDMProjectTree() As TreeNode
      ' To generate the tree, first read the projects table with a complete table scan, then the ProjectTree with a complete table scan.
      ' Create a dictionary of objects of type cRecursiveProjectTree, but only the project is set on the first pass, with a reference to it based on its key.
      ' After the dictionary is built, then link up children to parent using the dictinary.
      ' Finally, use the created tree to create the node structure for the tree view.

      Dim Diag_Stopwatch As New Stopwatch

      Dim IDtoTree As New Generic.Dictionary(Of Long, cProjectTree2)

      Dim C = New PDMVault.DataContext1
      '  C.Log = Console.Out

      Dim Projects = C.Projects.ToList  ' Database list of trees.

''''''''''''''''''''''This is the line that fails.  ProjectTrees only shows up as an association, and I can't seem to get access to it for a full table scan
          Dim Tree = C.ProjectTrees.ToList   ' Database hierarcy of the projects in the previous statement

'''''''''''''''''''''''''''''''''''''''''''''

      ' Create the dictionary with only the "Project" item set
      For Each P In Projects
         Dim ProjectTreeEntry As New cProjectTree2
         ProjectTreeEntry.ChildTree = New List(Of cProjectTree2)
         ProjectTreeEntry.Project = P
         IDtoTree.Add(P.ProjectID, ProjectTreeEntry)
      Next

      ' Now that the dictionary has been created, the children can be linked to the parent.
      For Each T In Tree
         Dim Parent As cProjectTree2 = Nothing
         Dim Child As cProjectTree2 = Nothing
         IDtoTree.TryGetValue(T.ProjectID, Parent)
         IDtoTree.TryGetValue(T.ChildProject, Child)
         Parent.ChildTree.Add(Child)
      Next

      ' The tree has been built, create the tree view from the tree (using a little recursion)

      Dim GetChildTrees As Func(Of cProjectTree2, TreeNode) =
         Function(P As cProjectTree2) As TreeNode
            Dim Result As New TreeNode
            For Each Child In P.ChildTree.OrderBy(Function(ProjectNode) ProjectNode.Project.Name)
               Dim N = GetChildTrees(Child)
               If N IsNot Nothing Then
                  Result.Nodes.Add(N)
               End If
            Next
            Result.Tag = P.Project.ProjectID
            Result.Text = P.Project.Name
            Return Result
         End Function

      Dim RootProject As cProjectTree2 = Nothing
      If IDtoTree.TryGetValue(1, RootProject) = True Then
         Dim N2 As TreeNode = GetChildTrees(RootProject)
         Return N2
      Else
         Return Nothing
      End If
   End Function

Body:
I came very close to going backwards and sticking with LINQ to SQL, but this is a new project and I wanted to learn EF before I had significant code investment.  With a little experimenting with Entities Framework, the following handles the recursive tree nicely without me having to get access to the ProjectTrees table.

 Public Function GetPDMProjectTree() As TreeNode
      Dim Diag_Stopwatch As New Stopwatch
      Diag_Stopwatch.Start()

      Dim C = New PDMVault.DataContext1
      C.Configuration.LazyLoadingEnabled = False ' Necessary for the materialization to work in the next line
      Dim MaterializeDatabase = C.Projects.ToList

      C.Database.Log = Sub(Log) Debug.Print(Log) ' Verify that only two table scans occurs and that it's not hitting repeatedly

      Dim RootProject = (From P In C.Projects Where P.ProjectID = 1).SingleOrDefault

      If RootProject Is Nothing Then Return Nothing

      Dim GetTree As Func(Of PDMVault.Project, TreeNode) =
         Function(P As PDMVault.Project) As TreeNode
            Dim Result As New TreeNode
            For Each Child In P.Projects1.OrderBy(Function(ProjectNode) ProjectNode.Name)
               Result.Nodes.Add(GetTree(Child))
            Next
            Result.Tag = P.ProjectID
            Result.Text = P.Name
            Return Result
         End Function

      If RootProject Is Nothing Then Return Nothing
      Debug.Print($"Tree building time={Diag_Stopwatch.ElapsedMilliseconds / 1000:#0.00}")
      Return GetTree(RootProject)

   End Function

For the SO archives, here is a former method that did it with two trips to the database (one for the initial dictionary, and one for the root) and used an external dictionary before I learned about turning off lazy loading, probably not as optimal as my final solution.

 Public Function GetPDMProjectTree2() As TreeNode

      Dim Diag_Stopwatch As New Stopwatch

      Dim C = New PDMVault.DataContext1

      C.Database.Log = Sub(Log) Debug.Print(Log) ' Verify that only one table scan occurs and that it isn't an N+1 problem.

      ' Force a complete table scan before starting the recursion below, which will come from cached content

      Dim ProjectTreeFromDatabase = (From P In C.Projects
                                     Select Project = P,
                                            Children = P.Projects1).ToDictionary(Function(F) F.Project.ProjectID)

      Dim GetTree As Func(Of PDMVault.Project, TreeNode) =
         Function(P As PDMVault.Project) As TreeNode
            Dim Result As New TreeNode
            For Each Child In ProjectTreeFromDatabase(P.ProjectID).Children.OrderBy(Function(ProjectNode) ProjectNode.Name)
               Dim N = GetTree(Child)
               If N IsNot Nothing Then
                  Result.Nodes.Add(N)
               End If
            Next
            Result.Tag = P.ProjectID
            Result.Text = P.Name
            Return Result
         End Function

      Dim RootProject = (From P In C.Projects Where P.ProjectID = 1).SingleOrDefault
      If RootProject Is Nothing Then Return Nothing
      Return GetTree(RootProject)

   End Function

Both solutions prevent repeated trips to the database.


问:
Create 2-dimension table reporting average
In the table Products in the link below, I have 3 columns.

SupplierID, CategryID and Price.

https://www.w3schools.com/sql/trysql.asp?filename=trysql_drop_table

I want to create 3 group of SupplierID and 3 group of CategryID. The rule is listed below.

```<code>case    when SupplierID<=10 then 'SupplierID_group1'
            when 10<SupplierID and SupplierID<=15 then 'SupplierID_group2'
            when 15<SupplierID then 'SupplierID_group3'
end SupplierID_group

case    when CategoryID<=3 then 'Category_Mode Low'
        when 3< CategoryID and CategoryID<=6 then 'Category_Mode Mid'
        when 6< CategoryID then 'Category_Mode High'
end Category_Group
</code>```

I want a 3-by-3 table which report the average Price for each combination of SupplierID_group and Category_Group.

My problem is that I am not allowed to create new table or new column in existing table.

Can anyone please help?

Thank you.

Harry

答:
If your database is MySQL, this query will give you the results that you want; it works in the w3schools TryMySQL window:

```<code>SELECT CASE WHEN CategoryID<=3 THEN "Category_Mode Low"
            WHEN 3< CategoryID and CategoryID<=6 THEN "Category_Mode Mid"
            WHEN 6< CategoryID THEN "Category_Mode High"
       END AS Category_Group,
       AVG(CASE WHEN SupplierID<=10 THEN price end) AS SupplierID_group1,
       AVG(CASE WHEN 10<SupplierID and SupplierID<=15 THEN price END) AS SupplierID_group2,
       AVG(CASE WHEN 15<SupplierID THEN price END) AS SupplierID_group3
FROM Products
GROUP BY Category_Group
</code>```

If you're running more standard SQL, you'll need to repeat the Category_Group expression in the GROUP BY clause:

```<code>SELECT CASE WHEN CategoryID<=3 THEN "Category_Mode Low"
            WHEN 3< CategoryID and CategoryID<=6 THEN "Category_Mode Mid"
            WHEN 6< CategoryID THEN "Category_Mode High"
       END AS Category_Group,
       AVG(CASE WHEN SupplierID<=10 THEN price end) AS SupplierID_group1,
       AVG(CASE WHEN 10<SupplierID and SupplierID<=15 THEN price END) AS SupplierID_group2,
       AVG(CASE WHEN 15<SupplierID THEN price END) AS SupplierID_group3
FROM Products
GROUP BY CASE WHEN CategoryID<=3 THEN "Category_Mode Low"
            WHEN 3< CategoryID and CategoryID<=6 THEN "Category_Mode Mid"
            WHEN 6< CategoryID THEN "Category_Mode High"
       END
</code>```

Output for the sample Products table:

```<code>Category_Group      SupplierID_group1   SupplierID_group2   SupplierID_group3
Category_Mode High  27.1667             36                  19.5556
Category_Mode Low   22.3889             22                  39.1429
Category_Mode Mid   37.5                37.25               25.7778
</code>```

Demo on SQLFiddle

Body:
In the table Products in the link below, I have 3 columns.

SupplierID, CategryID and Price.

https://www.w3schools.com/sql/trysql.asp?filename=trysql_drop_table

I want to create 3 group of SupplierID and 3 group of CategryID. The rule is listed below.

case    when SupplierID<=10 then 'SupplierID_group1'
            when 10<SupplierID and SupplierID<=15 then 'SupplierID_group2'
            when 15<SupplierID then 'SupplierID_group3'
end SupplierID_group

case    when CategoryID<=3 then 'Category_Mode Low'
        when 3< CategoryID and CategoryID<=6 then 'Category_Mode Mid'
        when 6< CategoryID then 'Category_Mode High'
end Category_Group

I want a 3-by-3 table which report the average Price for each combination of SupplierID_group and Category_Group.

My problem is that I am not allowed to create new table or new column in existing table.

Can anyone please help?

Thank you.

Harry

Body:
If your database is MySQL, this query will give you the results that you want; it works in the w3schools TryMySQL window:

SELECT CASE WHEN CategoryID<=3 THEN "Category_Mode Low"
            WHEN 3< CategoryID and CategoryID<=6 THEN "Category_Mode Mid"
            WHEN 6< CategoryID THEN "Category_Mode High"
       END AS Category_Group,
       AVG(CASE WHEN SupplierID<=10 THEN price end) AS SupplierID_group1,
       AVG(CASE WHEN 10<SupplierID and SupplierID<=15 THEN price END) AS SupplierID_group2,
       AVG(CASE WHEN 15<SupplierID THEN price END) AS SupplierID_group3
FROM Products
GROUP BY Category_Group

If you're running more standard SQL, you'll need to repeat the Category_Group expression in the GROUP BY clause:

SELECT CASE WHEN CategoryID<=3 THEN "Category_Mode Low"
            WHEN 3< CategoryID and CategoryID<=6 THEN "Category_Mode Mid"
            WHEN 6< CategoryID THEN "Category_Mode High"
       END AS Category_Group,
       AVG(CASE WHEN SupplierID<=10 THEN price end) AS SupplierID_group1,
       AVG(CASE WHEN 10<SupplierID and SupplierID<=15 THEN price END) AS SupplierID_group2,
       AVG(CASE WHEN 15<SupplierID THEN price END) AS SupplierID_group3
FROM Products
GROUP BY CASE WHEN CategoryID<=3 THEN "Category_Mode Low"
            WHEN 3< CategoryID and CategoryID<=6 THEN "Category_Mode Mid"
            WHEN 6< CategoryID THEN "Category_Mode High"
       END

Output for the sample Products table:

Category_Group      SupplierID_group1   SupplierID_group2   SupplierID_group3
Category_Mode High  27.1667             36                  19.5556
Category_Mode Low   22.3889             22                  39.1429
Category_Mode Mid   37.5                37.25               25.7778

Demo on SQLFiddle


问:
How does R lm choose contrasts with interaction between a categorical and continuous variables?
If I run lm with a formula like Y ~ X1 + X2:X1 + X3:X1 where X1 is continuous and X2,X3 are categorical, I get a contrast for both levels of X2, but not X3.

The pattern is that the first categorical interaction gets both levels but not the second.

library(tidyverse)
library(magrittr)
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#>
#>     set_names
#> The following object is masked from 'package:tidyr':
#>
#>     extract

df = data.frame(Frivolousness = sample(1:100, 50, replace =T))
df %<>% mutate(
  Personality=sample(c("Bad", "Good"), 50, replace = T),
  Timing=ifelse(Frivolousness %% 2 == 0 & runif(50) > 0.2, "Early", "Late")
  )
df %<>% mutate(
  Enchantedness = 11 +
    ifelse(Personality=="Good", 0.23, -0.052)*Frivolousness -
    1.3*ifelse(Personality=="Good", 1, 0) +
    10*rnorm(50)
  )
df %<>% mutate(
  Personality = factor(Personality, levels=c("Bad", "Good")),
  Timing = factor(Timing, levels=c("Early", "Late"))
)

lm(Enchantedness ~ Personality + Timing + Timing:Frivolousness + Personality:Frivolousness, df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Timing:Frivolousness +
#>     Personality:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate      TimingEarly:Frivolousness
#>                      -1.41757                       -0.05796
#>      TimingLate:Frivolousness  PersonalityGood:Frivolousness
#>                      -0.07433                        0.33410

lm(Enchantedness ~ Personality + Timing + Personality:Frivolousness+ Timing:Frivolousness , df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Personality:Frivolousness +
#>     Timing:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate   PersonalityBad:Frivolousness
#>                      -1.41757                       -0.05796
#> PersonalityGood:Frivolousness       TimingLate:Frivolousness
#>                       0.27614                       -0.01636
```

Created on 2020-02-15 by the reprex package (v0.3.0)

答:
You get this kind of weird behavior because you are missing the term main term, Frivolousness. If you do:

```<code>set.seed(111)
## run your data frame stuff
lm(Enchantedness ~ Personality + Timing + Timing:Frivolousness + Personality:Frivolousness, df)

Coefficients:
                  (Intercept)                PersonalityGood
                     -1.74223                        5.31189
                   TimingLate      TimingEarly:Frivolousness
                     12.47243                        0.19090
     TimingLate:Frivolousness  PersonalityGood:Frivolousness
                     -0.09496                        0.17383

    lm(Enchantedness ~ Personality + Timing + Frivolousness+Timing:Frivolousness + Personality:Frivolousness, df)

Coefficients:
                  (Intercept)                PersonalityGood
                      -1.7422                         5.3119
                   TimingLate                  Frivolousness
                      12.4724                         0.1909
     TimingLate:Frivolousness  PersonalityGood:Frivolousness
                      -0.2859                         0.1738
</code>```

In your model, the interaction term TimingLate:Frivolousness means the change in slope of Frivolousness when Timing is Late. Since the default is not estimated, it has to do it for TimingEarly (the reference level). Hence you can see the coefficients for TimingEarly:Frivolousness and Frivolousness are the same.

As you can see the TimingLate:Frivolousness are very different and In your case I think doesn't make sense to do only the interaction term without the main effect, because it's hard to interpret or model it.

You can roughly check what is the slope for different groups of timing and the model with all terms gives a good estimate:

```<code>df %>% group_by(Timing) %>% do(tidy(lm(Enchantedness ~ Frivolousness,data=.)))
# A tibble: 4 x 6
# Groups:   Timing [2]
  Timing term          estimate std.error statistic p.value
  <fct>  <chr>            <dbl>     <dbl>     <dbl>   <dbl>
1 Early  (Intercept)    6.13       6.29      0.975   0.341
2 Early  Frivolousness  0.208      0.0932    2.23    0.0366
3 Late   (Intercept)   11.5        5.35      2.14    0.0419
4 Late   Frivolousness -0.00944    0.107    -0.0882  0.930
</code>```

Body:
If I run lm with a formula like Y ~ X1 + X2:X1 + X3:X1 where X1 is continuous and X2,X3 are categorical, I get a contrast for both levels of X2, but not X3.

The pattern is that the first categorical interaction gets both levels but not the second.

library(tidyverse)
library(magrittr)
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#>
#>     set_names
#> The following object is masked from 'package:tidyr':
#>
#>     extract

df = data.frame(Frivolousness = sample(1:100, 50, replace =T))
df %<>% mutate(
  Personality=sample(c("Bad", "Good"), 50, replace = T),
  Timing=ifelse(Frivolousness %% 2 == 0 & runif(50) > 0.2, "Early", "Late")
  )
df %<>% mutate(
  Enchantedness = 11 +
    ifelse(Personality=="Good", 0.23, -0.052)*Frivolousness -
    1.3*ifelse(Personality=="Good", 1, 0) +
    10*rnorm(50)
  )
df %<>% mutate(
  Personality = factor(Personality, levels=c("Bad", "Good")),
  Timing = factor(Timing, levels=c("Early", "Late"))
)

lm(Enchantedness ~ Personality + Timing + Timing:Frivolousness + Personality:Frivolousness, df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Timing:Frivolousness +
#>     Personality:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate      TimingEarly:Frivolousness
#>                      -1.41757                       -0.05796
#>      TimingLate:Frivolousness  PersonalityGood:Frivolousness
#>                      -0.07433                        0.33410

lm(Enchantedness ~ Personality + Timing + Personality:Frivolousness+ Timing:Frivolousness , df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Personality:Frivolousness +
#>     Timing:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate   PersonalityBad:Frivolousness
#>                      -1.41757                       -0.05796
#> PersonalityGood:Frivolousness       TimingLate:Frivolousness
#>                       0.27614                       -0.01636

Created on 2020-02-15 by the reprex package (v0.3.0)

Body:
You get this kind of weird behavior because you are missing the term main term, Frivolousness. If you do:

set.seed(111)
## run your data frame stuff
lm(Enchantedness ~ Personality + Timing + Timing:Frivolousness + Personality:Frivolousness, df)

Coefficients:
                  (Intercept)                PersonalityGood
                     -1.74223                        5.31189
                   TimingLate      TimingEarly:Frivolousness
                     12.47243                        0.19090
     TimingLate:Frivolousness  PersonalityGood:Frivolousness
                     -0.09496                        0.17383

    lm(Enchantedness ~ Personality + Timing + Frivolousness+Timing:Frivolousness + Personality:Frivolousness, df)

Coefficients:
                  (Intercept)                PersonalityGood
                      -1.7422                         5.3119
                   TimingLate                  Frivolousness
                      12.4724                         0.1909
     TimingLate:Frivolousness  PersonalityGood:Frivolousness
                      -0.2859                         0.1738

In your model, the interaction term TimingLate:Frivolousness means the change in slope of Frivolousness when Timing is Late. Since the default is not estimated, it has to do it for TimingEarly (the reference level). Hence you can see the coefficients for TimingEarly:Frivolousness and Frivolousness are the same.

As you can see the TimingLate:Frivolousness are very different and In your case I think doesn't make sense to do only the interaction term without the main effect, because it's hard to interpret or model it.

You can roughly check what is the slope for different groups of timing and the model with all terms gives a good estimate:

df %>% group_by(Timing) %>% do(tidy(lm(Enchantedness ~ Frivolousness,data=.)))
# A tibble: 4 x 6
# Groups:   Timing [2]
  Timing term          estimate std.error statistic p.value
  <fct>  <chr>            <dbl>     <dbl>     <dbl>   <dbl>
1 Early  (Intercept)    6.13       6.29      0.975   0.341
2 Early  Frivolousness  0.208      0.0932    2.23    0.0366
3 Late   (Intercept)   11.5        5.35      2.14    0.0419
4 Late   Frivolousness -0.00944    0.107    -0.0882  0.930


答:
You don't need to create an extra table to preprocess the results. You can use a CTE (Common Table Expression) or a plain table expression.

Here I used the latter:

```<code>select
  category_group,
  avg(g1) as 'SupplierID_group1',
  avg(g2) as 'SupplierID_group2',
  avg(g3) as 'SupplierID_group3'
from (
  select
    case when SupplierID<=10 then price else 0 end as g1,
    case when 10<SupplierID and SupplierID<=15 then price else 0 end as g2,
    case when 15<SupplierID then price  else 0 end as g3,
    case when CategoryID<=3 then 'Category_Mode Low'
         when 3< CategoryID and CategoryID<=6 then 'Category_Mode Mid'
         else 'Category_Mode High'
    end category_group
  from products
) x
group by category_group
</code>```

Result:

```<code>category_group      SupplierID_group1  SupplierID_group2  SupplierID_group3
------------------  -----------------  -----------------  -----------------
Category_Mode High  9.5882             4.2353             10.3529
Category_Mode Low   10.8919            2.973              14.8108
Category_Mode Mid   9.7826             12.9565            10.087
</code>```

See SQL Fiddle.

Title: Create 2-dimension table reporting average

Body:
You don't need to create an extra table to preprocess the results. You can use a CTE (Common Table Expression) or a plain table expression.

Here I used the latter:

select
  category_group,
  avg(g1) as 'SupplierID_group1',
  avg(g2) as 'SupplierID_group2',
  avg(g3) as 'SupplierID_group3'
from (
  select
    case when SupplierID<=10 then price else 0 end as g1,
    case when 10<SupplierID and SupplierID<=15 then price else 0 end as g2,
    case when 15<SupplierID then price  else 0 end as g3,
    case when CategoryID<=3 then 'Category_Mode Low'
         when 3< CategoryID and CategoryID<=6 then 'Category_Mode Mid'
         else 'Category_Mode High'
    end category_group
  from products
) x
group by category_group

Result:

category_group      SupplierID_group1  SupplierID_group2  SupplierID_group3
------------------  -----------------  -----------------  -----------------
Category_Mode High  9.5882             4.2353             10.3529
Category_Mode Low   10.8919            2.973              14.8108
Category_Mode Mid   9.7826             12.9565            10.087

See SQL Fiddle.


问:
How to simulate silent login to Facebook Graph API?
I'm working on an API that will aggregate data from several website, including facebook. The API has an engine that harvests data on regular intervals, and then the client app polls the API to get the data from all websites centrally.

The problem is that the API has no way of authenticating on the regular, behind-the-scenes harvests, as Facebook insists that the user has to click on the OAuth Dialog. With the short story being that there is no way to login to graph API silently this almost means that developing such an API is not possible (except for harvesting only public data).

However, I'm not easily satisfied by "it's not possible" answers and my clients - even less so. Accessing private information on demmand is defnitely possible as Facebook apps do that. For example, the official Twitter app posts on my wall whenever I tweet. I guess apps only need a permission once and then can access the user's profile as much as they like.
So this leads me to think that I should do a combination of a Graph API client and an application that talk to each other, and whenever the API needs to harvest - it asks the app to get the data and fetch it to the API. Or maybe it should be a push model (the app sends the data whenever it's generated) rather than pull (the API requests the data at regular intervals).
Am I on the right track? Is any of these the correct design approach?

I did some searching but it's very hard to find any useful discussion on the topic as whatever keywords I try I only find "Can I login silently? No" type of discussions.

答: You'll want to look into the offline_access permission. This lets you access a user's data when they don't have an active session, or are offline. That's as close to "silent login" as you can get.


问:
How can I pass multiple std::filesystem options?
Here is my recursive copy line:

```<code>fs::copy(line, backupLocation, fs::copy_options::recursive);
</code>```

I want to have it be both recursive and update existing.
So something like:

```<code>fs::copy(line, backupLocation, fs::copy_options::recursive, fs::copyoptions::update_existing);
</code>```

The above is invalid. How do I achieve this? Thank you.

答:
From https://en.cppreference.com/w/cpp/filesystem/copy_options:

copy_options satisfies the requirements of BitmaskType

This means you should be able to OR them together:

```<code>fs::copy(line, backupLocation, fs::copy_options::recursive | fs::copyoptions::update_existing);
</code>```

Body:
Here is my recursive copy line:

fs::copy(line, backupLocation, fs::copy_options::recursive);

I want to have it be both recursive and update existing.
So something like:

fs::copy(line, backupLocation, fs::copy_options::recursive, fs::copyoptions::update_existing);

The above is invalid. How do I achieve this? Thank you.

Body:
From https://en.cppreference.com/w/cpp/filesystem/copy_options:

copy_options satisfies the requirements of BitmaskType

This means you should be able to OR them together:

fs::copy(line, backupLocation, fs::copy_options::recursive | fs::copyoptions::update_existing);


问:
How to create Semaphores in c?
Im trying to recreate a "Blackbox" library. In my CS class when we are supposed to use Semaphores (in our on paper final) we are given a "sem.h" file. there are 3 functions one for creating a new Semaphore with an inital number of tokens, one for taking a token out of a semaphore and one for placing a token into a semaphore. at 0 tokes any thread using the blocking funktion has to wait for a token.

for better understanding ive been trying to recreate this sem.h and sem.c based on some exams asking for an implementation of single funktions. since this is all intended to be done on paper, it donst compile but I feel im close

sem.h

```<code>typedef struct SEM SEM;
struct SEM *semCreate(int);
void P(struct SEM*); //tokens--
void V(struct SEM*); //tokens++
</code>```

sem.c

```<code>#include "sem.h"
#include <pthread.h>
#include <errno.h>
typedef struct SEM{
    volatile int val; //number of tokens
    pthread_mutex_t m;
    pthread_cond_t c;
}SEM;

/*create new semaphore with #initVal tokens */
SEM *semCreate(int initVal){
    static SEM *sem ={
        .val=initVal
    };
    errno = 0;
    if((errno = pthread_mutex_init(&sem->m,NULL))!=0){
        return NULL;
    }
    if((errno = pthread_cond_init(&sem->c,NULL))!=0){
        return NULL;
    }
    return sem;
}
//take a token from the semaphore
void P(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }
    while(sem->val <=0){
        if((errno=pthread_cond_wait(&sem->c,&sem->m))!=0){
            pthread_mutex_unlock(&sem->m);
            return;
        }
        sem->val--;
        if(errno = pthread_mutex_unlock(&sem->m)!=0)return;
    }
}
//put a token into the semaphore
void V(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }

    sem-> val++;

    if((errno = pthread_cond_broadcast(&sem->c))!=0)return;
    if((errno=pthread_mutex_unlock(&sem->m)!=0)) return;
}

</code>```

Incase it isnt clear what this is for:
The functions should limit how many threads can access a segment of code at the same time
example

```<code>//global
static SEM *sem = semCreate(1);
/.../
//critical segment in threadfunction
P(sem);
doReadAndWriteGlobalList();
V(sem);
</code>```

as soon as the 1st thread passes P() any subsequent calls of P wont be able to pass it until V was called on the same sem

on compiling I get the following error:

```<code>sem.c: In function ‘semCreate’:
sem.c:14:3: error: field name not in record or union initializer
   .val=initVal
   ^
sem.c:14:3: note: (near initialization for ‘sem’)
sem.c:14:8: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
   .val=initVal
        ^~~~~~~
sem.c:14:8: note: (near initialization for ‘sem’)
sem.c:14:8: error: initializer element is not constant
sem.c:14:8: note: (near initialization for ‘sem’)
cc1: all warnings being treated as errors
</code>```

答:
Your Procure is wrong.
Inside the loop, you release the mutex; which invalidates both the test at the top of the loop and the cond wait.

You probably want something like:

```<code>   lock(&s->mutex);
   while (s->val <= 0) {
        wait(&s->cv, &s->mutex);
   }
   s->val--;
   unlock(&s->mutex);
</code>```

A wakeup from a condition variable is just an indication you should recheck your condition; not an assertion that your condition has arrived.

Title: How to create Semaphores in c?

Body:
Im trying to recreate a "Blackbox" library. In my CS class when we are supposed to use Semaphores (in our on paper final) we are given a "sem.h" file. there are 3 functions one for creating a new Semaphore with an inital number of tokens, one for taking a token out of a semaphore and one for placing a token into a semaphore. at 0 tokes any thread using the blocking funktion has to wait for a token.

for better understanding ive been trying to recreate this sem.h and sem.c based on some exams asking for an implementation of single funktions. since this is all intended to be done on paper, it donst compile but I feel im close

sem.h

typedef struct SEM SEM;
struct SEM *semCreate(int);
void P(struct SEM*); //tokens--
void V(struct SEM*); //tokens++

sem.c

#include "sem.h"
#include <pthread.h>
#include <errno.h>
typedef struct SEM{
    volatile int val; //number of tokens
    pthread_mutex_t m;
    pthread_cond_t c;
}SEM;

/*create new semaphore with #initVal tokens */
SEM *semCreate(int initVal){
    static SEM *sem ={
        .val=initVal
    };
    errno = 0;
    if((errno = pthread_mutex_init(&sem->m,NULL))!=0){
        return NULL;
    }
    if((errno = pthread_cond_init(&sem->c,NULL))!=0){
        return NULL;
    }
    return sem;
}
//take a token from the semaphore
void P(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }
    while(sem->val <=0){
        if((errno=pthread_cond_wait(&sem->c,&sem->m))!=0){
            pthread_mutex_unlock(&sem->m);
            return;
        }
        sem->val--;
        if(errno = pthread_mutex_unlock(&sem->m)!=0)return;
    }
}
//put a token into the semaphore
void V(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }

    sem-> val++;

    if((errno = pthread_cond_broadcast(&sem->c))!=0)return;
    if((errno=pthread_mutex_unlock(&sem->m)!=0)) return;
}

Incase it isnt clear what this is for:
The functions should limit how many threads can access a segment of code at the same time
example

//global
static SEM *sem = semCreate(1);
/.../
//critical segment in threadfunction
P(sem);
doReadAndWriteGlobalList();
V(sem);

as soon as the 1st thread passes P() any subsequent calls of P wont be able to pass it until V was called on the same sem

on compiling I get the following error:

sem.c: In function ‘semCreate’:
sem.c:14:3: error: field name not in record or union initializer
   .val=initVal
   ^
sem.c:14:3: note: (near initialization for ‘sem’)
sem.c:14:8: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
   .val=initVal
        ^~~~~~~
sem.c:14:8: note: (near initialization for ‘sem’)
sem.c:14:8: error: initializer element is not constant
sem.c:14:8: note: (near initialization for ‘sem’)
cc1: all warnings being treated as errors

Body:
Your Procure is wrong.
Inside the loop, you release the mutex; which invalidates both the test at the top of the loop and the cond wait.

You probably want something like:

   lock(&s->mutex);
   while (s->val <= 0) {
        wait(&s->cv, &s->mutex);
   }
   s->val--;
   unlock(&s->mutex);

A wakeup from a condition variable is just an indication you should recheck your condition; not an assertion that your condition has arrived.


答:
One more thing...

You can use BeautifulSoup to just find the parts of the xml file that you're extracting data from. Would stagger processing as-needed rather than loading the entire file into a variable and then iterating element by element.

For example:

If your xml file has tags such as:

```<code><pos reviews>
<review_id>001<review_id>
<reviewer_name>John Stamos (From full house)</reviewer_name>
<review_text>This is a great item</review_text>
</code>```

You could just beautifulsoup.findAll(whatever tag) and just grab that data. I don't know what you're doing specifically, though. Figured it was worth suggesting.

Body:
I have to parse a large amount of XML files and write it to a text file. However, some of the XML files contain special/illegal characters. I have tried using different methods such as Escaping strings for use in XML
but I could not get it to work. I know 1 way to solve this is by editing the XML file itself, but there are thousands of files.

import os
from xml.etree import ElementTree
from xml.sax.saxutils import escape

fileNum = 0;
saveFile = open('NewYork_1.txt','w')

for path, dirs, files in os.walk("NewYork_1"):
   for f in files:
      fileName = os.path.join(path, f)
      with open(fileName,'r', encoding='utf-8') as myFile:
        # print(myFile.read())
        if "&" in myFile:
            myFile = myFile.replace("&", "&") #This does not work.

Also, some of the XML files also have unicode in them. There are emojis.

<Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
      <UserID></UserID>
      <Date></Date>
      <icontent></icontent>
   </InitPost>
   <Post>
      <UserID></UserID>
      <Date></Date>
      <rcontent></rcontent>
  </Post>
</Thread>

Body:
One more thing...

You can use BeautifulSoup to just find the parts of the xml file that you're extracting data from. Would stagger processing as-needed rather than loading the entire file into a variable and then iterating element by element.

For example:

If your xml file has tags such as:

<pos reviews>
<review_id>001<review_id>
<reviewer_name>John Stamos (From full house)</reviewer_name>
<review_text>This is a great item</review_text>

You could just beautifulsoup.findAll(whatever tag) and just grab that data. I don't know what you're doing specifically, though. Figured it was worth suggesting.


问:
Angular subscribe. Can't get to data
UPDATE
How I managed to do it is below (scroll to my answer or here's the link):
https://stackoverflow.com/a/55013081/1729405

I'm trying to build a APIService in Angular 7. I'm using subscribe to push to an array which I can't access through another service.

Here's the api service method:

```<code>  getResponse(url):Observable<any> {
    return this.http.post(url, '', {responseType: 'text'});
  }

  getAll() {
      this.getResponse(this.todayApiUrl).subscribe(
        (response) => {
          this.data.push(response);
        });

      return this.data;
  }
</code>```

Here's how I'm trying to call it in the secondary service:

```<code>export class AdsHealthService {
  today = this.callResponseApiService.getAll();

  constructor(private callResponseApiService: CallResponseApiService) { }

  getHealthValue(interval, type) {
    let obj = this.today;
    console.log(obj);
  }
}
</code>```

In the attached image is what I get when I console.log() the response. It looks like an array but when I try to access the first element, I get an undefined message. What am I doing wrong??

答:
you can do it like this:

In your app-component:

```<code>public getDataFromService() {
  this._api.getData(this);
}

public setData(data: any){
 this.data=data;
}
</code>```

In your service.ts:

```<code>public getData(obj: appComponentModel){
    this.http.get(url).subscribe(res => obj.setData(res));
}
</code>```

its not exactly in the same format as your question but is easy one to understand by anyone.

Title: Angular subscribe. Can't get to data

Body:
UPDATE
How I managed to do it is below (scroll to my answer or here's the link):
https://stackoverflow.com/a/55013081/1729405

I'm trying to build a APIService in Angular 7. I'm using subscribe to push to an array which I can't access through another service.

Here's the api service method:

  getResponse(url):Observable<any> {
    return this.http.post(url, '', {responseType: 'text'});
  }

  getAll() {
      this.getResponse(this.todayApiUrl).subscribe(
        (response) => {
          this.data.push(response);
        });

      return this.data;
  }

Here's how I'm trying to call it in the secondary service:

export class AdsHealthService {
  today = this.callResponseApiService.getAll();

  constructor(private callResponseApiService: CallResponseApiService) { }

  getHealthValue(interval, type) {
    let obj = this.today;
    console.log(obj);
  }
}

In the attached image is what I get when I console.log() the response. It looks like an array but when I try to access the first element, I get an undefined message. What am I doing wrong??

Body:
you can do it like this:

In your app-component:

public getDataFromService() {
  this._api.getData(this);
}

public setData(data: any){
 this.data=data;
}

In your service.ts:

public getData(obj: appComponentModel){
    this.http.get(url).subscribe(res => obj.setData(res));
}

its not exactly in the same format as your question but is easy one to understand by anyone.