问:
How can I map postgresql json data type using Hibernate?
I am following the example mentioned in the below URL ?
Mapping PostgreSQL JSON column to a Hibernate entity property

But always get the following exception:

```<code>Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2000
    at org.hibernate.dialect.TypeNames.get(TypeNames.java:76)
    at org.hibernate.dialect.TypeNames.get(TypeNames.java:99)
    at org.hibernate.dialect.Dialect.getTypeName(Dialect.java:310)
    at org.hibernate.mapping.Column.getSqlType(Column.java:226)
    at org.hibernate.mapping.Table.validateColumns(Table.java:369)
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1305)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:512)
</code>```

I am using TomEE as the Server. and trying to store Json body to a postgresql column. I am trying to map the entity pojos to the postgres datatype structure.

Any idea what could be the issue ? or does any has a better technique to handle such as scenario ? Please point me to that source.

The script used to create the entity table is:

    CREATE TABLE historyentity
    (
      id character varying(255) NOT NULL,
      userid character varying(255),
      lastchanged timestamp without time zone,
      type character varying(255),
      history json [],
      CONSTRAINT historyentity_pkey PRIMARY KEY (id),
      CONSTRAINT historyentity_userid_fkey FOREIGN KEY (userid)
          REFERENCES userentity (id) MATCH SIMPLE
          ON UPDATE NO ACTION ON DELETE NO ACTION
    )
    WITH (
      OIDS=FALSE
    );
    ALTER TABLE historyentity
      OWNER TO postgres;
    GRANT ALL ON TABLE historyentity TO postgres;
```
<p>Entity Pojos look like as follows:</p>
<pre class="lang-java prettyprint-override"><code>    @Entity
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @TypeDefs({ @TypeDef(name = "StringJsonObject", typeClass = StringJsonUserType.class) })
    public class HistoryEntity {

        @Id
        private String id;
        private String userid;
        private String type;
        @Type(type = "StringJsonObject")
        private String history;
        private Date lastchanged;

    }
</code>```

I am using lombok to define the entity pojos.

Following is the Dialect extended class:
I have tried with both the registered types, Column and Hibenate. But both are not working out.

    import org.hibernate.dialect.PostgreSQL82Dialect;

    public class JsonPostgreSQLDialect extends PostgreSQL82Dialect

        {
            @Inject
            public JsonPostgreSQLDialect()
            {
                super();
                   this.registerColumnType(Types.JAVA_OBJECT, "json");
                // this.registerHibernateType(Types.JAVA_OBJECT, "json");
            }
        }
```
<p>The following class is being used to define the User Type:</p>
<pre class="lang-java prettyprint-override"><code>    import java.io.Serializable;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Types;

    import org.hibernate.HibernateException;
    import org.hibernate.engine.spi.SessionImplementor;
    import org.hibernate.usertype.UserType;

    public class StringJsonUserType implements UserType
    {
        private final int[] sqlTypesSupported = new int[]{ Types.JAVA_OBJECT };

        /**
         * Return the SQL type codes for the columns mapped by this type. The codes are defined on <tt>java.sql.Types</tt>.
         *
         * @return int[] the typecodes
         * @see java.sql.Types
         */
        @Override
        public int[] sqlTypes()
        {
            return sqlTypesSupported;
        }

        /**
         * The class returned by <tt>nullSafeGet()</tt>.
         *
         * @return Class
         */
        @Override
        public Class returnedClass()
        {
            return String.class;
        }

        /**
         * Compare two instances of the class mapped by this type for persistence "equality". Equality of the persistent
         * state.
         *
         * @return boolean
         */
        @Override
        public boolean equals(Object x, Object y) throws HibernateException
        {

            if (x == null)
            {

                return y == null;
            }

            return x.equals(y);
        }

        /**
         * Get a hashcode for the instance, consistent with persistence "equality"
         */
        @Override
        public int hashCode(Object x) throws HibernateException
        {

            return x.hashCode();
        }

        /**
         * Retrieve an instance of the mapped class from a JDBC resultset. Implementors should handle possibility of null
         * values.
         *
         * @param rs a JDBC result set
         * @param names the column names
         * @param owner the containing entity  @return Object
         */
        @Override
        public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
            throws HibernateException, SQLException
        {
            if (rs.getString(names[0]) == null)
            {
                return null;
            }
            return rs.getString(names[0]);
        }

        /**
         * Write an instance of the mapped class to a prepared statement. Implementors should handle possibility of null
         * values. A multi-column type should be written to parameters starting from <tt>index</tt>.
         *
         * @param st a JDBC prepared statement
         * @param value the object to write
         * @param index statement parameter index
         */
        @Override
        public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
            throws HibernateException, SQLException
        {
            if (value == null)
            {
                st.setNull(index, Types.OTHER);
                return;
            }

            st.setObject(index, value, Types.OTHER);
        }

        /**
         * Return a deep copy of the persistent state, stopping at entities and at collections. It is not necessary to copy
         * immutable objects, or null values, in which case it is safe to simply return the argument.
         *
         * @param value the object to be cloned, which may be null
         * @return Object a copy
         */
        @Override
        public Object deepCopy(Object value) throws HibernateException
        {

            return value;
        }

        /**
         * Are objects of this type mutable?
         *
         * @return boolean
         */
        @Override
        public boolean isMutable()
        {
            return true;
        }

        /**
         * Transform the object into its cacheable representation. At the very least this method should perform a deep copy
         * if the type is mutable. That may not be enough for some implementations, however; for example, associations must
         * be cached as identifier values. (optional operation)
         *
         * @param value the object to be cached
         * @return a cachable representation of the object
         */
        @Override
        public Serializable disassemble(Object value) throws HibernateException
        {
            return (String) this.deepCopy(value);
        }

        /**
         * Reconstruct an object from the cacheable representation. At the very least this method should perform a deep copy
         * if the type is mutable. (optional operation)
         *
         * @param cached the object to be cached
         * @param owner the owner of the cached object
         * @return a reconstructed object from the cachable representation
         */
        @Override
        public Object assemble(Serializable cached, Object owner) throws HibernateException
        {
            return this.deepCopy(cached);
        }

        /**
         * During merge, replace the existing (target) value in the entity we are merging to with a new (original) value
         * from the detached entity we are merging. For immutable objects, or null values, it is safe to simply return the
         * first parameter. For mutable objects, it is safe to return a copy of the first parameter. For objects with
         * component values, it might make sense to recursively replace component values.
         *
         * @param original the value from the detached entity being merged
         * @param target the value in the managed entity
         * @return the value to be merged
         */
        @Override
        public Object replace(Object original, Object target, Object owner) throws HibernateException
        {
            return original;
        }
    }
</code>```

答:
This work for me :

Your Entity :

```<code>@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@TypeDef(name = "json", typeClass = JSONUserType.class, parameters = {
        @Parameter(name = JSONUserType.CLASS, value = "java.lang.String")})
    public class HistoryEntity {

        @Id
        private String id;
        private String userid;
        private String type;
        @Type(type = "json")
        private String history;
        private Date lastchanged;

    }
</code>```

Implement Hibernate ParameterizedType and UserType to ensure the conversion between the 2 types (json <->string)

```<code>public class JSONUserType implements ParameterizedType, UserType {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final ClassLoaderService classLoaderService = new ClassLoaderServiceImpl();

    public static final String JSON_TYPE = "json";
    public static final String CLASS = "CLASS";

    private Class jsonClassType;

    @Override
    public Class<Object> returnedClass() {
        return Object.class;
    }

    @Override
    public int[] sqlTypes() {
        return new int[]{Types.JAVA_OBJECT};
    }

    @Override
    public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
        try {
            final String json = resultSet.getString(names[0]);
            return json == null ? null : objectMapper.readValue(json, jsonClassType);
        } catch (IOException e) {
            throw new HibernateException(e);
        }
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
        try {
            final String json = value == null ? null : objectMapper.writeValueAsString(value);
            PGobject pgo = new PGobject();
            pgo.setType(JSON_TYPE);
            pgo.setValue(json);
            st.setObject(index, pgo);
        } catch (JsonProcessingException e) {
            throw new HibernateException(e);
        }
    }

    @Override
    public void setParameterValues(Properties parameters) {
        final String clazz = (String) parameters.get(CLASS);
        jsonClassType = classLoaderService.classForName(clazz);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object deepCopy(Object value) throws HibernateException {

        if (!(value instanceof Collection)) {
            return value;
        }

        Collection<?> collection = (Collection) value;
        Collection collectionClone = CollectionFactory.newInstance(collection.getClass());

        collectionClone.addAll(collection.stream().map(this::deepCopy).collect(Collectors.toList()));

        return collectionClone;
    }

    static final class CollectionFactory {
        @SuppressWarnings("unchecked")
        static <E, T extends Collection<E>> T newInstance(Class<T> collectionClass) {
            if (List.class.isAssignableFrom(collectionClass)) {
                return (T) new ArrayList<E>();
            } else if (Set.class.isAssignableFrom(collectionClass)) {
                return (T) new HashSet<E>();
            } else {
                throw new IllegalArgumentException("Unsupported collection type : " + collectionClass);
            }
        }
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y) {
            return true;
        }

        if ((x == null) || (y == null)) {
            return false;
        }

        return x.equals(y);
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        assert (x != null);
        return x.hashCode();
    }

    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return deepCopy(cached);
    }

    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        Object deepCopy = deepCopy(value);

        if (!(deepCopy instanceof Serializable)) {
            throw new SerializationException(String.format("%s is not serializable class", value), null);
        }

        return (Serializable) deepCopy;
    }

    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return deepCopy(original);
    }
}
</code>```

