text:
Q: Winpcap program runs with MinGW but not with MSVC 2015 in Qt I have a Qt application that uses winpcap library. When I build the project with MinGW 64-bit, everything works fine and the project runs without any errors. But when I compile the same application with MSVC 2015 64-bit, I get a lot of errors related to redefinition, different linkage or macro redefinition. I have other Qt applications using winpcap that run on the same OS (windows 10 64-bit), both with MinGW and MSVC 2015.
Part of the errors are as below.
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(103): warning C4005: 'AF_IPX': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(457): note: see previous definition of 'AF_IPX'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(147): warning C4005: 'AF_MAX': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(476): note: see previous definition of 'AF_MAX'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(185): warning C4005: 'SO_DONTLINGER': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(399): note: see previous definition of 'SO_DONTLINGER'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(235): error C2011: 'sockaddr': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1007): note: see declaration of 'sockaddr'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(437): error C2059: syntax error: 'constant'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(437): error C3805: 'constant': unexpected token, expected either '}' or a ','
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(572): warning C4005: 'IN_CLASSA': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(284): note: see previous definition of 'IN_CLASSA'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(597): warning C4005: 'INADDR_BROADCAST': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(303): note: see previous definition of 'INADDR_BROADCAST'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared\ws2def.h(633): error C2011: 'sockaddr_in': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1011): note: see declaration of 'sockaddr_in'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(136): error C2011: 'fd_set': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1019): note: see declaration of 'fd_set'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(156): warning C4005: 'FD_CLR': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(94): note: see previous definition of 'FD_CLR'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(171): warning C4005: 'FD_SET': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(99): note: see previous definition of 'FD_SET'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(180): error C2011: 'timeval': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1035): note: see declaration of 'timeval'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(236): error C2011: 'hostent': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1023): note: see declaration of 'hostent'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(249): error C2011: 'netent': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(177): note: see declaration of 'netent'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(256): error C2011: 'servent': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1027): note: see declaration of 'servent'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(268): error C2011: 'protoent': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1031): note: see declaration of 'protoent'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(364): error C2011: 'WSAData': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(319): note: see declaration of 'WSAData'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(462): error C2011: 'sockproto': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(491): note: see declaration of 'sockproto'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(504): error C2011: 'linger': 'struct' type redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(1015): note: see declaration of 'linger'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(517): warning C4005: 'SOMAXCONN': macro redefinition
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(541): note: see previous definition of 'SOMAXCONN'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1667): error C2375: 'closesocket': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(749): note: see declaration of 'closesocket'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1684): error C2375: 'connect': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(751): note: see declaration of 'connect'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1705): error C2375: 'ioctlsocket': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(756): note: see declaration of 'ioctlsocket'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1726): error C2375: 'getpeername': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(761): note: see declaration of 'getpeername'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1747): error C2375: 'getsockname': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(766): note: see declaration of 'getsockname'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1768): error C2375: 'getsockopt': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(771): note: see declaration of 'getsockopt'
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock2.h(1793): error C2375: 'htonl': redefinition; different linkage
C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um\winsock.h(778): note: see declaration of 'htonl'

Please note that I already have included "winsock2.h" before "windows.h" , which is the solution to a lot of related questions I found on stackoverflow, like this one and this one . I've also tried defining WIN32_LEAN_AND_MEAN which did reduce a few errors. Any help would be appreciated. Thanks.

A: As suggested by similar questions on StackOverflow, the problem is with including "windows.h" before "winsock2.h". What I actually had was a header file called mypcap.h and another header file called mainwindow.h that included mypcap.h.
mypcap.h:
#pragma once

#include "winsock2.h"
#include "windows.h"

// ...

mainwindow.h:
#pragma once
/*
---- Includes ---
*/
#include "mypcap.h"

In mainwindow.h, windows.h was already included in the other headers. Putting #define _WINSOCKAPI_ before all the includes fixed the errors. Moving mypcap.h to the top of mainwindow.h was another solution.


text:
Q: How to align geometric shapes I'm trying to align geometric shapes like this image bellow

I tried to use position absolute but I didn't have success, this is my code that I tried to use

      <Hexagon />

    <Hexagon />

      <Hexagon />

CSS:
.container {
  height: 800px;
}

.hexagons {
  display: flex;
  position: absolute;
  width: 100%;
}

.teste {
  margin-top: 50px;
}

it's like this on the screen
If you can help me, or show me the way a was gratefull

A: Put all of them above each other then use transformation. Here is an example:

.box {
  width: 100px; /* adjust this to control the size */
  margin: 80px auto 0;
  display: grid;
}

.box div {
  grid-area: 1/1; /* above each other */
  clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
  transform: rotate(var(--d)) translate(-52%); /* a little bigger than 50% to create gap */
}

.box div::before {
  content: "";
  padding-top: 86.6%; /* 100%*cos(30) */
  display: block;
}

.box div:nth-child(1) {--d:0deg;   }
.box div:nth-child(2) {--d:120deg; }
.box div:nth-child(3) {--d:240deg; }

Without CSS grid for better support:

.box {
  width: 100px; /* adjust this to control the size */
  margin: 80px auto 0;
  position:relative;
}

.box div {
  clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
  transform: rotate(var(--d)) translate(-52%); /* a little bigger than 50% to create gap */
}
.box div:not(:first-child) {
  position:absolute;
  top:0;
  left:0;
  right:0;
}

.box div::before {
  content: "";
  padding-top: 86.6%; /* 100%*cos(30) */
  display: block;
}

.box div:nth-child(1) {--d:0deg;   }
.box div:nth-child(2) {--d:120deg; }
.box div:nth-child(3) {--d:240deg; }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Joins in hibernate HQL I have the following mysql query :
SELECT s.file, sheet, s.messagetemplate,s.time_to_run,s.frequency,s.schedule_name, t.Value
FROM  s   INNER JOIN  tFrequencies t ON s.frequencyId=t.id

My need is to implement this in hibernate. I look for a simple to understand answer being a beginner. I wouldn't understand prior complex implementations. Thanks.
package com.mspace1.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author support
 */
@Entity
@Table(name = "tFrequencies")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "TFrequencies.findAll", query = "SELECT t FROM TFrequencies t")
    , @NamedQuery(name = "TFrequencies.findById", query = "SELECT t FROM TFrequencies t WHERE t.id = :id")
    , @NamedQuery(name = "TFrequencies.findByValue", query = "SELECT t FROM TFrequencies t WHERE t.value = :value")
    , @NamedQuery(name = "TFrequencies.findByDescription", query = "SELECT t FROM TFrequencies t WHERE t.description = :description")})
public class TFrequencies implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 11)
    @Column(name = "Value")
    private String value;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 100)
    @Column(name = "Description")
    private String description;

    private List <tEXCELSMSTOSENDSchedule> schedule;

    public TFrequencies() {
    }

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

    public TFrequencies(Integer id, String value, String description) {
        this.id = id;
        this.value = value;
        this.description = description;
    }

    public Integer getId() {
        return id;
    }

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

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<tEXCELSMSTOSENDSchedule> getSchedule() {
        return schedule;
    }

    public void setSchedule(List<tEXCELSMSTOSENDSchedule> schedule) {
        this.schedule = schedule;
    }

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

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

    @Override
    public String toString() {
        return "com.mspace1.model.TFrequencies[ id=" + id + " ]";
    }
    public static void main(String [] args){

    }
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mspace1.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author support
 */
@Entity
@Table(catalog = "dbSMS", schema = "")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findAll", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findById", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.id = :id")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findBySheet", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.sheet = :sheet")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByMobileColumn", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.mobileColumn = :mobileColumn")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByTimeTosend", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.timeTosend = :timeTosend")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByUser", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.user = :user")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findBySource", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.source = :source")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByDeliverFrequency", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.deliverFrequency = :deliverFrequency")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByTimeToRun", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.timeToRun = :timeToRun")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByProcessed", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.processed = :processed")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByFrequency", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.frequency = :frequency")
    , @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByFrequencyId", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.frequencyId = :frequencyId")
