问:
FabricTransientException during load test "Could not ping any of the provided Service Fabric gateway endpoints."
We have a class that broadcasts messages to a Service Fabric stateless service. This stateless service has a single partition, but with many replica's.
The message should be send to all the replica's in the system. Therefore we query the FabricClient for the single partition, and all the replica's of that partition.
We use standard HTTP communication (the stateless service has Communication Listener with a selfhosted OWIN listener, using WebListener/HttpSys) with a shared HttpClient instance.
During a load test, we get many errors during the sending of messages. Note that we have other services in the same application, also communicating (WebListener/HttpSys, ServiceProxy, and ActorProxy).

The code where we see Exceptions is (stacktrace is below the code sample):

```<code>private async Task SendMessageToReplicas(string actionName, string message)
{
  var fabricClient = new FabricClient();
  var eventNotificationHandlerServiceUri = new Uri(ServiceFabricSettings.EventNotificationHandlerServiceName);

  var promises = new List<Task>();
  // There is only one partition of this service, but there are many replica's
  Partition partition = (await fabricClient.QueryManager.GetPartitionListAsync(eventNotificationHandlerServiceUri).ConfigureAwait(false)).First();

  string continuationToken = null;
  do
  {
    var replicas = await fabricClient.QueryManager.GetReplicaListAsync(partition.PartitionInformation.Id, continuationToken).ConfigureAwait(false);
    foreach(Replica replica in replicas)
    {
      promises.Add(SendMessageToReplica(replica, actionName, message));
    }

    continuationToken = replicas.ContinuationToken;
  } while(continuationToken != null);

  await Task.WhenAll(promises).ConfigureAwait(false);
}

private async Task SendMessageToReplica(Replica replica, string actionName, string message)
{
  if(replica.TryGetEndpoint(out Uri replicaUrl))
  {
    Uri requestUri = UriUtility.Combine(replicaUrl, actionName);
    using(var response = await _httpClient.PostAsync(requestUri, message == null ? null : new JsonContent(message)).ConfigureAwait(false))
    {
      string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
      if(!response.IsSuccessStatusCode)
      {
        throw new Exception();
      }
    }
  }
  else
  {
    throw new Exception();
  }
}
</code>```

The following Exception is thrown:

```<code>System.Fabric.FabricTransientException: Could not ping any of the provided Service Fabric gateway endpoints. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071C49
at System.Fabric.Interop.NativeClient.IFabricQueryClient9.EndGetPartitionList2(IFabricAsyncOperationContext context)
at System.Fabric.FabricClient.QueryClient.GetPartitionListAsyncEndWrapper(IFabricAsyncOperationContext context)
at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Company.ServiceFabric.ServiceFabricEventNotifier.<SendMessageToReplicas>d__7.MoveNext() in c:\work\ServiceFabricEventNotifier.cs:line 138
</code>```

During the same period we also see this Exception being thrown:

```<code>System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.) ---> System.ComponentModel.Win32Exception (0x80004005): An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken)
</code>```

The event logs on the machines in the cluster show these warnings:

```<code>Event ID: 4231
Source: Tcpip
Level: Warning
A request to allocate an ephemeral port number from the global TCP port space has failed due to all such ports being in use.

Event ID: 4227
Source: Tcpip
Level: Warning
TCP/IP failed to establish an outgoing connection because the selected local endpoint was recently used to connect to the same remote endpoint. This error typically occurs when outgoing connections are opened and closed at a high rate, causing all available local ports to be used and forcing TCP/IP to reuse a local port for an outgoing connection. To minimize the risk of data corruption, the TCP/IP standard requires a minimum time period to elapse between successive connections from a given local endpoint to a given remote endpoint.
</code>```

And finally the Microsoft-Service Fabric admin log shows hundreds of warnings similar to

```<code>Event 4121
Source Microsoft-Service-Fabric
Level: Warning
client-02VM4.company.nl:19000/192.168.10.36:19000: error = 2147942452, failureCount=160522. Filter by (type~Transport.St && ~"(?i)02VM4.company.nl:19000") to get listener lifecycle. Connect failure is expected if listener was never started, or listener/its process was stopped before/during connecting.

Event 4097
Source Microsoft-Service-Fabric
Level: Warning
client-02VM4.company.nl:19000 : connect failed, having tried all addresses
</code>```

After a while, the warnings become errors:

```<code>Event 4096
Source Microsoft-Service-Fabric
Level: Error
client-02VM4.company.nl:19000 failed to bind to local port for connecting: 0x80072747
</code>```

Can anyone tell us why this happends, and what we can do to solve this? Are we doing something wrong?

答:
We (I work with the OP) have been testing this and it turned out to be the FabricClient as suggested by Esben Bach.

The documentation on the FabricClient also states:

It is highly recommended that you share FabricClients as much as possible. This is because the FabricClient has multiple optimizations such as caching and batching that you would not be able to fully utilize otherwise.

It seems the FabricClient behaves like the HttpClient class where you should also share the instance and when you don't you'll get the same problem, port exhaustion.

The common exceptions working with the FabricClient documentation however also mentions that when a FabricObjectClosedException occurs you should:

Dispose of the FabricClient object you are using and instantiate a new FabricClient object.

Sharing the FabricClient fixes the port exhaustion problem.

Body:
We have a class that broadcasts messages to a Service Fabric stateless service. This stateless service has a single partition, but with many replica's.
The message should be send to all the replica's in the system. Therefore we query the FabricClient for the single partition, and all the replica's of that partition.
We use standard HTTP communication (the stateless service has Communication Listener with a selfhosted OWIN listener, using WebListener/HttpSys) with a shared HttpClient instance.
During a load test, we get many errors during the sending of messages. Note that we have other services in the same application, also communicating (WebListener/HttpSys, ServiceProxy, and ActorProxy).

The code where we see Exceptions is (stacktrace is below the code sample):

private async Task SendMessageToReplicas(string actionName, string message)
{
  var fabricClient = new FabricClient();
  var eventNotificationHandlerServiceUri = new Uri(ServiceFabricSettings.EventNotificationHandlerServiceName);

  var promises = new List<Task>();
  // There is only one partition of this service, but there are many replica's
  Partition partition = (await fabricClient.QueryManager.GetPartitionListAsync(eventNotificationHandlerServiceUri).ConfigureAwait(false)).First();

  string continuationToken = null;
  do
  {
    var replicas = await fabricClient.QueryManager.GetReplicaListAsync(partition.PartitionInformation.Id, continuationToken).ConfigureAwait(false);
    foreach(Replica replica in replicas)
    {
      promises.Add(SendMessageToReplica(replica, actionName, message));
    }

    continuationToken = replicas.ContinuationToken;
  } while(continuationToken != null);

  await Task.WhenAll(promises).ConfigureAwait(false);
}

private async Task SendMessageToReplica(Replica replica, string actionName, string message)
{
  if(replica.TryGetEndpoint(out Uri replicaUrl))
  {
    Uri requestUri = UriUtility.Combine(replicaUrl, actionName);
    using(var response = await _httpClient.PostAsync(requestUri, message == null ? null : new JsonContent(message)).ConfigureAwait(false))
    {
      string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
      if(!response.IsSuccessStatusCode)
      {
        throw new Exception();
      }
    }
  }
  else
  {
    throw new Exception();
  }
}

The following Exception is thrown:

System.Fabric.FabricTransientException: Could not ping any of the provided Service Fabric gateway endpoints. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071C49
at System.Fabric.Interop.NativeClient.IFabricQueryClient9.EndGetPartitionList2(IFabricAsyncOperationContext context)
at System.Fabric.FabricClient.QueryClient.GetPartitionListAsyncEndWrapper(IFabricAsyncOperationContext context)
at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Company.ServiceFabric.ServiceFabricEventNotifier.<SendMessageToReplicas>d__7.MoveNext() in c:\work\ServiceFabricEventNotifier.cs:line 138