And extends PostgreSQL94Dialect class to tell the serializer the matching type:

```<code>public class JSONPostgreSQLDialect extends PostgreSQL94Dialect {

    public JSONPostgreSQLDialect() {
        super();
        registerColumnType(Types.JAVA_OBJECT, JSONUserType.JSON_TYPE);
    }
}
</code>```

If you use Spring you must declare this last class in application.properties like this :
spring.jpa.database-platform=com.yourpackage.JSONPostgreSQLDialect

Body:
I am following the example mentioned in the below URL ?
Mapping PostgreSQL JSON column to a Hibernate entity property

But always get the following exception:

Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2000
    at org.hibernate.dialect.TypeNames.get(TypeNames.java:76)
    at org.hibernate.dialect.TypeNames.get(TypeNames.java:99)
    at org.hibernate.dialect.Dialect.getTypeName(Dialect.java:310)
    at org.hibernate.mapping.Column.getSqlType(Column.java:226)
    at org.hibernate.mapping.Table.validateColumns(Table.java:369)
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1305)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:512)

I am using TomEE as the Server. and trying to store Json body to a postgresql column. I am trying to map the entity pojos to the postgres datatype structure.

Any idea what could be the issue ? or does any has a better technique to handle such as scenario ? Please point me to that source.

The script used to create the entity table is:

    CREATE TABLE historyentity
    (
      id character varying(255) NOT NULL,
      userid character varying(255),
      lastchanged timestamp without time zone,
      type character varying(255),
      history json [],
      CONSTRAINT historyentity_pkey PRIMARY KEY (id),
      CONSTRAINT historyentity_userid_fkey FOREIGN KEY (userid)
          REFERENCES userentity (id) MATCH SIMPLE
          ON UPDATE NO ACTION ON DELETE NO ACTION
    )
    WITH (
      OIDS=FALSE
    );
    ALTER TABLE historyentity
      OWNER TO postgres;
    GRANT ALL ON TABLE historyentity TO postgres;

Entity Pojos look like as follows:

    @Entity
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @TypeDefs({ @TypeDef(name = "StringJsonObject", typeClass = StringJsonUserType.class) })
    public class HistoryEntity {

        @Id
        private String id;
        private String userid;
        private String type;
        @Type(type = "StringJsonObject")
        private String history;
        private Date lastchanged;

    }

I am using lombok to define the entity pojos.

Following is the Dialect extended class:
I have tried with both the registered types, Column and Hibenate. But both are not working out.

    import org.hibernate.dialect.PostgreSQL82Dialect;

    public class JsonPostgreSQLDialect extends PostgreSQL82Dialect

        {
            @Inject
            public JsonPostgreSQLDialect()
            {
                super();
                   this.registerColumnType(Types.JAVA_OBJECT, "json");
                // this.registerHibernateType(Types.JAVA_OBJECT, "json");
            }
        }

The following class is being used to define the User Type:

    import java.io.Serializable;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Types;

    import org.hibernate.HibernateException;
    import org.hibernate.engine.spi.SessionImplementor;
    import org.hibernate.usertype.UserType;

    public class StringJsonUserType implements UserType
    {
        private final int[] sqlTypesSupported = new int[]{ Types.JAVA_OBJECT };

        /**
         * Return the SQL type codes for the columns mapped by this type. The codes are defined on <tt>java.sql.Types</tt>.
         *
         * @return int[] the typecodes
         * @see java.sql.Types
         */
        @Override
        public int[] sqlTypes()
        {
            return sqlTypesSupported;
        }

        /**
         * The class returned by <tt>nullSafeGet()</tt>.
         *
         * @return Class
         */
        @Override
        public Class returnedClass()
        {
            return String.class;
        }

        /**
         * Compare two instances of the class mapped by this type for persistence "equality". Equality of the persistent
         * state.
         *
         * @return boolean
         */
        @Override
        public boolean equals(Object x, Object y) throws HibernateException
        {

            if (x == null)
            {

                return y == null;
            }

            return x.equals(y);
        }

        /**
         * Get a hashcode for the instance, consistent with persistence "equality"
         */
        @Override
        public int hashCode(Object x) throws HibernateException
        {

            return x.hashCode();
        }

        /**
         * Retrieve an instance of the mapped class from a JDBC resultset. Implementors should handle possibility of null
         * values.
         *
         * @param rs a JDBC result set
         * @param names the column names
         * @param owner the containing entity  @return Object
         */
        @Override
        public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
            throws HibernateException, SQLException
        {
            if (rs.getString(names[0]) == null)
            {
                return null;
            }
            return rs.getString(names[0]);
        }

        /**
         * Write an instance of the mapped class to a prepared statement. Implementors should handle possibility of null
         * values. A multi-column type should be written to parameters starting from <tt>index</tt>.
         *
         * @param st a JDBC prepared statement
         * @param value the object to write
         * @param index statement parameter index
         */
        @Override
        public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
            throws HibernateException, SQLException
        {
            if (value == null)
            {
                st.setNull(index, Types.OTHER);
                return;
            }

            st.setObject(index, value, Types.OTHER);
        }

        /**
         * Return a deep copy of the persistent state, stopping at entities and at collections. It is not necessary to copy
         * immutable objects, or null values, in which case it is safe to simply return the argument.
         *
         * @param value the object to be cloned, which may be null
         * @return Object a copy
         */
        @Override
        public Object deepCopy(Object value) throws HibernateException
        {

            return value;
        }

        /**
         * Are objects of this type mutable?
         *
         * @return boolean
         */
        @Override
        public boolean isMutable()
        {
            return true;
        }

        /**
         * Transform the object into its cacheable representation. At the very least this method should perform a deep copy
         * if the type is mutable. That may not be enough for some implementations, however; for example, associations must
         * be cached as identifier values. (optional operation)
         *
         * @param value the object to be cached
         * @return a cachable representation of the object
         */
        @Override
        public Serializable disassemble(Object value) throws HibernateException
        {
            return (String) this.deepCopy(value);
        }

        /**
         * Reconstruct an object from the cacheable representation. At the very least this method should perform a deep copy
         * if the type is mutable. (optional operation)
         *
         * @param cached the object to be cached
         * @param owner the owner of the cached object
         * @return a reconstructed object from the cachable representation
         */
        @Override
        public Object assemble(Serializable cached, Object owner) throws HibernateException
        {
            return this.deepCopy(cached);
        }

        /**
         * During merge, replace the existing (target) value in the entity we are merging to with a new (original) value
         * from the detached entity we are merging. For immutable objects, or null values, it is safe to simply return the
         * first parameter. For mutable objects, it is safe to return a copy of the first parameter. For objects with
         * component values, it might make sense to recursively replace component values.
         *
         * @param original the value from the detached entity being merged
         * @param target the value in the managed entity
         * @return the value to be merged
         */
        @Override
        public Object replace(Object original, Object target, Object owner) throws HibernateException
        {
            return original;
        }
    }

Body:
This work for me :

Your Entity :

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@TypeDef(name = "json", typeClass = JSONUserType.class, parameters = {
        @Parameter(name = JSONUserType.CLASS, value = "java.lang.String")})
    public class HistoryEntity {

        @Id
        private String id;
        private String userid;
        private String type;
        @Type(type = "json")
        private String history;
        private Date lastchanged;

    }

