问:
How to do Streaming at controller layer Spring
I am developing one simple Java Spring application and trying to get all the saved Order from database. Application flow is simple though have around 100k record in database. I used streaming at JPA layer from DB to application data is coming fine.
But when this start transferring from Controller to client something it throws 502 response. Following is piece of code for all three layer. </p>

<p>Could someone help to solve this problem? Requirement all this data should come without using any filter or pagination.     </p>

```<code>@GetMapping(produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public Resources getOrders() {
        return userService.getOrders();
    }

    @Transactional
    public Resources getOrders() {
        Stream<Orders> orders = streamAll();

        List<Order> orderList = new ArrayList<>();
        orderList.addAll(orderConverter.createFromEntities(orders));

        Resource resources = new Resource();
        resources.setResources(orderList);
        return resources;
    }

    @Query("select u from Order")
    Stream<Orders> streamAll();
</code>```

答:
You are getting a 502 response because your JVM is exhausted in memory. Use streaming detached objects at the repository layer.

First, check if your database supports fetching a result set through streaming data. For example, MYSQL supports it using a read-only session and fetch size with value Integer.MIN_VALUE [1].

Later, customize your repository to open a stateless session with StatelessSession interface [2]. Thanks to this interface you are getting objects detached, so Hibernate releases it immediately and no cost memory in cache.

If you need to make changes, remember again, your objects are detached. You need open another session (read-write). Your objects will be saved with these session, and after saving it, you must detach it manually.

This example covers the first requirement:

```<code>@PersistenceContext
private EntityManager entityManager;

public void stackoverflowQuestion() {
        Session currentSession = entityManager.unwrap(Session.class);
        ScrollableResults rows = currentSession
            .createQuery("SELECT u FROM Order", Orders.class)
            .setFetchSize(Integer.MIN_VALUE)
            .scroll(ScrollMode.FORWARD_ONLY);

        while (rows.next()) {
            Orders order = (Orders) rows.get(0);
                ...
            }
}
</code>```

[1] https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-implementation-notes.html

[2] https://docs.jboss.org/hibernate/orm/3.5/reference/en-US/html/batch.html

Body:
I am developing one simple Java Spring application and trying to get all the saved Order from database. Application flow is simple though have around 100k record in database. I used streaming at JPA layer from DB to application data is coming fine.
But when this start transferring from Controller to client something it throws 502 response. Following is piece of code for all three layer.

Could someone help to solve this problem? Requirement all this data should come without using any filter or pagination.

@GetMapping(produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public Resources getOrders() {
        return userService.getOrders();
    }

    @Transactional
    public Resources getOrders() {
        Stream<Orders> orders = streamAll();

        List<Order> orderList = new ArrayList<>();
        orderList.addAll(orderConverter.createFromEntities(orders));

        Resource resources = new Resource();
        resources.setResources(orderList);
        return resources;
    }

    @Query("select u from Order")
    Stream<Orders> streamAll();

Body:
You are getting a 502 response because your JVM is exhausted in memory. Use streaming detached objects at the repository layer.

First, check if your database supports fetching a result set through streaming data. For example, MYSQL supports it using a read-only session and fetch size with value Integer.MIN_VALUE [1].

Later, customize your repository to open a stateless session with StatelessSession interface [2]. Thanks to this interface you are getting objects detached, so Hibernate releases it immediately and no cost memory in cache.

If you need to make changes, remember again, your objects are detached. You need open another session (read-write). Your objects will be saved with these session, and after saving it, you must detach it manually.

This example covers the first requirement:

@PersistenceContext
private EntityManager entityManager;

public void stackoverflowQuestion() {
        Session currentSession = entityManager.unwrap(Session.class);
        ScrollableResults rows = currentSession
            .createQuery("SELECT u FROM Order", Orders.class)
            .setFetchSize(Integer.MIN_VALUE)
            .scroll(ScrollMode.FORWARD_ONLY);

        while (rows.next()) {
            Orders order = (Orders) rows.get(0);
                ...
            }
}

[1] https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-implementation-notes.html

[2] https://docs.jboss.org/hibernate/orm/3.5/reference/en-US/html/batch.html


来源: stackexchange

问:
what is the fastest way to toggle images by class
i have a list of image

```<code><img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
</code>```

and i want to change the source of all of the images (by using the class selector .onOff so each of the above images changes to this:

```<code><img class="onOff" src="/Content/Images/off.png" />
</code>```

what is the most efficient way to changing all of these images through jquery?

答:
Call this javascript function</p>

```<code>    function changeImage() {
        $(".onOff").each(
            function()
            {
                $(this).attr("src","/Content/Images/off.png");
            }
        );
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have a list of image

and i want to change the source of all of the images (by using the class selector .onOff so each of the above images changes to this:

what is the most efficient way to changing all of these images through jquery?

Body:
Call this javascript function

    function changeImage() {
        $(".onOff").each(
            function()
            {
                $(this).attr("src","/Content/Images/off.png");
            }
        );
    }


问:
JanusGraph image stop responding after query timeout, how to prevent it?
When JanusGraph server exceeded his 'evaluationTimeout' the server stop responding

I'm using the default docker image janusgraph/janusgraph:latest (Berkeley and Lucene)
and connecting with gremlin console

After the first timeout accord, queries that worked before getting the same response:

```<code>Evaluation exceeded the configured 'evaluationTimeout' threshold of 30000 ms or evaluation was otherwise cancelled directly for request [g.V().limit(4).valueMap()]: null - try increasing the timeout with the :remote command
</code>```

server error:

```<code>
java.util.concurrent.TimeoutException: Evaluation exceeded the configured 'evaluationTimeout' threshold of 30000 ms or evaluation was otherwise cancelled directly for request [g.V()]
        at org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.lambda$eval$1(GremlinExecutor.java:316)
        at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98)
        at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:170)
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at java.lang.Thread.run(Thread.java:748)
1318978 [pool-6-thread-1] WARN  org.janusgraph.diskstorage.log.kcvs.KCVSLog  - Could not read messages for timestamp [2020-05-24T10:12:30.449Z] (this read will be retried)
org.janusgraph.core.JanusGraphException: Could not execute operation due to backend exception
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:56)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:158)
        at org.janusgraph.diskstorage.log.kcvs.KCVSLog$MessagePuller.run(KCVSLog.java:725)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.janusgraph.diskstorage.PermanentBackendException: Could not start BerkeleyJE transaction
        at org.janusgraph.diskstorage.berkeleyje.BerkeleyJEStoreManager.beginTransaction(BerkeleyJEStoreManager.java:163)
        at org.janusgraph.diskstorage.berkeleyje.BerkeleyJEStoreManager.beginTransaction(BerkeleyJEStoreManager.java:47)
        at org.janusgraph.diskstorage.keycolumnvalue.keyvalue.OrderedKeyValueStoreManagerAdapter.beginTransaction(OrderedKeyValueStoreManagerAdapter.java:68)
        at org.janusgraph.diskstorage.log.kcvs.KCVSLog.openTx(KCVSLog.java:319)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:145)
        at org.janusgraph.diskstorage.util.BackendOperation$1.call(BackendOperation.java:161)
        at org.janusgraph.diskstorage.util.BackendOperation.executeDirect(BackendOperation.java:68)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:54)
        ... 9 more
Caused by: com.sleepycat.je.ThreadInterruptedException: (JE 18.3.12) Environment must be closed, caused by: com.sleepycat.je.ThreadInterruptedException: Environment invalid because of previous exception: (JE 18.3.12) /var/lib/janusgraph/data java.lang.InterruptedException THREAD_INTERRUPTED: InterruptedException may cause incorrect internal state, unable to continue. Environment is invalid and must be closed.
        at com.sleepycat.je.ThreadInterruptedException.wrapSelf(ThreadInterruptedException.java:105)
        at com.sleepycat.je.dbi.EnvironmentImpl.checkIfInvalid(EnvironmentImpl.java:1835)
        at com.sleepycat.je.dbi.EnvironmentImpl.checkOpen(EnvironmentImpl.java:1844)
        at com.sleepycat.je.Environment.checkOpen(Environment.java:2697)
        at com.sleepycat.je.Environment.beginTransactionInternal(Environment.java:1409)
        at com.sleepycat.je.Environment.beginTransaction(Environment.java:1383)
        at org.janusgraph.diskstorage.berkeleyje.BerkeleyJEStoreManager.beginTransaction(BerkeleyJEStoreManager.java:146)
        ... 16 more