During the same period we also see this Exception being thrown:

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.) ---> System.ComponentModel.Win32Exception (0x80004005): An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken)

The event logs on the machines in the cluster show these warnings:

Event ID: 4231
Source: Tcpip
Level: Warning
A request to allocate an ephemeral port number from the global TCP port space has failed due to all such ports being in use.

Event ID: 4227
Source: Tcpip
Level: Warning
TCP/IP failed to establish an outgoing connection because the selected local endpoint was recently used to connect to the same remote endpoint. This error typically occurs when outgoing connections are opened and closed at a high rate, causing all available local ports to be used and forcing TCP/IP to reuse a local port for an outgoing connection. To minimize the risk of data corruption, the TCP/IP standard requires a minimum time period to elapse between successive connections from a given local endpoint to a given remote endpoint.

And finally the Microsoft-Service Fabric admin log shows hundreds of warnings similar to

Event 4121
Source Microsoft-Service-Fabric
Level: Warning
client-02VM4.company.nl:19000/192.168.10.36:19000: error = 2147942452, failureCount=160522. Filter by (type~Transport.St && ~"(?i)02VM4.company.nl:19000") to get listener lifecycle. Connect failure is expected if listener was never started, or listener/its process was stopped before/during connecting.

Event 4097
Source Microsoft-Service-Fabric
Level: Warning
client-02VM4.company.nl:19000 : connect failed, having tried all addresses

After a while, the warnings become errors:

Event 4096
Source Microsoft-Service-Fabric
Level: Error
client-02VM4.company.nl:19000 failed to bind to local port for connecting: 0x80072747

Can anyone tell us why this happends, and what we can do to solve this? Are we doing something wrong?


来源: stackexchange

问:
Karate - Cannot Validate XML response if DTD is not accessible
I have a situation where I need to parse an XML response using Karate, but the reference to the DTD is not accessible. In other words is DTD required for parsing?

Is there a way around this?

答:
To be honest I'm not sure. Are you facing an error if the XML has a DTD ?

Then maybe we need to make a change to Karate to skip DTD validation. I think this Stack Overflow question is relevant: Make DocumentBuilder.parse ignore DTD references

If you can raise a ticket and provide a sample XML that has a DTD, we can fix this pretty quickly.

ContentLicense: CC BY-SA 3.0


问:
Show and Hide Div onMouseOver
Hey guys, need just a little bit of help here, it's very close to what I'm after but not quite.

I want the text links I hover over to animate hidden text in a target div. So when I hover over link A, that text fades in; when I hover over link B, the previous text fades away and new text fades in.

Here is my javascript:

```<code><script type="text/javascript">
function ShowHide(){
    $("#textMessages").animate({"height": "toggle"}, { duration: 1000 });
    }
</script>
</code>```

Here are my links:

```<code><a onMouseOver="ShowHide(); return false;" href="#">Message A</a>

<a onMouseOver="ShowHide(); return false;" href="#">Message B</a>

<a onMouseOver="ShowHide(); return false;" href="#">Message C</a>
</code>```

And here is my target div with text snippets to fade in and fade out:

```<code><div id="textMessages">

<div id="defaultMessage">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

<div id="MessageA">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

<div id="MessageB">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

<div id="MessageC">
Lorem ipsum dolor sit amet, consectetur adipiscing elit
</div>

</div>
</code>```

I assume I will need to set the #MessageA/B/C display:none

答:
Here is a jsFiddle that does what I think you are trying to do.

http://jsfiddle.net/rcravens/md3Xe/

If that is not it, please provide additional information.

Bob

ContentLicense: CC BY-SA 2.5

Title: Show and Hide Div onMouseOver

Body:
Hey guys, need just a little bit of help here, it's very close to what I'm after but not quite.

I want the text links I hover over to animate hidden text in a target div. So when I hover over link A, that text fades in; when I hover over link B, the previous text fades away and new text fades in.

Here is my javascript:

Here are my links:

Message A

Message B

Message C

And here is my target div with text snippets to fade in and fade out:

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit

I assume I will need to set the #MessageA/B/C display:none


问:
Android How to add ScrollView? ScrollView shits layout
I have a problem with adding ScrollView into my layout. So, when I add ScrollView (match_parent) into my layout, it shifts my layout into right side. Hereby, I see only background picture on the screen of the device. All Buttons, Textviews, and Edittexts shifted into right. By the way, I wrote code for only portrait layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context="com.example.rauf.myapplication.Main2Activity"
android:background="@drawable/bii3">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp"
    android:paddingLeft="60dp"
    android:paddingRight="58dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:layout_weight="2"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingTop="42dp">

        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:src="@drawable/kamera" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_weight="0.5"
        android:paddingTop="35dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/message" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:background="#00000000"
                android:hint="email address"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/log"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/usrusr"/>
            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:background="#00000000"
                android:hint="username"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/passwordconf"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password confirm"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_background2"
            android:text="SIGN UP"
            android:onClick="clickButton2"
            android:clickable="true"
            android:layout_marginTop="20dp"
            android:textColor="#ffffff"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="30dp"
            android:onClick="clickFunction2"
            android:text="Already have an Account ?"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>
</code>```

I want ScrollView for this:

But I end up with this:

答:
There was an empty linear layout and a small typo, so i fixed those as well.
You need to change back the backgrounds

here is your code:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="wrap_content">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/ic_launcher_background">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"
        android:paddingLeft="60dp"
        android:paddingRight="58dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="600dp"
            android:layout_weight="2"
            android:gravity="center"
            android:orientation="vertical"
            android:paddingTop="42dp">

            <ImageView
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher_background" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="0.5"
            android:paddingTop="35dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">

                <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background" />

                <EditText
                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textEmailAddress"
                    android:background="#00000000"
                    android:hint="email address"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#4a5a71"></LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">
                <ImageView
                    android:id="@+id/log"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background"/>
                <EditText
                    android:id="@+id/username"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:background="#00000000"
                    android:hint="username"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#4a5a71"></LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">
                <ImageView
                    android:id="@+id/red"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background"/>
                <EditText
                    android:id="@+id/password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:background="#00000000"
                    android:hint="password"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">
                <ImageView
                    android:id="@+id/red2"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background"/>
                <EditText
                    android:id="@+id/passwordconf"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:background="#00000000"
                    android:hint="password confirm"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#4a5a71"
                android:orientation="vertical">
            <Button
                android:id="@+id/button1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_launcher_background"
                android:text="SIGN UP"
                android:onClick="clickButton2"
                android:clickable="true"
                android:layout_marginTop="20dp"
                android:textColor="#ffffff"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginTop="30dp"
                android:onClick="clickFunction2"
                android:text="Already have an Account ?"
                android:textColor="#000000" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</ScrollView>
</code>```

Body:
I have a problem with adding ScrollView into my layout. So, when I add ScrollView (match_parent) into my layout, it shifts my layout into right side. Hereby, I see only background picture on the screen of the device. All Buttons, Textviews, and Edittexts shifted into right. By the way, I wrote code for only portrait layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context="com.example.rauf.myapplication.Main2Activity"
android:background="@drawable/bii3">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp"
    android:paddingLeft="60dp"
    android:paddingRight="58dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:layout_weight="2"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingTop="42dp">

        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:src="@drawable/kamera" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_weight="0.5"
        android:paddingTop="35dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/message" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:background="#00000000"
                android:hint="email address"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/log"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/usrusr"/>
            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:background="#00000000"
                android:hint="username"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="16dp">
            <ImageView
                android:id="@+id/red2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_gravity="center"
                android:src="@drawable/pswrd"/>
            <EditText
                android:id="@+id/passwordconf"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:background="#00000000"
                android:hint="password confirm"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#4a5a71"></LinearLayout>
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_background2"
            android:text="SIGN UP"
            android:onClick="clickButton2"
            android:clickable="true"
            android:layout_marginTop="20dp"
            android:textColor="#ffffff"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_marginTop="30dp"
            android:onClick="clickFunction2"
            android:text="Already have an Account ?"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>

