问:
Django users can't login after I create an account but admin can and i didnt create any registration form by only manually can add users
I've created a login page as a homepage and only by adding manually in Django administration can create a user. I didn't create a registration form and message error else statement in home viwes.py is working on the admin panel. If I login by user, I get CSRF token error

homepage
views.py

```<code>from django.shortcuts import redirect, render
from loginapp.models import Register
from django.contrib import messages
from django.contrib.auth import authenticate, login , logout

def home(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request,username=username, password=password)
   if user is not None:
      login(request, user)
      return render(request, "home.html")
   else:
        messages.error(request, "Bad Creds!!")
        return redirect('/')

 return render(request, "home.html")
</code>```

login page views.py

```<code>def index(request):
  return render(request, "index.html")
</code>```

login page name as index.html

```<code><form id="stripe-login" method="POST" action="{% url 'home' %}">
  {% csrf_token %}
 <div class="trick" style="padding-bottom: 10px;">
   <input type="text" name="username" required>
   <label for="email">Username</label>
 </div>
 <div class=" trick" style="padding-bottom:10px;">
   <input type="password" name="password" required>
   <label for="password">Password</label>
 </div>

 <div class="field"  style="padding-bottom:10px; padding-top: 10px;">
   <input type="submit" name="submit" value="Continue">
 </div>
 <div class="reset-pass" style="padding-top: 20px;">
   <a href="#">Forgot your password?</a>
 </div>
 <div class="footer-link text-light" style="padding-top:10px;">
   <span>
     Don't have an account?
     <a href="{% url 'signup' %}">
       Request for a new account
     </a>
   </span>
 </div>
</form>
</code>```

答:
for creating user you must use
User.objects.create_user() method
Ex: User.objects.create_user(username=username,email=email,password=password)</p>

Body:
I've created a login page as a homepage and only by adding manually in Django administration can create a user. I didn't create a registration form and message error else statement in home viwes.py is working on the admin panel. If I login by user, I get CSRF token error

homepage
views.py

from django.shortcuts import redirect, render
from loginapp.models import Register
from django.contrib import messages
from django.contrib.auth import authenticate, login , logout

def home(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request,username=username, password=password)
   if user is not None:
      login(request, user)
      return render(request, "home.html")
   else:
        messages.error(request, "Bad Creds!!")
        return redirect('/')

 return render(request, "home.html")

login page views.py

def index(request):
  return render(request, "index.html")

login page name as index.html

<form id="stripe-login" method="POST" action="{% url 'home' %}">
  {% csrf_token %}

   <input type="text" name="username" required>
   Username

   <input type="password" name="password" required>
   Password

   <input type="submit" name="submit" value="Continue">

   Forgot your password?

     Don't have an account?

       Request for a new account

</form>


来源: stackexchange

问:
How to get all the data from clause from a string with SAX parser?
I have an application in response I get some data which I store into the string like below I

Want all clause data like all  &  how can I get?

Here is my code.

```<code>import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class soaparse {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        String ss =
        "<![CDATA[<translation>"+
     "<clause keyword=\"Alternative\"><en>Alternative</en><alt>Alternative</alt></clause>"+
     "<clause keyword=\"Back\"><en>Back</en><alt>Back</alt></clause>"+
     "<clause keyword=\"BackgroundImage\"><en>Bg. Image</en><alt>Bg. Image</alt></clause>"+
     "<clause keyword=\"ButtonColor\"><en>Button Color</en><alt>Button Color</alt></clause>"+
     "<clause keyword=\"ButtonText\"><en>Button Text</en><alt>Button Text</alt></clause>"+
     "<clause keyword=\"CategoryId\"><en>Category Id</en><alt>Category Id</alt></clause>"+
     "<clause keyword=\"English\"><en>English</en><alt>English</alt></clause>"+
     "<clause keyword=\"GsmNo\"><en>Gsm No</en><alt>Gsm No</alt></clause>"+
     "<clause keyword=\"GsmNumber\"><en>Gsm Number</en><alt>Gsm Number</alt></clause>"+
     "<clause keyword=\"LabelColor\"><en>Label Color</en><alt>Label Color</alt></clause>"+
     "<clause keyword=\"Language\"><en>Language</en><alt>Language</alt></clause>"+
     "<clause keyword=\"LanguageId\"><en>Lang Id</en><alt>Lang Id</alt></clause>"+
     "<clause keyword=\"Password\"><en>Password</en><alt>Password</alt></clause>"+
     "<clause keyword=\"PosSetup\"><en>Pos Setup</en><alt>Pos Setup</alt></clause>"+
    "<clause keyword=\"Redemption\"><en>Redemption</en><alt>Redemption</alt></clause>"+
     "<clause keyword=\"RedemptionSetup\"><en>Redemption Setup</en><alt>Redemption Setup</alt></clause>"+
     "<clause keyword=\"Sale\"><en>Sale</en><alt>Sale</alt></clause>"+
     "<clause keyword=\"Save\"><en>Save</en><alt>Save</alt></clause>"+
     "<clause keyword=\"ServiceUrl\"><en>Service Url</en><alt>Service Url</alt></clause>"+
     "<clause keyword=\"Setup\"><en>Setup</en><alt>Setup</alt></clause>"+
     "<clause keyword=\"Submit\"><en>Submit</en><alt>Submit</alt></clause>"+
     "<clause keyword=\"TerminalId\"><en>Terminal Id</en><alt>Terminal Id</alt></clause>"+
     "<clause keyword=\"TransactionId\"><en>Transaction Id</en><alt>Transaction Id</alt></clause>"+
     "<clause keyword=\"Void\"><en>Void</en><alt>Void</alt></clause>"+
     "<clause keyword=\"Voucher\"><en>Voucher</en><alt>Voucher</alt></clause>"+
     "<clause keyword=\"VoucherId\"><en>Voucher Id</en><alt>Voucher Id</alt></clause>"+
     " </translation>]]>";

         DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource in = new InputSource();
            in.setCharacterStream(new StringReader(ss));

            Document doc = db.parse(in);
            NodeList nodes = doc.getElementsByTagName("GetTranslationResult");

         for (int i = 0; i < nodes.getLength(); i++) {
              Element element = (Element) nodes.item(i);

              NodeList name = element.getElementsByTagName("en");
              Element line = (Element) name.item(i);
              System.out.println("Name: " + getCharacterDataFromElement(line));

              NodeList title = element.getElementsByTagName("alt");
              line = (Element) title.item(i);
              System.out.println("Title: " + getCharacterDataFromElement(line));

            }
    }

     public static String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
              CharacterData cd = (CharacterData) child;
              return cd.getData();
            }
            return "";
          }
}
</code>```

答:
I work on your query, and created parser class and calling class for solution.

XML Handler Class

```<code>class xmlHandler extends DefaultHandler {
    private Vector nodes = new Vector();
    private Stack tagStack = new Stack();

    public void startDocument() throws SAXException {
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // System.out.println("1");
        if (qName.equals("clause")) {
            Noden node = new Noden();
            nodes.addElement(node);
            // System.out.println("2");
        }
        // System.out.println("3");
        tagStack.push(qName);
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String chars = new String(ch, start, length).trim();

        if (chars.length() > 0) {
            String qName = (String) tagStack.peek();
            Noden currentnode = (Noden) nodes.lastElement();
            // System.out.println(qName);

            if (qName.equals("en")) {
                currentnode.setEn(chars);
            } else if (qName.equals("alt")) {
                currentnode.setAlt(chars);
            }
        }
    }

    public void endElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        tagStack.pop();
    }

    public void endDocument() throws SAXException {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < nodes.size(); i++) {
            Noden currentnode = (Noden) nodes.elementAt(i);
            result.append("En : " + currentnode.getEn() + " Alt : "
                    + currentnode.getAlt() + "\n");
        }
        System.out.println(result.toString());
    }

    class Noden {
        private String en;
        private String alt;

        public Noden() {
        }

        public void setEn(String en) {
            this.en = en;
        }

        public void setAlt(String alt) {
            this.alt = alt;
        }

        public String getEn() {
            return en;
        }

        public String getAlt() {
            return alt;
        }
    };
</code>```

and Calling Function

