Hibernate trying to set field value to object

Question: Trying to use Hibernate from scratch for first time.
I have entity class:
package centaurus.domain;

import javax.persistence.*;

@Entity
@Table(name="users")
public class Player {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private int id;

    @Column(name="email")
    private String email;

    public Player(){};

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

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

    public int getId() {
        return id;
    }
}

DAOimpl:
    package centaurus.service;
import centaurus.domain.Player;

import restx.factory.Component;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

@Component
public class PlayerDAOimpl implements PlayerDAO{
    private static SessionFactory factory;

    public PlayerDAOimpl() {
        try{
            factory = new Configuration().
                    configure().addAnnotatedClass(Player.class).
                    buildSessionFactory();
            //
        }catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }

    }

    public Player savePlayer(Player player){
        Session session = factory.openSession();
        Transaction tx = null;
        Integer playerID = null;

        try{
            tx = session.beginTransaction();

            playerID = (Integer) session.save(player);
            tx.commit();

        }catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace();
        }finally {
            session.close();
        }
        return player;
    }

    public Player getPlayer(Integer playerId){
        Session session = factory.openSession();
        try{
            Player player = (Player)session.get(Player.class, playerId);
            return player;
        }catch (HibernateException e) {

        }finally {
            session.close();
        }
        return null;
    }
}

to demo the error i made it add a player on startupscript.
and error:
 -- RESTX >> LOAD ON REQUEST << >> DEV MODE << >> AUTO COMPILE <<
 -- for admin console,
 --   VISIT http://127.0.0.1:9091/api/@/ui/
 --

2016-05-31 21:42:48,901 [main            ] [          ] INFO  restx.Apps - can't enable Apidocs doclet: make sure tools.jar is in your classpath
2016-05-31 21:42:49,978 [pool-1-thread-1 ] [          ] INFO  restx.classloader.CompilationManager - compilation finished: 12 sources compiled in 1.015 s
2016-05-31 21:42:50,061 [main            ] [          ] INFO  restx.Apps - can't enable Apidocs doclet: make sure tools.jar is in your classpath
2016-05-31 21:42:50,078 [main            ] [          ] INFO  restx.classloader.CompilationManager - watching for changes in [src/main/java, src/main/resources]; current location is /home/arthur/elorhia/api/.
2016-05-31 21:42:50,145 [main            ] [          ] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.1.0.Final}
2016-05-31 21:42:50,146 [main            ] [          ] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2016-05-31 21:42:50,147 [main            ] [          ] INFO  org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
2016-05-31 21:42:50,802 [main            ] [          ] INFO  o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2016-05-31 21:42:50,851 [main            ] [          ] WARN  org.hibernate.orm.connections - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2016-05-31 21:42:50,856 [main            ] [          ] INFO  org.hibernate.orm.connections - HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/andromeda]
2016-05-31 21:42:50,857 [main            ] [          ] INFO  org.hibernate.orm.connections - HHH10001001: Connection properties: {user=api, password=****}
2016-05-31 21:42:50,858 [main            ] [          ] INFO  org.hibernate.orm.connections - HHH10001003: Autocommit mode: false
2016-05-31 21:42:50,860 [main            ] [          ] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 1 (min=1)
2016-05-31 21:42:51,090 [main            ] [          ] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2016-05-31 21:42:51,321 [main            ] [          ] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.0.1.Final
START SCRIPT!
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String centaurus.domain.Player.email] by reflection for persistent property [centaurus.domain.Player#email] : centaurus.domain.Player@507b79f7
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:43)
    at org.hibernate.property.access.spi.GetterFieldImpl.getForInsert(GetterFieldImpl.java:58)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValuesToInsert(AbstractEntityTuplizer.java:521)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValuesToInsert(PojoEntityTuplizer.java:228)
    at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValuesToInsert(AbstractEntityPersister.java:4701)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:254)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at centaurus.service.PlayerDAOimpl.savePlayer(PlayerDAOimpl.java:39)
    at centaurus.Dbmaintain.start(Dbmaintain.java:26)
    at restx.factory.Factory.start(Factory.java:846)
    at restx.RestxMainRouterFactory.build(RestxMainRouterFactory.java:450)
    at restx.RestxMainRouterFactory.newInstance(RestxMainRouterFactory.java:70)
    at restx.servlet.RestxMainRouterServlet.init(RestxMainRouterServlet.java:74)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:519)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:331)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:747)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:706)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:492)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.Server.doStart(Server.java:277)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at restx.server.JettyWebServer.start(JettyWebServer.java:109)
    at restx.server.JettyWebServer.startAndAwait(JettyWebServer.java:114)
    at centaurus.AppServer.main(AppServer.java:30)
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field centaurus.domain.Player.email to centaurus.domain.Player
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39)
    ... 40 more
2016-05-31 21:42:51,673 [main            ] [          ] INFO  restx.monitor.MetricsConfiguration - registering Metrics JVM metrics
2016-05-31 21:44:41,646 [pool-2-thread-1 ] [          ] INFO  restx.classloader.CompilationManager - compilation finished: 1 sources compiled in 86.94 ms

it looks like its trying to set the email field to the player object.
I cant work out why!, what have I done wrong?
EDIT: as requested i have added the code creating the player and calling the dao
package centaurus;

import centaurus.domain.Player;
import centaurus.service.PlayerDAO;
import centaurus.service.PlayerDAOimpl;
import restx.factory.AutoStartable;
import restx.factory.Component;

import javax.inject.Named;

@Component
public class Dbmaintain implements AutoStartable{
    private PlayerDAO playerDAO;

    public Dbmaintain(@Named("PlayerDAOimpl") PlayerDAO playerDAO) {
        this.playerDAO = playerDAO;
    }

    public void start(){
        System.out.println("START SCRIPT!");

        //test
        Player p = new Player();
        p.setEmail("test");
        playerDAO.savePlayer(p);

        try {
         //  URL configurationUrl = new File("dbmaintain.properties").toURI().toURL();
          // MainFactory mainFactory = new MainFactory(configurationUrl);
          // DbMaintainer dbMaintainer = mainFactory.createDbMaintainer();
          // dbMaintainer.updateDatabase(false);
        } catch(Exception e) {

        }
    }
}

edit added git link if people wanted other bits:
https://github.com/ArthurGibbs/Centaurus-
Comment: Please show the code where you're populating your player object.
Comment: A wise tip: `SessionFactory` is an expensive object. You should not create it for each `DAO` implementation. Instead, define a `HibernateUtil` class and define a static object of `SessionFacory` there and use that object each time you require it from there.
Comment: how do i get around addAnnotatedClass, with hibernateUtil class , the only tutorials i have found are either have bean mappings or specify the class in the factory
Comment: I have added a hibernate utils class, i added the mapping the the hibernate config via linking the annotated class
Comment: @Arthur I also facing the same issue. Did you able to fix  this ?
Answer: How are you setting/creating your Player?
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field centaurus.domain.Player.email to centaurus.domain.Player

This says, that there is an attempt to store object of class centaurus.domain.Player into a String field. For futher explanation, attach che actual code that is modifying/creating player perfore passing it to DAO
Comment: Thanks for the reply, I have added the code as requested, i have the feeling its hibernate doing the incorrect setting, probably due to something weird i have done.
Comment: @Arthur you are right, notting fancy can be done here. Try cleaning your env. Shutdown webserver, remove deployment, clean and rebuild the project and finally try to do fresh deployment.
Comment: same error after cleaning all that can be cleaned. the mystery continues.
Comment: @Arthur this can be a problem. I am programmer, not a wizzard:) But have faith, most probably somebody will have the answer to your issue. The only essence is the time...
To be honest I have no idea what could cause such exception in your situation. It would be wise of you to run the debugger and trace the code step by step to check why hibernate wants to set String field's value as Player object
Comment: Bit of delay, (spare time coding project) i debugged the code and it appears to throw on the declaring line of org.hibernate.internal.sessionimp.class save() ,, ie before the first line.   maybe some weird interceptor stuff going on?
Comment: @Arthur even so, interceptors are still standard code and you should be able to debug it as well. I dont understand what do you mean by: "org.hibernate.internal.sessionimp.class save() ,, ie before the first line. " it would be much better to edit your post, paste related code, and pinpoint where actual exception is beeing thrown.
Answer: I have used your exact class Player to execute this piece of code and got no error at all. A row is inserted in table USERS correctly.
public class TestPlayer {

public static void main(String[] args) {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestDB");

    EntityManager em = emf.createEntityManager();

    Session session = (Session) em.getDelegate();

    Transaction tx = session.beginTransaction();

    try {

        Player p = new Player();
        p.setEmail("email");

        session.save(p);

        tx.commit();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        em.close();
        emf.close();
    }

}
}

The problem is not in the entity class. Maybe some changes that you made do not refresh correctly on deploy.


Manifold structure on a set of matrices

Question: Let $Ω$ denote the $((n+1)×(n+1))$ matrix given by
\begin{bmatrix}
-1&0\\0&I_n
\end{bmatrix}
where $I_n$ is the $n×n$ identity matrix.

Let $X=\{A∈M_{n+1}(\mathbb{R}):A^tΩA=Ω\}$. How can I show that $X$ is a manifold? What will its dimension be? I am thinking of using the determinant map. It is easy to see that the determinant of each element of $X$ is $1$ or $-1$. What next? Any help will be appreciated.
Comment: Maybe write $A$ by blocks? The last $n\times n$ block is the set of orthogonal matrices, to begin with...
Comment: https://ncatlab.org/nlab/show/Lorentz+group
Comment: Regular value theorem?
Answer: $X$ is a group, so a neighbourhood of the identity matrix $I$ is mapped to a neighbourhood of any $A \in X$ by the map
$B \mapsto AB$.  So it suffices to prove that a neighbourhood of $I$ is a manifold.  This can be done using the implicit function theorem.

Manifold structure on a set of matrices


Multiple choice question creation change checkbox to radio

Question: Using quiz module, I am creating Multiple Choice question. In that there is a check box to select the correct answer. Check box enables users to select multiple answers for a single question, but I want the users to select only one answer for a question. Is there any configuration to change that or can I change the check box to radio button. If so how can I change it to radio button? Should I change it in code base or is there any module available?
Answer: If I'm not mistaken, as long as you don't check the "Multiple Answers" option in the answer settings tab, your answers for that question will render with radio buttons on the front-end. This doesn't change the checkboxes to radio buttons when you are editing a question, but that's because you are supposed to be able to mark multiple correct answers for each question, if need be.


Keeping a Pure CSS Carousel in a fixed postion