Implement Hibernate ParameterizedType and UserType to ensure the conversion between the 2 types (json <->string)

public class JSONUserType implements ParameterizedType, UserType {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final ClassLoaderService classLoaderService = new ClassLoaderServiceImpl();

    public static final String JSON_TYPE = "json";
    public static final String CLASS = "CLASS";

    private Class jsonClassType;

    @Override
    public Class<Object> returnedClass() {
        return Object.class;
    }

    @Override
    public int[] sqlTypes() {
        return new int[]{Types.JAVA_OBJECT};
    }

    @Override
    public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
        try {
            final String json = resultSet.getString(names[0]);
            return json == null ? null : objectMapper.readValue(json, jsonClassType);
        } catch (IOException e) {
            throw new HibernateException(e);
        }
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
        try {
            final String json = value == null ? null : objectMapper.writeValueAsString(value);
            PGobject pgo = new PGobject();
            pgo.setType(JSON_TYPE);
            pgo.setValue(json);
            st.setObject(index, pgo);
        } catch (JsonProcessingException e) {
            throw new HibernateException(e);
        }
    }

    @Override
    public void setParameterValues(Properties parameters) {
        final String clazz = (String) parameters.get(CLASS);
        jsonClassType = classLoaderService.classForName(clazz);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object deepCopy(Object value) throws HibernateException {

        if (!(value instanceof Collection)) {
            return value;
        }

        Collection<?> collection = (Collection) value;
        Collection collectionClone = CollectionFactory.newInstance(collection.getClass());

        collectionClone.addAll(collection.stream().map(this::deepCopy).collect(Collectors.toList()));

        return collectionClone;
    }

    static final class CollectionFactory {
        @SuppressWarnings("unchecked")
        static <E, T extends Collection<E>> T newInstance(Class<T> collectionClass) {
            if (List.class.isAssignableFrom(collectionClass)) {
                return (T) new ArrayList<E>();
            } else if (Set.class.isAssignableFrom(collectionClass)) {
                return (T) new HashSet<E>();
            } else {
                throw new IllegalArgumentException("Unsupported collection type : " + collectionClass);
            }
        }
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y) {
            return true;
        }

        if ((x == null) || (y == null)) {
            return false;
        }

        return x.equals(y);
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        assert (x != null);
        return x.hashCode();
    }

    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return deepCopy(cached);
    }

    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        Object deepCopy = deepCopy(value);

        if (!(deepCopy instanceof Serializable)) {
            throw new SerializationException(String.format("%s is not serializable class", value), null);
        }

        return (Serializable) deepCopy;
    }

    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return deepCopy(original);
    }
}

And extends PostgreSQL94Dialect class to tell the serializer the matching type:

public class JSONPostgreSQLDialect extends PostgreSQL94Dialect {

    public JSONPostgreSQLDialect() {
        super();
        registerColumnType(Types.JAVA_OBJECT, JSONUserType.JSON_TYPE);
    }
}

If you use Spring you must declare this last class in application.properties like this :
spring.jpa.database-platform=com.yourpackage.JSONPostgreSQLDialect


来源: stackexchange

问:
Incorrect lookat matrix
I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

It currently looks like this:
https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0),
Up vector = (0, 1, 0)

```<code>Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f);

        Vector3f z = position.substract(center).normalize();

        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}
</code>```

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

```<code>void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}
</code>```

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

```<code>gl_Position = projection * view * model * vec4(vertexPosition, 1.0);
</code>```

And this is how my matrix multiplication works:

```<code>Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}
</code>```

Edit: updated picture
Edit: Added a more detailed description

答:
After hours of trying to make the lookat matrix working I had given up on way of constructing the lookat matrix, instead I constructed a lookat matrix based on the position of the camera and position the camera should look at, using trigonometry functions I was able to create the result which I was seeking.

My current way of constructing a lookat matrix:

```<code>Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center) {
        Vector3f deltaVector = (position - center).normalize();

        fl32 yaw = (fl32)radToDeg(atan(deltaVector.x / deltaVector.z));
        fl32 pitch = (fl32)radToDeg(acos(Vector2f(deltaVector.x, deltaVector.z).magnitude()));

        if (deltaVector.z > 0)
            yaw = yaw - 180.0f;

        Matrix4f yRotation = Matrix4f::rotation(Vector3f(0.0f, 1.0f, 0.0f), -yaw);
        Matrix4f xRotation = Matrix4f::rotation(Vector3f(1.0f, 0.0f, 0.0f), pitch);

        Matrix4f translation = Matrix4f::translation(position);

        return (translation * (yRotation * xRotation));
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Incorrect lookat matrix

Body:
I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

It currently looks like this:
https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0),
Up vector = (0, 1, 0)

Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f);

        Vector3f z = position.substract(center).normalize();

        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

gl_Position = projection * view * model * vec4(vertexPosition, 1.0);

And this is how my matrix multiplication works:

Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}

Edit: updated picture
Edit: Added a more detailed description

Body:
After hours of trying to make the lookat matrix working I had given up on way of constructing the lookat matrix, instead I constructed a lookat matrix based on the position of the camera and position the camera should look at, using trigonometry functions I was able to create the result which I was seeking.

My current way of constructing a lookat matrix:

Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center) {
        Vector3f deltaVector = (position - center).normalize();

        fl32 yaw = (fl32)radToDeg(atan(deltaVector.x / deltaVector.z));
        fl32 pitch = (fl32)radToDeg(acos(Vector2f(deltaVector.x, deltaVector.z).magnitude()));

        if (deltaVector.z > 0)
            yaw = yaw - 180.0f;

        Matrix4f yRotation = Matrix4f::rotation(Vector3f(0.0f, 1.0f, 0.0f), -yaw);
        Matrix4f xRotation = Matrix4f::rotation(Vector3f(1.0f, 0.0f, 0.0f), pitch);

        Matrix4f translation = Matrix4f::translation(position);

        return (translation * (yRotation * xRotation));
    }


问:
C# foreach with string - ignore last character
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

```<code>    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}
</code>```

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

答:
It misses the last value because you only add numbers if you find a +. So for the last unparsedNumber you never enter the else if (c == '+') block.

Let me suggest an more compact solution:

```<code>public int addFromString(string str)
{
    string trimmed = str.Trim();
    if (str.StartsWith("+") || str.EndsWith("+")) return 0; // invalid -> return immediatly

    // split string at "+" and trim parts
    string[] numbers = str.Split('+').Select(s => s.Trim()).ToArray();
    int result = 0;
    foreach(string number in numbers)
    {
        int n;
        if (!int.TryParse(number, out n)) return 0; // invalid -> return
        result += n;
    }

    return result;
}
</code>```

Body:
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

Body:
It misses the last value because you only add numbers if you find a +. So for the last unparsedNumber you never enter the else if (c == '+') block.

Let me suggest an more compact solution:

public int addFromString(string str)
{
    string trimmed = str.Trim();
    if (str.StartsWith("+") || str.EndsWith("+")) return 0; // invalid -> return immediatly

    // split string at "+" and trim parts
    string[] numbers = str.Split('+').Select(s => s.Trim()).ToArray();
    int result = 0;
    foreach(string number in numbers)
    {
        int n;
        if (!int.TryParse(number, out n)) return 0; // invalid -> return
        result += n;
    }

    return result;
}


问:
JavaScript - Get only negative numbers form array
I have task: Write the function getNegativeNumbers (array) which as an argument take array. The function has to return a new array filled only negative numbers.

I have done this solution, but I ask about different methods.

```<code>var myArray = [4, -5, 0, 2, -67, 8, 10, -34 ];

function getNegativeNumbers(array) {

    var negatives = [];

    for (var i = 0; i < array.length; i++) {
        if (array[i] < 0) {
            negatives.push(array[i]);
        }
    }
    return negatives;

}
console.log(getNegativeNumbers(myArray));
</code>```

答:
Use Array.filter

var myArray = [4, -5, 0, 2, -67, 8, 10, -34 ];

var negatives = myArray.filter(e => e < 0);

console.log(negatives);```

Body:
I have task: Write the function getNegativeNumbers (array) which as an argument take array. The function has to return a new array filled only negative numbers.

I have done this solution, but I ask about different methods.

var myArray = [4, -5, 0, 2, -67, 8, 10, -34 ];

