问:
how to change hibernate connection at runtime in java?
i found this solution but its not working, im using netbeans

my hibernate.cfg.xml:

```<code><hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url"></property>
        <property name="hibernate.connection.username"></property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping resource="entity/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
</code>```

my java code:

```<code>Object server=txtServer.getText();
Object database = txtDatabase.getText();
Object port = txtPort.getText();
String serverUsername = txtSUsername.getText();
String serverPassword = new String(txtSPassword.getPassword());
String url = "jdbc:mysql://" + server + ":" + port + "/" + database;
Configuration conf = new Configuration();
conf.configure().setProperty("hibernate.connection.url", url);
conf.setProperty("hibernate.connection.username", serverUsername);
conf.setProperty("hibernate.connection.password", serverPassword);
SessionFactory sf = conf.buildSessionFactory();
</code>```

error message:

```<code>WARNING: Could not obtain connection metadata
java.sql.SQLException: No suitable driver found for
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at util.NewHibernateUtil.<clinit>(NewHibernateUtil.java:23)
at services.service_connection.countRow(service_connection.java:20)
at gui.mainFrame.action(mainFrame.java:241)
at gui.mainFrame.btnOkActionPerformed(mainFrame.java:190)
at gui.mainFrame.access$100(mainFrame.java:25)
at gui.mainFrame$2.actionPerformed(mainFrame.java:78)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    WARNING: SQL Error: 0, SQLState: 08001
    SEVERE: No suitable driver found for
    org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
at $Proxy0.beginTransaction(Unknown Source)
at services.service_connection.countRow(service_connection.java:21)
at gui.mainFrame.action(mainFrame.java:241)
at gui.mainFrame.btnOkActionPerformed(mainFrame.java:190)
at gui.mainFrame.access$100(mainFrame.java:25)
at gui.mainFrame$2.actionPerformed(mainFrame.java:78)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    Caused by: java.sql.SQLException: No suitable driver found for
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
... 51 more
</code>```

my mysql-connector-java-5.1.15-bin.jar is in lib folder.

what fix is necessary?

答:
I use NHibernate which is a C# port of Hibernate.

I recently developed an application that had user configurable database connection, so the HIbernate config had to be able to be loaded dynamically. Pretty much that same as what you are trying to do.

The way I made this work was to save the new config to an XML file, then reload the session factory:

save new config to a XML pointed to by configFilePath

Close the current session

re-initialise a new session with saved config file - sessionFactory = new Configuration().Configure(configFilePath).BuildSessionFactory();

Hope this helps

Body:
i found this solution but its not working, im using netbeans

my hibernate.cfg.xml:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url"></property>
        <property name="hibernate.connection.username"></property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping resource="entity/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

my java code:

Object server=txtServer.getText();
Object database = txtDatabase.getText();
Object port = txtPort.getText();
String serverUsername = txtSUsername.getText();
String serverPassword = new String(txtSPassword.getPassword());
String url = "jdbc:mysql://" + server + ":" + port + "/" + database;
Configuration conf = new Configuration();
conf.configure().setProperty("hibernate.connection.url", url);
conf.setProperty("hibernate.connection.username", serverUsername);
conf.setProperty("hibernate.connection.password", serverPassword);
SessionFactory sf = conf.buildSessionFactory();

error message:

WARNING: Could not obtain connection metadata
java.sql.SQLException: No suitable driver found for
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at util.NewHibernateUtil.<clinit>(NewHibernateUtil.java:23)
at services.service_connection.countRow(service_connection.java:20)
at gui.mainFrame.action(mainFrame.java:241)
at gui.mainFrame.btnOkActionPerformed(mainFrame.java:190)
at gui.mainFrame.access$100(mainFrame.java:25)
at gui.mainFrame$2.actionPerformed(mainFrame.java:78)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    WARNING: SQL Error: 0, SQLState: 08001
    SEVERE: No suitable driver found for
    org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
at $Proxy0.beginTransaction(Unknown Source)
at services.service_connection.countRow(service_connection.java:21)
at gui.mainFrame.action(mainFrame.java:241)
at gui.mainFrame.btnOkActionPerformed(mainFrame.java:190)
at gui.mainFrame.access$100(mainFrame.java:25)
at gui.mainFrame$2.actionPerformed(mainFrame.java:78)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    Caused by: java.sql.SQLException: No suitable driver found for
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
... 51 more

my mysql-connector-java-5.1.15-bin.jar is in lib folder.

what fix is necessary?


来源: stackexchange

问:
Lookup in Informatica PowerCenter
Why do we use Lookup Transformation in Fact Table construction in Informatica PowerCenter? And what exactly is the difference between Lookup and Joiner Transformation ?</p>

答:
Below are the differences in lookup and joiner transformations in informatica:
1) Joiner supports only = operator lookup supports<=,>=,=,!= operators
2)Joiner doesn't have provision of caches. but different caches(like persistent, dynamic) are possible in Lookup transformation which improves performance
3) You can write lookup override in Lookup transformation, however joiner doesn't have facility to write lookup override.
4) Joiner supports inner join, left,right,full outer join however lookup supports left outer join
Hope this helps!</p>

ContentLicense: CC BY-SA 3.0

Title: Lookup in Informatica PowerCenter

ContentLicense: CC BY-SA 4.0


