How do I install Java? I can't figure it out

Question: I want to play Java games on my Ubuntu 16.04 LTS Laptop. I have looked at many tutorials across the web and keep getting confused and hitting error messages. Please help. (Former Windows User)
Comment: Please edit your question to clearly explain exactly what you have tried and the complete, exact error messages that resulted. The details matter a lot.
Comment: E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
Comment: I can't do anything because of this message
Comment: Next time, look just a little harder: http://askubuntu.com/questions/15433/unable-to-lock-the-administration-directory-var-lib-dpkg-is-another-process
Answer: You can install java from the commandline with:
$ sudo apt install openjdk-8-jdk

You can get to a terminal commandline by hitting this keyboard shortcut: Alt+Ctrl+T
The $ you see in the commanline is the prompt you see when your enter the terminal mode.  Type in the text the follows and press ENTER.
Answer: If you would like to use Oracle's Java, you can install it with a PPA. First open a terminal by using Ctrl+Alt+T and run the following commands:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

The first command adds the PPA so you are able to download Java. The second command 'refreshes' or 're-syncs' the avaliable packages. The last one installs Oracle's Java, version 8.
After it has installed, you can check by running:
java -version

Comment: Please use the `{}` button in the editor for multiline terminal commands, and surround keys with `` and ``.
Answer: I prefer to install Oracle's Java. Here are the steps:
Open a terminal with CTRL + ALT + T, or just type terminal in dash.
Then start typing . . .
1) First add the PPA
sudo add-apt-repository ppa:webupd8team/java

2) Update your repositories
sudo apt-get update

3) Install Java version of your preference
sudo apt install oracle-java8-installer

If you prefer to install another Java version, just change "8" to your desired version, for example, if you want to install Java 6 just type this: sudo apt install oracle-java6-installer
4) Mark Java version as default (if you installed Java 8)
sudo apt install oracle-java8-set-default

In this link you can find more information about:
http://tipsonubuntu.com/2016/07/31/install-oracle-java-8-9-ubuntu-16-04-linux-mint-18/
Comment: After doing your third step, a EULA came up, and when I click OK nothing happens
Comment: You have to press Tab until it highlights the OK, then press Enter.


Showing a function $f$ cannot be surjective

Question: Good day all!
So I have a question about the problem:
Let $E$ be a set, and $f$ be a mapping from $E$ to $P(E)$.
Consider a set $A$ such that $x$ is in $E$ but $x$ in NOT in $f(x)$
Show $f$ cannot be surjective.
My question is: How is this?
I see that if $x$ is in $A$ then $x$ is not in $f(x)$ which means $x$ is not in $P(E)$.
How is $x$ in $E$ but $x$ not in $P(E)$?
Is my understanding flawed?
Comment: $x$ is an element of $E$, not a subset of $E$, so in general, you would not expect it to be in $P(E)$, whose elements are subsets of $E$. (There are exceptions, where a set contains some subsets of itself as elements. But in general you would not expect it to happen.)
Comment: ok, so to prove this do I just show that A is not contained in P(E)?
Answer: $A=\{x\in E,\, x\notin f(x)\}\in P(E)$. So if $f$ is surjective, then there exists $y\in E$ such that $f(y)=A$. Try to show that this leads to a contradiction.
See also: https://en.wikipedia.org/wiki/Cantor's_theorem
Comment: I almost see what you are saying, but how is f(y)=A?
Comment: By definition of surjectivity, _if_ $f$ is surjective, such a $y$ exists.
Comment: So this already shows the contradiction right? Since f(y)=A but A is the set of all elements in E such that y is not an element of f(y)?
Comment: The contradiction comes from the fact that if $y\in A$, then $y\notin f(y)$, by definition of $A$. But $f(y)=A$. So we have $y\in A\implies y\notin A$. Similarly, $y\notin A\implies y\in A$...
Comment: ahh. Ok, thanks. Logically it makes sense. Its just the notation that throws me off since im new to most of it. Thanks for your help!
Answer: Ahh, this is Cantors Theorem.
Listed here:
Non-existence of a Surjective Function from a Set to Its Subsets (Cantor's theorem)
Thanks for the help everyone!
Answer: If I understand your question correctly, you ask how $x\in E$ and $x\notin P(E)$ can be true at the same time.
Well, that is easy to see with an example:
Be $E=\{1,2,\}$. Then $P(E)=\{\emptyset,\{1\},\{2\},\{1,2\}\}$.
Clearly in this case none of the elements of $E$ is in $P(E)$. Note that $1\ne\{1\}$.
However note that in other cases, elements of $E$ can be elements of $P(E)$. For example, consider $E=\{\emptyset\}$, then $P(E)=\{\emptyset,\{\emptyset\}\}$. Here the only element of $E$ ($\emptyset$) is also member of $P(E)$.


Add item to Owl Carousel in the first postion

Question: So far have it working where I can dynamically add a slide into an owl carousel. But I'm not sure how to get it to be placed at the beginning? I've combed through the docs a bit, and it's not really clear to me how to get to be the first slide, rather than the last.
Here's what I have so far:
JS
  var img = '

';
    $("#carousel").data('owlCarousel').addItem(img);

I would think that this would be pretty easy, but I'm not sure what the method is to get it to be in the first position.
Answer: Ok, I just figured it out.
Needs to be this:
JS
  var img = '

';
  $("#carousel").data('owlCarousel').addItem(img,[0]);

I dug through it a bit more and realized that addItem will add a slide on a given position. So by passing a value to it, would insert the slide at a specific position in the carousel. One other issue I had was I was using [1] when testing, which was inserting the slide in the second position. By setting it to [0] makes inserts the slide at the very beginning.
Answer: @ultraloveninja
There may be some weird things after added.
I use below:
var img = '

';
$("#carousel").data('owlCarousel').trigger('add.owl.carousel', [$(img), 0])
        .trigger('refresh.owl.carousel')
        .trigger('to.owl.carousel', [0, 500]);

Answer: $(document).ready(function () {
var owl = $(".owl-carousel").owlCarousel({
loop: true,
margin: 10,
responsiveClass: true,
autoplay: true,
responsive: {
0: {
items: 1,
nav: true
},
600: {
items: 3,
nav: false
},
1000: {
items: 5,
nav: true,
loop: false
}
},
attachable: function () {
            },
            triggerable: function (data) {
                this.data = data + 'jfeoajfeo'
                console.log('replace')
                console.log(data)
            }

        });

        var img = '

';
        owl.trigger('add.owl.carousel', img)

    });

Comment: Please format your code because it is very hard to read it in this form. It is also recommended to describe your answer alongside the code so the OP can figure it out how you achieved the result


How to update value of useState in call back function

Question: I have a function named Login, that gets initiated on login button click. When user gets authenticated setUser sould get udpated with the email id of user, but it is not updating it and giving the previous value which is "Logged in User" in session storage. I tried useEffect but it said React Hook "useEffect" cannot be called inside a callback.
function Login() {
    const [userIdLogin, setuserIdLogin] = useState("");
    const [passwordLogin, setpasswordLogin] = useState("");
    const [user, setuser] = useState("");

    let navigate = useNavigate();

    const LoginUser = (e) => {
        e.preventDefault();

        if (!userIdLogin || !passwordLogin) {
            setErrMessage("Error.")
        } else {
            Axios.post("http://localhost:4000/api/login", {
                userID_Login: userIdLogin,
                password_Login: passwordLogin
            }).then((res) => {
                if (!res.data.recordsets) {
                    alert("Error")
                } else {
                    setuser(res.data.recordset[0].Email);
                    sessionStorage.setItem('Email', user)

                    console.log(res)
                    navigate("/");
                }
            });
        };
    };

    return (

                <form onSubmit={LoginUser}>
                    <input type="text" name="userid" placeholder="User Id" value={userIdLogin} onChange={(e) => {
                        setuserIdLogin(e.target.value);
                    }} />

                    <input type="password" name="password" placeholder="Password" value={passwordLogin} onChange={(e) => {
                        setpasswordLogin(e.target.value);
                    }} />

                    <input type="submit" name="" value="Login" />  {errMessage}
                </form>

    );
}

export default Login;

Answer: It's not updating the 'user' state because when state is updated in React, it doesn't immediately take into effect. Instead, it continues executing your code as if nothing happened, and when it's done executing, your component re-renders with the updated state.
The best way to get around this is with useEffect. It takes an array of dependencies, and will listen to any changes to those dependencies, and only execute if one of the dependencies changes from the previous render.
function Login() {
    const [userIdLogin, setuserIdLogin] = useState("");
    const [passwordLogin, setpasswordLogin] = useState("");
    const [user, setuser] = useState("");

    let navigate = useNavigate();

    const LoginUser = (e) => {
        e.preventDefault();

        if (!userIdLogin || !passwordLogin) {
            setErrMessage("Error.")
        } else {
            Axios.post("http://localhost:4000/api/login", {
                userID_Login: userIdLogin,
                password_Login: passwordLogin
            }).then((res) => {
                if (!res.data.recordsets) {
                    alert("Error")
                } else {
                    setuser(res.data.recordset[0].Email); // User is updating
                }
            });
        };
    };

    useEffect(() => {
        sessionStorage.setItem('Email', user)
        console.log(res)
        navigate("/");
    }, [user]) // Dependency array, listening for user changes

    return (

                <form onSubmit={LoginUser}>
                    <input type="text" name="userid" placeholder="User Id" value={userIdLogin} onChange={(e) => {
                        setuserIdLogin(e.target.value);
                    }} />

                    <input type="password" name="password" placeholder="Password" value={passwordLogin} onChange={(e) => {
                        setpasswordLogin(e.target.value);
                    }} />

                    <input type="submit" name="" value="Login" />  {errMessage}
                </form>

    );
}

export default Login;


Unknown bean entity class - error with Glassfish and NetBeans

Question: I'm using GlassFish 3.1.1. and NetBeans 6.9.1.
In NetBeans, I created web application and generated an entity class. Only thing I added is the @GeneratedValue annotation. Here is the code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities.worker;

import java.io.Serializable;
import java.util.Date;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 *
 * @author pzielins
 */
@Entity
@Table(name = "cdrconfig", catalog = "cdrworker_db", schema = "public")
@NamedQueries({
    @NamedQuery(name = "CdrConfig.findAll", query = "SELECT c FROM CdrConfig c"),
    @NamedQuery(name = "CdrConfig.findById", query = "SELECT c FROM CdrConfig c WHERE c.id = :id"),
    @NamedQuery(name = "CdrConfig.findByCdrpath", query = "SELECT c FROM CdrConfig c WHERE c.cdrpath = :cdrpath"),
    @NamedQuery(name = "CdrConfig.findByWorkerinterval", query = "SELECT c FROM CdrConfig c WHERE c.workerinterval = :workerinterval"),
    @NamedQuery(name = "CdrConfig.findByMakebackup", query = "SELECT c FROM CdrConfig c WHERE c.makebackup = :makebackup"),
    @NamedQuery(name = "CdrConfig.findByBackuppath", query = "SELECT c FROM CdrConfig c WHERE c.backuppath = :backuppath"),
    @NamedQuery(name = "CdrConfig.findByLastsyncdate", query = "SELECT c FROM CdrConfig c WHERE c.lastsyncdate = :lastsyncdate"),
    @NamedQuery(name = "CdrConfig.findByWaslastsyncmanual", query = "SELECT c FROM CdrConfig c WHERE c.waslastsyncmanual = :waslastsyncmanual")})
public class CdrConfig implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id", nullable = false)
    private Integer id;
    @Column(name = "cdrpath", length = 10485760)
    private String cdrpath;
    @Column(name = "workerinterval")
    private Integer workerinterval;
    @Column(name = "makebackup")
    private Boolean makebackup;
    @Column(name = "backuppath", length = 10485760)
    private String backuppath;
    @Column(name = "lastsyncdate")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastsyncdate;
    @Column(name = "waslastsyncmanual")
    private Boolean waslastsyncmanual;

    public CdrConfig() {
    }

    public CdrConfig(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCdrpath() {
        return cdrpath;
    }

    public void setCdrpath(String cdrpath) {
        this.cdrpath = cdrpath;
    }

    public Integer getWorkerinterval() {
        return workerinterval;
    }

    public void setWorkerinterval(Integer workerinterval) {
        this.workerinterval = workerinterval;
    }

    public Boolean getMakebackup() {
        return makebackup;
    }

    public void setMakebackup(Boolean makebackup) {
        this.makebackup = makebackup;
    }

    public String getBackuppath() {
        return backuppath;
    }

    public void setBackuppath(String backuppath) {
        this.backuppath = backuppath;
    }

    public Date getLastsyncdate() {
        return lastsyncdate;
    }

    public void setLastsyncdate(Date lastsyncdate) {
        this.lastsyncdate = lastsyncdate;
    }

    public Boolean getWaslastsyncmanual() {
        return waslastsyncmanual;
    }

    public void setWaslastsyncmanual(Boolean waslastsyncmanual) {
        this.waslastsyncmanual = waslastsyncmanual;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.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 CdrConfig)) {
            return false;
        }
        CdrConfig other = (CdrConfig) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entities.worker.CdrConfig[id=" + id + "]";
    }

}