```<code>try
        {
          SAXParserFactory factory = SAXParserFactory.newInstance();
          SAXParser saxParser = factory.newSAXParser();
          InputStream is = null;

          String xml = "<![CDATA[<translation>"+
          "<clause keyword=\"Alternative\"><en>Alternative</en><alt>Alternative</alt></clause>"+
          "<clause keyword=\"Back\"><en>Back</en><alt>Back</alt></clause>"+
          "<clause keyword=\"BackgroundImage\"><en>Bg. Image</en><alt>Bg. Image</alt></clause>"+
          "<clause keyword=\"ButtonColor\"><en>Button Color</en><alt>Button Color</alt></clause>"+
          "<clause keyword=\"ButtonText\"><en>Button Text</en><alt>Button Text</alt></clause>"+
          "<clause keyword=\"CategoryId\"><en>Category Id</en><alt>Category Id</alt></clause>"+
          "<clause keyword=\"English\"><en>English</en><alt>English</alt></clause>"+
          "<clause keyword=\"GsmNo\"><en>Gsm No</en><alt>Gsm No</alt></clause>"+
          "<clause keyword=\"GsmNumber\"><en>Gsm Number</en><alt>Gsm Number</alt></clause>"+
          "<clause keyword=\"LabelColor\"><en>Label Color</en><alt>Label Color</alt></clause>"+
          "<clause keyword=\"Language\"><en>Language</en><alt>Language</alt></clause>"+
          "<clause keyword=\"LanguageId\"><en>Lang Id</en><alt>Lang Id</alt></clause>"+
          "<clause keyword=\"Password\"><en>Password</en><alt>Password</alt></clause>"+
          "<clause keyword=\"PosSetup\"><en>Pos Setup</en><alt>Pos Setup</alt></clause>"+
         "<clause keyword=\"Redemption\"><en>Redemption</en><alt>Redemption</alt></clause>"+
          "<clause keyword=\"RedemptionSetup\"><en>Redemption Setup</en><alt>Redemption Setup</alt></clause>"+
          "<clause keyword=\"Sale\"><en>Sale</en><alt>Sale</alt></clause>"+
          "<clause keyword=\"Save\"><en>Save</en><alt>Save</alt></clause>"+
          "<clause keyword=\"ServiceUrl\"><en>Service Url</en><alt>Service Url</alt></clause>"+
          "<clause keyword=\"Setup\"><en>Setup</en><alt>Setup</alt></clause>"+
          "<clause keyword=\"Submit\"><en>Submit</en><alt>Submit</alt></clause>"+
          "<clause keyword=\"TerminalId\"><en>Terminal Id</en><alt>Terminal Id</alt></clause>"+
          "<clause keyword=\"TransactionId\"><en>Transaction Id</en><alt>Transaction Id</alt></clause>"+
          "<clause keyword=\"Void\"><en>Void</en><alt>Void</alt></clause>"+
          "<clause keyword=\"Voucher\"><en>Voucher</en><alt>Voucher</alt></clause>"+
          "<clause keyword=\"VoucherId\"><en>Voucher Id</en><alt>Voucher Id</alt></clause>"+
          " </translation>]]>";

          String newXml = xml.substring(xml.indexOf("<translation>"), xml.indexOf("]]"));
          System.out.println(newXml);
          is = new ByteArrayInputStream(newXml.getBytes());
          InputSource inputSource = new InputSource(is);
          saxParser.parse(inputSource,new xmlHandler());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an application in response I get some data which I store into the string like below I

Want all clause data like all  &  how can I get?

Here is my code.

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class soaparse {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        String ss =
        "<![CDATA[<translation>"+
     "<clause keyword=\"Alternative\"><en>Alternative</en><alt>Alternative</alt></clause>"+
     "<clause keyword=\"Back\"><en>Back</en><alt>Back</alt></clause>"+
     "<clause keyword=\"BackgroundImage\"><en>Bg. Image</en><alt>Bg. Image</alt></clause>"+
     "<clause keyword=\"ButtonColor\"><en>Button Color</en><alt>Button Color</alt></clause>"+
     "<clause keyword=\"ButtonText\"><en>Button Text</en><alt>Button Text</alt></clause>"+
     "<clause keyword=\"CategoryId\"><en>Category Id</en><alt>Category Id</alt></clause>"+
     "<clause keyword=\"English\"><en>English</en><alt>English</alt></clause>"+
     "<clause keyword=\"GsmNo\"><en>Gsm No</en><alt>Gsm No</alt></clause>"+
     "<clause keyword=\"GsmNumber\"><en>Gsm Number</en><alt>Gsm Number</alt></clause>"+
     "<clause keyword=\"LabelColor\"><en>Label Color</en><alt>Label Color</alt></clause>"+
     "<clause keyword=\"Language\"><en>Language</en><alt>Language</alt></clause>"+
     "<clause keyword=\"LanguageId\"><en>Lang Id</en><alt>Lang Id</alt></clause>"+
     "<clause keyword=\"Password\"><en>Password</en><alt>Password</alt></clause>"+
     "<clause keyword=\"PosSetup\"><en>Pos Setup</en><alt>Pos Setup</alt></clause>"+
    "<clause keyword=\"Redemption\"><en>Redemption</en><alt>Redemption</alt></clause>"+
     "<clause keyword=\"RedemptionSetup\"><en>Redemption Setup</en><alt>Redemption Setup</alt></clause>"+
     "<clause keyword=\"Sale\"><en>Sale</en><alt>Sale</alt></clause>"+
     "<clause keyword=\"Save\"><en>Save</en><alt>Save</alt></clause>"+
     "<clause keyword=\"ServiceUrl\"><en>Service Url</en><alt>Service Url</alt></clause>"+
     "<clause keyword=\"Setup\"><en>Setup</en><alt>Setup</alt></clause>"+
     "<clause keyword=\"Submit\"><en>Submit</en><alt>Submit</alt></clause>"+
     "<clause keyword=\"TerminalId\"><en>Terminal Id</en><alt>Terminal Id</alt></clause>"+
     "<clause keyword=\"TransactionId\"><en>Transaction Id</en><alt>Transaction Id</alt></clause>"+
     "<clause keyword=\"Void\"><en>Void</en><alt>Void</alt></clause>"+
     "<clause keyword=\"Voucher\"><en>Voucher</en><alt>Voucher</alt></clause>"+
     "<clause keyword=\"VoucherId\"><en>Voucher Id</en><alt>Voucher Id</alt></clause>"+
     " </translation>]]>";

         DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource in = new InputSource();
            in.setCharacterStream(new StringReader(ss));

            Document doc = db.parse(in);
            NodeList nodes = doc.getElementsByTagName("GetTranslationResult");

         for (int i = 0; i < nodes.getLength(); i++) {
              Element element = (Element) nodes.item(i);

              NodeList name = element.getElementsByTagName("en");
              Element line = (Element) name.item(i);
              System.out.println("Name: " + getCharacterDataFromElement(line));

              NodeList title = element.getElementsByTagName("alt");
              line = (Element) title.item(i);
              System.out.println("Title: " + getCharacterDataFromElement(line));

            }
    }

     public static String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
              CharacterData cd = (CharacterData) child;
              return cd.getData();
            }
            return "";
          }
}

Body:
I work on your query, and created parser class and calling class for solution.

XML Handler Class

class xmlHandler extends DefaultHandler {
    private Vector nodes = new Vector();
    private Stack tagStack = new Stack();

    public void startDocument() throws SAXException {
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // System.out.println("1");
        if (qName.equals("clause")) {
            Noden node = new Noden();
            nodes.addElement(node);
            // System.out.println("2");
        }
        // System.out.println("3");
        tagStack.push(qName);
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String chars = new String(ch, start, length).trim();

        if (chars.length() > 0) {
            String qName = (String) tagStack.peek();
            Noden currentnode = (Noden) nodes.lastElement();
            // System.out.println(qName);

            if (qName.equals("en")) {
                currentnode.setEn(chars);
            } else if (qName.equals("alt")) {
                currentnode.setAlt(chars);
            }
        }
    }

    public void endElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        tagStack.pop();
    }

    public void endDocument() throws SAXException {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < nodes.size(); i++) {
            Noden currentnode = (Noden) nodes.elementAt(i);
            result.append("En : " + currentnode.getEn() + " Alt : "
                    + currentnode.getAlt() + "\n");
        }
        System.out.println(result.toString());
    }

    class Noden {
        private String en;
        private String alt;

        public Noden() {
        }

        public void setEn(String en) {
            this.en = en;
        }

        public void setAlt(String alt) {
            this.alt = alt;
        }

        public String getEn() {
            return en;
        }

        public String getAlt() {
            return alt;
        }
    };

and Calling Function

try
        {
          SAXParserFactory factory = SAXParserFactory.newInstance();
          SAXParser saxParser = factory.newSAXParser();
          InputStream is = null;

          String xml = "<![CDATA[<translation>"+
          "<clause keyword=\"Alternative\"><en>Alternative</en><alt>Alternative</alt></clause>"+
          "<clause keyword=\"Back\"><en>Back</en><alt>Back</alt></clause>"+
          "<clause keyword=\"BackgroundImage\"><en>Bg. Image</en><alt>Bg. Image</alt></clause>"+
          "<clause keyword=\"ButtonColor\"><en>Button Color</en><alt>Button Color</alt></clause>"+
          "<clause keyword=\"ButtonText\"><en>Button Text</en><alt>Button Text</alt></clause>"+
          "<clause keyword=\"CategoryId\"><en>Category Id</en><alt>Category Id</alt></clause>"+
          "<clause keyword=\"English\"><en>English</en><alt>English</alt></clause>"+
          "<clause keyword=\"GsmNo\"><en>Gsm No</en><alt>Gsm No</alt></clause>"+
          "<clause keyword=\"GsmNumber\"><en>Gsm Number</en><alt>Gsm Number</alt></clause>"+
          "<clause keyword=\"LabelColor\"><en>Label Color</en><alt>Label Color</alt></clause>"+
          "<clause keyword=\"Language\"><en>Language</en><alt>Language</alt></clause>"+
          "<clause keyword=\"LanguageId\"><en>Lang Id</en><alt>Lang Id</alt></clause>"+
          "<clause keyword=\"Password\"><en>Password</en><alt>Password</alt></clause>"+
          "<clause keyword=\"PosSetup\"><en>Pos Setup</en><alt>Pos Setup</alt></clause>"+
         "<clause keyword=\"Redemption\"><en>Redemption</en><alt>Redemption</alt></clause>"+
          "<clause keyword=\"RedemptionSetup\"><en>Redemption Setup</en><alt>Redemption Setup</alt></clause>"+
          "<clause keyword=\"Sale\"><en>Sale</en><alt>Sale</alt></clause>"+
          "<clause keyword=\"Save\"><en>Save</en><alt>Save</alt></clause>"+
          "<clause keyword=\"ServiceUrl\"><en>Service Url</en><alt>Service Url</alt></clause>"+
          "<clause keyword=\"Setup\"><en>Setup</en><alt>Setup</alt></clause>"+
          "<clause keyword=\"Submit\"><en>Submit</en><alt>Submit</alt></clause>"+
          "<clause keyword=\"TerminalId\"><en>Terminal Id</en><alt>Terminal Id</alt></clause>"+
          "<clause keyword=\"TransactionId\"><en>Transaction Id</en><alt>Transaction Id</alt></clause>"+
          "<clause keyword=\"Void\"><en>Void</en><alt>Void</alt></clause>"+
          "<clause keyword=\"Voucher\"><en>Voucher</en><alt>Voucher</alt></clause>"+
          "<clause keyword=\"VoucherId\"><en>Voucher Id</en><alt>Voucher Id</alt></clause>"+
          " </translation>]]>";

          String newXml = xml.substring(xml.indexOf("<translation>"), xml.indexOf("]]"));
          System.out.println(newXml);
          is = new ByteArrayInputStream(newXml.getBytes());
          InputSource inputSource = new InputSource(is);
          saxParser.parse(inputSource,new xmlHandler());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }


问:
Remove the extra " " in "lng " in array object javascript
The below code is for csv to array. I am getting an extra "space" in the output.

Example:
output : {lat: 42.546245, "lng ": 1.601554}

expected : {lat: 42.546245, "lng": 1.601554}
Help needed in removing the extra space in the "lng "header.

```<code>function initMap() {
mapLoad();
readFiles();

 }