问:
Is there a way to position a html element absolute but still place it in the center of the page?

 .container{
   position: absolute;
   margin: 0 auto;// this doesn't position it in the centre anymore.
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
   this is a container
</div></code>```

"This is supposed to be placed in the center... but when i positioned it as absolute, it went back to the top of the webpage. Is there anyway to bypass this."

答:
This will do it:

 .container{
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
 }
```

Body:
 .container{
   position: absolute;
   margin: 0 auto;// this doesn't position it in the centre anymore.
 }

   this is a container

"This is supposed to be placed in the center... but when i positioned it as absolute, it went back to the top of the webpage. Is there anyway to bypass this."


问:
Creating object literal fails in observable notebook
I'm trying to run this simple code snippet from O'Reilly's "Learning React" book in an Observable notebook (https://observablehq.com/).

It works if I run it in the Chrome console (I can define the object and then run tahoe.print()), but if I try to run it in Observable I get SyntaxError: Unexpected Token when running the cell.

Is there something strange about Observable that prevents me from creating object literals like this?

```<code>tahoe = {
  resorts: ["Kirkwood","Squaw","Alpine"],
  print: function(delay=1000) {
    setTimeout(() => {
      console.log(this.resorts.join(", "))
    }, delay)
  }
}
</code>```

Here's the notebook with the code: https://observablehq.com/@jritch/simple-snippet-breaks-in-observable

答:
Blex pointed out that to get this to work you need to wrap the object in parentheses:

```<code>tahoe = ({
  resorts: ["Kirkwood","Squaw","Alpine"],
  print: function(delay=1000) {
    setTimeout(() => {
      console.log(this.resorts.join(", "))
    }, delay)
  }
})
</code>```

Working snippet.

For a fuller explanation of why this is, see this blogpost that outlines the differences between Observable and vanilla javascript:

Statements need curly braces, and return (or yield). A cell body can be a simple expression, such as a number or string literal, or a
  function call. But sometimes you want statements, such as for loops.
  For that you’ll need curly braces, and a return statement to give the
  cell a value. Think of a cell as a function, except the function has
  no arguments. For the same reason, you’ll need to wrap object literals
  in parentheses, or use a block statement with a return.

There's also a (somewhat difficult to see) magic wand widget that comes up beside the play button icon for the cell, that will automatically fix this issue if you click it:

Body:
I'm trying to run this simple code snippet from O'Reilly's "Learning React" book in an Observable notebook (https://observablehq.com/).

It works if I run it in the Chrome console (I can define the object and then run tahoe.print()), but if I try to run it in Observable I get SyntaxError: Unexpected Token when running the cell.

Is there something strange about Observable that prevents me from creating object literals like this?

tahoe = {
  resorts: ["Kirkwood","Squaw","Alpine"],
  print: function(delay=1000) {
    setTimeout(() => {
      console.log(this.resorts.join(", "))
    }, delay)
  }
}

Here's the notebook with the code: https://observablehq.com/@jritch/simple-snippet-breaks-in-observable

Body:
Blex pointed out that to get this to work you need to wrap the object in parentheses:

tahoe = ({
  resorts: ["Kirkwood","Squaw","Alpine"],
  print: function(delay=1000) {
    setTimeout(() => {
      console.log(this.resorts.join(", "))
    }, delay)
  }
})

Working snippet.

For a fuller explanation of why this is, see this blogpost that outlines the differences between Observable and vanilla javascript:

Statements need curly braces, and return (or yield). A cell body can be a simple expression, such as a number or string literal, or a
  function call. But sometimes you want statements, such as for loops.
  For that you’ll need curly braces, and a return statement to give the
  cell a value. Think of a cell as a function, except the function has
  no arguments. For the same reason, you’ll need to wrap object literals
  in parentheses, or use a block statement with a return.

There's also a (somewhat difficult to see) magic wand widget that comes up beside the play button icon for the cell, that will automatically fix this issue if you click it:


问:
RecyclerView is cutting off the last item
I have a fragment with a toolbar and a recyclerView inside it.

I am populating the recyclerView with dummy data and then try to show them. For some reason, the last element of the recyclerView is getting cut-off.

This is the XML of the fragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/placeholder_rect_header"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

The items at the list are really simple ones:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/background_1"
    android:orientation="horizontal"
    android:padding="@dimen/space_for_a_bit_of_air">

    <ImageView
        android:id="@+id/album_cover"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_vertical"
        android:scaleType="fitXY"
        android:src="@drawable/placeholder_album_cover"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/space_for_distinguishing_stuff"
        android:orientation="vertical">

        <TextView
            android:id="@+id/album_title"
            style="@style/titleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_c"/>

        <TextView
            android:id="@+id/album_year"
            style="@style/subtitleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_a"/>

    </LinearLayout>

</LinearLayout>
</code>```

I am now at the end of the list, but the last element still looks cut-off.

I am using the latest version as of 2015-09-23 of google libraries, 23.0.1, (i.e. com.android.support:recyclerview-v7:23.0.1), and the following configuration at the build.gradle:

```<code>compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
   minSdkVersion 14
   targetSdkVersion 23
   versionCode 1
   versionName "1.0"

   multiDexEnabled true// Enabling multidex support
 }
</code>```

Any help would be greatly appreciated since I am going nuts with this problem :(

SOLUTION

Ok, after cleaning the code to the bare essentials and removing complexity, I found the problem: it was a combination of wrong flags and missing or extra attributes. The following works fine for both Android 4.x and 5.x:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:collapsedTitleTextAppearance="@style/Title.collapsed"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleTextAppearance="@style/Title.Expanded"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/artistic_4"
                app:layout_collapseMode="parallax"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/height_of_app_bar"
                android:background="@drawable/gradient"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        style="@style/genericRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:listitem="@layout/item_discography_album"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

In a nutshell, android:fitsSystemWindows="true" should only be at the coordinatorLayout, AppBarLayout and theCollapsingToolbarLayout (which are the ones that we want to be adjusted based on the screen on Android 5.x), the app:layout_scrollFlags should be set to "scroll|enterAlways|enterAlwaysCollapsed" and the toolbar should have as height, the height of the actionBar. Finally, it's better to keep the RecyclerView as clean as possible so you can control the layout spacing at each line item.

答:
Set layout_height="match_parent" then add layout_marginBottom="?attr/actionBarSize" or
50dp this will compensate for the ToolBar forcing the RecyclerView down cutting off the last view.

Additionally set nestedScrollingEnabled="false" if you have a hideOnScroll enabled toolbar.

```<code><androidx.recyclerview.widget.RecyclerView
     android:id="@+id/my_recycler_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_marginBottom="?attr/actionBarSize"
     android:nestedScrollingEnabled="false"  />
</code>```

Body:
I have a fragment with a toolbar and a recyclerView inside it.

I am populating the recyclerView with dummy data and then try to show them. For some reason, the last element of the recyclerView is getting cut-off.

This is the XML of the fragment:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/placeholder_rect_header"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

The items at the list are really simple ones:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/background_1"
    android:orientation="horizontal"
    android:padding="@dimen/space_for_a_bit_of_air">

    <ImageView
        android:id="@+id/album_cover"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_vertical"
        android:scaleType="fitXY"
        android:src="@drawable/placeholder_album_cover"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/space_for_distinguishing_stuff"
        android:orientation="vertical">

        <TextView
            android:id="@+id/album_title"
            style="@style/titleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_c"/>

        <TextView
            android:id="@+id/album_year"
            style="@style/subtitleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sample_text_a"/>

    </LinearLayout>

</LinearLayout>

I am now at the end of the list, but the last element still looks cut-off.

I am using the latest version as of 2015-09-23 of google libraries, 23.0.1, (i.e. com.android.support:recyclerview-v7:23.0.1), and the following configuration at the build.gradle:

compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
   minSdkVersion 14
   targetSdkVersion 23
   versionCode 1
   versionName "1.0"

   multiDexEnabled true// Enabling multidex support
 }

Any help would be greatly appreciated since I am going nuts with this problem :(

SOLUTION

Ok, after cleaning the code to the bare essentials and removing complexity, I found the problem: it was a combination of wrong flags and missing or extra attributes. The following works fine for both Android 4.x and 5.x:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_1"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/height_of_app_bar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:collapsedTitleTextAppearance="@style/Title.collapsed"
            app:contentScrim="@color/primary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleTextAppearance="@style/Title.Expanded"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/artistic_4"
                app:layout_collapseMode="parallax"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/height_of_app_bar"
                android:background="@drawable/gradient"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/simpleList"
        style="@style/genericRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:listitem="@layout/item_discography_album"/>

</android.support.design.widget.CoordinatorLayout>

In a nutshell, android:fitsSystemWindows="true" should only be at the coordinatorLayout, AppBarLayout and theCollapsingToolbarLayout (which are the ones that we want to be adjusted based on the screen on Android 5.x), the app:layout_scrollFlags should be set to "scroll|enterAlways|enterAlwaysCollapsed" and the toolbar should have as height, the height of the actionBar. Finally, it's better to keep the RecyclerView as clean as possible so you can control the layout spacing at each line item.

Body:
Set layout_height="match_parent" then add layout_marginBottom="?attr/actionBarSize" or
50dp this will compensate for the ToolBar forcing the RecyclerView down cutting off the last view.

Additionally set nestedScrollingEnabled="false" if you have a hideOnScroll enabled toolbar.

<androidx.recyclerview.widget.RecyclerView
     android:id="@+id/my_recycler_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_marginBottom="?attr/actionBarSize"
     android:nestedScrollingEnabled="false"  />


问:
How to decrease execution time limit for a list-traverser
I'm working on a Python problem on Code Signal and I'm trying to see if a given list is a strictly increasing sequence when only one element is removed from it.  So I've built code that, in a for-loop, removes element i from the list and checks if it is an increasing sequence and then replaces that element at that exact index and starts over.  This is the code:

```<code>def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        element = sequence[i]
        del sequence[i]

        if all(i < j for i, j in zip(sequence, sequence[1:])):
            return True
        sequence.insert(i, element)

    return False
