text:
Q: An instance of a null PK has been incorrectly provided for this find operation I'm using Eclipselink to persist data to MySQL database and when I call the create method, it give me the error:

An instance of a null PK has been incorrectly provided for this find
operation

I've searched on other questions here, but none of them solved my problem.
I have a class Autor and a class Filme. Both have the ID field as AUTO INCREMENT and the table Filme have the foreign key referencing to Autor.id_autor.
Here is the code of my database:

CREATE TABLE `autor` (
  `id_autor` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(100) NOT NULL,
  PRIMARY KEY (`id_autor`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

CREATE TABLE `filme` (
  `id_filme` int(11) NOT NULL AUTO_INCREMENT,
  `id_autor` int(11) NOT NULL,
  `nome` varchar(100) NOT NULL,
  PRIMARY KEY (`id_filme`),
  KEY `fk_flme_ator_idx` (`id_autor`),
  CONSTRAINT `fk_flme_ator` FOREIGN KEY (`id_autor`) REFERENCES `autor` (`id_autor`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

And the Java classes:
Autor.java
package model;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

@Entity
@Table(name = "autor")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Autor.findAll", query = "SELECT a FROM Autor a"),
    @NamedQuery(name = "Autor.findByIdAutor", query = "SELECT a FROM Autor a WHERE a.idAutor = :idAutor"),
    @NamedQuery(name = "Autor.findByNome", query = "SELECT a FROM Autor a WHERE a.nome = :nome")})
public class Autor implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_autor")
    private Integer idAutor;
    @Basic(optional = false)
    @Column(name = "nome")
    private String nome;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idAutor")
    private Collection<Filme> filmeCollection;

    public Autor() {
    }

    public Autor(Integer idAutor) {
        this.idAutor = idAutor;
    }

    public Autor(Integer idAutor, String nome) {
        this.idAutor = idAutor;
        this.nome = nome;
    }

    public Integer getIdAutor() {
        return idAutor;
    }

    public void setIdAutor(Integer idAutor) {
        this.idAutor = idAutor;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    @XmlTransient
    public Collection<Filme> getFilmeCollection() {
        return filmeCollection;
    }

    public void setFilmeCollection(Collection<Filme> filmeCollection) {
        this.filmeCollection = filmeCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idAutor != null ? idAutor.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Autor)) {
            return false;
        }
        Autor other = (Autor) object;
        if ((this.idAutor == null && other.idAutor != null) || (this.idAutor != null && !this.idAutor.equals(other.idAutor))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return nome;
    }

}

Filme.java
package model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "filme")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Filme.findAll", query = "SELECT f FROM Filme f"),
    @NamedQuery(name = "Filme.findByIdFilme", query = "SELECT f FROM Filme f WHERE f.idFilme = :idFilme"),
    @NamedQuery(name = "Filme.findByNome", query = "SELECT f FROM Filme f WHERE f.nome = :nome")})
public class Filme implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_filme")
    private Integer idFilme;
    @Basic(optional = false)
    @Column(name = "nome")
    private String nome;
    @JoinColumn(name = "id_autor", referencedColumnName = "id_autor")
    @ManyToOne(optional = false)
    private Autor idAutor;

    public Filme() {
    }

    public Filme(Integer idFilme) {
        this.idFilme = idFilme;
    }

    public Filme(Integer idFilme, String nome) {
        this.idFilme = idFilme;
        this.nome = nome;
    }

    public Integer getIdFilme() {
        return idFilme;
    }

    public void setIdFilme(Integer idFilme) {
        this.idFilme = idFilme;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Autor getIdAutor() {
        return idAutor;
    }

    public void setIdAutor(Autor idAutor) {
        this.idAutor = idAutor;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idFilme != null ? idFilme.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Filme)) {
            return false;
        }
        Filme other = (Filme) object;
        if ((this.idFilme == null && other.idFilme != null) || (this.idFilme != null && !this.idFilme.equals(other.idFilme))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return nome;
    }

}

Main.java:
public static void main(String[] args) {

        EntityManagerFactory emf = null;
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("Estudos_JPAPU");
        }

        Autor a = new Autor();
        a.setNome("Autor 1");
        a.setFilmeCollection(new ArrayList());

        Filme f = new Filme();
        f.setNome("Filme 1");
        f.setIdAutor(a);

        a.getFilmeCollection().add(f);

        new AutorJpaController(emf).create(a);

    }

EDIT
AutorJpaController.java
import controller.exceptions.IllegalOrphanException;
import controller.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.Filme;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import model.Autor;

public class AutorJpaController implements Serializable {