function getNegativeNumbers(array) {

    var negatives = [];

    for (var i = 0; i < array.length; i++) {
        if (array[i] < 0) {
            negatives.push(array[i]);
        }
    }
    return negatives;

}
console.log(getNegativeNumbers(myArray));


问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答:
My only thought is that if this function is only called with C null-terminated strings, you might be requiring the extra construction of a std::string for parameter 's'.

Possibly the 'more' efficient method would be to allow either a std::string or const char *s passed in.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

ContentLicense: CC BY-SA 2.5

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}


问:
Covariance (OOP) in PHP - how does it work
```<code>class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(Param a) {
  }

}

class Sub extends Base {

 function mymethod(Subparam a) {
 }

}
</code>```

In PHP, this leads to a warning: Declaration should be compatible with Base->mymethod(a : \Param)

What can I do to prevent that, other than using annotations only?

答:
```<code>class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(a) {
    // Remove the parameter type from the method declaration.
    if (a !instanceof Param) {
      throw new \Exception('Paramater type should be of 'Param.');
    }

}

class Sub extends Base {

 function mymethod(a) {
 }

}
</code>```

This should get you close.

ContentLicense: CC BY-SA 4.0

Body:
class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(Param a) {
  }

}

class Sub extends Base {

 function mymethod(Subparam a) {
 }

}

In PHP, this leads to a warning: Declaration should be compatible with Base->mymethod(a : \Param)

What can I do to prevent that, other than using annotations only?

Body:
class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(a) {
    // Remove the parameter type from the method declaration.
    if (a !instanceof Param) {
      throw new \Exception('Paramater type should be of 'Param.');
    }

}

class Sub extends Base {

 function mymethod(a) {
 }

}

This should get you close.


问:
Php send 0 bytes excel file through echo
I am creating a very large table in a single string $output with the data from a MySQL database. In end of the php script, I send two headers:

```<code>header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");
</code>```

The problem is when the large table has about more than 55000 rows. When this happens, the file sent is 0 bytes and the user opens a empty file. I am sending the file through this after the headers:

```<code>echo $output;
</code>```

When the table has not too many rows, the file sent work. How to send a file in this way that the size of the string $output don't matter?

答:
The solution found in another question worked for this. The file is too large to send, so the solution is send part by part to the user. Instead of use readfile() function, use the readfile_chuncked() customized function:</p>

```<code>define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}
</code>```

Body:
I am creating a very large table in a single string $output with the data from a MySQL database. In end of the php script, I send two headers:

header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");

The problem is when the large table has about more than 55000 rows. When this happens, the file sent is 0 bytes and the user opens a empty file. I am sending the file through this after the headers:

echo $output;

When the table has not too many rows, the file sent work. How to send a file in this way that the size of the string $output don't matter?

Body:
The solution found in another question worked for this. The file is too large to send, so the solution is send part by part to the user. Instead of use readfile() function, use the readfile_chuncked() customized function:

define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}


问:
symfony 2.8 FOSUserBundle legacyFormHelper: get input field of form in twig template
I am trying to restyle the register form of the FOSUserBundle,
i try to putt the input in my template line by line like this.

```<code>{{ form_widget(form.username) }}
{{ form_widget(form.first_name) }}
</code>```

This works, but when i try to do this with the password en confirmation password it doesn't work.

Here is the line of the form builder:

```<code>->add('plainPassword', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\RepeatedType'), array(
        'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\PasswordType'),
        'options' => array('translation_domain' => 'FOSUserBundle'),
        'first_options' => array('label' => 'form.password'),
        'second_options' => array('label' => 'form.password_confirmation'),
        'invalid_message' => 'fos_user.password.mismatch',
</code>```

I try to put it in the temlate like this:

```<code>{{ form_widget(form.plainPassword) }}
{{ form_widget(form.password_confirmation) }}
</code>```

but it is not working, i tried some other things also but i cant figure it out.

Thanks in advance.

答:
I found the answer to my question:

```<code>{{ form_widget(form.plainPassword.first) }}
{{ form_widget(form.plainPassword.second) }}
</code>```

Full information about the register template customization can be found here:

https://www.amalhichri.net/user-management-with-fosuserbundle/

Body:
I am trying to restyle the register form of the FOSUserBundle,
i try to putt the input in my template line by line like this.

{{ form_widget(form.username) }}
{{ form_widget(form.first_name) }}

This works, but when i try to do this with the password en confirmation password it doesn't work.

Here is the line of the form builder:

->add('plainPassword', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\RepeatedType'), array(
        'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\PasswordType'),
        'options' => array('translation_domain' => 'FOSUserBundle'),
        'first_options' => array('label' => 'form.password'),
        'second_options' => array('label' => 'form.password_confirmation'),
        'invalid_message' => 'fos_user.password.mismatch',

I try to put it in the temlate like this:

{{ form_widget(form.plainPassword) }}
{{ form_widget(form.password_confirmation) }}

but it is not working, i tried some other things also but i cant figure it out.

Thanks in advance.

Body:
I found the answer to my question:

{{ form_widget(form.plainPassword.first) }}
{{ form_widget(form.plainPassword.second) }}

Full information about the register template customization can be found here:

https://www.amalhichri.net/user-management-with-fosuserbundle/


问:
Ruby on Rails Microsoft Graph Client Specifying Parameters for Calendars
I'm using rails to build an app that uses the Microsoft Graph client to get events in a users calendar. I've read lots of tutorials and documentation on the graph api, and the problem i'm having is finding resources for the actual client itself. All the documentation shows examples for using an http request, such as:

```<code>GET https://outlook.office.com/api/v2.0/me/calendarview?startDateTime={start_datetime}&endDateTime={end_datetime}
</code>```

But I can't find any resources on how to add parameters like startDateTime and endDateTime to the graph client itself. For example, this is a sample function from the MS tutorial using the graph client to get events:

```<code>def index
    token = get_access_token
    email = session[:user_email]
    if token
      # If a token is present in the session, get events from the calendar
      callback = Proc.new do |r|
        r.headers['Authorization'] = "Bearer #{token}"
        r.headers['X-AnchorMailbox'] = email
      end

      graph = MicrosoftGraph.new(base_url: 'https://graph.microsoft.com/v1.0',
                                cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, 'metadata_v1.0.xml'),
                                &callback)

      @events = graph.me.events.order_by('start/dateTime asc')
    else
      # If no token, redirect to the root url so user
      # can sign in.
      redirect_to root_url
    end
  end
</code>```

They get the events from @events = graph.me.events.order_by('start/dateTime asc')
Which is almost what I need, but I need the events between a specific date range.

I believe what I actually want is the calendar view (https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_list_calendarview), and to specify a date range, but I can't find any resources that explain how to specify that date range using the client.

I've tried just getting the calendar view from graph.me.calendar_view which works fine but returns a huge amount of data, and I want to specify the date ranges to return the events between.

Can anyone tell me how to specify the date range for the client?

Thanks!

答:
No much documentation on that matter indeed, but this should help:</p>

```<code>@events = graph.me.events.filter("start/dateTime ge '#{start}' and end/dateTime le '#{end}'")
</code>```

Body:
I'm using rails to build an app that uses the Microsoft Graph client to get events in a users calendar. I've read lots of tutorials and documentation on the graph api, and the problem i'm having is finding resources for the actual client itself. All the documentation shows examples for using an http request, such as:

GET https://outlook.office.com/api/v2.0/me/calendarview?startDateTime={start_datetime}&endDateTime={end_datetime}

But I can't find any resources on how to add parameters like startDateTime and endDateTime to the graph client itself. For example, this is a sample function from the MS tutorial using the graph client to get events:

def index
    token = get_access_token
    email = session[:user_email]
    if token
      # If a token is present in the session, get events from the calendar
      callback = Proc.new do |r|
        r.headers['Authorization'] = "Bearer #{token}"
        r.headers['X-AnchorMailbox'] = email
      end

      graph = MicrosoftGraph.new(base_url: 'https://graph.microsoft.com/v1.0',
                                cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, 'metadata_v1.0.xml'),
                                &callback)

      @events = graph.me.events.order_by('start/dateTime asc')
    else
      # If no token, redirect to the root url so user
      # can sign in.
      redirect_to root_url
    end
  end

They get the events from @events = graph.me.events.order_by('start/dateTime asc')
Which is almost what I need, but I need the events between a specific date range.

I believe what I actually want is the calendar view (https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_list_calendarview), and to specify a date range, but I can't find any resources that explain how to specify that date range using the client.