</code>```

The code works well but it causes an error with the execution time.  Is there any way I can improve this existing code so it runs faster?

答:
It would be quicker to run through the list, comparing each value to the previous to ensure it's strictly increasing. Allow this to not be true for one number in the list and skip this number. Unfortunately it's not quite that simple, as we can see below:

Won't work (eg. [1,4,2,3])

def almostIncreasingSequence(sequence):
    lastValue = sequence[0]
    removed_value = False
    for i in range(1,len(sequence)):
        if sequence[i] <= lastValue:
            if removed_value:
                return False
            else:
                removed_value = True
        else:
            lastValue = sequence[i]
    return True
```

<p>Instead, we need to cover the two possibilities if we encounter a non-increase: remove the current number (eg. [1,2,1,3]) or remove the previous (eg. [1,2,8,4]). We also have some edge cases for removing the first or last number in the list.</p>

<p><strong>Final (not so pretty) solution</strong></p>

<pre class="lang-py prettyprint-override"><code>def almostIncreasingSequence(sequence):
    lastValue = sequence[0]
    skipped_value = False
    for i in range(1,len(sequence)):
        if sequence[i] <= lastValue:
            if i+1 == len(sequence):
                return not skipped_value # last number is not decreasing, skip if we can
            if skipped_value:
                # if we've already skipped a number - won't work
                return False
            elif sequence[i+1] > sequence[i-1]:
                # skipping the current number will fix it
                skipped_value = True
                lastValue = sequence[i-1]
            else:
                # try and skip the previous number
                skipped_value = True
                if i == 1 or sequence[i] > sequence[i-2]:
                    # can skip the previous number and it'll work
                    lastValue = sequence[i]
                else:
                    # we have no chance
                    return False
        else:
            lastValue = sequence[i]
    return True
</code>```

Body:
I'm working on a Python problem on Code Signal and I'm trying to see if a given list is a strictly increasing sequence when only one element is removed from it.  So I've built code that, in a for-loop, removes element i from the list and checks if it is an increasing sequence and then replaces that element at that exact index and starts over.  This is the code:

def almostIncreasingSequence(sequence):

    for i in range(len(sequence)):
        element = sequence[i]
        del sequence[i]

        if all(i < j for i, j in zip(sequence, sequence[1:])):
            return True
        sequence.insert(i, element)

    return False

The code works well but it causes an error with the execution time.  Is there any way I can improve this existing code so it runs faster?

Body:
It would be quicker to run through the list, comparing each value to the previous to ensure it's strictly increasing. Allow this to not be true for one number in the list and skip this number. Unfortunately it's not quite that simple, as we can see below:

Won't work (eg. [1,4,2,3])

def almostIncreasingSequence(sequence):
    lastValue = sequence[0]
    removed_value = False
    for i in range(1,len(sequence)):
        if sequence[i] <= lastValue:
            if removed_value:
                return False
            else:
                removed_value = True
        else:
            lastValue = sequence[i]
    return True

Instead, we need to cover the two possibilities if we encounter a non-increase: remove the current number (eg. [1,2,1,3]) or remove the previous (eg. [1,2,8,4]). We also have some edge cases for removing the first or last number in the list.

Final (not so pretty) solution

def almostIncreasingSequence(sequence):
    lastValue = sequence[0]
    skipped_value = False
    for i in range(1,len(sequence)):
        if sequence[i] <= lastValue:
            if i+1 == len(sequence):
                return not skipped_value # last number is not decreasing, skip if we can
            if skipped_value:
                # if we've already skipped a number - won't work
                return False
            elif sequence[i+1] > sequence[i-1]:
                # skipping the current number will fix it
                skipped_value = True
                lastValue = sequence[i-1]
            else:
                # try and skip the previous number
                skipped_value = True
                if i == 1 or sequence[i] > sequence[i-2]:
                    # can skip the previous number and it'll work
                    lastValue = sequence[i]
                else:
                    # we have no chance
                    return False
        else:
            lastValue = sequence[i]
    return True


问:
How to set current directory for ES6 dynamic import function
I have this directory tree:

```<code>project
  |
  -> dir1
      |
      -> dir2
          |
          -> module.mjs

     server.mjs
     utils.mjs
</code>```

My current working directory is:

```<code> project/
</code>```

Source code of server.mjs

```<code>async function main(){
    var module = await import("./dir1/dir2/module.mjs");
}

main();
</code>```

Source code of module.mjs

```<code>//this works!
import utils from "../../utils.mjs";

//this fails!
import utils from "./utils.mjs";
</code>```

It seems that the static import in the module.mjs consider the dot '.' as the directory of itself, not the current working directory.

How to set a current directory for dynamic import?
And the actual base question is: How to avoid the long '../../.......' of static imports in a dynamic module.

For example, I wish to have something like this in server.mjs:

```<code>var module = await import("./dir1/dir2/module.mjs",{cwd:"project/"});
</code>```

Or, in dynamic module, able to use:

```<code>import utils from './utils.mjs'
</code>```

instead of:

```<code>import utils from '../../long dot dot/utils.mjs'
</code>```

答:
It seems like there's no way to do static import in a dynamic imported module with the dot . refer to current working directory yet.

So, the work-around is still using the dotdot-slashslash...

I've submitted a new feature request to Node.js team here: https://github.com/nodejs/node/issues/31822

Body:
I have this directory tree:

project
  |
  -> dir1
      |
      -> dir2
          |
          -> module.mjs

     server.mjs
     utils.mjs

My current working directory is:

 project/

Source code of server.mjs

async function main(){
    var module = await import("./dir1/dir2/module.mjs");
}

main();

Source code of module.mjs

//this works!
import utils from "../../utils.mjs";

//this fails!
import utils from "./utils.mjs";

It seems that the static import in the module.mjs consider the dot '.' as the directory of itself, not the current working directory.

How to set a current directory for dynamic import?
And the actual base question is: How to avoid the long '../../.......' of static imports in a dynamic module.

For example, I wish to have something like this in server.mjs:

var module = await import("./dir1/dir2/module.mjs",{cwd:"project/"});

Or, in dynamic module, able to use:

import utils from './utils.mjs'

instead of:

import utils from '../../long dot dot/utils.mjs'


问:
Preg Replace - E Modifier
```<code>$strpost_a = preg_replace("/\[CallName]([^]]+)\[\/CallName\]/e", getInfo('\\1',"fullname"), $strpost_a);
</code>```

I always get this in return:

```<code>Parse error: syntax error, unexpected T_STRING in C:\wamp\www\-site\files\index\stream.php(88) : regexp code on line 1
Fatal error: preg_replace() [<a href='function.preg-replace'>function.preg-replace</a>]: Failed evaluating code: James -LastName Removed- in C:\wamp\www\-site-\files\index\stream.php on line 88
</code>```

答:
First, you need to properly escape your brackets:

```<code>"/\[CallName\]([^]]+)\[\/CallName\]/e"
</code>```

Second, when using the e modifier your replacement still needs to be a string. However it is a string that is evaluated as PHP code after backreferences are substituted. Try the following:

```<code>"getInfo('\\1', 'fullname')"
</code>```

Check out the docs for more detail on the e modifier

Title: Preg Replace - E Modifier

Body:
$strpost_a = preg_replace("/\[CallName]([^]]+)\[\/CallName\]/e", getInfo('\\1',"fullname"), $strpost_a);

I always get this in return:

Parse error: syntax error, unexpected T_STRING in C:\wamp\www\-site\files\index\stream.php(88) : regexp code on line 1
Fatal error: preg_replace() [function.preg-replace]: Failed evaluating code: James -LastName Removed- in C:\wamp\www\-site-\files\index\stream.php on line 88

Body:
First, you need to properly escape your brackets:

"/\[CallName\]([^]]+)\[\/CallName\]/e"

Second, when using the e modifier your replacement still needs to be a string. However it is a string that is evaluated as PHP code after backreferences are substituted. Try the following:

"getInfo('\\1', 'fullname')"

Check out the docs for more detail on the e modifier


问:
Can a default user's password be set in SQL using PHP's password_hash?
My old PHP app has a default admin user and md5 encrypted password created by the SQL that creates the database: insert into users values ( 1, 'admin', MD5('changeMe'), 2 );

Is there a simple way to include a default user and encrypted password using PHP's passowrd_hash function on creating the tables? I ask because I understand that password_hash is a native PHP function and I assume it won't be understood in SQL.

答:
you can do something like this in php:

```<code>$hash = password_hash('changeMe');
//echo $hash;
</code>```

then use this hash in the Database.

Body:
you can do something like this in php:

$hash = password_hash('changeMe');
//echo $hash;

then use this hash in the Database.


问:
How to reduce each individual ingredient according to another seq of 'applied' ingredients in a recipe
So I have a soup that is compromised of a sequence of ingredient.
I need to determine what ingredients I still need to apply to the soup, based on a sequence of mixtures I have already added to the soup that I am making.

```<code>case class Ingredient(name: String)
case class Mixture(ingredient: Ingredient, amount: Int)