Then, I've generated a JPAController class for Entity class. Here is the code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jpa.worker;

import entities.worker.CdrConfig;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpa.exceptions.NonexistentEntityException;
import jpa.exceptions.PreexistingEntityException;

/**
 *
 * @author pzielins
 */
public class CdrConfigJpaController {

    public CdrConfigJpaController() {
        emf = Persistence.createEntityManagerFactory("CDRFileWorkerPU");
    }
    private EntityManagerFactory emf = null;

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

    public void create(CdrConfig cdrConfig) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(cdrConfig);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCdrConfig(cdrConfig.getId()) != null) {
                throw new PreexistingEntityException("CdrConfig " + cdrConfig + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(CdrConfig cdrConfig) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            cdrConfig = em.merge(cdrConfig);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = cdrConfig.getId();
                if (findCdrConfig(id) == null) {
                    throw new NonexistentEntityException("The cdrConfig 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();
            CdrConfig cdrConfig;
            try {
                cdrConfig = em.getReference(CdrConfig.class, id);
                cdrConfig.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cdrConfig with id " + id + " no longer exists.", enfe);
            }
            em.remove(cdrConfig);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<CdrConfig> findCdrConfigEntities() {
        return findCdrConfigEntities(true, -1, -1);
    }

    public List<CdrConfig> findCdrConfigEntities(int maxResults, int firstResult) {
        return findCdrConfigEntities(false, maxResults, firstResult);
    }

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

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

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

}

Because my application needs to work with two databases, I've edited generated by NetBeans Persistence Unit and now I have sth like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="CDRFileWorkerPU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/cdrworkerdb</jta-data-source>
    <class>entities.config.CdrConfig</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
  <persistence-unit name="CDRDataStorePU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/cdrdb</jta-data-source>
    <class>entities.cdr.CallRecord</class>
    <class>entities.cdr.RecordColumn</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Everything is fine until now, but when I try to use this method in my JSF Managed Bean:
public void test() {
        try {
            CdrConfig cfg = new CdrConfig();
            cfg.setBackuppath("foo");
            CdrConfigJpaController cjc = new CdrConfigJpaController();
            cjc.create(cfg);
            Record rec = new Record();
            RecordJpaController rjc = new RecordJpaController();
            rjc.create(rec);
            RecordColumn col = new RecordColumn();
            col.setColumnname("foo1");
            col.setRecord(rec);
            RecordColumnJpaController rcjc = new RecordColumnJpaController();
            rcjc.create(col);
        } catch (Exception ex) {
            Logger.getLogger(FileWorkerBackup.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

I get following error:
java.lang.IllegalArgumentException: Unknown entity bean class: class entities.worker.CdrConfig, please verify that this class has been marked with the @Entity annotation.
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:576)
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:460)
        at jpa.worker.CdrConfigJpaController.findCdrConfig(CdrConfigJpaController.java:125)
        at jpa.worker.CdrConfigJpaController.create(CdrConfigJpaController.java:43)
        at web.FileWorkerBackup.test(FileWorkerBackup.java:52)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at...

From Google I know, that it is sometimes helpful to tick "Include all Entity classes in module" in Persistence Unit editor, but then it gives me error about some cross-db references between tables (I'm sure that I'm not trying to do this).
I also found on Google, that restarting glassfish helps (because of unclosed persistence sessions), but it doesn't help as well.
Please, point me to the right direction.
Answer: Maybe this line in the xml
<class>entities.config.CdrConfig</class>

should be
<class>entities.worker.CdrConfig</class>

Comment: Thanks mate! Dunno where did wrong package name came from, but thanks a lot.


Can't figure out Python scraping code issue

Question: I'm using python/bs to scrape this site: https://www.hhs.gov/hipaa/for-professionals/compliance-enforcement/agreements/index.html
There's two annoying issues that I can't figure out:

It always includes 'Resolution Agreements,/hipaa/for-professionals/compliance-enforcement/agreements/index.html' as the first entry of the CSV.

The actual first entry of the site is never included. In this case, "HHS' Office for Civil Rights Settles Malicious Insider Cybersecurity Investigation for $4.75 Million"

Any suggestions?
import requests
from bs4 import BeautifulSoup
import csv

# URL of the page to scrape
url = "https://www.hhs.gov/hipaa/for-professionals/compliance-enforcement/agreements/index.html"

# Send a GET request to the URL
response = requests.get(url)

# Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')

# Find all  tags containing the links
links = soup.find_all('a')

# Create and open a CSV file in write mode
with open('hipaa_links.csv', mode='w', newline='', encoding='utf-8') as file:
    # Create a CSV writer object
    writer = csv.writer(file)

    # Write the header row
    writer.writerow(['Title', 'URL'])

    # Iterate over each link
    for link in links:
        # Extract link URL
        link_url = link.get('href')

        # Extract link title
        link_title = link.text.strip()

        # Check if the link is related to "Resolution Agreements" or subsequent ones and if link text and URL are not empty
        if link_url and link_title and "/hipaa/for-professionals/compliance-enforcement/agreements/" in link_url:
            # Write the link title and URL to the CSV file
            writer.writerow([link_title, link_url])

print("Data has been written to hipaa_links.csv")

Answer: The 'Resolution Agreements' link is from the left side-bar/nav, and the first link (the HHS Office .. settles...) goes to an /about/news/ page.
I'd suggest you filter your search down to the innermost l-content div, and remove the filter on link destination:
content_divs = soup.find_all('div', class_='l-content')
content_div = content_divs[-1]
links = content_div.find_all('a')
...
        if link_url and link_title:

Answer:
Issue is that you are not that specific with your selection, try to focus the  you really like to scrape - Using css selectors you can stil filter your results. Followoing will just select the  from the link list, thats href meets your statement:
soup.select('section.usa-section ul a[href*="hipaa/for-professionals/compliance-enforcement/agreements"]')

Issue here is that the first link do not fit your statement:
https://www.hhs.gov/about/news/2024/02/06/hhs-office-civil-rights-settles-malicious-insider-cybersecurity-investigation.html
Do not contain:
"/hipaa/for-professionals/compliance-enforcement/agreements/"

That is the reason why int never show up.

Example based on your code
import requests
from bs4 import BeautifulSoup
import csv

# URL of the page to scrape
url = "https://www.hhs.gov/hipaa/for-professionals/compliance-enforcement/agreements/index.html"

# Send a GET request to the URL
response = requests.get(url)

# Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')

# Find all  tags containing the links
links = soup.select('section.usa-section ul a[href*="hipaa/for-professionals/compliance-enforcement/agreements"]')

# Create and open a CSV file in write mode
with open('hipaa_links.csv', mode='w', newline='\n', encoding='utf-8') as file:
    # Create a CSV writer object
    writer = csv.writer(file)

    # Write the header row
    writer.writerow(['Title', 'URL'])

    # Iterate over each link
    for link in links:
        # Extract link URL
        link_url = link.get('href')

        # Extract link title
        link_title = link.text.strip()
        writer.writerow([link_title, link_url])

print("Data has been written to hipaa_links.csv")


PHP Image Libraries

Question: I'm working on a PHP application that needs to obtain data from a topographical map (different elevations denoted by different colors). I need to do two things:

Using this map (800x600), find a way to determine the exact pixel location of a particular city. For example, San Francisco is located at precisely 121x585.
Using the location from (1) above, I need to read the exact color at that location.

Note: The map provider does not provide location-based data, only a colored map. I suspect multiple libraries would be needed to map coordinates to locations on the map (via a ratio?) and then use OCR to read the color.
Are there any PHP libraries/tools that do this? How would you pull this off?
Answer: I may not have understood the problem entirely, but you should map the locations you want into an array (of objects?)
$city_mapping = array(new City("San Francisco", 121, 585), new City....); //Map your cities to an array.

Where City should be defined as a class to contain those variables.

Then use imagecolorat() to check for the color.
Comment: -1, completely misses the fact that he wants to find the cities automatically.
Comment: It's not possible to determine the points of cities on an annonymouse map, with no relation points to hang on to, and no scale. He has to map the points himself.
Answer: Once you know the pixel-coordinates, you can use PHP's built-in GD library to sample the color of an arbitrary pixel quite easily.
The tricky bit will be determining the pixel to sample, which can get pretty darned tricky.  The earth being sphere-like, maps use various projections to produce a 2-d representation.  If you know how the colored map image is projected, and you know the latitude/longitude of the pixel at (0,0), you should be able to write a function to convert lat/long to a pixel coordinate.
Comment: You need the maps scale as well, either that or another point to relate to.

PHP Image Libraries


What is $\langle 3u+2v , -u+4v\rangle$ Given $\lVert u\rVert$ , $\lVert v\rVert$ , and $\langle u,v\rangle$?

Question: What is $\langle 3u+2v , -u+4v\rangle$ Given $\lVert u\rVert$ , $\lVert v\rVert$ , and $\langle u,v\rangle$?
\begin{align}
    \lVert u\rVert &= 3\\
    \lVert v\rVert &= 5\\
    \langle u,v\rangle &= -4
\end{align}
Well, to solve this I thought I'd break down certain elements.
I know that...
\begin{gather}
 \langle u,v\rangle = \mathbf{u}\cdot\mathbf{v} = u_1v_1 + u_2v_2 + u_3v_3 + \cdots + u_nv_n = -4\\
    \langle u+v , u+v\rangle = \langle u,u\rangle + \langle u,v\rangle + \langle v,u\rangle + \langle v,v\rangle
\end{gather}
But I don't know what $\langle 3u+2v , -u+4v\rangle$ actually is...
Is it
$$
    \langle 3u,-u\rangle + \langle 3u,4v\rangle + \langle 2v,-u\rangle + \langle 2v,4v\rangle \mbox{?}
$$
Comment: Yes it is. Then use $(aU,bV) = ab(U,V)$ (if $U,V$ are vectors and $a,b$ scalars) to finish it up.
Comment: Ok I figured it out, thanks!
Comment: Good. Let me encourage you to write up what you have figured out, and post it as an answer.
Answer: Hints.$\def\v#1{{\bf#1}}$

Expand $(3\v u+2\v v , -\v u+4\v v)$ pretty much as you did for $(\v u+\v v,\v u+\v v)$.
You are given $(\v u,\v v)$: how does this help you to find $(\v v,\v u)$?
You are given $\|\v u\|$ and $\|\v v\|$: what does this tell you about the other terms in your expansion?
Answer: $\langle 3u+2v,-u+4v\rangle    =\langle 3u,-u\rangle +\langle 3u,4v\rangle +\langle 2v,-u\rangle +\langle 2v,4v\rangle$
\begin{align}
          &=-3\langle u,u\rangle +12\langle u,v\rangle -2\langle v,u\rangle +8\langle v,v\rangle\\
              &=-3\cdot 9 + 12\cdot -4 - 2\cdot 4 + 8\cdot 25
\end{align}
since $\lVert u\rVert = 3$, $\lVert v\rVert = 5$, $\langle u,v\rangle = -4$ and  $\lVert u\rVert^2 =\langle u,u\rangle$
Comment: Welcome to math.stackexchange ! Please edit your answer to explain a little bit what you have done in order to make i easier to understand for the asker. Right now it is a little bit unclear what you mean.


Protractor-Flake is running the same script in all instances after retry instead of using only one instance

Question: I have a project with Protractor, Protractor-Flake (To re-run failed tests, 3 times), Multicapabilities for parallelization in two instances. But when the first execution finishes, the failed spec is executed at the same time in two different instances, is it possible to have only one instance running on retry attempts, or at least if the two specs fail then to execute each spec in each instance. (On the first execution Test1 and Test 2 are running at the same time in different sessions) This is my config.json.
multiCapabilities:  [{
    browserName: 'chrome',
    shardTestFiles: true,
    maxSessions: 1,
    chromeOptions: {
      w3c: false
    },
    specs: ['../tests/Test1.spec.js']
  }, {
    browserName: 'chrome',
    shardTestFiles: true,
    maxSessions: 1,
    chromeOptions: {
      w3c: false
    },
    specs: ['../tests/Test2.spec.js']
  }],

And this is how the second attempt looks like:
Using multi to parse output
Re-running tests: test attempt 2
Re-running the following test files:
Test2.spec.js

[18:40:29] W/launcher - You have specified both capabilities and multiCapabilities. This will result in capabilities being ignored
[18:40:29] I/launcher - Running 2 instances of WebDriver
    [18:40:19] I/testLogger - [chrome #01] PID: 36072
    [chrome #01] Specs: Test2.spec.js
    [chrome #01]
    [chrome #01] [18:39:36] I/direct - Using ChromeDriver directly...
    [chrome #01] Started
    [chrome #01] Jasmine started

    [chrome #01] 3 specs, 1 failure
    [chrome #01] Finished in 41.496 seconds
    [chrome #01]

    [18:40:19] I/testLogger -

    [18:40:19] I/launcher - 1 instance(s) of WebDriver still running
    .[18:40:28] I/testLogger -
    ------------------------------------

    [18:40:28] I/testLogger - [chrome #11] PID: 7760
    [chrome #11] Specs: Test2.spec.js
    [chrome #11]
    [chrome #11] [18:39:36] I/direct - Using ChromeDriver directly...
    [chrome #11] Started
    [chrome #11] Jasmine started
    [chrome #11] 3 specs, 0 failures
    [chrome #11] Finished in 49.188 seconds
    [chrome #11]
    [chrome #11] Executed 3 of 3 specs SUCCESS in 49 secs.

Answer: You would have to look at how protractor-flake works internally to understand why this is happening. Without getting into too much detail, essentially what's happening is each running protractor instance gets restarted with the list of failed tests. Because You have two capabilities both of them are restarted with this list. You can see the code that causes this to happen here.
That said, it doesn't make much sense to have two capabilities that are exactly the same. You have shardInstances set to true but are only running one test. As I'm sure you are aware, shardInstances is for parallel execution. Change the capabilities to something like this and it will solve your problem. It will still initially launch two specs, each with their own browser instance, and then the retry will only run the failed spec.
multiCapabilities:  [{
  browserName: 'chrome',
  shardTestFiles: true,
  maxInstances: 2,
  chromeOptions: {
    w3c: false
  },
  specs: [
    '../tests/Test1.spec.js',
    '../tests/Test2.spec.js'
  ]
}]


How do you handle long charts that span multiple pages?

Question: I need to print several bar charts to PDF for some reporting requirements. One the of the issues I am certain to encounter is how to handle the display of very long charts that span multiple pages in the PDF. Some of the charts contain up to 500 records. There is even one case that would show nearly 3000 records!
When I scale the chart down to fit on a single 8.5" x 11" page the bars and labels on the charts are no longer readable. This is also how MS Excel addresses this scenario; it experiences the same problem.
However simply continuing the chart on subsequent pages results in a jarring experience at the page break and your x-axis might be located several pages down. This makes it terribly difficult to know what you are looking at.
Several solutions have been proposed:

Split the chart into multiple charts to be displayed sequentially in the report
Reduce the size of the dataset to only the top N records so as to fit on a single page
Replace the chart with a more compact form such as a table with multiple columns and numeric values.

Option 1 could make it more difficult to disseminate the proper information from the chart as you have to visually scan multiple disjointed datasets.
Option 2 could cause situations where important information was truncated. Perhaps all 200 records needed to be displayed.
Option 3 could work though it could suffer the same multi-page issues as with the chart (though it would likely be reduced in severity). Additionally it could be harder to visually scan for relative differences between one record and another.
How would you handle long charts that span multiple pages? Is there a standard or accepted way for addressing this scenario?
EDIT 2011-12-27
It has been proposed that we may need re-visit and adjust the requirements as there may not be value in a chart that spans multiple pages. It could simply be too difficult to interpret no matter how we format the chart across multiple pages.
Answer: I have thought something about this, because it is a major problem. I think there are two responses to this. Firstly, the requirements need to be changed, because charts of this size are difficult to interpret, so it is worth some investigation into what is actually needed.
The other approach, is to print these on something larger - like an A0 printer. If these sort of charts are needed at this scale, then a specialised printer is worth while. If not, the requirements is probably not that important.
Comment: I think revisiting the requirements is the right answer for us. Viewing 200, 500, or even 1000 records in a chart is simply not readable no matter how we slice it.
Comment: In some cases it is, which is why I gave this option, if the chart is going to be on the wall for intense study. But for you and most people, you are right, the requirements need to change.
Answer: How about print out the header of the chart on each page with a text Displaying 50-100 etc. That way it's easier to follow. You could also add vertical zebra stripes which also makes it easier to follow. And add a page break at the beginning of every chart. Option 2 doesn't quit solve your initial task - the reporting thing. And option 3 might also be harder to interpret.


Leaving lost neutral wire

Question: I am in the process of clearing out old random wires from my 100 year old house (think multiple layers, modern, knob and tube and everything in between).   In the process of doing this, I  tried to remove a knob and tube circuit that disappeared into an air duct.  I turned off the breaker feeding it and cut the wires before they entered the duct. Why is the wiring being traced through an air duct?  You'll have to ask someone from 100 years ago.
I then went to the panel to disconnect the wires completely from the breaker (leaving the loose in between pieces in the air return, as I don't want to take that apart).  The  hot wire is easy to identify being connected to a specific breaker.  However, it enters the panel by itself, as a single cloth wrapped conductor not linked in any way to the neutral.  The neutral is one of 30 other neutral wires entering the panel, and I can't easily see which one it is.  Is it safe to leave the neutral wire that is buried in the air duct connected to the neutral bar, or should I really unearth it so I can fully remove it from its panel connection.
Comment: @maple_shaft, Wouldn't you have to temporarily disconnect each neutral in turn while you test? Otherwise, they're all just connected together on a common block are they not?
Comment: US wiring is weird... in the UK we have this thing called a "cable", which contains a live wire, a neutral wire and an earth wire. It's easy to tell which neutral goes with which live - they're the ones in the same cable!
Comment: If you're doing this much work, why not go all out and redo all the wiring to bring everything up to modern standards?
Comment: If you know where this wire ends up, and you disconnected the conductor from the breaker, you can temporaily nut the hot and neutral together and then test the hot wire originally at the breaker to each neutral wire at the breaker. The neutral with 0 resistance is the one you need to remove.
Comment: @Octopus Yeah I guess that would be a pain huh? Cant really think of a way to for sure tell if you cant really see where the incoming wire is coming.
Comment: Extra neutrals are a whole lot better than having a hot lead that goes to God-knows-where. I am not qualified to tell you what to do, but if it were mine I would leave it alone until I was able to remove everything from that duct.
Answer: Chase down the matching neutral and remove it.
Otherwise it will drive you crazy, and be a loose end of wire unaccounted for.  What's more, it could wind up still being in use by some other circuit which shouldn't be there.   Part of the reason to fully explore an electrical system is to look for surprises.
Besides, since all wires must terminate in junction boxes, it will violate code and fail inspection.
I don't agree with my colleague that it's necessary to tear apart the ducting system, I feel unreachability is a defense.  But to play that defense, you must positively identify both wires of that circuit, both where they enter and exit the ducting, and fully remove all of that.
Comment: When I sold real estate and worked with home inspectors we were always aware that there is no requirement to bring homes up to modern code except for major renovations.  Of course, safety hazards would be of concern in a case like this.  But I'm with you - it would drive me crazy until I removed everything from that duct.
Answer: Wiring has no business in air ducts, so get it out of there
For safety reasons (burning wire insulation in air ducts smoking you out of your house is majorly no bueno), the NEC prohibits wiring in ductwork that isn't required by the HVAC system design in 300.22(B):

(B) Ducts Specifically Fabricated for Environmental
  Air. Equipment, devices, and the wiring methods specified
  in this section shall be permitted within such ducts only if
  necessary for the direct action upon, or sensing of, the
  contained air. Where equipment or devices are installed and
  illumination is necessary to facilitate maintenance and repair, enclosed gasketed-type luminaires shall be permitted.
Only wiring methods consisting of Type MI cable without an overall nonmetallic covering, Type MC cable employing a smooth or corrugated impervious metal sheath
  without an overall nonmetallic covering, electrical metallic
  tubing, flexible metallic tubing, intermediate metal conduit,
  or rigid metal conduit without an overall nonmetallic covering shall be installed in ducts specifically fabricated to
  transport environmental air. Flexible metal conduit shall be
  permitted, in lengths not to exceed 1.2 m (4 ft), to connect
  physically adjustable equipment and devices permitted to
  be in these fabricated ducts. The connectors used with flexible metal conduit shall effectively close any openings in
  the connection.

So, I'd get that ancient, stray wire out of the duct system and removed completely.
Comment: Thank you all (esp Harper and Three) for your guidance.  I think you are right, and will figure out a strategy to unearth the neutral and expunge it once and for all.  I agree about the chronology: K/T first, then duct.  Living in a house like this is like being an archeologist, where when you scrape a layer you discover signs of previous civilizations.
Comment: It's more likely that the wiring was there before someone decided to use the space between joists as a duct. Forced-air is newer than K&T and the previous system, gravity, needed fairly particular ducting.
Comment: @Harper -- talk about a silly tinbender for an HVAC guy, then...
Comment: Yup, what you hear talking there is my aversion to crafts I'm not skilled at. Wire up a pad transformer, sure,  actually pour the concrete pad, "yikes!"
Answer: You can die from cutting the wrong neutral wire...
(but it's not that easy)
There is something known as a 3-wire circuit that attempts to take advantage of AC's properties. Intended to let you use a smaller neutral wire than the two hot wires it supports. This is only done for hots sourced from different hot "legs" at the panel. This is supposed to have a single handle double breaker so that both hots get shut off at the same time.
Presuming a 220v service at panel supplying 110v home uses ->
The plan is commonly that you have a TV in one room and a table lamp in the next room sharing the same neutral wire, but they each have their own hot leg from different sides of the supply transformer (down the street on a pole somewhere). If you watch TV the neutral has only that load to carry. If you go read a book then the neutral only carries the lamp. BUT if you leave the TV on and go read a book, the neutral carries NOTHING since the TV and lamp are now in series in a 220v circuit.
The problem->
Cutting the neutral between the connection to use points and the panel can leave the 220v lines available to possibly hurt you and neither TV or lamp will work without the other.
It would take a very good psychic to guess what may have been done properly or otherwise in a house that old, so I agree with earlier advice - chase it down.
You certainly don't want your duct work becoming energized
Comment: An imbalanced load will also wreck havoc on the loads themselves because one load will get more voltage than it is meant to support if the neutral was cut.
Comment: True enough.  If that neutral is carrying a leakage current then cutting it could result in the whole duct becoming energized.

Leaving lost neutral wire


Mongo Balancer Not Running

Question: I configured mongo shared cluster but when i enter sh.isBalancerRunning() it gives false answer also when I checked the status  by sh.status() is giving the below output.
balancer:
    Currently enabled:  yes
    Currently running:  no
        Balancer lock taken at Wed Sep 13 2017 05:37:35 GMT+0000 (UTC) by ConfigServer:Balancer
        Balancer active window is set between 23:00 and 18:00 server local time
    Failed balancer rounds in last 5 attempts:  5
    Last reported error:  could not find host matching read preference { mode: "primary" } for set rs1
    Time of Reported error:  Tue Sep 12 2017 14:33:10 GMT+0000 (UTC)
    Migration Results for the last 24 hours:

How can I start balancer?
Comment: This question really belongs on [dba.stackexchange.com](https://dba.stackexchange.com) which is the site to use for database administration and configuration questions. StackOverflow is for programming topics only, of which this question is not. **Please move your question to the correct site by deleting and reposting.**
Answer: You need to check the connectivity first.
Validate connectivity from Mongo's server to the "rs1" primary mongod instance. I believe it should work.
Secondary, try it again without Balancer active window schedule. I guess MongoDB Balancer is not that smart to read 18:00 as a next day.
You can change it:
use config

db.settings.update({_id: "balancer"}, {$unset: {activeWindow: {start: "23:00", stop:"18:00"}}})

Mongo Balancer Not Running


Ubuntu server 16.04 no wireless internet connection

Question: I've installed a fresh Ubuntu 16.04 server and can't get WIFI to work. My /etc/network/interfaces file looks like this:
auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet dhcp
wpa-ssid lomboboo
wpa-psk password

I also tried this setup as it was suggested in this answer:
auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet static
address 192.168.1.150
netmask 255.255.255.0
gateway 192.168.1.1
wpa-ssid lomboboo
wpa-psk password
dns-nameservers 22.214.171.124 192.168.1.1

But none of them work.
Also this is info from ifconfig
P.S. Don't know if it matters - Ubuntu 16.04 server is running on Raspberry Pi 3.
EDITED
sudo ifdown wlan0 && sudo ifup -v wlan0 output:

ping -c3 18.104.22.168 output:
connect: Network is unreachable

Comment: Please edit your question to add the results of: `sudo ifdown wlan0 && sudo ifup -v wlan0` and also: `ping -c3 126.96.36.199`
Comment: @chili555 just updated the question
Comment: Is this a virtual machine? I don't understand `50-cloud-init.cfg`.  Sorry.
Comment: @chili555 actually no, it is not. I've installed Ubuntu from this image ``ubuntu-16.04-preinstalled-server-armhf+raspi3.img.xz`` on my Raspberry Pi 3
Answer: I suspect that you have set wpa-psk in /etc/network/interfaces to the passphrase for your wireless network. That will not work.
Let's say the SSID for my router is MYROUTER, and I set the WPA/WPA2 passphrase on my router to MySecretPassphrase. At first glance, you would think that /etc/network/interfaces should look like this:
wpa-ssid MYROUTER
wpa-psk MySecretPassphrase

Wrong. I made this mistake a few months ago, and it took me a while to figure why it was not working. In short, wpa-psk should be set to the 256-bit pre-shared key for this SSID. Do not set wpa-psk to the passphrase.
How do you that? By using the wpa_passphrase command (if it isn't installed, you can install it with sudo apt install wpasupplicant). From the man page:

wpa_passphrase  pre-computes  PSK  entries  for  network
  configuration blocks of a wpa_supplicant.conf file. An ASCII
  passphrase and SSID  are used to generate a 256-bit PSK.

Let's give it a try:
~$ wpa_passphrase MYROUTER MySecretPassphrase

Output:
network={
    ssid="MYROUTER"
    #psk="MySecretPassphrase"
    psk=93763b13c803b7269956cb9bf584c75eb0fd0e99c51ecf49598a4016a29aa3f1
}

Assuming the wireless adapter is labeled wlan0, the /etc/network/interfaces file for the example above should look like this:
auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet dhcp
wpa-ssid MYROUTER
wpa-psk 93763b13c803b7269956cb9bf584c75eb0fd0e99c51ecf49598a4016a29aa3f1

Instead of typing this long string or using copy/paste, you can do this to append the relevant lines to /etc/network/interfaces:
~$ wpa_passphrase MYROUTER MySecretPassphrase | grep -vE "{|#|}" | tr -d '\t' | sudo tee -a /etc/network/interfaces

Then edit /etc/network/interfaces to make sure everything looks right.
Finally, either reboot or restart the networking service:
~$ sudo service networking restart

Answer: For me
auto an_usb_interface
iface an_usb_interface inet dhcp

wpa-ssid MYROUTER
wpa-psk MySecretPassphrase

was enough.
I answered this because the answer at this question is saying that this is wrong and to use the 256-bit pre-shared key for this SSID, but this is working (and cannot comment there yet; wpasupplicant is used at some point by /etc/init.d/networking start).
Comment: This answer is very very unclear.


Why doesn't this work? (ProjectEulerProblem5)

Question: I'm trying our Project Euler and I've gotten to Problem 5 and this is the question:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
This is what I've come up with:
for (int x = 1; x >= 100100100; x++) { //100100100 is just a number to count to, an end point.
    int count = 0;
    for (int b = 1; b <= 20; b++) {
        if (x % b == 0) { //Tests numbers.
            count++; //Counter

            if (count == 20) { //Numbers that fit between 1 and 100100100
                System.out.println(x);
            }
        }
    }
}

When I run this it does not print a value. What have I done wrong/overlooked?
Comment: Shouldn't for condition be `x <= ...`? Because x is initialised as 1, so it doesn't even enter the body of the loop at all.
Comment: Hint: instead of using `x++` you might take steps of `20` :)
Comment: When is x == 1 and x >= 100100100 at the same time?
Comment: Why should I use steps of 20? Just curious.
Comment: You'll need to go further than 100100100.  The correct answer is bigger than this.
Comment: @Heavypick The number you're searching for needs to be divisible by `20`. Now think a bit about your loop. Is `1, 2, 3, 4, 5, 6, ..., 19` divisible by `20`? The same goes for `21, ..., 39`, you will basically skip a lot of iterations that obviously won't lead to the answer
Comment: @HamZa But `x` also has to be initialised at 20 then? Otherwise, any other value, if you add 20, will never be divisable by 20.
Comment: @AntonH If I spill all the beans I will ruin the fun
Comment: You can also do this by computing the multisets of prime factors of #'s from 1 to 20, taking the union of these multisets, then multiplying these numbers: union({2}{3}{2,2}{5}{3,2}{7}{2,2,2}{3,3}{5,2}{11}{3,2,2}{13}{7,2}{3,5}{2,2,2,2}{17}{3,3,2}{19}{2,2,5})={2,2,2,2,3,3,5,7,11,13,17,19}. So try `System.out.println(2*2*2*2*3*3*5*7*11*13*17*19);`.
Comment: I got the answer. I just had to change the sign and also increase the size of the number, then I took the idea of adding 20 instead of 1 to each cycle and found it even faster. Thanks everyone!
Answer: Change the loop from:
for (int x = 1; x >= 100100100; x++) {

to:
for (int x = 1; x <= 100100100; x++) {

As it is, you're not even entering the body of the loop, since you don't verify the condition after initialising the values.
Comment: This won't work, as the correct answer is larger than 100100100.
Comment: My answer was concerning his loop condition, rather than the actual value that has was using as a max value (he could use `Integer.MAX_VALUE instead`). But yes, you are correct.
Answer: First of  all what the question is really asking for is that finding the smallest number which is evenly divisible byall of the numbers from 1 to 20. Which means you do not need to deal with another number in your code 100100100. All you need to do is finding the biggest powers of all the prime numbers which is in the range.In which case it would be
2^4*3^2*5*7*11*13*17
.
Answer: Your maximum is took small.  You need to solve you problem differently as brute force will take too long (as indeed most project euler tasks do) This is because most of them are mathematical challenges not really programming challenges.
What you need to do it to work out the factors this number will have.
2 => must be a multiple of 2
3 => must also be a multiple of 3
4 => must be a multiple of 2 and 2
5 => must be a multiple of 5
6 = > must be a multiple of 2 and 3

From 2 to 6 you need 2*2 * 3 * 5 is the smallest factors will satisfy all of these or 60.  For 2 to 20 you need to consider them all.  Note: it will be a multiple of 7, 11, 13 ,17 and 19.  Once you find how many factors of each you need,
Comment: @DavidWallace Thank you, just googled the answer ;)
Comment: Googled it?  I just typed `16 x 9 x 5 x 7 x 11 x 13 x 17 x 19 =` into a calculator.
Comment: @DavidWallace I used cut-n-paste of aliatlii's answer.
Answer: That's not an answer to your question, since it has been answered, but my input:
You should do something like this:
boolean flag = true;
if(x % b !=0){        // If one number does not meet the condition
    flag = false;     // A flag tells you the test failed
}

instead of counting through every item. And a while loop to count to infinity.
Also, SOLUTION SPOILER ALERT: For the solution of the problem, my approach would be using prime numbers and something called prime factorization.


Within a script in the UI Automation instrument, how do I import another script?

Question: Within a script written in JavaScript for the UI Automation instrument, how do I import another JavaScript file?
Comment: Be more specific of what you want to do.
Answer: Within UI Automation, you can add something like
<code>#import "MySharedFunctions.js"
</code>
at the top of your script to have it pull in code from another JavaScript file.  This can be used for storing common testing or other helper functions within a shared source file.
Comment: @ZS - Possibly. All of the times I've used this, the JavaScript files were in the same directory. I haven't experimented too much with file location.
Comment: Does the file have to be in the same directory? I'm trying to do this, but it keeps telling me "The #import file 'UIAutomationTest-CreateAccount.js' was not found, as required from the script '(null
Comment: You will see the not found error if you have created a new script and have not yet saved it (i.e. exported - menu click on text area). Once you save it the error should go away.
Comment: @ZS you can use `../` to move back up the file tree.


Python and terminal - Strings with special characters

Question: I know the Python thing that if I'm using interactive interpreter and I write '\\ ' it prints '\\ ' but if if I write print '\\ ' it prints '\ '.
What I'm trying to do is (in a script called p.py):
import os
os.system('echo ' + 'string with spaces'.replace(' ', '\ '))

obviously it won't let me do this. I mean, Python manages to add TWO backslashes instead of one but I think it does so only in interactive mode, but the terminal, when passed special chars like \, ignores them.
So that, as the output of the provious code, I get:
local:$ string with spaces

and not
local:$ string\ with\ spaces

I already tried hardcoded strings and everything else in Python, but I guess the problem is with shell strings.
How could I solve this?
It it can help to find alteratives solutions, what I'm trying to do is moving a file from python with the mv command, and this file has spaces in its name.
Comment: Just curious, why are you trying to use backslashes?

The shell uses quotes note backslashes to not treat spaces as special.  For example echo "string with spaces".  I feel like I'm missing something here.
Answer: os.system('echo ' + 'string with spaces'.replace(' ', '\ '))

In that line, the last string '\ ' will try to escape a space, even though that is not an escape sequence. If you want it to become a space with a preceding backspace, you can either escape the backspace ('\\ '), or you can use a raw string which will ignore all escape sequences (r'\ ').


What happened to Alucard after Castlevania: Symphony of the Night? (Possible Spoilers)

Question: At the end of SOTN, Alucard says he is going to

 hide himself from humanity forever.

But, he appears later on in the series. What happened during that time, if it is ever told?
Answer: According to a Japanese-only, internet radio drama titled Akumajō Dracula X: Tsuioku no Yasōkyoku (悪魔城ドラキュラX:追憶の夜想曲) (Castlevania: Nocturne of Recollection), Alucard lived with Maria for a while. The script appears to play up the dedicated girlfriend/wife angle. The drama ends with them as a happy couple, more or less. There is no further mention of Alucard's life until his appearance in Aria of Sorrow.


How can I tell when I can run again?

Question: I seem to run out of "sprint juice" in Red Faction and I'm not 100% sure how long I can run or when I can run again. Best I can tell there's no meter for it anywhere. Is there any visual/etc indication that shows me when I can sprint again?
Answer: No, there is no indication of when you can run again.

How can I tell when I can run again?


What is the easiest way to complete the clearance of the Hallow?

Question: I just beat Skeleton Prime and unlocked the Steampunk (and Clentaminator), and I have the money to easily unlock Green Solution. However, I have a hard time getting world evils to 0% because I can't find the remaining Hallow until it grows and becomes hard to eliminate. How do I find the remaining Hallow to quickly convert to the Purity?
Answer: The method recommended by the terraria wiki is probably what I would do. Dig hellevators  180 tiles apart in the general area of the Hallow, then jump down them and spray on both sides, that should get rid of all of the Hallow.


Scraping md5s from webpage and comparing them against common password

Question: So i have the following code which scrapes through a given webpage and finds md5s using a regex (I know you never find md5s in the source code but its for a uni project). Once found the md5s it compares it against a list of common passwords which also get hashed. The problem is that its always returning that none of the md5s match which i know to be false.
If anyone could help that would be great however i feel like the problem is the inserting of md5 as it might no be iterable is my hunch.
md5s = re.findall(r'[a-zA-Z0-9]{32}',webpage.decode())
md5s.sort()
print (f'[+] {len(md5s)} md5s Found:')
for md5 in md5s:
    print(md5)

passwd_found = False

dic = []

for k in dic:
    md5hash = hashlib.md5(k.encode('utf-8'))
    #print(md5hash.hexdigest())
    if md5 in md5hash.hexdigest():
        passwd_found = True
    else:
        passwd_found = False

    if passwd_found:
         print (f'[+] Password recovered: {k}')
    else:
         print ('[-] Password not recovered')

OUTPUT FROM REGEX
`[+] 6 md5s Found:
5efweev789d3d1d09794d8f021f40f0e
5fcfd41e547aewfwefwefff47fdd3739
9d377b10ce778few2334c7g2c63a229a
FEA0F1F6FEDE90BDfn89049194DEAC11
aDsxMzE0MDY7ajsx785g90f0MjAwOzQw
d1133275ee2118b9739440f759fc0524
OUTPUT FROM COMPARISON
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered
[-] Password not recovered

Answer: In this code, what do you think is the value of md5?

for k in dic:
    md5hash = hashlib.md5(k.encode('utf-8'))
    #print(md5hash.hexdigest())
    if md5 in md5hash.hexdigest():
        passwd_found = True
    # ...

Before this snippet, md5 was used in a loop.
At this point, the value of md5 is the last value from the previous loop.
That's hardly what you want.
If you want to find the values of dic whose hashed value occurs in md5s (on the page you scraped), it will be better to do like this:
md5s = frozenset([m.lower() for m in md5s])
for k in dic:
    md5hash = hashlib.md5(k.encode('utf-8'))
    if md5hash.hexdigest() in md5s:
        print("found", k)

That is, turn md5s into a set,
to make it fast to search in it,
and then for each value in dic,
check if its hashed value is contained in md5s.
Comment: I believe its not matching of of the md5s as one is upper case and one is lowercase, and idea how to fix this. eg md5s starts with FE and fe.
Comment: @JDoe sure, you can do `md5s = frozenset([m.lower() for m in md5s])`


Conditional Post-Build step in Jenkins without plugins

Question: For my post-build step, I will be executing Sonar analysis (from SonarQube plugin) and a script that I wrote. I don't want this to run all the time and want to trigger the post-build step with a boolean parameter. Is there anyway to do this? Ideally, I want to have a checkbox that determines if the Post-Build step will execute in the Build-with-Configurations page.
Answer: You could use the Promoted Builds Plugin to start further steps after a build. This can be done either manually (I think that's what you're looking for) or based on some logic you've defined.


IONotificationPortDestroy - to call or not to call?

Question: I have code to set up notification for USB device add/remove using XCode 4.3.3 on OS X 10.7.4. For a USB device with myVid and myPid, it is pretty boilerplate:
<code>// Global declarations somewhere near the top of the file.
IONotificationPortRef g_notificationPort= NULL;
io_object_t g_notification= 0;
io_iterator_t g_iteratorAdded= 0;
.
.
.
- (BOOL)setupDeviceNotification
{
// Set up matching dictionary.
NSMutableDictionary* matchingDictionary= (NSMutableDictionary*)IOServiceMatching(kIOUSBDeviceClassName);
[matchingDictionary setObject:[NSNumber numberWithLong:myVid] forKey:[NSString stringWithUTF8String:kUSBVendorID]];
[matchingDictionary setObject:[NSNumber numberWithLong:myPid] forKey:[NSString stringWithUTF8String:kUSBProductID]];

// Create a run loop source for the notification object.
g_notificationPort= IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopSourceRef notificationRunLoopSource= IONotificationPortGetRunLoopSource(g_notificationPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

// Set up a notification callback for device addition on first match.
kern_return_t kRet= IOServiceAddMatchingNotification(g_notificationPort, kIOFirstMatchNotification, (CFMutableDictionaryRef)matchingDictionary, deviceAddedCallback, (void*)self, &g_iteratorAdded);

// Rudimentary error handling.
if(KERN_SUCCESS != kRet)
{
  [matchingDictionary release];
  return FALSE;
}

// Arm the notification and check for existing devices.
[self deviceWasAdded:g_iteratorAdded];

return TRUE;
}
</code>
This code works well, and when a device is added, I use IOServiceAddInterestNotification using the IONotificationPortRef and store the io_object_t that is set in a global object.
Upon analyzing this code to do a little refactoring (making the globals into object variables in the class), I realized I am never calling IONotificationPortDestroy on my IONotificationPortRef object. Should I call it? Also, I am not doing anything with the io_object_t that is assigned in IOServiceAddInterestNotification - is there any cleanup required there?
Answer: OK, one thing I have found after poking around in a lot of Apple documentation is that I should really do an IOObjectRelease on the io_object_t that is the notification. I found a couple of references to it, but the easiest is in the document "User-Mode USB Device Arbitration" on the Apple Developer site.


Bench Vise Restoration: Removing Spindle

Question: I'm in the process of restoring an old Bench Vise and first I'm disassembling it, so I can check parts for excessive wear, remove rust and repaint. I'm not sure what is the brand, but here's a picture of it:

I could remove a plate that holds the dynamic jaw to the main frame, letting it slide and not allowing it to move up. Below the dynamic jaw already without the guiding plate:

But the spindle is somehow fixed inside the dynamic jaw. I could notice two small holes, after removing some grease, on the bottom (picture above), and two small holes that I had to scrap rust off on the top in the same axis.

I suspect there are some pins inside there holding the spindle, not sure how though. Before I started hammering a small nail inside it I thought someone could answer if they've ever seem this kind of spindle fixing before, how it works and how to remove it/replace it.
Any ideas? Thanks!
Comment: That's a machine or milling vice rather than a bench vice. The elongated holes are for fastening to a mill table. I'd check for allen screws in the holes, and possibly try asking somewhere with more machinists around.
Comment: I think that the two closest to the threads are small set screws. It also looks like you haven't removed the plates from the jaws, and there's likely screws behind them. Searching the web for "kurt vice disassembly" may or may not help; kurt's a well-known manufacturer of similar vices.
Comment: @MatthewGauthier Thanks, didn't know that! The holes barely fit a toothpick, you think it can be a very thin screw? I thought it could be some of those nails that fit by pressure, and that I'd have to hammer back and replace them on the assembly. Not sure where I can find a machinist around here, but I'll start searching!
Comment: @MatthewGauthier I hadn't removed the jaws because the access to the screws where very short with the dynamic and static jaws still assembled. Today I tried to buy a short flathead screwdriver and was able to remove 3 of 4 jaw screws, the last is still stuck. I'll keep trying tomorrow and check for any screws behind the jaw. I was noticing that there's a high chance the head of the screws are damaged if those very small holes actually have a screw inside them, and possibly the only way to remove them will be drilling them out, but that's just guessing right now.
Answer: To get the last jaw screw out try this: choose a short quarter-inch hex bit to match the jaw screw. Place the hex bit into a quarter-inch box-end wrench and close the vise jaws so the bit is trapped and pressing against the stuck screw. Use the box wrench as a handle to turn the bit and loosen the screw. Adjust the vise tension to prevent the bit from slipping.
The pair of holes look small enough to be roll pins or steel pins. They would have the hardness to clinch the groove in the spindle. Poke with a sharp tool, then use a pin punch to tap it out. The holes on the underside look smaller; there may be a step to prevent the pin from falling through. In that case it's probably a solid pin. Punch it through from the smaller hole.
Comment: Thanks! I'm sorry for taking a while to answer, had no time to work on the bench last couple of days. I'll try that, I did something similar with a flathead screwdriver, but I guess with the hex bit I'll have much more support and a better surface to press against. Also will check the correct pin punch size and get one so I can try to extract the roll/solid pin!


Iterating over huge S3 zip file's entries without download- and as fast as possible

Question: I am trying to find a fast and efficient solution to iterate over a zip's entries, while it is located in S3. The zip file is huge (60-100GB+), and downloading is not a viable solution since we are limited in storage.
The iteration is for calculating the offset of each entry.
One way to do that is by creating an S3 stream, and using SharpZipLib to iterate over the entries. The problem is that this method simply "downloads" the entries one by one everytime, which is pretty slow.
I know that for calculating the entrie's offsets, I don't really need to download all the bytes everytime, but rather fetch specific bytes. This can be done in python, but can this also be done in C#? From the libraries which I tried (Ionic, sharpziplib), I couldn't find a way to a way to minimize the byte fetching as much as possible.
Any ideas?
EDIT: Even though I need the solution in C#, I tried to fetch the last 22 bytes of a simple zip in python, but I get an "ValueError: negative seek value -55"
import io
import zipfile

zip_file = "path/to/zip"
with open(zip_file, 'rb') as file:

    file.seek(-22, io.SEEK_END)
    cd_bytes = file.read()

cd_stream = io.BytesIO(cd_bytes)
cd_stream.seek(0)

zipfile_obj = zipfile.ZipFile(cd_stream, mode='r', allowZip64=True)

for filename in zipfile_obj.namelist():
    print(filename)

Comment: Zips have a duplicate directory at the end of the file. You could read backwards from the end of the file until you find the start of that, https://stackoverflow.com/questions/8593904/how-to-find-the-position-of-central-directory-in-a-zip-file although you might end up writing code to parse this yourself.
Comment: I can't answer how to do this off the top of my head in C#, but the basic idea in Python would [look something like this](https://gist.github.com/Q726kbXuN/2fc857f887d87d3133f6cb6767fea3e4), turning the reads from a Zip library into S3 requests.  For a sample ~60gb Zip file I have on S3 it requred reading only around 24kb from S3 in 5 requests to display 250 files.
Comment: Neat! Here's a .NET [Seekable S3 Stream](https://github.com/mlhpdx/seekable-s3-stream) that might just do what Anon Coward's Python example does. Haven't tried it myself to recommend it though.
Comment: Ok sounds interesting. So If I start from the end, I have two questions:
1) How do I know which bytes are the EOCD / CD?
2)Can I load only the CD bytes into a ZipArchive objectin C#?
Because I will need to know the size of each file to skip and fetch the header bytes

EDIT: Ok. I see that I can iterate over enSize-22 until it works. But how do I know that I got the CD bytes?
Comment: What python library are you using?  Did you try with your S3 to see if it is working?  You can only open a remote S# file is you have permission to access the file on a network drive.  Download uses a different protocol for accessing the file than direct opening the file.  An S3 stream is downloading.  Does python download or opens the file remotely?
Comment: There is a ZIP specification the specifies the format of the zip file which zip utilities use.  A zip file is similar to the File System where there are Directories with pointers to the data.  the Directories contain the file size and date.  The directories are fixed size records (one for each file) and end with a null.
Answer: While this isn't directly possible with built in APIs, as you point out, the Zip header is at the end of the zip file.  Not much of the Zip file actually needs to be read to produce a list of its contents generally.  Though because of a couple of edge cases that can lead to multiple directory entries, and because the size of the directory entries are in fact after the entries themselves, you'll need to be able to seek a bit in the file to produce the list.
AWS S3 does allow you to seek, in a sense, since you can ask for specific ranges of data using byte range requests.  It would be possible to directly map a zip library's calls to Seek() and Read() to S3 calls. Doing so will likely be very inefficient, as many zip libraries will make many small requests, leading to lots of network traffic.  To work around that, you can request some amount of data beyond what the underlying library requests, and return results from that buffer when possible.
Putting it all together with some sample code looks like this:
using Amazon.S3;
using Amazon.S3.Model;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;

namespace ZipTestApp
{
    class S3WrapperStream : Stream
    {
        readonly AmazonS3Client _s3;
        readonly string _bucket;
        readonly string _key;
        readonly long _length;
        private long _offset;

        // Keep a local buffer to avoid many small round trips to S3
        // The size here of 32KiB is arbitrary
        readonly byte[] _localBuffer = new byte[32768];
        long _localStart = 0;
        long _localLength = 0;

        // Some stats, purely for debug/demo purposes
        public long TotalBytesRead = 0;
        public long NumberOfReads = 0;

        public S3WrapperStream(AmazonS3Client s3, string bucket, string key)
        {
            _s3 = s3;
            _bucket = bucket;
            _key = key;
            _offset = 0;

            // Get the object size to enable Seek from end operations
            var data = s3.GetObjectMetadata(bucket, key);
            _length = data.ContentLength;
        }

        // Implementations of Stream's properties
        public override bool CanSeek => true;
        public override bool CanRead => true;
        public override long Length => _length;
        public override long Position { get => _offset; set => _offset = value; }

        // Seek simply moves our current pointer around
        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    _offset = offset;
                    break;
                case SeekOrigin.End:
                    _offset = _length + offset;
                    break;
                case SeekOrigin.Current:
                    _offset += offset;
                    break;
            }
            return _offset;
        }

        // Turn reads into S3 calls
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (count > _localBuffer.Length)
            {
                // A big read goes directly to S3
                var req = new GetObjectRequest
                {
                    BucketName = _bucket,
                    Key = _key,
                    ByteRange = new ByteRange(_offset, _offset + count - 1),
                };
                var resp = _s3.GetObject(req);
                var read = resp.ResponseStream.Read(buffer, offset, count);

                _offset += read;
                NumberOfReads++;
                TotalBytesRead += read;

                return read;
            }
            else
            {
                // Otherwise, the read is small enough to fit in our local buffer
                if (_offset < _localStart || _offset + count >= _localStart + _localLength)
                {
                    // A request for data outside of our buffer came in, fill up to the size
                    // of our buffer first
                    var req = new GetObjectRequest
                    {
                        BucketName = _bucket,
                        Key = _key,
                        ByteRange = new ByteRange(_offset, _offset + _localBuffer.Length - 1),
                    };
                    var resp = _s3.GetObject(req);
                    var read = resp.ResponseStream.Read(_localBuffer, 0, _localBuffer.Length);
                    _localStart = _offset;
                    _localLength = read;

                    NumberOfReads++;
                    TotalBytesRead += _localLength;
                }

                // The data is in our buffer, pull out the correct data and return it
                Buffer.BlockCopy(_localBuffer, (int)(_offset - _localStart), buffer, offset, count);
                _offset += count;
                return count;
            }
        }

        // No need to implement write methods
        public override bool CanWrite => false;
        public override void Flush() { throw new NotImplementedException(); }
        public override void SetLength(long value) { throw new NotImplementedException(); }
        public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); }
    }

    class Program
    {
        static void Main()
        {
            // Create a helper to call into S3 based on Stream requests
            var helper = new S3WrapperStream(new AmazonS3Client(), "example-bucket", "example.zip");

            // Pass the helper along to the ZipFile method
            using (var zf = new ZipFile(helper))
            {
                // Just dump out the list of files
                foreach (ZipEntry entry in zf)
                {
                    Console.WriteLine("{0} {1}", entry.Size, entry.Name);
                }
            }

            // And finally some stats
            Console.WriteLine("Number of reads: {0}", helper.NumberOfReads);
            Console.WriteLine("Bytes read: {0}", helper.TotalBytesRead);
        }
    }
}

For a test zip file stored in S3, about 60GiB big with around 250 files the zip file, this required 9 calls to S3 pulling down a total of 25,477 bytes.


How can I keep a coupling nut aligned with its bolt?

Question: F25\F20 Westwood oil furnace filter housing.
This should come from the factory with that nut very tight on the lower bolt. To replace the filter element you remove upper bolt, remove the can, change the filter element, reassemble & replace upper bolt. Those are the instructions and there are many YouTube videos showing this.
It seems to me that if upper bolt was over tightened, then that might cause the nut to come off the lower bolt the next time upper bolt is removed to change the element. I think this is bad design. Still, I found no one else posting issues.
A replacement worked fine, but it leaked where can seats against upper red piece. So I had to tighten the upper bolt twice to stop leak (yes there is rubber gasket between). I hope nut stays on lower bolt when I change the element next year
I now have 2 extra units and I'd like to assemble as spares. I've tried but I can't keep the nut exactly centered when tightening it onto lower bolt, which means that upper bolt won't thread in. Ideas?
Comment: I'm not clear on the actual problem. If you snug down the sleeve nut, then add the upper bolt, what can go wrong? It appears that the lower bolt is fairly short, so it can't really end up too far into the nut.
Comment: That's a lot of ranting for a question with very little substance. Please [edit] your question to get rid of the first 2/3 or so of the rant, then use the site's built in image hosting facility to embed the images directly in your question. Remember, the easier it is for us to figure out what's going on, the easier it is for us to help you.
Comment: Most filters are only suppose to be tighten enough to stop leaking.  Over tightening would be abuse.
Comment: Most filters of that type, getting stuff to line up is more feel since you are doing it blind.  The bottom should be hand tighten plus a bit, somewhere between a 1/4 to one turn.  The top should be easy, but a few have been lucky they were not toss out of a window.
Comment: "i cant keep the nut exactly centered when tightening it onto lower bolt" - that's the backwards way to do it. Needle nose : hold the nut pointing straight up. Turn the can upside down. Now *screw the little bolt into the nut* that you know is pointing straight up even though you can't see it. You're watching the head of the bolt to know its threads are pointing straight down.
Answer: It seems like the split lock washer should retain the nut, but if it doesn't, thread locking compound, a.k.a. Loctite™, should do. I'd probably go with the removable variety because it's more useful in your tool kit, but use a good dose of it on the lower bolt.
If we're talking about alignment of the top of the sleeve nut with the upper bolt, here are two strategies that come to mind:

Snug the nut down on the lower bolt, then simply tilt it into a centered position. The bottom of the filter housing should bend fairly easily to accommodate.

Thread the nut onto the lower bolt, but leave it slightly loose. Now assemble the filter and hold both bolts, feeling for alignment. Tightening the bolts should now be possible.
Comment: That aspect of the problem wasn't clear from your question. You're apparently talking about _angle_, not position. "Straight" might be a better choice of words than "centered". I took that to mean at the bottom attachment point. The problem is that the bulk of your post deals with another part of the issue, so that was misleading.
Comment: The blue is "easily" removable. The red requires heat to remove. I'm not sure if there are other colors of Loctite™. Different brands may have different colors. YMMV. +1
Comment: Yeah, I don't go by (or refer to) color. For one thing it's unintuitive so I'll probably get it wrong.
Comment: Unless that coupling nut is exactly straight up (centered), the upper bolt wont thread in after its dropped thru the center hole of the lid. Pic 3 that bolt is not in center of upper lid.


how to declare 10000 x 100000 sized integer matrix in C++

Question: I need to create a matrix which size is 10000x100000. My RAM is 4GB. It works till the 25th iteration (debug), but after 25th iteration I get an error "bad allocation" however only 25% of RAM is used which means the problem is not related with memory. So what can I do?
EDIT:
int **arr;
arr=new int*[10000];
for(i=0;i<10000;i++)
    arr[i]=new int[100000];

My allocation is above.
Comment: I was waiting for someone to reply with "who cares". Please post code.
Comment: Allocate it on the heap, you may have 4GB of ram but the stack size is only a few MB (std::vector would be great for this)
Comment: How are you allocating this?
Comment: @Who Cares: You wrote: "I see from Task Manager that program runs until 25th iteration" And I was wondering, how you could determine this just from the task manager.
Comment: 25th iteration of what?
Comment: @MikeMB I mean i=25.. It allocates till the 25th row. Then nothing.
Comment: @Who Cares: And how do you determine that you only reach the 25th iteration?
Comment: @MikeMB have you ever heard something "debug" ?
Comment: @MikeMB ops. sorry my bad. I meant that When I debug I was observing the task manager, after the 25th iteration it didn't go further. And the usage of my RAM was 25%
Comment: Hmm... The 2GB limit ? http://stackoverflow.com/questions/5686459/what-is-the-maximum-memory-available-to-a-c-application-on-32-bit-windows
Comment: Now we are getting somewhere. Are you compiling for a x64 or x86 target? A typical 32bit windows Application on Windows has only 1GB of memory available for data.
Comment: @MikeMB it is x64 with 4 GB RAM Windows 7
Comment: Sorry, I missed a few zeros there. Which compiler (and even on a x64 Windows e.g. VS will by default compile a 32Bit Application)
Comment: @MikeMB So you say there is no way to do it? Right?
Answer: If you're compiling for x64, you shouldn't have any problems.
If you're compiling for x86 (most likely), you can enable the /LARGEADDRESSAWARE linker flag if you're using Visual C++, or something similar for other compilers. For Visual C++, the option can also be found in the Linker -> System -> Enable Large Addresses property in the IDE.
This sets a flag in the resulting EXE file telling the OS that the code can handle addresses over 2 GB. When running such an executable on x64 Windows (your case), the OS gives it 4 GB of address space to play with, as opposed to just 2 GB normally.
I tested your code on my system, Windows 7 x64, 8 GB, compiled with Visual C++ Express 2013 (x86, of course) with the linker flag, and the code ran fine - allocated almost 4 GB with no error.
Anyway, the 25th iteration is far too quick for it to fail, regardless of where it runs and how it's compiled (it's roughly 10 MB), so there's something else going wrong in there.
By the way, the HEAP linker option doesn't help in this case, as it doesn't increase the maximum heap size, it just specifies how much address space to reserve initially and in what chunks to increase the amount of committed RAM. In short, it's mostly for optimization purposes.
Answer: A possible solution would be to use your hard drive.
just open a file and store the data you need.
then just copy the data you need to a buffer.
Even if you will be successful with allocating this amount of data on the heap
you will overload the heap with data you are most likely wont be using most of the time.
Eventually you might run out of space and that will lead to either decreased performance or unexpected behaviors.
If you are worried about hindered performance by using the hard drive maybe to your problem thinking about a procedural solution would be fitting. If you could produce the data you need at any given moment instead of storing it you could solve your problem as well.
Answer: For allocating extremely large buffers you are best off using the operating system services for mapping pages to the address space rather than new/malloc.
You are trying to allocate more than 4GB.
Answer: If you are using VS, you'll probably want to try out the HEAP linker option and make sure, you compile for a x64 bit target, because otherwise you'll run out of address space. The size of you physical memory should not be a limiting factor, as windows can use the pagefile to provide additional memory.
However, from a performance point of view it is probably a horrible Idea to just allocate a matrix of this size. Maybe you should consider using a spares matrix, or (as suggested by LifePhilPsyPro) generate the data on demand.


reading gmail is failing with IMAP

Question: I am running a cron job which executes the python script for reading gmail (2 min interval). I have used imaplib for reading the new mails. This was working fine until yesterday. Suddenly its throwing below error

imaplib.error: [AUTHENTICATIONFAILED] Invalid credentials (Failure)

and sometimes i am getting the below error

raise self.abort(bye[-1]) imaplib.abort: [UNAVAILABLE] Temporary System Error

When i run the same script on a different machine. Its working fine. I am assuming that the host has been blacklisted or something like that.
What are my options ?
I cant generate the Credentials (Gmail API) as this is under company domain account.
Comment: Thanks guys. Its working now. The issue was that the google blocked our network.. because of multiple attempts. I tried that unlock URL from a different URL and it didnt work. The catch is that, we have to run that URL in the machine where you are trying to run the script. Hope it may help someone :)
Comment: Gmail has set some internal limitations like downloading. Check that limit.
https://support.google.com/a/answer/1071518?hl=en
Gmail will not showing appropriate error. Another machine IP address is different so that same code is working on his machine.
Comment: bandwidth cannot be exceeding the allowed limit. as there are only 3-4 mails from yesterday.
Comment: Take call from google support, may your IP is blocked. It happened with me some months ago.
Comment: Do you have scope https://mail.google.com/. If your account is locked, you can unlock it using this link https://om4.com.au/google-apps-gmail-invalid-credentials-unlock-captcha/
Comment: Focus on working out why your credentials are invalid... the system error is possibly not your fault, but the credentials certainly are.
Answer: try with:
1)
https://myaccount.google.com/lesssecureapps?pli=1
2) Gmail Settings -> Forwarding and POP / IMAP -> IMAP Acess to Enable IMAP
Comment: As like @Nv7, the above answers does not work for me too.
Comment: Google Account setting "Less secure app access" does no longer work (February 2023). Using the link above shows the message "This setting is no longer available".
Comment: Hi, welcome to Stack Overflow. Please provide context for links.
Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it's there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. https://stackoverflow.com/help/how-to-answer
Comment: Thank you! None of these answers helped but this one. Wish it was marked as the right answer.
Comment: this answer should be the accepted one since it is probably the most prevalent cause for the issue.
Comment: this didn't work for me
Answer: Some apps and devices use less secure sign-in technology. So we need to enable Less secure app access option from gmail account.
Steps:

Login into Gmail
Go to Google Account
Navigate to Security section
Turn on access for Less secure app access

By following above steps, issue will be resolved.
Comment: Seems this option isn't available anymore.
Answer: This can be solved in two steps:

Turn on the Less secure app access at: Google Account> Security> Less secure app access
Enable the  IMAP Access at: Gmail Settings> Forwarding and POP / IMAP> IMAP Acess
Answer: Ensure you have entered the right password

Even after that if it is not working

Enable the IMAP Access at: Gmail Settings> Forwarding and POP / IMAP> IMAP Acess

Enable 2-factor authentication for the google account

then generate an app-specific password    (https://myaccount.google.com/apppasswords)

Use this newly generated password for imap login
Answer: Got the same error and it was fixed by getting the new google app password. Maybe this will work for someone
Answer: Thanks guys. Its working now. The issue was that the google blocked our network.. because of multiple attempts. I tried that unlock URL from a different URL and it didnt work. The catch is that, we have to run that URL in the machine where you are trying to run the script. Hope it may help someone :)
Answer: Google Gmail - Security - Less secure app access ... won't work anymore !
See  https://support.google.com/accounts/answer/6010255?hl=en
"To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password."
Regards
Diego
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Enable 2FA and generate App passwords, use this generated password with IMAP.
step 1: Enable 2FA
step 2: Generate App passwords
step 3: Enable IMAP access
Answer: Now Google has created set of libraries to read Gmail data, after creating project in API and Services on Google Cloud. Following link contains python quickstart guide for same:
https://developers.google.com/gmail/api/quickstart/python
After following the steps, when I got a link from my script to proceed through Browser after logging I was getting "Access Blocked: project has not completed the Google Verification process". Then I found this Youtube video, which solved this issue as well.

reading gmail is failing with IMAP


Create a database table depends on XML

Question: Is there an option to create a database table (SQL Server) automatically depends on a large XML data? Instead of creating the table manually.
, let say you have the xml with 50 nodes
 i need a pattern to create a table with the mentioned 50 columns automatically for one time Because i have a huge xml tree . My needs is to save time
Comment: Please provide further detail on how you are importing your XML data.
Comment: Please [edit] any clarifications directly into the question.
Comment: Im importing the xml from a webservice, my question is , let say you have the xml 1test50 , i need a pattern to create a table with the mentioned three column above . Because i have a huge xml tree . My needs is to save time
Answer: You can use Liquibase for XML based Database management on SQL Server.
First, you need to integrate your code base with Liquibase then need to convert your existing XML to Liquibase version XML like below. So, you can start to manage your database changes (including DDL and DML operations) via a DBMS Tool.
<code><databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">

    <changeSet id="1" author="bob">
        <createTable tableName="department">
            <column name="id" type="int">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="name" type="varchar(50)">
                <constraints nullable="false"/>
            </column>
            <column name="active" type="boolean"
              defaultValueBoolean="true"/>
        </createTable>
   </changeSet>
</databaseChangeLog>
</code>
https://www.liquibase.org/documentation/xml_format.html
https://www.liquibase.org/documentation/tutorials/mssql.html

Create a database table depends on XML


Designing/debugging complex data binding graphs in polymer

Question: As far as I can tell, most of the talks and resources on Polymer cover fairly trivial cases of data binding.
However, Polymer is a powerful tool that can in principle be used to build things like IDEs, WYSIWYG editors, or even simple games; as long as the total number of elements on the page is kept fairly small (certainly <1000, but  ideally <100).
However, in these examples, the graph of data bindings can become very complex, and the results of a single event (e.g. a mouse click) can propagate/reverberate around the binding graph in hard-to-comprehend ways.
So, the question is, firstly are there any resources (videos/blogs etc.) that discuss best practices etc. for these types of complex scenarios; and two is there any chance of having a tool which generates a graphical representation of the binding graph.  Ideally such a graph could be rendered in the page, superimposed on the elements themselves.  In fact, one could imagine having a "record" feature, that tracked data propagation during an event and generated a GIF showing the data moving around the graph.
This may not be an ideal question for SO, but it didn't seem right as an issue on github either.
Comment: Here's a [video](https://www.youtube.com/watch?v=pAW4YDLtPVs&list=PLNYkxOF6rcICc687SxHQRuo9TVNOJelSZ&index=12) on data flow from this week's Polymer summit:
Comment: @Maria - yes, I was at the summit.  That was one of the more in depth looks at binding, but it was still fairly trivial.  I'm interested in how to deal with greater levels of complexity.
Answer: That's the reason why you should use an external state management framework such as redux for complex apps.
You can use the polymer-redux behavior which is a simple behavior that allows you to interact with redux.
You basically split up your components in Presentational and Container Components. The presentational polymer components are your leaf components that are unaware of redux and only take in data and emit events. The container components implement the redux behavior and dispatch actions for state changes and pass data to their childs (usually presentational components).
The state is stored globally and all the state modifications happen in reducers that you can easily unit test. The advantage is that you can use the redux-devtools to do time travel debugging and also visualize your state as a graph
Comment: That certainly looks helpful, but having loads of events doesn't seem like idiomatic polymer..unless you just use the auto-generated prop change events ( registered when notify is true)...it also seems a shame to require that visual components always be paired with a logic component.
Comment: In reference to my second point, I remember the pagination component demoed in one of the summit talks (a non-googler guy showing off a women's shopping app). This component was both visual and logical.
Comment: What do you mean with "loads of events" ? The idiomatic way in Polymer is usually that data flows down via properties/attributes and data flows upwards via events.  The only difference when introducing redux is that you don't have to pass all the data along the DOM tree. The container elements allow you to subscribe to slices of the state tree that they are interested in. Also a container component can be both visual as well as logical but you should aim to have as many re-usuable visual elements and when needed a container component in between