Caused by: com.sleepycat.je.ThreadInterruptedException: Environment invalid because of previous exception: (JE 18.3.12) /var/lib/janusgraph/data java.lang.InterruptedException THREAD_INTERRUPTED: InterruptedException may cause incorrect internal state, unable to continue. Environment is invalid and must be closed.
        at com.sleepycat.je.latch.LatchImpl.acquireExclusive(LatchImpl.java:67)
        at com.sleepycat.je.tree.IN.latch(IN.java:547)
        at com.sleepycat.je.dbi.CursorImpl.latchBIN(CursorImpl.java:402)
        at com.sleepycat.je.dbi.CursorImpl.cloneCursor(CursorImpl.java:230)
        at com.sleepycat.je.Cursor.beginMoveCursor(Cursor.java:5252)
        at com.sleepycat.je.Cursor.beginMoveCursor(Cursor.java:5259)
        at com.sleepycat.je.Cursor.retrieveNextNoDups(Cursor.java:3550)
        at com.sleepycat.je.Cursor.retrieveNext(Cursor.java:3312)
        at com.sleepycat.je.Cursor.getInternal(Cursor.java:1313)
        at com.sleepycat.je.Cursor.get(Cursor.java:1244)
        at com.sleepycat.je.Cursor.getNext(Cursor.java:1512)

</code>```

答:
This JanusGraph issue explains the problem in reference to traversal interruption with TinkerPop's test suite:

https://github.com/JanusGraph/janusgraph/issues/171

Since interrupts are not supported in Berkeley JE (see BerkeleyJEStoreManager and Berkeley JE FAQ) there are internal state errors in all tests after that suite runs.

One reason TinkerPop has that interruption test because it validates that Gremlin Server can use that interrupt function to cancel server based traversals successfully. It looks like Berkeley simply can't support that. You would need to use a different JanusGraph backend.

ContentLicense: CC BY-SA 4.0

Body:
When JanusGraph server exceeded his 'evaluationTimeout' the server stop responding

I'm using the default docker image janusgraph/janusgraph:latest (Berkeley and Lucene)
and connecting with gremlin console

After the first timeout accord, queries that worked before getting the same response:

Evaluation exceeded the configured 'evaluationTimeout' threshold of 30000 ms or evaluation was otherwise cancelled directly for request [g.V().limit(4).valueMap()]: null - try increasing the timeout with the :remote command

server error:

java.util.concurrent.TimeoutException: Evaluation exceeded the configured 'evaluationTimeout' threshold of 30000 ms or evaluation was otherwise cancelled directly for request [g.V()]
        at org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.lambda$eval$1(GremlinExecutor.java:316)
        at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98)
        at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:170)
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at java.lang.Thread.run(Thread.java:748)
1318978 [pool-6-thread-1] WARN  org.janusgraph.diskstorage.log.kcvs.KCVSLog  - Could not read messages for timestamp [2020-05-24T10:12:30.449Z] (this read will be retried)
org.janusgraph.core.JanusGraphException: Could not execute operation due to backend exception
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:56)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:158)
        at org.janusgraph.diskstorage.log.kcvs.KCVSLog$MessagePuller.run(KCVSLog.java:725)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.janusgraph.diskstorage.PermanentBackendException: Could not start BerkeleyJE transaction
        at org.janusgraph.diskstorage.berkeleyje.BerkeleyJEStoreManager.beginTransaction(BerkeleyJEStoreManager.java:163)
        at org.janusgraph.diskstorage.berkeleyje.BerkeleyJEStoreManager.beginTransaction(BerkeleyJEStoreManager.java:47)
        at org.janusgraph.diskstorage.keycolumnvalue.keyvalue.OrderedKeyValueStoreManagerAdapter.beginTransaction(OrderedKeyValueStoreManagerAdapter.java:68)
        at org.janusgraph.diskstorage.log.kcvs.KCVSLog.openTx(KCVSLog.java:319)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:145)
        at org.janusgraph.diskstorage.util.BackendOperation$1.call(BackendOperation.java:161)
        at org.janusgraph.diskstorage.util.BackendOperation.executeDirect(BackendOperation.java:68)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:54)
        ... 9 more
Caused by: com.sleepycat.je.ThreadInterruptedException: (JE 18.3.12) Environment must be closed, caused by: com.sleepycat.je.ThreadInterruptedException: Environment invalid because of previous exception: (JE 18.3.12) /var/lib/janusgraph/data java.lang.InterruptedException THREAD_INTERRUPTED: InterruptedException may cause incorrect internal state, unable to continue. Environment is invalid and must be closed.
        at com.sleepycat.je.ThreadInterruptedException.wrapSelf(ThreadInterruptedException.java:105)
        at com.sleepycat.je.dbi.EnvironmentImpl.checkIfInvalid(EnvironmentImpl.java:1835)
        at com.sleepycat.je.dbi.EnvironmentImpl.checkOpen(EnvironmentImpl.java:1844)
        at com.sleepycat.je.Environment.checkOpen(Environment.java:2697)
        at com.sleepycat.je.Environment.beginTransactionInternal(Environment.java:1409)
        at com.sleepycat.je.Environment.beginTransaction(Environment.java:1383)
        at org.janusgraph.diskstorage.berkeleyje.BerkeleyJEStoreManager.beginTransaction(BerkeleyJEStoreManager.java:146)
        ... 16 more
Caused by: com.sleepycat.je.ThreadInterruptedException: Environment invalid because of previous exception: (JE 18.3.12) /var/lib/janusgraph/data java.lang.InterruptedException THREAD_INTERRUPTED: InterruptedException may cause incorrect internal state, unable to continue. Environment is invalid and must be closed.
        at com.sleepycat.je.latch.LatchImpl.acquireExclusive(LatchImpl.java:67)
        at com.sleepycat.je.tree.IN.latch(IN.java:547)
        at com.sleepycat.je.dbi.CursorImpl.latchBIN(CursorImpl.java:402)
        at com.sleepycat.je.dbi.CursorImpl.cloneCursor(CursorImpl.java:230)
        at com.sleepycat.je.Cursor.beginMoveCursor(Cursor.java:5252)
        at com.sleepycat.je.Cursor.beginMoveCursor(Cursor.java:5259)
        at com.sleepycat.je.Cursor.retrieveNextNoDups(Cursor.java:3550)
        at com.sleepycat.je.Cursor.retrieveNext(Cursor.java:3312)
        at com.sleepycat.je.Cursor.getInternal(Cursor.java:1313)
        at com.sleepycat.je.Cursor.get(Cursor.java:1244)
        at com.sleepycat.je.Cursor.getNext(Cursor.java:1512)


问:
how to insert data into H2 database using reflection API
I have a Person class anootated with @PrimaryKey and @Column

```<code>    public class Person {

    @PrimaryKey(name = "p_id")
    private Integer id;

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

    @Column(name = "c_age")
    private Integer age;
    }
</code>```

Following is the persist method:

```<code>   public void persist(T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
    // TODO Auto-generated method stub
    MetaModel metaModel = MetaModel.of(t.getClass());
    String sql = metaModel.buildInsertRequest();

    try(PreparedStatement statement = prepareStatementWith(sql).andParameters(t)){
        statement.executeUpdate();
    }

}

    private PreparedStatementWrapper prepareStatementWith(String sql) throws SQLException {
    // TODO Auto-generated method stub

    Connection con = buildConnection();
    PreparedStatement statement = con.prepareStatement(sql);

    return new PreparedStatementWrapper(statement);
}

    private class PreparedStatementWrapper{

    private PreparedStatement statement;
    public PreparedStatementWrapper(PreparedStatement statement) {
        // TODO Auto-generated constructor stub
         this.statement = statement;
    }
</code>```

Here. returning the sql query

```<code>   public String buildInsertRequest() {
    // insert into Person(id, name, age) values(?, ?, ?)
    String pkColumnName = getPrimaryKey().getName();
    List<String> columNames = getColumn().stream().map(c -> c.getName()).collect(Collectors.toList());
    columNames.add(0, pkColumnName);
    String columnElement = String.join(", ", columNames);

    int numberOfColumns = getColumn().size() + 1;
    String questionMarkElement = IntStream.range(0, numberOfColumns)
                                            .mapToObj(index -> "?")
                                            .collect(Collectors.joining(", "));
    return "INSERT into " + this.clss.getSimpleName() + "(" + columnElement + ") values (" + questionMarkElement + ")";
}

   Here adding the parameter

   public PreparedStatement andParameters(T t) throws SQLException, IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub

        MetaModel metaModel = MetaModel.of(t.getClass());
        Class<?> pkType = metaModel.getPrimaryKey().getType();
        if(pkType == Integer.class) {
            Integer id = idGenerator.incrementAndGet();
            statement.setInt(1, id);
            Field field = metaModel.getPrimaryKey().getField();
            field.setAccessible(true);
            field.set(t, id);
        }
        for(int columnIndex = 0; columnIndex < metaModel.getColumn().size(); columnIndex++) {
            ColumnField columnField = (ColumnField) metaModel.getColumn().get(columnIndex);
            Class<?> fieldType = columnField.getType();
            Field field = columnField.getField();
            field.setAccessible(true);
            Object value = field.get(t);
            if(fieldType == Integer.class) {
                statement.setInt(columnIndex + 2,(Integer) value);
            } else if(fieldType == String.class) {
                statement.setString(columnIndex + 1, (String)value);
            }
        }
        return statement;
    }