    public AutorJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Autor autor) {
        if (autor.getFilmeCollection() == null) {
            autor.setFilmeCollection(new ArrayList<Filme>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Filme> attachedFilmeCollection = new ArrayList<Filme>();
            for (Filme filmeCollectionFilmeToAttach : autor.getFilmeCollection()) {
                filmeCollectionFilmeToAttach = em.getReference(filmeCollectionFilmeToAttach.getClass(), filmeCollectionFilmeToAttach.getIdFilme());
                attachedFilmeCollection.add(filmeCollectionFilmeToAttach);
            }
            autor.setFilmeCollection(attachedFilmeCollection);
            em.persist(autor);
            for (Filme filmeCollectionFilme : autor.getFilmeCollection()) {
                Autor oldIdAutorOfFilmeCollectionFilme = filmeCollectionFilme.getIdAutor();
                filmeCollectionFilme.setIdAutor(autor);
                filmeCollectionFilme = em.merge(filmeCollectionFilme);
                if (oldIdAutorOfFilmeCollectionFilme != null) {
                    oldIdAutorOfFilmeCollectionFilme.getFilmeCollection().remove(filmeCollectionFilme);
                    oldIdAutorOfFilmeCollectionFilme = em.merge(oldIdAutorOfFilmeCollectionFilme);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Autor autor) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Autor persistentAutor = em.find(Autor.class, autor.getIdAutor());
            Collection<Filme> filmeCollectionOld = persistentAutor.getFilmeCollection();
            Collection<Filme> filmeCollectionNew = autor.getFilmeCollection();
            List<String> illegalOrphanMessages = null;
            for (Filme filmeCollectionOldFilme : filmeCollectionOld) {
                if (!filmeCollectionNew.contains(filmeCollectionOldFilme)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Filme " + filmeCollectionOldFilme + " since its idAutor field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Filme> attachedFilmeCollectionNew = new ArrayList<Filme>();
            for (Filme filmeCollectionNewFilmeToAttach : filmeCollectionNew) {
                filmeCollectionNewFilmeToAttach = em.getReference(filmeCollectionNewFilmeToAttach.getClass(), filmeCollectionNewFilmeToAttach.getIdFilme());
                attachedFilmeCollectionNew.add(filmeCollectionNewFilmeToAttach);
            }
            filmeCollectionNew = attachedFilmeCollectionNew;
            autor.setFilmeCollection(filmeCollectionNew);
            autor = em.merge(autor);
            for (Filme filmeCollectionNewFilme : filmeCollectionNew) {
                if (!filmeCollectionOld.contains(filmeCollectionNewFilme)) {
                    Autor oldIdAutorOfFilmeCollectionNewFilme = filmeCollectionNewFilme.getIdAutor();
                    filmeCollectionNewFilme.setIdAutor(autor);
                    filmeCollectionNewFilme = em.merge(filmeCollectionNewFilme);
                    if (oldIdAutorOfFilmeCollectionNewFilme != null && !oldIdAutorOfFilmeCollectionNewFilme.equals(autor)) {
                        oldIdAutorOfFilmeCollectionNewFilme.getFilmeCollection().remove(filmeCollectionNewFilme);
                        oldIdAutorOfFilmeCollectionNewFilme = em.merge(oldIdAutorOfFilmeCollectionNewFilme);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = autor.getIdAutor();
                if (findAutor(id) == null) {
                    throw new NonexistentEntityException("The autor with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Autor autor;
            try {
                autor = em.getReference(Autor.class, id);
                autor.getIdAutor();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The autor with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Filme> filmeCollectionOrphanCheck = autor.getFilmeCollection();
            for (Filme filmeCollectionOrphanCheckFilme : filmeCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Autor (" + autor + ") cannot be destroyed since the Filme " + filmeCollectionOrphanCheckFilme + " in its filmeCollection field has a non-nullable idAutor field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(autor);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Autor> findAutorEntities() {
        return findAutorEntities(true, -1, -1);
    }

    public List<Autor> findAutorEntities(int maxResults, int firstResult) {
        return findAutorEntities(false, maxResults, firstResult);
    }

    private List<Autor> findAutorEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Autor.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Autor findAutor(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Autor.class, id);
        } finally {
            em.close();
        }
    }

    public int getAutorCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Autor> rt = cq.from(Autor.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}

FilmeJpaController.java
import controller.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.Autor;
import model.Filme;

public class FilmeJpaController implements Serializable {

    public FilmeJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Filme filme) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Autor idAutor = filme.getIdAutor();
            if (idAutor != null) {
                idAutor = em.getReference(idAutor.getClass(), idAutor.getIdAutor());
                filme.setIdAutor(idAutor);
            }
            em.persist(filme);
            if (idAutor != null) {
                idAutor.getFilmeCollection().add(filme);
                idAutor = em.merge(idAutor);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Filme filme) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Filme persistentFilme = em.find(Filme.class, filme.getIdFilme());
            Autor idAutorOld = persistentFilme.getIdAutor();
            Autor idAutorNew = filme.getIdAutor();
            if (idAutorNew != null) {
                idAutorNew = em.getReference(idAutorNew.getClass(), idAutorNew.getIdAutor());
                filme.setIdAutor(idAutorNew);
            }
            filme = em.merge(filme);
            if (idAutorOld != null && !idAutorOld.equals(idAutorNew)) {
                idAutorOld.getFilmeCollection().remove(filme);
                idAutorOld = em.merge(idAutorOld);
            }
            if (idAutorNew != null && !idAutorNew.equals(idAutorOld)) {
                idAutorNew.getFilmeCollection().add(filme);
                idAutorNew = em.merge(idAutorNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = filme.getIdFilme();
                if (findFilme(id) == null) {
                    throw new NonexistentEntityException("The filme with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Filme filme;
            try {
                filme = em.getReference(Filme.class, id);
                filme.getIdFilme();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The filme with id " + id + " no longer exists.", enfe);
            }
            Autor idAutor = filme.getIdAutor();
            if (idAutor != null) {
                idAutor.getFilmeCollection().remove(filme);
                idAutor = em.merge(idAutor);
            }
            em.remove(filme);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Filme> findFilmeEntities() {
        return findFilmeEntities(true, -1, -1);
    }

    public List<Filme> findFilmeEntities(int maxResults, int firstResult) {
        return findFilmeEntities(false, maxResults, firstResult);
    }

    private List<Filme> findFilmeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Filme.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Filme findFilme(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Filme.class, id);
        } finally {
            em.close();
        }
    }

    public int getFilmeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Filme> rt = cq.from(Filme.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}

A: For create, depending on how you want to handle the object graph, you'll need to look at the references within that graph and handle them appropriately:
public void create(Filme filme) {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Autor autor = filme.getIdAutor();
        if (autor != null) {
            Integer autorId = autor.getId();
          if (autorId == null) {
            em.persist(autor);
          } else {
            //if this has an id, let this call throw an error if it doesn't exist in the database
            autor = em.getReference(idAutor.getClass(), autorId);
            filme.setIdAutor(autor);
            //autor is managed already, so no need to call merge
            autor.getFilmeCollection().add(filme);
        }
        em.persist(filme);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

The above allows you to decide what to do when you encounter an Autor instance being referenced from the Filme. Calling Persist explicitly on it though will cause that persist call to cascade over the filmeCollection relationship, so anything referenced in there will also have persist called on it - something to watch out for if this isn't a blank/empty instance.


text:
Q: how do i maintain previous and current received data arrays with out getting out of bounds in C# so i am maintaining previous and current received data from textbox, by putting received data into an array, but when splitting them up using split() one of my newPosition arrays does not work, triggers "Index was outside the bounds of the array" but the other oldPosition works fine. Im abit stuck
here is my current implmenetation
           for (i = 1; i < textBox_ReceievedData.Lines.Length; i++)
            {
                currentPos = textBox_ReceievedData.Lines[i];
                prevPos = textBox_ReceievedData.Lines[i - 1];

                System.Console.WriteLine("array pos " + i);
                System.Console.WriteLine("previous array " +prevPos);
                System.Console.WriteLine("current Array " + currentPos);

                oldPosition = prevPos.Split(delimiterChars);
                newPosition = currentPos.Split(delimiterChars);

                System.Console.WriteLine("op " + oldPosition[2]);// used to get value in 2nd postition
            //System.Console.WriteLine("np " + newPosition[2]);// used to get value in 2nd postition, but will get an error
}

output:
array pos 2
previous array $GPGGA,090156.80,3651.09301173,S,17445.84851186,E,1,05,2.87,038.38,M,-21.3213,M,,*63
current Array $GPGGA,090157.00,3651.09230339,S,17445.84886368,E,1,05,2.87,038.33,M,-21.3213,M,,*6D
op 3651.09301173
array pos 3
previous array $GPGGA,090157.00,3651.09230339,S,17445.84886368,E,1,05,2.87,038.33,M,-21.3213,M,,*6D
current Array $GPGGA,090157.20,3651.09159552,S,17445.84921771,E,1,05,2.87,038.29,M,-21.3213,M,,*68
op 3651.09230339

if i were to use System.Console.WriteLine("np " + newPositon) i would get,
System.String[]

A: Just checked , Your code is working fine. it seems input is having incorrect format. plz put a if condition to check whether index exist or not like as below:
if (newPosition.Length > 2)
 {
  System.Console.WriteLine("np " + newPosition[2]);
 }

Output Here:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Socket not defined error in client application I am trying to make a GUI for this script I made. I want to press the connect button first to connect to the server. then hit send to send a file. But when I press connect it sends an empty text file and the send button gives me an error that my socket is not defined.
from Tkinter import *

class Application(Frame):

def __init__(self, master):

    Frame.__init__(self, master)
    self.grid()
    self.create_widgets()

def create_widgets(self):

    self.instruction = Label(self, text = 'Enter ip')
    self.instruction.grid(row=0, column = 0, columnspan = 2, sticky = W)

    self.instruction = Label(self, text = 'Enter Port')
    self.instruction.grid(row=1, column = 0, columnspan = 2, sticky = W)

    self.instruction = Label(self, text = '      ')
    self.instruction.grid(row=2, column = 0, columnspan = 2, sticky = W)

    self.instruction = Label(self, text = 'Enter path')
    self.instruction.grid(row=5, column = 0, columnspan = 2, sticky = W)

    self.ip = Entry(self)
    self.ip.grid(row=0, column = 1, sticky = W)

    self.port = Entry(self)
    self.port.grid(row=1, column = 1, sticky = W)

    self.path = Entry(self)
    self.path.grid(row=5, column = 1, sticky = W)

    self.submit_button = Button(self, text='connect', command = self.connect)
    self.submit_button.grid(row = 1, column = 2, sticky = W)

    self.send_button = Button(self, text='Send file', command = self.send)
    self.send_button.grid(row = 5, column = 2, sticky = W)

    self.text = Text(self, width = 80, height = 5, wrap = WORD)
    self.text.grid(row = 10, column = 0, columnspan = 3, sticky = W)

def connect(self):

    ip = self.ip.get()
    port = int(self.port.get())

    import socket
    import sys
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))

    self.text.insert(0.0, 'connecting to' ,ip, port )

def send(self):
    path = self.path.get()
    f=open (path, "rb")
    l = f.read(1024)
    while (l):
        s.send(l)
        l = f.read(1024)
    s.close()

 root = Tk()
 root.title("Client")
 root.geometry("420x200")
 app = Application(root)

 root.mainloop()

this is my server script
from Tkinter import *

import socket
import sys

class Application(Frame):

def __init__(self, master):

    Frame.__init__(self, master)
    self.grid()
    self.create_widgets()

def create_widgets(self):

    self.text = Text(self, width = 35, height = 5, wrap = WORD)
    self.text.grid(row = 0, column = 0, columnspan = 2, sticky = W)

    self.submit_button = Button(self, text='start', command = self.start)
    self.submit_button.grid(row = 2, column = 0, sticky = W)

def start(self):

    self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.text.insert(0.0, 'Server started!\n' )
    self.s.bind(('',1080))
    self.s.listen(10)

    while True:
        sc, address = self.s.accept()
        i=1
        f = open('file_'+ str(i)+".txt",'wb') #open in binary
        i=i+1
        while (True):
            l = sc.recv(1024)
            while (l):
                print l
                f.write(l)
                f.flush()
                l = sc.recv(1024)
        f.close()

        sc.close()

    #s.close()

  root = Tk()
  root.title("Server")
  root.geometry("500x250")
  app = Application(root)
  root.mainloop()

A: s is a local variable of connect, so it isn't within the scope of the send method. Since you are already using a class for the application, you can store a reference to the socket by replacing every s with self.s.
Also keep in mind that your socket operations run on the GUI thread, so your application won't be responsive until they finish their execution. As a possible solution, you can use the threading module to run them on a separate thread.


text:
Q: 32-Bit 64-Bit Difference While Calculating Cipher I have a simple Xades/BES implementation and two situations.

*

*On Windows 7 32Bit
with java
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode)

*On Windows 2008 Server 64 Bit, and with the same JVM.
My application works perfectly fine on 32 bit Windows 7, however when I try to run the compiled code in Windows 2008 Server I get an error:
    javax.crypto.BadPaddingException: Data must start with zero
    at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
    at sun.security.rsa.RSAPadding.unpad(Unknown Source)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:349)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
    at javax.crypto.Cipher.doFinal(Cipher.java:2087)

Problematic code field is as follows:
    public static byte[] getDecryptedSignatureValue(XMLSignature signature) throws         XadesElementException, InvalidKeyException
{
    byte[] signatureValue = null;
    try {
        KeyInfo keyInfo = signature.getKeyInfo();
        PublicKey key = keyInfo.getPublicKey();
        Cipher cipher = getCipher("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);

        signatureValue = signature.getSignatureValue();
        byte[] cipherData = cipher.doFinal(signatureValue);
        return cipherData;

    } catch (KeyResolverException | XMLSignatureException | IllegalBlockSizeException | BadPaddingException ex) {
        Logger.getLogger(KeyUtils.class.getName()).log(Level.SEVERE, null, ex);
        Logger.getLogger(KeyUtils.class.getName()).log(Level.SEVERE, null, "SignatureValue:"+ BaseUtils.toBase64String(signatureValue));
    } finally {

    }
    return null;

}

The only thing I can come up with is the architecture difference. Am I missing something here? What can be the problem?
Thanks in advance.
EDIT:
Here are my new findings.
1. I have tested my application on Windows 7 64 bit and there was no problem, while signing and verifying.
2. More interestingly, I have tested the application on another Windows 2008 Server 64 bit and it worked with a success.
I think there is a configuration setting for something but I could not figure it out what.

A: This is likely due to the chosen provider and/or provider implementation. Note that there is a difference between PKCS#1 padding for encryption (EME-PKCS1-v1_5 decoding) and PKCS#1 padding for signature verification (EMSA-PKCS1-v1_5 encoding). Some providers will choose a padding depending on the key type (public or private), others will keep to a single padding scheme depending if you are using Cipher or Signature.
If possible try and use Signature for signature verification, not Cipher decryption with a public key. Otherwise check which providers are chosen (using e.g. Cipher.getProvider() and try to find one that works. Note that - as you may already have discovered - it depends on the implementation, not on the interface specification if decryption succeeds or fails.
So currently it is trying to decode this:
EM = 0x00 || 0x02 || PS || 0x00 || M

with a random, nonzero PS and message M
You expect however to verify this:
EM = 0x00 || 0x01 || PS || 0x00 || T

with a PS with values FF, and T being an ASN.1 DER encoded algorithm OID and hash value.


text:
Q: Get partial string from string I have the following string:
This isMyTest testing

I want to get isMyTest as a result. I only have two first characters available("is"). The rest of the word can vary.
Basically, I need to select a first word delimeted by spaces which starts with chk.
I've started with the following:
if (text.contains(" is"))
{
text.LastIndexOf(" is"); //Should give me index.
}

now  I cannot find the right bound of the word since I need to match on something like

A: You can use regular expressions:

    string pattern = @"\bis";
    string input = "This isMyTest testing";
    return Regex.Matches(input, pattern);

A: You can use IndexOf to get the index of the next space:
int startPosition = text.LastIndexOf(" is");
if (startPosition != -1)
{
    int endPosition = text.IndexOf(' ', startPosition + 1); // Find next space
    if (endPosition == -1)
       endPosition = text.Length - 1; // Select end if this is the last word?
}

A: What about using a regex match? Generally if you are searching for a pattern in a string (ie starting with a space followed by some other character) regex are perfectly suited to this. Regex statements really only fall apart in contextually sensitive areas (such as HTML) but are perfect for a regular string search.
// First we see the input string.
string input = "/content/alternate-1.aspx";

// Here we call Regex.Match.
Match match = Regex.Match(input, @"[ ]is[A-z0-9]*",     RegexOptions.IgnoreCase);

// Here we check the Match instance.
if (match.Success)
{
    // Finally, we get the Group value and display it.
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}


text:
Q: Category of topological spaces with open or closed maps Consider the category whose objects are topological spaces and whose morphisms are the open maps (or closed maps, open continuous maps, closed continuous maps ... that is, one whose isomorphisms are  precisely the homeomorphisms). How does such a category compare with the usual one whose objects are topological spaces and whose morphisms are continuous maps?  For example, what limits and colimits exist?
I'm probably missing something obvious, but why don't products typically exist in the category with open maps? The projections from the usual product (in the category with continuous maps) are open, yielding a canonical open map from the usual product to the putative unusual product.
Todd's observation is true enough: the product in the usual topology (contiuous maps) typically fails to realize the corresponding universal property in the unusual topology  (open maps). Nevertheless,  some other object might realize that universal property. Is it even clear that the if such a space exists its underlying set should be naturally identifiable with the underlying set of the factors? After all, while one point spaces are still terminal, maps out of such objects tend not to be open: it seems one would thereby only extract the subset of isolated points. In any event, http://christianmarks.wordpress.com/category/bagatelle
treats the special case of squares. The appropriate space is $X\times X$ with the weakest topology (stronger than the usual) which makes the diagonal embedding open. This construction is clearly not available for products of distinct spaces. My question concerns whether there isn't (as that post suggests there isn't) some devious workaround.

A: The category can be drastically different. For example, suppose your morphisms are precisely local homeomorphisms. Call this category $Top^{et}$. This category is locally a topos, which is something certainly not the case for the category $Top$ of all continuous maps. Moreover,  $Top^{et}$ lacks a terminal object (which is something which will happen for many variants). In fact, $Top^{et}$ behaves much more like a category of sheaves on a single space, then a category of spaces; to see this, if we let $\mathfrak{Top}^{et}$ denote the bicategory of (etale) topological stacks and local homeomorphisms,  this is equivalent to the bicategory of stacks on some (filtered colimit of) etale topological stack(s). The bicategory $\mathfrak{Top}^{et}$ contains $Top^{et}$ as a full subcategory, and (if we restrict to a set of topological spaces) is a $2$-topos, so has all the limits, colimits etc. you can imagine. Using this, it can be shown that $Top^{et}$ does have at least binary products, but they behave very differently than in $Top.$ For example, instead of $Top$, consider the category $Mfd$ of smooth manifolds. Given an $n$-manifold $N$ and an $m$-manifold $M,$ their product $N \times^{et} M$ in $Mfd^{et}$ is empty if $n \ne m,$ and if $n=m,$ their product is a highly non-Hausdorff smooth $n$-manifold. This is discussed in http://arxiv.org/abs/1212.2282.

A: This seems difficult to answer in any kind of uniform way, i.e., it seems we have to work on a case-by-case basis. Let's start with $\mathrm{Top}_{\mathrm{open}}$, the category of topological spaces and open continuous maps.
A useful heuristic is to let oneself be guided by locales instead of topological spaces. (For general information on locales, see for instance Mac Lane-Moerdijk, Sheaves in Geometry and Logic, chapter IX.) Recall that the category of locales is (by definition) the category opposite to the category of frames (sup-lattices in which finite meets distribute over arbitrary joins); the frame associated with a locale (by viewing the same object in the opposite category) should be thought of as its topology. Now a frame automatically carries Heyting algebra structure, and it turns out that open continuous maps of locales correspond to frame maps that are also Heyting algebra maps (i.e., Heyting algebra maps which are sup-preserving). Thus, the category of locales and open continuous maps is opposite to the category of cocomplete Heyting algebras, which is a category of algebras of an infinitary algebraic theory. It follows that the category of locales and open continuous maps is complete. Moreover, limits of cocomplete Heyting algebras are computed just as they are in $Set$, and so the calculation of colimits in locales and open continuous maps will be similarly straightforward.
Guided by this heuristic, one might at the very least expect that colimits in $\mathrm{Top}_{\mathrm{open}}$ are calculated just as they are in $\mathrm{Top}$. Indeed, one can easily check this directly for arbitrary coproducts (where the coproduct topology on a disjoint union $X = \sum_\alpha X_\alpha$ is the largest one such that all the canonical inclusions $X_\alpha \to X$ are continuous; notice they are open). As for coequalizers, if two maps
$$f, g: R \stackrel{\to}{\to} X$$
are open and continuous, and if we consider the coequalizer $q: X \to Y$ in $\mathrm{Top}$ (where the topology on $Y$ is the usual quotient topology induced by $q$), then we claim that $q$ is also open and this is the coequalizer in the category of open continuous maps. For, if $V$ is open in $X$, then $q(V)$ is open in $Y$ iff $q^{-1}(q(V))$ is open in $X$, and clearly this holds since
$$q^{-1}(q(V)) = V \cup \bigcup_n (g f^{-1})^n(V) \cup (f g^{-1})^n(V)$$
where the right side is open because $f$ and $g$ are open and continuous.
Pausing briefly to consider the category of topological spaces and closed continuous maps, it is certainly true that finite coproducts exist and are computed just as they are in $\mathrm{Top}$. Also, it is true that quotients of equivalence relations are computed as in $\mathrm{Top}$. That is to say: if $E \subseteq X \times X$ is an equivalence relation and the two projection maps $\pi_1: E \to X$ and $\pi_2: E \to X$ are closed, then the coequalizer $q = \mathrm{coeq}(\pi_1, \pi_2)$ in $Top$ is the coequalizer in the category of closed continuous maps. Indeed, if $C$ is closed in $X$, then $q(C)$ is closed because
$$q^{-1}(q(C)) = \pi_1(\pi_2^{-1}(C))$$
is closed.
Limits are trickier, and I believe do not always exist in $\mathrm{Top}_{\mathrm{open}}$ (see below). Even when they do exist, one should not expect to calculate limits as one would in $\mathrm{Top}$ (for example, Cantor space as a countable product of copies of the discrete two-element space could not possibly be the correct product in $\mathrm{Top}_{\mathrm{open}}$ since Cantor space has no isolated points), nor even as in $\mathrm{Set}$, so this makes limits a little weird.
Here's a partial result: if we have a diagram $F: D \to \mathrm{Top}_{\mathrm{open}}$ and all the spaces $F(d)$ are sober (i.e., of the form $\mathrm{Pt}(\mathcal{O}(X))$, where $\mathrm{Pt}: \mathrm{Frame}^{op} \to \mathrm{Top}$ is right adjoint to $\mathcal{O}: Top \to \mathrm{Frame}^{op}$), then the limit of $F$ in $\mathrm{Top}_{\mathrm{open}}$ can be constructed as $\mathrm{Pt}(\mathrm{colim} \; \mathcal{O}(F d))$ where the colimit is computed in the category of cocomplete Heyting algebras, provided that colimit exists. This uses the fact that for any topological space $X$, the set of open continuous maps $X \to \mathrm{Pt}(H)$ ($H$ a cocomplete Heyting algebra) is in natural one-one correspondence with cocomplete Heyting algebra maps $H \to \mathcal{O}(X)$, together with elementary categorical manipulations.
I conjecture that finite colimits of cocomplete Heyting algebras exist (so that finite limits of sober spaces in $\mathrm{Top}_{\mathrm{open}}$ exist). But inasmuch as the countable coproduct of copies of the free cocomplete Heyting algebra on one generator does not exist (it would be the free cocomplete Heyting algebra on countably many generators, which is known not to exist), it seems to me that $\mathrm{Top}_{\mathrm{open}}$ does not have countable products.


text:
Q: Password Security for Shared Hosts (PHP 5.2+) I'm working on some PHP meant to be deployed to users' servers - likely cheap/shared hosting (meaning lowest-common-denominator PHP 5.2, no modification of PHP installation). Common advice for password hashes seems to be bcrypt or scrypt, via installable extensions for PHP 5.2.
I've been thinking about using an iterated SHA-512 with a beefy per-user salt, but it doesn't sound like it really compares to bcrypt/scrypt.
Without the ability to modify the base PHP installation, what options do I have for strong password security?

A: The first thing I would say is that PHP 5.2 should not be considered. It was declared end-of life nearly two years ago, and hasn't had any security patches in that time, so any host still using it clearly doesn't take security seriously anyway. You should consider 5.3 as the minimum version these days.
No on to passwords...
The next version of PHP (v5.5) will have a set of functions built-in that provide standardised password hashing. The idea is to once-and-for all get rid of any excuse for bad password practice in PHP. Once this version is released, that will be the only recommended way to handle passwords.
In the meanwhile, you can download a compatibility library that implements the same functions for current PHP versions. Download it from here: https://github.com/ircmaxell/password_compat
My recommendation is to use this library, enclosed in a if(function_exists()) wrapper. That way you'll be using best practice, and also be ready to use the built-in funcs when 5.5 is released.
See also: http://www.h-online.com/open/news/item/PHP-5-5-should-reduce-password-sloppiness-1707835.html for reference.
Hope that helps.

A: As mentioned in the comments to the original question, a PHP < 5.2 implementation of PBKDF2 is available at http://crackstation.net/hashing-security.htm.
PBKDF2 is arguably a better option than bcrypt/scrypt, having been much more thoroughly studied and tested.


text:
Q: Add to CONCAT() if a column is = 1 Im trying to get a SQL query to concat "FreeShipping" to a string only if I have a '1' in FreeShipping field
This is the current SQL I have but I have no clue how to use the IF statement and add the concat() function
Im I suposed to make the if select between two concat() function?
SELECT
    `Id`
FROM
    `product_products` as pp
WHERE
    CONCAT(
        `Id`,
        ' ',
        (SELECT `Name` FROM `product_brands` WHERE `Id` = pp.BrandId),
        ' ',
        `ModelNumber`,
        ' ',
        `Title`
    )
LIKE :SearchStr AND isActive = 1;

Expected result is only Id of products, I want to select the products by Searching for "FreeShipping"
The :SearchStr is a variable

A: Assuming you are filtering by that concatenated string, you could do something like this:
SELECT
    `Id`
FROM
    `product_products` as pp
WHERE
    CONCAT(
        `Id`,
        ' ',
        (SELECT `Name` FROM `product_brands` WHERE `Id` = pp.BrandId),
        ' ',
        `ModelNumber`,
        ' ',
        `Title`,
        IF(`FreeShipping` = 1, " FreeShipping", "")
    )
LIKE :SearchStr AND isActive = 1;

If FreeShipping = 1 then concat " FreeShipping" (with leading space). If not, then concat with an empty string.


text:
Q: Thinking sphinx with privacy settings using facets? I'm trying to use Thinking Sphinx with my Can Can solution for authorization.
I found this answer helpful Cancan Thinking Sphinx current_ability Questions, but was wondering if there might be a way to accomplish this with facets.
So I have projects, where there is a column called privacy which is a bool. If a project is private then there is an index for collaborator_ids, which is a list of all of the users that can view the project.
I was wondering if there is a way to form a query using facets to return all projects that are either public OR private and the user's id is in the collaborator_ids.

Another approach I'm considering is formulating an extended query in my controller to check for these fields. http://sphinxsearch.com/docs/current.html#extended-syntax

A: I have no idea how you would do it thinking sphinx, but in normal sphinx this should work..
$cl->setSelect("*,privacy+IF(IN($user_id,collaborator_ids),1,0) AS myint");
$cl->setFilter('myint',array(1,2));

Which effectily makes an 'OR' query.
As I say, cant help you write thatin in thinging-sphinx.


text:
Q: Deleting a column in a pandas frame
I have been trying the past 40 minutes to delete a specific column (Name) from my data frame but no method seems to work. I am using jupyter notebook by the way, not sure if that may be an issue. I am also 100% sure that the column name is named Name and that it is not the index of the data frame -- I am using the Titanic data set.

What I have tried:

*

*del df['Name']

*df.drop('Name', axis=1, inplace=True)

*df = df.drop('Name', 1)
All the above seem to delete the column, but when re-reading the csv the column appears back. Any clue on why this is happening?

A: When you read a csv to Pandas DataFrame you load the data to memory. Doing anything to data frame won't change your csv. I would suggest you export your modified dataframe as a new csv
df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)
DOCS

A: With reading a csv file and loading its content in a dataframe, you create a python object called df.
Then, with the three methods you showed us, you only delete some content of this object, not the csv's content.
I would recommend you to use the first method, del, keep working with the dataframe and not reading the csv again.
Let me know if anything is unclear, please.


text: Q: How to integrate odoo google calendar with odoo Sales module or Crm Module in odoo V13? To integrate Google Calendar api with odoo sale module or crm module.Now i have enable google api and get client id and client secret.


text:
Q: Flowplayer6 does not work on mobile I'm using Flowplayer6 / HTML5 wordpress plugin to play videos on the site.
I have trouble playing the player on the phone. By clicking on the player, the video does not run .
Please find an online example of the problem below:
http://www.muzika.com.br/vertice/player_portacurtas/filme/?name=j_carlos_o_cronista_do_rio
obs .: the 5/2 is normal to stop the video.

A: According to the know issues section in flowplayer documentation, it seems that:

*

*Mobile devices and iOS do not support automatic playback on page load.
  Volume and mute state cannot be controlled on mobile platforms and
  iOS.

*Mobile phones and iPod do not allow inline playback in the
  browser. The native player component takes over entirely. They
  therefore also do not fully support the JavaScript API, especially
  when it comes to interaction with the page.

You will find in the documentation some workarounds, but maybe this is not the right plugin for what you need.


text:
Q: Boxed equation with empheq: adding text outside box I'm trying to have a box around my align environment, so I do the following:
\usepackage{empheq}
\begin{empheq}[box=\fbox]{align}
  equations
\end{empheq}

This works fine, but I would like to have above the box text as some kind of title for the box.
So I try
 \newcommand*\textfbox[2][Title]{
     \begin{center}
        \text{#2}
     \end{center}
     \fbox{#1}
 }

And then replace box=\fbox with box={\textfbox{the title that I want}}. This does not work, it places the text next to the box and not above the box, so I have tried inserting \par or \newline but to no avail.

A: You are using in a wrong way the parameters, first of all: #1 refers to the optional argument, #2 to the mandatory one. Moreover, there's no centering environment and the \centering command is useless here.
\newcommand*\textfbox[2][Title]{%
  \begin{tabular}[b]{@{}c@{}}#1\\\fbox{#2}\end{tabular}}

\begin{empheq}[box={\textfbox[A different title]}]{align}
  equations
\end{empheq}


text:
Q: Solving numerically a dissipative non-linear system of coupled ODEs My problem is to integrate a set of couple non-linear and first order ODEs. They are Eqs. (45) -- (50) in the paper https://arxiv.org/pdf/1901.03380.pdf.
This is the set of differential equations I should integrate:
(*Useful initial functions*)
\[CapitalSigma][r_, a_, \[Theta]_] := r^2 + (a*Cos[\[Theta]])^2;
\[CapitalDelta][r_, a_] := r^2 - 2*r + a^2;
\[Rho][r_, a_, \[Theta]_] :=
  r^2 + a^2 +
   2*r*(a*Sin[\[Theta]])^2/\[CapitalSigma][r, a, \[Theta]];
\[Gamma][\[Upsilon]_] := (1 - \[Upsilon]^2)^(-1/2);

(*Useful further functions*)
N2[r_, a_, \[Theta]_] := \[CapitalDelta][r, a]/\[Rho][r,
    a, \[Theta]];
Nphi[r_, a_, \[Theta]_] := -2*a*
   r/(\[CapitalSigma][r, a, \[Theta]]*\[Rho][r, a, \[Theta]]);

(*Metric components*)
gtphi[r_, a_, \[Theta]_] := -2*a*r*
   Sin[\[Theta]]^2/\[CapitalSigma][r, a, \[Theta]];
gphiphi[r_, a_, \[Theta]_] := \[Rho][r, a, \[Theta]]*Sin[\[Theta]]^2;
grr[r_, a_, \[Theta]_] := \[CapitalSigma][r,
    a, \[Theta]]/\[CapitalDelta][r, a];
gthth[r_, a_, \[Theta]_] := \[CapitalSigma][r, a, \[Theta]];
gtt[r_, a_, \[Theta]_] := -(1 - 2*r/\[CapitalSigma][r, a, \[Theta]]);

(*Kinematical quantities*)
AR[r_, a_, \[Theta]_] := (1/(\[Rho][r, a, \[Theta]]*
       Sqrt[\[CapitalSigma][r, a, \[Theta]]^5*\[CapitalDelta][r,
          a]]))*(\[CapitalSigma][r, a, \[Theta]]^2*(r^2 -
        a^2) + (a*
         Sin[\[Theta]])^2*(r^2*(3*r^2 - 4*r +
           a^2) + (a*Cos[\[Theta]])^2*(r^2 - a^2)));
TR[r_, a_, \[Theta]_] :=
  a*Sin[\[Theta]]*((r^2 + a^2)*(\[CapitalSigma][r, a, \[Theta]] -
         2*r^2) -
      2*r^2*\[CapitalSigma][r, a, \[Theta]])/(\[Rho][r, a, \[Theta]]*
      Sqrt[\[CapitalSigma][r, a, \[Theta]]^5]);
KR[r_, a_, \[Theta]_] := -Sqrt[\[CapitalDelta][r,
       a]/\[CapitalSigma][r,
        a, \[Theta]]^5]*(r*\[CapitalSigma][r,
         a, \[Theta]]^2 + (a*Sin[\[Theta]])^2 *(\[CapitalSigma][r,
          a, \[Theta]] - 2*r^2))/(\[Rho][r, a, \[Theta]]);

AT[r_, a_, \[Theta]_] := -a^2*r*
   Sin[2*\[Theta]]*(r^2 + a^2)/(\[Rho][r, a, \[Theta]]*
      Sqrt[\[CapitalSigma][r, a, \[Theta]]^5]);
TT[r_, a_, \[Theta]_] :=
  a^2*r*Sin[2*\[Theta]]*Sin[\[Theta]]*
   Sqrt[\[CapitalDelta][r, a]]/(\[Rho][r, a, \[Theta]]*
      Sqrt[\[CapitalSigma][r, a, \[Theta]]^5]);
KT[r_, a_, \[Theta]_] := -Sin[
     2*\[Theta]]*((r^2 +
         a^2)*(2*a^2*r*
          Sin[\[Theta]]^2 + \[CapitalSigma][r, a, \[Theta]]^2) +
      2*a^2*r*\[CapitalSigma][r, a, \[Theta]]*
       Sin[\[Theta]]^2)/(2*\[Rho][r, a, \[Theta]]*
      Sqrt[\[CapitalSigma][r, a, \[Theta]]^5]*Sin[\[Theta]]^2);

(*Impact parameters and emission angles*)
RS = 2.5; (*radius of the emission source*)

b[a_, \[Theta]_, \[CapitalOmega]_] := -(gtphi[RS, a, \[Theta]] +
     gphiphi[RS, a, \[Theta]]*\[CapitalOmega])/(gtt[RS, a, \[Theta]] +
     gtphi[RS, a, \[Theta]]*\[CapitalOmega]);
q[a_, \[Theta]_, \[CapitalOmega]_] :=
 If[b[a, \[Theta], \[CapitalOmega]] !=
   0, (b[a, \[Theta], \[CapitalOmega]]*Cot[\[Theta]])^2 - (a*
      Cos[\[Theta]])^2, -(a*Cos[\[Theta]])^2];
\[Beta][r_, a_, \[Theta]_, \[CapitalOmega]_] :=
  ArcCos[b[a, \[Theta], \[CapitalOmega]]*
    Sqrt[N2[r,
       a, \[Theta]]]/(Sqrt[
        gphiphi[r, a, \[Theta]]]*(1 +
         b[a, \[Theta], \[CapitalOmega]]*Nphi[r, a, \[Theta]]))];

(*Factor of the radiation field*)
Rrad[r_, a_, \[Theta]_, \[CapitalOmega]_] := (r^2 + a^2 -
      a*b[a, \[Theta], \[CapitalOmega]])^2 - \[CapitalDelta][r,
     a]*(q[a, \[Theta], \[CapitalOmega]] + (b[
          a, \[Theta], \[CapitalOmega]] - a)^2);
FACT[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] :=
  A*(1 + b[a, \[Theta], \[CapitalOmega]]*Nphi[r, a, \[Theta]])^2/(N2[
       a, \[Theta], \[CapitalOmega]]*
      Sqrt[Rrad[r, a, \[Theta], \[CapitalOmega]]]);

(*Radiation field components*)
F1[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] :=
  FACT[A, a, \[CapitalOmega], \[Upsilon], \[Alpha], \[Psi],
    r, \[Theta]]*(1 - \[Upsilon]*Sin[\[Psi]]*
      Cos[\[Alpha] - \[Beta][r,
         a, \[Theta], \[CapitalOmega]]])*(Sin[\[Psi]]*
      Cos[\[Alpha] - \[Beta][r,
         a, \[Theta], \[CapitalOmega]]] - \[Upsilon]);

F2[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] :=
  FACT[A, a, \[CapitalOmega], \[Upsilon], \[Alpha], \[Psi],
    r, \[Theta]]*(1 - \[Upsilon]*Sin[\[Psi]]*
      Cos[\[Alpha] - \[Beta][r, a, \[Theta], \[CapitalOmega]]])*
   Cos[\[Psi]]*
   Cos[\[Alpha] - \[Beta][r, a, \[Theta], \[CapitalOmega]]]/\[Upsilon];

F3[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] :=
  FACT[A, a, \[CapitalOmega], \[Upsilon], \[Alpha], \[Psi],
    r, \[Theta]]*(1 - \[Upsilon]*Sin[\[Psi]]*
      Cos[\[Alpha] - \[Beta][r, a, \[Theta], \[CapitalOmega]]])*
   Sin[\[Alpha] - \[Beta][r,
       a, \[Theta], \[CapitalOmega]]]/(\[Upsilon]*Sin[\[Psi]]);

(*EQUATIONS OF MOTION*)
Eq1[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] := -1/\[Gamma][\[Upsilon]]*(Sin[\[Alpha]]*
       Sin[\[Psi]]*(AR[r, a, \[Theta]] +
         2*\[Upsilon]*Cos[\[Alpha]]*Sin[\[Psi]]*TR[r, a, \[Theta]]) +
      Cos[\[Psi]]*(AT[r, a, \[Theta]] +
         2*\[Upsilon]*Cos[\[Alpha]]*Sin[\[Psi]]*TT[r, a, \[Theta]])) +
    F1[A, a, \[CapitalOmega], \[Upsilon], \[Alpha], \[Psi],
    r, \[Theta]];

Eq2[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] := \[Gamma][\[Upsilon]]/\[Upsilon]*(Sin[\[Psi]]*(AT[
          r, a, \[Theta]] +
         2*\[Upsilon]*Cos[\[Alpha]]*Sin[\[Psi]]^2*TT[r, a, \[Theta]] +
          KT[r, a, \[Theta]]*\[Upsilon]^2*Cos[\[Alpha]]^2) -
      Sin[\[Alpha]]*
       Cos[\[Psi]]*(AR[r, a, \[Theta]] +
         2*\[Upsilon]*Cos[\[Alpha]]*Sin[\[Psi]]*TR[r, a, \[Theta]] +
         KR[r, a, \[Theta]]*\[Upsilon]^2)) +
   F2[A, a, \[CapitalOmega], \[Upsilon], \[Alpha], \[Psi],
    r, \[Theta]];

Eq3[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] := -\[Gamma][\[Upsilon]]*
    Cos[\[Alpha]]/(\[Upsilon]*Sin[\[Psi]])*(AR[r, a, \[Theta]] +
      2*\[Upsilon]*Cos[\[Alpha]]*Sin[\[Psi]]*TR[r, a, \[Theta]] +
      KR[r, a, \[Theta]]*\[Upsilon]^2 +
      KT[r, a, \[Theta]]*\[Upsilon]^2*Cos[\[Psi]]^2*Sin[\[Alpha]]) +
   F3[A, a, \[CapitalOmega], \[Upsilon], \[Alpha], \[Psi],
    r, \[Theta]];

Eq4[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] := \[Gamma][\[Upsilon]]*\[Upsilon]*Sin[\[Alpha]]*
   Sin[\[Psi]]/Sqrt[grr[r, a, \[Theta]]];

Eq5[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] := \[Gamma][\[Upsilon]]*\[Upsilon]*
   Cos[\[Psi]]/Sqrt[gthth[r, a, \[Theta]]];

Eq6[A_, a_, \[CapitalOmega]_, \[Upsilon]_, \[Alpha]_, \[Psi]_,
   r_, \[Theta]_] := \[Gamma][\[Upsilon]]*\[Upsilon]*Sin[\[Psi]]*
    Cos[\[Alpha]]/
     Sqrt[gphiphi[r, a, \[Theta]]] - \[Gamma][\[Upsilon]]*
    Nphi[r, a, \[Theta]]/Sqrt[N2[r, a, \[Theta]]];

This is the method I used to numerically solve this system of ODEs:
(*Initial parameters*)
A = 0.5;
a = 0.9;
\[CapitalOmega] = 0.24;

(*Initial conditions*)
\[Upsilon]0 = 0.22;
\[Alpha]0 = Pi;
\[Psi]0 = Pi/2;
r0 = 20;
\[Theta]0 = Pi/8;
\[CurlyPhi]0 = 0;

Needs["DifferentialEquations`NDSolveProblems`"]; \
Needs["DifferentialEquations`NDSolveUtilities`"];
(*Systems to integrate*)

system = {x1'[t] ==
    Eq1[A, a, \[CapitalOmega], x1[t], x2[t], x3[t], x4[t], x5[t]],
   x2'[t] ==
    Eq2[A, a, \[CapitalOmega], x1[t], x2[t], x3[t], x4[t], x5[t]],
   x3'[t] ==
    Eq3[A, a, \[CapitalOmega], x1[t], x2[t], x3[t], x4[t], x5[t]],
   x4'[t] ==
    Eq4[A, a, \[CapitalOmega], x1[t], x2[t], x3[t], x4[t], x5[t]],
   x5'[t] ==
    Eq5[A, a, \[CapitalOmega], x1[t], x2[t], x3[t], x4[t], x5[t]],
   x6'[t] ==
    Eq6[A, a, \[CapitalOmega], x1[t], x2[t], x3[t], x4[t], x5[t]],
   x1[0] == \[Upsilon]0, x2[0] == \[Alpha]0, x3[0] == \[Psi]0,
   x4[0] == r0, x5[0] == \[Theta]0, x6[0] == \[CurlyPhi]0};

sol = NDSolve[system
   , {x1, x2, x3, x4, x5, x6}, {t, 0, 14000},
   Method -> {"StiffnessSwitching",
     Method -> {"ExplicitRungeKutta", Automatic}}, AccuracyGoal -> 22,
    MaxSteps -> Infinity, PrecisionGoal -> 15, WorkingPrecision -> 22];

ParametricPlot3D[
 Evaluate[{x4[t]*Sin[x5[t]]*Cos[x6[t]], x4[t]*Sin[x5[t]]*Sin[x6[t]],
    x4[t]*Cos[x5[t]]} /. sol], {t, 0, 14000}, PlotPoints -> 10000,
 ColorFunction -> {Red}, ImageSize -> 500]

I receive message of error, which is

At t == 140.91450584595810929101802343188260751055`22., step size is \
  effectively zero; singularity or stiff system suspected

Could you please help me? Thank you very much.
For further information, please see the images reported down. Thank you very much.


text:
Q: Can a pdf splitter on appengine be built? Would it be technically possible to build a pdf splitter on appengine or is there some part of it that couldn't be done? I was thinking of a function where you just upload the pdf file, choose which pages you want and the output is e.g. one chapter from a book and this can be done online. I think it can be a good service but I don't know whether it is technically feasible or whether the best choice first this would be Java, Python, PHP or Go?

A: I cannot see why not. Splitting a PDF should be possible in all 4 languages so it's up to you what you pick. I know that Python performs faster than Java. PHP doesn't sound like a good fit for me and Go isn't that widely used.
I'd go with Python. There is also a Python library that allows you to split a PDF.


text:
Q: storing wp_head in a variable? how to store WP_head and footer functions in a variable? Is that possible?
I wanted to be like this.
$var = wp_head();

How can achieve it?

A: This function doesn't take any params, so there is no nice way of doing it.
But of course you can do this PHP way using output buffering ;)
ob_start();
wp_head();
$var = ob_get_clean();


text:
Q: Flutter: Use choice function with PopupMenuButton to navigate to another page I am trying to navigate back to the login page from a 'Sign Out' button on a PopupMenuButton list located on the app's homepage. The SignOut button I'm trying to configure looks like this:

The simplified code looks like this:
@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: AppBar(
      title: Text('Home Page'),
      actions: <Widget>[
        PopupMenuButton<String>(
          onSelected: choiceAction,
          itemBuilder: (BuildContext context) {
            return MenuOptions.choices.map((String choice){
              return PopupMenuItem<String>(
                value: choice,
                child: Text(choice),
              );
            }).toList();

and  onSelected calls the following choiceAction:
  void choiceAction(String choice) {
    setState() {
      if (choice == MenuOptions.SignOut) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => LoginPage()),
        );
      }
    }
  }

The problem I'm facing is that it says context in Navigator.push is undefined. I'm not sure if I use the context defined in Widget build(BuildContext context) or itemBuilder: (BuildContext context) and I am lost on how I would fix the error that its undefined to make it use the definition where its being called in onSelected.

A: You have to send context to your function too. The only thing that you need to do is like this:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
  title: Text('Home Page'),
  actions: <Widget>[
    PopupMenuButton<String>(
      onSelected: (choice) => choiceAction(choice, context),
      itemBuilder: (BuildContext context) {
        return MenuOptions.choices.map((String choice){
          return PopupMenuItem<String>(
            value: choice,
            child: Text(choice),
          );
        }).toList();

and your choice action function should be like this:
void choiceAction(String choice, BuildContext context) {
setState() {
  if (choice == MenuOptions.SignOut) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => LoginPage()),
    );
    }
  }
}


text:
Q: code{font-weight:bold} not working in mobile-chrome Mobile-chrome is obstinately overriding my request for font-weight:bold.  I've tried everything reasonable, including increasing the "specificity" by adding id's and even the dreaded "!important" rule.  Nothing has worked.  I'm getting the desired effect on my desktop browsers, just not on my Android HTC One S9 using mobile-chrome.
Ideally I'd like a pure CSS solution since the html will be generated by another program, and it will be a little tedious to write a regex script to handle all the use cases, and I'd rather not have to add  tags everywhere when this ought to be such an easy CSS fix.  The code below is just a minimal sample of a much larger collection of webpages.
Some questions:

*

*Is there a pure CSS solution to this where I don't have to modify the html?

*Where can I find the default CSS stylesheet that mobile-chrome is using?  Even if I can't modify it, just seeing it could help me figure something out.

*I confess the Chrome DevTools interface confused me.  I connected my phone to my laptop, and indeed saw the undesired output, but I don't know what I should be looking for to actually debug the problem.  Any help is appreciated.
Pity that it takes 3 hours to put some text in bold.  Code and links below.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width">
    <title>CSS test</title>

    I want this bold.
<var>I don't want this bold.</var>

Here's the actual webpage
Here's a picture of the mobile view on chrome DevTools showing the problem

A: It turns out that this is simply a bug in Chrome for Android. See this question for another example.
If you need this to work, try using the "Chrome Beta" or "Chrome Dev" apps from the Play Store, as they does not have the issue.
Tested with the following code:

code {font-weight:bold; font-size:3em;}
code var {font-weight:normal;}
I want this bold.
<var>I don't want this bold.</var>


text:
Q: Smallest positive integer with a rule Find the smallest positive integer $N$ with the following property: of the three numbers $N,$ $N + 1,$ and $N + 2,$ one of them is divisible by $2^2,$ one of them is divisible by $3^2,$ one of them is divisible by $5^2,$ and one of them is divisible by $7^2.$
I think that the lcm of $2^2$, $3^2$, $5^2$, which is (2*3*5)=90, would be the answer because I feel like the smallest N would be if N is the one that all the numbers are divisible by.

A: This is an exercise in the Chinese remainder theorem.  One way to satisfy the requirement is to have $$N \equiv 0 \pmod {2^2\cdot 3^2}\\N+1 \equiv 0 \pmod {5^2}\\N+2\equiv 0 \pmod {7^2}$$
There are a number of other ways to assign the divisors.  The theorem says that once you find one solution there will be others at intervals of $2^2\cdot 3^2 \cdot 5^2 \cdot 7^2=168100$.  I don't think there is any easy way to figure out how to assign the divisors to get the smallest answer.  The fact that $7^2$ is just about twice $5^2$ is interesting, and I note that $N=48$ satisfies
$$N+1\equiv 0 \pmod {7^2}\\N+2\equiv 0 \pmod {5^2}$$
The solutions for $N$ are then $48+1225k$.  We now need to find $k$ so that $48+1225k$ is a multiple of $36$.  $48$ has a remainder of $12$ on division by $36$ and $1225$ has a remainder of $1$, so $k=24$ will work and $N=48+24\cdot 1225=29448$ is the smallest positive number that satisfies our requirement.


text:
Q: How can I get an MD5 hash in ColdFusion? I'm trying to get an MD5 hash of a value in ColdFusion. I tried this code using the Encrypt function1:
<cfscript>
val = 1117;
md5 = Encrypt(val, 0, "MD5", "Hex");
</cfscript>

But I get an error:

The MD5 algorithm is not supported by the Security Provider you have chosen.

How can I choose a different security provider?

1 Yes, I know that MD5 isn't an encryption algorithm, but the ColdFusion folks don't seem to know that because they list it as a supported algorithm for the Encrypt function.  Edit: I didn't see the built-in Hash function but I saw the fact that Encrypt lists md5 and sha as supposedly supported algorithms, so I thought (incorrectly it turns out) that this was just how you got a hash in CF.

A: Use CF built in "Hash" function. It takes the following format:
Hash(string [, algorithm [, encoding ]])

The following works:
<cfscript>
    val = 1117;
    md5 = Hash(val, "MD5");
</cfscript>

A: If you are wanting a hash shouldn't you try the hash function in ColdFusion? I end up using the SHA or SHA-256 algorithms, but the MD5 should work using that function.
hash(saltTheHash & trim(UserPassword), "SHA")

I would only use encrypt if you are wanting to decrypt sometime later. For things like passwords, you don't want to decrypt them so use the hash function instead.


text:
Q: Predicting the square root of a number using Machine Learning I am trying to create a program in python that uses machine learning to predict the square root of a number. I am listing what all I have done in my program:-

*

*created a csv file with numbers and their squares

*extracted the data from csv into suitable variables (X stores squares, y stores numbers)

*scaled the data using sklearn's, StandardScaler

*built the ANN with two hidden layers each of 6 units (no activation functions)

*compiled the ANN using SGD as the optimizer and mean squared error as the loss function

*trained the model. Loss was around 0.063

*tried predicting but the result is something else.

My actual code:-
import numpy as np
import tensorflow as tf
import pandas as pd

df = pd.read_csv('CSV/SQUARE-ROOT.csv')

X = df.iloc[:, 1].values
X = X.reshape(-1, 1)
y = df.iloc[:, 0].values
y = y.reshape(-1, 1)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size=0.2)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_test_sc = sc.fit_transform(X_test)
X_train_sc = sc.fit_transform(X_train)
sc1 = StandardScaler()
y_test_sc1 = sc1.fit_transform(y_test)
y_train_sc1 = sc1.fit_transform(y_train)

ann = tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units=6))
ann.add(tf.keras.layers.Dense(units=6))
ann.add(tf.keras.layers.Dense(units=1))

ann.compile(optimizer='SGD', loss=tf.keras.losses.MeanSquaredError())

ann.fit(x = X_train_sc, y = y_train_sc1, batch_size=5, epochs = 100)

print(sc.inverse_transform(ann.predict(sc.fit_transform([[144]]))))

OUTPUT:- array([[143.99747]], dtype=float32)
Shouldn't the output be 12? Why is it giving me the wrong result?
I am attaching the csv file I used to train my model as well: SQUARE-ROOT.csv

A: TL;DR: You really need those nonlinearities.
The reason behind it not working could be one (or a combination) of several causes, like bad input data range, flaws in your data, over/underfitting, etc.
However, in this specific case the model you build literally can't learn the function you're trying to approximate, because not having nonlinearities makes this a purely linear model, which can't accurately approximate nonlinear functions.
A Dense layer is implemented as follows:
x_res = activ_func(w*x + b)

where x is the layer input, w the weights, b the bias vector and activ_func the activation function (if one is defined).
Your model, then, mathematically becomes (I'm using indices 1 to 3 for the three Dense layers):
pred = w3 * (w2 * ( w1 * x + b1 ) + b2 ) + b3
     = w3*w2*w1*x + w3*w2*b1 + w3*b2 + b3

As you see, the resulting model is still linear.
Add activation functions and your mode becomes capable of learning nonlinear functions too. From there, experiment with the hyperparameters and see how the performance of your model changes.

A: The reason your code does not work is because you apply fit_transform to your test set, which is wrong. You can fix it by replacing fit_transform(test) to transform(test). Although I don't think StandardScaler is neccessary, please try this:
import numpy as np
import tensorflow as tf
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

N = 10000
X = np.arange(1, N).reshape(-1, 1)
y = np.sqrt(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size=0.2)

sc = StandardScaler()
X_train_sc = sc.fit_transform(X_train)
#X_test_sc = sc.fit_transform(X_test)      # wrong!!!
X_test_sc = sc.transform(X_test)

sc1 = StandardScaler()
y_train_sc1 = sc1.fit_transform(y_train)
#y_test_sc1 = sc1.fit_transform(y_test)   # wrong!!!
y_test_sc1 = sc1.transform(y_test)

ann = tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units=32, activation='relu'))    # you have 10000 data, maybe you need a little deeper network
ann.add(tf.keras.layers.Dense(units=32, activation='relu'))
ann.add(tf.keras.layers.Dense(units=32, activation='relu'))
ann.add(tf.keras.layers.Dense(units=1))

ann.compile(optimizer='SGD', loss='MSE')
ann.fit(x=X_train_sc, y=y_train_sc1, batch_size=32, epochs=100, validation_data=(X_test_sc, y_test_sc1))

#print(sc.inverse_transform(ann.predict(sc.fit_transform([[144]]))))  # wrong!!!
print(sc1.inverse_transform(ann.predict(sc.transform([[144]]))))


text:
Q: Delete all pages (thousands) except a few by their IDs I have over 20 thousand pages and need to delete all of them except very few.
Deleting them from the wp-admin page would take too long and a huge effort.
Is there a command I can run in PhpMyAdmin to do the job?
let's assume that I want to keep pages with ID (1,2,3) and delete the rest.
Thanks a lot.

A: You could do something like this
if (current_user_can('administrator')) {
    $pages = get_posts([
        'post_type' => 'page', // get only pages
        'posts_per_page' => -1, // get all
        'post_status' => array_keys(get_post_statuses()), // all post statuses (publish, draft, private etc...)
        'post__not_in' => [8,18,15,16,17] // list of ids you want to exclude (pages not for deletion)
    ]);

    foreach ($pages as $page) {
        wp_delete_post($page->ID); // delete page (moves to trash)
    }
}

If you want something quick without working with wp-cli.
I use this sometimes when I need to delete something quickly and once.
You can put this code in your, header.php (will probably get flamed for this XD), and enter your site, this code will only execute for administrator level users.
It will retrieve all pages you want to delete and delete them.
In post__not_in => [pages_ids_here] put all the pages ids you DO NOT want to delete.
wp_delete_post($page->ID) will do a soft delete, move it to trash, if you want to delete the pages permanently the use this wp_delete_post($page->ID, true) (not recommended straight away because you will not have a way to restore them, unless you did a DB backup).
Before you run this code, check what $pages contains to see if you got the correct pages, once you are sure that those are the correct pages you can delete them.
If you can do a DB backup in case something went wrong.
After all pages were deleted remove this code immediately to prevent unwated pages deletion in the future.

A: I found it easier to first empty trash, then trash the pages I want to keep, then via wp-cli I delete all pages permanently (skip the trash with --force flag)
https://developer.wordpress.org/cli/commands/post/delete/
then restore the few trashed pages.
hope that helps someone else.


text:
Q: Jmeter : How to test a website to render a page regardless of the content I have a requirement where the site only needs to respond to the user within certain seconds, regardless of the contents.
Now there is a option in Jmeter in HTTP Proxy Server -> URL Patterns to exclude and then to start recording.
Here I can specify gif, css or other content to ignore. However before starting the recording I have to be aware of what are the various contents that are going to be there.
Is there any specific parameter to pass to Jmeter or any other tool which takes care about loading the page only and I can assert the response code of that page and no the other contents of the page are recorded.
Thanks.

A: *

*Use the standard HTTP Request sampler with DISABLED (not checked) option Retrieve All Embedded Resources from HTML Files (set via sampler's control panel):

"It also lets you control whether or not JMeter parses HTML files for
  images and other embedded resources and sends HTTP requests to
  retrieve them."

NOTE: You may also define the same setting via HTTP Request Defaults.
NOTE: See also "Response size calculation" in the same HTTP Request article.

*Add assertions to your http samplers:

*

*Duration Assertion: to tests if response was received within a defined amount of time;

*Response Assertion: to ensure that request was successfull,
e.g.

Response Field to Test = Response Code
Pattern Matching Rules = Equals
Patterns to Test = 200

A: You want to run test that would ignore resources after certain number of seconds?
I don't understand, what are you trying to accomplish by doing that?
Users will still receive those resources when they request your url, so your tests wont be accurate.
I don't mean any disrespect, but is it possible that you misunderstood the requirements?
I assume that the requirement is to load all the resources in certain number of seconds, not to cut off the ones that fail to fit in that time?


text:
Q: Pascal's Triangle + Fibonacci Numbers How can I draw this picture in LaTeX, with those skew lines? Any hints?

A: This isn't precisely what the OP requests, I think, but it's similar...
\documentclass{book}
\usepackage{mathtools}
\usepackage{cancel}

\begin{document}
\LARGE \boldmath
% horizontal loop
\foreach \x in {0,...,6} {%
% vertical loop

\foreach \y in {0,...,\x} {%
$\cancel{\binom{\x}{\y}}$
}

}

\end{document}

A: \documentclass{article}
\usepackage{cancel,mathtools,stackengine}
\stackMath
\def\CBN#1#2{%
  \cancel{\addstackgap[6pt]{\kern6pt\displaystyle\binom{#1}{#2}\kern6pt}}%
  }
\def\BN#1#2{%
  \addstackgap[6pt]{\kern6pt\displaystyle\binom{#1}{#2}\kern6pt}%
  }
\begin{document}
\[
\def\stackalignment{l}
\setstackgap{S}{-5.2pt}
\setstackEOL{\cr}
\Shortstack{
\CBN{0}{0}\cr
\CBN{1}{0}\CBN{1}{1}\cr
\CBN{2}{0}\CBN{2}{1}\CBN{2}{2}\cr
\CBN{3}{0}\CBN{3}{1}\CBN{3}{2}\CBN{3}{3}\cr
\CBN{4}{0}\CBN{4}{1}\CBN{4}{2}\BN{4}{3}\BN{4}{4}\cr
\CBN{5}{0}\CBN{5}{1}\BN{5}{2}\BN{5}{3}\BN{5}{4}\BN{5}{5}\cr
\CBN{6}{0}\BN{6}{1}\BN{6}{2}\BN{6}{3}\BN{6}{4}\BN{6}{5}\BN{6}{6}
}
\]
\end{document}

A: EDIT: changed \ifthenelse to \ifnum as suggested by percusse and Heiko.
\documentclass[tikz,border=2mm]{standalone}
\begin{document}
    \begin{tikzpicture}
        \foreach \n in {0,...,6} {
            \foreach \k in {0,...,\n} {
                \node (\n\k) at (\k,-\n) {${\n \choose \k}$};
                \pgfmathtruncatemacro{\x}{(\n+1)/2}
                \pgfmathtruncatemacro{\y}{\n/2}
                \ifnum\k=0 \draw (\n\k.south west) -- (\x\y.north east);\fi
            }
        }
    \end{tikzpicture}
\end{document}

EDIT 2: Eliminated if statement as suggested by Misch:
\documentclass[tikz,border=2mm]{standalone}
\begin{document}
    \begin{tikzpicture}
        \foreach \n in {0,...,6} {
            \foreach \k in {0,...,\n} {
                \node (\n\k) at (\k,-\n) {${\n \choose \k}$};
            }
            \pgfmathtruncatemacro{\x}{(\n+1)/2}
            \pgfmathtruncatemacro{\y}{\n/2}
            \draw (\n0.south west) -- (\x\y.north east);
        }
    \end{tikzpicture}
\end{document}


text:
Q: sql filtering 2 or more     voorletters, naam, geslacht, boete
    B   Niewenburg  V   25.00
    B   Niewenburg  V   140.00
    D   Moerman V   35.00
    D   Moerman V   50.00
    DD  Cools   V   75.00
    DD  Cools   V   85.00
    E   Bakker, de  M   30.00
    E   Bakker, de  M   35.00
    E   Bakker, de  M   90.00
    E   Bakker, de  M   95.00
    IP  Baalen, van V   140.00
    R   Permentier  M   100.00

And I have this as sql statement
SELECT VOORLETTERS, NAAM, GESLACHT, BEDRAG
FROM SPELER S
RIGHT JOIN BOETE B ON B.SPELERSNR = S.SPELERSNR
LEFT joiN BESTUURSLID BL ON BL.SPELERSNR = S.SPELERSNR
GROUP BY VOORLETTERS, NAAM, GESLACHT, BEDRAG

how can i make it that I only see people with 2 or more 'boete'?
so that I get this as an answer
voorletters, naam, geslacht, boete
B   Niewenburg  V   25.00
B   Niewenburg  V   140.00
D   Moerman V   35.00
D   Moerman V   50.00
DD  Cools   V   75.00
DD  Cools   V   85.00
E   Bakker, de  M   30.00
E   Bakker, de  M   35.00
E   Bakker, de  M   90.00
E   Bakker, de  M   95.00

A: use a subselect for get the people with two or more rows  in speler
SELECT VOORLETTERS, NAAM, GESLACHT, BEDRAG
FROM SPELER S
RIGHT JOIN BOETE B ON B.SPELERSNR = S.SPELERSNR
LEFT joiN BESTUURSLID BL ON BL.SPELERSNR = S.SPELERSNR
where s.naam in (select naam from (select naam, count(*) from speler group by name ) )
GROUP BY VOORLETTERS, NAAM, GESLACHT, BEDRAG


text:
Q: react native json object issue I want to fetch my json data but when I fetch my json data it return object format. How can I solve

async fetchAllPass() {
        try {
            let response = await fetch('http://10.12.12.84:8080/uncludes/select.php');
            let responseJson = await response.json();
            alert(responseJson);
            this.setState({
                allData: responseJson
            })
        } catch (error) {
            console.error(error);
        }

screenShot

A: Try alert(JSON.stringify(responseJson))


text:
Q: styling a context menu I noticed some context menus in various tutorials on the web look different than mine, i.e. there a title with an arrow in a circle at the top.  Mine is just a square box with items.  Is this just a newer version of the context menu, or is there a way to style the menu?
I'd like to center the items, set a backcolor, etc.

A: ContextMenu has several methods like setHeaderTitle()(for adding a title, but you have setHeaderView() for more complex stuff) so you can customize the ContextMenu in the method onCreateContextMenu().


text:
Q: Как мне прилепить к каждому пункту li РАЗНЫЕ png картинки вместо маркеров? Помогите пожалуйста сверстать меню, все способы уже перебрал по-моему однако картинки не выводятся. Итак... Сверстал макет с помощью одного сервиса который из psd как-то ( плохо конечно) верстает макеты в HTML. Все каартинки все иконки он автоматом порезал в формат png. Меню сайта сервис обернул в тег в котором тег  без ссылок просто текст. Мне и сие нужно было если честно - терепь можно не морочиться с подключением шрифта, размерами блоков и т.п. Стал приводить меню моего шаблончика в порядок вот код:

.left-bar {
    float: left;
    width: 178px;
    background: #375e89;
}

.lb-block {
    margin: 0;
    padding: 20px;
}

.lb-block  ul {
    clear: both;
    margin: 0 0 0 15px;
    padding: 0px;
}

.lb-block  ul li {
    margin: 0 0 5px 0;
    padding: 0 0 5px 0;
}

.lb-block  ul li a {
    font-size: 13px;
    color: #c3d6ed;
}

.lb-block  ul li a:hover {
    color: #fff;
}

Моя страница

Новости

Сообщения

Друзья

Сообщества

Фотографии

Музыка

Видео

Клипы

Игры

VK Pay

Работа

Товары

Закладки

Коронавирус

Как мне прилепить к каждому пункту li РАЗНЫЕ png картинки вместо маркеров? В курсе что есть давно иконки font awesome, svs и т.п. Но мне нужно сейчас временно именно так, поскольку в последствии буду рисовать свои иконки на подобии FA.

A:

.left-bar {
    float: left;
    width: 178px;
    background: #375e89;
}

.lb-block {
    margin: 0;
    padding: 20px;
}

.lb-block  ul {
    clear: both;
    margin: 0 0 0 15px;
    padding: 0px;
}

.lb-block  ul li {
    margin: 0 0 5px 0;
    padding: 0 0 5px 0;
    list-style: none;
}

.lb-block  ul li a {
    font-size: 13px;
    color: #c3d6ed;
}

.lb-block  ul li a:hover {
    color: #fff;
}
  .image_1{
width: 10%;
padding-right: 10px;
position: relative;
top: 2px;}

Моя страница

Новости

Сообщения

Друзья

Сообщества

URL только свои подставьте


text:
Q: C++11 Shared Ptr, share the same reference counter Is it possible to have 2 different objects that share same reference counter?
Says I have
shared_ptr<Foo> myFoo;
shared_ptr<Bar> myBar;

I want both objects alive until there is one reference to Foo or to Bar (so maybe no one is referencing Bar, but since Foo is referenced both will not be deleted).

A: Put them in a struct and have the shared_ptr own that struct.
struct FooBar {
    Foo f;
    Bar b;
};
shared_ptr<FooBar> myFooBar;

A: OK perfect I found the answer:
http://www.codesynthesis.com/~boris/blog/2012/04/25/shared-ptr-aliasing-constructor/
The aliasing constructor! (code taken from the link)
struct data {...};

struct object
{
  data data_;
};

void f ()
{
  shared_ptr<object> o (new object); // use_count == 1
  shared_ptr<data> d (o, &o->data_); // use_count == 2

  o.reset (); // use_count == 1

  // When d goes out of scope, object is deleted.
}


text:
Q: C# DataGrid sorting by absolute value on dynamically created columns I have DataGrid and columns are added dynamically because it can change based on user input.
I setup grid by :
this.grid.DataContext =  d;
where d is an instance of System.Data.DataTable().DefaultView
Columns are mostly in integers and I want to sort them by absolute values.   How do I do that?
In the past, I used "SortMemberPath" for static grid that has objects as underlying but I am not sure how I can do this on dynamically created one that contains bunch of numbers as columns.


text:
Q: Console log statements on React event handler causes synthetic event warnings Code Sandbox here: https://codesandbox.io/s/0olpzq7n3n
It's some pretty straight forward code:
const Form = ({ form, updateForm }) => {
  const handleChange = (event, value) => {
    console.log(event, value);
    console.log(event.target.name, event.target.value);

    const newForm = { ...form, ...{ [event.target.name]: event.target.value } };
    updateForm(newForm);
  };

  return (
    <form>
      <input
        name="value1"
        value={form.value1}
        onChange={event => handleChange(event)}
      />
    </form>
  );
};

const Form1 = connect(
  state => ({ form: state.form1 }),
  dispatch => ({ updateForm: newForm => dispatch(updateFormOne(newForm)) })
)(Form);

function Home() {
  return (

 Welcome to the Home route

      <Form1 />

  );
}

If you edit the form input in this scenario it gives these warnings:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `nativeEvent` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See (shortend URL that StackOverflow doesn't like).

If I remove those console log statements, the warning disappears.
What's happening here?

A: You're trying to console.log() an asynchronous synthetic event that is removed by the time the callback is executed. If you wish to to persist the event, then use event.persist().
Using event.persist(), you can see all of the event properties:
ispatchConfig: Object
_targetInst: FiberNode
nativeEvent: InputEvent
type: "change"
target: <input name="value1" value="this is form a1"></input>
currentTarget: null
eventPhase: 3
bubbles: true
cancelable: false
timeStamp: 2926.915000000008
defaultPrevented: false
isTrusted: true
isDefaultPrevented: function () {}
isPropagationStopped: function () {}
_dispatchListeners: null
_dispatchInstances: null
isPersistent: function () {}
<constructor>: "SyntheticEvent"

More information about synthetic events can be found here and here.
However, if you already know what you want from the event, then you can destructure its properties like so:
const handleChange = ({ target: { value, name } }) => {
    console.log(name, value);

    const newForm = { ...form, [name]: value };
    updateForm(newForm);
  };


text: Q: Rectangle intersections I'm trying to make a program using WindowsForms with visualC++ to move one rectangle (CJ) through keyboard (using rectangle structures) and intersect it with another rectangle (C1) from the right, left, botton or top. So that when that happens it will automatically move to the same direction I was holding the key to move it, and until it passes all the rectangles (C1) that were on the way. Any thoughts on that?


text:
Q: How to get data correctly from graphql I'm working on Nestjs project using graphql I want to display the objected nested in my response of graphql as you see below, so I have object comes from socket look like this
socket.emit('sendSettlement', {
        bReconcileError: true,
        batchNumber: 112233,
        btransfered: true,
        countryCode: 112233,
        currencyCode: 12233,
        merchantID: 'd2s13g',
        nSettlementAmount: 1122332,
        onlineMessageMACerror: true,
        reconciliationAdviceRRN: 1122333,
        reconciliationApprovalCode: '1122fdsf',
        settledTransactions: [
          {
            appName: '5411fdsb',
            cardInputMethod: '6s51b',
            cardPAN_PCI: '3f1dbs3df1sss',
            networkName: '5d4dsf',
            onlineApprovalCode: 11651,
            onlineRetrievalReferenceNumber: 6516161,
            transactionAmount: 156161,
            transactionDate: 'sd3f1g3',
            transactionTime: '2f4gB24G',
            transacttransactionTypeionTime: 'frqd56r1f',
          },
        ],

        settlementAmount: 'ds4f1vd1fv',
        settlementDate: '3dfv1',
        settlementTime: 'sd3f1vsdf',
        terminalID: 'sdRGRD',
        traceNumber: 12,
        uniqueID: 's56d1rvdr',
      });

I saved this to mongoDb correctly but when I want to get this data using graphql I got this Error
{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Query.findAllSettlement.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "findAllSettlement"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR"
      }
    }
  ],
  "data": null
}

and the console shows this
  {
    _id: new ObjectId("62aba86b614eef23deb46cfa"),
    bReconcileError: true,
    batchNumber: 112233,
    btransfered: true,
    countryCode: 112233,
    currencyCode: 12233,
    merchantID: 'd2s13g',
    nSettlementAmount: 1122332,
    onlineMessageMACerror: true,
    reconciliationAdviceRRN: 1122333,
    reconciliationApprovalCode: '1122fdsf',
    settledTransactions: [ [Object] ],
    settlementAmount: 'ds4f1vd1fv',
    settlementDate: '3dfv1',
    settlementTime: 'sd3f1vsdf',
    terminalID: 'sdRGRD',
    traceNumber: 12,
    uniqueID: 's56d1rvdr',
    __v: 0
  }

for who wants more info about my code : this is my Schema
export const SettlementSchema = new mongoose.Schema({
  bReconcileError: { type: Boolean, required: false },
  batchNumber: { type: Number, required: false },
  btransfered: { type: Boolean, required: false },
  countryCode: { type: Number, required: false },
  currencyCode: { type: Number, required: false },
  merchantID: { type: String, required: false },
  nSettlementAmount: { type: Number, required: false },
  onlineMessageMACerror: { type: Boolean, required: false },
  reconciliationAdviceRRN: { type: Number, required: false },
  reconciliationApprovalCode: { type: String, required: false },
  settledTransactions: [
    {
      appName: String,
      cardInputMethod: String,
      cardPAN_PCI: String,
      networkName: String,
      onlineApprovalCode: Number,
      onlineRetrievalReferenceNumber: Number,
      transactionAmount: Number,
      transactionDate: String,
      transactionTime: String,
      transacttransactionTypeionTime: String,
    },
  ],
  settlementAmount: { type: String, required: false },
  settlementDate: { type: String, required: false },
  settlementTime: { type: String, required: false },
  terminalID: { type: String, required: false },
  traceNumber: { type: Number, required: false },
  uniqueID: { type: String, required: false },
});

this is my Object Type
@ObjectType()
export class SettledTransactionsType {
  @Field()
  appName: string;
  @Field()
  cardInputMethod: string;
  @Field()
  cardPAN_PCI: string;
  @Field()
  networkName: string;
  @Field()
  onlineApprovalCode: number;
  @Field()
  onlineRetrievalReferenceNumber: number;
  @Field()
  transactionAmount: number;
  @Field()
  transactionDate: string;
  @Field()
  transactionTime: string;
  @Field()
  transactionType: string;
}

@ObjectType()
export class Settlement {
  @Field()
  bReconcileError: boolean;
  @Field()
  batchNumber: number;
  @Field()
  btransfered: boolean;
  @Field()
  countryCode: number;
  @Field()
  currencyCode: number;
  @Field()
  merchantID: string;
  @Field()
  nSettlementAmount: number;
  @Field()
  onlineMessageMACerror: boolean;
  @Field()
  reconciliationAdviceRRN: number;
  @Field()
  reconciliationApprovalCode: string;
  @Field()
  settledTransactions: SettledTransactionsType;
  @Field()
  settlementAmount: string;
  @Field()
  settlementDate: string;
  @Field()
  settlementTime: string;
  @Field()
  terminalID: string;
  @Field()
  traceNumber: number;
  @Field()
  uniqueID: string;
}