, @NamedQuery(name = "tEXCELSMSTOSENDSchedule.findByFrequencyName", query = "SELECT t FROM tEXCELSMSTOSENDSchedule t WHERE t.frequencyName = :frequencyName")})
public class tEXCELSMSTOSENDSchedule implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(nullable = false)

    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Lob
    @Size(min = 1, max = 65535)
    @Column(nullable = false, length = 65535)
    private String file;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(nullable = false, length = 50)
    private String sheet;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(nullable = false, length = 20)
    private String mobileColumn;
    @Basic(optional = false)
    @NotNull
    @Lob
    @Size(min = 1, max = 65535)
    @Column(nullable = false, length = 65535)
    private String messagetemplate;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date timeTosend;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(nullable = false, length = 20)
    private String user;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(nullable = false, length = 20)
    private String source;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private int deliverFrequency;
    @Column(name = "time_to_run")
    @Temporal(TemporalType.TIMESTAMP)
    private Date timeToRun;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private short processed;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private short frequency;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private int frequencyId;
    @Basic(optional = false)
    @NotNull
    @Lob
    @Size(min = 1, max = 65535)
    @Column(name = "schedule_name", nullable = false, length = 65535)
    private String scheduleName;
    private String frequencyName;
    public tEXCELSMSTOSENDSchedule() {
    }

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

    public tEXCELSMSTOSENDSchedule(Integer id, String file, String sheet, String mobileColumn, String messagetemplate, Date timeTosend, String user, String source, int deliverFrequency, short processed, short frequency, int frequencyId,String frequencyName, String scheduleName) {
        this.id = id;
        this.file = file;
        this.sheet = sheet;
        this.mobileColumn = mobileColumn;
        this.messagetemplate = messagetemplate;
        this.timeTosend = timeTosend;
        this.user = user;
        this.source = source;
        this.deliverFrequency = deliverFrequency;
        this.processed = processed;
        this.frequency = frequency;
        this.frequencyId = frequencyId;
        this.scheduleName = scheduleName;
        this.frequencyName=frequencyName;
    }

    public Integer getId() {
        return id;
    }

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

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    public String getSheet() {
        return sheet;
    }

    public void setSheet(String sheet) {
        this.sheet = sheet;
    }

    public String getMobileColumn() {
        return mobileColumn;
    }

    public void setMobileColumn(String mobileColumn) {
        this.mobileColumn = mobileColumn;
    }

    public String getMessagetemplate() {
        return messagetemplate;
    }

    public void setMessagetemplate(String messagetemplate) {
        this.messagetemplate = messagetemplate;
    }

    public Date getTimeTosend() {
        return timeTosend;
    }

    public void setTimeTosend(Date timeTosend) {
        this.timeTosend = timeTosend;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public int getDeliverFrequency() {
        return deliverFrequency;
    }

    public void setDeliverFrequency(int deliverFrequency) {
        this.deliverFrequency = deliverFrequency;
    }

    public Date getTimeToRun() {
        return timeToRun;
    }

    public void setTimeToRun(Date timeToRun) {
        this.timeToRun = timeToRun;
    }

    public short getProcessed() {
        return processed;
    }

    public void setProcessed(short processed) {
        this.processed = processed;
    }

    public short getFrequency() {
        return frequency;
    }

    public void setFrequency(short frequency) {
        this.frequency = frequency;
    }

    public int getFrequencyId() {
        return frequencyId;
    }

    public void setFrequencyId(int frequencyId) {
        this.frequencyId = frequencyId;
    }

    public String getScheduleName() {
        return scheduleName;
    }

    public void setScheduleName(String scheduleName) {
        this.scheduleName = scheduleName;
    }

    public String getFrequencyName() {
        return frequencyName;
    }

    public void setFrequencyName(String frequencyName) {
        this.frequencyName = frequencyName;
    }

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

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

    @Override
    public String toString() {
        return "com.mspace1.model.tEXCELSMSTOSENDSchedule[ id=" + id + " ]";
    }

}

I have edited my question to add the two entities I am using. The first entity contains frequencies which I want to join with selected item from the the other entity. TFrequency table has a constant values that don't change.This frequency is mapped to tEXCELSMSTOSENDSchedule entity using ID. However, I want to select name from TFrequency and not the mapped id. This I then use to populate my data-table. Do I need to create a third entity? I am not sure how this works and I have been trying joins around with no success.

A: To do this in the "hibernate way", you need to map the tFrequencies table in a entity to get the Value from tFrequencies, creating a relationship to tFrequencies.
After that, if you not bother to return the entire entity tEXCELSMSTOSENDSchedule, you can do:
SELECT s FROM tEXCELSMSTOSENDSchedule s
JOIN s.tFrequencies t
where t.id = :idFrequency

After the query returned the result, you can access the Value from tFrequencies by the tEXCELSMSTOSENDSchedule:
tEXCELSMSTOSENDSchedule.getTFrequencies().getValue();

Tip: If you are using the Hibernate version 5.1 or superior, you don't need the relationship to do the JOIN.
Without return the entire entity
If you don't want to return the entire entity, you can pass only the informations you want using the Object array, Hibernate Tuple or a specific Dto to handle that. Using Dto, the code is like:
List<PostDTO> postDTOs = entityManager.createQuery(
"select new " +
"   com.páckage.ExcelDto("+
"       s.file, " +
"       s.sheet " + //TODO add the other attributes
"   ) " +
"from tEXCELSMSTOSENDSchedule s JOIN s.tFrequencies t" +
"where t.id = :idFrequency")
.setParameter("idFrequency", 1).getResultList();

Without mapping the table into entity
It's also possible doing that without entities (using native SQL), by the ResultTransformer, passing the informations to a DTO too.


text:
Q: Move qemu window output over the network to catch it with another PC I have an application written in C which uses qemu and its output is continuously displaying itself on the qemu window.
Now what I want is to get this output over the network.
I need some changing in the overall command of qemu. I have read the documentation.
But it is not happening the way I want.


text:
Q: CREATE EXTENSION using cloud_sql_proxy fails due to insufficient privileges My goal is to enable the ltree postgres extension in an automated way (GCP PostgreSQL extensions).
This is the query needed to create the extension
CREATE EXTENSION IF NOT EXISTS ltree;. I verified that this command works when I manually connect to the cloudsql instance using the following method. When I do this, the migrations run fine for that instance.
gcloud sql connect MyBackendInstance --user=postgres
postgres=> \c my_database;
Password:
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
You are now connected to database "my_database" as user "postgres".
mch_staging=> CREATE EXTENSION IF NOT EXISTS ltree;
CREATE EXTENSION

Now I have the following django migration from a library called django-ltree, which works perfect on my local installation.
migrations.RunSQL(
    "CREATE EXTENSION IF NOT EXISTS ltree;",
    "DROP EXTENSION ltree;"
)

However, when I run that migration in my pipeline (without manually installing the ltree connection using the method above), which uses the cloud_sql_proxy to connect to the database, I get the following error:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute
    return self.cursor.execute(sql)
psycopg2.errors.InsufficientPrivilege: permission denied to create extension "ltree"
HINT:  Must be superuser to create this extension.

The command in the pipeline is quite simple:
./cloud_sql_proxy -instances="$CLOUD_SQL_INSTANCES"=tcp:5432 -credential_file=gcloud-api-credentials.json &
python backend/manage.py migrate

The credentials to connect with the database are correctly defined in the django settings, we've been able to use these credentials to perform all kinds of migrations for ages.
I have tried creating a new user as described in this question, this did not solve the issue and thus seems unrelated.
UPDATE I tried running the cloud_sql_proxy locally, using the same authentication file to install a different extension, and that seems to work flawlessly.


text:
Q: How to download dynamically generated *.xlsx file by ajax request to JAX-RS I create .xlsx file on a server by using Apache POI library. I just can't understand whats steps I should to perform to download this file when user click on a button?
This button invoke method in JAX-RS which create .xlsx, it didn't write it to server. Is it possible to download it directly to user (without writing to the server's disk), i.e. open popup where user being asked if he want to download this file?
I tried this solution but it doesn't work:
File file = new File("test.xlsx");

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition",
            "attachment; filename=new-excel-file.xls");
        return response.build();

And ajax code:
$.ajax({
                  type: "POST",
                  url: 'api/export',
                  data: JSON.stringify(chartData),
                  headers : {
                        'Accept' : 'application/json',
                        'Content-Type' : 'application/json'
                  },
                  success: function(data){
                    alert(data);
                  }
            });

And I get error 406 error, I suspect that I should define that ajax requests accept returned data type, but don't know which data type is?
Thank you.


text:
Q: Hibernate annotation equivalent of  We're trying to migrate to Hibernate annotations from .hbm.xml files.
I'm searching for the annotation equivalent of the following XML:
<set name="someSet">
    <subselect>
        <![CDATA[some long SQL query]]>
    </subselect>
    <key column="fk" />
    <element type="MyUserType" column="value" />
</set>

I know there is @Subselect, but I'm not sure how to use it for my problem.
I found this question, but as far as I understand it, I don't want to define a View for the entire entity, but just for that one field.
Declaring it on MyUserType doesn't achieve my goal, as it would apply to everywhere MyUserType is used. Do I need to subclass MyUserType, or is there a better way?

A: @OneToMany(mappedBy = "department", fetch = FetchType.LAZY)
@Fetch(FetchMode.SUBSELECT)
private List<Employee> employees = new ArrayList<>();

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#fetching-fetchmode-subselect

A: We ended up going with database views to solve this problem.
Unfortunately it separates the query from the code, but this is the method with the least chance of breaking something accidentally.
As far as I can tell, there is no direct @Subselect-annotation to replace that hbm construct.


text:
Q: Change Scrollbar Shape (CSS3) I am making a custom scrollbar for a site. Currently I have it in an oval shape using border-radius but would like the ends to be sharp, like a triangle. I need just the handle of the scroll bar changed, and this is what I currently have for the oval shape:
::-webkit-scrollbar-thumb {
    background: #d62222;
    border-radius: 5px;
}

A: The solution you might be looking for to use percentage instead of pixel in the border-radius, for example:
::-webkit-scrollbar-thumb {
  background: #d62222;
  border-radius: 50%;
}

This way the scrollbar has a more sharp shape instead of an oval. You can play with different percentages to get what you need.


text:
Q: How to read Assembly Opcode Reference? I want to make Assembly compiler. To do that, I should make research about Assembly opcodes, so I found this on the Web. When I test to compile some codes with NASM, like this:
add eax, eax

It outputs this on Binary:

6601C0

However, when I see the reference of Assembly Opcodes, it displays this screen:

Where ADD opcode is 00, 01, 02, 03, 04, 05.
Which opcode is right? Can I use all of them, or should I use 01 (based on binary compiled with NASM).

A: What you found is just some reference that someone on the Internet put together. The authoritative reference comes from Intel and can be downloaded here: Intel® 64 and IA-32 Architectures Software Developer Manuals.
You obviously assembled the code for a 16-bit real-mode environment (like DOS), where it was assembled to 66 01 C0.

*

*Look at the first byte 66. This is called by Intel "operand-size override prefix" and in your reference "OPSIZE". It changes the size of the operands from 16-bit to 32-bit (AX to EAX). That is why I guess the environment is a 16-bit system.

*The second byte 01 is the ADD instruction in your reference on the second place in the first line. Your reference calls it ADD Ev Gv. The Intel manual calls it ADD r/m16, r16. With the operand-size override prefix you can read it as ADD r/m32, r32.