</code>```

I am getting error in prepareStatementWith(sql) method, it's not reurning the new PreparedStatementWrapper instead it's throwing exception Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement:
INSERT into Person(p_id, c_name, c_age) values (?, ?, ?)

Following is the connection details:

```<code>    public Connection buildConnection() throws SQLException {
    Connection con =
            DriverManager.getConnection("jdbc:h2:C:\\Users\\biplab.musib\\eclipse-workspace\\ReflectionProject\\db-files\\db-files", "sa", "");
    return con;
</code>```

JDBC url in H2 promp : jdbc:h2:C:\Users\biplab.musib\eclipse-workspace\ReflectionProject\db-files\db-reflection

can someone help me here

答:
For me changing connection URL to same as the H2 database connection URL worked:</p>

```<code>Connection connection = DriverManager.getConnection("jdbc:h2:C:\\Users\\PUSHPENDRA KUMAR\\IdeaProjects\\PlayWithReflection\\dbfiles\\db-pluralsight","sa","");
</code>```

Body:
I have a Person class anootated with @PrimaryKey and @Column

    public class Person {

    @PrimaryKey(name = "p_id")
    private Integer id;

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

    @Column(name = "c_age")
    private Integer age;
    }

Following is the persist method:

   public void persist(T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
    // TODO Auto-generated method stub
    MetaModel metaModel = MetaModel.of(t.getClass());
    String sql = metaModel.buildInsertRequest();

    try(PreparedStatement statement = prepareStatementWith(sql).andParameters(t)){
        statement.executeUpdate();
    }

}

    private PreparedStatementWrapper prepareStatementWith(String sql) throws SQLException {
    // TODO Auto-generated method stub

    Connection con = buildConnection();
    PreparedStatement statement = con.prepareStatement(sql);

    return new PreparedStatementWrapper(statement);
}

    private class PreparedStatementWrapper{

    private PreparedStatement statement;
    public PreparedStatementWrapper(PreparedStatement statement) {
        // TODO Auto-generated constructor stub
         this.statement = statement;
    }

Here. returning the sql query

   public String buildInsertRequest() {
    // insert into Person(id, name, age) values(?, ?, ?)
    String pkColumnName = getPrimaryKey().getName();
    List<String> columNames = getColumn().stream().map(c -> c.getName()).collect(Collectors.toList());
    columNames.add(0, pkColumnName);
    String columnElement = String.join(", ", columNames);

    int numberOfColumns = getColumn().size() + 1;
    String questionMarkElement = IntStream.range(0, numberOfColumns)
                                            .mapToObj(index -> "?")
                                            .collect(Collectors.joining(", "));
    return "INSERT into " + this.clss.getSimpleName() + "(" + columnElement + ") values (" + questionMarkElement + ")";
}

   Here adding the parameter

   public PreparedStatement andParameters(T t) throws SQLException, IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub

        MetaModel metaModel = MetaModel.of(t.getClass());
        Class<?> pkType = metaModel.getPrimaryKey().getType();
        if(pkType == Integer.class) {
            Integer id = idGenerator.incrementAndGet();
            statement.setInt(1, id);
            Field field = metaModel.getPrimaryKey().getField();
            field.setAccessible(true);
            field.set(t, id);
        }
        for(int columnIndex = 0; columnIndex < metaModel.getColumn().size(); columnIndex++) {
            ColumnField columnField = (ColumnField) metaModel.getColumn().get(columnIndex);
            Class<?> fieldType = columnField.getType();
            Field field = columnField.getField();
            field.setAccessible(true);
            Object value = field.get(t);
            if(fieldType == Integer.class) {
                statement.setInt(columnIndex + 2,(Integer) value);
            } else if(fieldType == String.class) {
                statement.setString(columnIndex + 1, (String)value);
            }
        }
        return statement;
    }

I am getting error in prepareStatementWith(sql) method, it's not reurning the new PreparedStatementWrapper instead it's throwing exception Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement:
INSERT into Person(p_id, c_name, c_age) values (?, ?, ?)

Following is the connection details:

    public Connection buildConnection() throws SQLException {
    Connection con =
            DriverManager.getConnection("jdbc:h2:C:\\Users\\biplab.musib\\eclipse-workspace\\ReflectionProject\\db-files\\db-files", "sa", "");
    return con;

JDBC url in H2 promp : jdbc:h2:C:\Users\biplab.musib\eclipse-workspace\ReflectionProject\db-files\db-reflection

can someone help me here

Body:
For me changing connection URL to same as the H2 database connection URL worked:

Connection connection = DriverManager.getConnection("jdbc:h2:C:\\Users\\PUSHPENDRA KUMAR\\IdeaProjects\\PlayWithReflection\\dbfiles\\db-pluralsight","sa","");


问:
Semantic 2 Dropdown angular 2 not working
EDIT - 1 - implemented AfterViewInit in the class as per the suggestion.

I am trying to find the issue but am not able to. I have used a simple dropdown and have imported (I believe so) all the semantic configurations, but the dropdown wont work like it should. I think the css is getting applied but the animation isn't. I'm really confused, any help is greatly appreciated.

It gives error at

```<code> ngAfterViewInit(){
    $('.ui.dropdown').dropdown();
  }
</code>```

Below are the details of the app.

Index.html

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

<link rel="stylesheet" type="text/css" href="../semantic/dist/semantic.min.css">
<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
<script src="../semantic/dist/semantic.min.js"></script>
<script src="../semantic/dist/components/dropdown.js"></script>

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>
</code>```

Module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MaterialModule,MdButtonModule} from '@angular/material';
import 'hammerjs';
import { AppComponent } from './app.component';
import { ScripttableComponent } from './scripts/scripttable/scripttable.component';
import { ScriptsComponent } from './scripts/scripts.component';