I want ScrollView for this:

But I end up with this:

Body:
There was an empty linear layout and a small typo, so i fixed those as well.
You need to change back the backgrounds

here is your code:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="wrap_content">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/ic_launcher_background">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"
        android:paddingLeft="60dp"
        android:paddingRight="58dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="600dp"
            android:layout_weight="2"
            android:gravity="center"
            android:orientation="vertical"
            android:paddingTop="42dp">

            <ImageView
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher_background" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="0.5"
            android:paddingTop="35dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">

                <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background" />

                <EditText
                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textEmailAddress"
                    android:background="#00000000"
                    android:hint="email address"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#4a5a71"></LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">
                <ImageView
                    android:id="@+id/log"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background"/>
                <EditText
                    android:id="@+id/username"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:background="#00000000"
                    android:hint="username"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#4a5a71"></LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">
                <ImageView
                    android:id="@+id/red"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background"/>
                <EditText
                    android:id="@+id/password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:background="#00000000"
                    android:hint="password"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="16dp">
                <ImageView
                    android:id="@+id/red2"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_launcher_background"/>
                <EditText
                    android:id="@+id/passwordconf"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:background="#00000000"
                    android:hint="password confirm"
                    android:layout_marginLeft="15dp"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#4a5a71"
                android:orientation="vertical">
            <Button
                android:id="@+id/button1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_launcher_background"
                android:text="SIGN UP"
                android:onClick="clickButton2"
                android:clickable="true"
                android:layout_marginTop="20dp"
                android:textColor="#ffffff"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginTop="30dp"
                android:onClick="clickFunction2"
                android:text="Already have an Account ?"
                android:textColor="#000000" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</ScrollView>


问:
Oracle SQL count group by day distinct in day and days before
I need help with this: I have this table:

```<code>DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020
</code>```

I need to group by day distinct WO, but not only in the day I'm grouping, also distinct in the days before, to obtain this:

```<code>DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)
</code>```

Thanks for your help

```<code>Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547
</code>```

答:
You can use the following query:

```<code>SELECT DAY, COUNT(DISTINCT WO)
FROM (
   SELECT MIN(DAY) AS DAY, WO
   FROM mytable
   GROUP BY WO) AS t
GROUP BY DAY
</code>```

Demo here

Explanation: The inner query delivers the first Day related to each WO value (if by first you mean the minimum Day value. The outer query can then perform a COUNT DISTINCT operation to get the number of distinct WO values per DAY.

Edit: To get all days returned, even those having no WO, you can use the following query:

```<code>SELECT t1.DAY,
       COUNT(DISTINCT t2.WO) wo_cnt,
       LISTAGG(t2.WO, ',') WITHIN GROUP (ORDER BY t2.WO) wo_list
FROM (
  SELECT DISTINCT DAY
  FROM mytable) t1
LEFT JOIN (
   SELECT MIN(DAY) AS DAY, WO
   FROM mytable
   GROUP BY WO
) t2 ON t1.DAY = t2.DAY
GROUP BY t1.DAY
ORDER BY t1.DAY
</code>```

Demo here

Body:
I need help with this: I have this table:

DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020

I need to group by day distinct WO, but not only in the day I'm grouping, also distinct in the days before, to obtain this:

DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)

Thanks for your help

Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547

Body:
You can use the following query:

SELECT DAY, COUNT(DISTINCT WO)
FROM (
   SELECT MIN(DAY) AS DAY, WO
   FROM mytable
   GROUP BY WO) AS t
GROUP BY DAY

Demo here