I've tried just getting the calendar view from graph.me.calendar_view which works fine but returns a huge amount of data, and I want to specify the date ranges to return the events between.

Can anyone tell me how to specify the date range for the client?

Thanks!

Body:
No much documentation on that matter indeed, but this should help:

@events = graph.me.events.filter("start/dateTime ge '#{start}' and end/dateTime le '#{end}'")


问:
How To Reverse A Nested Python List
Given the following nested list,

myList=([1,[2,3],[[4,5,[6],7],8,9]])

I want to reverse it to be converted into:

myList= [[[4, 5, [6], 7], 8, 9], [2, 3], 1]

How do I do that?
Thanks.

答:
This can be done easily with list slicing

```<code>In [60]: myList
Out[60]: [1, [2, 3], [[4, 5, [6], 7], 8, 9]]

In [61]: myList[::-1]
Out[61]: [[[4, 5, [6], 7], 8, 9], [2, 3], 1]
</code>```

For more info, go to
    https://docs.python.org/2.3/whatsnew/section-slices.html

Title: How To Reverse A Nested Python List

Body:
This can be done easily with list slicing

In [60]: myList
Out[60]: [1, [2, 3], [[4, 5, [6], 7], 8, 9]]

In [61]: myList[::-1]
Out[61]: [[[4, 5, [6], 7], 8, 9], [2, 3], 1]

For more info, go to
    https://docs.python.org/2.3/whatsnew/section-slices.html


问:
Flash IDE Project ActionScript 3 To Flex: How to convert?
Hi I have a project which is build with Flash CS3 IDE and ActionScript 3. Now I need to integrate some feature with file refrence class. that is avail only in flex. So I want to migrate to flex(MXML)..

how is it possible?

I did some code, but doesn't work properly

```<code>ProjectFile.mxml
</code>```

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "initApp()" >
    <mx:Script>

    <![CDATA[

        import mx.core.UIComponent;

        public function initApp():void {

            var app:Applications =  new Applications(this);
            addChild(app);

        }
    ]]>
    </mx:Script>

</mx:Application>
</code>```

Applications.as
The Applications class is called from the FLA earlier, now i need to add my base class to mxml.

```<code>package {

    import com.AnotherClass;

    import flash.display.*;
    import flash.events.*;

    public class Main extends Sprite {

        public var _mystage:Stage;
        public function Main() {
            var app:AnotherClass=  new AnotherClass(this);
            addChild(app);
        }

    }
}
</code>```

But Iam unable to load the Applicatios  class object on the MXML.

答:
Of course you can use FileReference.save without deploying AIR content and/or porting to Flex.  The only problem is: FileReference.save is available in Flash Player 10 or greater, but CS3 will deploy only up to Flash Player 9.

It turns out you can still do it, but it's a bit messy, and you have to use a little hack:

Get the FlashPlayer 10 AS3
libraries.  They are a part of Flex SDK, which you can download from Adobe for free.

Create a Flash 9 AS3 document.

Add the libraries to your classpath, instead of the default ones.

Use FileReference.save in your
program.

Deploy to FP 9. Ignore compiler warnings, if any.

Open the SWF in a hex editor.

Change the 4th byte from 09 to 0A (his indicates the version number).

Save the SWF.

Open your SWF in Flash Player 10 -
everything should work.

(Most of these hints are from ZEROSEVEN's german page).

Body:
Hi I have a project which is build with Flash CS3 IDE and ActionScript 3. Now I need to integrate some feature with file refrence class. that is avail only in flex. So I want to migrate to flex(MXML)..

how is it possible?

I did some code, but doesn't work properly

ProjectFile.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "initApp()" >
    <mx:Script>

    <![CDATA[

        import mx.core.UIComponent;

        public function initApp():void {

            var app:Applications =  new Applications(this);
            addChild(app);

        }
    ]]>
    </mx:Script>

</mx:Application>

Applications.as
The Applications class is called from the FLA earlier, now i need to add my base class to mxml.

package {

    import com.AnotherClass;

    import flash.display.*;
    import flash.events.*;

    public class Main extends Sprite {

        public var _mystage:Stage;
        public function Main() {
            var app:AnotherClass=  new AnotherClass(this);
            addChild(app);
        }

    }
}

But Iam unable to load the Applicatios  class object on the MXML.


问:
wordpress footer.php will not appear in single.php
My footer.php file will pull into every page except the single.php, I have no idea why this is occurring! Any ideas?

Below is the Single.php code

```<code><?php get_header(); ?>

    <div class="page-content">
        <div class="small-banner">
            <h1><?php the_title(); ?></h1>
            <img src="http://www.quorngrangehotel.local/wp-content/uploads/2017/04/new-events-banner.jpg">
        </div>

<main role="main" class="mainContent">

        <div id="inner-content" class="row">

            <main id="main" class="large-8 medium-8 columns" role="main">

                <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

                    <?php get_template_part( 'parts/loop', 'single' ); ?>

                <?php endwhile; else : ?>

                    <?php get_template_part( 'parts/content', 'missing' ); ?>

                <?php endif; ?>

            </main> <!-- end #main -->

        </div> <!-- end #inner-content -->

</main><!-- end #content -->

<?php get_footer(); ?>
</code>```

答: I found out the issue it was something to do with the comments section being pulled in via the single template part! </p>

Body:
My footer.php file will pull into every page except the single.php, I have no idea why this is occurring! Any ideas?

Below is the Single.php code

<?php get_header(); ?>

<?php the_title(); ?>

                <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

                    <?php get_template_part( 'parts/loop', 'single' ); ?>

                <?php endwhile; else : ?>

                    <?php get_template_part( 'parts/content', 'missing' ); ?>

                <?php endif; ?>

<?php get_footer(); ?>


问:
Docker run error: "Thin Pool has free data blocks which is less than minimum required"
We are trying to run a docker in a way that used to work, but now we get a "Thin Pool lack of space" error:

```<code>docker run --privileged -d --net=host --name=fat-redis -v /fat/deploy:/fat/deploy -v /fat/fat-redis/var/log:/var/log -v /home:/home fat-local.indy.xiolab.myserv.com/fat-redis:latest /fat/deploy/docker/fat-redis/fat_start_docker_inner.sh
docker: Error response from daemon: devmapper: Thin Pool has 486 free data blocks which is less than minimum required 163840 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior.
See 'docker run --help'.
</code>```

What does this error mean?
We tried 'docker rmi' and the advise from here, but all in vain.

Any ideas?

Thank you

答:
My issue was unrelated to the loopback device problem, but was generating the same error condition. "docker images -a" showed a number of name=none tag=none images taking up space.  These images were not "dangling"; they were referenced by a current active image, and could not be deleted.

My solution was to run "docker save" and write the active image to a tar file, delete the active image (which deleted all the child images), then run "docker load -i" from the tar file and create a single new image. No more errors related to Thin Pool space.

Reinstalling docker would have corrected it, simply because reinstalling docker does clear out all images, but it would have begun building up again and then I would have re-encountered this issue in the future.

Body:
We are trying to run a docker in a way that used to work, but now we get a "Thin Pool lack of space" error:

docker run --privileged -d --net=host --name=fat-redis -v /fat/deploy:/fat/deploy -v /fat/fat-redis/var/log:/var/log -v /home:/home fat-local.indy.xiolab.myserv.com/fat-redis:latest /fat/deploy/docker/fat-redis/fat_start_docker_inner.sh
docker: Error response from daemon: devmapper: Thin Pool has 486 free data blocks which is less than minimum required 163840 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior.
See 'docker run --help'.

What does this error mean?
We tried 'docker rmi' and the advise from here, but all in vain.

Any ideas?

Thank you


问:
When implementing a JSONRPC 2.0 server, is it required to support both named, and positional arguments?
According the spec here: http://groups.google.com/group/json-rpc/web/json-rpc-2-0

more specifically, this section:

If present, parameters for the rpc
  call MUST be provided as a Structured
  value. Either by-position through an
  Array or by-name through an Object.

To me it seems obvious that both styles must be supported, however I've filed a bug report and another developer feels that it's up the developers to decide which method to support, and that the spec doesn't require both.

I can't find an official answer, other than what I quoted above, which the other developer doesn't interpret the same way I do.

So, what is the general consensus?

答: Joining your side, and I did not think this could be controversial.</p>


问:
Pre-commit hook for devtools::document
I want to set-up a pre-commit hook for devtools::document and want to fail the commit if devtools::document changes anything. I checked the devtools::document source and it returns invisible() so it's not possible to conditionally return an exit code.

Are there any clever ways to stop the commit from happening when devtools::document does work?

答:
Using the function capture.output we can catch the messages devtools::documents sends whenever it changes a file:

```<code>Writing getScore.Rd
</code>```

So when we run:

```<code>results <- capture.output(devtools::document())
</code>```

When a document is updated (for this example, I removed one of my .Rd files, results looks as follows:

```<code>> results
[1] "Writing getScore.Rd"
</code>```

If nothing is written, results is empty:

```<code>> results
character(0)
</code>```

It is easy to go on from here I think :)

The OP, @BobJansen created the following script that runs the above method and returns a status = 0 if no files were edited, and a status = 100 if any where:

```<code>#!/usr/bin/Rscript