@NgModule({
  declarations: [
    AppComponent,
    ScripttableComponent,
    ScriptsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule,
    BrowserAnimationsModule,
    MdButtonModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component,AfterViewInit } from '@angular/core';

import {$} from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'app works!';

  ngAfterViewInit(){
    $('.ui.dropdown').dropdown();
  }

}
</code>```

app.component.html

```<code>   <select name="Program" id="program" class="ui search dropdown">
        <option value="">Program</option>
        <option value="eCQMs">eCQMs</option>
        <option value="Mips">Mips</option>
        <option value="Pqrs">Pqrs</option>
      </select>
</code>```

- App folders -

Console-error

答:
https://edcarroll.github.io/ng2-semantic-ui/#/getting-started

You need to use Angular semantic for angular projects.

Body:
EDIT - 1 - implemented AfterViewInit in the class as per the suggestion.

I am trying to find the issue but am not able to. I have used a simple dropdown and have imported (I believe so) all the semantic configurations, but the dropdown wont work like it should. I think the css is getting applied but the animation isn't. I'm really confused, any help is greatly appreciated.

It gives error at

 ngAfterViewInit(){
    $('.ui.dropdown').dropdown();
  }

Below are the details of the app.

Index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Demo</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

<link rel="stylesheet" type="text/css" href="../semantic/dist/semantic.min.css">

  <app-root>Loading...</app-root>

Module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MaterialModule,MdButtonModule} from '@angular/material';
import 'hammerjs';
import { AppComponent } from './app.component';
import { ScripttableComponent } from './scripts/scripttable/scripttable.component';
import { ScriptsComponent } from './scripts/scripts.component';

@NgModule({
  declarations: [
    AppComponent,
    ScripttableComponent,
    ScriptsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule,
    BrowserAnimationsModule,
    MdButtonModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component,AfterViewInit } from '@angular/core';

import {$} from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'app works!';

  ngAfterViewInit(){
    $('.ui.dropdown').dropdown();
  }

}

app.component.html

   <select name="Program" id="program" class="ui search dropdown">
        <option value="">Program</option>
        <option value="eCQMs">eCQMs</option>
        <option value="Mips">Mips</option>
        <option value="Pqrs">Pqrs</option>
      </select>

- App folders -

Console-error


问:
Converting 15 minutes interval usage data in pivot form to 60 minutes format

I want to convert this to hourly format like:

```<code>df['1:00'] = df['0:15'] + df['0:30'] + df['0:45'] + df['1:00']
</code>```

Also, i do not want to create extra duplicate columns.

Please help. Thanks in advance.

答:
Use:</p>

```<code>#convert non time values to MultiIndex and sorting times columns
df1 = df.set_index(['Account','Date']).sort_index(axis=1)
#create groups by previous values of ends with :00
g = df1.columns.str.endswith(':00')[::-1].cumsum()[::-1]
#aggregate sum
df2 = df1.groupby(g, axis=1).sum().add_suffix(':00').reset_index()
</code>```

Body:
I want to convert this to hourly format like:

df['1:00'] = df['0:15'] + df['0:30'] + df['0:45'] + df['1:00']

Also, i do not want to create extra duplicate columns.

Please help. Thanks in advance.

Body:
Use:

#convert non time values to MultiIndex and sorting times columns
df1 = df.set_index(['Account','Date']).sort_index(axis=1)
#create groups by previous values of ends with :00
g = df1.columns.str.endswith(':00')[::-1].cumsum()[::-1]
#aggregate sum
df2 = df1.groupby(g, axis=1).sum().add_suffix(':00').reset_index()


问:
Angular 8 Jasmine and karma testing: mocked ngonit promise value is not rendered in the DOM
My mock data in a test will not display in the markup when running the test. No matter what i try (fakeasync, done, stubs) the content of the promise is not rendered in the markup after running the test.

Can anyone please tell me why this mocked promise data will not display in the dom. I have spent 2 days almost on this and it simply does not work no matter what i try. I'm using angular 8 and starting to think it's a bug in the framework.

I have the following markup:

```<code><div>
    <div class="pt-8">
        <!-- Displays -->
        <ul>
            <li *ngFor="let worker of workers">{{worker.getName()}}</li>
        </ul>

        <!-- DOES NOT DISPLAY -->
        <ol>
            <li *ngFor="let centre of centres">{{centre.name}}</li>
        </ol>
    </div>
</div>
</code>```

This is the class:

```<code>import { Component, OnInit, Input, Inject } from '@angular/core';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { User } from 'app/model/user';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  workers: User[];
  centres: Workcenter[];

  constructor(private workcentersService: WorkcentersService) { }

  ngOnInit(): void {
    let user1 = new User(); user1.name = "worker 1"; user1.surname = "surname1";
    let user2 = new User(); user2.name = "worker 2"; user2.surname = "surname2";
    let user3 = new User(); user3.name = "worker 3"; user3.surname = "surname3";
    this.workers = [user1, user2, user3];
    this.workcentersService.getWorkcentersList().then(wc => this.centres = wc);
  }
}
</code>```

This is the test:

```<code>import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { TestComponent } from './test.component';

fdescribe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async () => {
    const mockCentres = createMockCentres();
    const mockWorkcentersService = jasmine.createSpyObj(["getWorkcentersList"]);
    mockWorkcentersService.getWorkcentersList.and.returnValue(Promise.resolve(mockCentres));

    TestBed.configureTestingModule({
      declarations: [TestComponent],
      imports: [],
      providers: [
        { provide: WorkcentersService, useValue: mockWorkcentersService }
      ]
    });

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    await fixture.whenStable();
    fixture.detectChanges();
  });

  // Passes
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // Passes
  it('should render users', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ul li");
    expect(displayedUsers.length).toEqual(3);
  });

  // Fails
  it('should render centres', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  });

  // Fails
  it('should display "hello"', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  }));

  function createMockCentres(): Workcenter[] {
    const mockCentre1 = new Workcenter();mockCentre1.id = 1;mockCentre1.name = "Test centre 1";
    const mockCentre2 = new Workcenter();mockCentre2.id = 2;mockCentre2.name = "Test centre 2";
    return [mockCentre1, mockCentre2];
  }
});
</code>```

答:
```<code>import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { WorkCenter } from './workCenter';
import { WorkcentersService } from './workcenters.service';

fdescribe('TestComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let mockWorkcentersService: WorkcentersService;
  beforeEach(async () => {
    const mockCentres = createMockCentres();
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [],
      providers: [
        WorkcentersService
      ]
    });

    fixture = TestBed.createComponent(AppComponent);
    mockWorkcentersService = TestBed.get(WorkcentersService);
    spyOn(mockWorkcentersService, 'getWorkcentersList').and.returnValue(new Promise((resolve, reject) => resolve(mockCentres)));
    component = fixture.componentInstance;
    await fixture.whenStable();
    fixture.detectChanges();
  });

  // Passes
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // Passes
  it('should render users', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll('ul li');
    expect(displayedUsers.length).toEqual(3);
  });

  // Fails
  it('should render centres', async () => {
    expect(mockWorkcentersService.getWorkcentersList).toHaveBeenCalled();
    fixture.detectChanges();
    await fixture.whenStable();
    const displayedUsers = fixture.nativeElement.querySelectorAll('ol li');
    expect(displayedUsers.length).toEqual(2);
  });

  // Fails
  it('should display "hello"', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    const displayedUsers = fixture.nativeElement.querySelectorAll('ol li');
    expect(displayedUsers.length).toEqual(2);
  }));

  function createMockCentres(): WorkCenter[] {
    const mockCentre1 = new WorkCenter(); mockCentre1.id = 1; mockCentre1.name = 'Test centre 1';
    const mockCentre2 = new WorkCenter(); mockCentre2.id = 2; mockCentre2.name = 'Test centre 2';
    return [mockCentre1, mockCentre2];
  }
});
</code>```

This worked for me

proof :-

Also tried running single test case to show you that test centers are displaying now :-

Body:
My mock data in a test will not display in the markup when running the test. No matter what i try (fakeasync, done, stubs) the content of the promise is not rendered in the markup after running the test.

Can anyone please tell me why this mocked promise data will not display in the dom. I have spent 2 days almost on this and it simply does not work no matter what i try. I'm using angular 8 and starting to think it's a bug in the framework.

I have the following markup:

{{worker.getName()}}

{{centre.name}}

This is the class:

import { Component, OnInit, Input, Inject } from '@angular/core';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { User } from 'app/model/user';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  workers: User[];
  centres: Workcenter[];

  constructor(private workcentersService: WorkcentersService) { }

  ngOnInit(): void {
    let user1 = new User(); user1.name = "worker 1"; user1.surname = "surname1";
    let user2 = new User(); user2.name = "worker 2"; user2.surname = "surname2";
    let user3 = new User(); user3.name = "worker 3"; user3.surname = "surname3";
    this.workers = [user1, user2, user3];
    this.workcentersService.getWorkcentersList().then(wc => this.centres = wc);
  }
}

This is the test:

import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { TestComponent } from './test.component';

fdescribe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async () => {
    const mockCentres = createMockCentres();
    const mockWorkcentersService = jasmine.createSpyObj(["getWorkcentersList"]);
    mockWorkcentersService.getWorkcentersList.and.returnValue(Promise.resolve(mockCentres));

    TestBed.configureTestingModule({
      declarations: [TestComponent],
      imports: [],
      providers: [
        { provide: WorkcentersService, useValue: mockWorkcentersService }
      ]
    });

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    await fixture.whenStable();
    fixture.detectChanges();
  });

  // Passes
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // Passes
  it('should render users', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ul li");
    expect(displayedUsers.length).toEqual(3);
  });

  // Fails
  it('should render centres', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  });

  // Fails
  it('should display "hello"', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  }));

  function createMockCentres(): Workcenter[] {
    const mockCentre1 = new Workcenter();mockCentre1.id = 1;mockCentre1.name = "Test centre 1";
    const mockCentre2 = new Workcenter();mockCentre2.id = 2;mockCentre2.name = "Test centre 2";
    return [mockCentre1, mockCentre2];
  }
});

Body:
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { WorkCenter } from './workCenter';
import { WorkcentersService } from './workcenters.service';

fdescribe('TestComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let mockWorkcentersService: WorkcentersService;
  beforeEach(async () => {
    const mockCentres = createMockCentres();
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [],
      providers: [
        WorkcentersService
      ]
    });

    fixture = TestBed.createComponent(AppComponent);
    mockWorkcentersService = TestBed.get(WorkcentersService);
    spyOn(mockWorkcentersService, 'getWorkcentersList').and.returnValue(new Promise((resolve, reject) => resolve(mockCentres)));
    component = fixture.componentInstance;
    await fixture.whenStable();
    fixture.detectChanges();
  });

  // Passes
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // Passes
  it('should render users', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll('ul li');
    expect(displayedUsers.length).toEqual(3);
  });

  // Fails
  it('should render centres', async () => {
    expect(mockWorkcentersService.getWorkcentersList).toHaveBeenCalled();
    fixture.detectChanges();
    await fixture.whenStable();
    const displayedUsers = fixture.nativeElement.querySelectorAll('ol li');
    expect(displayedUsers.length).toEqual(2);
  });

  // Fails
  it('should display "hello"', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    const displayedUsers = fixture.nativeElement.querySelectorAll('ol li');
    expect(displayedUsers.length).toEqual(2);
  }));

  function createMockCentres(): WorkCenter[] {
    const mockCentre1 = new WorkCenter(); mockCentre1.id = 1; mockCentre1.name = 'Test centre 1';
    const mockCentre2 = new WorkCenter(); mockCentre2.id = 2; mockCentre2.name = 'Test centre 2';
    return [mockCentre1, mockCentre2];
  }
});

This worked for me

proof :-

Also tried running single test case to show you that test centers are displaying now :-


问:
Textfield hiding under keyboard flutter
Before textfield use to go up with the keyboard but now its not going and hiding under keyboard. I have tried all the solutions in internet like resizeToAvoidBottomInset, resizeToAvoidBottomPadding etc. but none of them worked for me. This is very frustrating. Can you guys help me?

```<code>import 'package:darpandentalhome/services/auth.dart';
import 'package:darpandentalhome/shared/const.dart';
import 'package:darpandentalhome/shared/loading.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_svg/flutter_svg.dart';