Explanation: The inner query delivers the first Day related to each WO value (if by first you mean the minimum Day value. The outer query can then perform a COUNT DISTINCT operation to get the number of distinct WO values per DAY.

Edit: To get all days returned, even those having no WO, you can use the following query:

SELECT t1.DAY,
       COUNT(DISTINCT t2.WO) wo_cnt,
       LISTAGG(t2.WO, ',') WITHIN GROUP (ORDER BY t2.WO) wo_list
FROM (
  SELECT DISTINCT DAY
  FROM mytable) t1
LEFT JOIN (
   SELECT MIN(DAY) AS DAY, WO
   FROM mytable
   GROUP BY WO
) t2 ON t1.DAY = t2.DAY
GROUP BY t1.DAY
ORDER BY t1.DAY

Demo here


问:
Why is my .on("click") function for the AuthorButton only returning my variable every other quote?
Some background: I am working through FreeCodeCamps Front-End Development projects and this project represents a Random Quote Machine.

I would like to keep the author hidden for each quote, but at the moment, the "Click to Reveal" button only reveals an author every other quote...

https://codepen.io/DecisiveIndecisive/pen/KXjXXd

The code in question is the Javascript. Thank You!

```<code>$(document).ready(function() {
  var url =
    "https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";

  $("#refreshButton").on("click", function() {
    $.getJSON(url, function(json) {
      var jsonQuote = json.quoteText;
      var jsonAuthor = json.quoteAuthor;
      $(".counter").html(jsonAuthor);
      $("#authorButton").text("Click to Reveal");

      if (jsonAuthor === "") {
        $("#refreshButton").trigger("click");
      } else {
        $(".message").html(jsonQuote);
        $("#authorButton").click(function() {
          $(this).text(function(i, text) {
            return text === "Click to Reveal"
             ? "- " + jsonAuthor
              : "Click to Reveal";
          });
        });
      } //else close
    }); //getJSON close
  }); //refreshButton Close
});
</code>```

答:
The problem here is that you're re-binding the click function every time the refresh button is clicked. This means that when it is clicked for the second quote, the same effective function is invoked twice. You can see this in action if you add a log message inside of your #authorButton click handler.

```<code>$("#authorButton").click(function() {
  $(this).text(function(i, text) {
     console.log(text)
     return text === "Click to Reveal" ? "- " + jsonAuthor : "Click to Reveal";
  });
});
</code>```

A better option would be to have a hidden element which you can update with the jsonAuthor when you get your json feed. Then have a single #authorButton click handler which shows that hidden element when invoked.

Body:
Some background: I am working through FreeCodeCamps Front-End Development projects and this project represents a Random Quote Machine.

I would like to keep the author hidden for each quote, but at the moment, the "Click to Reveal" button only reveals an author every other quote...

https://codepen.io/DecisiveIndecisive/pen/KXjXXd

The code in question is the Javascript. Thank You!

$(document).ready(function() {
  var url =
    "https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";

  $("#refreshButton").on("click", function() {
    $.getJSON(url, function(json) {
      var jsonQuote = json.quoteText;
      var jsonAuthor = json.quoteAuthor;
      $(".counter").html(jsonAuthor);
      $("#authorButton").text("Click to Reveal");

      if (jsonAuthor === "") {
        $("#refreshButton").trigger("click");
      } else {
        $(".message").html(jsonQuote);
        $("#authorButton").click(function() {
          $(this).text(function(i, text) {
            return text === "Click to Reveal"
             ? "- " + jsonAuthor
              : "Click to Reveal";
          });
        });
      } //else close
    }); //getJSON close
  }); //refreshButton Close
});

Body:
The problem here is that you're re-binding the click function every time the refresh button is clicked. This means that when it is clicked for the second quote, the same effective function is invoked twice. You can see this in action if you add a log message inside of your #authorButton click handler.

$("#authorButton").click(function() {
  $(this).text(function(i, text) {
     console.log(text)
     return text === "Click to Reveal" ? "- " + jsonAuthor : "Click to Reveal";
  });
});

A better option would be to have a hidden element which you can update with the jsonAuthor when you get your json feed. Then have a single #authorButton click handler which shows that hidden element when invoked.


问:
Printing Multiple Labels from PHP/Web Application to Dymo LabelWriter 450 Turbo
I'm looking to add the functionality to print multiple labels using a Dymo LabelWriter 450 Turbo. I've downloaded the DYMO-Label-v.8-SDK.dmg from the Dymo site but can't see any Javascript/web related SDK files or documentation - all I can see are AppleScript examples which won't help here.

Does anyone know if this is possible (data for labels will come from backend database connected to PHP web app). I can't find any documentation for a Javascript SDK on the Dymo Developer website - only some examples from a few years ago so not even sure what is the current state and which is the latest version etc and whether there is a way to print multiple labels?

答:
I actually just built this functionality in my own web app using the exact same printer and I'm feeling friendly today. Here is what I have working for me in a production level application. Good luck!

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>DYMO: QR-code</title>
<!-- JQuery -->
<script src = "http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript" charset="UTF-8"> </script>
<!-- Dymo Script -->
<script src="DYMO.Label.Framework.2.0.2.js" type="text/javascript" charset="UTF-8"></script>
<!-- QR Code -->
<script src="QRCode.js" type="text/javascript" charset="UTF-8"> </script>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</head>

<body>

<div class="container">

    <div class="jumbotron">
        <h3>DYMO Label Framework JavaScript Library Samples: QR code</h3>
        <div class="header">
            <div id="sampleDesctiption">
                <span>
                    This sample shows different ways to print a label with a QR-code barcode.
                </span>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="printControls">

            <div class="row">
                <div class="col-md-6">
                    <div id="printersDiv">
                        <label for="printersSelect">Printer:</label><br/>
                        <select class="form-control" id="printersSelect"></select>
                    </div>
                </div>
            </div>

            <div id="printDiv" style="padding-top:20px">
                <button class="btn btn-primary btn-lg" id="printButton">Print QR Code</button>
            </div>

        </div>
    </div>

</div>

</body>

</html>
</code>```

QRCode.js

```<code>// stores loaded label info
var barcodeLabel;

// called when the document loaded
function onload() {
    var printersSelect = document.getElementById('printersSelect');
    var printButton = document.getElementById('printButton');

    // loads all supported printers into a combo box
    function loadPrinters() {
        var printers = dymo.label.framework.getLabelWriterPrinters();
        if (printers.length == 0) {
            alert("No DYMO printers are installed. Install DYMO printers.");
            return;
        }
        console.log("got here: ", printers );

        for (var i = 0; i < printers.length; i++) {
            var printer = printers[i];

            var printerName = printer.name;

            var option = document.createElement('option');
            option.value = printerName;
            option.appendChild(document.createTextNode(printerName));
            printersSelect.appendChild(option);
        }
    }

    printButton.onclick = function () {
            var label_text = 'QRCode Text Here..';

            barcodeLabel.setObjectText('Barcode', label_text);

            // Should Be Printer Name, Dymo 450 Turbo..
            console.log("print: ", printersSelect.value );

            barcodeLabel.print( printersSelect.value );

    }

    function getBarcodeLabelXml() {

        var labelXml = '<?xml version="1.0" encoding="utf-8"?>\
                            <DieCutLabel Version="8.0" Units="twips">\
                                <PaperOrientation>Landscape</PaperOrientation>\
                                <Id>Address</Id>\
                                <PaperName>30252 Address</PaperName>\
                                <DrawCommands>\
                                    <RoundRectangle X="0" Y="0" Width="1581" Height="5040" Rx="270" Ry="270" />\
                                </DrawCommands>\
                                <ObjectInfo>\
                                    <BarcodeObject>\
                                        <Name>Barcode</Name>\
                                        <ForeColor Alpha="255" Red="0" Green="0" Blue="0" />\
                                        <BackColor Alpha="0" Red="255" Green="255" Blue="255" />\
                                        <LinkedObjectName></LinkedObjectName>\
                                        <Rotation>Rotation0</Rotation>\
                                        <IsMirrored>False</IsMirrored>\
                                        <IsVariable>False</IsVariable>\
                                        <Text></Text>\
                                        <Type>QRCode</Type>\
                                        <Size>Small</Size>\
                                        <TextPosition>None</TextPosition>\
                                        <TextFont Family="Arial" Size="8" Bold="False" Italic="False" Underline="False" Strikeout="False" />\
                                        <CheckSumFont Family="Arial" Size="8" Bold="False" Italic="False" Underline="False" Strikeout="False" />\
                                        <TextEmbedding>None</TextEmbedding>\
                                        <ECLevel>0</ECLevel>\
                                        <HorizontalAlignment>Center</HorizontalAlignment>\
                                        <QuietZonesPadding Left="0" Top="300" Right="600" Bottom="0" />\
                                    </BarcodeObject>\
                                    <Bounds X="331" Y="57.9999999999999" Width="2880" Height="1435" />\
                                </ObjectInfo>\
                            </DieCutLabel>';
        return labelXml;
    }

    function loadLabelFromWeb() {
        barcodeLabel = dymo.label.framework.openLabelXml( getBarcodeLabelXml() );
    }

    // Load Labels
    loadLabelFromWeb();

    // load printers list on startup
    loadPrinters();
};

// Run's Dymo Javascript..
dymo.label.framework.init(onload);
</code>```

Body:
I actually just built this functionality in my own web app using the exact same printer and I'm feeling friendly today. Here is what I have working for me in a production level application. Good luck!

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>DYMO: QR-code</title>
<!-- JQuery -->
<script src = "http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript" charset="UTF-8"> </script>
<!-- Dymo Script -->
<script src="DYMO.Label.Framework.2.0.2.js" type="text/javascript" charset="UTF-8"></script>
<!-- QR Code -->
<script src="QRCode.js" type="text/javascript" charset="UTF-8"> </script>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</head>

<body>

<div class="container">

    <div class="jumbotron">
        <h3>DYMO Label Framework JavaScript Library Samples: QR code</h3>
        <div class="header">
            <div id="sampleDesctiption">
                <span>
                    This sample shows different ways to print a label with a QR-code barcode.
                </span>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="printControls">

            <div class="row">
                <div class="col-md-6">
                    <div id="printersDiv">
                        <label for="printersSelect">Printer:</label><br/>
                        <select class="form-control" id="printersSelect"></select>
                    </div>
                </div>
            </div>

            <div id="printDiv" style="padding-top:20px">
                <button class="btn btn-primary btn-lg" id="printButton">Print QR Code</button>
            </div>

        </div>
    </div>

</div>

</body>

</html>

QRCode.js

// stores loaded label info
var barcodeLabel;

// called when the document loaded
function onload() {
    var printersSelect = document.getElementById('printersSelect');
    var printButton = document.getElementById('printButton');

    // loads all supported printers into a combo box
    function loadPrinters() {
        var printers = dymo.label.framework.getLabelWriterPrinters();
        if (printers.length == 0) {
            alert("No DYMO printers are installed. Install DYMO printers.");
            return;
        }
        console.log("got here: ", printers );

        for (var i = 0; i < printers.length; i++) {
            var printer = printers[i];

            var printerName = printer.name;

            var option = document.createElement('option');
            option.value = printerName;
            option.appendChild(document.createTextNode(printerName));
            printersSelect.appendChild(option);
        }
    }

    printButton.onclick = function () {
            var label_text = 'QRCode Text Here..';

            barcodeLabel.setObjectText('Barcode', label_text);

            // Should Be Printer Name, Dymo 450 Turbo..
            console.log("print: ", printersSelect.value );

            barcodeLabel.print( printersSelect.value );

    }

    function getBarcodeLabelXml() {

        var labelXml = '<?xml version="1.0" encoding="utf-8"?>\
                            <DieCutLabel Version="8.0" Units="twips">\
                                <PaperOrientation>Landscape</PaperOrientation>\
                                <Id>Address</Id>\
                                <PaperName>30252 Address</PaperName>\
                                <DrawCommands>\
                                    <RoundRectangle X="0" Y="0" Width="1581" Height="5040" Rx="270" Ry="270" />\
                                </DrawCommands>\
                                <ObjectInfo>\
                                    <BarcodeObject>\
                                        <Name>Barcode</Name>\
                                        <ForeColor Alpha="255" Red="0" Green="0" Blue="0" />\
                                        <BackColor Alpha="0" Red="255" Green="255" Blue="255" />\
                                        <LinkedObjectName></LinkedObjectName>\
                                        <Rotation>Rotation0</Rotation>\
                                        <IsMirrored>False</IsMirrored>\
                                        <IsVariable>False</IsVariable>\
                                        <Text></Text>\
                                        <Type>QRCode</Type>\
                                        <Size>Small</Size>\
                                        <TextPosition>None</TextPosition>\
                                        <TextFont Family="Arial" Size="8" Bold="False" Italic="False" Underline="False" Strikeout="False" />\
                                        <CheckSumFont Family="Arial" Size="8" Bold="False" Italic="False" Underline="False" Strikeout="False" />\
                                        <TextEmbedding>None</TextEmbedding>\
                                        <ECLevel>0</ECLevel>\
                                        <HorizontalAlignment>Center</HorizontalAlignment>\
                                        <QuietZonesPadding Left="0" Top="300" Right="600" Bottom="0" />\
                                    </BarcodeObject>\
                                    <Bounds X="331" Y="57.9999999999999" Width="2880" Height="1435" />\
                                </ObjectInfo>\
                            </DieCutLabel>';
        return labelXml;
    }

    function loadLabelFromWeb() {
        barcodeLabel = dymo.label.framework.openLabelXml( getBarcodeLabelXml() );
    }

    // Load Labels
    loadLabelFromWeb();

    // load printers list on startup
    loadPrinters();
};

// Run's Dymo Javascript..
dymo.label.framework.init(onload);


问:
Laravel post data through api routes throws 404 not found
I'm trying to send data with ajax (using axios for that) through an api to my controller.

First of all my routes file (/routes/api.php):

```<code>Route::post('/booking/request', 'BookingController@sendMail');
</code>```

I want to send data to this route, so here is my request for that:

```<code>var bookingUrl = baseUrl + 'api/booking/request';

axios.post(bookingUrl, {
    name: "username",
    amount: 2
});
</code>```

And after that, I just want to log this data to see if it got to my controller (app/Http/Controllers/BookingController):

```<code>class BookingController extends Controller
{
    public function sendMail(Request $request)
    {
        Log::info('data: ' . $request->name);

    }
}
</code>```

This doesn't work at all. I just get an error "404 Not Found". I also tried this request with Postman, but same results. Since I can't get more information about what exactly isn't working, I can't fix it. Can someone get me on the right path here?

Edit: So the actual problem was the baseUrl. There was a wrong link behind, so it couldn't work.

答:
axios.post is just a post request, not an API specific request.

Put you route declaration in routes/web.php file

```<code>//web.php
// now the url for post request will be /booking/request
Route::post('/booking/request', 'BookingController@sendMail');
</code>```

and in js

```<code>//JS
var bookingUrl = baseUrl + 'booking/request';

axios.post(bookingUrl, {
    name: "username",
    amount: 2
});
</code>```

If you still need api prefix, add api in route declaration

```<code>Route::post('/api/booking/request', 'BookingController@sendMail');

// or

Route::group(['prefix'=>'api'], function(){
    Route::post('/booking/request', 'BookingController@sendMail');
});
</code>```

Body:
I'm trying to send data with ajax (using axios for that) through an api to my controller.

First of all my routes file (/routes/api.php):

Route::post('/booking/request', 'BookingController@sendMail');

I want to send data to this route, so here is my request for that:

var bookingUrl = baseUrl + 'api/booking/request';

axios.post(bookingUrl, {
    name: "username",
    amount: 2
});

And after that, I just want to log this data to see if it got to my controller (app/Http/Controllers/BookingController):

class BookingController extends Controller
{
    public function sendMail(Request $request)
    {
        Log::info('data: ' . $request->name);

    }
}

This doesn't work at all. I just get an error "404 Not Found". I also tried this request with Postman, but same results. Since I can't get more information about what exactly isn't working, I can't fix it. Can someone get me on the right path here?

Edit: So the actual problem was the baseUrl. There was a wrong link behind, so it couldn't work.

Body:
axios.post is just a post request, not an API specific request.

Put you route declaration in routes/web.php file

//web.php
// now the url for post request will be /booking/request
Route::post('/booking/request', 'BookingController@sendMail');

and in js

//JS
var bookingUrl = baseUrl + 'booking/request';

axios.post(bookingUrl, {
    name: "username",
    amount: 2
});

If you still need api prefix, add api in route declaration

Route::post('/api/booking/request', 'BookingController@sendMail');

// or

Route::group(['prefix'=>'api'], function(){
    Route::post('/booking/request', 'BookingController@sendMail');
});


问:
When using jQuery's click event on a class, how can I avoid calling the event for all with that class name?
I am sorry for the poorly worded question, but if you look at the code, what I am asking is really quite simple.

```<code>$(".toggle").click(function () {
    var togg = $(this).attr( 'id' );
    if( $(this).text() == 'Read More >>' )
    {
        $("." + togg).addClass( "myBlurbExpanded" , 2000 );
        $("." + togg).removeClass( togg , 2000 );
        $(this).text('Read Less >>');
    }
    else if( $(this).text() == 'Read Less >>' )
    {
        $(".myBlurbExpanded").addClass( togg , 2000 );
        $(".myBlurbExpanded").removeClass( "myBlurbExpanded" , 2000 );
        $(this).text('Read More >>');
    }
   });
</code>```

My page has a bunch of biographies on different people next to their picture.  I do not want the entire bio to be visible, so there is a 'show more' and 'show less' link.  The 'show more/less' link has a class of '.toggle'.  So every time this click is executed, all of the biographies expand.  How can I limit the biography expansion to only the one which is clicked.  Am I going about it the wrong way by adding the .toggle class to the link.  Thanks!

Thank you for the responses.

First, here is an example of my html

```<code><div class="teamInfo">
    <h3 class="lightblue">John Doe</h3>
    <p class="lightblue"><strong>Programmer</strong></p>
    <div class="myBlurb8">
      information about this person
    </div>
    <a href="#" onclick="return false;" id="myBlurb8" class="toggle">Read More >></a>
</div>
</code>```

Next, I will try to change . + togg to (this) and see what happens.

Cheers!

答:
You need to assign a variable to the click function's event and then use the event.target instead of this like so:

```<code>$(".toggle").click(function (event) {
    var $target = $(event.target);
    var togg = $target.attr( 'id' );
    if( $target.text() == 'Read More >>' )
    {
        $("." + togg).addClass( "myBlurbExpanded" , 2000 );
        $("." + togg).removeClass( togg , 2000 );
        $target.text('Read Less >>');
    }
    else if( $target.text() == 'Read Less >>' )
    {
        $(".myBlurbExpanded").addClass( togg , 2000 );
        $(".myBlurbExpanded").removeClass( "myBlurbExpanded" , 2000 );
        $target.text('Read More >>');
    }
});
</code>```

Body:
I am sorry for the poorly worded question, but if you look at the code, what I am asking is really quite simple.

$(".toggle").click(function () {
    var togg = $(this).attr( 'id' );
    if( $(this).text() == 'Read More >>' )
    {
        $("." + togg).addClass( "myBlurbExpanded" , 2000 );
        $("." + togg).removeClass( togg , 2000 );
        $(this).text('Read Less >>');
    }
    else if( $(this).text() == 'Read Less >>' )
    {
        $(".myBlurbExpanded").addClass( togg , 2000 );
        $(".myBlurbExpanded").removeClass( "myBlurbExpanded" , 2000 );
        $(this).text('Read More >>');
    }
   });

My page has a bunch of biographies on different people next to their picture.  I do not want the entire bio to be visible, so there is a 'show more' and 'show less' link.  The 'show more/less' link has a class of '.toggle'.  So every time this click is executed, all of the biographies expand.  How can I limit the biography expansion to only the one which is clicked.  Am I going about it the wrong way by adding the .toggle class to the link.  Thanks!

Thank you for the responses.

First, here is an example of my html

John Doe

Programmer

      information about this person

    Read More >>

Next, I will try to change . + togg to (this) and see what happens.

Cheers!

Body:
You need to assign a variable to the click function's event and then use the event.target instead of this like so:

$(".toggle").click(function (event) {
    var $target = $(event.target);
    var togg = $target.attr( 'id' );
    if( $target.text() == 'Read More >>' )
    {
        $("." + togg).addClass( "myBlurbExpanded" , 2000 );
        $("." + togg).removeClass( togg , 2000 );
        $target.text('Read Less >>');
    }
    else if( $target.text() == 'Read Less >>' )
    {
        $(".myBlurbExpanded").addClass( togg , 2000 );
        $(".myBlurbExpanded").removeClass( "myBlurbExpanded" , 2000 );
        $target.text('Read More >>');
    }
});


问:
How to implement tidyr's complete() in SQL?
Using a dummy example, I need to complete a data set with implicit missing values. This is trivial in R using tidyr's function complete.

```<code>library(tidyr)

df <- data.frame(Borough = c('Brooklyn', 'Brooklyn', 'Queens'),
                 Crime = c('Robbery', 'Homicide', 'Drug'),
                 Count=c(1, 2, 1))

> df
   Borough    Crime Count
1 Brooklyn  Robbery     1
2 Brooklyn Homicide     2
3   Queens     Drug     1

#Complete implicit missing values

> complete(df, Borough, Crime, fill=list(Count=0))
   Borough    Crime Count
1 Brooklyn     Drug     0
2 Brooklyn Homicide     2
3 Brooklyn  Robbery     1
4   Queens     Drug     1
5   Queens Homicide     0
6   Queens  Robbery     0
</code>```

But, in the case that the real data very big and is stored in Oracle's SQL table, how could this be done using an SQL query?

答:
Cross join distinct boroughs with crimes and left join the original table to get the missing rows with 0 counts.</p>

```<code>select b.borough,c.crime,coalesce(t.count,0) as count
from (select distinct borough from tbl) b
cross join (select distinct crime from tbl) c
left join tbl t on t.borough=b.borough and t.crime=c.crime
</code>```

Body:
Using a dummy example, I need to complete a data set with implicit missing values. This is trivial in R using tidyr's function complete.

library(tidyr)

df <- data.frame(Borough = c('Brooklyn', 'Brooklyn', 'Queens'),
                 Crime = c('Robbery', 'Homicide', 'Drug'),
                 Count=c(1, 2, 1))

> df
   Borough    Crime Count
1 Brooklyn  Robbery     1
2 Brooklyn Homicide     2
3   Queens     Drug     1

#Complete implicit missing values

> complete(df, Borough, Crime, fill=list(Count=0))
   Borough    Crime Count
1 Brooklyn     Drug     0
2 Brooklyn Homicide     2
3 Brooklyn  Robbery     1
4   Queens     Drug     1
5   Queens Homicide     0
6   Queens  Robbery     0

But, in the case that the real data very big and is stored in Oracle's SQL table, how could this be done using an SQL query?

Body:
Cross join distinct boroughs with crimes and left join the original table to get the missing rows with 0 counts.

select b.borough,c.crime,coalesce(t.count,0) as count
from (select distinct borough from tbl) b
cross join (select distinct crime from tbl) c
left join tbl t on t.borough=b.borough and t.crime=c.crime


问:
How to sum two timespan fields in RDLC
If I have two fields of type System.TimeSpan like this :

```<code>Fields!OverTimeBefore6.Value

Fields!OverTimeAfter6.Value
</code>```

How to sum these fields together in RDLC and the result in same format like this:

```<code>03:04:17
</code>```

Note: I want to sum two or multiple fields not the total of a specific field.

答:
You can use the .Add(...) function of a Timespan.

That is, if you have a textbox in your report you could set the expression to be:

```<code>=System.TimeSpan.FromSeconds(100).Add(System.TimeSpan.FromSeconds(200))
</code>```

and the format to Default, and see the text:

```<code>00:05:00
</code>```

Title: How to sum two timespan fields in RDLC

Body:
If I have two fields of type System.TimeSpan like this :

Fields!OverTimeBefore6.Value

Fields!OverTimeAfter6.Value

How to sum these fields together in RDLC and the result in same format like this:

03:04:17

Note: I want to sum two or multiple fields not the total of a specific field.

Body:
You can use the .Add(...) function of a Timespan.

That is, if you have a textbox in your report you could set the expression to be:

=System.TimeSpan.FromSeconds(100).Add(System.TimeSpan.FromSeconds(200))

and the format to Default, and see the text:

00:05:00


问:
Why isnt my javascript function being run?
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:

```<code> <div class = mainInfo>
    <?php include "header.php"; ?>
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>
    <div id="feedback">
    </div>
 </div>
<script>
function validate()
{
    document.getElementById("feedback").innerHTML = "functionbeingcalled";
    var p1 = document.getElementById("p1").value,
                p2 = document.getElementById("p2").value);
    if( ! p1===p2 )
    {

        document.getElementById("feedback").innerHTML = "passwords dont match";
    }
    if(p1==="")
    {
         document.getElementById("feedback").innerHTML = "Must have a password";
    }
}
window.setInterval(validate(),1000);
</script>