// ingredient required to make soup
val i1 = Ingredient("water")
val i2 = Ingredient("salt")
val i3 = Ingredient("sugar")

val soupRequirements = Seq(Mixture(i1, 100), Mixture(i2, 200), Mixture(i3, 50))

println(soup)

val addedIngrediants = Seq(Mixture(i1, 50), Mixture(i2, 200), Mixture(i3, 40))

def determineWhatsLeft(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] = ???
</code>```

Reference: https://scastie.scala-lang.org/X6PIG7zYQOGuZX7zcebgRQ

How exactly can I reduce each mixture by the correct amount in a functional way?

答:
First define way of reducing two Mixtures via infix operator

```<code>implicit class ReduceMixtures(a: Mixture) {
  def +(b: Mixture): Mixture =
    if (a.ingredient == b.ingredient) Mixture(a.ingredient, a.amount - b.amount)
    else a
}
</code>```

Note how if the ingredients do not match we return a unchanged. Now we can implement determineWhatsLeft using foldLeft

```<code>def determineWhatsLeft(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] = {
  addedIngredients.foldLeft(soupRequirements) { case (acc, next) => acc.map(_ + next) }
}
</code>```

Using foldLeft the order does not matter, however if the order of soupRequirements and addedIngredients was always mirrored then we could zip and map like so

```<code>def determineWhatsLeft(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] =
  (soupRequirements zip addedIngredients).map { case (a, b) => a + b }
</code>```

Semigroup seems to be the least powerful abstraction fitting the requirement

```<code>import cats.implicits._
import cats.Semigroup

implicit object mixtureSemigroup extends Semigroup[Mixture] {
  def combine(a: Mixture, b: Mixture): Mixture =
    if (a.ingredient == b.ingredient) Mixture(a.ingredient, a.amount - b.amount)
    else a
}

implicit object seqMixtureSemigroup extends Semigroup[Seq[Mixture]] {
  def combine(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] =
    addedIngredients.foldLeft(soupRequirements) { case (acc, next) =>
      acc.map(_ |+| next)
    }
}

soupRequirements |+| addedIngredients
</code>```

Body:
So I have a soup that is compromised of a sequence of ingredient.
I need to determine what ingredients I still need to apply to the soup, based on a sequence of mixtures I have already added to the soup that I am making.

case class Ingredient(name: String)
case class Mixture(ingredient: Ingredient, amount: Int)

// ingredient required to make soup
val i1 = Ingredient("water")
val i2 = Ingredient("salt")
val i3 = Ingredient("sugar")

val soupRequirements = Seq(Mixture(i1, 100), Mixture(i2, 200), Mixture(i3, 50))

println(soup)

val addedIngrediants = Seq(Mixture(i1, 50), Mixture(i2, 200), Mixture(i3, 40))

def determineWhatsLeft(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] = ???

Reference: https://scastie.scala-lang.org/X6PIG7zYQOGuZX7zcebgRQ

How exactly can I reduce each mixture by the correct amount in a functional way?

Body:
First define way of reducing two Mixtures via infix operator

implicit class ReduceMixtures(a: Mixture) {
  def +(b: Mixture): Mixture =
    if (a.ingredient == b.ingredient) Mixture(a.ingredient, a.amount - b.amount)
    else a
}

Note how if the ingredients do not match we return a unchanged. Now we can implement determineWhatsLeft using foldLeft

def determineWhatsLeft(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] = {
  addedIngredients.foldLeft(soupRequirements) { case (acc, next) => acc.map(_ + next) }
}

Using foldLeft the order does not matter, however if the order of soupRequirements and addedIngredients was always mirrored then we could zip and map like so

def determineWhatsLeft(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] =
  (soupRequirements zip addedIngredients).map { case (a, b) => a + b }

Semigroup seems to be the least powerful abstraction fitting the requirement

import cats.implicits._
import cats.Semigroup

implicit object mixtureSemigroup extends Semigroup[Mixture] {
  def combine(a: Mixture, b: Mixture): Mixture =
    if (a.ingredient == b.ingredient) Mixture(a.ingredient, a.amount - b.amount)
    else a
}

implicit object seqMixtureSemigroup extends Semigroup[Seq[Mixture]] {
  def combine(soupRequirements: Seq[Mixture], addedIncredients: Seq[Mixture]): Seq[Mixture] =
    addedIngredients.foldLeft(soupRequirements) { case (acc, next) =>
      acc.map(_ |+| next)
    }
}

soupRequirements |+| addedIngredients


问:
Node/ Angular CORS issue
so I am having this weird issue. I have an application with Node/Angular hosted on the server, working on the same port. But only on one page, there is a CORS error.

So far, I have added allowed CORS before the routes in the app.js.

CODE:

```<code>const apiRoutes = require("./routes/api");

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, Content-Length, X-Requested-With, cache-control"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET,POST,PATCH,DELETE,OPTIONS,PUT"
  );
  next();
})

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/uploads', express.static(path.join(__dirname, './uploads')));

app.use('/api', apiRoutes);