class SignIn extends StatefulWidget {

  final Function toggleView;
  SignIn({this.toggleView});

  @override
  _SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();
  final _formKey = GlobalKey<FormState>();
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();

  bool loading = false;

  String email = '';
  String password = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Color(0xfff9f9f9),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              width: MediaQuery. of(context). size. width,
              child: SvgPicture.asset('assets/images/Illustration.svg', fit: BoxFit.cover,),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(
                child: Text(
                  'Darpan Dental Home',
                  style: GoogleFonts.rubik(
                    textStyle: TextStyle(
                      fontSize: 35,
                      fontWeight: FontWeight.w500
                    ),
                  ),
                ),
              ),
            ),
            loading ? Loading() : SizedBox(height: 6),
            Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                      padding: const EdgeInsets.fromLTRB(25,10,20,0),
                      child: Text(
                        'Email:',
                        style: GoogleFonts.rubik(
                          textStyle: TextStyle(
                              fontSize: 18,
                          ),
                        )
                      )
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20,10,20,10),
                    child: TextFormField(
                      textInputAction: TextInputAction.next,
                      onEditingComplete: () => FocusScope.of(context).nextFocus(),
                      validator: (val) => val.isEmpty ? "Please Enter your email" : null,
                      onChanged: (val) {
                        setState(() {
                          email = val;
                        });
                      },
                      style: GoogleFonts.rubik(
                        textStyle: TextStyle(
                          fontSize: 15,
                        ),
                      ),
                      cursorColor: Colors.black,
                      decoration: textInputDecoration.copyWith(hintText: 'sanjivgurung@gmail.com'),
                    ),
                  ),
                  Padding(
                      padding: const EdgeInsets.fromLTRB(25,10,20,0),
                      child: Text(
                        'Password:',
                          style: GoogleFonts.rubik(
                            textStyle: TextStyle(
                              fontSize: 18,
                            ),
                          )
                      )
                  ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(20,10,20,20),
                      child: TextFormField(
                        textInputAction: TextInputAction.done,
                        validator: (val) => val.length<6 ? "Please enter a password 6+ character" : null,
                        onChanged: (val) {
                          setState(() {
                            password = val;
                          });
                        },
                          style: GoogleFonts.rubik(
                            textStyle: TextStyle(
                              fontSize: 15,
                            ),
                          ),
                          obscureText: true,
                          cursorColor: Colors.black,
                          decoration: textInputDecoration.copyWith(hintText: '**********'),
                      ),
                  )
                ],
              ),
            ),
            MaterialButton(
              height: 55,
              minWidth: 230,
              elevation: 0,
              shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(10.0)),
              color: Color(0xff4CBBB9),
              onPressed: () async {
                if(_formKey.currentState.validate()){
                  setState(() {
                    loading = true;
                  });
                  dynamic result = await _auth.signInWithEmailAndPassword(email, password);
                  if(result==null) {
                    setState(() {
                      loading = false;
                    });
                    _scaffoldKey.currentState.showSnackBar(
                        SnackBar(
                          behavior: SnackBarBehavior.floating,
                          elevation: 0,
                          duration: Duration(milliseconds: 800),
                          backgroundColor: Colors.red[700],
                          content: Text(
                              'Error Signing In',
                              style: GoogleFonts.rubik(
                                textStyle: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18,
                                  letterSpacing: 1.5
                                ),
                              )
                          ),
                        )
                    );
                  }
                }
              },
              child: Text(
                'Sign In',
                  style: GoogleFonts.rubik(
                    textStyle: TextStyle(
                      fontSize: 17,
                      color: Colors.white,
                      fontWeight: FontWeight.w500
                    ),
                  )
              ),
            ),
            Center(
                child: Padding(
                  padding: EdgeInsets.only(top: 10, bottom: 10),
                  child: InkWell(
                    onTap: () {
                      widget.toggleView();
                    },
                    child: Text(
                      'Want a new account?',
                      style: GoogleFonts.rubik(
                        textStyle: TextStyle(
                          fontSize: 15,
                          color: Color(0xffCE5B51),
                        ),
                      ),
                    ),
                  ),
                )
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

I am also getting this message when I click on the textfield. Is there any problem?

```<code>W/IInputConnectionWrapper(18968): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(18968): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(18968): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(18968): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(18968): endBatchEdit on inactive InputConnection
</code>```

Screen after keyboard is up

Screen before keyboard is up

答:
Fixed this issue by removing this line of code from AndroidManifest.xml file and full restarting the app. Before it did not work because I was just removing the line and hot restarting the app. In order to save the changes in AndroidManifest.xml file you have to full restart the app to see the changes.

```<code><item name="android:windowFullscreen">true</item>
</code>```

Thank You.

Title: Textfield hiding under keyboard flutter

Body:
Before textfield use to go up with the keyboard but now its not going and hiding under keyboard. I have tried all the solutions in internet like resizeToAvoidBottomInset, resizeToAvoidBottomPadding etc. but none of them worked for me. This is very frustrating. Can you guys help me?

import 'package:darpandentalhome/services/auth.dart';
import 'package:darpandentalhome/shared/const.dart';
import 'package:darpandentalhome/shared/loading.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_svg/flutter_svg.dart';

class SignIn extends StatefulWidget {

  final Function toggleView;
  SignIn({this.toggleView});

  @override
  _SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();
  final _formKey = GlobalKey<FormState>();
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();

  bool loading = false;

  String email = '';
  String password = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Color(0xfff9f9f9),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              width: MediaQuery. of(context). size. width,
              child: SvgPicture.asset('assets/images/Illustration.svg', fit: BoxFit.cover,),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(
                child: Text(
                  'Darpan Dental Home',
                  style: GoogleFonts.rubik(
                    textStyle: TextStyle(
                      fontSize: 35,
                      fontWeight: FontWeight.w500
                    ),
                  ),
                ),
              ),
            ),
            loading ? Loading() : SizedBox(height: 6),
            Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                      padding: const EdgeInsets.fromLTRB(25,10,20,0),
                      child: Text(
                        'Email:',
                        style: GoogleFonts.rubik(
                          textStyle: TextStyle(
                              fontSize: 18,
                          ),
                        )
                      )
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20,10,20,10),
                    child: TextFormField(
                      textInputAction: TextInputAction.next,
                      onEditingComplete: () => FocusScope.of(context).nextFocus(),
                      validator: (val) => val.isEmpty ? "Please Enter your email" : null,
                      onChanged: (val) {
                        setState(() {
                          email = val;
                        });
                      },
                      style: GoogleFonts.rubik(
                        textStyle: TextStyle(
                          fontSize: 15,
                        ),
                      ),
                      cursorColor: Colors.black,
                      decoration: textInputDecoration.copyWith(hintText: 'sanjivgurung@gmail.com'),
                    ),
                  ),
                  Padding(
                      padding: const EdgeInsets.fromLTRB(25,10,20,0),
                      child: Text(
                        'Password:',
                          style: GoogleFonts.rubik(
                            textStyle: TextStyle(
                              fontSize: 18,
                            ),
                          )
                      )
                  ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(20,10,20,20),
                      child: TextFormField(
                        textInputAction: TextInputAction.done,
                        validator: (val) => val.length<6 ? "Please enter a password 6+ character" : null,
                        onChanged: (val) {
                          setState(() {
                            password = val;
                          });
                        },
                          style: GoogleFonts.rubik(
                            textStyle: TextStyle(
                              fontSize: 15,
                            ),
                          ),
                          obscureText: true,
                          cursorColor: Colors.black,
                          decoration: textInputDecoration.copyWith(hintText: '**********'),
                      ),
                  )
                ],
              ),
            ),
            MaterialButton(
              height: 55,
              minWidth: 230,
              elevation: 0,
              shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(10.0)),
              color: Color(0xff4CBBB9),
              onPressed: () async {
                if(_formKey.currentState.validate()){
                  setState(() {
                    loading = true;
                  });
                  dynamic result = await _auth.signInWithEmailAndPassword(email, password);
                  if(result==null) {
                    setState(() {
                      loading = false;
                    });
                    _scaffoldKey.currentState.showSnackBar(
                        SnackBar(
                          behavior: SnackBarBehavior.floating,
                          elevation: 0,
                          duration: Duration(milliseconds: 800),
                          backgroundColor: Colors.red[700],
                          content: Text(
                              'Error Signing In',
                              style: GoogleFonts.rubik(
                                textStyle: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18,
                                  letterSpacing: 1.5
                                ),
                              )
                          ),
                        )
                    );
                  }
                }
              },
              child: Text(
                'Sign In',
                  style: GoogleFonts.rubik(
                    textStyle: TextStyle(
                      fontSize: 17,
                      color: Colors.white,
                      fontWeight: FontWeight.w500
                    ),
                  )
              ),
            ),
            Center(
                child: Padding(
                  padding: EdgeInsets.only(top: 10, bottom: 10),
                  child: InkWell(
                    onTap: () {
                      widget.toggleView();
                    },
                    child: Text(
                      'Want a new account?',
                      style: GoogleFonts.rubik(
                        textStyle: TextStyle(
                          fontSize: 15,
                          color: Color(0xffCE5B51),
                        ),
                      ),
                    ),
                  ),
                )
            ),
          ],
        ),
      ),
    );
  }
}