function readFiles() {
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");

  function csvToArray(str, delimiter = ",") {

    // slice from start of text to the first \n index
    // use split to create an array from string by delimiter
    console.log(str);
    const headers = str.slice(0, str.indexOf("\n")).split(delimiter);

    // slice from \n index + 1 to the end of the text
    // use split to create an array of each csv value row
    // const rows = str.slice(str.indexOf("\n") + 1).split("\n");
    const rows = str.slice(str.indexOf("\n") + 1).split("\n");

    // Map the rows
    // split values from each row into an array
    // use headers.reduce to create an object
    // object properties derived from headers:values
    // the object passed as an element of the array
    const arr = rows.map(function (row) {
      const values = row.split(delimiter).map(Number);
      const el = headers.reduce(function (object, header, index) {
        object[header] = values[index];
        return object;
      }, {});
      return el;
    });

    // return the array
    return arr;
  }

  myForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const input = csvFile.files[0];
    const reader = new FileReader();

    reader.onload = function (e) {
      const text = e.target.result;
      const data = csvToArray(text);
      console.log(data);
      mapLoad_1(data);
    };

    reader.readAsText(input);
  });
  }
</code>```

答:
When you get the title, you can remove all spaces through the trim() function</p>
```<code>const headers = str.slice(0,str.indexOf("\n")).trim().split(delimiter);

const rows = str.slice(str.indexOf("\n") + 1).trim().split("\n");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The below code is for csv to array. I am getting an extra "space" in the output.

Example:
output : {lat: 42.546245, "lng ": 1.601554}

expected : {lat: 42.546245, "lng": 1.601554}
Help needed in removing the extra space in the "lng "header.

function initMap() {
mapLoad();
readFiles();

 }
function readFiles() {
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");

  function csvToArray(str, delimiter = ",") {

    // slice from start of text to the first \n index
    // use split to create an array from string by delimiter
    console.log(str);
    const headers = str.slice(0, str.indexOf("\n")).split(delimiter);

    // slice from \n index + 1 to the end of the text
    // use split to create an array of each csv value row
    // const rows = str.slice(str.indexOf("\n") + 1).split("\n");
    const rows = str.slice(str.indexOf("\n") + 1).split("\n");

    // Map the rows
    // split values from each row into an array
    // use headers.reduce to create an object
    // object properties derived from headers:values
    // the object passed as an element of the array
    const arr = rows.map(function (row) {
      const values = row.split(delimiter).map(Number);
      const el = headers.reduce(function (object, header, index) {
        object[header] = values[index];
        return object;
      }, {});
      return el;
    });

    // return the array
    return arr;
  }

  myForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const input = csvFile.files[0];
    const reader = new FileReader();

    reader.onload = function (e) {
      const text = e.target.result;
      const data = csvToArray(text);
      console.log(data);
      mapLoad_1(data);
    };

    reader.readAsText(input);
  });
  }

Body:
When you get the title, you can remove all spaces through the trim() function

const headers = str.slice(0,str.indexOf("\n")).trim().split(delimiter);

const rows = str.slice(str.indexOf("\n") + 1).trim().split("\n");


问:
how to connect to mongodb from express?
Tried to connect To mongodb, it says connection not found.  can someone point out what error I have made in code, is there any problem in db connect URI

```<code>const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

const db =
  "mongodb+srv://<sumit>:<sumit>@bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";

console.log(db);
mongoose
  .connect(db)
  .then(() => {
    console.log("connection successful");
  })
  .catch((err) => console.log(err));

app.use(express.json());

//importing routes

const authRoute = require("./routes/auth");

//route middle wares
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("gg server is running"));
</code>```

答:
This is a snippet from my own application it works there

```<code>mongoose.connect(dbUrl).then((dbo)=>{
  console.log("DB connected")
},(err)=>{
  console.log("error")
});
</code>```

I have connected like this your then is missing a variable tell me if this dosnt work

Title: how to connect to mongodb from express?

Body:
Tried to connect To mongodb, it says connection not found.  can someone point out what error I have made in code, is there any problem in db connect URI

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

const db =
  "mongodb+srv://<sumit>:<sumit>@bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";

console.log(db);
mongoose
  .connect(db)
  .then(() => {
    console.log("connection successful");
  })
  .catch((err) => console.log(err));

app.use(express.json());

//importing routes

const authRoute = require("./routes/auth");

//route middle wares
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("gg server is running"));

Body:
This is a snippet from my own application it works there

mongoose.connect(dbUrl).then((dbo)=>{
  console.log("DB connected")
},(err)=>{
  console.log("error")
});

I have connected like this your then is missing a variable tell me if this dosnt work


问:
Open all images in a folder and apply and merge it with a given folder?
I am adjusting a script.

I have 4427 images in a specified folder, named

(1).png

(2).png

(3).png

etc.

Along with those, I have another 14 images, named:

1.png

2.png

3.png

etc.

Basically the script should:

Take a specific image I tell it to open of the 4427

Then, open one of the 14 images at random

Merge the two and save it to a specified directory.

Code

import os
import random
from PIL import Image

path = r"C:\Users\17379\Desktop\images\Low effort glasses"
random_filename = random.choice([
    x for x in os.listdir(path)
    if os.path.isfile(os.path.join(path, x))
])
print(random_filename)

x = Image.open(r"(1).png").convert("RGBA")
y = Image.open(random_filename)
z = Image.alpha_composite(x, y)

z.save(r"C:\Users\17379\Desktop\images\Resized punks\Resized punks\punk1.png")

```

How to do this to all 4427 images and then save each file to the specified directory?

答:
The pseudo-code for your task is:

```<code>for file_name in source_image_list:
    # 1. Take a specific image I tell it to open of the 4427
    source_image = open_source(file_name)
    # 2. Then, open one of the 14 images at random
    random_image = open_random_of(random_image_list)
    # 3. Merge the two and save it to a specified directory.
    target_image = merge(source_image, random_image)
    save(target_image, file_name, directory)
</code>```

Translate this to Python:

```<code>import os
import glob
import random
from PIL import Image

def open_random(random_image_list):
    random_filename = random.choice(in random_image_list)
    print(f"Random: {random_filename}")
    return Image.open(random_filename)

def open_source(file_name):
    return Image.open(file_name).convert("RGBA")

def merge(source, random):
    return Image.alpha_composite(source, random)

def save(image, original_name, directory):
    target = os.path.join(directory, os.path.basename(original_name))
    print(f"Saving: {target}")
    image.save(target)

if __name__ == '__main__':
    source_path = r"C:\Users\17379\Desktop\images"
    random_path = r"C:\Users\17379\Desktop\images\Low effort glasses"
    directory =  r"C:\Users\17379\Desktop\images\Resized punks\Resized punks"

    random_image_list = os.listdir(random_path)  # can also use glob here to filter for (specific) images only
    source_image_list = glob.glob(f"{source_path}/\([0-9]+\).png")

    for file_name in source_image_list:
        print(f"Source: {file_name}")
        # 1. Take a specific image I tell it to open of the 4427
        source_image = open_source(file_name)
        # 2. Then, open one of the 14 images at random
        random_image = open_random_of(random_image_list)
        # 3. Merge the two and save it to a specified directory.
        target_image = merge(source_image, random_image)
        save(target_image, file_name, directory)
</code>```

Note: I had to replace os.listdir(source_path) for glob.glob because it accepts a regular-expression to filter for specific files only. See also
Python3 create list of image in a folder

Body:
I am adjusting a script.

I have 4427 images in a specified folder, named

(1).png

(2).png

(3).png

etc.

Along with those, I have another 14 images, named:

1.png

2.png

3.png

etc.

Basically the script should:

Take a specific image I tell it to open of the 4427

Then, open one of the 14 images at random

Merge the two and save it to a specified directory.

Code

import os
import random
from PIL import Image

path = r"C:\Users\17379\Desktop\images\Low effort glasses"
random_filename = random.choice([
    x for x in os.listdir(path)
    if os.path.isfile(os.path.join(path, x))
])
print(random_filename)

x = Image.open(r"(1).png").convert("RGBA")
y = Image.open(random_filename)
z = Image.alpha_composite(x, y)

z.save(r"C:\Users\17379\Desktop\images\Resized punks\Resized punks\punk1.png")

How to do this to all 4427 images and then save each file to the specified directory?

Body:
The pseudo-code for your task is:

for file_name in source_image_list:
    # 1. Take a specific image I tell it to open of the 4427
    source_image = open_source(file_name)
    # 2. Then, open one of the 14 images at random
    random_image = open_random_of(random_image_list)
    # 3. Merge the two and save it to a specified directory.
    target_image = merge(source_image, random_image)
    save(target_image, file_name, directory)

Translate this to Python:

import os
import glob
import random
from PIL import Image

def open_random(random_image_list):
    random_filename = random.choice(in random_image_list)
    print(f"Random: {random_filename}")
    return Image.open(random_filename)

def open_source(file_name):
    return Image.open(file_name).convert("RGBA")

def merge(source, random):
    return Image.alpha_composite(source, random)

def save(image, original_name, directory):
    target = os.path.join(directory, os.path.basename(original_name))
    print(f"Saving: {target}")
    image.save(target)

if __name__ == '__main__':
    source_path = r"C:\Users\17379\Desktop\images"
    random_path = r"C:\Users\17379\Desktop\images\Low effort glasses"
    directory =  r"C:\Users\17379\Desktop\images\Resized punks\Resized punks"

    random_image_list = os.listdir(random_path)  # can also use glob here to filter for (specific) images only
    source_image_list = glob.glob(f"{source_path}/\([0-9]+\).png")

    for file_name in source_image_list:
        print(f"Source: {file_name}")
        # 1. Take a specific image I tell it to open of the 4427
        source_image = open_source(file_name)
        # 2. Then, open one of the 14 images at random
        random_image = open_random_of(random_image_list)
        # 3. Merge the two and save it to a specified directory.
        target_image = merge(source_image, random_image)
        save(target_image, file_name, directory)

Note: I had to replace os.listdir(source_path) for glob.glob because it accepts a regular-expression to filter for specific files only. See also
Python3 create list of image in a folder


问:
Python: function that exclude negative values from list and give back new list
I have list of numbers.
I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me.
Could you please suggest something.

This is the code which is working but it's loop:

```<code>new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