<?php include "footer.php"; ?>
</code>```

I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all.  This line:

```<code> document.getElementById("feedback").innerHTML = "functionbeingcalled";
</code>```

isn't working either.

Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.

答:
Well, you've got several issues...

First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.

You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is:  if(p1 !== p2 ), which is how you express "not strictly equal to".

Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:

just before the entire form is submitted

just after the user leaves a form field

as the user is entering data

some combination of all 3

Each of those scenarios is handled through event handlers and a working example of each is shown below.

// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");

// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");

var form = document.querySelector("form");

// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
  // If validate function returns false, don't submit
  if(!validate()){
    evt.preventDefault(); // cancel the form submission
    feedback.textContent = "Can't submit. Form is not valid!";
  }
});

// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");

// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);

// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
  input.addEventListener("blur", validate);   // Used to validate when user moves off of each element
  input.addEventListener("input", validate);  // Used to validate as data is being entered
});

function validate()  {
  // Keep track of whether the form is valid or not. Assume that it is by default
  var valid = true;

  // .innerHTML is for when you want to assign a string containing
  // HTML to a DOM element. This invokes the HTML parser and renders
  // the HTML. If you don't have HTML in the string, use .textContent
  // instead, which doesn't invoke the HTML parser and is more efficient

  // See if the password was typed in both boxes before telling the user
  // that the passwords don't match
  if(p1.value && p2.value){
    // Are they the same?
    if(p1.value !== p2.value){
      feedback.textContent = "passwords dont match";
      valid = false;
    } else {
      feedback.textContent = "passwords match";
    }
  } else {
    // If both password fields aren't filled in, the form can't be valid
    valid = false;
  }

  if(p1.value === "") {
   feedback.textContent = "Must have a password";
   valid = false;
  }

  // Send a result to the caller so it can be known by other code if the form is valid
  return valid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "mainInfo">
  <form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
    <div>username: <input type="text" name="userName"></div>
    <div>password: <input id="p1" type="password" name="password"></div>
    <div>reenter password:  <input id="p2" type="password" name="passwordConfirmation"></div>

    <!-- Any form element that has a "name" attribute will submit its name/value as
         part of the form data when the form gets submitted. You probably don't want
         the actual submit button to be included in this, so don't give the button
         a "name" attribute. -->
    <input type="submit" value="submit">     <input type="reset" value="reset">
  </form>
  <div id="feedback"></div>
</div></code>```