I am also getting this message when I click on the textfield. Is there any problem?

W/IInputConnectionWrapper(18968): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(18968): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(18968): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(18968): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(18968): endBatchEdit on inactive InputConnection

Screen after keyboard is up

Screen before keyboard is up

Body:
Fixed this issue by removing this line of code from AndroidManifest.xml file and full restarting the app. Before it did not work because I was just removing the line and hot restarting the app. In order to save the changes in AndroidManifest.xml file you have to full restart the app to see the changes.

<item name="android:windowFullscreen">true</item>

Thank You.


问:
Push committed files in PyCharm
I have committed some files to Git using PyCharm. Now I want to push them but I don't see such an option.

答: You can perform git push by selecting from VCS -> Git -> Push button

Title: Push committed files in PyCharm


问:
JavaScript : Regular expression
The subject exists but I don't understand here: (I am beginner)

Check whether a string matches a regex in JS

In fact, I have a form name, in my validation I would like to avoid that the user enters numbers or symbols.

function validation()
{
    const name = document.getElementById('name').value;

    if(!name){
        document.getElementById('nameError').innerHTML = " ** Empty ! ";
        return false;
    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="return validation()" >
  <br>
  <label>Name </label>
  <br>
  <input type="text" name="name" id="name" placeholder="Your name">
  <br>
  <span id="nameError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

Thank you very much for your help.

答:
Try</p>

```<code>if(/^([a-zA-Z ]+)$/.test(name) === false) {
 ... // Your error handle code
}
</code>```

Title: JavaScript : Regular expression

Body:
The subject exists but I don't understand here: (I am beginner)

Check whether a string matches a regex in JS

In fact, I have a form name, in my validation I would like to avoid that the user enters numbers or symbols.

function validation()
{
    const name = document.getElementById('name').value;

    if(!name){
        document.getElementById('nameError').innerHTML = " ** Empty ! ";
        return false;
    }

}

<form action="#" onsubmit="return validation()" >

  Name

  <input type="text" name="name" id="name" placeholder="Your name">

  <input type="submit" value="ok">
</form>

Thank you very much for your help.

Body:
Try

if(/^([a-zA-Z ]+)$/.test(name) === false) {
 ... // Your error handle code
}


答:
function validation() {
  const name = document.getElementById('name').value;

  if (!name) {
    document.getElementById('nameError').innerHTML = ' ** Empty ! ';
    return false;
  }

  if (!/^[a-zA-Z]+$/.test(name)) {
    document.getElementById('nameError').innerHTML = ' ** No number or symbol ! ';
    return false;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="return validation()" >
  <br>
  <label>Name </label>
  <br>
  <input type="text" name="name" id="name" placeholder="Your name">
  <br>
  <span id="nameError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

Title: JavaScript : Regular expression

Body:
function validation() {
  const name = document.getElementById('name').value;

  if (!name) {
    document.getElementById('nameError').innerHTML = ' ** Empty ! ';
    return false;
  }

  if (!/^[a-zA-Z]+$/.test(name)) {
    document.getElementById('nameError').innerHTML = ' ** No number or symbol ! ';
    return false;
  }
}

<form action="#" onsubmit="return validation()" >
  <br>
  <label>Name </label>
  <br>
  <input type="text" name="name" id="name" placeholder="Your name">
  <br>
  <span id="nameError"></span>
  <br>
  <input type="submit" value="ok">
</form>


问:
PHP fileToUpload
I've traced around many of the forums looking for an answer. Hopefully someone could steer me in the right direction. Or possibly have the answer.

I understand this part

```<code><form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>
</code>```

I get most of this part.

```<code><?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    echo $imageFileLoc;
    //echo "www.fastersmartereasier.com/noindex/video/test/uploads/".basename( $_FILES["fileToUpload"]["name"]);
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>
</code>```

Now if I select the file and hit submit. All works fine.

The problem is, I don't want to have to select the file. I want to launch my HTML page and it upload my files that reside in a folder. Let's call it /Users/Scott/Desktop/exports

Based on the forums I've found, PHP isn't able to do that.

1) is this true?
2) if it isn't how can I use PHP to take files from a defined folder.
3) If it is true, what Methods can I do to achieve the above without using PHP then.

答:
Is a security feature, the user must select or drop the file into the browser window. If we can set the value dynamically we can steal any file from the user computer.

You can use html5 and drag and drop multiple files at a time, but you can not set the value dynamically using JavaScript.

Take a look on this link to upload multiples files.

Title: PHP fileToUpload

Body:
I've traced around many of the forums looking for an answer. Hopefully someone could steer me in the right direction. Or possibly have the answer.

I understand this part

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

I get most of this part.

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    echo $imageFileLoc;
    //echo "www.fastersmartereasier.com/noindex/video/test/uploads/".basename( $_FILES["fileToUpload"]["name"]);
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

Now if I select the file and hit submit. All works fine.

The problem is, I don't want to have to select the file. I want to launch my HTML page and it upload my files that reside in a folder. Let's call it /Users/Scott/Desktop/exports

Based on the forums I've found, PHP isn't able to do that.

1) is this true?
2) if it isn't how can I use PHP to take files from a defined folder.
3) If it is true, what Methods can I do to achieve the above without using PHP then.


问:
Adding Text beneath each column 4X4 using CSS GRID
I am very new to CSS Grid and am trying to create a 2 X 2 grid. I am able to create the four image divs ( 2 on each row and 2 on each column) but I want the text to appear underneath each one. I have tried to use the grid-template-areas property but all the text just appears under one div all overlapped.

Any help would be appreciated, please.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-template-areas: "image image " "text text";
}

.text {
  grid-area: text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">
        TEXT 2
      </p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner --></code>```

答:
I removed the grid-area configuration from CSS code. Also, I have rearranged the sequence of your image and text HTML code. I hope this is what you expected.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
  /*grid-area: image;*/
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  /* grid-template-areas: "image image" "text text"; */
}

.text {
  text-align: center; /* Aligning the text to center */
  /* grid-area: text;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <p class="text">TEXT 2</p>
      <div class="image"></div>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner --></code>```

Body:
I am very new to CSS Grid and am trying to create a 2 X 2 grid. I am able to create the four image divs ( 2 on each row and 2 on each column) but I want the text to appear underneath each one. I have tried to use the grid-template-areas property but all the text just appears under one div all overlapped.

Any help would be appreciated, please.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-template-areas: "image image " "text text";
}

.text {
  grid-area: text;
}

TEXT 1

        TEXT 2

TEXT 3

TEXT 4