*The third byte C0 is the "Ev Gv" in your reference (Intel: "r/m32, r32"). Intel calls it "ModR/M" byte. Some bits in this byte define the target("Ev"), some bits define the source ("Gv"). Look at the table "Table 2-1. 16-Bit Addressing Forms with the ModR/M Byte" in the Intel manual.
To answer your question: No, you have to use the specific ADD instruction for the specific purpose. The ADD instructions perform different operations.


text:
Q: cart->insert(); not working in CI I check with all stack Sites and google it also. But i can't  find proper solution for this.
Any one with idea about this??

Question is data not get insert to cart. I echo data inside controller data retrieving to controller well.
  But not get inserting to cart??

Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Cart extends CI_Controller
    {
        public function  __construct()
        {
            parent::__construct();
            $this->load->library('session');
            $this->load->model('Product_Model');
            $this->load->library('cart');

        }
        public function index()
        {

        }
        public function insert_cart()
        {
            $data = array(
                'id' => $this->input->post('id'),
                'qty' => $this->input->post('qty'),
                'price' => $this->input->post('price'),
                'name' => $this->input->post('head'),
            );
            $cartdata = $this->cart->insert($data);

            if(!empty($cartdata)){
                print_r($cartdata);
            }else{
            echo "no data";
        }

//            $count = $this->cart->contents();
//            print_r($count) ;
            die();
        }
    }

in view ajex data sending.
<script>
    $(function(){
        $( "#submit" ).click(function(event) {
            event.preventDefault();

            var head= $("#head").text();
            var price= $("#price_value").val();
            var pid= $("#pid").text();
            var qty= $("#qty").val();
//         alert(price);

            $.ajax({
                type:"post",
                url: "<?php echo base_url(); ?>index.php/cart/insert_cart",
                data:{
                    head:head, price:price,pid:pid,qty:qty
                }

            });
        });
    });
</script>

A: Problem is with id in your ajax request you pass pid
head:head, price:price,pid:pid,qty:qty
                       ^^^^^^^^

So you receive pid instead of id
'id' => $this->input->post('pid'),// here receive pid not id


text:
Q: Apache reverse proxy: Should I see name of server I'm redirected to in the browser? It could be that my expectations are incorrect, but I assumed I'd see the following behavior after configuring an instance of Apache as a reverse proxy:

*

*I hit server1:9089 which runs a reverse proxy rule to forward requests to Server8:80

*My request is redirected to Server8:80 which serves content

*My browser should show me that I'm still "sitting" on server1:80, not Server8:80

I'm not seeing this. After I am redirected, the hostname of the machine that I was directed to shows up in address bar of the browser. (and was visible in the status bar of the browser during the redirect)
I thought part of the "goodness" of a reverse proxy was that it hides the machine/machines doing the heavy lifting (Server8, in this case) from the user?
Here is what (I think) is the relevant part of my httpd.conf:
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
localhost:9089

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#####PROXY
ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass / http://server8/
ProxyPassReverse / http://server8/

Can anyone give me a feel for what I'm doing wrong here? Or do I not understand something more fundamental about what a reverse proxy can and can't do for me?
Thanks much!

A: The configuration shown here is correct. What is happening is the backend server does a redirect to a login page (according to further comments from OP) which uses the server's host name for the URL.
Without knowing which backend server technology is used, I can't say how to fix that but changing this behavior will solve the problem.
Apache's proxy won't change the redirect URL in this configuration.


text:
Q: Simplest way to get First and last day of every month of the year with JodaTime I'm storing date/times in a Sqlite table as Long values, so they end up looking something like 138329292113.   The problem with this, while easy to store, is that it's harder to sort on.   I am working on a filter function that ties in to a highcharts graph, to allow users to filter the graph to certain date ranges, and therefore need to be able to filter and sum the results by day, month, etc from the tables.
The only way so far I've thought of to do this, is with the following lines of code, which will need to be repeated for each month:
LocalDate ld2 = new LocalDate();
long januaryStart = ld2.monthOfYear().withMinimumValue().dayOfMonth().withMinimumValue().toDateTimeAtStartOfDay().getMillis();
long januaryEnd = ld2.monthOfYear().withMinimumValue().dayOfMonth().withMaximumValue().toDateTimeAtMidnight().getMillis();

I would then simply add a month to January to get February, etc.  Using this, I should be able to get the millis for the beginning of the month, and the end of the month, passing this to a SQL statement to return a sum based on this range.   I've been thinking if there is a simpler way to do this for every month (or other time interval) but so far this is all I could come up with.
is there a simpler way to do this that I'm missing?
Thanks in advance!

A: I think you tried a little bit too much:
LocalDate date = new LocalDate(); // note: current date in system time zone
date = date.withMonthOfYear(1); // set to January

while (date.getMonthOfYear() < 12) {
  long monthStart = date.dayOfMonth().withMinimumValue().toDateTimeAtStartOfDay().getMillis();
  long monthEnd = date.dayOfMonth().withMaximumValue().toDateTimeAtStartOfDay().getMillis();
  // store your longs in db
  date = date.plusMonths(1);
}

Personally I would like you to reconsider your decision to store the results as absolute long-millis. This approach makes it difficult to change the stored timestamps back to plain dates. Sometimes there will not be a reversible 1:1-mapping. ANSI-SQL has the column type definition of a DATE without time or timezone. In JDBC you can then use the class java.sql.Date. Generally you should choose the data type which is most appropriate for your domain use case. A UNIX-like timestamp in millis should not be seen as all-purpose solution. So if you decide to choose a plain date instead then your code can be simplified further! Then no need for conversion to DateTime at begin of day (even timezone-dependent).


text:
Q: Haywire Match Function I am grappling with a bizarre Match malfunction which is difficult to understand and seek explanations for possible causes.
Several authors have helped compile the following code:
    Dim t1s As Long: t1s = 1
    Dim t2s As Long: t2s = 6
    Dim t1l As Long: t1l = 4 - 1
    Dim t2l As Long: t2l = 5 - 1
    Dim r As Long
    Dim rMatch As Long

    With wsR
        For r = wsR.Cells(.Rows.Count, t1s).End(xlUp).Row To 2 Step -1
            If Application.WorksheetFunction.CountIf(.Columns(t2s), wsR.Cells(r, t1s).Value) > 0 Then

                rMatch = Application.WorksheetFunction.Match(.Cells(r, t1s).Value, .Columns(t2s), 0)

                .Range(.Cells(r, t2s), .Cells(r, t2s + t2l)).Insert shift:=xlDown
                .Range(.Cells(rMatch, t2s), .Cells(rMatch, t2s + t2l)).Cut
                .Select
                .Range(.Cells(r, t2s), .Cells(r, t2s + t2l)).Select
                .Paste
                .Range(.Cells(rMatch, t2s), .Cells(rMatch, t2s + t2l)).Delete

            End If
        Next r
    End With

The code runs beautifully (match, insert, cut, paste, delete, repeat) until halfway through a dataset, at which point it then inexplicably "breaks", returning unmatched cells and shifting rows beneath the deleted row, up. This action also scrambles the prior correct results above.
I have debugged line by line and can find no clue apart from the fact it coincides with date changes in a corresponding column. Excel does have some oddities but I am convinced there is a simple explanation. Whoever knows a good place to start, please do not simply provide a solution - it's really important I learn the skill of debugging.
Many thanks.

A: Try replacing the line .Range(.Cells(rMatch + 1, t2s), .Cells(rMatch + 1, t2s + t2l)).Delete with
.Range(.Cells(rMatch + 1, t2s), .Cells(rMatch + 1, t2s + t2l)).Delete Shift:=xlUp

Edit:
Ok, I think you need to account for situations when rMatch = r and rMatch < r. See if it helps (tested it on made-up data as I don't have sample data):
    Dim t1s As Long: t1s = 1
    Dim t2s As Long: t2s = 6
    Dim t1l As Long: t1l = 4 - 1
    Dim t2l As Long: t2l = 5 - 1
    Dim r As Long
    Dim rMatch As Long

    With Sheets(1) ' wsR
        For r = .Cells(.Rows.Count, t1s).End(xlUp).Row To 2 Step -1
            If Application.WorksheetFunction.CountIf(.Columns(t2s), .Cells(r, t1s).Value) > 0 Then

                rMatch = Application.WorksheetFunction.Match(.Cells(r, t1s).Value, .Columns(t2s), 0)
                If rMatch <> r Then
                    .Range(.Cells(r + 1, t2s), .Cells(r + 1, t2s + t2l)).Insert shift:=xlDown
                    .Range(.Cells(rMatch, t2s), .Cells(rMatch, t2s + t2l)).Cut
                    .Select
                    .Range(.Cells(r + 1, t2s), .Cells(r + 1, t2s + t2l)).Select
                    .Paste
                    .Range(.Cells(rMatch, t2s), .Cells(rMatch, t2s + t2l)).Delete
                End If
            End If
        Next r
    End With


text:
Q: Undefined symbol in Poco C++ I previously compiled a simple command line program that made use of Poco C++ (which I love, by the way). The program ran perfectly for several months.
A few things must have changed on my computer, because now when I run the program, I receive the following error.
dyld: Symbol not found: __ZN4Poco4Util11Application12handleOptionERKNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEESA_
  Referenced from: /Users/me/bin/sqlmerge
  Expected in: /usr/local/opt/poco/lib/libPocoUtil.16.dylib
 in /Users/me/bin/sqlmerge

Can someone tell me why this is occurring? I compiled with Poco 1.4.6 and ran with Poco 1.4.6, even though for some reason Poco was missing from my computer and I had to reinstall with brew install poco (I'm obviously running this on a Mac).
EDIT: I'm not sure of the cause, but reinstalling with the --c++11 option turned on fixes the issue. E.g.:
brew install poco --c++11

Perhaps the C++ name mangling slightly changes from older versions of the C++ standard to C++11?

A: C++ has no Application Binary Interface.  This leads to lots of headaches, including forcing people to recompile if they upgrade compiler versions.  Same compiler, different version, different name mangling.  This is why most libraries have a C interface..for historical reasons, the C interface has stable name mangling on all known platforms.
http://morpher.com/documentation/articles/abi/
C++ ABI issues list
Herb Sutter has proposed a Stable Platform ABI for C++.  So help might be on the way :-)
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4028.pdf


text:
Q: model class inheritance (problem with view) I have 2 model classes with different attributes:
class User < ActiveRecord::Base
end

class Subuser < User
end

When I call the 'new' function within controller:
def new
 @subuser = Subuser.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @hosting }
  end