</code>```

I have also used the cors npm package and allowed it with that as well, but still no luck.

The request parameters of getting the same image from the same directory are attached.

Response param when the image is accessed on page 1

Response param when the same image is blocked CORS

Image for error

EDIT:

```<code>const cors = require('cors');
app.use(cors());
app.options('*', cors());
</code>```

I have also used this, but it doesn't work either.

Request from same origin is getting blocked,

Access to image at 'https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png' from origin 'https://pay2mate.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

答:
Based on your error;

Access to image at
  'https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png'
  from origin 'https://pay2mate.com' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

You may have confused the difference between your NodeJS API and the web server itself.

As your code shows the image you are requesting is being served by Apache (the web server) and not by your NodeJS API;

```<code>URL: https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png
server: Apache
accept-ranges: bytes
content-length: 5774
content-type: image/png
date: Mon, 17 Feb 2020 01:41:59 GMT
etag: "69c3450-168e-59cda4d2ef8f3"
last-modified: Fri, 24 Jan 2020 03:24:55 GMT
status: 200
</code>```

You will either need to direct all requests to your API in your .htaccess file regardless of whether the physical file exists and then stream the file through your API.

Or, you could update your .htaccess file to add this header for you which will then appear on file requests (if you want this wide open like your example);

```<code><IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
</code>```

You can read more about this here; https://enable-cors.org/server_apache.html

If this does not work. Please post more information about your hosting server configuration & the contents of your current .htaccess file

Title: Node/ Angular CORS issue

Body:
so I am having this weird issue. I have an application with Node/Angular hosted on the server, working on the same port. But only on one page, there is a CORS error.

So far, I have added allowed CORS before the routes in the app.js.

CODE:

const apiRoutes = require("./routes/api");

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, Content-Length, X-Requested-With, cache-control"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET,POST,PATCH,DELETE,OPTIONS,PUT"
  );
  next();
})

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/uploads', express.static(path.join(__dirname, './uploads')));

app.use('/api', apiRoutes);

I have also used the cors npm package and allowed it with that as well, but still no luck.

The request parameters of getting the same image from the same directory are attached.

Response param when the image is accessed on page 1

Response param when the same image is blocked CORS

Image for error

EDIT:

const cors = require('cors');
app.use(cors());
app.options('*', cors());

I have also used this, but it doesn't work either.

Request from same origin is getting blocked,

Access to image at 'https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png' from origin 'https://pay2mate.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Body:
Based on your error;

Access to image at
  'https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png'
  from origin 'https://pay2mate.com' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

You may have confused the difference between your NodeJS API and the web server itself.

As your code shows the image you are requesting is being served by Apache (the web server) and not by your NodeJS API;

URL: https://www.pay2mate.com/uploads/1579836295281-Affinity_Logo.png
server: Apache
accept-ranges: bytes
content-length: 5774
content-type: image/png
date: Mon, 17 Feb 2020 01:41:59 GMT
etag: "69c3450-168e-59cda4d2ef8f3"
last-modified: Fri, 24 Jan 2020 03:24:55 GMT
status: 200

You will either need to direct all requests to your API in your .htaccess file regardless of whether the physical file exists and then stream the file through your API.

Or, you could update your .htaccess file to add this header for you which will then appear on file requests (if you want this wide open like your example);

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

You can read more about this here; https://enable-cors.org/server_apache.html

If this does not work. Please post more information about your hosting server configuration & the contents of your current .htaccess file


问:
get variables substituted when I cat a file
Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

```<code>$ cat <<EOF
$HOME
EOF
/home/myself
</code>```

cat returns /home/myself because it is already expanded by the shell.

```<code>$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME
</code>```

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

My question is if this is possible somehow, otherwise I will have to write some dirty code.

EDIT: they are big xml files containing

```<code><checkbox active="$value">
</code>```

true or false

答:
This would be trivial to attempt in Python, and see if that works for you.  You could use the re.sub function to replace all occurrences of some pattern like "\$\w+" by calling a function which does the transformation (rather than a specific string to replace it with).  And for the replacement function you could use os.getenv(), which of course takes a variable name and returns its value.

Edit: Here's a complete Python script that does the above:

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

import fileinput
import os
import re

def transform(match):
    return os.getenv(match.group(1)) # replace the "capture" to omit $

for line in fileinput.input(): # reads from stdin or from a file in argv
    print re.sub('\$(\w+)', transform, line), # comma to omit newline
</code>```

Body:
Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

$ cat <<EOF
$HOME
EOF
/home/myself

cat returns /home/myself because it is already expanded by the shell.

$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

My question is if this is possible somehow, otherwise I will have to write some dirty code.

EDIT: they are big xml files containing

<checkbox active="$value">

true or false

Body:
This would be trivial to attempt in Python, and see if that works for you.  You could use the re.sub function to replace all occurrences of some pattern like "\$\w+" by calling a function which does the transformation (rather than a specific string to replace it with).  And for the replacement function you could use os.getenv(), which of course takes a variable name and returns its value.

Edit: Here's a complete Python script that does the above:

#!/usr/bin/python

import fileinput
import os
import re

def transform(match):
    return os.getenv(match.group(1)) # replace the "capture" to omit $

for line in fileinput.input(): # reads from stdin or from a file in argv
    print re.sub('\$(\w+)', transform, line), # comma to omit newline


问:
how to run two shell commands in different folders in docker-compose
I'm trying to dockerize my application. It consists of a .NET Core backend and an Angular frontend, set up like this:

root folder

docker-compose

Dockerfile

web subfolder (contains Angular frontend)

api subfolder (contains .NET Core backend)

I can successfully create a container using a docker-compose and Dockerfile. I can't figure out how to actually run the application in Docker. Normally when I want to run the application locally on my computer I do the 'dotnet run' command from the api folder using Powershell and then in another Powershell window I run the 'ng serve' command from the web folder. How would I run two shell commands from two different folders in either docker-compose or a Dockerfile?

I tried adding the two commands at the end of the Dockerfile like this:

```<code>RUN cd api && dotnet run api.csproj

RUN cd web && ng serve
</code>```

Docker runs the first line but never gets to the next line. I'm guessing I have to issue commands from the docker-compose but I don't know how to go about it.

UPDATE:
In response to splitting the application into two different containers, the two parts are dependent on each other. The backend has a symlink to the frontend. When the backend is initialized it checks to see if node is installed and the node_modules folder from the frontend exists, if it doesn't then an error occurs. In the docker container, I need to create the frontend first and install node then create the backend. I also figured to keep the file size down it made sense to keep everything in one container.

答:
You are using 'command1 && command2' which means run command2 if command1 exited with exit code 0, however command1 never exits.

In order to run 2 processes in one container you can follow this guide.

Note: A container in most cases is supposed to be one isolated process, as a result you should consider separating your application in two containers, one for the frontend and one for the backend.

Body:
I'm trying to dockerize my application. It consists of a .NET Core backend and an Angular frontend, set up like this:

root folder

docker-compose

Dockerfile

web subfolder (contains Angular frontend)

api subfolder (contains .NET Core backend)

I can successfully create a container using a docker-compose and Dockerfile. I can't figure out how to actually run the application in Docker. Normally when I want to run the application locally on my computer I do the 'dotnet run' command from the api folder using Powershell and then in another Powershell window I run the 'ng serve' command from the web folder. How would I run two shell commands from two different folders in either docker-compose or a Dockerfile?

I tried adding the two commands at the end of the Dockerfile like this:

RUN cd api && dotnet run api.csproj

RUN cd web && ng serve

Docker runs the first line but never gets to the next line. I'm guessing I have to issue commands from the docker-compose but I don't know how to go about it.

UPDATE:
In response to splitting the application into two different containers, the two parts are dependent on each other. The backend has a symlink to the frontend. When the backend is initialized it checks to see if node is installed and the node_modules folder from the frontend exists, if it doesn't then an error occurs. In the docker container, I need to create the frontend first and install node then create the backend. I also figured to keep the file size down it made sense to keep everything in one container.


问:
How to subtract quantity between two tables based on item types in Java Netbeans?
Hi I have two tabels PURCHASE and DELIVERY where by I want to show the remaining quantity in another table 'STOCK'.
Below is the output I got from my STOCK table  and the code I did, but the calculation is wrong.
Can anyone help me with this?

```<code>private void stock(){

        dbConection db = new dbConection();
        Connection con=db.getConnection();
            String sql = "Select delivery.pro_Name, delivery.pro_Code, (sum(purchase.pur_qty) - sum(delivery.Qty)) AS bal from  delivery, purchase where purchase.productCode = delivery.pro_Code GROUP BY delivery.pro_Code ";
            PreparedStatement pst = con.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            DefaultTableModel tm = (DefaultTableModel)stockTable.getModel();

            tm.setRowCount(0);
            while(rs.next()){

                Object o[]={rs.getString("pro_Code"), rs.getString("pro_Name"), rs.getString("bal")};
                tm.addRow(o);
            }

        }catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex);

        }
</code>```