Body:
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:

    <?php include "header.php"; ?>
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>

<?php include "footer.php"; ?>

I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all.  This line:

 document.getElementById("feedback").innerHTML = "functionbeingcalled";

isn't working either.

Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.

Body:
Well, you've got several issues...

First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.

You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is:  if(p1 !== p2 ), which is how you express "not strictly equal to".

Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:

just before the entire form is submitted

just after the user leaves a form field

as the user is entering data

some combination of all 3

Each of those scenarios is handled through event handlers and a working example of each is shown below.

// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");

// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");

var form = document.querySelector("form");

// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
  // If validate function returns false, don't submit
  if(!validate()){
    evt.preventDefault(); // cancel the form submission
    feedback.textContent = "Can't submit. Form is not valid!";
  }
});

// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");

// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);

// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
  input.addEventListener("blur", validate);   // Used to validate when user moves off of each element
  input.addEventListener("input", validate);  // Used to validate as data is being entered
});

function validate()  {
  // Keep track of whether the form is valid or not. Assume that it is by default
  var valid = true;

  // .innerHTML is for when you want to assign a string containing
  // HTML to a DOM element. This invokes the HTML parser and renders
  // the HTML. If you don't have HTML in the string, use .textContent
  // instead, which doesn't invoke the HTML parser and is more efficient

  // See if the password was typed in both boxes before telling the user
  // that the passwords don't match
  if(p1.value && p2.value){
    // Are they the same?
    if(p1.value !== p2.value){
      feedback.textContent = "passwords dont match";
      valid = false;
    } else {
      feedback.textContent = "passwords match";
    }
  } else {
    // If both password fields aren't filled in, the form can't be valid
    valid = false;
  }

  if(p1.value === "") {
   feedback.textContent = "Must have a password";
   valid = false;
  }

  // Send a result to the caller so it can be known by other code if the form is valid
  return valid;
}