Body:
I removed the grid-area configuration from CSS code. Also, I have rearranged the sequence of your image and text HTML code. I hope this is what you expected.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
  /*grid-area: image;*/
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  /* grid-template-areas: "image image" "text text"; */
}

.text {
  text-align: center; /* Aligning the text to center */
  /* grid-area: text;*/
}

<div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <p class="text">TEXT 2</p>
      <div class="image"></div>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner -->


问:
Pandas - Adjust stock prices to stock splits
I have a DataFrame, with prices data and stock splits data.
I want to put all the prices on the same page, so for example if we had a stock split of 0.11111 (1/9),
from now on all the stock prices would be multiplied by 9.

So for example if this is my initial dataframe:

```<code>df=         Price  Stock_Splits
         0   100       0
         1   99        0
         2   10        0.1111111
         3   8         0
         4   8.5       0
         5   4         0.5
</code>```

The "Price" column will become:

```<code> df=         Price  Stock_Splits
         0   100       0
         1   99        0
         2   90        0.1111111
         3   72         0
         4   76.5       0
         5   72         0.5
</code>```

Body:
I have a DataFrame, with prices data and stock splits data.
I want to put all the prices on the same page, so for example if we had a stock split of 0.11111 (1/9),
from now on all the stock prices would be multiplied by 9.

So for example if this is my initial dataframe:

df=         Price  Stock_Splits
         0   100       0
         1   99        0
         2   10        0.1111111
         3   8         0
         4   8.5       0
         5   4         0.5

The "Price" column will become:

 df=         Price  Stock_Splits
         0   100       0
         1   99        0
         2   90        0.1111111
         3   72         0
         4   76.5       0
         5   72         0.5

Body:
Here is one example:

df['New_Price'] = (1 / df.Stock_Splits).replace(np.inf, 1).cumprod() * df.Price

   Price  Stock_Splits   New_Price
0  100.0      0.000000  100.000000
1   99.0      0.000000   99.000000
2   10.0      0.111111   90.000009
3    8.0      0.000000   72.000007
4    8.5      0.000000   76.500008
5    4.0      0.500000   72.000007


问:
How to POST User Credential to external domain?
I'm doing web programming and have some trouble in implementing log in to external domain.

What I'm building is a web application that helps a user to log in to multiple domain from my site (mysite.com).
This is how my web application works.

My site(mysite.com) contains users's credential (ID and password) of other domains

When user logs in to my site(mysite.com), user's credentials are given from server

By clicking on the icons of the domain (ex. thenounproject.com), domain is open on a new tab with users logged in

To implement this, I investigated and checked many options, but I still gets error.

Posting the credential form to external domain

<form method="POST" action="https://thenounproject.com/accounts/login/" target="_blank">
   <input type="text" name="login" required>
   <input type="password" name="password" required>
   <button type="submit">Login</button>
</form>```
</div>
</div>
</li>
</ol>

<p>The url(https://thenounproject.com/accounts/login/) is the login page of the domain(https://thenounproject.com/), and the name of the input (login / password) is same as the name of parameters that url POSTS to its own domain server. </p>

<p>But I got HTTP 403 Error, so it didn't work out.</p>

<ol start="2">
<li>Embedding credential into url (HTTP GET)</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="window.open('https://username:password@thenounproject.com/accounts/login/')"></code>```

But above code also doesn't work, it just opens the url (https://thenounproject.com/accounts/login/) and log in doesn't work.

Would there be any way to implement this?

答:
Doing a quick look at this for the noun project, they're using a CSRF token during log in.  These are designed to prevent you from doing exactly what you've described.  If you don't know what these are and why they're important, it's important you read up on them for your project before you continue

https://owasp.org/www-community/attacks/csrf

To make this work as described you would need something which can manipulate the browser's cookie store (like develop a custom browser extension).  You first need to establish a session to get the token (a GET to the login page should render this).  To work as described, you then need to have it added to the cookies in the browser for noun project's domain and this is actively prevented by a browser due to the security risk it introduces.

Body:
I'm doing web programming and have some trouble in implementing log in to external domain.

What I'm building is a web application that helps a user to log in to multiple domain from my site (mysite.com).
This is how my web application works.

My site(mysite.com) contains users's credential (ID and password) of other domains

When user logs in to my site(mysite.com), user's credentials are given from server

By clicking on the icons of the domain (ex. thenounproject.com), domain is open on a new tab with users logged in

To implement this, I investigated and checked many options, but I still gets error.

Posting the credential form to external domain

<form method="POST" action="https://thenounproject.com/accounts/login/" target="_blank">
   <input type="text" name="login" required>
   <input type="password" name="password" required>
   <button type="submit">Login</button>
</form>

The url(https://thenounproject.com/accounts/login/) is the login page of the domain(https://thenounproject.com/), and the name of the input (login / password) is same as the name of parameters that url POSTS to its own domain server.

But I got HTTP 403 Error, so it didn't work out.

Embedding credential into url (HTTP GET)

<button type="button" onclick="window.open('https://username:password@thenounproject.com/accounts/login/')">

But above code also doesn't work, it just opens the url (https://thenounproject.com/accounts/login/) and log in doesn't work.

Would there be any way to implement this?


问:
Proper way to create JSON data with PHP/MySQL
Updated based on answers below:

Based on the answers below, I now have the following PHP script:

```<code>header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    header('Content-type:application/json');

    $the_data['rss']['channels']['title'] = $title;
    $the_data['rss']['channels']['link'] = $link;
    $the_data['rss']['channels']['description'] = $description;

    while($row = mysql_fetch_array($result))
    {
        extract($row);

        $the_data['rss']['channels']['items']['title'] = $item_title;
        $the_data['rss']['channels']['items']['link'] = "$item_link;
        $the_data['rss']['channels']['items']['date'] = $item_date;
        $the_data['rss']['channels']['items']['description'] = $item_description;
    }

    mysql_close($connection);

    return json_encode($the_data);
}
</code>```

Which returns the following:

```<code>{
    "rss":
    {
        "channels":
        {
            "title":"title goes here",
            "link":"link goes here",
            "description":"description goes here",
            "items":
            {
                "title":"'title goes here",
                "link":"link goes here",
                "date":"date goes here",
                "description":"description goes here"
            }
        }
    }
}
</code>```

It should be returning many items based on the number of rows returned from the database, why am I only getting 1 items?

答:
Yes it should be fairly simple, something along the lines of

```<code>$the_data['rss']['channels']['title'] = $title;
$the_data['rss']['channels']['link'] = $link;
$the_data['rss']['channels']['description'] = $desc;
</code>```

and then inside your while loop you can have,

```<code>$the_data['rss']['channels']['items'][] = $row;
</code>```

and finally encode the array,

```<code>json_encode($the_data);
</code>```

Body:
Updated based on answers below:

Based on the answers below, I now have the following PHP script:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    header('Content-type:application/json');

    $the_data['rss']['channels']['title'] = $title;
    $the_data['rss']['channels']['link'] = $link;
    $the_data['rss']['channels']['description'] = $description;

    while($row = mysql_fetch_array($result))
    {
        extract($row);

        $the_data['rss']['channels']['items']['title'] = $item_title;
        $the_data['rss']['channels']['items']['link'] = "$item_link;
        $the_data['rss']['channels']['items']['date'] = $item_date;
        $the_data['rss']['channels']['items']['description'] = $item_description;
    }

    mysql_close($connection);

    return json_encode($the_data);
}

Which returns the following:

{
    "rss":
    {
        "channels":
        {
            "title":"title goes here",
            "link":"link goes here",
            "description":"description goes here",
            "items":
            {
                "title":"'title goes here",
                "link":"link goes here",
                "date":"date goes here",
                "description":"description goes here"
            }
        }
    }
}

It should be returning many items based on the number of rows returned from the database, why am I only getting 1 items?

Body:
Yes it should be fairly simple, something along the lines of

$the_data['rss']['channels']['title'] = $title;
$the_data['rss']['channels']['link'] = $link;
$the_data['rss']['channels']['description'] = $desc;

and then inside your while loop you can have,

$the_data['rss']['channels']['items'][] = $row;

and finally encode the array,

json_encode($the_data);


问:
Oracle sql combination
I have table with this result (just for example, actually it has more records):

```<code>31.3.2020   A  1
30.4.2020   A  2
31.3.2020   B  1
30.4.2020   C  3
</code>```

Is possible to add there empty missing values by sql?
In this case:

```<code>30.4.2020   B  0
31.3.2020   C  0
</code>```

Thanks

答:
You can use a cross join to generate the rows and then left join to bring in the existing values:

```<code>select  c1.col1, c2.col2, coalesce(col3, 0) as col3
from (select distinct col1 from t) c1 cross join
     (select distinct col2 from t) c2 left join
     t
     on t.col1 = c1.col1 and t.col2 = c2.col2;
</code>```

This returns all rows (including those with existing values).  You can add where t.col1 is null to get only the additional rows.

Title: Oracle sql combination

Body:
I have table with this result (just for example, actually it has more records):

31.3.2020   A  1
30.4.2020   A  2
31.3.2020   B  1
30.4.2020   C  3

Is possible to add there empty missing values by sql?
In this case:

30.4.2020   B  0
31.3.2020   C  0

Thanks

Body:
You can use a cross join to generate the rows and then left join to bring in the existing values:

select  c1.col1, c2.col2, coalesce(col3, 0) as col3
from (select distinct col1 from t) c1 cross join
     (select distinct col2 from t) c2 left join
     t
     on t.col1 = c1.col1 and t.col2 = c2.col2;

This returns all rows (including those with existing values).  You can add where t.col1 is null to get only the additional rows.


问:
Convert decimal to string
While converting decimal value 0.00005 to string the code converts it to 5E-05.
The value 0.00005 is from a DataTable row.
How do I restrict converting the same to keep it 0.00005 instead of 5E-05? </p>

答:
you can do like this.</p>

```<code>((decimal)(0.00005 )).ToString()
</code>```

Title: Convert decimal to string

Body:
you can do like this.

((decimal)(0.00005 )).ToString()


问:
Center a text inside an spinning element
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slide-loader">
    <div class="loader-text">Loading...</div>
  </div></code>```

答:
The spinner and text can be siblings and you can center both relative to the parent:

.slide-loader {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100px;
  height: 100px;
}

.spinner {
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  box-sizing: border-box;
  position: absolute;
  /*Center spinner with these 4 lines*/
  top: 50%;
  left: 50%;
  margin-left: -50px;
  margin-top: -50px;
}

.loader-text {
  position: absolute;
  /*Center text with these 3 lines*/
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slide-loader">
  <div class="spinner"></div>
  <div class="loader-text">Loading...</div>
</div></code>```

Body:
I have a simple loader animation and I want to add a loading text inside the circle.

As I'm spinning the .slide-loader and my text is inside it I've tried to exclude the .loader-text but it still spins?! how can I fix the loader-text inside the circle?

Here is the code:

.slide-loader:not(.loader-text) {
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;

}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

Loading...

Body:
The spinner and text can be siblings and you can center both relative to the parent:

.slide-loader {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100px;
  height: 100px;
}

.spinner {
  width: 100px;
  height: 100px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  border: 6px solid #f3f3f3;
  border-radius: 50%;
  border-top: 6px solid #3498db;
  box-sizing: border-box;
  position: absolute;
  /*Center spinner with these 4 lines*/
  top: 50%;
  left: 50%;
  margin-left: -50px;
  margin-top: -50px;
}

.loader-text {
  position: absolute;
  /*Center text with these 3 lines*/
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<div class="slide-loader">
  <div class="spinner"></div>
  <div class="loader-text">Loading...</div>
</div>


问:
Vue.js - Child components are re-rendered while updating their position
I'm new to Vue.js and i'm using it alongside with Vue-Draggable in order to re-arrange the position of stand-alone widgets (components) inside the DOM.

I also want to be able to rearrange this position dynamically via an Ajax response containing the order.

The problem that i have with my current implementation is that when i'm re-arranging, the components are re-rendered. I don't want that.

Any ideas would be helpful.

```<code><template>
  <draggable tag="div"
             class="container-fluid"
             @start="drag=true"
             @end="drag=false"
             handle=".v-drag-handle"
             v-bind="dragOptions"
             v-model="widgetList"
  >
    <transition-group type="transition">
      <component v-for="(widget, key) in widgetList"
                 :key="key"
                 :is="widget.widget">
      </component>
    </transition-group>
  </draggable>
</template>

 const widgets = [
    Component1,
    Component2,
    Component3,
    Component4,
    Component5
  ];

  export default {
    name: 'Stack overflow',

    data() {
      return {
        widgetList: [],
        drag: false,
        config: this.getHttpConfig(),
      };
    },

    computed: {
      dragOptions() {
        return {
          animation: 800,
          disabled: false,
          ghostClass: "v-ghost"
        };
      }
    },
    created() {
      this.getWidgetOrder();
    },
    watch: {
      widgetList(val, oldVal) {
        if (oldVal) {
          this.setWidgetOrder(this.widgetList);
        }
      }
    },
    methods: {
      sort() {
        this.widgetList = widgets.map((widget, index) => {
          return { widget: widgets[index], order: index + 1 };
        });
      },
      getWidgetOrder() {
        this.prepareFormData('get');

        this.$http(this.config)
          .then(response => {
            //todo handle response
            this.sort();
          })
          .catch(response => {
            throw new Error('Could not get widget order.');
          });
      }
    },
    components: {
      Component1,
      Component2,
      Component3,
      Component4,
      Component5
    }
}
</code>```

For time saving i have removed all non-related methods and i kept only the ones that are used while the problem is occurs.
 I believe that the problem is happening on the v-model, when the widgetList is updated i'm getting this issue.

答:
The problem here occurs because the key in the loop is changing, and Vue automatically re-creates the component.

The solution was to use the component's name as a key. :key="widget.name"

Body:
I'm new to Vue.js and i'm using it alongside with Vue-Draggable in order to re-arrange the position of stand-alone widgets (components) inside the DOM.

I also want to be able to rearrange this position dynamically via an Ajax response containing the order.

The problem that i have with my current implementation is that when i'm re-arranging, the components are re-rendered. I don't want that.

Any ideas would be helpful.

<template>
  <draggable tag="div"
             class="container-fluid"
             @start="drag=true"
             @end="drag=false"
             handle=".v-drag-handle"
             v-bind="dragOptions"
             v-model="widgetList"
  >
    <transition-group type="transition">
      <component v-for="(widget, key) in widgetList"
                 :key="key"
                 :is="widget.widget">
      </component>
    </transition-group>
  </draggable>
</template>

 const widgets = [
    Component1,
    Component2,
    Component3,
    Component4,
    Component5
  ];

  export default {
    name: 'Stack overflow',

    data() {
      return {
        widgetList: [],
        drag: false,
        config: this.getHttpConfig(),
      };
    },

    computed: {
      dragOptions() {
        return {
          animation: 800,
          disabled: false,
          ghostClass: "v-ghost"
        };
      }
    },
    created() {
      this.getWidgetOrder();
    },
    watch: {
      widgetList(val, oldVal) {
        if (oldVal) {
          this.setWidgetOrder(this.widgetList);
        }
      }
    },
    methods: {
      sort() {
        this.widgetList = widgets.map((widget, index) => {
          return { widget: widgets[index], order: index + 1 };
        });
      },
      getWidgetOrder() {
        this.prepareFormData('get');

        this.$http(this.config)
          .then(response => {
            //todo handle response
            this.sort();
          })
          .catch(response => {
            throw new Error('Could not get widget order.');
          });
      }
    },
    components: {
      Component1,
      Component2,
      Component3,
      Component4,
      Component5
    }
}

For time saving i have removed all non-related methods and i kept only the ones that are used while the problem is occurs.
 I believe that the problem is happening on the v-model, when the widgetList is updated i'm getting this issue.


问:
what is parse error: naked expression at top level?
I was trying to get the length of each element, given a nested list; and I also I want to get rid of the repeated length.

For example, a nested list [[1],[1,2],[4..5]] should give me [1,2].

I can do it in the interactive by nub (map  length  [[1],[1,2],[4..5]]). But if I write a file with the following code:

```<code>Import Data.List
getLen :: [[a]] ->[Int]
getLen xs = nub (map length xs)
</code>```

I got the error saying:

"Parse error: naked expression at top level"

What does this error mean and how can I fix this?

答:
In the parser, Import Data.List looks like an application of the data constructor Import with the data constructor Data.List as its argument.

Since this error occurred during parsing, the compiler has not yet figured out that neither of the data constructors Import or Data.List actually exist, but it does know that an expression like this is not allowed at the top level.

Of course, in this case it was just a typo as @augustss pointed out.

Body:
I was trying to get the length of each element, given a nested list; and I also I want to get rid of the repeated length.

For example, a nested list [[1],[1,2],[4..5]] should give me [1,2].

I can do it in the interactive by nub (map  length  [[1],[1,2],[4..5]]). But if I write a file with the following code:

Import Data.List
getLen :: [[a]] ->[Int]
getLen xs = nub (map length xs)

I got the error saying:

"Parse error: naked expression at top level"

What does this error mean and how can I fix this?