答:
First of all, this is only a SQL problem, and Java is only for view the results.
The above code will be for MS SQL Server, as you did not provide the type of SQL Database.

A final stock is calculated starting from an initial stock.
So you will must have something like:

```<code>initial_stock + purchase_qty - delivery_qty  = final_stock (group by ProductId)
</code>```

Now, if you store your articles/products in your database as FIFO, that means you imply also the price in this formula, so group by implies also Fifo_Price . This could be also more complex SQL Select, based of related tables.

Supposing you don't need FIFO, but only a remaining quantity stock, the select syntax will be something like this:

-- Supposing initial stock is stored in Product Table
Select pr.ProductID, pr.InitialStock, Sum(IsNull(pc.Quantity,0)) AS QuantityIn,
    Sum(IsNull(dv.Quantity,0)) AS QuantityOut,
    pr.InitialStock + sum(IsNull(pc.Quantity,0) - IsNull(dv.Quantity,0)) AS FinalStock
From Products pr
Left Join Purchase pc on pr.ProductID = pc.ProductID
Left Join Delivery dv on pr.ProductID = dv.ProductID
Group By pr.ProductID, pr.InitialStock

-- if you want to see only products that are implied in purchase and delivery tables, you must Inner Join all tables
```

Edit: I have deleted the rest of answer, because was not relevant to question.

Edit 2: Please look at this picture. I have made a simple test showing what are results as I did and as you did:

Considering that initial stock is not null, I did not force a replacement with 0, but you can replace that too, so st.qty will be IsNull(st.Qty, 0) as InitialStock

Body:
Hi I have two tabels PURCHASE and DELIVERY where by I want to show the remaining quantity in another table 'STOCK'.
Below is the output I got from my STOCK table  and the code I did, but the calculation is wrong.
Can anyone help me with this?

private void stock(){

        dbConection db = new dbConection();
        Connection con=db.getConnection();
            String sql = "Select delivery.pro_Name, delivery.pro_Code, (sum(purchase.pur_qty) - sum(delivery.Qty)) AS bal from  delivery, purchase where purchase.productCode = delivery.pro_Code GROUP BY delivery.pro_Code ";
            PreparedStatement pst = con.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            DefaultTableModel tm = (DefaultTableModel)stockTable.getModel();

            tm.setRowCount(0);
            while(rs.next()){

                Object o[]={rs.getString("pro_Code"), rs.getString("pro_Name"), rs.getString("bal")};
                tm.addRow(o);
            }

        }catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex);

        }

Body:
First of all, this is only a SQL problem, and Java is only for view the results.
The above code will be for MS SQL Server, as you did not provide the type of SQL Database.

A final stock is calculated starting from an initial stock.
So you will must have something like:

initial_stock + purchase_qty - delivery_qty  = final_stock (group by ProductId)

Now, if you store your articles/products in your database as FIFO, that means you imply also the price in this formula, so group by implies also Fifo_Price . This could be also more complex SQL Select, based of related tables.

Supposing you don't need FIFO, but only a remaining quantity stock, the select syntax will be something like this:

-- Supposing initial stock is stored in Product Table
Select pr.ProductID, pr.InitialStock, Sum(IsNull(pc.Quantity,0)) AS QuantityIn,
    Sum(IsNull(dv.Quantity,0)) AS QuantityOut,
    pr.InitialStock + sum(IsNull(pc.Quantity,0) - IsNull(dv.Quantity,0)) AS FinalStock
From Products pr
Left Join Purchase pc on pr.ProductID = pc.ProductID
Left Join Delivery dv on pr.ProductID = dv.ProductID
Group By pr.ProductID, pr.InitialStock

-- if you want to see only products that are implied in purchase and delivery tables, you must Inner Join all tables

Edit: I have deleted the rest of answer, because was not relevant to question.

Edit 2: Please look at this picture. I have made a simple test showing what are results as I did and as you did:

Considering that initial stock is not null, I did not force a replacement with 0, but you can replace that too, so st.qty will be IsNull(st.Qty, 0) as InitialStock


问:
How to iterate/foreach array in SwiftUI
I have this array of dictionaries.

```<code>let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]
</code>```

And my view:

```<code>struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}
</code>```

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

答:
This seems a very complex way to implement a struct:

```<code>struct DeckColor {
    var name: String
    var desc: String
}