source("packrat/init.R")

lines <- capture.output(devtools::document(), type = 'output')
if (length(lines) > 0) {
  print(lines)
  q(save = 'no', status = 100)
} else {
  q(save = 'no', status = 0)
}
</code>```

Title: Pre-commit hook for devtools::document

Body:
Using the function capture.output we can catch the messages devtools::documents sends whenever it changes a file:

Writing getScore.Rd

So when we run:

results <- capture.output(devtools::document())

When a document is updated (for this example, I removed one of my .Rd files, results looks as follows:

> results
[1] "Writing getScore.Rd"

If nothing is written, results is empty:

> results
character(0)

It is easy to go on from here I think :)

The OP, @BobJansen created the following script that runs the above method and returns a status = 0 if no files were edited, and a status = 100 if any where:

#!/usr/bin/Rscript

source("packrat/init.R")

lines <- capture.output(devtools::document(), type = 'output')
if (length(lines) > 0) {
  print(lines)
  q(save = 'no', status = 100)
} else {
  q(save = 'no', status = 0)
}


问:
Jenkins on Windows - Matlab Doesn't Exit
The following command on Jenkins freestyle doesn't exit(runs forever) in Windows environment. However when I run the same command in CMD it works as expected.

```<code>matlab -nodesktop -nosplash -minimize -c "path_to_license" -r "run('path_to_run_all_tests_script')" -wait -logfile unittestlog.txt set output=%errorlevel% MORE unittestlog.txt EXIT %output%
</code>```

What am I doing wrong?

EDIT:

This is the Matlab script that the command calls:

```<code>import matlab.unittest.TestSuite;

disp('Hello from TestSuite');
try
    suite = TestSuite.fromPackage('test','IncludingSubpackages',true);
    results = run(suite);
    display(results);
catch e
    disp(getReport(e,'extended'));
    exit(1);
end
exit(any([results.Failed])+1);
</code>```

答:
My guess would be that this is a licensing issue - you need Jenkins to be running as the same user that is named in the MATLAB license (assuming of course that your MATLAB license is a named-user license - if it's a concurrent or named-machine license, please ignore me).

If it's the wrong user, then MATLAB will start up, but show a dialog box telling you of the licensing issue. However, since you've called it with -nodesktop, this dialog will not be visible, and MATLAB will then just hang around for ever as a "zombie" process without sending a return value to Jenkins. If you go into Task Manager, you may find that you have one or more of them hanging around, and you can force-quit them there.

Note that you should be careful about the licensing requirements if you're running MATLAB for unit testing or automated builds via Jenkins. If you have a named-user license, only that named user is allowed to use it, and that includes via Jenkins. So long as you're the only person who can kick off a Jenkins/MATLAB job, that's fine - but if you're exposing Jenkins to several users, all of whom can kick off a MATLAB job, you're violating the license agreement. If you need to do that, you should really acquire a concurrent license for Jenkins to run under. But it's a bit of a grey area, you might want to speak to your account manager about it.

Hope that helps!

Edit: I think you might also want to take a look at the exit codes you're using in your test script. You want MATLAB to exit with a success code of zero when the tests pass, and a non-zero failure code when the tests fail, or when an error occurs during testing. So you probably want your last line to be exit(any([results.Failed]));, not exit(any([results.Failed])+1);.

Body:
The following command on Jenkins freestyle doesn't exit(runs forever) in Windows environment. However when I run the same command in CMD it works as expected.

matlab -nodesktop -nosplash -minimize -c "path_to_license" -r "run('path_to_run_all_tests_script')" -wait -logfile unittestlog.txt set output=%errorlevel% MORE unittestlog.txt EXIT %output%

What am I doing wrong?

EDIT:

This is the Matlab script that the command calls:

import matlab.unittest.TestSuite;

disp('Hello from TestSuite');
try
    suite = TestSuite.fromPackage('test','IncludingSubpackages',true);
    results = run(suite);
    display(results);
catch e
    disp(getReport(e,'extended'));
    exit(1);
end
exit(any([results.Failed])+1);


问:
How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

```<code>@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

Controller action:

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}
</code>```

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

答:
You need to write html like this

```<code>@Html.DropDownListFor(WHATEVER, new SelectList(ViewBag.languages, "Id", "Name"), new { @class = "form-control" })
</code>```

And in your controller

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeL;

   return View();
</code>```

}

Body:
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}

                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })

                    }

                }
            }
        }
    }
}

Controller action:

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

Body:
You need to write html like this

@Html.DropDownListFor(WHATEVER, new SelectList(ViewBag.languages, "Id", "Name"), new { @class = "form-control" })

And in your controller

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeL;

   return View();

}


问:
MySQL: What is the most performant way of storing a whole year (365 elements) in MySQL?
Within a project, I have to store the daily availability of different meeting rooms. So let's suppose around 1.000.000 meeting rooms, where each meeting room is in a city, and a city could have hundreds of meeting rooms.

I would also like to be able to make SELECT Queries entering the city and the availability that I need, so I would like to get a list of the available meeting rooms for a day, or set of continues days, in a concrete city.

I have one table called "MeetingRoom", when I store the city and the name of the meeting room, but my design question is how to design the availability part:

Is it better in terms of performance to have a binary array that stores the 365 days of the year with a '1' or '0' according to the availability of the meeting room?

Is it better in terms of performance to have another table called "Availability" that stores a DATE and a BIT with the availability, and then JOIN both tables for each meeting room that exists in a city?

Could it better another option I don't have in mind?

I wonder what querying time would be optimal having around 1.000.000 meeting rooms, and searching for the meeting rooms in a city and available for concrete days. Is it crazy about thinking in database responses below 100 ms?

Some colleagues told me that I should also consider to migrate to MongoDB or NoSQL approach. I don't know if a change of DB could fit better with my issues, or if it don't. Any comment about this?

Thank you very much for the help!!

答:
Please don't fill your database with lots of rows which are default values.

so you don't store availability of a meeting room, you store booking of a meeting room.

primary key of booking table is date and room id , other fields are who booked this room, when booking was asked, a booking id...

If it is possible to book meeting room for part of the day then primary key should be start_date and room id, end date is stored in another field of the table.


问:
Angular2 carrying data stored in a variable from app.component.ts(parent component) to other components
Question(1):-Want to carry "results" data from app.component.ts to abc.component.ts, bcd.component.ts, cde.component.ts and use in function like done below.
  How to do that?

Question(2):-Here, getting "results" data in console.log.

but Getting Error in  alert(this.loadedCharacter ) as undefined?

app.component.ts