</code>```

This function does not work. It gives me None.

```<code>
data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)
</code>```

答:
Your function prepocessing returns None because you call the return too early.

append() is a method of the list object that modifies the object and returns nothing. So when you return the result of this method, it returns None.

You could simply do this:

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            new_list.append(i)
    return new_list
```

Body:
I have list of numbers.
I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me.
Could you please suggest something.

This is the code which is working but it's loop:

new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

This function does not work. It gives me None.

data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)


问:
Forge IFC model weird "shadow lines"
When an IFC model is uploaded and translated by Autodesk Forge, some weird "shadow lines" are generated and appear in the Forge viewer. These lines mostly are IFC wall elements and correspond to real walls in the model, but they are drawn under the actual model. Here is an example of such lines:

Now, if I try to add another model, which should align with the first one and I set both Global Offset Zs to 0, the added model fits into the shadow lines at the bottom and not the actual model. Thus, it seems that the shadow lines are the considered to be a part of the model. Here is a visualisation of the problem:

When I load the model with other IFC viewers, these shadow lines don't appear:

Thus, I guess these lines are generated during the Forge translation process. Where are these lines coming from and how can I get rid of these? And even more important, how can I align the models correctly?

Thanks for any kind of help!

EDIT:
When I use legacy conversion, the alignment works! Here is an image:

The problem is, that I need to have spaces and opening elements, thus I need to use the modern conversion.

答:
The lines shown are actual geometries. Some viewers draw them, others don't. Unfortunately, our customer generates the data and isn't able to remove these line geometries.

The main problem of aligning the models was fixed by manipulating the IFC file. We figured out, that one model has a geographic reference point defined in the IfcSite and the other doesn't. When we replaced the longitude, latitude and elevation attribues by '$', the alignment worked again. According to iFC definition, the geographic reference point is only given for informational purposes, but still, it affects the global offset, at least when using 'modern' conversion.

Title: Forge IFC model weird "shadow lines"


问:
Why is IIS app pool stopping after long request?
I have created an API that makes calls to other APIs and returns a very long string (approximately 200mb).

Every time I make a request to it, it takes a long time to run then only responds with 4mb (exactly) of response and shut down the application pool.

I tried these solutions :

Increase executionTimeout and shutdownTimeout to 01:00:00

Setting bufferingOn to false and bufferingLimit to 1073741824

Disable Rapid-Fail Protection

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\Program.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
    <system.web>
        <httpRuntime executionTimeout="3600" shutdownTimeout="3600" />
    </system.web>
</configuration>
</code>```
```<code><location path="Internal Interfaces">
    <system.webServer>
        <asp bufferingOn="false">
            <limits bufferingLimit="1073741824" />
        </asp>
    </system.webServer>
</location>
</code>```

Thanks,

Khalenn

答:
You can try this setting to increase the request Limits in iis.

IIS Setting: Request Limits:

```<code><configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
    </security>
  <system.webServer>
</configuration>
</code>```

With the above maxAllowedContentLength, users can upload files that are 2 GB in size.

Edit the request filtering feature settings and the request limits using IIS manager:

Open IIS Manager.

Select the website that you want to configure.

Select Requests Filtering and open it by double-clicking the icon. The Request Filtering pane displays.

From the Actions pane on the right hand side of the screen click Edit Feature Settings... link. The Edit Request Filtering Settings window displays.

In the Request Limits section, enter the appropriate Maximum allowed content length (Bytes) and then click the OK button.

Restart IIS.

Body:
I have created an API that makes calls to other APIs and returns a very long string (approximately 200mb).

Every time I make a request to it, it takes a long time to run then only responds with 4mb (exactly) of response and shut down the application pool.

I tried these solutions :

Increase executionTimeout and shutdownTimeout to 01:00:00

Setting bufferingOn to false and bufferingLimit to 1073741824

Disable Rapid-Fail Protection

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\Program.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
    <system.web>
        <httpRuntime executionTimeout="3600" shutdownTimeout="3600" />
    </system.web>
</configuration>

<location path="Internal Interfaces">
    <system.webServer>
        <asp bufferingOn="false">
            <limits bufferingLimit="1073741824" />
        </asp>
    </system.webServer>
</location>

Thanks,

Khalenn

Body:
You can try this setting to increase the request Limits in iis.

IIS Setting: Request Limits:

<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
    </security>
  <system.webServer>
</configuration>

With the above maxAllowedContentLength, users can upload files that are 2 GB in size.

Edit the request filtering feature settings and the request limits using IIS manager:

Open IIS Manager.

Select the website that you want to configure.

Select Requests Filtering and open it by double-clicking the icon. The Request Filtering pane displays.

From the Actions pane on the right hand side of the screen click Edit Feature Settings... link. The Edit Request Filtering Settings window displays.

In the Request Limits section, enter the appropriate Maximum allowed content length (Bytes) and then click the OK button.

Restart IIS.


问:
save array to database - reactjs
I have a form with 3 data, name, data1, data2 but data1 and data2 is a dynamic array where I can add various data with the + button to this array, but I have not been able to save them in the database which are php and MySQL , I have tried to make my code work but I have not succeeded, and what I need is for me to save the array in the database, I have tried to do it but my code does not work. I send my source code:

https://codesandbox.io/s/peaceful-http-bg949?file=/src/App.js

import React, {useState} from 'react';
import axios from 'axios';

import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from "@material-ui/core";
import AddCircleOutlineIcon from "@material-ui/icons/AddCircleOutline";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import DeleteIcon from "@material-ui/icons/Delete";

const StyledTableRow = withStyles((theme) => ({
  root: {
    "&:nth-of-type(odd)": {
      backgroundColor: theme.palette.action.hover
    }
  }
}))(TableRow);

const useStyles = makeStyles((theme) => ({
  paper: {
    display: "flex",
    flexDirection: "column",
    padding: "30px 40px",
    marginTop: "50px",
    marginLeft: "20px",
    marginRight: "20px"
  },

  heading: {
    paddingLeft: "10px"
  },

  label: {
    lineHeight: "2",
    fontSize: "14px"
  },
  input: {
    height: "10px"
  },
  table: {
    minWidth: 700
  }
}));

const options = [
  { value: 1, label: 1 },
  { value: 2, label: 2 },
  { value: 3, label: 3 }
];

function Pruebas() {
    const baseUrlAd = 'https://www.inventarios.gemcont.com/apiGemcont/compras/ingresos/';
    const [data, setData]=useState([]);
    const [frameworkSeleccionado, setFrameworkSeleccionado]=useState({
        id_ingreso:'',
        nombre:'',
        dato1:'',
        dato2:''
      });

    const handleChange=e=>{
        const {name, value}=e.target;
        setFrameworkSeleccionado((prevState)=>({
          ...prevState,
          [name]: value
        }))
       console.log(frameworkSeleccionado);
      }

      const peticionPost = async() =>{
        var f = new FormData();
        f.append("nombre", frameworkSeleccionado.nombre);
        f.append("dato1", frameworkSeleccionado.dato1);
        f.append("dato2", frameworkSeleccionado.dato2);
        f.append("METHOD", "POST_prueba");
        await axios.post(baseUrlAd,f)
        .then(response=>{
         setData(data.concat(response.data));
        }).catch(error=>{
          console.log(error);
        })

      }

  const classes = useStyles();

  const [roomInputs, setRoomInputs] = useState([
    { dato1: "", dato2: "" }
  ]);

  const handleRoomChange = (option, index, name) => {
    const value = option.value;
    console.log(value);
    const list = [...roomInputs];
    list[index][name] = value;
    setRoomInputs(list);
  };

  const handleRemoveClickRoom = (index) => {
    const list = [...roomInputs];
    list.splice(index, 1);
    setRoomInputs(list);
  };

  const handleAddClickRoom = () => {
    setRoomInputs([...roomInputs, { dato1: "", dato2: "" }]);
  };

    return (

Datos

                  <input type="text" name="nombre"
                  placeholder='nombre' className="form-control"/>

          <Grid item sm={12}>
            <TableContainer component={Paper} variant="outlined">

                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    <TableCell align="left">dato1</TableCell>
                    <TableCell align="left">dato2</TableCell>
                  </TableRow>

                </TableHead>
                <TableBody>
                  {roomInputs.map((x, i) => (

                  ))}
                </TableBody>

            </TableContainer>
          </Grid>

                  <button className="btn btn-primary" onClick={()=>peticionPost()}> Registrar</button>

    )
}

export default Pruebas```
</div>
</div>
</p>
<p>PHP</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?php

include '../../bd/global.php';

header('Access-Control-Allow-Origin: *');