let deckColors = [
    DeckColor(name: "blue", desc: "desc1"),
    DeckColor(name: "yellow", desc: "desc2")
]

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) { value in
            Text(deckColors[value].name)
        }
    }
}
</code>```

The way you've implemented it requires dealing with the case that the dictionary does not include a "name" value. You can do that, but it's uglier and more fragile:

```<code>struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) { value in
            Text(deckColors[value]["name"] ?? "default text if name isn't there.")
        }
    }
}
</code>```

Title: How to iterate/foreach array in SwiftUI

Body:
I have this array of dictionaries.

let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]

And my view:

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

Body:
This seems a very complex way to implement a struct:

struct DeckColor {
    var name: String
    var desc: String
}

let deckColors = [
    DeckColor(name: "blue", desc: "desc1"),
    DeckColor(name: "yellow", desc: "desc2")
]

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) { value in
            Text(deckColors[value].name)
        }
    }
}

The way you've implemented it requires dealing with the case that the dictionary does not include a "name" value. You can do that, but it's uglier and more fragile:

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) { value in
            Text(deckColors[value]["name"] ?? "default text if name isn't there.")
        }
    }
}


问:
Compiler error: Invalid library file - CoreLocation
I have one of my application, that is created in Xcode 8. I have used CoreLocation and MapKit in that app.

I have update app with latest iOS till now. and it was working fine. Now I am updating application with iOS 1. So I hvae opened app with Xcode 11.0 and updated all the required code. Also updated setting that is suggested by Xcode "Perform Changes" and all that.

Now I run application, but I am getting error like :

Compiler error: Invalid library file.

I have searched lot, but can't find any solution. Is this a bug in new Xcode or new iOS ?

Is there anything I have to do extra changes or settings ? Please guide me.
Is this known bug by Apple ?

EDIT :

2019-10-18 10:34:39.899827+0530 MapLocation[1697:57778] Compiler error: Invalid library file
  2019-10-18 10:34:39.900098+0530 MapLocation[1697:57778] Compiler error: Invalid library file
  2019-10-18 10:34:39.915973+0530 MapLocation[1697:57778] Compiler error: Invalid library file
  2019-10-18 10:34:39.916228+0530 MapLocation[1697:57778] Compiler error: Invalid library file

2019-10-18 10:34:39.920608+0530 MapLocation[1697:57778] Updated coordinate are : <+23.02055700,+72.50524900> +/- 5.00m (speed -1.00 mps / course -1.00) @ 10/18/19, 10:34:39 AM India Standard Time

2019-10-18 10:34:39.920697+0530 MapLocation[1697:57778] Latitude:- 23.0206, Longitude:- 72.5052

2019-10-18 10:34:39.925441+0530 MapLocation[1697:57778] Entering in ----> (Latitude:- 23.0206, Longitude:- 72.5052), With Radius:- 300.00

2019-10-18 10:34:39.925546+0530 MapLocation[1697:57778] Stated in ----> (Latitude:- 23.0206, Longitude:- 72.5052), With Radius:- 300.00

2019-10-18 10:34:39.926582+0530 MapLocation[1697:57778] Exit from ----> (Latitude:- 23.0021, Longitude:- 72.4995), With Radius:- 300.00

2019-10-18 10:34:39.926683+0530 MapLocation[1697:57778] Stated in ----> (Latitude:- 23.0021, Longitude:- 72.4995), With Radius:- 300.00

2019-10-18 10:34:39.932080+0530 MapLocation[1697:57778] Compiler error: Invalid library file
  2019-10-18 10:34:39.932268+0530 MapLocation[1697:57778] Compiler error: Invalid library file
  2019-10-18 10:34:39.948942+0530 MapLocation[1697:57778] Compiler error: Invalid library file
  2019-10-18 10:34:39.949220+0530 MapLocation[1697:57778] Compiler error: Invalid library file

答: I started running into this error recently and was able to get it to go away by clearing the Simulator from Hardware->Erase All Content and Settings... menu item.  </p>


问:
Mimic Windows Task Scheduler with code
I'm looking for a way to make a program that runs itself (or a method) every X time (days, weeks, whatever). Basically, I want my program to do what the Windows Task Scheduler could do. The reason I don't use the Task Scheduler is because I plan to deploy this application on a server which I have no remote access to, but need to re-generate some files every given time.

Suggestions?

答:
You could use Quarts.net:

http://quartznet.sourceforge.net/

Title: Mimic Windows Task Scheduler with code


答: This might be an issue with the drive where you placed the dataset. The code was working fine everywhere but not on this server. I changed the drive (from one NFS share to another) and everything works well. </p>

Title: Why Tensorflow GPU is not working with larger batch sizes?

Body:
I am training an Auto-encoder network on Tensorflow GPU 1.13.1. Initially, I used the batch size 32/64/128 but it seems the GPU is not being used at all. Although, "memory-usage" from "nvidia-smi returns the following:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 418.39       Driver Version: 418.39       CUDA Version: 10.1     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla V100-SXM2...  On   | 00000000:06:00.0 Off |                    0 |
| N/A   34C    P0    53W / 300W |  31316MiB / 32480MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

And, the training stops at 39th steps every time.

Model: "model_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_3 (InputLayer)         (None, 256, 256, 3)       0
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 64, 64, 96)        34944
_________________________________________________________________
batch_normalization_6 (Batch (None, 64, 64, 96)        384
_________________________________________________________________
activation_6 (Activation)    (None, 64, 64, 96)        0
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 31, 31, 96)        0
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 31, 31, 256)       614656
_________________________________________________________________
batch_normalization_7 (Batch (None, 31, 31, 256)       1024
_________________________________________________________________
activation_7 (Activation)    (None, 31, 31, 256)       0
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 15, 15, 256)       0
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 15, 15, 384)       885120
_________________________________________________________________
batch_normalization_8 (Batch (None, 15, 15, 384)       1536
_________________________________________________________________
activation_8 (Activation)    (None, 15, 15, 384)       0
_________________________________________________________________
conv2d_9 (Conv2D)            (None, 15, 15, 384)       1327488
_________________________________________________________________
batch_normalization_9 (Batch (None, 15, 15, 384)       1536
_________________________________________________________________
activation_9 (Activation)    (None, 15, 15, 384)       0
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 15, 15, 256)       884992
_________________________________________________________________
batch_normalization_10 (Batc (None, 15, 15, 256)       1024
_________________________________________________________________
activation_10 (Activation)   (None, 15, 15, 256)       0
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 7, 7, 256)         0
_________________________________________________________________
conv2d_11 (Conv2D)           (None, 1, 1, 1024)        12846080
_________________________________________________________________
batch_normalization_11 (Batc (None, 1, 1, 1024)        4096
_________________________________________________________________
encoded (Activation)         (None, 1, 1, 1024)        0
_________________________________________________________________
reshape_1 (Reshape)          (None, 2, 2, 256)         0
_________________________________________________________________
conv2d_transpose_1 (Conv2DTr (None, 4, 4, 128)         819328
_________________________________________________________________
activation_11 (Activation)   (None, 4, 4, 128)         0
_________________________________________________________________
conv2d_transpose_2 (Conv2DTr (None, 8, 8, 64)          204864
_________________________________________________________________
activation_12 (Activation)   (None, 8, 8, 64)          0
_________________________________________________________________
conv2d_transpose_3 (Conv2DTr (None, 16, 16, 32)        51232
_________________________________________________________________
activation_13 (Activation)   (None, 16, 16, 32)        0
_________________________________________________________________
conv2d_transpose_4 (Conv2DTr (None, 32, 32, 16)        12816
_________________________________________________________________
activation_14 (Activation)   (None, 32, 32, 16)        0
_________________________________________________________________
conv2d_transpose_5 (Conv2DTr (None, 64, 64, 8)         3208
_________________________________________________________________
activation_15 (Activation)   (None, 64, 64, 8)         0
_________________________________________________________________
conv2d_transpose_6 (Conv2DTr (None, 128, 128, 4)       804
_________________________________________________________________
activation_16 (Activation)   (None, 128, 128, 4)       0
_________________________________________________________________
conv2d_transpose_7 (Conv2DTr (None, 256, 256, 3)       303
=================================================================
Total params: 17,695,435
Trainable params: 17,690,635
Non-trainable params: 4,800
_________________________________________________________________
Epoch 1/1
Found 11058 images belonging to 1 classes.
Found 11058 images belonging to 1 classes.
Found 11058 images belonging to 1 classes.
Found 44234 images belonging to 1 classes.
Found 11058 images belonging to 1 classes.
Found 44234 images belonging to 1 classes.
Found 44234 images belonging to 1 classes.
Found 44234 images belonging to 1 classes.

   1/1382 [..............................] - ETA: 19:43:47 - loss: 0.6934 - accuracy: 0.1511
   2/1382 [..............................] - ETA: 10:04:16 - loss: 0.6933 - accuracy: 0.1545
   3/1382 [..............................] - ETA: 7:28:21 - loss: 0.6933 - accuracy: 0.1571
   4/1382 [..............................] - ETA: 6:07:30 - loss: 0.6932 - accuracy: 0.1590
   5/1382 [..............................] - ETA: 5:21:58 - loss: 0.6931 - accuracy: 0.1614
   6/1382 [..............................] - ETA: 4:55:45 - loss: 0.6930 - accuracy: 0.1648
   7/1382 [..............................] - ETA: 4:32:58 - loss: 0.6929 - accuracy: 0.1668
   8/1382 [..............................] - ETA: 4:15:07 - loss: 0.6929 - accuracy: 0.1692
   9/1382 [..............................] - ETA: 4:02:22 - loss: 0.6928 - accuracy: 0.1726
  10/1382 [..............................] - ETA: 3:50:11 - loss: 0.6926 - accuracy: 0.1745
  11/1382 [..............................] - ETA: 3:39:13 - loss: 0.6925 - accuracy: 0.1769
  12/1382 [..............................] - ETA: 3:29:38 - loss: 0.6924 - accuracy: 0.1797
  13/1382 [..............................] - ETA: 3:21:11 - loss: 0.6923 - accuracy: 0.1824
  14/1382 [..............................] - ETA: 3:13:42 - loss: 0.6922 - accuracy: 0.1845
  15/1382 [..............................] - ETA: 3:07:17 - loss: 0.6920 - accuracy: 0.1871
  16/1382 [..............................] - ETA: 3:01:59 - loss: 0.6919 - accuracy: 0.1896
  17/1382 [..............................] - ETA: 2:57:36 - loss: 0.6918 - accuracy: 0.1916
  18/1382 [..............................] - ETA: 2:53:06 - loss: 0.6917 - accuracy: 0.1938
  19/1382 [..............................] - ETA: 2:49:37 - loss: 0.6915 - accuracy: 0.1956
  20/1382 [..............................] - ETA: 2:45:51 - loss: 0.6915 - accuracy: 0.1979
  21/1382 [..............................] - ETA: 2:43:18 - loss: 0.6914 - accuracy: 0.2000
  22/1382 [..............................] - ETA: 2:41:02 - loss: 0.6913 - accuracy: 0.2022
  23/1382 [..............................] - ETA: 2:39:23 - loss: 0.6912 - accuracy: 0.2039
  24/1382 [..............................] - ETA: 2:37:23 - loss: 0.6911 - accuracy: 0.2060
  25/1382 [..............................] - ETA: 2:35:58 - loss: 0.6909 - accuracy: 0.2080
  26/1382 [..............................] - ETA: 2:34:06 - loss: 0.6909 - accuracy: 0.2098
  27/1382 [..............................] - ETA: 2:33:19 - loss: 0.6908 - accuracy: 0.2115
  28/1382 [..............................] - ETA: 2:32:24 - loss: 0.6906 - accuracy: 0.2130
  29/1382 [..............................] - ETA: 2:31:43 - loss: 0.6904 - accuracy: 0.2143
  30/1382 [..............................] - ETA: 2:31:09 - loss: 0.6904 - accuracy: 0.2157
  31/1382 [..............................] - ETA: 2:30:34 - loss: 0.6902 - accuracy: 0.2173
  32/1382 [..............................] - ETA: 2:29:26 - loss: 0.6901 - accuracy: 0.2185
  33/1382 [..............................] - ETA: 2:28:55 - loss: 0.6900 - accuracy: 0.2199
  34/1382 [..............................] - ETA: 2:28:05 - loss: 0.6899 - accuracy: 0.2213
  35/1382 [..............................] - ETA: 2:27:23 - loss: 0.6898 - accuracy: 0.2227
  36/1382 [..............................] - ETA: 2:27:02 - loss: 0.6897 - accuracy: 0.2238
  37/1382 [..............................] - ETA: 2:26:56 - loss: 0.6895 - accuracy: 0.2253
  38/1382 [..............................] - ETA: 2:26:32 - loss: 0.6893 - accuracy: 0.2266
  39/1382 [..............................] - ETA: 2:26:11 - loss: 0.6891 - accuracy: 0.2278

Even waiting hours, the training process doesn't move further.

Another, unusual thing I noticed is that, setting the batch size to "1", the GPU is being continuously utilized.

What could be the problem?


问:
Result of VBA code not visible in textbox in Access
I use Access to maintain a list (with details) of cases I work on (I am a legal professional).

I want to add a unique case identifier to every case. I use a form to enter the data in the database.

I wrote this very simple code to add the Case ID nr:

```<code>Private Sub Command81_Click()
    If Not IsNull(Me.Case_ID) Then
        DoCmd.CancelEvent
    Else
        Command81.Enabled = True
        Me.Case_ID = Me.Combo321 + Format(Me.[Date Original Event], "yymmdd") + Format(Time, "hhmmss")
    End If