```<code>    import { Component,OnInit, HostListener } from '@angular/core';
    import { Router } from "@angular/router";
    import { Http } from "@angular/http";
    import { SingletonService } from './commons/data-singleton.service';
    import { JsonDataService } from "app/services/json-data/json-data.service";
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/forkJoin';
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers:[]
    })
    export class AppComponent implements OnInit  {
      loadedCharacter: {};
loadedCharacter1: {};
      clientJson1: {
        "aoId": string;
        "viewBys": string[];
        "viewIds": string[];
        "globalViewbys": string[];
        "globalViewIds": string[];
        "dimensions": string[];
        "meassures": string[];
        "meassureIds": string[];
        "aggregation": string[];
        "globalInFilters": any;
        "globalNotInFilters": {
        };
        "localInFilters": {
        };
        "localNotInFilters": {
        };
        "drillDownFilters": {
        };
        "drillAcrossFilters": {
        };
      };
      clientJson: {
        "aoId": string;
        "viewBys": string[];
        "viewIds": string[];
        "globalViewbys": string[];
        "globalViewIds": string[];
        "dimensions": string[];
        "meassures": string[];
        "meassureIds": string[];
        "aggregation": string[];
        "globalInFilters": any;
        "globalNotInFilters": {
        };
        "localInFilters": {
        };
        "localNotInFilters": {
        };
        "drillDownFilters": {
        };
        "drillAcrossFilters": {
        };
      };
      data1: Observable<any>;
      data: Observable<any>;

      // SolrService
      public aoId: string[]
      public viewbys: string[] = ["brand"];  //Given by user  "Brand", "Category", "State" , "Region" , "city" , "Payment Method"
      public viewbysId: string[] = ["", "615128", "614847"];
      public dimensions: string[] = ["615228"];
      public measuresDefault: string[] = ["sales", "netsales"]; //Given by user
      public measures: string[] = ["sales", "netsales"]; //Given by user
      public measuresId: string[] = ["616275", "616283", "616279", "616648", "616295"];
      public aggregation = ["SUM", "SUM", "SUM", "SUM", "SUM", "SUM"];
      public globalInFilters: any = {};
      public globalNotInFilters = {};
      public localInFilters = {};
      public localNotInFilters = {};
      public drillDownFilters = {};
      public drillAcrossFilters = {};

      public elementIdsMap: any = { "615228": "Brand", "615128": "Category", "614847": "state" };

    private url ="http://183.82./Pvice/sovice"; //Global Server
      constructor(private router: Router, private http: Http, public jsonDataService: JsonDataService) {
      }

      ngOnInit() {
         this.clientJson = {
          "aoId": "M_AO_918",
          "viewBys": this.viewbys,
          "viewIds": this.viewbysId,
          "globalViewbys": ["brand", "uscity", "usstate"],
          "globalViewIds": ["615228", "615128", "614847"],
          "dimensions": this.dimensions,
          "meassures": this.measuresDefault,
          "meassureIds": this.measuresId,
          "aggregation": this.aggregation,
          "globalInFilters": this.globalInFilters,
          "globalNotInFilters": this.globalNotInFilters,
          "localInFilters": this.localInFilters,
          "localNotInFilters": this.localNotInFilters,
          "drillDownFilters": this.drillDownFilters,
          "drillAcrossFilters": this.drillAcrossFilters
        };

    this.clientJson1 ={
     "aoId": "M_AO_918",
          "viewBys": ["usstate"],
          "viewIds": this.viewbysId,
          "globalViewbys": ["brand", "uscity", "usstate"],
          "globalViewIds": ["615228", "615128", "614847"],
          "dimensions": this.dimensions,
          "meassures": this.measuresDefault,
          "meassureIds": this.measuresId,
          "aggregation": this.aggregation,
          "globalInFilters": this.globalInFilters,
          "globalNotInFilters": this.globalNotInFilters,
          "localInFilters": this.localInFilters,
          "localNotInFilters": this.localNotInFilters,
          "drillDownFilters": this.drillDownFilters,
          "drillAcrossFilters": this.drillAcrossFilters
    }

     this.data = this.http.post(this.url,this.clientJson).map(res => res.json());
        this.data1 = this.http.post(this.url,this.clientJson1).map(res => res.json());
           Observable.forkJoin([this.data , this.data1 ]).subscribe(results => {
          //results here
          this.loadedCharacter1  = results[1];
          this.loadedCharacter = results[0];
          console.log("results"+JSON.stringify(results[1]));
          console.log("results"+JSON.stringify(results[0]));
          // return results;
        });
         alert(this.loadedCharacter );
      }
    }
</code>```

 abc.component.ts

```<code> initData(){

//how to get loadedCharacter from `app.component.ts` here, and then pass it into buildabcchart() as below;

let jsonData = loadedCharacter;   // loadedCharacter: {}; from app.component.ts
buildabcchart(jsonData );
}

buildabcchart(jsonData ){
/*--------------*/
}
</code>```

答:
Question 1:

Here is a plunkr that demonstrates passing data from a parent component to child components https://plnkr.co/edit/dsnJShi87UUseFLVGscH?p=preview

So this uses the input binding to pass data from the parent to child.

```<code>// parent html
<child-component [someInput]="loadedCharacter"></child-component>

// child ts
export class ChildComponent{
    @Input() someInput; // someInput can be used throughout the child component
}
</code>```

Now when loadedCharacter is defined in your parent.ts it is passed to the child through the "someInput" input binding.

For the second part of your question, "using the passed in data in a function", you can use the ngOnChanges lifecycle hook. In your child component you can add something like

```<code>// child ts
export class ChildComponent implements OnChanges {
    @Input() someInput; // someInput can be used throughout the child component

    ngOnChanges(){
        // do something with someInput here. This lifecycle hook is fired every time 1 or multiple input bindings are changed
    }
}
</code>```

Resource on input binding: https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

Resource on ngOnChanges lifecycle hook: https://angular.io/api/core/OnChanges

Question 2

this.loadedCharacter is undefined because you are calling alert outside of the asynchronous task (forkJoin().subscribe). It is being called before the http requests finish. If you move it into the subscribe (and after you assign this.loadedCharacter) it should alert the data

Body:
Question(1):-Want to carry "results" data from app.component.ts to abc.component.ts, bcd.component.ts, cde.component.ts and use in function like done below.
  How to do that?

Question(2):-Here, getting "results" data in console.log.

but Getting Error in  alert(this.loadedCharacter ) as undefined?

app.component.ts

    import { Component,OnInit, HostListener } from '@angular/core';
    import { Router } from "@angular/router";
    import { Http } from "@angular/http";
    import { SingletonService } from './commons/data-singleton.service';
    import { JsonDataService } from "app/services/json-data/json-data.service";
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/forkJoin';
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers:[]
    })
    export class AppComponent implements OnInit  {
      loadedCharacter: {};
loadedCharacter1: {};
      clientJson1: {
        "aoId": string;
        "viewBys": string[];
        "viewIds": string[];
        "globalViewbys": string[];
        "globalViewIds": string[];
        "dimensions": string[];
        "meassures": string[];
        "meassureIds": string[];
        "aggregation": string[];
        "globalInFilters": any;
        "globalNotInFilters": {
        };
        "localInFilters": {
        };
        "localNotInFilters": {
        };
        "drillDownFilters": {
        };
        "drillAcrossFilters": {
        };
      };
      clientJson: {
        "aoId": string;
        "viewBys": string[];
        "viewIds": string[];
        "globalViewbys": string[];
        "globalViewIds": string[];
        "dimensions": string[];
        "meassures": string[];
        "meassureIds": string[];
        "aggregation": string[];
        "globalInFilters": any;
        "globalNotInFilters": {
        };
        "localInFilters": {
        };
        "localNotInFilters": {
        };
        "drillDownFilters": {
        };
        "drillAcrossFilters": {
        };
      };
      data1: Observable<any>;
      data: Observable<any>;

      // SolrService
      public aoId: string[]
      public viewbys: string[] = ["brand"];  //Given by user  "Brand", "Category", "State" , "Region" , "city" , "Payment Method"
      public viewbysId: string[] = ["", "615128", "614847"];
      public dimensions: string[] = ["615228"];
      public measuresDefault: string[] = ["sales", "netsales"]; //Given by user
      public measures: string[] = ["sales", "netsales"]; //Given by user
      public measuresId: string[] = ["616275", "616283", "616279", "616648", "616295"];
      public aggregation = ["SUM", "SUM", "SUM", "SUM", "SUM", "SUM"];
      public globalInFilters: any = {};
      public globalNotInFilters = {};
      public localInFilters = {};
      public localNotInFilters = {};
      public drillDownFilters = {};
      public drillAcrossFilters = {};

      public elementIdsMap: any = { "615228": "Brand", "615128": "Category", "614847": "state" };

    private url ="http://183.82./Pvice/sovice"; //Global Server
      constructor(private router: Router, private http: Http, public jsonDataService: JsonDataService) {
      }

      ngOnInit() {
         this.clientJson = {
          "aoId": "M_AO_918",
          "viewBys": this.viewbys,
          "viewIds": this.viewbysId,
          "globalViewbys": ["brand", "uscity", "usstate"],
          "globalViewIds": ["615228", "615128", "614847"],
          "dimensions": this.dimensions,
          "meassures": this.measuresDefault,
          "meassureIds": this.measuresId,
          "aggregation": this.aggregation,
          "globalInFilters": this.globalInFilters,
          "globalNotInFilters": this.globalNotInFilters,
          "localInFilters": this.localInFilters,
          "localNotInFilters": this.localNotInFilters,
          "drillDownFilters": this.drillDownFilters,
          "drillAcrossFilters": this.drillAcrossFilters
        };

    this.clientJson1 ={
     "aoId": "M_AO_918",
          "viewBys": ["usstate"],
          "viewIds": this.viewbysId,
          "globalViewbys": ["brand", "uscity", "usstate"],
          "globalViewIds": ["615228", "615128", "614847"],
          "dimensions": this.dimensions,
          "meassures": this.measuresDefault,
          "meassureIds": this.measuresId,
          "aggregation": this.aggregation,
          "globalInFilters": this.globalInFilters,
          "globalNotInFilters": this.globalNotInFilters,
          "localInFilters": this.localInFilters,
          "localNotInFilters": this.localNotInFilters,
          "drillDownFilters": this.drillDownFilters,
          "drillAcrossFilters": this.drillAcrossFilters
    }

     this.data = this.http.post(this.url,this.clientJson).map(res => res.json());
        this.data1 = this.http.post(this.url,this.clientJson1).map(res => res.json());
           Observable.forkJoin([this.data , this.data1 ]).subscribe(results => {
          //results here
          this.loadedCharacter1  = results[1];
          this.loadedCharacter = results[0];
          console.log("results"+JSON.stringify(results[1]));
          console.log("results"+JSON.stringify(results[0]));
          // return results;
        });
         alert(this.loadedCharacter );
      }
    }

 abc.component.ts

 initData(){

//how to get loadedCharacter from `app.component.ts` here, and then pass it into buildabcchart() as below;

let jsonData = loadedCharacter;   // loadedCharacter: {}; from app.component.ts
buildabcchart(jsonData );
}