<div class = "mainInfo">
  <form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
    <div>username: <input type="text" name="userName"></div>
    <div>password: <input id="p1" type="password" name="password"></div>
    <div>reenter password:  <input id="p2" type="password" name="passwordConfirmation"></div>

    <!-- Any form element that has a "name" attribute will submit its name/value as
         part of the form data when the form gets submitted. You probably don't want
         the actual submit button to be included in this, so don't give the button
         a "name" attribute. -->
    <input type="submit" value="submit">     <input type="reset" value="reset">
  </form>
  <div id="feedback"></div>
</div>


问:
How to draw animated legend for subplots?
I would like to draw animated subplots with ArtistAnimation. Unfortunately, I cannot figure out how to have an animated legend. I tried out different methods I found on StackOverflow. If I manage to get a legend it is not animated, but just the legends of all animation steps together.

My code looks like this:

```<code>import numpy as np
import pylab as pl
import matplotlib.animation as anim

fig, (ax1, ax2, ax3) = pl.subplots(1,3,figsize=(11,4))
ims   = []
im1   = ['im11','im12','im13']
im2   = ['im21','im22','im23']
x = np.arange(0,2*np.pi,0.1)

n=50
for i in range(n):
    for sp in (1,2,3):
        pl.subplot(1,3,sp)

        y1 = np.sin(sp*x + i*np.pi/n)
        y2 = np.cos(sp*x + i*np.pi/n)

        im1[sp-1], = pl.plot(x,y1)
        im2[sp-1], = pl.plot(x,y2)

        pl.xlim([0,2*np.pi])
        pl.ylim([-1,1])

        lab = 'i='+str(i)+', sp='+str(sp)
        im1[sp-1].set_label([lab])
        pl.legend(loc=2, prop={'size': 6}).draw_frame(False)

    ims.append([ im1[0],im1[1],im1[2], im2[0],im2[1],im2[2] ])

ani = anim.ArtistAnimation(fig,ims,blit=True)
pl.show()
</code>```

I thought this code would be equivalent to the method used here How to add legend/label in python animation but obviously I am missing something.

I also tried to set the labels as suggested in Add a legend for an animation (of Artists) in matplotlib but I do not really understand how to use it for my case. Like this

```<code>im2[sp-1].legend(handles='-', labels=[lab])
</code>```

I get an AttributeError: 'Line2D' object has no attribute 'legend'.

[EDIT]: I did not state it clearly: I would like to have a legend for both lines in the plots.

答:
I do not know what exactly the legend should look like, but I'd imaginge you simply want to let it display the current value of the one line from the current frame. You'd therefore better update the data of the line, instead of plotting 150 new plots.

```<code>import numpy as np
import pylab as plt
import matplotlib.animation as anim

fig, axes = plt.subplots(1,3,figsize=(8,3))
ims   = []
im1   = [ax.plot([],[], label="label")[0] for ax in axes]
im2   = [ax.plot([],[], label="label")[0] for ax in axes]
x = np.arange(0,2*np.pi,0.1)

legs = [ax.legend(loc=2, prop={'size': 6})  for ax in axes]

for ax in axes:
    ax.set_xlim([0,2*np.pi])
    ax.set_ylim([-1,1])
plt.tight_layout()
n=50
def update(i):
    for sp in range(3):
        y1 = np.sin((sp+1)*x + (i)*np.pi/n)
        y2 = np.cos((sp+1)*x + (i)*np.pi/n)

        im1[sp].set_data(x,y1)
        im2[sp].set_data(x,y2)

        lab = 'i='+str(i)+', sp='+str(sp+1)
        legs[sp].texts[0].set_text(lab)
        legs[sp].texts[1].set_text(lab)

    return im1 + im2 +legs

ani = anim.FuncAnimation(fig,update, frames=n,blit=True)
plt.show()
</code>```

Body:
I would like to draw animated subplots with ArtistAnimation. Unfortunately, I cannot figure out how to have an animated legend. I tried out different methods I found on StackOverflow. If I manage to get a legend it is not animated, but just the legends of all animation steps together.

My code looks like this:

import numpy as np
import pylab as pl
import matplotlib.animation as anim

fig, (ax1, ax2, ax3) = pl.subplots(1,3,figsize=(11,4))
ims   = []
im1   = ['im11','im12','im13']
im2   = ['im21','im22','im23']
x = np.arange(0,2*np.pi,0.1)

n=50
for i in range(n):
    for sp in (1,2,3):
        pl.subplot(1,3,sp)

        y1 = np.sin(sp*x + i*np.pi/n)
        y2 = np.cos(sp*x + i*np.pi/n)

        im1[sp-1], = pl.plot(x,y1)
        im2[sp-1], = pl.plot(x,y2)

        pl.xlim([0,2*np.pi])
        pl.ylim([-1,1])

        lab = 'i='+str(i)+', sp='+str(sp)
        im1[sp-1].set_label([lab])
        pl.legend(loc=2, prop={'size': 6}).draw_frame(False)

    ims.append([ im1[0],im1[1],im1[2], im2[0],im2[1],im2[2] ])