End Sub
</code>```

The idea is I fill the different fields in the form and then click a button to add the case ID (listed in the textbox (in the form) and field (in the database) called 'Case_ID').

When I click the button it should check whether there is already a case ID. If there is it will not create a new one. If there is none yet a new case ID will be created based on the country where the case happened (Combo321) + the date when the original event happened + time I created the case ID.

(There is a reason why the case ID is so complicated, but that doesn't matter for the purpose of my question.).

The code works like a charm, except: when I click the button nothing happens in the form. The Case ID only appears in the relevant textbox in the form after I click on it (after the Case ID was created).

Is there anything I can add to the code to make the Case ID appear in the textbox in the form when it is created, without having to click the text box?

答:
What is the recordsource of your form?
You really need to update/value the CaseId in the table
underlying your form.</p>

Body:
I use Access to maintain a list (with details) of cases I work on (I am a legal professional).

I want to add a unique case identifier to every case. I use a form to enter the data in the database.

I wrote this very simple code to add the Case ID nr:

Private Sub Command81_Click()
    If Not IsNull(Me.Case_ID) Then
        DoCmd.CancelEvent
    Else
        Command81.Enabled = True
        Me.Case_ID = Me.Combo321 + Format(Me.[Date Original Event], "yymmdd") + Format(Time, "hhmmss")
    End If
End Sub

The idea is I fill the different fields in the form and then click a button to add the case ID (listed in the textbox (in the form) and field (in the database) called 'Case_ID').

When I click the button it should check whether there is already a case ID. If there is it will not create a new one. If there is none yet a new case ID will be created based on the country where the case happened (Combo321) + the date when the original event happened + time I created the case ID.

(There is a reason why the case ID is so complicated, but that doesn't matter for the purpose of my question.).

The code works like a charm, except: when I click the button nothing happens in the form. The Case ID only appears in the relevant textbox in the form after I click on it (after the Case ID was created).

Is there anything I can add to the code to make the Case ID appear in the textbox in the form when it is created, without having to click the text box?


问:
Loop colnames basis a vector pattern
I wish to filter basis column names basis a vector and subsequently bind them together.

This is my data frame -

```<code>df = data.frame("Applefor_yes" = 1:4,
                "Applefor_no" = 2:5,
                "Bananfor_yes" = 1:4,
                "Bananfor_no" = 2:5)

   Applefor_yes Applefor_no Bananfor_yes Bananfor_no
1            1           2            1           2
2            2           3            2           3
3            3           4            3           4
4            4           5            4           5
</code>```

I want the output to look like this.

```<code>     fruit yes no
1 Applefor   1  2
2 Applefor   2  3
3 Applefor   3  4
4 Applefor   4  5
5 Bananfor   1  2
6 Bananfor   2  3
7 Bananfor   3  4
8 Bananfor   4  5
</code>```

In short, I want to loop the column names basis a vector c("Bananfor", "Applefor")

答:
We can use pivot_longer from tidyr specifying names_to and names_sep argument.

```<code>tidyr::pivot_longer(df, cols = everything(),
                        names_to = c("fruit", ".value"),
                        names_sep = "_")

#  fruit      yes    no
#  <chr>    <int> <int>
#1 Applefor     1     2
#2 Bananfor     1     2
#3 Applefor     2     3
#4 Bananfor     2     3
#5 Applefor     3     4
#6 Bananfor     3     4
#7 Applefor     4     5
#8 Bananfor     4     5
</code>```

Title: Loop colnames basis a vector pattern

Body:
I wish to filter basis column names basis a vector and subsequently bind them together.

This is my data frame -

df = data.frame("Applefor_yes" = 1:4,
                "Applefor_no" = 2:5,
                "Bananfor_yes" = 1:4,
                "Bananfor_no" = 2:5)

   Applefor_yes Applefor_no Bananfor_yes Bananfor_no
1            1           2            1           2
2            2           3            2           3
3            3           4            3           4
4            4           5            4           5

I want the output to look like this.

     fruit yes no
1 Applefor   1  2
2 Applefor   2  3
3 Applefor   3  4
4 Applefor   4  5
5 Bananfor   1  2
6 Bananfor   2  3
7 Bananfor   3  4
8 Bananfor   4  5

In short, I want to loop the column names basis a vector c("Bananfor", "Applefor")

Body:
We can use pivot_longer from tidyr specifying names_to and names_sep argument.

tidyr::pivot_longer(df, cols = everything(),
                        names_to = c("fruit", ".value"),
                        names_sep = "_")

#  fruit      yes    no
#  <chr>    <int> <int>
#1 Applefor     1     2
#2 Bananfor     1     2
#3 Applefor     2     3
#4 Bananfor     2     3
#5 Applefor     3     4
#6 Bananfor     3     4
#7 Applefor     4     5
#8 Bananfor     4     5