buildabcchart(jsonData ){
/*--------------*/
}

Body:
Question 1:

Here is a plunkr that demonstrates passing data from a parent component to child components https://plnkr.co/edit/dsnJShi87UUseFLVGscH?p=preview

So this uses the input binding to pass data from the parent to child.

// parent html
<child-component [someInput]="loadedCharacter"></child-component>

// child ts
export class ChildComponent{
    @Input() someInput; // someInput can be used throughout the child component
}

Now when loadedCharacter is defined in your parent.ts it is passed to the child through the "someInput" input binding.

For the second part of your question, "using the passed in data in a function", you can use the ngOnChanges lifecycle hook. In your child component you can add something like

// child ts
export class ChildComponent implements OnChanges {
    @Input() someInput; // someInput can be used throughout the child component

    ngOnChanges(){
        // do something with someInput here. This lifecycle hook is fired every time 1 or multiple input bindings are changed
    }
}

Resource on input binding: https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

Resource on ngOnChanges lifecycle hook: https://angular.io/api/core/OnChanges

Question 2

this.loadedCharacter is undefined because you are calling alert outside of the asynchronous task (forkJoin().subscribe). It is being called before the http requests finish. If you move it into the subscribe (and after you assign this.loadedCharacter) it should alert the data


问:
Button on click event disable button after 5 times it was clicked
I am fairly new to VB.NET. I feel like I did the hard parts and struggling with the easy one! I googled it before coming here but still struggling.

Basically I have a drop down list with all the available treatments and button next to it ( Add treatment). Every time I choose treatment from list I click on the button and it add it then bind it to gridview, the only issue is I want users to be able to add up to 5 treatments then disable the button. The question how Can I say find the number of times the button was clicked then I suppose I can just put If statement, I dont know how to find the value of the number of times the button was clicked.

```<code> Dim availableTreatment As ListItem = New ListItem
    Dim count As Integer = 0
    For count = 0 To 4
        If count <= 4 And btnavailableTreatment ( button clicked value is what should go here)  Then
            availableTreatment = DDTreatmentList.SelectedItem
            c.name = availableTreatment.Value
           saveTreatment(c)
            gvavailableTreatment.DataSource = getTreatment(c.name)
            gvavailableTreatment.DataBind()

        Else
            btnavailableTreatment.Enabled = False
        End If
        count = count + 1
    Next
</code>```

答:
Add this markup to your page:

```<code><asp:HiddenField id="NumberOfTimesClickedHiddenField"
                 value="0"
                 runat="server"/>
</code>```

Add this to your button click handler

```<code>'get previous value
Dim numberOfTimesClicked = Integer.Parse(NumberOfTimesClickedHiddenField.Value)

'increment value
numberOfTimesClicked += 1

'store new value
NumberOfTimesClickedHiddenField.Value = numberOfTimesClicked.ToString()

If numberOfTimesClicked >= 5 Then
    btnavailableTreatment.Enabled = False
End If
</code>```

Now the value will be persisted in the form data on the page.

I originally wrote this in C#, and I'm not a VB.NET programmer so I used a translator to convert it. There may be syntax errors but the general flow should be correct.

Body:
I am fairly new to VB.NET. I feel like I did the hard parts and struggling with the easy one! I googled it before coming here but still struggling.

Basically I have a drop down list with all the available treatments and button next to it ( Add treatment). Every time I choose treatment from list I click on the button and it add it then bind it to gridview, the only issue is I want users to be able to add up to 5 treatments then disable the button. The question how Can I say find the number of times the button was clicked then I suppose I can just put If statement, I dont know how to find the value of the number of times the button was clicked.

 Dim availableTreatment As ListItem = New ListItem
    Dim count As Integer = 0
    For count = 0 To 4
        If count <= 4 And btnavailableTreatment ( button clicked value is what should go here)  Then
            availableTreatment = DDTreatmentList.SelectedItem
            c.name = availableTreatment.Value
           saveTreatment(c)
            gvavailableTreatment.DataSource = getTreatment(c.name)
            gvavailableTreatment.DataBind()

        Else
            btnavailableTreatment.Enabled = False
        End If
        count = count + 1
    Next

Body:
Add this markup to your page:

<asp:HiddenField id="NumberOfTimesClickedHiddenField"
                 value="0"
                 runat="server"/>

Add this to your button click handler

'get previous value
Dim numberOfTimesClicked = Integer.Parse(NumberOfTimesClickedHiddenField.Value)

'increment value
numberOfTimesClicked += 1

'store new value
NumberOfTimesClickedHiddenField.Value = numberOfTimesClicked.ToString()

If numberOfTimesClicked >= 5 Then
    btnavailableTreatment.Enabled = False
End If

Now the value will be persisted in the form data on the page.

I originally wrote this in C#, and I'm not a VB.NET programmer so I used a translator to convert it. There may be syntax errors but the general flow should be correct.


问:
Create PDF / Word (Doc) file within app
Is there a definitive method of creating either a PDF or a MS Word Doc file within the app and email it immediately (and possibly, also store it).

I have been trying for quite some time and have found out the JAVA libraries: apwlibrary and iText. But both of them dont provide any tutorials of sorts.

Could anyone point me in the right direction?

EDIT: Come to think of it, is could an online PDF generator be used, first by sending the data to the service, then retrieve the result and save it on the phone?

答:
Unless it is a core feature of your device to create a pdf file I would suggest not to do it yourself. Adding PDF creation is going to be quite a lot of work potentially depending on your performance needs. Java libraries will be easier to add but less performant. Native libraries combined with Java will be more hazzle to maintain build and bug fixing wise. </p>

<p>If you just need to email some information why dont you create a message text in html and use a intent to email it with the build in email program instead? Or if you want you could e.g. put the PDF generation on a server and just email a link.. </p>

Title: Create PDF / Word (Doc) file within app

Body:
Unless it is a core feature of your device to create a pdf file I would suggest not to do it yourself. Adding PDF creation is going to be quite a lot of work potentially depending on your performance needs. Java libraries will be easier to add but less performant. Native libraries combined with Java will be more hazzle to maintain build and bug fixing wise.

If you just need to email some information why dont you create a message text in html and use a intent to email it with the build in email program instead? Or if you want you could e.g. put the PDF generation on a server and just email a link..


问:
How to disable auto changing tabs to spaces in the code in Intellij Idea?
How to disable auto changing tabs to spaces and removing empty lines, whitespaces in the sourcefiles after it opened?

In other words if the line contains tabs and spaces in one line Idea shouldn't change them. For example if file contains "-->-->....-->public void setAttribute();" Idea shouldn't change tabs to spaces or spaces to tabs. I can disable all autoformattig.

答: There is an option 'keep indents on empty line'