end

and try to access data with view thats held by the Subuser model (migration):
<% form_for(@subuser) do |f| %>
  <%= f.text_field :subname %>
<% end %>

I get:
undefined method `subname' for #
However, if I change it to some other cell that is defined under User model/migration, it will all work okay.
It seems like there are some isssues with the data access.
What am I doing wrong?
Thanks for help!
I get the following error

A: From the code posted, @hosting is only defined for format=xml, it won't exist for the HTML view.

A: What is the @hosting variable supposed to be?  Mike is right, you aren't defining it anywhere.
My guess is that you probably want to do something more along the lines of
form_for(@subuser) do |f|

A: Are you sure that you are properly using STI (single table inheritance) here? What is your schema for the users table?  Are you saying that you have a migration for Subuser... because if you are trying to use STI, it should use the users table with a type column.

A: Your sub model only knows what it is given via it's parent. So if your trying to access an "imaginary" attribute you will get that undefined method error.
Try added attr_accessor :subname to give it that attribute.
I'm also a bit curious about that @hosting thing...


text:
Q: Search for new line position in a VB.NET string variable using InStr I have an application in VB.NET which gets string data from the database. This string has data which looks as below:

"This is the update:
  I have an issue with the application"

I need only part of the data, that comes after the new line i.e. "I have an issue with the application".
For this I am trying to search the position using InStr where the string has data in a new line. I tried many options, but they don't work.
I used "vbCrLf", Chr(13), "\r\n", "\n", "<br/>", Environment.NewLine, but none of them work.
How can I get the data I need?

A: The newline character can be represented either by just a newline character (Chr(10)) or by a carriage return/linefeed pair (Chr(13) + Chr(10)). Depending on the source of the data this may of course vary. One way to achieve this is to make a string split on those two characters with the option to remove empty elements, throw away the first one and join the others together with newlines in between them:
ReadOnly separators As Char() = New Char() {Chr(10), Chr(13)}
Private Function StripFirstLine(ByVal input As String) As String
    Dim parts() As String = input.Split(separators, StringSplitOptions.RemoveEmptyEntries)

    If parts.Length > 1 Then
        Return String.Join(Environment.NewLine, parts, 1, parts.Length - 1)
    Else
        Return input
    End If

End Function

A: Use vbCrLf and not "vbCrLf"
It may also be that you have only line feeds or only carrige returns so using Chr(10) and Chr(13) may also be a better option.

A: I don't think I'm adding much to this discussion but for what it's worth... you can also use "ControlChars" as in "ControlChars.CrLf".
ControlChars @ MSDN

A: This script returns the string in lines and then add it to a listbox:
    Dim fileContents As String
    fileContents = My.Computer.FileSystem.ReadAllText("d:\a.txt")
    TextBox2.Text = fileContents
    Dim a As Integer = 1

    For i = 1 To fileContents.Length
        Dim xx As String = Mid(fileContents, i, 1)
        If xx = Chr(10) Then
            If Mid(fileContents, i - 1, 1) = Chr(13) Then
                ListBox1.Items.Add(Mid(fileContents, a, (i - a) - 1))
                a = i
            End If
        End If
    Next


text:
Q: velocity template when object is not null , need to replace with extra string I create one text message i.e.
"vishal is working as developer, since $obj.object[0].timeStamp"
if timeStamp is null then String should replace with
"vishal is working as developer"
So I tried like
"vishal is working as developer, #if ($obj.object[0].timeStamp) , since $obj.object[0].timeStamp" #end
it is not working please help me out

A: Have you got getters?
Please read this: How to access an object's public fields from a Velocity template
If I were you maybe I would pass the $obj.object[0].timeStamp to the velocity not only the $obj. (Especially if you need only this value from the object)
Finally for checking the null I think soorapadman's answer is perfect.


text:
Q: qt put multiple executables into one bundle on mac OSX We have 4 mac applications that form part of a 'suite', each for use with a different scientific instrument connected via USB.
My colleagues on Windows have developed a splash screen app that lets you choose one of the four separate programs to run, depending on what instrument you are using. On Windows this splash screen app is in the same folder as the other executables and all the dependencies and libraries are included in the same folder as well. So its as easy as clicking the required radio button and then that program will launch.
What I was hoping to do on Mac OS X was to bundle the 4 separate programs into one app bundle and also the splash screen, so that when the application is launched the user will be presented with the splash screen, then when you choose the appropriate app it gets launched automatically.
The dependencies and libraries are common for all the apps.
I'm comfortable building an app bundle with all the dependencies using the mac deployment tool but i'm unsure if its possible to build multiple binaries into one app bundle, and how to set the default app to be launched (the splash screen).
Thanks in advance :)
Mitch

A: Yes, multiple app bundles inside another app bundle is possible.

how to set the default app to be launched

As you're probably aware, when you build a bundle, the main executable binary file is resident in the bundle's Contents/MacOS folder.
Also in the bundle is the Info.plist file, which is a manifest that OS X uses, amongst other things, to know which binary to execute when the user runs the application. In this case, the key CFBundleExecutable names the binary in the Contents/MacOS folder.
If you copy the other application bundles to the Resources folder, you can then locate them from the Splash Screen app and execute as required.


text:
Q: Android Google maps custom image according to direction Is it possible to add custom image according to direction between two markers ? I mean I want like this:

That red arrows custom image and their direction according to marker direction. Is it possible ?

A: Here's an example (of what you can do with PHP; it appears Google does not provide the possibility of directly rotating a marker)
I took this image, and downloaded it as 15722.png:
http://cdn-img.easyicon.net/png/157/15722.png  (an arrow pointing to the right)
index.php

image.php
<?php
// @file: creates a rotated arrow. The rotation is $_GET['r'] (default 0).
$degrees = isset($_GET['r']) ? (int) $_GET['r'] : 0;
$filename = '15722.png'; // found at 'http://cdn-img.easyicon.net/png/157/15722.png', downloaded as '15722.png' in the same folder as this file

// @see http://php.net/manual/en/function.imagerotate.php , in the user comments
$source = imagecreatefrompng($filename);
imagealphablending($source, false);
imagesavealpha($source, true);

$rotation = imagerotate($source, $degrees, imageColorAllocateAlpha($source, 0, 0, 0, 127));
imagealphablending($rotation, false);
imagesavealpha($rotation, true);

header('Content-type: image/png');
imagepng($rotation);
imagedestroy($source);
imagedestroy($rotation);
?>


text:
Q: Force ul to contain floated list items: use &nbsp or overflow: auto? I don't wan't to use clearfix on all the parents above, because that would mess up my layout.
What is the best way and the correct way to do this?
I added a nbsp; after the last li and everything worked perfectly. No need for clearfix spamming. But is this the "correct" way to do it?
Edit: I've just seen List doesn't contain its floated list items.
So my new question is: what's better, &nbsp or adding overflow: auto?

A: Using overflow: auto or overflow: visible is obviously the better way but a concern may be that it may not render correctly in all browsers (*cough* Internet Explorer *cough*) with different rendering engines, etc.
In reality, if using   works, then use it.
A good article to read about floats is this one
EDIT: Don't use overflow:visible, that was just silly of me to suggest that.

A: You could us display:inline-block; to achieve the same thing.
http://jsfiddle.net/jasongennaro/w7U26/


text:
Q: Exclude from recent not working if hard recent button pressed I want to remove my activity from a recent list when it closed. I am using activity tags
android:excludeFromRecents="true"
android:noHistory="true"

This is working fine on all devices but the devices have a hard View Recent Button (Right most button). When I click on this button, recent activity still shows up in the list. Whereas when I pressed the home button first (middle button) and then the recent apps button (right most button), the app does not show up in the list.


text:
Q: Why are my getters returning null when I try to send to the server? I know this question has been asked a countless number of times on here, and I've searched SO and other sources for a solution but I just can't resolve the error. I have a getter and setter for my ClientPlayer class attribute, the setter is called in the GUI when a certain button is called, and I would like to use the getter after a client connects and send the object to the server. Calling the method "this.client.sendTCP(clientPlayer.getPlayerName());" in the ClientController returns a nullPointerException.
Error: "JavaFX Application Thread" java.lang.IllegalArgumentException: object cannot be null.
My guess would be that I create a new instance of ClientPlayer one time too many thus returning null as my string playerName is originally set to none. However, I am not sure on how to go about solving the problem. I would really appreciate any help whatsoever.
public class ClientPlayer implements Serializable {

public ClientPlayer() {

}

private String playerName;

public void setPlayerName(String playerName) {
    this.playerName = playerName;
   }

public String getPlayerName() {
    return this.playerName;
   }
}

Below the relevant part of my GUI-code where I set a button to connect the to the server:
    ClientPlayer clientPlayer = new ClientPlayer();

    clientToGame.setOnAction((ActionEvent w) -> {
         clientPlayer.setPlayerName(clientNameText.getText());
         clientController.connect();
         window.setScene(lobbyScene);
    });

Here is the bit of my client-class where I try to get the name and send to server:
    public class ClientController() {
     ClientPlayer clientPlayer = new ClientPlayer();

    public void connect() {
    if (client.isConnected()) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "You are      already connected to :{0}", config.getHost());
        return;
    }
    this.client.start();
    try {
        this.client.connect(5000, config.getHost(), config.getTCPPort());
        System.out.println("Successfully connected to " + config.getHost());
        this.client.sendTCP(clientPlayer.getPlayerName());

    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Server connection failed: {0}", ex.getMessage());
        throw new RuntimeException(ex);
    }

    MessageRegistry.registerMessages(client.getKryo());
    this.client.addListener(listener);
  }
 }

A: In your GUI, you create a ClientPlayer instance and call setPlayerName() on it. Then in ClientController, you create a new ClientPlayer instance (on which you never call setPlayerName()), and call getPlayerName() on it. Since you never set the player name for that instance, getPlayerName() of course returns null.
You need to decide whose responsibility it is to "own" the ClientPlayer instance. If it is the responsibility of the ClientController, then either add a getClientPlayer() method to ClientController, and do
clientToGame.setOnAction((ActionEvent w) -> {
     clientController.getClientPlayer().setPlayerName(clientNameText.getText());
     clientController.connect();
     window.setScene(lobbyScene);
});

and remove the ClientPlayer entirely from your GUI class. If it is the responsibility of the GUI class to own it, then pass a reference to it to the connect() method, and remove the ClientPlayer field from the controller:
public class ClientController() {
     // ClientPlayer clientPlayer = new ClientPlayer();

    public void connect(ClientPlayer clientPlayer) {
    if (client.isConnected()) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "You are      already connected to :{0}", config.getHost());
        return;
    }
    this.client.start();
    try {
        this.client.connect(5000, config.getHost(), config.getTCPPort());
        System.out.println("Successfully connected to " + config.getHost());
        this.client.sendTCP(clientPlayer.getPlayerName());

    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Server connection failed: {0}", ex.getMessage());
        throw new RuntimeException(ex);
    }

    MessageRegistry.registerMessages(client.getKryo());
    this.client.addListener(listener);
  }
 }

and of course
clientToGame.setOnAction((ActionEvent w) -> {
     clientPlayer.setPlayerName(clientNameText.getText());
     clientController.connect(clientPlayer);
     window.setScene(lobbyScene);
});

A: Ugly but should work:
Make the ClientPlayer access static. In your gui class:
public static ClientPlayer clientPlayer = new ClientPlayer();

then you can access that very same object in your ClientController via:
...
this.client.sendTCP(MyGuiClass.clientPlayer.getPlayerName());
...

Edit:
The thing is, you do not reference the "same" object via clientPlayer in your ClientController as you do in GUI-Class. You should somehow hand that object over or use a static reference. You could also hand it over in the constructor of ClientController.
Edit2:
How you should do it
ClientPlayer clientPlayer = new ClientPlayer();

    clientToGame.setOnAction((ActionEvent w) -> {
         clientPlayer.setPlayerName(clientNameText.getText());
         clientController.connect(clientPlayer);
         window.setScene(lobbyScene);
    });

In your ClientController:
public void connect(ClientPlayer player) {
    this.clientPlayer = player;
    if (client.isConnected()) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "You are already connected to :{0}", config.getHost());
        return;
    }
    this.client.start();
    try {
        this.client.connect(5000, config.getHost(), config.getTCPPort());
        System.out.println("Successfully connected to " + config.getHost());
        this.client.sendTCP(player.getPlayerName());

    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Server connection failed: {0}", ex.getMessage());
        throw new RuntimeException(ex);
    }

    MessageRegistry.registerMessages(client.getKryo());
    this.client.addListener(listener);
}


text:
Q: How to delete a specifil line by line number in a file? I'm trying to write a simple Phyton script that alway delete the line number 5 in a tex file, and replace with another string always at line 5. I look around but I could't fine a solution, can anyone tell me the correct way to do that? Here what I have so far:
#!/usr/bin/env python3
import od
import sys
import fileimput

f= open('prova.js', 'r')
filedata = f,read()
f.close ()

newdata = "mynewstring"

f = open('prova.js', 'w')
f.write(newdata, 5)
f.close

basically I need to add newdata at line 5.

A: One possible simple solution to remove/replace 5th line of file. This solution should be fine as long as the file is not too large:
fn = 'prova.js'
newdata = "mynewstring"
with open(fn, 'r') as f:
    lines = f.read().split('\n')
    #to delete line use "del lines[4]"
    #to replace line:
    lines[4] = newdata
with open(fn,'w') as f:
    f.write('\n'.join(lines))

A: I will try to point you in the right direction without giving you the answer directly.  As you said in your comment you know how to open a file. So after you open a file you might want to split the data by the newlines (hint: .split("\n")). Now you have a list of each line from the file. Now you can use list methods to change the 5th item in the list (hint: change the item at list[4]).  Then you can convert the list into a string and put the newlines back (hint: "\n".join(list)). Then write that string to the file which you know how to do. Now, see if you can write the code yourself. Have fun!


text:
Q: orchard cms built in datetime field How can i plug my date time field in place of built in one?
I want to change date time field repository type from datetime to string not just for my modules but also for all wxisting fields like page creation date time.


text:
Q: bluetoothctl: using gatt menu commands in non-interactive mode On my Raspberry Pi 4, I would like to use bluetoothctl in non interactive mode but cannot figure out how to access the gatt menu. The command should be something like "bluetoothctl gatt menu list-attributes" but this syntax doesn't work.
For info, in interactive mode one must type "menu gatt" to switch to gatt menu and then commands like "list-attributes" are available.
Thanks in advance !
Eric

A: bluetoothctl allows for the commands to be specified using a dot to indicate the hierarchy. e.g gatt.list-attributes
For accessing information with code BlueZ provides APIs using D-Bus bindings.
For example, to get all the information BlueZ has can be done like this:
import pydbus
bus = pydbus.SystemBus()
obj_mngr = bus.get('org.bluez', '/')
mngd_objs = obj_mngr.GetManagedObjects()
for path, obj in mngd_objs.items():
    print(obj)

The API is documented at:
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc
Examples are available at:
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/test


text:
Q: A characterization of finitely cogenerated modules Let $R$ be a ring with unity and $M$ a right $R$-module. Recall that $M$ is called a finitely cogenerated module if for every collection $\lbrace A_i \rbrace_{i\in I}$ of submodules with $\bigcap_{i\in I}A_i=0$ there exists a finite subset $J\subset I$ with $\bigcap_{j\in J}A_j=0$.
I need to prove the following result.

If the intersection of every chain of nonzero submodules of $M$ is nonzero, then $M$ is finitely cogenerated.

I made the following proof which is not complete:
Proof. Let $\lbrace B_i \rbrace_{i\in I}$ be a collection of submodules of $M$ with $\bigcap_{i\in I}B_i=0$. Suppose that for every finite subset $J\subset I$, $\bigcap_{j\in J}B_j \neq 0$. If $K:=\lbrace i_1,i_2,\ldots \rbrace \subseteq$, then $B_{i_1} \cap B_{i_2} \supseteq B_{i_1} \cap B_{i_2} \cap B_{i_3} \supseteq \ldots$ is a descending chain of nonzero submodules. By the hypothesis, $\bigcap_{i\in K}B_i \neq 0$. This shows that every countable intersection of nonzero submodules is nonzero.
How can I prove that the intersection $\bigcap_{i\in I}B_i \neq 0$ to get a contradiction.
I need any help. Thanks in advance.

A: Just continue by induction on the cardinality of the index set $I$.  That is, prove by induction on $|I|$ that if $(B_i)_{i\in I}$ is a family of submodules of $M$ whose finite intersections are all nonzero, then $\bigcap_{i\in I} B_i$ is nonzero.  You have already shown this when $I$ is countable.  In general, suppose that this is known for all cardinalities smaller than $|I|$.  You can then write $I$ as the union of a chain of subsets $J_\alpha$, each of which has cardinality less than $I$ (for instance, pick a well-ordering of $I$ of length $|I|$ and let the $J_\alpha$ be the initial segments).  Then $\bigcap_{i\in J_\alpha}B_i$ is nonzero for each $\alpha$ by the induction hypothesis, and these modules then form a chain whose intersection is $\bigcap_{i\in I}B_i$.


text:
Q: Rails 6 : How to retreive a csv file in /tmp in order to send via API I'm building a CRON JOB in order to create a CSV file once a month and send it to an API
My method bellow generates a csv file in /tmp folder
  def save_csv_to_tmp
    f = Tempfile.create(["nb_administrateurs_par_mois_#{date_last_month}", '.csv'], 'tmp')
    f << generate_csv
    f.close
  end

Now, in the perform method, I have to retreive this csv file but I do not know how to do it :
def perform(*args)
    # creates the csv file in tmp folder
    save_csv_to_tmp
    # TODO : retreive this csv file and send it to the API
  end

A: You can do something like this (Using the block version of Tempfile#create, it will automatically close and unlink the temporary file):
  def save_csv_to_tmp
    Tempfile.create(["nb_administrateurs_par_mois_#{date_last_month}", '.csv'], 'tmp'] do |f|
      f << generate_csv
      # You might need to call `f.rewind` here
      # so that your service object can use the file object right away

      yield f if block_given?
    end
  end

And in perform
def perform(*args)
    save_csv_to_tmp do |file|
       # Send file to API
       SendFileService.new(file: file).call # Or something similar
    end
end


text:
Q: altering a list in a text file with Python I am brand new to Python and am trying to alter a list in a text file. I'm taking a list from Oracle and want to add information to the list so I can paste it into a script. I would like to:
1. open the text file
2. for each line in the text file, concatenate it with some other text
3. rewrite the text file (or create a new one) to contain the new altered lines
ie.:
   if my list has these lines:
  -NorthAmerica
  -SouthAmerica
  -Asia

I want to rewrite the list with this text concatenated with it:
GRANT SELECT ON GEODATA. + line + TO GEO_VIEWER;

so it would ultimately look like this:
GRANT SELECT ON GEODATA.NorthAmerica TO GEO_VIEWER;
GRANT SELECT ON GEODATA.SouthAmierica TO GEO_VIEWER;
GRANT SELECT ON GEODATA.Asia to GEO_VIEWER;

Any help is appreciated. Thank you!

A: So here's what I would recommend:

*

*Open both files using the with structure

*Use a format() function to write the contents of file 1 into preset string, then into file 2

So the code elements would look something like this:
with open("file_to_be_read.txt", 'r') as fread, open("file_to_be_written.txt", 'w') as fwrite:
    for line in fread:
        fwrite.write("GRANT SELECT ON GEODATA.{} TO GEO_VIEWER;\n".format(line[1:]))

You may need to tweak the format() function a bit to get exactly what you want.  Right now it just does the whole line of fread except the first character.
Since you're new at this, here's some more in-depth explanation of what's going on:
The with structure is very useful when working with files, since it handles closing and a few other things.  This means with with, it is much less likely that you end up with errors because you forgot to close a file.  So,
with open("file.txt") as f:
    #Do stuff

Is equivalent to,
f = open("file.txt")
#Do stuff
f.close()

In addition to making your code less error prone, it also improves readability.
The format() function is an incredibly useful (and slightly cryptic) tool for working with strings in Python.  The short version is that any {} within the string to which format() is applied, get filled with the arguments of the function.  So
print "Hello, my name is {}".format("Dave")

Produces
"Hello, my name is Dave"

Now, this is a silly example of course, but there is a huge amount of flexibility in the function.  There's even a whole mini-language for the formatting syntax!  You can use this for tables, producing fancy output, or all sorts of things.

A: You should include what code you have done so far and since you haven't done this, I am not going to give you the full code but the tools and skills you need to do this yourself.
Okay, so problem 1. Opening a textfile. When we do this, we have several ways we can open the file such as read, write, append, readwrite. If you want the full list, you can see it here. For our job we need to read and write to the file. So we want Readwrite or (if you look on your table) r+. So first, let's do that.
with open('your_file_name.txt','r+') as file:

So we have our file opened. Now what?
We next need to read the file. Thanks to Pyhton's great dev's, we use an amazingly simply named function: .read(). So we have our file opened and saved in the variable file. Let's read it.
    countries = file.readlines()

But wait, I hear you ask, you said read and you've used readlines. This is because if we used read, we would have got a simple string but readlines will return us a list that we can loop through. Okay, so we have a list of strings that need to be written back to the file. So, let's do that. Surprisingly again we have a simply named function called write.
    for country in countries: #Loop through all the countries we just read
        file.write('GRANT SELECT ON GEODATA. ' + country + ' TO GEO_VIEWER')

This should do it, although you may want to play around with opening files in different ways. For example open one file by doing with open('yourfile.txt','r') and opening the one containing countries to read. Then, make a new file by using with open('newfile.txt','w') and then write them to this file! Play around! Hope I helped!


text:
Q: Transform JavaScript getElementById to PHP
How do I transform these .getElementIds and the last line into PHP code? I've been struggling mightily on how to tackle these.

A: I am not sure if this solves your issue, but if you're trying to use a javascript code inside a .php file, you can just echo the js code. e.g.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="first-name-field">
  Howdy
  </div>
</body>
</html>

<?php

echo "
            <script type=\"text/javascript\">
            var e = document.getElementById('first-name-field')
            console.log(e);
            </script>";
?>

Hope this solves your issue

A: I don't understand but if you mean to send your attr to PHP/server then do something like (Post data to server).
$.post("hello.php", {
    firstName: firstName,
    city:city,
    zip:zip
  }, function(result){
    alert(result);
  });
});

hello.php is a file sitting on the server to serve your request, bellow is a code in hello.php
<?php echo $_POST['city']; ?>


text:
Q: iTunes music API for accessing user's play history I know I can use MPMediaQuery to query songs on the device, and from there I can get play counts from MPMediaItem. This is good, but assume that the user played a song 100 times on their computer and did not sync this song to their device. Is there an API outside the iOS SDK that allows me to retrieve a user's play history from their iTunes account? I assume the answer is no, but just wanted to make sure there are no other ideas on how to do this.

A: Sorry, but there is no way you could retrieve a user's play history from their iTunes account.


text:
Q: Calculating angle using Pythagoras' theorem I'm finishing an assignment. But I've been bashing my head against one problem with it and can't work it out.
I'm supposed to be calculating the angle in degrees and distance between 2 points, rounded to 3 decimal places. Everything is working fine but the angle it's putting out is wrong
double angleInRadians = Math.Atan2(point2X, point1X) - Math.Atan2(point2Y, point1Y);

This should be correct right? But it just keeps saying 0 when it should be saying 45 degrees. I've checked and the calculation for converting it into degree is correct, it's getting the angle in radians that is playing up
Does anyone know what's wrong with it?

A: You can't compute angle between two points. But in case of "angle we'd have to move in to go from point 1 to point 2" it's
double angle = Math.Atan2(point2Y - point1Y, point2X - point1X) / Math.PI * 180.0;

Computing this angle is the very thing Atan2 is designed for. Some tests:
(1, 0), (0, 1) -> 135
(1, 0), (5, 0) ->   0
(5, 0), (1, 0) -> 180
(0, 1), (1, 0) -> -45


text:
Q: Create a list from a complex comparison of two lists I am working on market transaction data where each observation contains the value of the variable of the buyer's id, and the value of the variable of the seller's id. For each observation (i.e each transaction), I would like to create a variable equal to the number of other transactions the associated seller has done with a different buyer than the one involved in this transaction. As a consequence, in the following
data <- data.frame(Buyer_id = c("001","001","002","001"), Seller_id = c("021","022","022","021"))

I would like to obtain:
Result <- list(0,1,1,0)

I searched for already existing answers for similar problems than mine, usually involving the function mapply(), and tried to implement them, but it proved unsuccessful.
Thank you very much for helping me.

A: Are you looking for something like this? If yes, then you might want to change your reproducible example to have a c instead of list when you construct your data.frame.
data <- data.frame(Buyer_id = c("001","001","002","001"),
                   Seller_id = c("021","022","022","021"))

data$n <- NA
for (i in seq_len(nrow(data))) {
  seller <- as.character(data[i, "Seller_id"])
  buyer <- as.character(data[i, "Buyer_id"])

  with.buyers <- as.character(data[data$Seller_id == seller, "Buyer_id"])
  with.buyers <- unique(with.buyers)

  diff.buyers <- with.buyers[!(with.buyers %in% buyer)]

  data[i, "n"] <- length(diff.buyers)
}

  Buyer_id Seller_id n
1      001       021 0
2      001       022 1
3      002       022 1
4      001       021 0

A: Apart from Roman Lustrik's solution, there is also an approach that uses graphs.
library(igraph)

data <- data.frame(Seller_id = c("021","022","022","021"),
                   Buyer_id = c("001","001","002","001"),
                   stringsAsFactors = FALSE)

my.graph <- graph_from_data_frame(data)
plot(my.graph)
degree(my.graph, mode = c("out"))

# Transform the graph into a simple graph. A simple graph does not allow
# duplicate edges.
my.graph <- simplify(my.graph)
plot(my.graph)
degree(my.graph, mode = c("out"))

V(my.graph)$out.degree <- degree(my.graph, mode = c("out"))

data$n <- apply(data,
                MARGIN = 1,
                FUN = function(transaction)
                {
                  node.out.degree <- V(my.graph)$out.degree[ V(my.graph)$name == transaction["Seller_id"] ]

                  if (node.out.degree <= 1) {
                    # Since the vertex has at most 1 out degree we know that the current transaction
                    # is the only appearance of the current seller.
                    return(0)
                  } else {
                    # In this case, we know that the seller participates in at least one more
                    # tansaction. We therefore simply subtract minus one (the current transaction)
                    # from the out degree.
                    return(node.out.degree - 1)
                  }

                })

data


text:
Q: Best way to store tokens during lexing stage Hi I am currently implementing a lexer that breaks XML files up into tokens, I'm considering ways of passing the tokens onto a parser to create a more useful data structure out of said tokens - my current plan is to store them in an arraylist and pass this to the parser , would a link list where each token points to the next be better suited? Or is being able to access tokens by index easier to make a parser for? Or is this all a terrible strategy?
Also if anyone has used antlr , I know it uses a token stream to pass tokenized input to the parser, how can the parser make decisions on if the input is valid / create a data structure if it does not have all the tokens from the input yet?
Any feedback / opinion welcome, thanks!

A: The most common architecture for this type of parser, to run the lexer inside your parser. Every time you need a token , make a call to a function (from lexer) that retrieves the next one.
I don't know Antlr, but I think they all uses the same. What I'm proposing is how the yacc and lex work.


text:
Q: cannot delete nodes and visualize in cayley database I am playing little bit with cayley database and I run to some problems. I am using last version 0.4, with nodejs, npm package (https://www.npmjs.org/package/cayley), mongoDB and angular.
Anyway first problem is that I cannot visualize any nodes. I am getting error "Uncaught The node must have a string id.". When I run g.V().All() I get:
{
 "result": [
  {
  "id": "alice"
  },
  {
   "id": "bob"
  },
  {
   "id": "follows"
  },
  {
   "id": "John"
  },
  {
   "id": "Subject Node"
  },
  {
   "id": "Object Node"
  },
  {
   "id": "Predicate Node"
  }
 ]
}

As I see it all my nodes has string ID, maybe I am missing something.
Second problem is deleting nodes or quads. As I mention I am using npm package and also the example from bottom
client.delete([{
  subject: "Subject Node",
  predicate: "Predicate Node",
  object: "Object Node"
}], function(err, body, res) {

});

When I run it I get successful message that I have deleted 1 tripple but nodes are still there. Also quad. One thing I noticed is that in quads appeared this:
"Deleted" : [
    NumberLong(9)
]

EDIT 1:
I sucessfully visualized data:
<moving> <name> "Moving" .
<moving> <description> "Basic object action." .
<moving> <parent> <walking> .
<moving> <parent> <running> .
<walking> <name> "Walking" .
<walking> <description> "Slow moving." .
<running> <name> "Running" .
<running> <description> "Fast moving." .

by running this:
moving = g.M("moving")
g.V().As("source").Follow(moving).Out("parent").Out("name").As("target").All()


text:
Q: Cell mode in Python editors In recent versions of MATLAB, one can execute a code region between two lines starting with %% using Ctrl-Enter. Such region is called a code cell, and it allows for fast code testing and debugging.
E.g.
%% This is the beginning of the 1st cell

a = 5;

%% This is the end of the 1st cell and beginning of the 2nd cell

% This is just a comment
b = 6;

%% This is the end of the 2nd cell

Are there any python editors that support a similar feature?
EDIT: I just found that Spyderlib supports "block" execution (code regions separated with blank lines) with F9, but as the this thread mentions, this feature is still not very robust (in particular in combination with loops).

A: The Interactive Editor for Python IEP has a Matlab-style cell notation to mark code sections (by starting a line with '##'), and the shortcut by default is also Ctrl+Enter:
## Cell one
"""
A cell is everything between two commands starting with '##'
"""
a = 3
b = 4
print('The answer is ' + str(a+b))

## Cell two

print('Hello World')

A: Spyder3 defines a cell as all code between lines starting with #%%.
Run a cell with Ctrl+Enter, or run a cell and advance with Shift+Enter.

A: Spyder3 & PyCharm: #%% or # %%
Spyder3: Ctrl+Enter: to run current cell, Shift+Enter: to run current cell and advance.
PyCharm: Ctrl+Enter: to run and advance
# %%

print('You are in cell 1')

# %%

print('You are in cell 2')
# %%

print('You are in cell 3')

enter image description here

A: Pyscripter supports block execution. But it's Win only. And it's limited to select code block - > run it(Ctrl+F7). No notion of cells.

A: IDLE with IdleX has support for Matlab-like and Sage-like cells using SubCodes. Code in between '##' markers can be executed with Ctrl+Return. It also allows for indented markers so that indented code can be executed.

A: I have written a vim plugin in which cells are delimited by ## . It sends cells to an ipython interpreter running in tmux. You can define key mappings to execute the current cell, execute current cell and move to next or execute the current line :
https://github.com/julienr/vim-cellmode
I recently started working on a similar plugin for Intellij PyCharm. It can send the cell to either the internal python console (which has some issues with plots) or to an ipython interpreter running in tmux :
https://github.com/julienr/pycharm-cellmode

A: There is Sage that offers something like this. It is meant to be a python alternative to Matlab, you should take a look.
In a sage notebook, you write python commands within blocks that are pretty similar to matlab's cell.


text:
Q: If the sum of the distances is the distance from start to finish, show that the points are collinear
For a natural number $n$, let $x_0,\ldots,x_n\in\mathbb{R}^k$. Suppose $$d(x_0,x_n)=\sum_{i=0}^{n-1}d(x_i,x_{i+1}).$$ Prove that there exist real numbers $0\leq t_1\leq \cdots\leq t_n\leq 1$, such that $x_i=(1-t_i)x_0+t_ix_n$ for each $0<i<n$.

A: Equality holds in the triangle inequality $d(x,z) \le d(x,y) + d(y,z)$ for $x,y, z \in \mathbb R^n$ when the points are collinear with $y$ between $x$ and $z$. (hint: you can use Cauchy-Schwarz to prove the triangle inequality, including the equality case).
This gives you the case when $n = 2$. Then use induction on $n$ in your problem.

A: This does not hold with $d(x,y) = \|x-y\|_\infty$. Take the points $x_1 = (0,0), x_2 = (1,1), x_3 = (2,1)$ in $\mathbb{R}^2$. Then $d(x_1,x_3) = d(x_1,x_2)+d(x_2,x_3)$, but the points are clearly not collinear.


text:
Q: Flash Run-Time performance testing Lee Brimelow got me thinking about my Flash Application CPU and Memory consumption in his blog. So I'm thinking if there is a good (non task manager) tool for performance testing?

A: you can measure your FPS if you want ... you can put your FPS to the max your system allows ... and then watch the framerate drop as you run your app ... it's at leas an indicator ... :)
you can use flash.system::System.totalMemory to have the memory used ...
also, you should have a look at the sampler package ... it can help you identify some bottle necks in your code etc. ...
greetz
back2dos

A: For a simple performance stats display, check out Mr. Doob's Stats class.
For a more in-depth look into your application's performance, there is FlashPreloadProfiler.


text:
Q: No sound coming from embed YouTube video When I run the following code in my iOS simulator I get sound from the embed YouTube video.  When I run this on my iPhone 6 I get no sound coming from the speakers but I do get sound from the headphones. Is this a hardware issue or is it software?
import UIKit

class ThreeKeyViewController: UIViewController {

@IBOutlet weak var videoView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let youTubeUrl = "https://www.youtube.com/embed/hP-vuMaoHjU"
    videoView.allowsInlineMediaPlayback = true

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        self.videoView.loadHTMLString("<iframe width=\"\(self.videoView.frame.width)\" height=\"\(self.videoView.frame.height)\" src=\"\(youTubeUrl)\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil)

        print("This is run on the main queue, after the previous code in outer block")
    })
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

A: SWIFT 2.0 version I have the same problem for me the solution was to add in the AppDelegate. Thanks to Daleks. Must not forget to Import AVFoundation.
Import UIKit
import AVFoundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    }
    catch let error as NSError {
        print(error)
    }

    do {
        try AVAudioSession.sharedInstance().setActive(true)
    }
    catch let error as NSError {
        print(error)
    }
    return true
}enter code here


text:
Q: NSData to [String : AnyObject] I have some legacy code I am porting to Swift 2.0 which is producing an error, where previously it had worked ok.
The error is : Cast from 'NSData?' to unrelated type '[String : AnyObject]' always fails
Prior to moving the code to a new project I did not receive the error and the code had worked just fine.
Code:
    func RestApiRequest(RestPath RestPath:String, Method:Alamofire.Method, Headers:NSDictionary?, Body:AnyObject?,ContentType:String,
    OnCompletion:(StatusCode:Int, ResponseData:NSData, inout ResponseError:NSError?) -> (Void))
{
    //Set REST url to be called
    let mutableURLRequest = NSMutableURLRequest(URL:  NSURL(string: "\(self.baseUrl!)\(RestPath)")!)
    //Store body data if it exists
    var data:  NSData?
    //Check if body value is set
    if(Body != nil) {

        //Check if body is a dictionary
        if(Body is NSDictionary){
            //Convert to JSON
            let jsonBody = JSON(Body!)
            data = try! jsonBody.rawData()
        }
        //Check if body is an array
        else if(Body is NSArray) {
            //convert to json
            let jsonBody = JSON(Body!)
            data = try! jsonBody.rawData()
        }
        else {
            let bodyData = Body?.dataUsingEncoding(NSUTF8StringEncoding)
            data = bodyData
        }
    }

    let manager = Alamofire.Manager.sharedInstance
    manager.session.configuration.HTTPAdditionalHeaders = Headers as? [NSObject : AnyObject]

    manager.request(Method,mutableURLRequest, parameters: data as? [String : AnyObject], encoding: .Custom({ (convertible, params) in

        let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
        if(data != nil) {
            mutableRequest.HTTPBody = data
        }

        return (mutableRequest, nil)
    })).response { (request, response, data, error) in
        var _error = error
        print(request)
        print(NSString(data: data!, encoding:NSUTF8StringEncoding))
        OnCompletion(StatusCode: (response?.statusCode)!, ResponseData: data!, ResponseError: &_error)

    }
}

}
Is there a way to successfully make this conversion without producing an error?


text:
Q: Users and user roles not shown in WordPress when Toolset Type-Access is active I just figured a strange behavior in the Toolset's Type-Access plugin. I think this si the same case as this unresolved issue.
I my case, it's a multisite context, so users can exists in others sites, specially super-admins.
Logged as super-admin, when Type-Access is active, the user-list of a blog is empty, so is the role list when I want to add a new user.
Strangely, in cli (wp role list, wp user list) -mode, users and roles are well shown.

A: After many cache clear and transient deletion, I found the solution, diving in the code of Type-Access.
WordPress roles are filters via the editable_roles hook, which reliates to the UserListing::get_excluded_roles method. In shot, this method return the intersection of global roles and the current user's roles. But if the current user is superadmin and do not have explicit roles, this list is empty, and no roles nor users are displayed.
The solution is to manually add administrator role to any superadmin.
wp user set-role THE_USERNAME administrator [--url=thesiteurl]


text:
Q: Escaping reserved words in MySQL: Unknown column 'PASSWORD' in 'field list' My problem is with regards to JDBC SQL. What i want to do is use my username in the employee entity to retrieve the password for my login. I have a datainitalization singleton bean to prepopulate my system admin.
Error Message in GlassFish.
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.1.v20150605-
31e8258): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column
'PASSWORD' in 'field list'
Error Code: 1054
Call: SELECT EMPLOYEEID, ACCESSRIGHT, ADDRESSLINE1, ADDRESSLINE2,
CONTACTNUMBER, FIRSTNAME, LASTNAME, PASSWORD, POSTALCODE, USERNAME FROM
EMPLOYEE WHERE USERNAME LIKE ?
bind => [1 parameter bound]
Query: ReadAllQuery(referenceClass=Employee sql="SELECT EMPLOYEEID,
ACCESSRIGHT, ADDRESSLINE1, ADDRESSLINE2, CONTACTNUMBER, FIRSTNAME, LASTNAME,
PASSWORD, POSTALCODE, USERNAME FROM EMPLOYEE WHERE USERNAME LIKE ?")

My method to retrieve password for login using username
    @Override
public Employee retrievePasswordByUsername(String username) throws UserNameNotFoundException
{
    //SELECT sl FROM SystemLogin sl WHERE sl.userName  = :inUserName
   return (Employee) em.createQuery("SELECT e FROM Employee e WHERE e.username LIKE :inUsername").setParameter("inUsername", username).getResultList();

}

This is my attempt to do a login method.
@Override
public Employee employeeLogin(String username, String password) throws
InvalidLoginCredentialException
{

    Employee employee = null;
    try {
        employee = retrievePasswordByUsername(username);
    } catch (UserNameNotFoundException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    }

     if(employee.getPassword().equals(password))
        {
            return employee;
        }
        else
        {
            throw new InvalidLoginCredentialException("Username does not exist or invalid password!");
        }
    }

Lastly, this is the singleton bean that i mention for my system admin
     private void initializeData()
    {
        try {
            employeeControllerLocal.createNewEmployee(new Employee("Default",
    "Administrator", "99999999", "NUS", "Computing","599999",
    EmployeeAccessRight.ADMINISTRATOR, "admin", "password"));
        } catch (EmployeeExistException ex) {

 Logger.getLogger(DataInitializationSessionBean.class.getName()).log(Level.SEVERE
        , null, ex);
        } catch (GeneralException ex) {

  Logger.getLogger(DataInitializationSessionBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

This is part of my employee entity class.
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;
@Column(length = 32, nullable = false)
private String firstName;
@Column(length = 32, nullable = false)
private String lastName;
@Column(length = 32, nullable = false)
private String contactNumber;
@Column(length = 32, nullable = false)
private String addressLine1;
@Column(length = 32, nullable = false)
private String addressLine2;
@Column(length = 32, nullable = false)
private String postalCode;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private EmployeeAccessRight accessRight;
@Column(unique = true)
private String username;
@Column(length = 32, nullable = false)
private String password;

Thanks everyone for reading this! Hope i'll find a solution soon. :)
PS: This question has been solved. I've also posted one link for anyone who needs to check if they need to escape any reserved words:
https://dev.mysql.com/doc/refman/5.7/en/keywords.html

A: As PASSWORD is a reserved work you need to explicitly specify the escaped column name on your mapping
@Column(length = 32, nullable = false)
private String password;

Should be changes either to
@Column(name = "`PASSWORD`", length = 32, nullable = false)
private String password;

or to
@Column(name = "\"PASSWORD\"", length = 32, nullable = false)
private String password;

based on what variant is supported by your MySQL configuration (some details here)


text:
Q: make 2D density plot from python dictionary I have a dictionary which contains multiple values for each key.
dict = {'400.0': [0.051198, 0.051198, 0.045406, 0.15855, 0.33586, 0.079011, 0.085342], '420.0': [0.046287, 0.046287, 0.0061685, 0.099437, 0.27868, 0.093667, 0.093032], '440.0': [0.046454, 0.046454, 0.0015765, 0.052886, 0.23238, 0.084899, 0.088889], '460.0': [0.041944, 0.041944, 0.0083426, 0.027038, 0.19666, 0.032842, 0.07963], '480.0': [0.025476, 0.025476, 0.021437, 0.02845, 0.16916, 0.066085, 0.11551], '500.0': [0.037221, 0.037221, 0.02546, 0.01049, 0.14636, 0.15647, 0.17047], '520.0': [0.020769, 0.020769, 0.057708, 0.013889, 0.11284, 0.17052, 0.15862], '540.0': [0.0029368, 0.0029368, 0.086186, 0.026225, 0.090237, 0.098873, 0.072785], '560.0': [0.0024553, 0.0024553, 0.1034, 0.057088, 0.077615, 0.048153, 0.037146], '580.0': [0.020523, 0.020523, 0.105, 0.076162, 0.067578, 0.047222, 0.062943], '600.0': [0.042838, 0.042838, 0.09883, 0.077351, 0.056873, 0.048235, 0.096264], '620.0': [0.05615, 0.05615, 0.096128, 0.073473, 0.046765, 0.031932, 0.10801], '640.0': [0.065999, 0.065999, 0.093658, 0.088445, 0.040698, 0.0082049, 0.095002], '660.0': [0.099263, 0.099263, 0.074047, 0.13282, 0.041967, 0.016028, 0.1117], '680.0': [0.14634, 0.14634, 0.028374, 0.19581, 0.071541, 0.036822, 0.14719], '700.0': [0.13285, 0.13285, 0.023217, 0.23739, 0.0053786, 0.059918, 0.17545]}

The keys are the "x" values, and the dictionary values are are the "y" values.
Now I would like to make a density plot. Is this possible with matplotlib and if yes, how ? Thank you very much.
EDIT:
I think plt.imshow is a good option

A: This will do the work I guess. Please check and let me know. Thank you.
import pandas as pd
import matplotlib.pyplot as plt

dict1 = {
        '400.0': [0.051198, 0.051198, 0.045406, 0.15855, 0.33586, 0.079011, 0.085342],
        '420.0': [0.046287, 0.046287, 0.0061685, 0.099437, 0.27868, 0.093667, 0.093032],
        '440.0': [0.046454, 0.046454, 0.0015765, 0.052886, 0.23238, 0.084899, 0.088889],
        '460.0': [0.041944, 0.041944, 0.0083426, 0.027038, 0.19666, 0.032842, 0.07963],
        '480.0': [0.025476, 0.025476, 0.021437, 0.02845, 0.16916, 0.066085, 0.11551],
        '500.0': [0.037221, 0.037221, 0.02546, 0.01049, 0.14636, 0.15647, 0.17047],
        '520.0': [0.020769, 0.020769, 0.057708, 0.013889, 0.11284, 0.17052, 0.15862],
        '540.0': [0.0029368, 0.0029368, 0.086186, 0.026225, 0.090237, 0.098873, 0.072785],
        '560.0': [0.0024553, 0.0024553, 0.1034, 0.057088, 0.077615, 0.048153, 0.037146],
        '580.0': [0.020523, 0.020523, 0.105, 0.076162, 0.067578, 0.047222, 0.062943],
        '600.0': [0.042838, 0.042838, 0.09883, 0.077351, 0.056873, 0.048235, 0.096264],
        '620.0': [0.05615, 0.05615, 0.096128, 0.073473, 0.046765, 0.031932, 0.10801],
        '640.0': [0.065999, 0.065999, 0.093658, 0.088445, 0.040698, 0.0082049, 0.095002],
        '660.0': [0.099263, 0.099263, 0.074047, 0.13282, 0.041967, 0.016028, 0.1117],
        '680.0': [0.14634, 0.14634, 0.028374, 0.19581, 0.071541, 0.036822, 0.14719],
        '700.0': [0.13285, 0.13285, 0.023217, 0.23739, 0.0053786, 0.059918, 0.17545]}

df = pd.DataFrame(dict1)

df.plot.density()
plt.show()

A: If you want to use keys along x-axis and values along y-axis, you could just:
import matplotlib.pylab as plt

fig=plt.figure();
ax=fig.add_subplot(111);
ax.plot(dict.keys(),dict.values(),marker='.',ms=10,linestyle='none');
plt.show();

Nevertheless, this is just scatter plot. What do you mean by density plot?


text:
Q: Expressjs variable value is not updating In below code snippet, I declare one variable named sumOfRevenue. I set its value as 10 in router and then try to print its value but I am getting it blank. So may I know why I got blank rather then 10?
Please check below code and attached screenshot.

const express = require('express')
var router = express.Router()
const client = require('../models/db')

/* I defined sumOfRevenue variable as below */
sumOfRevenue = ""

router.get('/getSites', async(req, res) => {
  await client.query('select sum(revenue) from deals ', (error, results) => {
    if (!error)
      /* Here I just store static value as 10 to this variable */
      sumOfRevenue =10
    })
    /* Here when I want to get that value but it gives blank */
    console.log("sumOfRevenue is:" + sumOfRevenue);
});

module.exports = router

A: *

*You need to add var or let to declare your variable.

*You need to be sure "!error" is equal to "true" (console.log(!error))


text:
Q: How can we specify keytab based login information for multiple user principals while using Java GSS-API with Kerberos? I am using Java GSS-API with Kerberos for secure Authentication. I want to connect to two different KDC Servers from single Client program to access multiple services. For that I am using configuration file krb5.conf as shown below:
[libdefaults]
default_realm = HOST1
udp_preference_limit = 1
[realms]
HOST1 = {
    kdc = host1:88
}
HOST2 = {
    kdc = host2:88
}

For login, I am using keytab based login with configuration as shown below:
com.sun.security.jgss.initiate {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=true
  keyTab=user.keytab
  principal="user1@LOCALHOST"
  storeKey=true;
};

com.sun.security.jgss.accept {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=true
  keyTab=service.keytab
  principal="service1@LOCALHOST"
  storeKey=true;
};

This configuration requires principle name to be mentioned as a part of configuration file. Now the problem is that we can specify only one principle name in the configuration, but I want to access multiple services requiring login for multiple principal names. How can I specify login information for multiple user principals?


text:
Q: How do I increase an INT value in a postgres vote table I created an API for voting a question, but its not working. How can I implement vote to increase no_votes by 1 whenever the upvote api is called on. Here is what I have tried
exports.upvote_question = async (req, res) => {
    const text = `INSERT INTO
    votes(id, questionId, userId, no_votes, createdOn)
    VALUES($1, $2, $3, $4, $5)
    returning *`;
    const votes =`UPDATE votes
    SET no_votes = total + 1
      returning *`;
    const values = [
        uuidv4(),
        req.params.questionId,
        req.params.userId,
        0,
        moment(new Date())
    ];
    try {
        const { rows } = await db.query(text, values);
        return res.status(201).json({
            message: 'vote successful',
            votes: rows[0],
            request: {
                type: 'GET',
                url: 'http://localhost:3000/api/v1/upvote/' + rows[0].id
            }
        });
    } catch (err) {
        return res.status(400).json({
            error: console.error(err)});
    }
};