if($_POST['METHOD']=='POST_prueba'){
    unset($_POST['METHOD']);
    $nombre=$_POST['nombre'];
    $query="insert into ingresos(nombre) values ('$nombre')";
    $queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos";
    $resultado=metodoPost($query, $queryAutoIncrement);
    echo json_encode($resultado);
        $num_elementos=0;
        $sw=true;
        while ($num_elementos < count($idarticulo))
        {
            $sql_detalle = "INSERT INTO detalle_ingresos(id_ingreso, dato1, dato2) VALUES ('$idingresonew', '$idarticulo[$num_elementos]','$dato1[$num_elementos]','$dato2[$num_elementos]')";
            ejecutarConsulta($sql_detalle) or $sw = false;
            $num_elementos=$num_elementos + 1;
        }

    return $sw;

    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");

?></code>```

Data base

答:
Sorry i am not answering you question but i've noticed a vulnerable code in your SQL query which can allow an attacker to inject in your future website, therefore i advice you to make a look here ;
How can I prevent SQL injection in PHP?</p>

Title: save array to database - reactjs

Body:
I have a form with 3 data, name, data1, data2 but data1 and data2 is a dynamic array where I can add various data with the + button to this array, but I have not been able to save them in the database which are php and MySQL , I have tried to make my code work but I have not succeeded, and what I need is for me to save the array in the database, I have tried to do it but my code does not work. I send my source code:

https://codesandbox.io/s/peaceful-http-bg949?file=/src/App.js

import React, {useState} from 'react';
import axios from 'axios';

import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from "@material-ui/core";
import AddCircleOutlineIcon from "@material-ui/icons/AddCircleOutline";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import DeleteIcon from "@material-ui/icons/Delete";

const StyledTableRow = withStyles((theme) => ({
  root: {
    "&:nth-of-type(odd)": {
      backgroundColor: theme.palette.action.hover
    }
  }
}))(TableRow);

const useStyles = makeStyles((theme) => ({
  paper: {
    display: "flex",
    flexDirection: "column",
    padding: "30px 40px",
    marginTop: "50px",
    marginLeft: "20px",
    marginRight: "20px"
  },

  heading: {
    paddingLeft: "10px"
  },

  label: {
    lineHeight: "2",
    fontSize: "14px"
  },
  input: {
    height: "10px"
  },
  table: {
    minWidth: 700
  }
}));

const options = [
  { value: 1, label: 1 },
  { value: 2, label: 2 },
  { value: 3, label: 3 }
];

function Pruebas() {
    const baseUrlAd = 'https://www.inventarios.gemcont.com/apiGemcont/compras/ingresos/';
    const [data, setData]=useState([]);
    const [frameworkSeleccionado, setFrameworkSeleccionado]=useState({
        id_ingreso:'',
        nombre:'',
        dato1:'',
        dato2:''
      });

    const handleChange=e=>{
        const {name, value}=e.target;
        setFrameworkSeleccionado((prevState)=>({
          ...prevState,
          [name]: value
        }))
       console.log(frameworkSeleccionado);
      }

      const peticionPost = async() =>{
        var f = new FormData();
        f.append("nombre", frameworkSeleccionado.nombre);
        f.append("dato1", frameworkSeleccionado.dato1);
        f.append("dato2", frameworkSeleccionado.dato2);
        f.append("METHOD", "POST_prueba");
        await axios.post(baseUrlAd,f)
        .then(response=>{
         setData(data.concat(response.data));
        }).catch(error=>{
          console.log(error);
        })

      }

  const classes = useStyles();

  const [roomInputs, setRoomInputs] = useState([
    { dato1: "", dato2: "" }
  ]);

  const handleRoomChange = (option, index, name) => {
    const value = option.value;
    console.log(value);
    const list = [...roomInputs];
    list[index][name] = value;
    setRoomInputs(list);
  };

  const handleRemoveClickRoom = (index) => {
    const list = [...roomInputs];
    list.splice(index, 1);
    setRoomInputs(list);
  };

  const handleAddClickRoom = () => {
    setRoomInputs([...roomInputs, { dato1: "", dato2: "" }]);
  };

    return (

Datos

                  <input type="text" name="nombre"
                  placeholder='nombre' className="form-control"/>

          <Grid item sm={12}>
            <TableContainer component={Paper} variant="outlined">

                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    <TableCell align="left">dato1</TableCell>
                    <TableCell align="left">dato2</TableCell>
                  </TableRow>

                </TableHead>
                <TableBody>
                  {roomInputs.map((x, i) => (

                  ))}
                </TableBody>

            </TableContainer>
          </Grid>

                  <button className="btn btn-primary" onClick={()=>peticionPost()}> Registrar</button>

    )
}

export default Pruebas

PHP

<?php

include '../../bd/global.php';

header('Access-Control-Allow-Origin: *');

if($_POST['METHOD']=='POST_prueba'){
    unset($_POST['METHOD']);
    $nombre=$_POST['nombre'];
    $query="insert into ingresos(nombre) values ('$nombre')";
    $queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos";
    $resultado=metodoPost($query, $queryAutoIncrement);
    echo json_encode($resultado);
        $num_elementos=0;
        $sw=true;
        while ($num_elementos < count($idarticulo))
        {
            $sql_detalle = "INSERT INTO detalle_ingresos(id_ingreso, dato1, dato2) VALUES ('$idingresonew', '$idarticulo[$num_elementos]','$dato1[$num_elementos]','$dato2[$num_elementos]')";
            ejecutarConsulta($sql_detalle) or $sw = false;
            $num_elementos=$num_elementos + 1;
        }

    return $sw;

    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");

?>

Data base


问:
indexPath is nil after didSelectRow in tableView
I want to pass the selected row to the next VC.
But it is always nil, no matter which row was clicked.
I'm happy for any hints.</p>
```<code> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.performSegue(withIdentifier: "goToDetails", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goTo Details" {
            if let indexPath = collectionTableView.indexPathForSelectedRow{
            let destinationVC = segue.destination as! DetailsViewController
                destinationVC.IdentifierAlbum = dataArray[indexPath.row].album
                destinationVC.IdentifierArtist = dataArray[indexPath.row].artist
                destinationVC.IdentifierRow = indexPath.row
                print (indexPath.row)
            }

</code>```

答:
Instead of self you could pass the index path

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "goToDetails", sender: indexPath)
}
</code>```

and get it in prepare(for, by the way the identifier doesn't match the identifier of performSegue, check it also in the storyboard

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails",
       let indexPath = sender as? IndexPath { ...
</code>```

But if the segue is connected from table view cell to the destination controller rather than from the view controller you can delete didSelectRow and the sender parameter contains the instance of the selected cell

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails",
       let cell = sender as? UITableViewCell,
       let indexPath = collectionTableView.indexPath(for: cell) { ...
</code>```

Body:
I want to pass the selected row to the next VC.
But it is always nil, no matter which row was clicked.
I'm happy for any hints.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.performSegue(withIdentifier: "goToDetails", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goTo Details" {
            if let indexPath = collectionTableView.indexPathForSelectedRow{
            let destinationVC = segue.destination as! DetailsViewController
                destinationVC.IdentifierAlbum = dataArray[indexPath.row].album
                destinationVC.IdentifierArtist = dataArray[indexPath.row].artist
                destinationVC.IdentifierRow = indexPath.row
                print (indexPath.row)
            }

Body:
Instead of self you could pass the index path

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "goToDetails", sender: indexPath)
}

and get it in prepare(for, by the way the identifier doesn't match the identifier of performSegue, check it also in the storyboard

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails",
       let indexPath = sender as? IndexPath { ...

But if the segue is connected from table view cell to the destination controller rather than from the view controller you can delete didSelectRow and the sender parameter contains the instance of the selected cell

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToDetails",
       let cell = sender as? UITableViewCell,
       let indexPath = collectionTableView.indexPath(for: cell) { ...


问:
Checking new row is inserted in table database and run some script
I want to send some notification to android app when new row is inserted in table database, but I'm having trouble to check if there is new row inserted or not.

Is there any function or query to check if new row inserted in table? or some logic to acquire that.

答:
It depends on the database you are using.
For example in MySQL you can query the table information_schema.tables to get the latest update time.
https://dev.mysql.com/doc/refman/8.0/en/information-schema-tables-table.html

For postgres

Check if track commit timestamp is on

```<code>show track_commit_timestamp;
</code>```

If it's off, set it to on in your postgresql.conf file and restart postgres.

Post that run the following to track the latest updates in your table

```<code>SELECT pg_xact_commit_timestamp(xmin), * FROM YOUR_TABLE_NAME;
</code>```

Body:
It depends on the database you are using.
For example in MySQL you can query the table information_schema.tables to get the latest update time.
https://dev.mysql.com/doc/refman/8.0/en/information-schema-tables-table.html

For postgres

Check if track commit timestamp is on

show track_commit_timestamp;

If it's off, set it to on in your postgresql.conf file and restart postgres.

Post that run the following to track the latest updates in your table

SELECT pg_xact_commit_timestamp(xmin), * FROM YOUR_TABLE_NAME;


问:
How to name IP addresses on micro webserver
I have an stm32H743 micro controller webserver (Cubeide LWIP) which displays a small webpage on my local LAN.
When I look at the router page, I see that all local IP's have a name associated with them.

Ethernet:   COM-MID1    80:c7:55:94:12:14   192.168.1.115

STM32       00:80:e1:01:00:23   192.168.1.75
My question is - how do I change the name 'STM32' in my webserver code?
As you may imagine, there are thousands of references in my source code and I cant find the corresponding one. Where is it likely to be?
Thanks
Chris

答:
Could it be that your router is presenting client host names from DHCP option 12?
With lwIP, you can specify the DHCP client host name by #defining the LWIP_NETIF_HOSTNAME option and then setting the hostname-field in the netif struct.</p>


问:
no such file to load - require wordnet fails - troubleshoot gem installation
my ruby environment cant see an installed gem, at least the require fails

It's about the gem wordnet http://deveiate.org/projects/Ruby-WordNet I start an example script ( as user of course )

```<code>./meronymTree.rb
./meronymTree.rb:8:in `require': no such file to load -- wordnet (LoadError)
    from ./meronymTree.rb:8
</code>```

In some example scripts it'S called "WordNet" and in some it's lowercase, the error is same.

here's the scripts first lines

```<code>#!/usr/bin/ruby -w

$LOAD_PATH.unshift "lib"
require 'wordnet'
</code>```

Check if gem is installed, as user root

```<code>gem list |grep word
wordnet (0.0.5)

root@auedv18:/var/lib/gems/1.8/gems/wordnet-0.0.5# ls
ChangeLog  convertdb.rb  examples  lib  LICENSE  rake  Rakefile  Rakefile.local  README  spec  utils.rb
</code>```

Other gems are fine.

I am on current ubuntu and got ruby1.8 and rubygems-1.8.6 on it, (if that makes a difference).

hm and i downloaded the  wordnet-0.0.5.gem file from above site and did

```<code>gem install wordnet-0.0.5.gem
</code>```

答:
Try this:</p>

```<code>require 'rubygems'
require 'wordnet'
</code>```

Body:
my ruby environment cant see an installed gem, at least the require fails

It's about the gem wordnet http://deveiate.org/projects/Ruby-WordNet I start an example script ( as user of course )

./meronymTree.rb
./meronymTree.rb:8:in `require': no such file to load -- wordnet (LoadError)
    from ./meronymTree.rb:8

In some example scripts it'S called "WordNet" and in some it's lowercase, the error is same.

here's the scripts first lines

#!/usr/bin/ruby -w

$LOAD_PATH.unshift "lib"
require 'wordnet'

Check if gem is installed, as user root

gem list |grep word
wordnet (0.0.5)

root@auedv18:/var/lib/gems/1.8/gems/wordnet-0.0.5# ls
ChangeLog  convertdb.rb  examples  lib  LICENSE  rake  Rakefile  Rakefile.local  README  spec  utils.rb

Other gems are fine.

I am on current ubuntu and got ruby1.8 and rubygems-1.8.6 on it, (if that makes a difference).

hm and i downloaded the  wordnet-0.0.5.gem file from above site and did

gem install wordnet-0.0.5.gem

Body:
Try this:

require 'rubygems'
require 'wordnet'


问:
Concurrent Map with fixed size
I need a map with the following requirements :

It should be highly concurrent. The put(), get() and remove() methods may be called by multiple threads simultaneously.

It should be of fixed size. If the size of the HashMap reaches to the max value (e.g. 10000), addition of a new entry to the map should not be allowed. It CAN'T be LRU cache where the oldest entry gets removed on reaching maximum size.

ConcurrentHashMap may satisfy #1. But, not sure how #2 can be implemented on top of ConcurrentHashMap without impacting concurrency (Adding a custom put() method which will add to the map only when the size is lesser than the max size, needs to be "synchronized". That will defeat the purpose of using concurrent HashMap).

Please let me know your thoughts.

答:
Try this:</p>
```<code>public static class ConcurrentFixedMap<K, V> extends LinkedHashMap<K, V> {
    private final int MAX_ENTRIES;
    private ConcurrentFixedMap(int size) {
        super(size);
        this.MAX_ENTRIES = size;
    }

    public static <K, V> Map<K, V> init(int size) {
        return Collections.synchronizedMap(new ConcurrentFixedMap<>(size));
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > MAX_ENTRIES;
    }
}
</code>```

Title: Concurrent Map with fixed size

Body:
Try this:

public static class ConcurrentFixedMap<K, V> extends LinkedHashMap<K, V> {
    private final int MAX_ENTRIES;
    private ConcurrentFixedMap(int size) {
        super(size);
        this.MAX_ENTRIES = size;
    }

    public static <K, V> Map<K, V> init(int size) {
        return Collections.synchronizedMap(new ConcurrentFixedMap<>(size));
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > MAX_ENTRIES;
    }
}


问:
Log into the output file AND stdout in behave
I can't see the traceback in my console during behave run when I am redirecting output to with cmd option -o

Example log with -o:

```<code>2021-05-24:14:42:52, INFO     | environment.py         :22   : Before all
2021-05-24:14:42:54, INFO     | launch_test.py         :144  : 1
2021-05-24:14:42:54, INFO     | launch_test.py         :147  : feature: autogen_Generate_Cloud.feature | name: Run all projects from specified folder -- @1.1 Projects | project: Test_Beamer_Car1 | number: 1 --> FAILED
</code>```

Example of logs without -o option enabled:

```<code>Exception TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType
2021-05-24:14:50:57, ERROR    | launch_test.py         :141  : Exception thrown during behave run
Traceback (most recent call last):
[REDACTED TRACEBACK]
TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType
2021-05-24:14:50:57, INFO     | launch_test.py         :144  : 1
2021-05-24:14:50:57, INFO     | launch_test.py         :147  : feature: autogen_Generate_Cloud.feature | name: Run all projects from specified folder -- @1.1 Projects | project: Test_Beamer_Car1 | number: 1 --> FAILED
</code>```

What I am trying to achieve? Having the latter log format but with output also redirected to file.

What I tried?:

Verbose flag

No capture stderr

Turning off formatter and output file in behave seems to do the job

I run behave from python script according to this SO post (with custom runner and context classes)

My current behave parameters:

```<code>[PATH to feature files],
"--no-summary",
"-k",
"--no-junit",
"-f=allure_behave.formatter:AllureFormatter",
"--no-capture",
"--no-capture-stderr",
f"-i={scenario.feature}",
f"--name={scenario.name}",
f"-o={output_file}"
</code>```

I need to use AllureFormatter since the program uses allure to generate reports but it seems to catch the console output and return it only to file, not stdout or stderr as well

答:
You can combine multiple format and outfile parameters

So normally to see output in STDOUT you would use this command

```<code>behave --format pretty
behave --format json
</code>```

And if you want to send output to a file you add a output parameter

```<code>behave --format pretty --outfile behave.output
</code>```

So if you just combine them, you get output to STDOUT and an output file

```<code>behave --format json --outfile behave.json --format pretty
</code>```

put your STDOUT --format parameter after the outfile one just to be safe.

Body:
I can't see the traceback in my console during behave run when I am redirecting output to with cmd option -o

Example log with -o:

2021-05-24:14:42:52, INFO     | environment.py         :22   : Before all
2021-05-24:14:42:54, INFO     | launch_test.py         :144  : 1
2021-05-24:14:42:54, INFO     | launch_test.py         :147  : feature: autogen_Generate_Cloud.feature | name: Run all projects from specified folder -- @1.1 Projects | project: Test_Beamer_Car1 | number: 1 --> FAILED

Example of logs without -o option enabled:

Exception TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType
2021-05-24:14:50:57, ERROR    | launch_test.py         :141  : Exception thrown during behave run
Traceback (most recent call last):
[REDACTED TRACEBACK]
TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType
2021-05-24:14:50:57, INFO     | launch_test.py         :144  : 1
2021-05-24:14:50:57, INFO     | launch_test.py         :147  : feature: autogen_Generate_Cloud.feature | name: Run all projects from specified folder -- @1.1 Projects | project: Test_Beamer_Car1 | number: 1 --> FAILED

What I am trying to achieve? Having the latter log format but with output also redirected to file.

What I tried?:

Verbose flag

No capture stderr

Turning off formatter and output file in behave seems to do the job

I run behave from python script according to this SO post (with custom runner and context classes)

My current behave parameters:

[PATH to feature files],
"--no-summary",
"-k",
"--no-junit",
"-f=allure_behave.formatter:AllureFormatter",
"--no-capture",
"--no-capture-stderr",
f"-i={scenario.feature}",
f"--name={scenario.name}",
f"-o={output_file}"

I need to use AllureFormatter since the program uses allure to generate reports but it seems to catch the console output and return it only to file, not stdout or stderr as well

Body:
You can combine multiple format and outfile parameters

So normally to see output in STDOUT you would use this command

behave --format pretty
behave --format json

And if you want to send output to a file you add a output parameter

behave --format pretty --outfile behave.output

So if you just combine them, you get output to STDOUT and an output file

behave --format json --outfile behave.json --format pretty

put your STDOUT --format parameter after the outfile one just to be safe.


问:
How can I flip a curved line between two points in Python, and convert convex curve to concave?
I have two points say p1 = (1,2) and p2 = (5,4).

I want to plot straight line and curved line between these two points in Python. To draw the curved line, I have created a function called draw_curve which looks as follows:

```<code>import matplotlib.pyplot as plt
import numpy as np

#Points
p1 = [1, 2]
p2 = [5, 4]

#Function to draw curved line
def draw_curve(p1, p2):

    a = (p2[1] - p1[1])/ (np.cosh(p2[0]) - np.cosh(p1[0]))
    b = p1[1] - a * np.cosh(p1[0])
    x = np.linspace(p1[0], p2[0], 100)
    y = a * np.cosh(x) + b

    return x, y
</code>```

And I plot the straight line and curved line between the two points using the following code:

```<code>#Markers
plt.plot(p1[0], p1[1], marker = "o", markersize = 10, color = "black", label = "P1")
plt.plot(p2[0], p2[1], marker = "o", markersize = 10, color = "red", label = "P1")

#Straight line
plt.plot((p1[0], p2[0]),
         (p1[1], p2[1]),
         linewidth = 5,
         label = "Straight line")

#Curved line
x, y = draw_curve(p1, p2)

plt.plot(x, y, linewidth = 5, label = "Curved line", color = "orange")

plt.legend()
</code>```

The resulting plot is as shown:

The orange-colored curve I get now is convex shaped. However, I'd like to get a concave curve between the two points as well. It should look something as shown by the red-colored curve below. In a way, I'd like to mirror the orange curve using the blue line as the mirror.

What would be the appropriate way to do it? Can the function be adjusted accordingly? Or is there a way to flip the curve using the blue line as mirror? Thank you!

答:
This seems like simple math ;)

Get the difference between the blue an orange curve on y, reverse it, and add to the blue curve

```<code>blue_y = np.linspace(p1[1], p2[1], 100)

plt.plot(x, blue_y+(blue_y-y)[::-1], linewidth = 5, label = "mirror", color = "red")
</code>```

graphical hint to why the array need to be reversed

Body:
I have two points say p1 = (1,2) and p2 = (5,4).

I want to plot straight line and curved line between these two points in Python. To draw the curved line, I have created a function called draw_curve which looks as follows:

import matplotlib.pyplot as plt
import numpy as np

#Points
p1 = [1, 2]
p2 = [5, 4]

#Function to draw curved line
def draw_curve(p1, p2):

    a = (p2[1] - p1[1])/ (np.cosh(p2[0]) - np.cosh(p1[0]))
    b = p1[1] - a * np.cosh(p1[0])
    x = np.linspace(p1[0], p2[0], 100)
    y = a * np.cosh(x) + b

    return x, y

And I plot the straight line and curved line between the two points using the following code:

#Markers
plt.plot(p1[0], p1[1], marker = "o", markersize = 10, color = "black", label = "P1")
plt.plot(p2[0], p2[1], marker = "o", markersize = 10, color = "red", label = "P1")

#Straight line
plt.plot((p1[0], p2[0]),
         (p1[1], p2[1]),
         linewidth = 5,
         label = "Straight line")

#Curved line
x, y = draw_curve(p1, p2)

plt.plot(x, y, linewidth = 5, label = "Curved line", color = "orange")

plt.legend()

The resulting plot is as shown:

The orange-colored curve I get now is convex shaped. However, I'd like to get a concave curve between the two points as well. It should look something as shown by the red-colored curve below. In a way, I'd like to mirror the orange curve using the blue line as the mirror.

What would be the appropriate way to do it? Can the function be adjusted accordingly? Or is there a way to flip the curve using the blue line as mirror? Thank you!

Body:
This seems like simple math ;)

Get the difference between the blue an orange curve on y, reverse it, and add to the blue curve

blue_y = np.linspace(p1[1], p2[1], 100)

plt.plot(x, blue_y+(blue_y-y)[::-1], linewidth = 5, label = "mirror", color = "red")

graphical hint to why the array need to be reversed


问:
Create new column using data from If Else Loop in R
I have data frame that consist of names and scores of certain individual

```<code>       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70
</code>```

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

```<code>       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good
</code>```

I'm using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

```<code>df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}
</code>```

答:
The if statement in R is not vectorized, and you would instead want to use ifelse.  In this case, the case_when() function from the dplyr library is a good fit for your requirement:

df$verdict <- case_when(
    df$score >= 85 ~ "Passed, Cum Laude",
    df$score >= 80 ~ "Passed, Excellent",
    df$score >= 70 ~ "Passed, Good",
    df$score >= 60 ~ "Passed",
    TRUE ~ "Not Passed"
)
```

Body:
I have data frame that consist of names and scores of certain individual

       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good

I'm using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}


问:
How to convert a nested Python dict to object?
I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

```<code>>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
</code>```

Should be accessible in this way:

```<code>>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
</code>```

I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?

答:
Looking for a simple wrapper class for dict enabling attribute-style key access/assignment (dot notation) I was not satisfied with the existing options for the reasons below.

dataclasses, pydantic, etc. are great but require a static definition of the content. Also, they cannot replace dict in code which relied on dict since they don't share the same methods and __getitem__() syntax is not supported.

Hence, I developed MetaDict. It behaves exactly like dict but enables dot notation and IDE autocompletion (if the object is loaded in the RAM) without the shortcomings and potential namespace conflicts of other solutions. All features and usage examples can be found on GitHub (see link above).

Full disclosure: I am the author of MetaDict.

Shortcomings/limitations I encountered when trying out other solutions:

Addict

No key autocompletion in IDE

Nested key assignment cannot be turned off

Newly assigned dict objects are not converted to support attribute-style key access

Shadows inbuilt type Dict

Prodict

No key autocompletion in IDE without defining a static schema (similar to dataclass)

No recursive conversion of dict objects when embedded in list or other inbuilt iterables

AttrDict

No key autocompletion in IDE

Converts list objects to tuple behind the scenes

Munch

Inbuilt methods like items(), update(), etc. can be overwritten with obj.items = [1, 2, 3]

No recursive conversion of dict objects when embedded in list or other inbuilt iterables

EasyDict

Only strings are valid keys, but dict accepts all hashable objects as keys

Inbuilt methods like items(), update(), etc. can be overwritten with obj.items = [1, 2, 3]

Inbuilt methods don't behave as expected: obj.pop('unknown_key', None) raises an AttributeError

Note: I wrote a similar answer in this stackoverflow, which is related.

Body:
I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

Should be accessible in this way:

>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar

I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?


答:
When having multiple ifelse statements, consider using dplyr::case_when() instead:

Code:

```<code>library(dplyr)
df %>%
  mutate(verdict = case_when(
    score >= 85 ~ 'Passed, Cum Laude',
    score < 85 & score >= 80 ~ 'Passed, Excellent',
    score < 80 & score >= 70 ~ 'Passed, Good',
    score < 70 & score >= 60 ~ 'Passed',
    TRUE ~ 'Not Passed'
  ))
</code>```

Output:

```<code>       name score           verdict
     <char> <int>            <char>
 1:     Ted    90 Passed, Cum Laude
 2: Rebecca    88 Passed, Cum Laude
 3:     Roy    78      Passed, Good
 4:  Leslie    85 Passed, Cum Laude
 5:  Nathan    75      Passed, Good
 6:   Jamie    70      Passed, Good
 7:     Sam    78      Passed, Good
 8:   Isaac    70      Passed, Good
 9:  Keeley    85 Passed, Cum Laude
10:   Beard    90 Passed, Cum Laude
11:   Colin    70      Passed, Good
12:    Will    70      Passed, Good
13:     Jan    82 Passed, Excellent
14: Richard    70      Passed, Good
</code>```

Title: Create new column using data from If Else Loop in R

Body:
When having multiple ifelse statements, consider using dplyr::case_when() instead:

Code:

library(dplyr)
df %>%
  mutate(verdict = case_when(
    score >= 85 ~ 'Passed, Cum Laude',
    score < 85 & score >= 80 ~ 'Passed, Excellent',
    score < 80 & score >= 70 ~ 'Passed, Good',
    score < 70 & score >= 60 ~ 'Passed',
    TRUE ~ 'Not Passed'
  ))

Output:

       name score           verdict
     <char> <int>            <char>
 1:     Ted    90 Passed, Cum Laude
 2: Rebecca    88 Passed, Cum Laude
 3:     Roy    78      Passed, Good
 4:  Leslie    85 Passed, Cum Laude
 5:  Nathan    75      Passed, Good
 6:   Jamie    70      Passed, Good
 7:     Sam    78      Passed, Good
 8:   Isaac    70      Passed, Good
 9:  Keeley    85 Passed, Cum Laude
10:   Beard    90 Passed, Cum Laude
11:   Colin    70      Passed, Good
12:    Will    70      Passed, Good
13:     Jan    82 Passed, Excellent
14: Richard    70      Passed, Good


问:
How to get rid of xmlns: - Attributes in XSL transformation
I have an xsl transformation to generate ASP.NET User controls (ascx).

My XSL is defined this way:

```<code><xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:asp="System.Web.UI.WebControls"
    exclude-result-prefixes="asp msxsl"
>
<xsl:output method="xml" indent="no" omit-xml-declaration="yes" />
</code>```

So from that exclude-result-prefixes I would assume, that everything with the asp prefix should not add the namespace information, but i.e. this template here:

```<code><xsl:template match="Label">
    <asp:Label runat="server" AssociatedControlID="{../@id}">
        <xsl:copy-of select="./text()"/>
    </asp:Label>
</xsl:template>
</code>```

fed with this xml:

```<code><Label>Label Text</Label>
</code>```

results in this output:

```<code><asp:Label runat="server" AssociatedControlID="SomeName" xmlns:asp="System.Web.UI.WebControls">Label Text</asp:Label>
</code>```

So what do I need to do to prevent the xmlns:asp=".." to show up in every single tag in my result?

答: It is impossible, at least in MSXML, that is because output XML won't be well-formed. You can only output it like text, e.g. using CDATA.</p>

Body:
I have an xsl transformation to generate ASP.NET User controls (ascx).

My XSL is defined this way:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:asp="System.Web.UI.WebControls"
    exclude-result-prefixes="asp msxsl"
>
<xsl:output method="xml" indent="no" omit-xml-declaration="yes" />

So from that exclude-result-prefixes I would assume, that everything with the asp prefix should not add the namespace information, but i.e. this template here:

<xsl:template match="Label">
    <asp:Label runat="server" AssociatedControlID="{../@id}">
        <xsl:copy-of select="./text()"/>
    </asp:Label>
</xsl:template>

fed with this xml:

Label Text

results in this output:

<asp:Label runat="server" AssociatedControlID="SomeName" xmlns:asp="System.Web.UI.WebControls">Label Text</asp:Label>

So what do I need to do to prevent the xmlns:asp=".." to show up in every single tag in my result?


问:
How to efficiently generate, in C, x random numbers in a given interval such the sum is constant?
To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program

1 :  nbValue-1 are randomly generated

2 : the last value is calculated (fullSum - Sum of nbValue)

3 : If the last value is not in the interval, this loop is restarted.

This is the code :

```<code>int main()
{

    int fullSum = 4096, nbValue = 16;
    int average = round(fullSum / nbValue);
    int delta = round(average*0.125);
    int tryCounter = 0;
    int lastStep;

    srand(time(0));

    do {
      int currentSum = 0;
      for (int i=0;i<nbValue-1;i++)
        currentSum+=rand()%(delta*2+1)-delta+average ;
      tryCounter ++;
      lastStep = fullSum - currentSum;
    }
    while ( (lastStep < average - delta) || (lastStep > average + delta) );

    printf("Total tries : %d\n",tryCounter);
}
</code>```

Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)

Thanks for answer.

答:
Following the Luis Colorado comment, I post this answer to my question :
int main()
{</p>
```<code>int fullSum = 4096, nbValue = 16;
int average = round(fullSum / nbValue);
int delta = round(average*0.125);
int rdValues[nbValue];

srand(time(0));

int currentSum = 0;
for (int i=0;i<nbValue;i++) {
    rdValues[i] = rand()%(delta*2+1)-delta+average ;
    currentSum+=rdValues[i];
}

for (int i=0;i<nbValue;i++)
    rdValues[i]=round(rdValues[i]/currentSum*fullSum) ;

// To slightly adjust the values because they are integers
currentSum = 0;
for (int i=0;i<nbValue;i++)
    currentSum+=rdValues[i];

int deltaSum=fullSum-currentSum;
int nextInc,rdIndex;
for (int i=0; i<abs(deltaSum);i++) {
    nextInc=0;
    while (nextInc=0) {
        rdIndex = rand()%(nbValue) ;
        if ( deltaSum<0 && rdValues[rdIndex] > (average-delta) ) {
            nextInc=1;
            rdValues[rdIndex]--; }
        if ( deltaSum>0 && rdValues[rdIndex] < (average+delta) ) {
            nextInc=1;
            rdValues[rdIndex]++; }
    }
}

}
</code>```

Body:
To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program

1 :  nbValue-1 are randomly generated

2 : the last value is calculated (fullSum - Sum of nbValue)

3 : If the last value is not in the interval, this loop is restarted.

This is the code :

int main()
{

    int fullSum = 4096, nbValue = 16;
    int average = round(fullSum / nbValue);
    int delta = round(average*0.125);
    int tryCounter = 0;
    int lastStep;

    srand(time(0));

    do {
      int currentSum = 0;
      for (int i=0;i<nbValue-1;i++)
        currentSum+=rand()%(delta*2+1)-delta+average ;
      tryCounter ++;
      lastStep = fullSum - currentSum;
    }
    while ( (lastStep < average - delta) || (lastStep > average + delta) );

    printf("Total tries : %d\n",tryCounter);
}

Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)

Thanks for answer.

Body:
Following the Luis Colorado comment, I post this answer to my question :
int main()
{

int fullSum = 4096, nbValue = 16;
int average = round(fullSum / nbValue);
int delta = round(average*0.125);
int rdValues[nbValue];

srand(time(0));

int currentSum = 0;
for (int i=0;i<nbValue;i++) {
    rdValues[i] = rand()%(delta*2+1)-delta+average ;
    currentSum+=rdValues[i];
}

for (int i=0;i<nbValue;i++)
    rdValues[i]=round(rdValues[i]/currentSum*fullSum) ;

// To slightly adjust the values because they are integers
currentSum = 0;
for (int i=0;i<nbValue;i++)
    currentSum+=rdValues[i];

int deltaSum=fullSum-currentSum;
int nextInc,rdIndex;
for (int i=0; i<abs(deltaSum);i++) {
    nextInc=0;
    while (nextInc=0) {
        rdIndex = rand()%(nbValue) ;
        if ( deltaSum<0 && rdValues[rdIndex] > (average-delta) ) {
            nextInc=1;
            rdValues[rdIndex]--; }
        if ( deltaSum>0 && rdValues[rdIndex] < (average+delta) ) {
            nextInc=1;
            rdValues[rdIndex]++; }
    }
}

}


问:
Ant Design & Webpack not loading css
I've got a React project using Antd and webpack as I wanted to use css modules, however unfortunately this is impacting Antd and I'm way out of my depth to understand how to resolve this.

In my webpack config, I have the following loader:

```<code>  {
    test: /\.css$/,
    use: [
      require.resolve('style-loader'),
      {
        loader: require.resolve('css-loader'),
        options: {
          importLoaders: 1,
          modules: true,
          localIdentName: "[name]__[local]___[hash:base64:5]"
        },
      },
      {
        loader: require.resolve('postcss-loader'),
        options: {
          // Necessary for external CSS imports to work
          // https://github.com/facebookincubator/create-react-app/issues/2677
          ident: 'postcss',
          plugins: () => [
            require('postcss-flexbugs-fixes'),
            autoprefixer({
              browsers: [
                '>1%',
                'last 4 versions',
                'Firefox ESR',
                'not ie < 9', // React doesn't support IE8 anyway
              ],
              flexbox: 'no-2009',
            }),
          ],
        },
      },
    ],
  },
</code>```

I can confirm that this is working for my own styled elements, but Antd component s are unstyled.

In my App.js, I am importing the antd.css file, however when bundled, it applies the css modules to the antd.css.  This obviously causes a problem as the Antd components haven't had their class names changed.

Can anyone guide me through how to resolve this please?

答: you can solve this by adding the @import '~antd/dist/antd.css'; to your css file. However I am also looking for a solution by making the changes in webpack.config</p>

Title: Ant Design & Webpack not loading css

Body:
I've got a React project using Antd and webpack as I wanted to use css modules, however unfortunately this is impacting Antd and I'm way out of my depth to understand how to resolve this.

In my webpack config, I have the following loader:

  {
    test: /\.css$/,
    use: [
      require.resolve('style-loader'),
      {
        loader: require.resolve('css-loader'),
        options: {
          importLoaders: 1,
          modules: true,
          localIdentName: "[name]__[local]___[hash:base64:5]"
        },
      },
      {
        loader: require.resolve('postcss-loader'),
        options: {
          // Necessary for external CSS imports to work
          // https://github.com/facebookincubator/create-react-app/issues/2677
          ident: 'postcss',
          plugins: () => [
            require('postcss-flexbugs-fixes'),
            autoprefixer({
              browsers: [
                '>1%',
                'last 4 versions',
                'Firefox ESR',
                'not ie < 9', // React doesn't support IE8 anyway
              ],
              flexbox: 'no-2009',
            }),
          ],
        },
      },
    ],
  },

I can confirm that this is working for my own styled elements, but Antd component s are unstyled.

In my App.js, I am importing the antd.css file, however when bundled, it applies the css modules to the antd.css.  This obviously causes a problem as the Antd components haven't had their class names changed.

Can anyone guide me through how to resolve this please?


问:
jquery selecting elements and removing classes with partial class names
I have the following piece of JQuery code which searches an html document for instances of elements with the class <xyz>-annotation-invisible and replaces it with <xyz>-annotation-visible. The catch is that if a particular element already has class <abc>-annotation-visible, then I want to remove all classes of the form *-annotation-visible and *-annotation-invisible and replace them with the class multiple-annotation-visible. How can I check if a particular element already has <abc>-annotation-visible?

```<code>const urlParams = new URLSearchParams(window.location.search);
const annotationTypes = urlParams.get('annotypes').split(',');
const multipleVisibleClass = "multiple-annotation-visible";

$(document).ready(function () {
  for (var i=0; i<annotationTypes.length; i++)
  {
    var annotype = annotationTypes[i];
    var annotationVisibleClass = `${annotype}-annotation-visible`;
    var annotationInvisibleClass = `${annotype}-annotation-invisible`;

    var elem = $(`.${annotationInvisibleClass}`);
    if (elem.hasClass(anyVisibleClass)) # not sure how to do this part
    {
      elem.removeClass(anyVisibleClass);
      elem.addClass(multipleVisibleClass);
    }
    else
    {
      elem.addClass(annotationVisibleClass);
    }
    elem.removeClass(annotationInvisibleClass);
  }
});
</code>```

答:
You could use is() and the attribute ends with selecor :

let elem = $("div");

console.log(elem.is("[class$='-annotation-visible']"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="<abc>-annotation-visible">test</div></code>```

Body:
I have the following piece of JQuery code which searches an html document for instances of elements with the class <xyz>-annotation-invisible and replaces it with <xyz>-annotation-visible. The catch is that if a particular element already has class <abc>-annotation-visible, then I want to remove all classes of the form *-annotation-visible and *-annotation-invisible and replace them with the class multiple-annotation-visible. How can I check if a particular element already has <abc>-annotation-visible?

const urlParams = new URLSearchParams(window.location.search);
const annotationTypes = urlParams.get('annotypes').split(',');
const multipleVisibleClass = "multiple-annotation-visible";

$(document).ready(function () {
  for (var i=0; i<annotationTypes.length; i++)
  {
    var annotype = annotationTypes[i];
    var annotationVisibleClass = `${annotype}-annotation-visible`;
    var annotationInvisibleClass = `${annotype}-annotation-invisible`;

    var elem = $(`.${annotationInvisibleClass}`);
    if (elem.hasClass(anyVisibleClass)) # not sure how to do this part
    {
      elem.removeClass(anyVisibleClass);
      elem.addClass(multipleVisibleClass);
    }
    else
    {
      elem.addClass(annotationVisibleClass);
    }
    elem.removeClass(annotationInvisibleClass);
  }
});

Body:
You could use is() and the attribute ends with selecor :

let elem = $("div");

console.log(elem.is("[class$='-annotation-visible']"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="<abc>-annotation-visible">test</div>


问:
How to combine hierarchical lists into one while respecting the hierarchy of each one of them using networkx and python?
For a medical application I want to combine several lists into one list. The items in each list represent actions to be taken for a specific disease.
For instance the list Malaria would look like that:

'Give Malaria medication'

'Give antibiotics'

'Tell patient to come back tomorrow'

'Give a warm lemon tea'

A second list for Bacterial sore throat would be this:

'Give antibiotics'

'Give paracetamol'

'Give a warm lemon tea'

'Warm the patient'

The actions in each list are hierarchical. That means that the more important tasks are mentioned first.

The lists themselves have a hierarchy as well, so Malaria is higher than Bacterial sore throat.

I need to combine those lists into a global one, that has the items sorted in a way that both hierarchies are preserved. This would be the case that a patient has both Malaria AND Bacterial sore throat and receives treatment according to the importance of each action.

For this case I would want this list:

'Give Malaria medication' (from Malaria list because it is higher than sore throat)

'Give antibiotics' (covers an action from both lists)

'Tell patient to come back tomorrow' (from Malaria list)

'Give Paracetamol' (more important than warm tea as seen in sore throat)

'Give a warm lemon tea' (covers an action from both lists)

'Warm the patient'

Currently this sorting is done by hand, but it becomes too complex with 50+ diseases.
I have looked into networkx trying to do a topological sort but I guess this is not the right approach.

It becomes more complex when sorting is not possible and the actions are in reverse order.
For instance in Diarrhoea there are

make the patient drink

give treatment

while in Severe Diarrhoea these are in reverse order

give treatment

make the patient drink

In this case I want the solution to double an item in the global list to

give treatment

make the patient drink

give treatment

Is there a way to solve at least one of those steps?

答:
In Python, you can use the + operator to append one list to the end of the other -

For the case where 2 lists are to be combined, you can add (+) them and use the index of each item in the combined list as a sorting key to dedupe -

malaria = ['give malaria medication', 'give antibiotics', 'tell patient to come back tomorrow', 'give warm lemon tea']
bacterial_sore_throat = ['give antibiotics', 'give warm lemon tea', 'warm patient']
combined_list = sorted(set(malaria + bacterial_sore_throat), key=lambda x: (malaria + bacterial_sore_throat).index(x))
print(*combined_list, sep='\n')
#give malaria medication
#give antibiotics
#tell patient to come back tomorrow
#give warm lemon tea
#warm patient
```
<p>Note that in this case you are passing the diseases as <code>malaria + bacterial_sore_throat</code> when creating the combined list as <code>malaria</code> ranks higher than <code>bacterial_sore_throat</code>.</p>
<p>You can extend this logic to an arbitrary number of diseases using the <code>itertools.chain</code> function to combine diseases</p>
<pre class="lang-py prettyprint-override"><code>from itertools import chain
combined_list_2 = sorted(set(chain(malaria, bacterial_sore_throat)), key=lambda x: list(chain(malaria, bacterial_sore_throat)).index(x))
</code>```

Body:
In Python, you can use the + operator to append one list to the end of the other -

For the case where 2 lists are to be combined, you can add (+) them and use the index of each item in the combined list as a sorting key to dedupe -

malaria = ['give malaria medication', 'give antibiotics', 'tell patient to come back tomorrow', 'give warm lemon tea']
bacterial_sore_throat = ['give antibiotics', 'give warm lemon tea', 'warm patient']
combined_list = sorted(set(malaria + bacterial_sore_throat), key=lambda x: (malaria + bacterial_sore_throat).index(x))
print(*combined_list, sep='\n')
#give malaria medication
#give antibiotics
#tell patient to come back tomorrow
#give warm lemon tea
#warm patient

Note that in this case you are passing the diseases as malaria + bacterial_sore_throat when creating the combined list as malaria ranks higher than bacterial_sore_throat.

You can extend this logic to an arbitrary number of diseases using the itertools.chain function to combine diseases

from itertools import chain
combined_list_2 = sorted(set(chain(malaria, bacterial_sore_throat)), key=lambda x: list(chain(malaria, bacterial_sore_throat)).index(x))