Question: I have a number of links that run down a webpage and that all link to a popup gallery.
Whenever I click a link, it jumps to end of the webpage, but the carousel is shown at the top of the page.
I am trying to keep the pure CSS carousel in the same postion when a link is clicked to open it.
Also when the "next" button is clicked in the carousel, it also jumps up the bottom, which it shouldn't do.
Here's what I have already.
Any ideas?
Thanks

 .lightbox__slide img {
  position: absolute;
  z-index: 30;
  max-width: 90%;
  max-height: 80%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-name: hide;
  animation-duration: 0.5s;
  animation-iteration-count: 1;
  animation-direction: linear;
  animation-fill-mode: forwards;
}
 .lightbox__slide:target .btn { display: block; }
 .lightbox__slide:target img {
  opacity: 0;
  animation-name: show;
  animation-duration: 0.5s;
  animation-iteration-count: 1;
  animation-direction: linear;
  animation-fill-mode: forwards;
}
 .lightbox__slide:target ~ .lightbox__bg {
  position: relative;
  background:white;
  opacity: 0.6;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

 @-webkit-keyframes show { 0% { opacity: 0; } 100% { opacity: 1; } }
 @-webkit-keyframes hide { 0% { opacity: 1; } 100% { opacity: 0; } }
 .btn {
  position: absolute;
  z-index: 20;
  display: none;
  transition: all 0.2s;
  width: 40px;
  height: 40px;
  margin: -20px 0 0 -20px;
  text-align: center;
  line-height: 40px;
  text-decoration: none;
  color:black;
}
 .btn:hover {background: rgba(255, 255, 255, 0.8);}
 .btn--close { top: 40px; right: 20px; }
 .btn--close:after { content: '\2715'; }
 .btn--left { top: 50%; left: 40px; }
 .btn--left:after { content: '⯇'; }
 .btn--right { top: 50%; right: 20px; }
 .btn--right:after { content: '⯈'; }

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Here is a fiddle.
Answer: pls try this... we add here lightbox fixed
html

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

Link

Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line

css
.feature_category{
  position:relative;
  z-index:999;
}
.lightbox{
  position:fixed;
  top:0;
  right:0;
  width:100%;
  height:100%;
}
.lightbox__slide img {
     position: absolute;
     z-index: 30;
     max-width: 90%;
     max-height: 80%;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
     animation-name: hide;
     animation-duration: 0.5s;
     animation-iteration-count: 1;
     animation-direction: linear;
     animation-fill-mode: forwards;
}
 .lightbox__slide:target .btn { display: block; }
 .lightbox__slide:target img {
     opacity: 0;
     animation-name: show;
     animation-duration: 0.5s;
     animation-iteration-count: 1;
     animation-direction: linear;
     animation-fill-mode: forwards;
}
 .lightbox__slide:target ~ .lightbox__bg {
     position: relative;
     background:white;
     opacity: 0.6;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     z-index: 1;
}

 @-webkit-keyframes show { 0% { opacity: 0; } 100% { opacity: 1; } }
 @-webkit-keyframes hide { 0% { opacity: 1; } 100% { opacity: 0; } }
 .btn {
     position: absolute;
     z-index: 20;
     display: none;
     transition: all 0.2s;
     width: 40px;
     height: 40px;
     margin: -20px 0 0 -20px;
     text-align: center;
     line-height: 40px;
     text-decoration: none;
     color:black;
}
 .btn:hover {background: rgba(255, 255, 255, 0.8);}
 .btn--close { top: 40px; right: 20px; }
 .btn--close:after { content: '\2715'; }
 .btn--left { top: 50%; left: 40px; }
 .btn--left:after { content: '⯇'; }
 .btn--right { top: 50%; right: 20px; }
 .btn--right:after { content: '⯈'; }


Adding an Image field in webform module

Question: I am a newbie to drupal 7 and just started working with it a couple of months ago. My problem is I am making a "webform" where the user filling the form should upload his image. But as there is no such field I am not able to understand how to do it.....
I also tried the "entityform"  but as I install it and enable it, the edit links all over my website starts throwing an exception...
So please help me. Any help will be appreciated.
Thanks in advance.
Comment: Isn't there a file field available when you try to create a new webform? File field should be in the core in drupal 7.
Answer: To add an image field to a webform:

To go the webform tab where you manage the fields.
Add a new field of type file:
On the new field configuration page it's a good idea to set an Upload directory for your images. This means all the images upload from this field will sit in a particular folder in your files directly and help prevent too many files from sitting in one folder. You can also choose what types of files you want to allow users to upload. For an image field I would suggest only gif, jpg, and png.
Set any other settings such a label or display settings as required.
Finally save the component.
Now when you visit the frontend of your webform you should see your new field:
Answer: Try Plupload for a start. Hope this helps.
Comment: Plupload is for uploading multiple images at the same time and is not required for just uploading an image to a webform. Also integrating plupload and webforms would be a considerable challenge!
Answer: In Webform - If you navigate to manage field of it. Then you should will be able to see field type as Image. Just add one field with that Image type after that you can upload your image.
If you are not able to see then check your Drupal db log. Might be there is error you will get to fix.
Comment: There is no image field type in webform. For images the file field type is used.
Comment: Yes, we can use default file as field type then we can give image type extensions in settings.
Answer: I'd recommend you to try Webform Select Image. This module adds a new image component to the webform.

The purpose of this module is to add an images select component for webform (checkboxes or radios buttons).

Download and enable this module

Go to webform components admin page

Choose "Select image"

Upload your image, choose image style and other component settings
Comment: This functionality requested is available with just the webform module using the file field type. The module you linked to is not for uploading images at all, but instead for adding images to select options.

Adding an Image field in webform module


Is there an elementary proof of the following statement?

Question: There can never exist an infinite sequence of consecutive integers of the form:
<code>                             XY±X±Y where X,Y∈N
</code>
Clarification:
An example of such an integer would be 4, as;
4=(2)(2)+2-2
Edit:
The statement was in fact disproved, but I wonder if it is possible to disprove the statement;
There can never exist an infinite sequence of consecutive integers of the form:
<code>                             MXY±X±Y where X,Y,M∈N where M > 2
</code>
Comment: As far as I know, there can *never* be an infinite string of integers whatsoever *and still* be considered an integer number...and whta you wrote hardly makes any sense without more, way more explanation as to what you're trying to exrpess.
Comment: What does anything mean in this question?  Presumably by "infinite string of consecutive integers", you mean a "[sequence](http://en.wikipedia.org/wiki/Sequence) of integers", though that's not particularly clear.  Also, still no idea what `XY±X±Y where X,Y∈N` means in reference to this purported sequence.
Comment: @Omnomnomnom: I understand it so that every integer in the sequence is supposed to have that form (that is, there exists x,y and ++ +- -+ --)
Comment: What do you mean by "consecutive" here?
Comment: Yes  user2345215 that is how I meant the question.
Comment: Note in your update that $x=1$ in the expression $2xy\pm x\pm y$ yields one equation $y-1$, which disproves for $M \gt 1$ but not for $M\gt 2$.
Comment: Yes Ok I will change that, thanks.
Answer: Let $x=2,$ then we have $2y\pm2\pm y$ which is four equations, one of which is $y-2$.  Taking $y\in[3,\infty)$ we have the set of natural numbers $\{1,2,3,\dots\}$.
Note that the same is true (that there is an infinite sequence of consecutive integers of this form) for the expression $2xy\pm x\pm y$ but not (or at least, not proven) for $3xy\pm x\pm y$ and also not for $xy+x+y, x,y\in\Bbb N.$  This last expression yields only composite numbers (subtract $1$) and it is useful as an equation form of a sieve for the prime numbers.
Edit:
To follow along with the updated question, consider the following construction:
$$\begin{align}ak\pm 1&=(ax\pm 1)(ay\pm 1)\\
&=a^2xy\pm ax\pm ay\mp 1\\
\implies k&=axy\pm x\pm y
\end{align}$$
When $a\in \{1,2\},$ it is possible (as in the first example) to deconstruct $k=axy\pm x\pm y$ into an equation of the form $k=x-u,$ and this obviously results in the entire set of values of $x$ being directly transferred to $k$ with a $u$ offset.  But as soon as $a\gt 2$ this simple deconstruction is no longer possible.
In fact, for $a\in\{3,4,6\}$ we get varying subsets of twin prime related numbers.  For example, when $a=6$ then every $k$ which cannot be written in the form $6xy\pm x\pm y$ is a number such that $6k-1, 6k+1$ are a twin prime pair.  This (for $a=6$) was proven by Maria Suzuki and logged in the January 2000 edition of American Mathematical Monthly.
So the updated question belongs to the realm of "open conjecture" since at least three of the $M$ values listed hinge directly upon the Twin Primes conjecture.
Comment: Ok thanks I didn't see that.


Trying to Wrap my brain around HTML character encodings and htmlspecialchars()

Question: I've been trying to get a proper understanding of character-encoding in HTML, and was hoping someone might be able to help me out with a small problem I've been encountering.
I'm pulling a paragraph of text from a mySQL database table (latin-1).  The paragraph happens to have a right-single-quote in it, and I read it was a good idea to run that sort of string data through htmlspecialchars() before displaying on the screen, so I tried...
// So let's say $paragraph is a string like "The customer's computer is on".

echo htmlspecialchars($paragraph);

This renders to the screen as "The customer'’s computer is on". At first I thought that was weird, because I expected the ’ to automatically be rendered as a right-single-quote, but then I thought maybe I'd forgotten the meta-tag.  Since the database table was latin-1, I thought the following tag would help it render correctly...
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">

But still no dice, it's still showing up as ’.  I also tried...
htmlspecialchars($paragraph, ENT_QUOTES, 'ISO-8859-1');

But it's still rendering the same.  If I don't even use htmlspecialchars() it renders to the screen as expected, but I guess I'm just trying to understand why htmlspecialchars() doesn't render the way I was expecting.  Maybe I'm completely misunderstanding the functions and how they're supposed to be rendering in the browser, so any help on this would be really appreciated, thanks!
Edit:  To add some more oddness to the equation, I tried manually typing in ’ into the HTML document, and it does in fact render as right single-quotes.  However, when I look at the HTML I see ’ where the htmlspecialchars() is outputting, instead of the right single-quote I was expecting.  Does anyone know why that might be?  Is that expected functionality?
Answer: Refer to this post:
HTML code for an apostrophe
The apostrophe and the right single quote are two different characters. Perhaps it is rendering correctly because the apostrophe is what is in the db?
Comment: Is that what htmlspecialchars is supposed to do though?  I guess I thought when it places the html-entity into the document, I thought the browser would process it and display it as an actual right-single-quote on the screen.  Is that line of thinking incorrect?  Is it really supposed to just render as the unicode text?


How does GET_LOCK('lockname', 0) of MariaDB/MySQL work?

Question: I have found the use of GET_LOCK('lockname', 0) of MariaDB in a java application that I am working on.
The timeout value is used as 0 here. It should work in non-blocking fashion, I suppose. But, after getting some exceptions in the log file, I have got the impression that it is still trying the get the lock using a default timeout time. Applying the call of IS_FREE_LOCK('lockname') before  GET_LOCK call makes the application run smoothly.
My question is, what is the impact of using 0 as the timeout value here?
Comment: Note that using `GET_LOCK` isn't a great practice. Usually you can achieve a much less blocked code using transactions or better code structure. `GET_LOCK` isn't supported in Galera if you ever get to the stage of scaling your application.
Answer: Have you determined the timeout?. I can't reproduce the problem from the command line:
Session 1:
MariaDB [(none)]> SELECT GET_LOCK('lock1', 10);
+-----------------------+
| GET_LOCK('lock1', 10) |
+-----------------------+
|                     1 |
+-----------------------+
1 row in set (0.000 sec)

Session 2:
MariaDB [(none)]> SELECT GET_LOCK('lock1', 0.5);
+------------------------+
| GET_LOCK('lock1', 0.5) |
+------------------------+
|                      0 |
+------------------------+
1 row in set (0.500 sec)

MariaDB [(none)]> SELECT GET_LOCK('lock1', 0);
+----------------------+
| GET_LOCK('lock1', 0) |
+----------------------+
|                    0 |
+----------------------+
1 row in set (0.000 sec)

Comment: The scenario I am using is to use it from two Java clients concurrently, I have got so many exceptions in the log file like the following: _`java.sql.BatchUpdateException: Lock wait timeout exceeded; `_
In the application code, if GET_LOCK('lock1', 0) returns zero, the update query should not have executed. I suspect, GET_LOCK('lock1', 0) tries to continue to get the lock even if the timeout value is set to zero. The issue is fixed by applying IS_FREE_LOCK('lock1') call before GET_LOCK('lock1', 0) call. But I initially expected GET_LOCK call by using zero timeout would be sufficient here.
Comment: the JDBC batch is not using GET_LOCK(), you're probably getting MySQL Error Code: 1205. "Lock wait timeout exceeded; try restarting transaction"
Answer: "lock wait timeout" has nothing to do with GET_LOCK.  It only applies to InnoDB transactions.  The default for innodb_lock_wait_timeout is 50 seconds.  (In my opinion, that is much too high.)
InnoDB transactions should be designed to finish in very few seconds.  Never keep a transaction open while waiting for user interaction; a potty break could lead to "lock wait timeout".
I see that it is a "BatchUpdate".  Is this loading a lot of data?  Is it coming from some slow source?  Could you use autocommit and not put the entire load into a single transaction?
Another thing...  If you start a transaction (BEGIN or START TRANSACTION), then do GET_LOCK('foo', 51), and 'foo' is not available, you are asking for "wait lock timeout".
Please provide the bigger picture (BatchUpdate, reason for GET_LOCK, etc) so we can dig deeper.

How does GET_LOCK(‘lockname’, 0) of MariaDB/MySQL work?


how to download zip file through browser

Question: I have written a module that creates a zip file in the /tmp and then downloads the zip file through browser i.e. it will be downloaded in the ~/Downloads directory by itself.
I don't want to use hook_file_download() because it executes everytime you try to download a file, but I want to be specific while downloading. The above code snippet is written in the same function that creates the zip file.
I have taken the help of davidwalsh blog to create the zip file.
I can create the zip file in /tmp directory, but how to download the zip file.
My code looks like this:
$fp = fopen($filesystem_filepath, 'rb');
header('Content-type: application/octet-stream');
header('Content-Length: '. filesize($filesystem_filepath));
fpassthru($fp);

At first I tried downloading simply using header() function and then after more googling I took the help of readfile($filesystem_filepath) instead of fpassthru($fp) but its not working.
Answer: You don't mention exactly what's not working, but at a guess it might be that the download works in all browsers except Internet Explorer?
IE is an annoyance when it comes to forcing downloads, you really have to go around the houses to get all versions to respect what you're trying to do.
Here's the code I use to force downloads, and it works cross browser (updated to address @MPD's comment below):
function force_file_download($path, $filename) {
  // Most of this is only necessary because of IE
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"$filename\";" );
  header("Content-Transfer-Encoding: binary");

  $fp = fopen($path, 'rb');
  fpassthru($fp);
  exit();
}