ani = anim.ArtistAnimation(fig,ims,blit=True)
pl.show()

I thought this code would be equivalent to the method used here How to add legend/label in python animation but obviously I am missing something.

I also tried to set the labels as suggested in Add a legend for an animation (of Artists) in matplotlib but I do not really understand how to use it for my case. Like this

im2[sp-1].legend(handles='-', labels=[lab])

I get an AttributeError: 'Line2D' object has no attribute 'legend'.

[EDIT]: I did not state it clearly: I would like to have a legend for both lines in the plots.

Body:
I do not know what exactly the legend should look like, but I'd imaginge you simply want to let it display the current value of the one line from the current frame. You'd therefore better update the data of the line, instead of plotting 150 new plots.

import numpy as np
import pylab as plt
import matplotlib.animation as anim

fig, axes = plt.subplots(1,3,figsize=(8,3))
ims   = []
im1   = [ax.plot([],[], label="label")[0] for ax in axes]
im2   = [ax.plot([],[], label="label")[0] for ax in axes]
x = np.arange(0,2*np.pi,0.1)

legs = [ax.legend(loc=2, prop={'size': 6})  for ax in axes]

for ax in axes:
    ax.set_xlim([0,2*np.pi])
    ax.set_ylim([-1,1])
plt.tight_layout()
n=50
def update(i):
    for sp in range(3):
        y1 = np.sin((sp+1)*x + (i)*np.pi/n)
        y2 = np.cos((sp+1)*x + (i)*np.pi/n)

        im1[sp].set_data(x,y1)
        im2[sp].set_data(x,y2)

        lab = 'i='+str(i)+', sp='+str(sp+1)
        legs[sp].texts[0].set_text(lab)
        legs[sp].texts[1].set_text(lab)

    return im1 + im2 +legs

ani = anim.FuncAnimation(fig,update, frames=n,blit=True)
plt.show()


问:
PostgreSQL BEFORE INSERT trigger locking behavior in a concurrent environment
I have a general function that can manipulate the sequence of any table (why is irrelevant to my question). It reads the current value, works out the new value, sets it, and returns its calculation, which is what's inserted. This is obviously a multi-step process.

I call it from a BEFORE INSERT trigger on tables where I need it.

All I need to know is am I guaranteed that the function will be called by only one caller at a time in a multi-user environment?

Specifically, does the BEFORE INSERT trigger have to complete before it is called again by another caller?

Logically, I would assume yes, but one never knows what may be going on under the hood.

If the answer is no, what minimal locking would I need on the function to guarantee I can read and write the sequence in a "thread-safe" manner?

I'm using PG 10.

EDIT

Here is the function updated with a lock:

```<code>CREATE OR REPLACE FUNCTION public.uts_set()
RETURNS TRIGGER AS
$$
DECLARE
  sv        int8;
  seq       text := format('%I.%I_uts_seq', tg_table_schema, tg_table_name);
BEGIN
  EXECUTE   format('LOCK TABLE %I IN ROW EXCLUSIVE MODE;', tg_table_name);
  EXECUTE   'SELECT last_value+1 FROM ' || seq INTO sv; -- currval(seq) isn't useable
  PERFORM   setval(seq, GREATEST(sv, (EXTRACT(epoch FROM localtimestamp) * 1000000)::int8), false);
  RETURN    NULL;
END;
$$ LANGUAGE plpgsql;
</code>```

However, a SELECT already acquires ROW EXCLUSIVE, so this statement may be redundant and a stronger lock may be needed. Or, conversely, it may mean no lock is needed.

UPDATE

If I am reading this SO question correctly, my original version without the LOCK should work since the trigger acquires the same lock my updated function is redundantly taking.

答:
The sequence itself handles thread safety with concurrent sessions.  So it real comes down to the code that is interacting with the sequence.  The following code is thread safe:

```<code>SELECT nextval('myseq');
</code>```

If the sequence is doing much fancier things like setval and currval, I would be more worried about that being done in a high transaction/multi-user environment.  Even so, the sequence itself should be locked from other queries while the sequence is being manipulated.

Body:
I have a general function that can manipulate the sequence of any table (why is irrelevant to my question). It reads the current value, works out the new value, sets it, and returns its calculation, which is what's inserted. This is obviously a multi-step process.

I call it from a BEFORE INSERT trigger on tables where I need it.

All I need to know is am I guaranteed that the function will be called by only one caller at a time in a multi-user environment?

Specifically, does the BEFORE INSERT trigger have to complete before it is called again by another caller?

Logically, I would assume yes, but one never knows what may be going on under the hood.

If the answer is no, what minimal locking would I need on the function to guarantee I can read and write the sequence in a "thread-safe" manner?

I'm using PG 10.

EDIT

Here is the function updated with a lock:

CREATE OR REPLACE FUNCTION public.uts_set()
RETURNS TRIGGER AS
$$
DECLARE
  sv        int8;
  seq       text := format('%I.%I_uts_seq', tg_table_schema, tg_table_name);
BEGIN
  EXECUTE   format('LOCK TABLE %I IN ROW EXCLUSIVE MODE;', tg_table_name);
  EXECUTE   'SELECT last_value+1 FROM ' || seq INTO sv; -- currval(seq) isn't useable
  PERFORM   setval(seq, GREATEST(sv, (EXTRACT(epoch FROM localtimestamp) * 1000000)::int8), false);
  RETURN    NULL;
END;
$$ LANGUAGE plpgsql;

However, a SELECT already acquires ROW EXCLUSIVE, so this statement may be redundant and a stronger lock may be needed. Or, conversely, it may mean no lock is needed.

UPDATE

If I am reading this SO question correctly, my original version without the LOCK should work since the trigger acquires the same lock my updated function is redundantly taking.

Body:
The sequence itself handles thread safety with concurrent sessions.  So it real comes down to the code that is interacting with the sequence.  The following code is thread safe:

SELECT nextval('myseq');

If the sequence is doing much fancier things like setval and currval, I would be more worried about that being done in a high transaction/multi-user environment.  Even so, the sequence itself should be locked from other queries while the sequence is being manipulated.


问:
Automatically delete CloudFormation Stack after a timeout
I have a free tier account and I create stacks to learn how AWS works. Sometimes I forget to delete the stack and it stays on active for days, using up my free tier hours.

Can I make it so every stack I create will be deleted after a certain period of time, for example 1 day? I assume it would be either by adding something to the template or by adding some tag.

答:
TheeCodeDragon seems to have posted an answer with a self-deleting stack which addresses your problem. Here are some other solutions.

Scheduled AutoScaling

If your primary resources are EC2 instances, if you configure them in an autoscaling group and set a schedule for your group to scale to 0. We've done this to make instances vanish on the weekends, after 6:00 PM in our dev environment then scale back up Monday morning so we don't waste money in the dev environment. http://docs.aws.amazon.com/autoscaling/latest/userguide/schedule_time.html#create-sch-actions

Lambda (The Cron of the Cloud)

When management functionality doesn't exist out of the box, 9 out of 10 times you can write a lambda function to run on a schedule to take care of it. You can write a lambda function that runs every 'X' interval or time period and executes a delete-stack on the stack you've configured. Lambda can be set-up via CloudFormation.

Deployment Notes:

I saw your comment about the CLI not being installed by default. Even for dev I use AWS codebuild. A self-managed serverless build tool comparable to Jenkins. If you use it to run your templates the CLI is already installed. The caveat is you need to have it pull your project from source control or s3. I use codecommit because the setup is easy.