You'd use it in a page callback like this:
force_file_download($filesystem_filepath, 'file.zip');

That code works perfectly for me for any type of file, cross-browser, and if you change the exit() to drupal_exit(), it will also work great for Drupal 7 (currently it's a Drupal 6 snippet).
Comment: The "application/octet-stream" is part of the forced download thing.  If you use the proper MIME type, then the browser may decide to handle it instead of prompting for download.
Comment: the file download is not working. what exit() exactly does? what if I dont write exit() because my function returns value on zip file creation
Comment: @MPD Good point, I've updated the answer
Comment: @subhojit777 [`exit()`](http://php.net/manual/en/function.exit.php) terminates the current script; running `fpassthru()` should be the last thing your script does, you should do any other processing you need to before-hand


Can one do one-hot encoding with Count Vectorizer?

Question: I am new to machine learning. I am stuck with a doubt about whether we could do one-hot encoding using bag of words (e.g. scikit-learn's CountVectorizer)?
Comment: what is count vectorizer, and what is the application -- perhaps text mining?  for "words," do you mean word-document frequencies?
Comment: @NXGLogic count vectorizer is a function of scikit learn library in python. It is used in text mining to from bag of words representation of vectors from a corpus of words.
Comment: see this answer (https://stats.stackexchange.com/a/442663/32398), where one-hot coding was proposed for text mining.  You need word frequencies in each document (i.e., # times each word appeared), and not 0,1 coding for whether a word was present or not (y/n).
Answer: Yes, you can! However, their primary purposes are different. CountVectorizer is generally used for featurization of text data whereas OneHotEncoder is only used for featurization of categorical variables.
Comment: Sorry—how do you propose to make the data one-hot with scikit-learn's `CountVectorizer`? In the obvious way of using it, the vector representation would be multi-hot.
Comment: CountVectorizer creates a new feature for each unique word in the document, or in this case, a new feature for each unique categorical variable. However, this may not work if the categorical variables have spaces within their names (it would be multi-hot then as you pointed out)
Comment: There's one _feature_ per token in the training corpus, but the representation of a _document_ is a fixed-length, multi-hot vector. CountVectorizer is used to create a bag (or set, if `binary=True`) of words representation of a document.


Problema em requisição com jQuery ($.ajax) e Angular ($http)

Question: Estou tentado obter da forma mais rápida e direta alguns dados de uma API. Utilizando o Postman eu consigo isso facilmente apenas dando um GET na url (http://www.wsfebracis.com.br/Json/ListarGrupos), assim obtenho:
{
  "error": 0,
  "grupos": [
    {
      "Titulo": "A inteligência emocional do seu corpo",
      "ID": 1
    },
    {
      "Titulo": "Sua inteligência emocional em família",
      "ID": 2
    },
    {
      "Titulo": "Sua inteligência emocional em sociedade",
      "ID": 3
    },
    {
      "Titulo": "Sua inteligência emocional no trabalho",
      "ID": 4
    },
    {
      "Titulo": "Sua inteligência emocional nas férias",
      "ID": 5
    },
    {
      "Titulo": "Sua inteligência emocional no dia a dia",
      "ID": 6
    }
  ]
}

Porém quando eu tento fazer um GET utilizando jQuery ou Angular, não consigo. Abaixo seguem as duas chamadas e os erros que eu obtenho.

Utilizando jQuery
$.ajax({
  type: 'GET',
  dataType: 'JSONP',
  url: 'http://www.wsfebracis.com.br/Json/ListarGrupos/',
  success: function(data) {
    console.log(data);
  },
  error: function(e) {
    console.log(e);
  }
}).done(function( data ) {
  console.log("done ", data);
})
.fail( function(xhr, textStatus, errorThrown) {
    console.log('erro');
    console.log(xhr.responseText);
    console.log(textStatus);
    console.log(errorThrown);
});

Object {readyState: 4, status: 200, statusText: "success"}
erro
undefined
parsererror
Error: jQuery111108493785087484866_1448911631891 was not called(…)

Utilizando Angular
$http.jsonp('http://www.wsfebracis.com.br/Json/ListarGrupos/ListarGrupos')
.success(function(data, status, headers, config) {
  $log.error(data);
  $log.error(status);
  $log.error(headers);
  $log.error(config);
})
.error(function(data, status, headers, config) {
  $log.log(data);
  $log.log(status);
  $log.log(headers);
  $log.log(config);
});

undefined
(d){b||(b=ad(a));return d?(d=b[F(d)],void 0===d&&(d=null),d):b}
Object {method: "JSONP", transformRequest: Array1, transformResponse: Array1, url:
  "http://www.wsfebracis.com.br/Json/ListarGrupos", headers: Object}

Obs.: Eu consigo ver o retorno, porém ele é apresentado como erro, assim não consigo manipular os dados. Veja!

Importante! Não tenho acesso a API, por isso serão bem vindas soluções que se prendam a alguns dos métodos propostos (jQuery ou Angular).
Answer: Vai ter que modificar o retorno do serviço, já que é um JSONP.
Retorno atual:
{"error":0,"grupos":[{"Titulo":"A inteligência emocio...}

Retorno correto:
callback({"error":0,"grupos":[{"Titulo":"A inteligência emocio...})

https://stackoverflow.com/questions/19165925/jsonp-call-showing-uncaught-syntaxerror-unexpected-token
https://stackoverflow.com/a/19166256/1803238
Comment: JBJ era justamente isso que eu não gostaria de fazer. Pois mexer na API implica mexer em um sistema desktop legado.
Comment: Pode usar CORS no serviço?
Answer: Você está tentando usar JSONP para acessar a API porém a mesma não parece suportar o mesmo.
Se esta API é sua e você pode modificá-la existem duas coisas que podem ser feitas, uma delas é dar suporte a JSONP, porém teria que ter cuidado com quem já usa ela e espera que o resultado seja simplesmente JSON, e a outra seria adicionar os cabeçalhos do CORS para permitir o acesso a esta API de outros domínios, lembrando que isso deve ser feito no lado da API e não do lado de quem a consome.
Se estas alternativas não forem possíveis existe sempre a possibilidade de você fazer as requisições no servidor. Basicamente você cria uma API nova em seu site que funcione como uma espécie de proxy para a API externa, assim usaria o jQuery ou Angular para fazer a requisição para o servidor que hospeda o seu site, onde não existem restrições e este faria a requisição para a API externa.
Comment: O jeito será mexer na API. Obrigado pelo esclarecimento.


Are B&W images of digits linear seperable

Question: Given an image, expressed in the vector $\vec{v} = (v_1, \dots, v_n)\in \{0,1\}^n$
The vector $\vec{v}$ can represent images of the numbers 0 to 9. How do I know if this is linear seperable? Given the high dimension when we get big pictures, it becomes hard to reason about this, altough I think the answer is pretty straightforward.
What is a correct and (preferably) mathematical way of reasoning about this? I believe they are not linearly seperable, but I wouldn't know how to prove this.
Answer: First the question is not very clear to me. We we say "linear separable", we usually mean binary classification. Because when you draw a line or hyperplane, the data points will be divided into two parts. But in your question, it seems you want to do multi-class classification. then "linear separable" is not well defined.
I will focus on binary classification case. We can use linear programming to do it.
Details can be found in Testing for Linear Separability with Linear Programming in R.
Note, GLPK is just one solver, and R is the interface to build the problem. If you know other solvers, you can directly write other code (say python) to build MPS file or LP file to solve.
Comment: Well, we could start looking at just one class and its complement right? If we can show those are not linear seperable we're done.
I was mostly wondering if there's a quick and elegant way to show something is not linear seperable


Verifying trig identities

Question: $$\sec(2x)=\frac{\sec^2x+\sec^4x}{2+\sec^2x-\sec^4x}$$
I have no idea how to verify this. I've tried changing it into cosine but it doesn't work.
Comment: I've edited your post to include MathJax. Please verify that it's correct and says what you intend.
Comment: Change each $\sec(x)$ by $\frac{2}{z+z^{-1}}$ and $\sec(2x)$ by $\frac{2}{z^2+z^{-2}}$. Clear denominators and check that the polynomials in both sides are equal. If they are the identity is true.
Answer: Note
$$\dfrac{\sec^2{x}+\sec^4{x}}{2+\sec^2{x}-\sec^4{x}}=\dfrac{\sec^2{x}(1+\sec^2{x})}{(1+\sec^2{x})(2-\sec^2{x})}=\dfrac{\sec^2{x}}{2-\sec^2{x}}=\dfrac{1}{2\cos^2{x}-1}=\sec{(2x)}$$
Answer: You can also use Wolfram Alpha http://www.wolframalpha.com to verify it
<code>Simplify[(Sec[x]^2+Sec[x]^4)/(2+Sec[x]^2-Sec[x]^4)]
</code>
Comment: Wolfram|Alpha would be an invalid way of verifying the identity if it had the identity automatically programmed into it (as it does many trig identities), because then it would be assuming the conclusion. After looking through the [documentation](http://functions.wolfram.com/ElementaryFunctions/Sec/introductions/TrigonometricsInMathematica/04/) for Mathematica (and by extension Wolfram|Alpha), it does not assume the identity, and is therefore a valid way of verifying it.
Comment: The question was how to verify an identity. Surely, using wolfram alpha is a valid way to verify it. I hasten to add that it is probably more reliable too than doing it by hand.

Verifying trig identities


Debian Preseed use whole device for LVM Physical Volume

Question: I have the following recipe for a preseed install (truncated for readability):
d-i partman-auto/expert_recipe string \
  boot-root :: \
    1 1 1 free \
      $iflabel{ gpt } \
      $reusemethod{ } \
      method{ biosgrub } \
    . \
    512 512 1074 ext2 \
      $defaultignore{ } \
      method{ format } \
      format{ } \
      use_filesystem{ } \
      filesystem{ ext2 } \
      mountpoint{ /boot } \
    . \
    2147 800 -1 $default_filesystem \
      $lvmok{ } \
      lvm_name { root } \
      method{ format } \
      format{ } \
      use_filesystem{ } \
      $default_filesystem{ } \
      mountpoint{ / } \
    . \
    100% 512 100% linux-swap \
      $lvmok{ } \
      in_vg{ vg_01 } \
      method{ swap } \
      format{ } \
    . \
    100 10000 -1 $default_filesystem \
      $defaultignore{ } \
      method{ lvm } \
      device{ /dev/sdb } \
      vg_name{ vg_01 } \
    [...]
    .

This makes almost what I want, the only issue is that partman-auto creates the Physical Volume inside a partition of /dev/sdb (i.e pvcreate /dev/sdb1).
What I really want is partman-auto to create the PV on the whole device (i.e pvcreate /dev/sdb).
The reason why I want to do this is simple: easy online (hot) extend. (This is for a virtual environment).
I have tried multiple solutions but none of them seems to be working like removing the PV from my recipe and adding to my preseed file:
d-i partman/early_command \
  string dd if=/dev/zero of=/dev/sdb bs=512 count=1; pvcreate -ffy /dev/sdb; vgcreate -fy vg_01 /dev/sdb

But this make the installer either fail or hang asking me what partition layout I want.
Please help me if you know how to accomplish what I want or even if you know that it's impossible with preseed only at this time.
Thank you.
Answer: It doesn't seem that partman (Debian Installer tool for partitioning) supports that.
I've filed a wishlist in Debian bug tracker, it's currently marked as "wontfix":
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=418519
Answer: Even before trying preseed configuration, in manual installation partman is not able to use an existing PV created first by pvcreate /dev/sda and go on with LV defitions.
For partman lack of partition table on main boot disk is a no-go situation.
Recent Linux kernel have fixed reboot requirement after partition table edition. So delete PV partition and create it again larger to match virtual disk size, and run partprobe to inform kernel about its new size to then invoke pvresize /dev/sda1: How to extend a Linux PV partition online after virtual disk growth


How do I calculate probability of reference category in logistic regression?

Question: I came across this quote from a paper by Pool and Doris (2021): "The 18–24 age group reported the highest levels of food insecurity, with 27.6% reporting being food insecure, as opposed to 8.2% of over 65-year-olds (odds ratio (OR) 2.45, 95% confidence interval (CI): 1.05; 5.75)." I'd like to understand how they calculated the probability of over-65s which was their reference group in the logistic regression they ran.
Example logistic regression output:
<code>  Coefficients:
            Estimate Std.  Error z value Pr(>|z|)
(Intercept) -2.457415 0.221487 -11.095  < 2e-16 ***
wave5       -0.510565 0.089884  -5.680 1.34e-08 ***
wave7       -0.360667 0.089068  -4.049 5.14e-05 ***
age_r2      -0.167394 0.163767  -1.022 0.306713
age_r3      -0.664402 0.171821  -3.867 0.000110 ***
age_r4      -0.898270 0.161779  -5.552 2.82e-08 ***
age_r5      -1.704232 0.162821 -10.467  < 2e-16 ***
age_r6      -2.909736 0.183640 -15.845  < 2e-16 ***
</code>
I want to find out what the probability of the outcome variable is for the reference categories e.g. wave4 and age_r1. Apologies if this is straightforward but I've really struggled to find an answer. How can I do this in R?
Reference: Pool, U. and Dooris, M., 2021. Prevalence of food security in the UK measured by the Food Insecurity Experience Scale. Journal of Public Health,.
Comment: You could use the emmeans package to get the logit of each group. And then transform the logit to probability.
Answer: From what you say, I assume that the combination (wave4, age_r1) means that all other $X$ variable values are 0. (Although it seems odd that there are only categories wave4, wave5 and wave7).
So, the estimated logit of the probability is $$-2.457415 +(0\times -0.510565) +
(0 \times       -0.360667) +
(0 \times      -0.167394)  +
(0 \times      -0.664402)  +
(0 \times      -0.898270)  +
(0 \times      -1.704232)  +
(0 \times      -2.909736)$$ $$= -2.457415 $$
Thus the estimated probability itself is $$\frac{\exp(-2.457415)}{1+\exp(-2.457415)}$$ $$= 0.07889799$$
That is the easiest one.  You can use the same trick to get the probabilities for all other combinations too, although there will be some "$1\times$" multipliers.
You can see all of this using R the glm fitted object (call it "fit") by cbinding fit$fitted.values to your data set and scrolling through the result.


About the magic number of PE

Question: 0x10b : PE32 executable
0×107 : ROM image
0x20b : PE32+ (64 bit) executable

What is the ROM image?
Answer: Interesting question, I've dabbled with manipulating PE files but never noticed that.
Here's what I believe they are used for: A ROM image can be executed 'in place' (XIP), if you search MSDN for "rom image", you'll find a number of references to it in the Windows Mobile and older Windows CE tools, e.g. Rom Image Creation.
A ROM image can thus be executed directly from the ROM without having to load and relocate it in RAM, which is pretty handy for a mobile device with limited resources.
Comment: No, it's more like a memory mapping.

About the magic number of PE


Three.js: Build-in way to add object with bottom in z = 0

Question: Is there a build-way one-liner in three-js to add object to 'bottom' of the scene - with z = 0 corresponding to the bottom of the object (the bottom of the object's bounding box) instead of default's object centered in origin?
I know we can achieve this by adding the half of bbox's height to the position like:
const addToBottom = (scene: Three.Scene, object: Three.Object3D) => {
    const bbox = new Three.Box3();
    bbox.setFromObject(object);
    scene.add(object)
    object.position.z += (bbox.max.z - bbox.min.z) / 2
}

Comment: something like that: `object.position.z += new THREE.Box3().setFromObject(object).getSize().z * 0.5;`. I'd put `THREE.Box3()` in a variable for re-use and have a variable for the size for re-use too.
Comment: @prisoner849 makes sense
Comment: @prisoner849: since there are no more responses, mind making it into an answer so I can accept it?
Answer: One-liner can be like that:
object.position.z += new THREE.Box3().setFromObject(object).getSize().z * 0.5;
Comment: r139

const geometry = new THREE.BoxGeometry;
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
cube.position.z += new THREE.Box3().setFromObject( cube ).getSize().z * 0.5;

three.module.js:5645 Uncaught TypeError: Cannot read properties of undefined (reading 'subVectors')
    at Box3.getSize (three.module.js:5645:58)


How To Create an Algorithm For Continous Flow of Objects Without Any Gaps Or Overlaps?

Question: I need to create a mathematical solution or algorithm for the following real life problem:
<code>     F     E     D     C    B    A    Output
T1   _     _     _     _    _    _    _
T2   _     _     _     _    _    _    _
T3   _     _     _     _    _    _    _
T4   _     _     _     _    _    _    _
T5   _     _     _     _    _    _    _
T6   _     _     _     _    _    _    _
.
.
.
</code>
T is a clock ticking at 1 sec intervals and the underlines flow continuously from left to right. Every tick, I need to drop ONE letter on the underlines. Few rules must be followed for dropping the letters: 1) I can't drop/overlap letters on top of each other 2) the output needs to have a continuous (no gaps) flow of letters. Example,
<code>     F     E     D     C    B    A    Output
T1   F     _     _     _    _    _    _
T2   _     F     _     _    _    _    _
T3   _     E     F     _    _    _    _
T4   _     _     E     F    _    _    _
T5   _     _     D     E    F    _    _
T6   _     _     _     D    E    F    _
T7   _     _     _     C    D    E    F
T8   _     _     D     _    C    D    E (Problem Here! A gap is created!)
T9   _     _     _     D    _    C    D
T10   _     _     _     _    D    _   C
T11   _     _     _     _    _    D   _ (Gap. Not acceptable.)
</code>
How do I approach in solving this problem?
EDIT 1: There will always be 6 letter. There is no specific pattern of letters. I just need a continuous output.
EDIT 2: I also need an equal or close to equal effort of letter distribution. Lets say, each letter is dropped 1/6th of the time. An optimum distribution of letters at the output.
EDIT 3: You can drop the same letter twice in a row if you wish, but that won't give me a nice letter distribution.. Also, at every T time, a letter can be dropped.
EDIT 4: The action is: Every T, shift to the right, then drop a letter.
Comment: I don't understand the conditions yet. Please edit the question to show us a few more acceptable solutions (f there are any), and perhaps one that's unacceptable even though no letters overlap. Will you always have $6$ letters? If not, can you show us some examples for three or four letters too?
Comment: OK now we know there are always $6$ letters. Please edit the question to show us some other possible solutions. Since you seem to have one solution already, what do you want an algorithm to do? It's not clear what can or must happen after time about $13$, when it looks as if all the letters will have been used once and fallen off the end.
Comment: I want to continuously drop letters without creating gaps in the output: F E _ C D E F (the underline is not acceptable. It means there was a gap in the sequence)
Comment: Can you drop the same letter twice? Also you drop no letter at time T2 in your example. Can you only drop a single letter? Otherwise you will not be able to regain access to the leftmost letters later on, ie. once you have skipped $n$ time steps you have rendered $n$ letters useless.
Comment: - Yes you can drop the same letter twice.
- At T2, I didnt drop a letter was just an example. You can drop any letter at T2. Every T, you can drop a letter.
Comment: Then the algorithm is straight forward. If you drop a letter, you HAVE to drop letter $n$ from the left (zero indexed) where $n$ counts the total number of time steps you have skipped.
Answer: I figured out a solution (not sure if this is an optimum solution) by trial and error:
<code>    F   E   D   C   B   A   Output
T1  _   _   D   C   _   _   _
T2  _   E   _   D   C   _   _
T3  F   _   E   _   D   C   _
T4  _   F   _   E   _   D   C       (No Letter Dropped Here)
T5  _   _   F   _   E   A   DC
T6  _   _   _   F   B   E   ADC
T7  _   _   D   C   F   B   EADC        (T1 Event Repeats Here)
T8  _   E   _   D   C   F   BEADC
T9  F   _   E   _   D   C   FBEADC
T10 _   F   _   E   _   D   CFBEADC     (No Letter Dropped Here)
T11 _   _   F   _   E   A   DCFBEADC
T11 _   _   _   F   B   E   ADCFBEADC
T12 _   _   D   C   F   B   EADCFBEADC  (T1 Event Repeats Here
and so on
</code>
Now, I need a way to represent this mathematically so I am able to solve similar problem with different number of columns (letters from A to Z for example). Thanks!
Note: with even number of columns, two letters are dropped at the same time (T1, T7, T12) and a single drop is skipped (T4, T10). With Odd number of columns, I don't think these two things occur.


Is there a difference in bandwidth consumption between a RODC and RWDC?

Question: My organization has deployed 2008 RODCs on multiple seagoing platforms.  The idea was to extend our shore-based domain onto our ships to better control security policies.  RODCs were selected with the assumption they would consume less bandwidth.  There were also security concerns, but these were secondary.
Internet connectivity at sea is provided by a very expensive satellite link.  Speeds range from slow to non-existent. Managing users, computers, group and permission changes and GPO updates is excruciatingly slow.
I am beginning to believe that we have developed tunnel vision in regard to RODCs and that having a writable domain controller might be a better alternative.  I am thinking one RWDC and one RODC per ship for redundancy.  It is a small user base, but it's critical to have redundancy.
There is a lot more to this, but I cannot sum it up with any brevity.  I am curious if anyone has ever tested the difference in bandwidth consumption between an RODC and a RWDC?  Would replacing one of the RODCs with a RWDC significantly increase bandwidth consumption?  I would be redirecting the RODC to replicate from the RWDC.  This would mean one domain controller connecting back to shore.
As things sit right now, it can take hours to do things that would normally take minutes.  Having admins aboard the ships working on a RWDC would make life much better.  The fear is that RWDC chatter would fill the pipe.
So, anyone ever test the difference?
Answer: No, I've never tested the difference in bandwidth consumptions between a RODC and RWDC, but let me offer some observations none the less:
If security is the "least of concerns" in you considerations and network connectivity is paramount, RODC's might actually be a really bad choice.
Remember that, since it's read-only, any operation that requires updating data in the directory (including account lockouts, authentication failures etc.) will only succeed by re-targeting a writable domain controller and consuming bandwidth bi-directionally (originate write offsite + replicate on RODC).
You're probably better off with 2 RWDC's and a dedicated Site per vessel/platform.
Be sure to configure the Site Link between the off-shore Sites and the on-shore hub with the following characteristics:

Configure a replication schedule that only allows replication during times of the day/week/month where connection speed is assumed to be best, (and dial-up prices low, if fluctuating)
Configure a replication interval that's fairly high, to prevent the site bridgehead from polling every 15 minutes during its schedule
Enable Two-way sync (also known as "Reciprocal Replication") to reuse the same underlying connection bi-directionally
Change the Domain Controller used in GPMC to one in the local off-shore site, when you are working on-premises (otherwise it defaults to the PDC emulator, hopefully located at your hub site)
Leave intra-site replication settings as default (15-second delayed change notification), to avoid data loss in the event you lose one DC at an off-shore site
Comment: I would count operations that use RSO (replicate single object), like DNS dynamic updates, password sync etc. So I think RODCs in general cause more traffic.
Comment: @iPath Definitely, the list in my answer is non-exhaustive. RSO or partition sync, doesn't really matter. Any write operation initiated by a client on the platform *will* incur a connection out and subsequently back for replication on the RODC
Answer: RODC's are a TERRIBLE option for remote locations with a dodgy network.
Also, RODC's should NOT be deployed in a site that has an RWDC.
The only reason an RODC would consume less bandwidth is due to no outbound changes would be replicated (no outbound replication partners).
You can't edit/manage objects using an RODC with applications such as AD Users and Computers or Group Policy Management Console, they need to connect to a writable domain controller.  Not surprisingly, this is slow for you due to you need to connect to an RWDC over a slow WAN link.
Comment: RODCs are terrible option if you need to do administration (i.e. writable operations). RODCs are good option in common.
Comment: RODC's are a good option IF you have the business case for them, and IF you have good network connectivity.  If you don't have good network connectivity, there will be additional problems.  One red flag way to tell if they have the business case is if they want to put an RWDC in the same site.  If so, they NEVER had a legitimate business case for an RODC. I've seen organizations implement RODC's the wrong way so often it is tragic, including putting Authenticated Users or Domain Users in the Password Replication Policy or Allowed RODC Password Replication Group.


How can I change this DEBUG code to correspond to the window object as well?

Question: How can I change this DEBUG code to correspond to the window object as well?
What is the JavaScript equivalent of var_dump or print_r in PHP?

OK

var hoge = new Object();
hoge.q = "stack";
hoge.lang = "js";
hoge.state = 1;

dump(hoge, 'body');

ERROR

dump(hoge, this);

ERROR

dump(hoge, 'window');

Comment: The second argument simply tells the function how to display the result, eg display in page or display in alert box. How would you use `window` in order to display the information?
Comment: I wanted to display the WINDOW object debug
Answer: you have to define repeatString also, did you?
function repeatString(str, num) {
    out = '';
    for (var i = 0; i < num; i++) {
        out += str;
    }
    return out;
}

and only  dump(hoge, 'body'); would be available to use
Comment: I had to define in advance. So it's not covered by WINDOW objects


10 fold cross validation model in weka

Question: I'm trying to build a specific neural network architecture and testing it using 10 fold cross validation of a dataset. Now building the model is a tedious job and Weka expects me to make it 10 times for each of the 10 folds.
Can't I just make the model for the first fold and ask weka to use that same model for the remaining 9?
Also, since building neural networks in weka is so easy, can I import a neural network structure to matlab for further use?
Comment: 10-fold CV consists of building the model 10-times. There is no way around that. After all, in each fold you will have different train set.
Comment: I think you need to read up on what cross-validation does. Based on your question, it appears you don't know what cross-validation is for.
Comment: Chapter 5 of [An Introduction to Statistical Learning](http://www-bcf.usc.edu/~gareth/ISL/) provides a good intro to cross validation.
Comment: Could you tell us why you would want to use multi fold cross validation instead of a simpler train test split (1 fold). Since neural networks take longer to train, train test splits are used more often than n fold validation.
Answer: You can use the Evaluate class to perform this 10-fold cross-validation. To define the cross-validation you have to set the parameter as '-x 10' in the EvaluateModel.
<code>clear all; close all; clc;

%% Add jar file to path plus import dependencies
javaaddpath('/usr/local/weka-3-6-11/weka.jar');
import weka.classifiers.trees.RandomForest.*;
import weka.classifiers.meta.Bagging.*;
import weka.classifiers.Evaluation.*;
import weka.core.Instances.*

%% load the arff file and extract the informations
filename = 'algo_output/results_features_labeling2_2class.arff';
loader = weka.core.converters.ArffLoader();
loader.setFile(java.io.File(filename));
data = loader.getDataSet();
data.setClassIndex(D.numAttributes()-1);

%% classification
classifier = weka.classifiers.functions.MultilayerPerceptron();
classifier.buildClassifier(data);
classifier.toString()

%% 10-fold cross-validation
ev = weka.classifiers.Evaluation(data);

v(1) = java.lang.String('-t');
v(2) = java.lang.String(filename);
v(3) = java.lang.String('-x');
v(4) = java.lang.String('10');
v(5) = java.lang.String('-i');

prm = cat(1,v(1:end));
ev.evaluateModel(classifier, prm)
</code>
For more information, check this link.
Comment: Just a remark: Weka's internal algorithm for performing $k$-fold CV is single-threaded. Since you are dealing with Neural Networks, which take a *very* long to train, you will *desperately* need multi-threading. If you need a Java implementation of a multi-threaded $k$-fold CV, I can provide you the code.
Comment: Yeah sure, I would be more than happy to see your code (even tho my classification run quite fast for my -really- small data-set).
Comment: If you have small samples, then even `MultilayerPerceptron` will finish quickly. I have been using large datasets that can take days to train, and without multi-threading, it would take much longer. Here is my code for benchmarking: [pastebin](http://pastebin.com/5eUwAmXd). I have listed the source code for 3 files, but the first file is the most important. Since I am using Streams and lambda expressions, you will need Java 8 to run it.

10 fold cross validation model in weka


Multiply ranges

Question: If i want this code to loop (as it does) until there's nothing more to calculate but always have a static value (C1) that doesn't continue, C2, C3 and so on, without adding a value in the formula, is it possible? Check my code and my explanation.
Thisworkbook.Sheets(1).Range("A1") = "=--(B1 >= C1) * --(B1 <= C2)"

This loop until nothing more can be calculated, so the next row look like this
Thisworkbook.Sheets(1).Range("A2") = "=--(B2 >= C2) * --(B2 <= C3)"

i want the second row to be
Thisworkbook.Sheets(1).Range("A2") = "=--(B2 >= C1) * --(B2 <= C2)"

and so on, so C1 and C2 should not be changed at all, can i do that??
Comment: You do not require the double unaries (aka double minuses or `--`) The multiplication (or any maths operation) is sufficient to convert a boolean value to a 1 or 0.
Comment: The idea is that it should convert them to 1 or 0. but the $ sign didnt work :/
Answer: To fill the range with formulas you could try either of these:
Sheet1.Range("A1:A2").Formula = "=(B$1:B$2 >= C$1) * (B$1:B$2 <= C$2)"
Sheet1.Range("A1:A2").FormulaR1C1 = "= (RC[1] >= R1C[2]) * (RC[1] <= R2C[2])"

The first uses implicit intersection and the second R1C1 references. R1C1 references are generally preferable being easier to maintain and using a smaller range for calculation dependencies.
If you only want the values you can try instead:
Sheet1.[A1:A2] = Sheet1.[(B1:B2 >= C1) * (B1:B2 <= C2)]

Note: Sheet1 is here used for brevity in place of ThisWorkbook.Sheets(1)being the default codename of the sheet.

Multiply ranges


How Many Countable Models of the successor function

Question: Consider the successor function (s(x)=x+1), $T_{S}$ to be the set of axioms given by;
S1: ∀xy[s(x)=s(y)→x=y] (injective)
S2: [s(x)≠0] (never 0)
S3: ∀x[x≠0→∃y[s(y)=x]] (everything bar 0 is in image)
S4n : ∀x[sn(x)≠x] (no cycles)
clearly $\langle N;s,0 \rangle$ is a model of TS and the upward Löwenheim–Skolem theorem theorem tells us there are models of TS of every infinite cardinality
I claim that there are $\aleph _{0}$ many countable models, how would i prove this claim?
Comment: Every model of the theory $T_S$ is isomorphic to the union of set of natural numbers and copies of set of integers (with usual ordering).
Comment: sn(x) is $s^n(x)=\underbrace{s(\cdots(}_nx)\cdots)$?
Answer: HINT: Show (if you've not already done so) that a countable model of $T_S$ has the form $\Bbb N\cup(I\times\Bbb Z)$ for some countable $I$, where $s(\langle i,n\rangle)=\langle i,n+1\rangle$ for each $\langle i,n\rangle\in I\times Z$. Then show that if $|I|=|J|$, the resulting models are isomorphic. You will then have exactly one model for each $|I|\le\omega$. The key idea is that although the successor function determines a linear order on $\Bbb N$ and on each of the $\Bbb Z$-chains $\{i\}\times\Bbb Z$, it does not determine any ordering of the set of $\Bbb Z$-chains: they can be permuted arbitrarily.
Comment: Can i ask what $\omega$ is please?
Comment: @ENAFMTH: The smallest infinite ordinal, which is also the smallest infinite cardinal; you could substitute $\aleph_0$, if you prefer.
Comment: AHHHH OK!! thank you!!!
Comment: @ENAFMTH: You're welcome!
Answer: If $\langle X,s,0\rangle$ is a model, we can define an equvalence relaton on $X$ via $x\sim y\iff \exists z\in X, n,m\in \mathbb N_0\colon x=s^n(z), y=s^m(z)$. The equivalnece classes are all isomorphic to $\mathbb Z$ (with standard successor function) or $\mathbb N_0$ (for the unique class that contains $0$). Conclude that $X\cong \mathbb N_0\sqcup \mathbb Z^I$ for some set $I$ and that $X$ is countable iff $I$ is countable.


How to Capitalize text_field Words in Real Time Excluding Prepositions?

Question: How to titleize/captialize words, like this website, so that prepositions aren't included?
I'm not looking for you to list all the prepositions, but if you can just show how it can be done with a few like, "of, on, and" I would greatly appreciate it.
<%= f.text_area :name, id: "challenge-name" %>

UPDATE BASED ON FRED's ANSWER
function makeTitle(slug) {
  var preps = ['and', 'a', 'of', 'but', 'from'];
  return $.map(slug.split(' '), function(k, v) {
    return $.inArray(k.match(/\w*/g)[0], preps) >= 0 ? k : k[0].toUpperCase() + k.slice(1);
  }).join(' ');
}

$('#challenge-name').on('keyup', function(){ $(this).val( makeTitle($(this).val())) })

Answer: You might want to watch out for punctuation - this code takes punctuation into account:
def makeTitle(slug)
  preps = ['and', 'a']
  str.split(' ').map do |w|
    preps.include?(/\w*/.match(w)[0]) ? w : w.capitalize
  end.join ' '
end

I'll blame the late hour last nite - I didn't realize the OP wanted a jquery/javascript solution, so I created one in Ruby. I'll leave that in place in case any future viewer is looking for an answer in Ruby, but here is a JS method (using jQuery):
function makeTitle(slug) {
  var preps = ['and', 'a'];
  return $.map(slug.split(' '), function(k, v) {
    if(k){
        var word = k.match(/\w*/g)[0].toLowerCase();
      var letter = $.inArray(word, preps) >= 0 ? k[0].toLowerCase() : k[0].toUpperCase();
        return letter + k.slice(1);
    } else {
      return k;
    }
  }).join(' ');
}

Comment: Ok - it was a matter of the case of the input - for example, when typing 'of', as the user types, 'o' is found in the list of preps, so gets uppercased to 'O'; when the user finishes typing the word, it reads 'Of', which doesn't match 'of'. So I updated to account for that case, and also made some changes to improve readability.
Comment: You should be able to use it as the body of `makeTitle` if you substitute `slug` for `str`, get rid of the string literal assignment to `str` and create your own `preps` list
Comment: Also take out the `return` statement. By default Ruby will return the result of the last expression if there is not an explicit return statement.
Comment: Hey Fred. Updated question with my attempt at your answer. I tried others, which I could include if you want, but that is the most basic one
Comment: @AnthonyGalli.com - I was working late and didn't realize you were looking for a Javascript function! I've updated my answer, sorry for the confusion!
Comment: haha no worries buddy, I did put ruby and javascript in the tags. As to your update it is acting erratically for me where sometimes the propositions like, 'and' will capitalize anyway
Comment: now that I think about it, it might give an incorrect result if something like 'And' is already capitalized. Can you give me an example string where it's not behaving correctly?
Comment: As I can see all of them but sometimes a shorter word like `a` or `of` will stay lowercase
Comment: Please give me an example of an input string where it's not behaving correctly.
Comment: Updated question to account for updated version of your code. And per your example request. Let's say "test words - and, a, of, but, from". Now if I copy and paste that example then they are properly capitalized as such, "Test Words - and, a, of, but, from" , but if I write them into the `text_field` then it acts erratic by giving me, "Test Words - and, a, Of, But, From"
Comment: Thanks for walking me through this Fred. I appreciate this so much! Works perfectly now :)
Answer: You may do like this in a different coding approach;

var preps = ["of", "on", "and", "or", "in", "a", "the"],
      str = "the mother of the sea and a life in the depths of the ocean",
    words = str.match(/\b\w+\b/g);
   header = words.map((e,i) => preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e).join(" ");
console.log(header);

of course you may include what preposition you like to be kept as it is and exclude what not to the preps array.
As per your code; i would prefer to modify it as follows;
function makeTitle(slug) {
  var words = slug.match(/\b\w+\b/g),
      preps = ["of", "on", "and", "or", "in", "a", "the"];
  return words.map((e,i) => preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e).join(" ");
}

and this is the ES5 version which should be fine with Safari and older versions of Chrome, Firefox and IE which don't support JS arrows.

function makeTitle(slug) {
  var words = slug.match(/\b\w+\b/g),
      preps = ["of", "on", "and", "or", "in", "a", "the"];
  return words.map(function(e,i) {
                     return preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e;
                   }).join(" ");
}

var s = makeTitle("the mother of the sea and a life in the depths of the ocean");
console.log(s);
Comment: Thanks Redu for the help! How would I fit that in with my script if you wouldn't mind?
Comment: @AnthonyGalli.com: I have extended my answer to include a solution within the concept of your coding approaches.
Comment: Are you able to get that to work on your end? I can't get it to work. Once I type a word it wont let me click the spacebar
Comment: @AnthonyGalli.com: The `makeTitle()` function seems OK here. Keep in mind that it uses ES6 code though.
Comment: I'm unfamiliar with that @redu. It's not just normal javascript? I just plugged into my ruby on rails script and it didn't work. I played around with the punctuation, but it still didn't work. I'm not very good at javascript.
Comment: @AnthonyGalli.com: Are you using Safari as browser..? If so i believe it won't recognize JS arrow functions which are part of ES6 specs. I guess i have to convert it ES5 then.
Comment: @AnthonyGalli.com: Just added an ES5 version at the bottom of my answer.
Comment: Thanks Redu but that wasn't the issue. Are you familar with ruby on rails? I think it is this line `$('#challenge-action-home').on('keyup', function(){ $(this).val( makeTitle($(this).val())) })` that probably needs to be adjusted to make your code chunk work.
Comment: @AnthonyGalli.com: That line is jQuery.. Have you included jQuery at your script loading stages? and.. no sorry i haven't got any ruby experience at all.


Virtual wrapper of std::queue does not compile when T has no copy constructor

Question: I'm using C++11. I encountered a compilation error when writing a simple wrapper for std::queue<T>, and using it with a class that does not have a copy constructor.
Following is a snippet to illustrate the problem.
Basically, I have a wrapper for std::queue<T>, which has two virtual overloads for push.
#include <queue>
#include <utility>
#include <future>

template <typename T>
class myqueue {
public:
    myqueue() : q() {}
    virtual ~myqueue() {}

    // pushes a copy
    virtual void push(const T& item) {
        q.push(item);
    }
    // pushes the object itself (move)
    virtual void push(T&& item) {
        q.push(std::move(item));
    }
private:
    std::queue<T> q;
};

int main() {
    // Thanks to Yakk for pointing out that I can reduce clutter by using one of std's non-copyable classes!
    myqueue<std::packaged_task<int()>> q;
    std::packaged_task<int()> t([]{return 42;});
    q.push(std::move(t));
}

When I try to compile this (ICC 13.2, g++ 4.7.3 on my Linux machine here, and also g++ 4.7.2 on Ideone: http://ideone.com/HwBhIX ), the compiler complains that it cannot instantiate myqueue::push(const nocopy&) because nocopy's copy constructor is deleted.
If I remove the virtual modifiers from push, this compiles fine (both on my machine and on Ideone).
Can anyone help me understand why this is happening?

P.S.: here is the error stack from Ideone:
In file included from /usr/include/c++/4.7/i486-linux-gnu/bits/c++allocator.h:34:0,
                 from /usr/include/c++/4.7/bits/allocator.h:48,
                 from /usr/include/c++/4.7/deque:62,
                 from /usr/include/c++/4.7/queue:61,
                 from prog.cpp:1:
/usr/include/c++/4.7/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::packaged_task<int()>; _Args = {const std::packaged_task<int()>&}; _Tp = std::packaged_task<int()>]':
/usr/include/c++/4.7/bits/stl_deque.h:1376:6:   required from 'void std::deque<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::packaged_task<int()>; _Alloc = std::allocator<std::packaged_task<int()> >; std::deque<_Tp, _Alloc>::value_type = std::packaged_task<int()>]'
/usr/include/c++/4.7/bits/stl_queue.h:212:9:   required from 'void std::queue<_Tp, _Sequence>::push(const value_type&) [with _Tp = std::packaged_task<int()>; _Sequence = std::deque<std::packaged_task<int()>, std::allocator<std::packaged_task<int()> > >; std::queue<_Tp, _Sequence>::value_type = std::packaged_task<int()>]'
prog.cpp:13:9:   required from 'void myqueue<T>::push(const T&) [with T = std::packaged_task<int()>]'
prog.cpp:28:1:   required from here
/usr/include/c++/4.7/ext/new_allocator.h:110:4: error: use of deleted function 'std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(const std::packaged_task<_Res(_ArgTypes ...)>&) [with _Res = int; _ArgTypes = {}; std::packaged_task<_Res(_ArgTypes ...)> = std::packaged_task<int()>]'
In file included from prog.cpp:3:0:
/usr/include/c++/4.7/future:1337:7: error: declared here

Comment: g++ 4.8 compiled it all without problem.
clang++ 3.4 too.
Comment: @MichaelKuritzky please don't copy-type the code you have, that's obviously too risky to introduce errors (and to erase the reason for your real problem). If you don't have internet access on the computer, copy the code onto an usb pen drive and upload it from there.
Comment: gcc 4.7.2 compiles this fine: http://ideone.com/NPUkaS
Comment: **_of course_**, after I put the missing semicolon in nocopy.h (at the end, after the class definition)
Comment: `g++-4.7 (Ubuntu/Linaro 4.7.3-2ubuntu4) 4.7.3` still compiles it just fine. I just copied the text from here and pasted into the files.
Comment: @MichaelKuritzky in addition it would be very constructive if you could prvide the actual error message from the compiler. At least the first and last 3-4 lines - I assume it's a huge template error stack
Comment: `std::queue::push(T const&)` is probably declared using SFINAE, i.e. with something like `enable_if::value,...>` so that the member function is present only for instantiations that have a copyable T. However, from the standard I'd think that that function would be instantiated only if it is actually *used* and therefore should not lead to an error in your case.
Comment: It looks like it [works on gcc 4.7.2](http://ideone.com/J7Rram).
Comment: @Massa - it's a wonder that was the only compilation error you encountered, I had to type all this code by hand :)
(the computer I encountered this on does not have internet access :( );
I'll edit the question to fix this particular problem.
Comment: @ArneMertz - I looked at the g++ header several times myself, because I thought I was missing something like this, but I didn't find any trace of it... both versions of `push` are defined without any modifiers (aside from the C++0X `#ifdef` wrapper around the move version)
Comment: You **are** using the `-std=c++11` flags to compile, aren't you?
Comment: @Massa - I guess this means that my installation of g++ 4.7.3 is somehow faulty, then? :(
Comment: I used `-std=c++0x`, actually, but I just tried it with `-std=c++11`, and the problem persists
Comment: Please check that your source files are exactly what is in your question (don't forget that pesky semicolon! :D) and edit your post adding the complete text of the error message, and of `g++ --version`...
Comment: @ArneMertz - I wish I could, but alas, the policy here forbids the use of usb flash drives. This also means, unfortunately, that complying with Massa's request will take a while... :)
Comment: Do you have access to the same compiler on another computer that has internet access? So you could do your trial compilations on that one, giving a faster turnaround time while we try to spot the problem :)
Comment: The computer where the compiler is does not have any connectivity? You can put your code on your LAN and compile it from there, no? How do you enter code to be compiled, all by hand?
Comment: No, we don't have any Linux boxes here with internet access. I'm afraid this is not the place to discuss the company's security policies, though.. :)
Comment: I have edited the question, adding the (abbreviated) error stack. I'll update it with `gcc -v`'s result tomorrow. Thanks for all the help so far :)
Comment: @MichaelKuritzky the `main.cpp` you posted has 15 lines, but the compiler complains about something at line 17, column 12. Obviously the code you posted is *not* the exact same as the compiler tries to compile. Please make sure they are the same. Even if it's only a comment - we can't tell what the compiler complains about if we don't see the exact corresponding code. This includes comments, line indentation and everything else.
Comment: So the first thing you NEED to do is to simplify the problem.  Reproduce your problem using less code where the problem actually occurs.  Try `my_queue< std::unique_ptr >`, a standard no-copy class, and see if it still fails to work.  If it still fails, you just reduced the amount of code required to reproduce by 1/3!  Next, put everything in one `.cpp` file, not a file and two headers.  See if you still get the error *without calling `push`*?  How about if you eliminate `push` from your `my_queue` class, does the error still occur?
Comment: Produce the absolute least amount of code that reproduces your problem, in a single file.  Then copy it by hand to a piece of paper, have a colleague double-check each and every character, carry that piece of paper to an internet connection, and post the result along with a complete command-line of how you invoked it and the resulting error message.
Comment: Thanks, I'll try your suggestions when I come back to work tomorrow. :)
Comment: The error message tells us that the `nocopy` copy constructor is being used from `myqueue::push(const nocopy&)`. The problem is clearly that the real `main.cpp` is trying to push an lvalue, which the example code does not - otherwise the compiler would not instantiate `myqueue::push(const nocopy&)`.
Comment: Hi,
I'm very sorry, it seems that I did, indeed, have a little typing error in my code yesterday.
I have, however, now isolated the true problem I was facing, and in a way reproducible in Ideone (gcc 4.7.2). I will now edit the question accordingly.
Comment: Finished editing. Please take another look at the original post. :)
Answer: myqueue's standard copy constructor calls the copy constructor of nocopy. Simply overwrite or =delete the copy-constructor and the operator= of myqueue and you should be fine.
Comment: Unfortunately, this doesn't work :(
I tried `delete`ing the copy c'tor and operator=, but the problem persists. (in fact, they were `delete`d in the original classes from which I derived this snippet)
Comment: Did you try the 'old' way of preventing unwanted copies by declaring the copy and assignment operator private?
Comment: Just gave it a shot. Now it complains that the copy c'tor is private... :(
Comment: @MichaelKuritzky then the code you posted is not the code you actually have (or the compiler actually tries to compile, to be precise), because there you don't copy any `myqueue` (it compiles fine with delete copy ctor, see here: http://ideone.com/hLV2kl). Please provide your actual `main.cpp`
Comment: @ArneMertz - I did provide the original. As I said, `delete`ing the copy c'tor of `myqueue` didn't help. I guess my gcc/icpc installation is somehow faulty :(
Comment: @MichaelKuritzky when it cries about the private copy ctor it tries to copy the `myqueue`, obviously. But there is no copying in your code. Try a sole `int main() { myqueue q3; }` - and be sure to save the sources so the compiler actually sees what your editor shows you.
Comment: It complains about an attempt to use `nocopy`'s copy c'tor, not `myqueue`'s one. I'll try your suggestion tomorrow, thanks. :)
Answer: This occurs because the c++11 implementation provided by gcc 4.7 is incomplete. When using c++11 you must always use the most up-to-date compiler versions. clang is usually most complete, followed by gcc and, some distance behind, icpc.

Following your edit, the code is not compiling any more (clang 3.2 or gcc 4.8), because it's simply wrong. When the template class myqueue<std::packaged_task<int()>> is instantiated, the non-template member virtual void push(const T&) is instantiated too. However this member calls the deleted copy constructor of T, so is illegal, error.
(That it compiles for non-virtual push(const T&) is dangerous, as you will get an error as soon as you try to use that function.)
To make you code work, you must avoid that. A virtual member cannot be a template (which would have allowed you to avoid the problem via SFINAE). But you can specialise class myqueue<T> depending on whether T is copyable or not. The following code compiles with gcc 4.8 (but not with icpc 13 or clang 3.2, which has a faulty implementation of std::is_copy_constructible).
#include <queue>
#include <type_traits>
#include <utility>
#include <future>

template <typename T, typename E=void> class myqueue;

template <typename T>
class myqueue<T, typename std::enable_if<std::is_copy_constructible<T>::value>::type>
{
  std::queue<T> q;
public:
  virtual ~myqueue() {}
  // pushes a copy
  virtual void push(const T& item) { q.push(item); }
  // pushes the object itself (move)
  virtual void push(T&& item) { q.push(std::move(item)); }
};

template <typename T>
class myqueue<T,typename std::enable_if<!std::is_copy_constructible<T>::value>::type>
{
  std::queue<T> q;
public:
  virtual ~myqueue() {}
  // pushes the object itself (move)
  virtual void push(T&& item) { q.push(std::move(item)); }
};

int main() {
  std::packaged_task<int()> t([]{return 42;});
  myqueue<std::packaged_task<int()>> q;
  q.push(std::move(t));
}

Of course, this is not quite the same as your original code, as there will be no virtual void push(const&T) for non-copyable T, but I think this is exactly what you want. Alternatively, you could make the offending method pure virtual in the specialisation for non-copyable T.
Sorry, that I cannot fix icpc for you, but at least this code seems to be legal C++11.
Comment: The problem with this is that I have to use icpc, and g++ 4.7 is (from what I gather) the latest version (of the headers) they currently support. :(
We'll switch to g++ 4.8's headers as soon as icpc adds support for them...
Comment: @MichaelKuritzky icpc is not ready for C++11 (yet). Using icpc with C++11 was a bad decision. Best is to use clang. (I don't know why Intel is so bad at implementing C++11, they must prioritise other things.)
Comment: the reason we chose icpc is its performance, not its C++11 support. Anyway, the C++11 support there is quite good so far (albeit still not full :( ), and improving with each update.
Comment: Thanks for the answer, this seems to be the problem indeed. By the way, shouldn't it be possible to hide the methods (using SFINAE) without specializing the class, but rather on a per-method basis? (once icpc updates their erroneous implementation of `std::is_copy_constructible`, of course)
Comment: @MichaelKuritzky No, you **cannot use SFINAE** (as I explained), because a `virtual` member cannot be a `template`. If speed is important, then consider clang: I found this to be quite fast, competetive with icpc (though this always depends on the code).


Including newline character with any other character in regex - Python

Question: I am currently using Jupyter Notebook and Regex in Python to create a Word and Definition dictionary from a txt format dictionary file.
Sample data from text file:
ABACINATE\nA*bac"i*nate, v.t. Etym: [LL. abacinatus, p.p. of abacinare; ab off +\nbacinus a basin.]\n\nDefn: To blind by a red-hot metal plate held before the eyes. [R.]\n\nABACINATION\nA*bac`i*na"tion, n.\n\nDefn: The act of abacinating. [R.]\n\n
The pattern I am trying to create includes getting all capital letters for the word, followed by removing the text up until the definition.
Desired output
{'word': 'ABACINATE', 'definition': To blind by a red-hot metal plate held before the eyes.'}
{'word': 'ABACINATION', 'definition': The act of abacinating.'}

The pattern I have already tried is
pattern="""
(?P<word>[A-Z*]{3,}) #retrieve capital letter word
(\n.*\n\n\Defn:) #ignore all text up until Defn:
(?P<definition>\w*) #retrieve any worded character after Defn:
(.\ ) #end at the full stop and space
"""
for item in re.finditer(pattern,all_words,re.VERBOSE):
    print(item.groupdict())

I'm struggling to deal with the newline characters here. I have tried to isolate the capital letter, then start at the newline character immediately after and ignore any character up until the two newline characters before 'Defn:' and retrieve the definition ending at the full stop.
Is there a way to deal with newline characters in this way?
Comment: I would argue that this is not a good application for regular expressions.  You have specific search strings in a specific order.  Just grab through a '\n' for the word, then `str.find("Defn:",i)` to search for Defn from that point.
Answer: You mostly had it, just missing a non-greedy match and an expanded set for the characters in the definitions.
import re
all_words = """ABACINATE\nA*bac"i*nate, v.t. Etym: [LL. abacinatus, p.p. of abacinare; ab off +\nbacinus a basin.]\n\nDefn: To blind by a red-hot metal plate held before the eyes. [R.]\n\nABACINATION\nA*bac`i*na"tion, n.\n\nDefn: The act of abacinating. [R.]\n\n"""

pattern="""
(?P<word>[A-Z*]{3,})([\s\S]*?Defn:)(?P<definition>[a-zA-Z -]*)
"""
for item in re.finditer(pattern,all_words,re.VERBOSE):
    print(item.groupdict())

{'word': 'ABACINATE', 'definition': ' To blind by a red-hot metal
plate held before the eyes'} {'word': 'ABACINATION', 'definition': '
The act of abacinating'}
Comment: Thank you for your answer. This works, but does not include definitions that include other full stops, commas and quotations characters. Is there a workaround for the [a-zA-Z -]* part?
Comment: @beeslaw, I mean, there's lots of ways, but without you listing more desired input/output in the question I can only guess what you want.  For example, `(?P[A-Z*]{3,})([\s\S]*?Defn:\ )(?P.+?\.(?= ))` does what you say but I don't know if it does what you want.
Comment: That is perfect. Thank you so much!


How to access label of List (text) via node_load()

Question: In my module I'm generating some json based on some node content.
$node = node_load($nid);

One of the fields in the node is field_sport_type which is of type List (text). The allowed values look like this:
mens-surfing|Men's Surfing
womens-surfing|Women's Surfing
junior-mens-surfing|Junior Men's Surfing
junior-womens-surfing|Junior Women's Surfing
skate|Skate

When I var_dump($node), the field_sport_type section looks like this:
["field_sport_type"]=>
      array(1) {
        ["und"]=>
        array(1) {
          [0]=>
          array(1) {
            ["value"]=>
            string(14) "womens-surfing"
          }
        }
      }

So, the 'value' is the key from the allowed values, but I want to get the Label, not the key. In other words, I won't want womens-surfing, I want to get Women's Surfing.
How can I get access to the label of my List (text)?
Answer: You can get the list of values as a keyed array using list_allowed_values, and use it to show the "key" with whatever logic you want.
An example from the API comments section is as follows:
<?php
/*
assuming there's a field named machine name is 'field_my_field_name' whose
type is a list (float, integer or text), and you want to get the values that
were entered into the "Allowed values list" textarea on the edit screen for the field
*/
$all_fields_on_my_website = field_info_fields();
$allowed_values =       list_allowed_values($all_fields_on_my_website["field_my_field_name"]);
/*
$allowed_values is now an array of $key=>value pairs that
can be dropped into the '#options' value for a form field array, for instance
*/
//example:
$form = array();
$form['my_form_element'] = array(
  '#type' => 'select',
  '#title' => t('Choose something, sucka!'),
  '#description' => t('Descriptive text under form elements rather than above them is a great UX choice, really.'),
  '#options' => $allowed_values,
);
return $form;

Being a "field" in drupal the List field instance attached to a bundle has configuration and settings such as the custom list of items, the default value, whether its mandatory, etc.
Answer: You can access the key label in a simple way using an Entity Metadata Wrapper:
$wrapper = entity_metadata_wrapper('node', $nid);
$label = $wrapper->field_sport_type->label();

Or using de $node loaded vía node_load():
$wrapper = entity_metadata_wrapper('node', $node);
$label = $wrapper->field_sport_type->label();

You will need the Entity API module, but I think that this module is almost mandatory in custom module coding.


Cross Browser Compatible HTML

Question: Is there any tool available which will check my html page for different browsers and also suggest the changes I should make to make them cross browser compatible?
Some of my html pages are not working fine with IE and some in Chrome.
Comment: IME, Firefox is the most standards compliant browser - while there are some bits of functionality that other browsers fail to handle rather providing a superset of functionality, using Firefox as a reference platform saved me a lot of pain compared with MSIE
Answer: You can use something like http://browsershots.org/ to see how it looks in all kind of browsers. But it stop there, it will not give you any solutions for the problems.
You just don't need to install all kind of browsers on all kind of operating systems.

Cross Browser Compatible HTML


Compile a class or function into Javascript

Question: I want to send Javascript code over the wire and I don't want to use the full ScalaJS compiler for that. Let's assume this scenario in the backend:
I have a service that wants to define some validations for a textbox in the frontend. My frontend is written in Javascript and gets a Javascript function from the backend in json format and use that for validation.
I want to write that function in Scala in my backend and compile it to JS using ScalaJS and put it in json and send it to my frontend:
<code>def validation(input: String): Boolean = {
   input.contains("scala is cool")
}

val jsFunctionText:Json = ScalaJSMagicCompiler.compileAndOptimizeFunction(validation)

reply(jsFunctionText)
</code>
Is there any way to do that? If not, what would be the best route to use the ScalaJS compiler to compile the function or a class and get a pointer to the output compiled file in the output folder or something?
I would rather do it at compile time but don't know if it's possible to have safe access to the generated code. something like this would be great:
<code>@CompileAsJS("validation")
def validation(input: String): Boolean = {
   input.contains("scala is cool")
}

val jsFunctionText:Json = ScalaJSMagicCompiler.retrieveFromFile("validation", "output.jar")

reply(jsFunctionText)
</code>
Answer: I'm afraid you can't do that. Scala.js is designed to compile entire classpaths to JavaScript modules. You can't compile just one function. The main reason is that it preserves all the semantics of Scala, including the implementation of the collections, of strings, etc.
Of course in theory you could compile each such function as a module that exports only one function, and use that, but that would be way overkill, since it would bring the Scala.js "tax" on every function (a few KB minimum, but around 100 KB if you use anything from the collections).
Your use case was precisely the target of another project, namely JScala, but that project was discontinued.
Comment: Putting the ScalaJS "task" aside (imagine you can always ship the dependencies separately), is there any possible way to do it? If one wants to start something to do that, what would be the best path?
Comment: But you can't ship dependencies separately. Scala.js needs to generate the js for the entire program in one go. The best path forward for your use case is not to use Scala.js. It just isn't a solution for that use case, never was, and probably never will.


absolute  doesn't show show up (is in the right position)

Question: I'm trying to show an image in absolute positioning.
It's in the right place. http://gyazo.com/f1c545fe183c741d92c9466eacdbd020
it just doesn't show up, and I can't figure out why...
.active{
    background-color: #8b9dc3;
    font-weight: 600;
    position: relative;
}

.driehoek{
   position: absolute;
   left:28px;
   top:29px;
}

Home

Thanks in advance.
Comment: What you've posted doesn't allow us to see the problem you have. Please post a complete code example.
Comment: @j08691: http://jsfiddle.net/9r4ou50m/ Here is my JSF, I hope you can do something with that.
Answer: Trying to guess here. Looks like your absolutely positioned image is overlapped by content after it's parent element. Try adding z-index: 10; on .driehoek selector.
Or some of parent elements may have overflow: hidden;.
Comment: And what about `overflow: hidden;`? As @j08691 said it's hard to tell without seeing actual markup.
Comment: it was indeed the overflow:hidden. Thank you!