问:
Correct Proguard Rules for AWS AppSync with Cognito User Pool Authentication on Android
I have an Android App using the AWS AppSync SDK with the following gradle configuration to connect to a cloud backend.

```<code>implementation 'com.amazonaws:aws-android-sdk-appsync:2.7.+'
</code>```

Access to the backend resources is controlled via Cognito User Pools. User authentication and fetching data from the backend works fine without proguard enabled.
If I enable Proguard I get all sorts of warnings related to the AWS SDK.
The only way I managed to generate a signed APK with proguard enabled was by suppressing all AWS related warnings in the proguard-rules.pro like so:

-dontwarn com.amazonaws.**

When I do this, the generated APK does not authenticate the user and data cannot be retrieved from the backend.
When I try to debug the APK, I get the following error in Android Studio:

```<code>Could not connect to remote process. Aborting debug session.
</code>```

Is there a more fine-grained proguard setting that gets rid of all the warnings but does not mess up the connection to the backend?

答:
The following Proguard configuration did the trick for me:

```<code>-keepnames class com.amazonaws.**
-keepnames class com.amazon.**
# Request handlers defined in request.handlers
-keep class com.amazonaws.services.**.*Handler
# The following are referenced but aren't required to run
-dontwarn com.fasterxml.jackson.**
-dontwarn org.apache.commons.logging.**
# Android 6.0 release removes support for the Apache HTTP client
-dontwarn org.apache.http.**
# The SDK has several references of Apache HTTP client
-dontwarn com.amazonaws.http.**
-dontwarn com.amazonaws.metrics.**
-dontwarn com.amazonaws.mobile.**
-dontwarn com.amazonaws.mobileconnectors.**
</code>```

All warnings disappear and the apk connects to the backend without any issues.

Body:
I have an Android App using the AWS AppSync SDK with the following gradle configuration to connect to a cloud backend.

implementation 'com.amazonaws:aws-android-sdk-appsync:2.7.+'

Access to the backend resources is controlled via Cognito User Pools. User authentication and fetching data from the backend works fine without proguard enabled.
If I enable Proguard I get all sorts of warnings related to the AWS SDK.
The only way I managed to generate a signed APK with proguard enabled was by suppressing all AWS related warnings in the proguard-rules.pro like so:

-dontwarn com.amazonaws.**

When I do this, the generated APK does not authenticate the user and data cannot be retrieved from the backend.
When I try to debug the APK, I get the following error in Android Studio:

Could not connect to remote process. Aborting debug session.

Is there a more fine-grained proguard setting that gets rid of all the warnings but does not mess up the connection to the backend?

Body:
The following Proguard configuration did the trick for me:

-keepnames class com.amazonaws.**
-keepnames class com.amazon.**
# Request handlers defined in request.handlers
-keep class com.amazonaws.services.**.*Handler
# The following are referenced but aren't required to run
-dontwarn com.fasterxml.jackson.**
-dontwarn org.apache.commons.logging.**
# Android 6.0 release removes support for the Apache HTTP client
-dontwarn org.apache.http.**
# The SDK has several references of Apache HTTP client
-dontwarn com.amazonaws.http.**
-dontwarn com.amazonaws.metrics.**
-dontwarn com.amazonaws.mobile.**
-dontwarn com.amazonaws.mobileconnectors.**

All warnings disappear and the apk connects to the backend without any issues.


来源: stackexchange

问:
Distribute Time over milliseconds for a smooth curve
I have a dataframe in which one column contains datetime. The datetime is till seconds. I need to automatically add milliseconds to the seconds as I have multiple values for each second value.
For example- Feb 21, 2019 3:50:41 PM, I have this time stamp for 35 times. If I can add milliseconds to this time stamp so when I will plot the curve it will be a smooth one. and every second value has a different number of instances.</p>

ContentLicense: CC BY-SA 4.0

Body:
You can try groupby to modify the date

df = pd.DataFrame({'date': pd.to_datetime(['Feb 21, 2019 3:50:41 PM']*35 +
                                          ['Feb 21, 2019 3:50:42 PM']*100),
                        'val': np.linspace(0,1,135)})

def time_shift(s):
    count = len(s)
    deltas = pd.timedelta_range('0ms', '1000ms',
                                periods=count+1, closed='left')
    return s + deltas

df.date = df.groupby(['date']).date.transform(time_shift)

plt.plot(df.date, df.val)

Plot of original dataframe:

Plot after scaling by milliseconds:

Dataframe after shift:

df.tail(5)

+-----+-------------------------------+----------+
|     | date                          |      val |
|-----+-------------------------------+----------|
| 130 | 2019-02-21 15:50:42.959595959 | 0.970149 |
| 131 | 2019-02-21 15:50:42.969696969 | 0.977612 |
| 132 | 2019-02-21 15:50:42.979797979 | 0.985075 |
| 133 | 2019-02-21 15:50:42.989898989 | 0.992537 |
| 134 | 2019-02-21 15:50:43           | 1        |
+-----+-------------------------------+----------+


问:
How to call helper in Haml file
How do I call a method in a helper from a Haml file?

In sample.haml, I need to call the show_message method depending on some condition. Then I moved the method to the helper, but the returned value from the method is treated as just a string, not a Haml element.

This is sample.haml:

```<code>- flash.each do |msg|
  - if msg.is_a?(Array)
    - msg.each do |m|
      = show_message(m)
  - if msg.is_a?(String)
    = show_message(msg)
</code>```

This is helper.rb:

```<code>  def show_message(msg)
    haml = <<-HAML
    %div{class: some_class}
      = content_tag :div, #{msg}, id: "id"
    HAML
  end
</code>```

If I write the same HTML element in show_message in sample.html directly, it works properly. How can I solve this?

答:
Your helper method needs to construct the full HTML via methods. Since it's not actually part of the HAML, you cannot rely on syntax like %div{class: some_class}. Something like this:

```<code>def show_message(msg)
  content_tag(:div, class: 'some_class') do
    content_tag(:div, msg, id: "id")
  end
end
</code>```

See the content_tag  documentation for more usage examples.

Title: How to call helper in Haml file

Body:
How do I call a method in a helper from a Haml file?

In sample.haml, I need to call the show_message method depending on some condition. Then I moved the method to the helper, but the returned value from the method is treated as just a string, not a Haml element.

This is sample.haml:

- flash.each do |msg|
  - if msg.is_a?(Array)
    - msg.each do |m|
      = show_message(m)
  - if msg.is_a?(String)
    = show_message(msg)

This is helper.rb:

  def show_message(msg)
    haml = <<-HAML
    %div{class: some_class}
      = content_tag :div, #{msg}, id: "id"
    HAML
  end

If I write the same HTML element in show_message in sample.html directly, it works properly. How can I solve this?

Body:
Your helper method needs to construct the full HTML via methods. Since it's not actually part of the HAML, you cannot rely on syntax like %div{class: some_class}. Something like this:

def show_message(msg)
  content_tag(:div, class: 'some_class') do
    content_tag(:div, msg, id: "id")
  end
end

See the content_tag  documentation for more usage examples.


问:
How to use "Net::http" in Coro?
Got stuck on using Net::HTTP
when i create a Net::HTTP object it initialize with "IO::Socket::IP".
how can i change default socket without hard-coding? I would like to change it to IO::Socket::INET.

So if i hard-code socket, it works.
But when i'm trying to use Coro::LWP and Coro::LWP changes IO::Socket::INET to Coro::Socket i got error:

Status read failed: Transport endpoint is not connected at perl5/lib/perl5/Net/HTTP/Methods.pm line 282.

I need to change socket because Clickhouse module on cpan doesn't support async requests.

here is code that doesn't work

```<code>use IO::Socket::INET qw( );
BEGIN { $Net::HTTP::SOCKET_CLASS = 'IO::Socket::INET'; };
use Coro::LWP;
my $s = Net::HTTP->new(Host => "www.perl.com") || die $@;
$s->write_request(GET => "/");
print $_ for ( $s->read_response_headers );
</code>```

fixed!
just change Coro::Socket with Coro::PatchSet::Socket

答:
You can't use IO::Socket::INET or IO::Socket::IP with Coro. Coro is a co-operative multi-threading system, so it only works with co-operating modules, and neither of these modules are Coro-aware. (By "work", I mean allow threads and asynchronous operations to progress.)

Among other things, Coro::LWP specifically makes Net::HTTP use Coro::LWP::Socket instead of IO::Socket::INET. Your attempts to make Net::HTTP use IO::Socket::IP are counter-productive.

You said you're switching the module because Clickhouse (by which I presume you meant ClickHouse) doesn't support async requests, but replacing IO::Socket::INET with IO::Socket::IP doesn't help with that at all.

Have you looked at AnyEvent::ClickHouse?

Title: How to use "Net::http" in Coro?

Body:
Got stuck on using Net::HTTP
when i create a Net::HTTP object it initialize with "IO::Socket::IP".
how can i change default socket without hard-coding? I would like to change it to IO::Socket::INET.

So if i hard-code socket, it works.
But when i'm trying to use Coro::LWP and Coro::LWP changes IO::Socket::INET to Coro::Socket i got error:

Status read failed: Transport endpoint is not connected at perl5/lib/perl5/Net/HTTP/Methods.pm line 282.

I need to change socket because Clickhouse module on cpan doesn't support async requests.

here is code that doesn't work

use IO::Socket::INET qw( );
BEGIN { $Net::HTTP::SOCKET_CLASS = 'IO::Socket::INET'; };
use Coro::LWP;
my $s = Net::HTTP->new(Host => "www.perl.com") || die $@;
$s->write_request(GET => "/");
print $_ for ( $s->read_response_headers );

fixed!
just change Coro::Socket with Coro::PatchSet::Socket


问:
Access Reading Violation when writing a DICOM with vtkDICOMWriter
I'm trying to write vtkImageData as a DICOM. I keep getting an "Access Reading Violation" when I try to write the image.

Unhandled exception at 0x00007FFDA30ECA50 : 0xC0000005: Access violation reading location 0x000001BD38D5C000

Here is my code:

```<code>vtkSmartPointer<vtkDICOMWriter> dcmWriter = vtkSmartPointer<vtkDICOMWriter>::New();
dcmWriter->SetInputData(testDat);
dcmWriter->SetFileName(fullPath.toStdString().c_str());
dcmWriter->Update(); // this line breaks
dcmWriter->Write();
</code>```

testDat is a vtkSmartPointer<vtkImageData> type and has data in it. Any thoughts on whats causing the error? I can't find anything similar online.

I followed this example: https://github.com/dgobbi/vtk-dicom/blob/master/Examples/TestDICOMWriter.cxx

I don't have metadata, but that shouldn't be a problem.

答:
I need to make some guesses here because you didn't post all of your code, but I suspect that the problem happens in the following line:

```<code>dcmWriter->SetFileName(fullPath.toStdString().c_str());
</code>```

toStdString() is most probably returning a temporary std::string (fullPath looks like a Qt QString), on which you call c_str(). After the statement, your temporary is destroyed and whatever you have passed to SetFileName is now a dangling pointer. Hence the segfault.

Try the following instead::

```<code>const auto pathString = fullPath.toStdString();
dcmWriter->SetFileName(pathString.c_str());
</code>```

This should hopefully work fine. Even if not, it definitely is an issue with your code.

Body:
I'm trying to write vtkImageData as a DICOM. I keep getting an "Access Reading Violation" when I try to write the image.

Unhandled exception at 0x00007FFDA30ECA50 : 0xC0000005: Access violation reading location 0x000001BD38D5C000

Here is my code:

vtkSmartPointer<vtkDICOMWriter> dcmWriter = vtkSmartPointer<vtkDICOMWriter>::New();
dcmWriter->SetInputData(testDat);
dcmWriter->SetFileName(fullPath.toStdString().c_str());
dcmWriter->Update(); // this line breaks
dcmWriter->Write();

testDat is a vtkSmartPointer<vtkImageData> type and has data in it. Any thoughts on whats causing the error? I can't find anything similar online.

I followed this example: https://github.com/dgobbi/vtk-dicom/blob/master/Examples/TestDICOMWriter.cxx

I don't have metadata, but that shouldn't be a problem.

Body:
I need to make some guesses here because you didn't post all of your code, but I suspect that the problem happens in the following line:

dcmWriter->SetFileName(fullPath.toStdString().c_str());

toStdString() is most probably returning a temporary std::string (fullPath looks like a Qt QString), on which you call c_str(). After the statement, your temporary is destroyed and whatever you have passed to SetFileName is now a dangling pointer. Hence the segfault.

Try the following instead::

const auto pathString = fullPath.toStdString();
dcmWriter->SetFileName(pathString.c_str());

This should hopefully work fine. Even if not, it definitely is an issue with your code.


问:
Linux a long shell command with pipe operation
This is my command.

ssh username@hostname "cd /usr ; echo \"password\" | sudo -S tar cpf - . --ignore-failed-read" | tar xpf - -C /usr

The problem is that the latter tar command needs sudo, so if I change my code like
ssh username@hostname "cd /usr ; echo \"password\" | sudo -S tar cpf - . --ignore-failed-read" | sudo tar xpf - -C /usr。But I want to run it automatically, this case is not what I want.

If I change command to

ssh username@hostname "cd /usr ; echo \"password\" | sudo -S tar cpf - . --ignore-failed-read" | echo "password" | sudo -S tar xpf - -C /usr。In this case I can not get the former tar data flow。

So how can I simultaneously get the former tar data flow and give sudo to my latter tar command?

PS: I don't want to create actual tar file。I want it compress and uncompress on the fly.

Anyone can help me? Thank you very much~!

答:
Pipe the data to a fifo, read the password from stdin:</p>

```<code>trap 'rm -f /tmp/fifo' 0
mkfifo /tmp/fifo
ssh username@hostname 'cd /usr ; echo "password" |
     sudo -S tar cpf - . --ignore-failed-read' > /tmp/fifo &
echo "${password?}" | sudo -S sh -c 'tar xpf - -C /usr < /tmp/fifo'
</code>```

Body:
Pipe the data to a fifo, read the password from stdin:

trap 'rm -f /tmp/fifo' 0
mkfifo /tmp/fifo
ssh username@hostname 'cd /usr ; echo "password" |
     sudo -S tar cpf - . --ignore-failed-read' > /tmp/fifo &
echo "${password?}" | sudo -S sh -c 'tar xpf - -C /usr < /tmp/fifo'


问:
How can I access methods inside a class from outside of class
I have a couple questions regarding Class files. I have the below Class

```<code>class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }
</code>```

my problem is how can I go and access the doSomeQuery function from outside the class file? Inside there is no issue accessing the function but I need to be able to call it from outside.
I tried something like this

```<code>const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController
</code>```

doing so newTest never exposes the doSomeQuery method.

Also what are the limitations of a method ? Can it only be a simple one or can it be async and use promises etc ?

答:
You need to instantiate the class after importing it

Change the following

```<code>const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController
</code>```

to

```<code>const CouchController = require("../controllers/CouchController")
let newTest = new CouchController(couchbase, config)
</code>```

Also you need to export your class like this

export default class CouchController {

and then access method like this

newTest.doSomeQuery(...)

Body:
I have a couple questions regarding Class files. I have the below Class

class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }

my problem is how can I go and access the doSomeQuery function from outside the class file? Inside there is no issue accessing the function but I need to be able to call it from outside.
I tried something like this

const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController

doing so newTest never exposes the doSomeQuery method.

Also what are the limitations of a method ? Can it only be a simple one or can it be async and use promises etc ?

Body:
You need to instantiate the class after importing it

Change the following

const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController

to

const CouchController = require("../controllers/CouchController")
let newTest = new CouchController(couchbase, config)

Also you need to export your class like this

export default class CouchController {

and then access method like this

newTest.doSomeQuery(...)


问:
ssh user@pc 'source ~/.bashrc;printenv' doesn't source bashrc?
passing commands through ssh , but path not found due to the sourcing issue. no change after source. Some machines it works fine.

ssh user@pc 'source ~/.bashrc;printenv'

```<code>SSH_CONNECTION=192.168.5.249 59060 192.168.5.248 22
LANG=en_IN
XDG_SESSION_ID=57
USER=hadoop
PWD=/home/hadoop
HOME=/home/hadoop
SSH_CLIENT=192.168.5.249 59060 22
MAIL=/var/mail/hadoop
SHELL=/bin/bash
SHLVL=1
LANGUAGE=en_IN:en
LOGNAME=hadoop
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1001/bus
XDG_RUNTIME_DIR=/run/user/1001

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
_=/usr/bin/printenv
</code>```

bashrc in user home not loaded even though it is passed.

答:
just moving the path to bash profile then source.

```<code>ssh user@pc 'source ~/.bash_profile;printenv'
</code>```

This worked for me.

Body:
passing commands through ssh , but path not found due to the sourcing issue. no change after source. Some machines it works fine.

ssh user@pc 'source ~/.bashrc;printenv'

SSH_CONNECTION=192.168.5.249 59060 192.168.5.248 22
LANG=en_IN
XDG_SESSION_ID=57
USER=hadoop
PWD=/home/hadoop
HOME=/home/hadoop
SSH_CLIENT=192.168.5.249 59060 22
MAIL=/var/mail/hadoop
SHELL=/bin/bash
SHLVL=1
LANGUAGE=en_IN:en
LOGNAME=hadoop
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1001/bus
XDG_RUNTIME_DIR=/run/user/1001

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
_=/usr/bin/printenv

bashrc in user home not loaded even though it is passed.

Body:
just moving the path to bash profile then source.

ssh user@pc 'source ~/.bash_profile;printenv'

This worked for me.


问:
How can I view the visual graph representation of the nodes created from a Neo4J Java Application?
I'm working with NEO4J and Java to create a prototype for an application that integrates a graph database that holds patient information (with fake, made up data).

I've created a simple two class program, and created nodes (haven't assigned relationships yet). However, I want to be able to view the nodes that I've created in order to make sure that my application is working properly, and to be able to see the results in the NEO4J Browser / Community Server.

How can I get the nodes to appear visually? I know I could test the fact that they're being created by querying them, but I also want to know how to visually display them.

What I've tried to do is go into the Neo4j.conf file, and change the active database from the default "graph.db" to "Users/andrew/eclipse-workspace/patients-database/target/patient-db", since in the Java class I've created, I use this line of code to set my database:

```<code>private static final File Patient_DB = new File("target/patient-db");
</code>```

However, whenever I open the NEO4J browser at localhost:7474, after running my code there are no nodes visible.

Below, I'll paste the code to my PatientGraph class (the other class is just a Patient class that creates the Patients and their attributes)

```<code>package com.andrewhe.neo4j.Patients_Database;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.io.fs.FileUtils;

public class PatientGraph {
    private static final File Patient_DB = new File("target/patient-db");
    private ArrayList<Patient> patients = new ArrayList<Patient>();
    private long patientZero;
    private GraphDatabaseService graphDb;

    public ArrayList<Patient> getPatients() { return patients; }

    public void manualPatientSetUp() throws IOException {
        Patient homeNode = new Patient("");
        Patient jan = new Patient("Jan");
        patients.add(jan);
        Patient kim = new Patient("Kim");
        patients.add(kim);
        Patient ahmad = new Patient("Ahmad");
        patients.add(ahmad);
        Patient andrew = new Patient("Andrew");
        patients.add(andrew);
    }

    public void createPatientNodes() throws IOException {
        FileUtils.deleteRecursively(Patient_DB);
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(Patient_DB);
        registerShutdownHook();

        try (Transaction tx = graphDb.beginTx()) {
            for (Patient patient : patients) {
                Node patientNode = graphDb.createNode();
                System.out.println("Node created");
                setProperties(patientNode, patient);
            }
            tx.success();
        }
    }

    //Method to create and set properties for node instead of using 5 set properties each time.
    public void setProperties(Node node, Patient patient) {
        node.setProperty("name", patient.getName());
        node.setProperty("weight", patient.getWeight());
        node.setProperty("pat_id", new String(patient.getPatientID()));
        node.setProperty("age", patient.getAge());
        //Don't worry about diagnoses yet;
        //To get it to work, just turn the diagnoses ArrayList into a String separated by commas.
    }

    public void setUp() throws IOException {
        //reads in patients using a file
    }

    public void shutdown()
    {
        graphDb.shutdown();
    }

    private void registerShutdownHook()
    {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running example before it's completed)
        Runtime.getRuntime().addShutdownHook(new Thread(() -> graphDb.shutdown()));
    }

    public static void main(String[] args) throws IOException {
        PatientGraph pg = new PatientGraph();

        pg.manualPatientSetUp();
        pg.createPatientNodes();
        for (int i = 0; i < pg.getPatients().size(); i++) {
            pg.getPatients().get(i).printAllData();
        }
        pg.shutdown();
    }
}
</code>```

答:
You did not provide sufficient information about how you are querying the nodes. You did not even elaborate as to what you are classes do in a brief detail before actually pasting the entire class contents. What is the relationship between these classes? Expecting someone to decode this for you from the code, is asking for too much.

You could use Neo4J Browser (comes built-in) or Neo4J Bloom (commercial tool) to visualize the graph nodes and their interconnections (relations).

To query a Neo4j database you can use Cypher, a pictorial graph query language, that represents patterns as Ascii Art.

A detailed Hands-On procedure for querying and visualizing the Graph Nodes is given in the article below.

https://medium.com/neo4j/hands-on-graph-data-visualization-bd1f055a492d

Body:
I'm working with NEO4J and Java to create a prototype for an application that integrates a graph database that holds patient information (with fake, made up data).

I've created a simple two class program, and created nodes (haven't assigned relationships yet). However, I want to be able to view the nodes that I've created in order to make sure that my application is working properly, and to be able to see the results in the NEO4J Browser / Community Server.

How can I get the nodes to appear visually? I know I could test the fact that they're being created by querying them, but I also want to know how to visually display them.

What I've tried to do is go into the Neo4j.conf file, and change the active database from the default "graph.db" to "Users/andrew/eclipse-workspace/patients-database/target/patient-db", since in the Java class I've created, I use this line of code to set my database:

private static final File Patient_DB = new File("target/patient-db");

However, whenever I open the NEO4J browser at localhost:7474, after running my code there are no nodes visible.

Below, I'll paste the code to my PatientGraph class (the other class is just a Patient class that creates the Patients and their attributes)

package com.andrewhe.neo4j.Patients_Database;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.io.fs.FileUtils;

public class PatientGraph {
    private static final File Patient_DB = new File("target/patient-db");
    private ArrayList<Patient> patients = new ArrayList<Patient>();
    private long patientZero;
    private GraphDatabaseService graphDb;

    public ArrayList<Patient> getPatients() { return patients; }

    public void manualPatientSetUp() throws IOException {
        Patient homeNode = new Patient("");
        Patient jan = new Patient("Jan");
        patients.add(jan);
        Patient kim = new Patient("Kim");
        patients.add(kim);
        Patient ahmad = new Patient("Ahmad");
        patients.add(ahmad);
        Patient andrew = new Patient("Andrew");
        patients.add(andrew);
    }

    public void createPatientNodes() throws IOException {
        FileUtils.deleteRecursively(Patient_DB);
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(Patient_DB);
        registerShutdownHook();

        try (Transaction tx = graphDb.beginTx()) {
            for (Patient patient : patients) {
                Node patientNode = graphDb.createNode();
                System.out.println("Node created");
                setProperties(patientNode, patient);
            }
            tx.success();
        }
    }

    //Method to create and set properties for node instead of using 5 set properties each time.
    public void setProperties(Node node, Patient patient) {
        node.setProperty("name", patient.getName());
        node.setProperty("weight", patient.getWeight());
        node.setProperty("pat_id", new String(patient.getPatientID()));
        node.setProperty("age", patient.getAge());
        //Don't worry about diagnoses yet;
        //To get it to work, just turn the diagnoses ArrayList into a String separated by commas.
    }

    public void setUp() throws IOException {
        //reads in patients using a file
    }

    public void shutdown()
    {
        graphDb.shutdown();
    }

    private void registerShutdownHook()
    {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running example before it's completed)
        Runtime.getRuntime().addShutdownHook(new Thread(() -> graphDb.shutdown()));
    }

    public static void main(String[] args) throws IOException {
        PatientGraph pg = new PatientGraph();

        pg.manualPatientSetUp();
        pg.createPatientNodes();
        for (int i = 0; i < pg.getPatients().size(); i++) {
            pg.getPatients().get(i).printAllData();
        }
        pg.shutdown();
    }
}


问:
List subscriptions for a given Azure account
I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-

from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

```

It is supposed to return a list of subscriptions.
However, I see only empty list returned every time I try the above code.
Can anybody help?

答:
I think I solved the issue using Azure CLI. Yet, I still wonder why it didn't work as supposed using azure-python-sdk.

Here is the code:

```<code>import subprocess
import json
subscriptions = json.loads(subprocess.check_output('az account list', shell=True).decode('utf-8'))
print(subscriptions)
</code>```

Thank you for your responses.

Body:
I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-

from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

It is supposed to return a list of subscriptions.
However, I see only empty list returned every time I try the above code.
Can anybody help?

Body:
I think I solved the issue using Azure CLI. Yet, I still wonder why it didn't work as supposed using azure-python-sdk.

Here is the code:

import subprocess
import json
subscriptions = json.loads(subprocess.check_output('az account list', shell=True).decode('utf-8'))
print(subscriptions)

Thank you for your responses.


问:
If statement does not work when comparing two integers
I'am trying to make a python sort-of calculator that allows for any amount of digits to be entered and it checks if every second "word" is an operator, but when comparing the length of the sum and the index of the "word" it is currently checking to see if it should print the output, but it does not even though the 2 integers are the same.

```<code>operators = ["+", "-", "/", "*"]

def doSum(sum):
    split = sum.split()
    target = len(split)
    if split[1] in operators and "=" not in "".join(split):
        for WORD in split:
            if split.index(WORD) % 2 != 0:
                if WORD in operators:
                    if int(split.index(WORD)) == int(target):
                        print(eval("".join(split)))
                    else:
                        print(target)
                        print(len(split))
                        print("-=-=-=-=-=-=-=-=-=-=-=-")

doSum("1 + 2")
doSum("3 + 3")
doSum("8 - 4")
doSum("1 + 3 + 3 - 1")
</code>```

The problem lines are lines 10 - 15.
I expected the output to be:
    3
    6
    4
    6
But I got:

```<code>3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
</code>```

from the "else block" I use for debugging

Edit:

Thank you @chepner for providing the answer in a comment:

"Your if condition is never true because the indices of split run from 0 to len(split) - 1, and target == len(split)."

Body:
I'am trying to make a python sort-of calculator that allows for any amount of digits to be entered and it checks if every second "word" is an operator, but when comparing the length of the sum and the index of the "word" it is currently checking to see if it should print the output, but it does not even though the 2 integers are the same.

operators = ["+", "-", "/", "*"]

def doSum(sum):
    split = sum.split()
    target = len(split)
    if split[1] in operators and "=" not in "".join(split):
        for WORD in split:
            if split.index(WORD) % 2 != 0:
                if WORD in operators:
                    if int(split.index(WORD)) == int(target):
                        print(eval("".join(split)))
                    else:
                        print(target)
                        print(len(split))
                        print("-=-=-=-=-=-=-=-=-=-=-=-")

doSum("1 + 2")
doSum("3 + 3")
doSum("8 - 4")
doSum("1 + 3 + 3 - 1")

The problem lines are lines 10 - 15.
I expected the output to be:
    3
    6
    4
    6
But I got:

3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-

from the "else block" I use for debugging

Edit:

Thank you @chepner for providing the answer in a comment:

"Your if condition is never true because the indices of split run from 0 to len(split) - 1, and target == len(split)."

Body:
Try this,

import ast

>>> def doSum(sum1):
    print(ast.literal_eval(sum1))
    print('-=-=-=-=-=-=-=-=-=-=-=-')

>>> doSum("1 + 2")
3
-=-=-=-=-=-=-=-=-=-=-=-
>>> doSum("3 + 3")
6
-=-=-=-=-=-=-=-=-=-=-=-
>>> doSum("8 - 4")
4
-=-=-=-=-=-=-=-=-=-=-=-
>>> doSum("1 + 3 + 3 - 1")
6
-=-=-=-=-=-=-=-=-=-=-=-


问:
Any Bazel document to help migrate from an older version to newer version?
I am using Bazel 19 and I want to migrate to latest version 26. Looks like lot of things have changed and it is hard to figure out all changes from the release notes. Is there any document/tools that can help with migrating from older version to newer version</p>

答:
The simplest approach, in my opinion, is to incrementally update from 19 to 20, 20 to 21, and so on.

If you use bazelisk, version switching is easy:

USE_BAZEL_VERSION=0.19.0 bazelisk test //...

Fix breakages

Increment version and test: USE_BAZEL_VERSION=0.20.0 bazelisk test //...

Go back to 2.


问:
How to fix "Could not find method" error?
I'm working on home work on Android studio, every thing was Ok, and I shut down my pc till next day, when i opened android studio i found this error message

ERROR: Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13-beta-3'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.0.0-alpha1'

    // Displaying images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'

    // Realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}
</code>```

答:
Build file App Level :

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.example.appname"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//Add others below

}
</code>```

Build file for Project Level :

```<code>buildscript {

  repositories {
    google()
    jcenter()

    maven {
        url 'https://maven.fabric.io/public'
    }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

  }
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
  delete rootProject.buildDir
}
</code>```

After having the same as above, you perform clean and then rebuild.

Body:
I'm working on home work on Android studio, every thing was Ok, and I shut down my pc till next day, when i opened android studio i found this error message

ERROR: Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13-beta-3'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.0.0-alpha1'

    // Displaying images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'

    // Realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}

Body:
Build file App Level :

apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.example.appname"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//Add others below

}

Build file for Project Level :

buildscript {

  repositories {
    google()
    jcenter()

    maven {
        url 'https://maven.fabric.io/public'
    }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

  }
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
  delete rootProject.buildDir
}

After having the same as above, you perform clean and then rebuild.


问:
Adding the last two elements of a list
In Mathematica, what is the cleanest way of taking a list

```<code>{r1, r2, r3, ..., rn, a, b}
</code>```

and returning

```<code>{r1, r2, r3, ..., rn, a + b}
</code>```

or more generally

```<code>{r1, r2, r3, ..., rn, f[a, b]}
</code>```

for some function f?

答:
Here is my take on it:

```<code>addLastTwo = Function[Append[Drop[#, -2], Total[Take[#, -2]]]];

In[225]:= addLastTwo[{r1, r2, r3, r4, r5}]

Out[225]= {r1, r2, r3, r4 + r5}
</code>```

This is slightly faster than Mr.Wizard's solution, although less general:

```<code>In[226]:= Do[addLastTwo@a, {10000}] // Timing

Out[226]= {0.25, Null}

In[227]:= Do[combineLast[a, Plus], {10000}] // Timing

Out[227]= {0.39, Null}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding the last two elements of a list

Body:
In Mathematica, what is the cleanest way of taking a list

{r1, r2, r3, ..., rn, a, b}

and returning

{r1, r2, r3, ..., rn, a + b}

or more generally

{r1, r2, r3, ..., rn, f[a, b]}

for some function f?

Body:
Here is my take on it:

addLastTwo = Function[Append[Drop[#, -2], Total[Take[#, -2]]]];

In[225]:= addLastTwo[{r1, r2, r3, r4, r5}]

Out[225]= {r1, r2, r3, r4 + r5}

This is slightly faster than Mr.Wizard's solution, although less general:

In[226]:= Do[addLastTwo@a, {10000}] // Timing

Out[226]= {0.25, Null}

In[227]:= Do[combineLast[a, Plus], {10000}] // Timing

Out[227]= {0.39, Null}


问:
How to stop a function that is set to an interval instantly
I am currently working on a controller for an RGB LED strip and writing on the effects, but I have the problem where I cannot stop the effects instantly.

I've already tried the following, but that doesn't stop the effect right where it is. It only stops the effect after it's completed.

```<code>function jump3() {
  rgb.red = 255
  rgb.green = 0
  rgb.blue = 0

  socket.emit("rgbLed", rgb)

  var step1 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 255
    rgb.blue = 0
    socket.emit("rgbLed", rgb)
  }, 1000);

  var step2 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 0
    rgb.blue = 255
    socket.emit("rgbLed", rgb)
  }, 2000);
}
</code>```

What I've tried:

```<code>function jump3() {
  if (stopEffect == 1) {
    clearTimeout(step1)
    clearTimeout(step2)
    stopEffect = 0
    return
  }
  rgb.red = 255
  rgb.green = 0
  rgb.blue = 0

  socket.emit("rgbLed", rgb)

  var step1 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 255
    rgb.blue = 0
    socket.emit("rgbLed", rgb)
  }, 1000);

  var step2 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 0
    rgb.blue = 255
    socket.emit("rgbLed", rgb)
  }, 2000);
}
</code>```

答:
Try to place the declaration of the timer-variables outside the function.

var stopAction = false;
var timer = false;

function action() {
  if (stopAction) {
    clearTimeout(timer);
    stopAction = false;
    return;
  }
  timer = setTimeout(function(){
    let output = document.getElementById('output');
    output.textContent = output.textContent + 'StackOverflow! ';
  }, 1000);
}

document.getElementById('start').addEventListener('click', action);
document.getElementById('stop').addEventListener('click', function(){
  stopAction = true;
  action();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button id="start">Start</button>
  <button id="stop">Stop</button>
</div>
<div id="output"></div></code>```

Body:
I am currently working on a controller for an RGB LED strip and writing on the effects, but I have the problem where I cannot stop the effects instantly.

I've already tried the following, but that doesn't stop the effect right where it is. It only stops the effect after it's completed.

function jump3() {
  rgb.red = 255
  rgb.green = 0
  rgb.blue = 0

  socket.emit("rgbLed", rgb)

  var step1 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 255
    rgb.blue = 0
    socket.emit("rgbLed", rgb)
  }, 1000);

  var step2 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 0
    rgb.blue = 255
    socket.emit("rgbLed", rgb)
  }, 2000);
}

What I've tried:

function jump3() {
  if (stopEffect == 1) {
    clearTimeout(step1)
    clearTimeout(step2)
    stopEffect = 0
    return
  }
  rgb.red = 255
  rgb.green = 0
  rgb.blue = 0

  socket.emit("rgbLed", rgb)

  var step1 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 255
    rgb.blue = 0
    socket.emit("rgbLed", rgb)
  }, 1000);

  var step2 = setTimeout(() => {
    rgb.red = 0
    rgb.green = 0
    rgb.blue = 255
    socket.emit("rgbLed", rgb)
  }, 2000);
}

Body:
Try to place the declaration of the timer-variables outside the function.

var stopAction = false;
var timer = false;

function action() {
  if (stopAction) {
    clearTimeout(timer);
    stopAction = false;
    return;
  }
  timer = setTimeout(function(){
    let output = document.getElementById('output');
    output.textContent = output.textContent + 'StackOverflow! ';
  }, 1000);
}

document.getElementById('start').addEventListener('click', action);
document.getElementById('stop').addEventListener('click', function(){
  stopAction = true;
  action();
});

<div>
  <button id="start">Start</button>
  <button id="stop">Stop</button>
</div>
<div id="output"></div>


问:
Python - Extract yyyyMMddhhmmss from file using Regex
I am trying to get the date (format is yyyymmddhhmmss) from a string using Regex but I cannot find the pattern to use.

I am trying with the code below:

```<code>import re
string = "date file /20190529050003/folder "
regex = re.compile(r'\b\d{4}\d{2}\d{2}\s\d{2}\d{2}\d{2}\b')
result = regex.findall(string)[0],
print(result)
</code>```

But I am getting the following error:

```<code>result = regex.findall(string)[0],
IndexError: list index out of range
</code>```

How can I use regex to return "20190529050003" from the string that I have on my script?

Thanks!

答:
Your regex pattern is off, because there is no space in the target timestamp.  Here is one simple way to perform your search:

```<code>string = "date file /20190529050003/folder "
matches = re.findall(r'\b\d{14}\b', string)
print(matches)
</code>```

This prints:

```<code>['20190529050003']
</code>```

We could try to make the pattern more targeted, and e.g. only allow valid values for the hours, minutes, etc. fields.  But, that would be a lot more work, and if you don't expect to see any 14 digit numbers in your text which are not timestamps, then I suggest eschewing making the pattern more complicated than it has to be.

Body:
I am trying to get the date (format is yyyymmddhhmmss) from a string using Regex but I cannot find the pattern to use.

I am trying with the code below:

import re
string = "date file /20190529050003/folder "
regex = re.compile(r'\b\d{4}\d{2}\d{2}\s\d{2}\d{2}\d{2}\b')
result = regex.findall(string)[0],
print(result)

But I am getting the following error:

result = regex.findall(string)[0],
IndexError: list index out of range

How can I use regex to return "20190529050003" from the string that I have on my script?

Thanks!

Body:
Your regex pattern is off, because there is no space in the target timestamp.  Here is one simple way to perform your search:

string = "date file /20190529050003/folder "
matches = re.findall(r'\b\d{14}\b', string)
print(matches)

This prints:

['20190529050003']

We could try to make the pattern more targeted, and e.g. only allow valid values for the hours, minutes, etc. fields.  But, that would be a lot more work, and if you don't expect to see any 14 digit numbers in your text which are not timestamps, then I suggest eschewing making the pattern more complicated than it has to be.


问:
Where can I find the nodeport information on the ILB that sends traffic to a GKE service that is exposed using a nodeport
I have created a service in GKE exposed using an internal load balancer. The health check port for the ILB is 10256 which is kube-proxy. The port on the ILB is that of my kubernetes service port. (Not the target port). However there is no information as such on the ILB which indicates that the traffic is reaching the NodePort on which the service is exposed. How does this work internally ?</p>

答:
The answer is "you don't".  When using the Google ILB, traffic isn't forwarded to the NodePort.  From Google Compute Engine Docs:

Internal TCP/UDP load balancers are not proxies; they pass traffic to backends on the same port on which the traffic is received

The interesting part is that you don't even need the node port for Google Load Balancers.  From Kubernetes Docs

...not strictly required on all cloud providers (e.g. Google Compute Engine does not need to allocate a NodePort to make LoadBalancer work, but AWS does) but the current API requires it

So to answer your question on how it works, it's done in IP Tables by matching the external IP Address of the Service.  You can follow the chain from service ip address to pod ip address and port using iptables-save (Google Container Optimized OS doesn't have iptables-save, ubuntu does)

```<code>$ sudo iptables-save | grep 35.221.57.238
-A KUBE-SERVICES -d 35.221.57.238/32 -p tcp -m comment --comment "kuard/kuard: loadbalancer IP" -m tcp --dport 8081 -j KUBE-FW-VUXQQGPA6IZX7OIE

$ sudo iptables-save | grep KUBE-FW-VUXQQGPA6IZX7OIE
:KUBE-FW-VUXQQGPA6IZX7OIE - [0:0]
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-MARK-MASQ
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-MARK-DROP
-A KUBE-SERVICES -d 35.221.57.238/32 -p tcp -m comment --comment "kuard/kuard: loadbalancer IP" -m tcp --dport 8081

$ sudo iptables-save | grep KUBE-SVC-VUXQQGPA6IZX7OIE
:KUBE-SVC-VUXQQGPA6IZX7OIE - [0:0]
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-NODEPORTS -p tcp -m comment --comment "kuard/kuard:" -m tcp --dport 31297 -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-SERVICES -d 10.31.251.41/32 -p tcp -m comment --comment "kuard/kuard: cluster IP" -m tcp --dport 8081 -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.10000000009 -j KUBE-SEP-7UUYG24J2OBFZYRF
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.11110999994 -j KUBE-SEP-6ANDSGXDBEGTAG23
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.12500000000 -j KUBE-SEP-25IXXMCCF3XEBS6O
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.14286000002 -j KUBE-SEP-NHB6VFRNINLBDDVN
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.16667000018 -j KUBE-SEP-CORNB7YN4D5QTBEL
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.20000000019 -j KUBE-SEP-TVLRYFRKJELCUDJW
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.25000000000 -j KUBE-SEP-GZREDYSZ5AHV77PW
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-QJSD2YXPKN3UWYMO
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-GOWSUJ5VHTYBPFCG
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -j KUBE-SEP-HFAJBHAOVDISHRVT

$ sudo iptables-save | grep KUBE-SEP-7UUYG24J2OBFZYRF
:KUBE-SEP-7UUYG24J2OBFZYRF - [0:0]
-A KUBE-SEP-7UUYG24J2OBFZYRF -s 10.28.25.11/32 -m comment --comment "kuard/kuard:" -j KUBE-MARK-MASQ
-A KUBE-SEP-7UUYG24J2OBFZYRF -p tcp -m comment --comment "kuard/kuard:" -m tcp -j DNAT --to-destination 10.28.25.11 :8080
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.10000000009 -j KUBE-SEP-7UUYG24J2OBFZYRF
</code>```

Body:
The answer is "you don't".  When using the Google ILB, traffic isn't forwarded to the NodePort.  From Google Compute Engine Docs:

Internal TCP/UDP load balancers are not proxies; they pass traffic to backends on the same port on which the traffic is received

The interesting part is that you don't even need the node port for Google Load Balancers.  From Kubernetes Docs

...not strictly required on all cloud providers (e.g. Google Compute Engine does not need to allocate a NodePort to make LoadBalancer work, but AWS does) but the current API requires it

So to answer your question on how it works, it's done in IP Tables by matching the external IP Address of the Service.  You can follow the chain from service ip address to pod ip address and port using iptables-save (Google Container Optimized OS doesn't have iptables-save, ubuntu does)

$ sudo iptables-save | grep 35.221.57.238
-A KUBE-SERVICES -d 35.221.57.238/32 -p tcp -m comment --comment "kuard/kuard: loadbalancer IP" -m tcp --dport 8081 -j KUBE-FW-VUXQQGPA6IZX7OIE

$ sudo iptables-save | grep KUBE-FW-VUXQQGPA6IZX7OIE
:KUBE-FW-VUXQQGPA6IZX7OIE - [0:0]
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-MARK-MASQ
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-MARK-DROP
-A KUBE-SERVICES -d 35.221.57.238/32 -p tcp -m comment --comment "kuard/kuard: loadbalancer IP" -m tcp --dport 8081

$ sudo iptables-save | grep KUBE-SVC-VUXQQGPA6IZX7OIE
:KUBE-SVC-VUXQQGPA6IZX7OIE - [0:0]
-A KUBE-FW-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard: loadbalancer IP" -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-NODEPORTS -p tcp -m comment --comment "kuard/kuard:" -m tcp --dport 31297 -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-SERVICES -d 10.31.251.41/32 -p tcp -m comment --comment "kuard/kuard: cluster IP" -m tcp --dport 8081 -j KUBE-SVC-VUXQQGPA6IZX7OIE
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.10000000009 -j KUBE-SEP-7UUYG24J2OBFZYRF
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.11110999994 -j KUBE-SEP-6ANDSGXDBEGTAG23
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.12500000000 -j KUBE-SEP-25IXXMCCF3XEBS6O
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.14286000002 -j KUBE-SEP-NHB6VFRNINLBDDVN
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.16667000018 -j KUBE-SEP-CORNB7YN4D5QTBEL
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.20000000019 -j KUBE-SEP-TVLRYFRKJELCUDJW
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.25000000000 -j KUBE-SEP-GZREDYSZ5AHV77PW
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-QJSD2YXPKN3UWYMO
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-GOWSUJ5VHTYBPFCG
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -j KUBE-SEP-HFAJBHAOVDISHRVT

$ sudo iptables-save | grep KUBE-SEP-7UUYG24J2OBFZYRF
:KUBE-SEP-7UUYG24J2OBFZYRF - [0:0]
-A KUBE-SEP-7UUYG24J2OBFZYRF -s 10.28.25.11/32 -m comment --comment "kuard/kuard:" -j KUBE-MARK-MASQ
-A KUBE-SEP-7UUYG24J2OBFZYRF -p tcp -m comment --comment "kuard/kuard:" -m tcp -j DNAT --to-destination 10.28.25.11 :8080
-A KUBE-SVC-VUXQQGPA6IZX7OIE -m comment --comment "kuard/kuard:" -m statistic --mode random --probability 0.10000000009 -j KUBE-SEP-7UUYG24J2OBFZYRF


问:
Acitverecord specify `inverse_of` with `through` but not the other way
I have 3 models as follows :

class User
  has_many :event_series, inverse_of: :user
  has_many :events, through: :event_series, inverse_of: :user
end

class EventSeries
  belongs_to :user, inverse_of: :event_series
  has_many :events, inverse_of: :event_series
end

class Event
  belongs_to :event_series, inverse_of: :events
  has_one :user, through: :event_series, inverse_of: :events
end
```

<p>This is all fine.
Now I want to add a special event for each user called the 'showcase_event'.</p>

<pre class="lang-rb prettyprint-override"><code>class User
  has_one :showcase_event, class_name: 'Event', inverse_of: :user
end
</code>```

This isn't working because the Event model doesn't have the user directly, it's associated through EventSeries.

I'm getting an error during serialization:

```<code>ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column events.user_id does not exist
</code>```

I'm using fast jsonapi:

class PublicUserSerializer
  include FastJsonapi::ObjectSerializer
  ...
  has_one :showcase_event, record_type: :event, serializer: EventSerializer
  ...
end
```

It seems to me that the inverse relationship that I have between User, Event and EventSeries needs to work between User and showcase_event but I don't know how to specify that ONLY the inverse is through EventSeries
Apologies in advance for not having the best vocabulary to describe this problem.

答:
Solved by my rubber duck.
As seen in the documentation :

The #belongs_to association is always used in the model that has the
  foreign key.

So I changed my declaration of the showcase_event to this :

```<code>class User
  belongs_to :showcase_event, class_name: 'Event', inverse_of: :user, optional: true
end
</code>```

And problem solved

Body:
I have 3 models as follows :

class User
  has_many :event_series, inverse_of: :user
  has_many :events, through: :event_series, inverse_of: :user
end

class EventSeries
  belongs_to :user, inverse_of: :event_series
  has_many :events, inverse_of: :event_series
end

class Event
  belongs_to :event_series, inverse_of: :events
  has_one :user, through: :event_series, inverse_of: :events
end

This is all fine.
Now I want to add a special event for each user called the 'showcase_event'.

class User
  has_one :showcase_event, class_name: 'Event', inverse_of: :user
end

This isn't working because the Event model doesn't have the user directly, it's associated through EventSeries.

I'm getting an error during serialization:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column events.user_id does not exist

I'm using fast jsonapi:

class PublicUserSerializer
  include FastJsonapi::ObjectSerializer
  ...
  has_one :showcase_event, record_type: :event, serializer: EventSerializer
  ...
end

It seems to me that the inverse relationship that I have between User, Event and EventSeries needs to work between User and showcase_event but I don't know how to specify that ONLY the inverse is through EventSeries
Apologies in advance for not having the best vocabulary to describe this problem.

Body:
Solved by my rubber duck.
As seen in the documentation :

The #belongs_to association is always used in the model that has the
  foreign key.

So I changed my declaration of the showcase_event to this :

class User
  belongs_to :showcase_event, class_name: 'Event', inverse_of: :user, optional: true
end

And problem solved


问:
How would you analyse a file too big for memory?
Recently I was asked this question in a live coding interview round by the recruiter. I was not sure how to do this with code.

I thought of splitting the file into multiple files and then read those chunks through multiple threads.

But I was not able to implement the same.

Any help with the implementation or some other approach will be appreciated !

答: Depending on the file type/contents, you could possibly load it into a database table and do analysis through queries on it there (if it was a .csv file for example).</p>


答:
I suggest breaking the line that causes an error into two lines:

```<code>matches = regex.findall(string)
result = matches[0]
</code>```

Now you can inpsect matches to see what it contains.

Title: Python - Extract yyyyMMddhhmmss from file using Regex

Body:
I suggest breaking the line that causes an error into two lines:

matches = regex.findall(string)
result = matches[0]

Now you can inpsect matches to see what it contains.


问:
Invalid Verb on WMIC get variable
I am trying to get just the primary hard disk serial number to a variable to be echoed later.

I have used this and it works:

```<code>for /f "tokens=2 delims== " %%k in ('WMIC path win32_physicalmedia get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set "SerialNumber=%%l")
</code>```

However, it only does the last serial number and I want to get the primary.

If I used this command,

```<code>"wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value"
</code>```

then I get only the desired serial number.

Problem is when I try to modify the working code I get an error when running the bat:

Invalid Verb.

Trying to get to work:

```<code>for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)
</code>```

Errors:

Invalid Verb

If I run just:

```<code>wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value in CMD
</code>```

I get the following output:

```<code>SerialNumber=     WD-WCC2E1XJADRT
</code>```

So I know the command works.

It doesn't even matter if the spaces are in, I just want whats after the =. I am doing this in WINPE with WMIC support, so Powershell isn't an option.

Total script

```<code>@echo OFF
setlocal
for %%v in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do if exist %%v:\drives.txt set w=%%v

for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value)') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)

for /F "tokens=2" %%i in ('date /t') do set "Date=%%i"
echo %SerialNumber%,%Date% >> %w%:\drives.txt
</code>```

答:
If you modify your command to this:

WMIC Path Win32_PhysicalMedia Where "Tag='\\\\.\\PHYSICALDRIVE0'" Get SerialNumber /Value
```

<p>The <strong><code>=</code></strong> will be protected.</p>

<p>Try it like this:</p>

<pre class="lang-bat prettyprint-override"><code>@Echo Off
For /F "Tokens=1*Delims==" %%A in ('
    WMIC Path Win32_PhysicalMedia Where "Tag='\\\\.\\PHYSICALDRIVE0'" Get SerialNumber /Value 2^>Nul
') Do For %%C In (%%B) Do Set "SerialNumber=%%C"
Echo [%SerialNumber%] & Pause
</code>```

I've added the last line just to show any returned variable and value.

Title: Invalid Verb on WMIC get variable

Body:
I am trying to get just the primary hard disk serial number to a variable to be echoed later.

I have used this and it works:

for /f "tokens=2 delims== " %%k in ('WMIC path win32_physicalmedia get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set "SerialNumber=%%l")

However, it only does the last serial number and I want to get the primary.

If I used this command,

"wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value"

then I get only the desired serial number.

Problem is when I try to modify the working code I get an error when running the bat:

Invalid Verb.

Trying to get to work:

for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)

Errors:

Invalid Verb

If I run just:

wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value in CMD

I get the following output:

SerialNumber=     WD-WCC2E1XJADRT

So I know the command works.

It doesn't even matter if the spaces are in, I just want whats after the =. I am doing this in WINPE with WMIC support, so Powershell isn't an option.

Total script

@echo OFF
setlocal
for %%v in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do if exist %%v:\drives.txt set w=%%v

for /f "tokens=2 delims== " %%k in ('wmic path win32_physicalmedia where tag='\\\\.\\PHYSICALDRIVE0' get serialnumber /value)') do (for /f "delims=" %%l in ("%%k") do set SerialNumber=%%l)

for /F "tokens=2" %%i in ('date /t') do set "Date=%%i"
echo %SerialNumber%,%Date% >> %w%:\drives.txt

Body:
If you modify your command to this:

WMIC Path Win32_PhysicalMedia Where "Tag='\\\\.\\PHYSICALDRIVE0'" Get SerialNumber /Value

The = will be protected.

Try it like this:

@Echo Off
For /F "Tokens=1*Delims==" %%A in ('
    WMIC Path Win32_PhysicalMedia Where "Tag='\\\\.\\PHYSICALDRIVE0'" Get SerialNumber /Value 2^>Nul
') Do For %%C In (%%B) Do Set "SerialNumber=%%C"
Echo [%SerialNumber%] & Pause

I've added the last line just to show any returned variable and value.


问:
Linear gradient is showing two colors despite only one being specified
I'm trying to understand how a linear gradient with only one color specified is producing a background with two different colors.

.book-bg {
  height: 100px;
  width: 100%;
  background: #24ab9d
  linear-gradient(
      to bottom,
      #238d82 16px,
      rgba(35, 141, 130, 0) 16px,
      rgba(35, 141, 130, 0) 100%
    )
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="book-bg"></div></code>```

I would expect this linear gradient to produce a background with only #238d82. The rgba value (rgba(35, 141, 130, 0)) converts to the same hex code so shouldn't this div just be one color? What is causing the dark strip at the top?

答:
What you are seeing is the #24ab9d that you defined to be the background-color layer. Your code is equialent to this one:

.book-bg {
  height: 100px;
  width: 100%;
  background:
    linear-gradient( to bottom, #238d82 16px, rgba(35, 141, 130, 0) 16px, rgba(35, 141, 130, 0) 100%);
  background-color: #24ab9d;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="book-bg"></div></code>```

Or this one since you are considering transparent color:

.book-bg {
  height: 100px;
  width: 100%;
  background:
    linear-gradient( to bottom, #238d82 16px, transparent 16px);
  background-color: #24ab9d;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="book-bg"></div></code>```

Also the same as:

.book-bg {
  height: 100px;
  width: 100%;
  background:
    linear-gradient( to bottom, #238d82 16px, #24ab9d 16px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="book-bg"></div></code>```

Body:
I'm trying to understand how a linear gradient with only one color specified is producing a background with two different colors.

.book-bg {
  height: 100px;
  width: 100%;
  background: #24ab9d
  linear-gradient(
      to bottom,
      #238d82 16px,
      rgba(35, 141, 130, 0) 16px,
      rgba(35, 141, 130, 0) 100%
    )
}

I would expect this linear gradient to produce a background with only #238d82. The rgba value (rgba(35, 141, 130, 0)) converts to the same hex code so shouldn't this div just be one color? What is causing the dark strip at the top?

Body:
What you are seeing is the #24ab9d that you defined to be the background-color layer. Your code is equialent to this one:

.book-bg {
  height: 100px;
  width: 100%;
  background:
    linear-gradient( to bottom, #238d82 16px, rgba(35, 141, 130, 0) 16px, rgba(35, 141, 130, 0) 100%);
  background-color: #24ab9d;
}

<div class="book-bg"></div>

Or this one since you are considering transparent color:

.book-bg {
  height: 100px;
  width: 100%;
  background:
    linear-gradient( to bottom, #238d82 16px, transparent 16px);
  background-color: #24ab9d;
}

<div class="book-bg"></div>

Also the same as:

.book-bg {
  height: 100px;
  width: 100%;
  background:
    linear-gradient( to bottom, #238d82 16px, #24ab9d 16px);
}

<div class="book-bg"></div>


问:
Update JOIN table contents
I have a table joined from two other tables. I would like this table to stay updated with entries in the other two tables.

First Table is "employees"

I am using the ID, Last_Name, and First_Name.

And the second Table is "EmployeeTimeCardActions"

using columns ID, ActionTime, ActionDate, ShiftStart, and ActionType.

ID is my common column that the join was created by..Joined Table...

Because I usually have a comment saying I did not include enough information, I do not need a exact specific code sample and I think I have included everything needed. If there is a good reason to include more I will, I just try to keep as little company information public as possible

答: Sounds like you're having your data duplicated across tables. Not a smart idea at all. You can update data in one table when a row is updated in a different one via triggers but this is a TERRIBLE approach. If you want to display data joined from 2 tables, the right approach here is using an SQL VIEW which will display the current data.</p>

Title: Update JOIN table contents


问:
Uppaal template parameters
I am using UPPAAL 4.1.19 and I am following the train tutorial, given in this. In Train template, I put the parameters int[0,N] e, const int id and in the system declaration I declare Train1=Train(el, 1); and the system returns me "Incompatible argument" error for e1. I don't understand why it is actually incompatible? I have declared N as a constant equal to 5 in the global declarations, as well as el, but still it doesn't seem to work. Any idea?

答: Try int[0,N] &e, const int id, similarly as here (page 6): https://www.it.uu.se/research/group/darts/uppaal/small_tutorial.pdf.

Title: Uppaal template parameters


问:
Why are total only calculated in one dimension wiht margins=True in pandas.pivot_table?
Examples for pandas.pivot_table show totals being calculated for rows and columns, but for me totals are only calculated for rows.

I can reproduce this behavior with different DataFrames on this setup:

Ubuntu 18.04, Python 3.6.7, Pandas 0.24.2

import pandas
df = pandas.DataFrame([
    ["sec", "2019-01", 1],
    ["sec", "2019-02", 2],
    ["maint","2019-02", 1],
    ["maint","2019-03",3]
])
print(df)
# If not passing arguments as lists, behavior is essentially the same
p = df.pivot_table(
    index=[0], columns=[1], values=[2],
    aggfunc="sum", fill_value=0.,
    margins=True
)
print(p)
```

<p>Output:</p>

```       0        1  2
0    sec  2019-01  1
1    sec  2019-02  2
2  maint  2019-02  1
3  maint  2019-03  3

            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         0       0       0   7
```

<p>As you can see in the last row, the aggregation is not applied to the columns (except for the last one) and values are just 0.</p>

<p>As suggested by many examples I would have expected the <code>pivot_table</code> to produce this result:</p>

```            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         1       3       3   7
```

Did I do or understand something wrong? Or might this be a bug?

答:
This is a bug in pandas that only looks to occur with numeric columns and margins=True.  A workaround is to temporarily cast numeric column names to strings:

```<code>In [1]: import pandas as pd; pd.__version__
Out[1]: '0.24.2'

In [2]: df = pd.DataFrame([
   ...:     ["sec", "2019-01", 1],
   ...:     ["sec", "2019-02", 2],
   ...:     ["maint","2019-02", 1],
   ...:     ["maint","2019-03",3]])

In [3]: # wrong output with numeric columns
   ...: df.pivot_table(index=[0], columns=[1], values=[2],
   ...:                aggfunc="sum", fill_value=0., margins=True)
Out[3]:
            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         0       0       0   7

In [4]: # correct output with string columns
   ...: df.columns = df.columns.map(str)
   ...: df.pivot_table(index=['0'], columns=['1'], values=['2'],
   ...:                aggfunc="sum", fill_value=0., margins=True)
Out[4]:
            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         1       3       3   7
</code>```

Body:
Examples for pandas.pivot_table show totals being calculated for rows and columns, but for me totals are only calculated for rows.

I can reproduce this behavior with different DataFrames on this setup:

Ubuntu 18.04, Python 3.6.7, Pandas 0.24.2

import pandas
df = pandas.DataFrame([
    ["sec", "2019-01", 1],
    ["sec", "2019-02", 2],
    ["maint","2019-02", 1],
    ["maint","2019-03",3]
])
print(df)
# If not passing arguments as lists, behavior is essentially the same
p = df.pivot_table(
    index=[0], columns=[1], values=[2],
    aggfunc="sum", fill_value=0.,
    margins=True
)
print(p)

Output:

       0        1  2
0    sec  2019-01  1
1    sec  2019-02  2
2  maint  2019-02  1
3  maint  2019-03  3

            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         0       0       0   7

As you can see in the last row, the aggregation is not applied to the columns (except for the last one) and values are just 0.

As suggested by many examples I would have expected the pivot_table to produce this result:

            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         1       3       3   7

Did I do or understand something wrong? Or might this be a bug?

Body:
This is a bug in pandas that only looks to occur with numeric columns and margins=True.  A workaround is to temporarily cast numeric column names to strings:

In [1]: import pandas as pd; pd.__version__
Out[1]: '0.24.2'

In [2]: df = pd.DataFrame([
   ...:     ["sec", "2019-01", 1],
   ...:     ["sec", "2019-02", 2],
   ...:     ["maint","2019-02", 1],
   ...:     ["maint","2019-03",3]])

In [3]: # wrong output with numeric columns
   ...: df.pivot_table(index=[0], columns=[1], values=[2],
   ...:                aggfunc="sum", fill_value=0., margins=True)
Out[3]:
            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         0       0       0   7

In [4]: # correct output with string columns
   ...: df.columns = df.columns.map(str)
   ...: df.pivot_table(index=['0'], columns=['1'], values=['2'],
   ...:                aggfunc="sum", fill_value=0., margins=True)
Out[4]:
            2
1     2019-01 2019-02 2019-03 All
0
maint       0       1       3   4
sec         1       2       0   3
All         1       3       3   7


问:
Unable to access value from `Transformations.map` in unit test
To give some background to this question, I have a ViewModel that waits for some data, posts it to a MutableLiveData, and then exposes all the values through some properties. Here's a short gist of what that looks like:

```<code>class QuestionViewModel {

    private val state = MutableLiveData<QuestionState>()

    private val currentQuestion: Question?
        get() = (state.value as? QuestionState.Loaded)?.question

    val questionTitle: String
        get() = currentQuestion?.title.orEmpty()

    ...
}
</code>```

Then, in my test, I mock the data and just run an assertEquals check:

```<code>assertEquals("TestTitle", viewModel.questionTitle)
</code>```

All of this works fine so far, but I actually want my fragment to observe for when the current question changes. So, I tried changing it around to use Transformations.map:

```<code>class QuestionViewModel {

    private val state = MutableLiveData<QuestionState>()

    private val currentQuestion: LiveData<Question> = Transformations.map(state) {
        (it as? QuestionState.Loaded)?.question
    }

    val questionTitle: String
        get() = currentQuestion.value?.title.orEmpty()

    ...
}
</code>```

Suddenly, all of my assertions in the test class have failed. I made currentQuestion public and verified that it's value is null in my unit test. I've determined this is the issue because:

I can mock the data and still get the right value from my state LiveData

I can run my app and see the expected data on the screen, so this issue is specific to my unit test.

I have already added the InstantTaskExecutorRule to my unit test, but maybe that doesn't handle the Transformations methods?

答:
Looks like you're missing the .value on the it variable.

```<code>private val currentQuestion: LiveData<Question> = Transformations.map(state) {
        (it.value as? QuestionState.Loaded)?.question
    }
</code>```

Body:
To give some background to this question, I have a ViewModel that waits for some data, posts it to a MutableLiveData, and then exposes all the values through some properties. Here's a short gist of what that looks like:

class QuestionViewModel {

    private val state = MutableLiveData<QuestionState>()

    private val currentQuestion: Question?
        get() = (state.value as? QuestionState.Loaded)?.question

    val questionTitle: String
        get() = currentQuestion?.title.orEmpty()

    ...
}

Then, in my test, I mock the data and just run an assertEquals check:

assertEquals("TestTitle", viewModel.questionTitle)

All of this works fine so far, but I actually want my fragment to observe for when the current question changes. So, I tried changing it around to use Transformations.map:

class QuestionViewModel {

    private val state = MutableLiveData<QuestionState>()

    private val currentQuestion: LiveData<Question> = Transformations.map(state) {
        (it as? QuestionState.Loaded)?.question
    }

    val questionTitle: String
        get() = currentQuestion.value?.title.orEmpty()

    ...
}

Suddenly, all of my assertions in the test class have failed. I made currentQuestion public and verified that it's value is null in my unit test. I've determined this is the issue because:

I can mock the data and still get the right value from my state LiveData

I can run my app and see the expected data on the screen, so this issue is specific to my unit test.

I have already added the InstantTaskExecutorRule to my unit test, but maybe that doesn't handle the Transformations methods?

Body:
Looks like you're missing the .value on the it variable.

private val currentQuestion: LiveData<Question> = Transformations.map(state) {
        (it.value as? QuestionState.Loaded)?.question
    }


问:
Transparent scrollbar with css
Now use this code (and many variations of this), but scroll track get dark-grey color, something like #222222 or near this. Find many examples, but all of them give same result. Opera, Chrome and Firefox show this bug. How to fix?

#style-3::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    background-color: transparent;
}

#style-3::-webkit-scrollbar {
    width: 6px;
    background-color: transparent;
}

#style-3::-webkit-scrollbar-thumb {
    background-color: #000000;
}
```

答:
Edit:

The solution that I gave with overflow: overlay still works in browsers like Google Chrome and you can still see my answer below. However, overflow: overlay was marked depreciated.

Whether an alternative solution exists, is unknown, but the one mentioned below still works for Google Chrome.
From what I understood from https://github.com/w3c/csswg-drafts, is that the alternative was ment to be scrollbar-gutter. But there's actually nothing pointing towards an alternative solution, except people saying that there would be.

The documention of scrollbar-gutter says, that the user agent is able to control whether it shows classic or overlay scrollbars. And the people at the csswg-drafts say that the people that would implement such a feature, don't seem to be interested into it.

If we want an alternative solution, then we have to tell them, here: https://github.com/w3c/csswg-drafts/issues/7716

I can't suggest this alone, they need more people that would be interested in having a "feature" to let the website author control whether a classic or a overlay scrollbar should be used.

Regarding Google Chrome's overlay scrollbars. They've made an experiment that allows the user to enable it at chrome://flags/ and then searching for "Overlay Scrollbars".

Answer:

If you use this for "body":

body {
    overflow: overlay;
}
```
<p>The scrollbar will then also take transparent backgrounds across the page.
This will also put the scrollbar inside the page instead of removing some of the width to put in the scrollbar.</p>
<p>Here is a demo code. I wasn't able to put it inside any of the codepen or jsfiddle, apparently it took me a while until I figured out, but they don't show the transparency, and I don't know why.</p>
<p>But putting this in a HTML file should go fine.</p>
<p>Was able to put it on fiddle: https://jsfiddle.net/3awLgj5v/</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<style>
html, body {
  margin: 0;
  padding: 0;
}

body {
  overflow: overlay;
}

.div1 {
  background: grey;
  margin-top: 200px;
  margin-bottom: 20px;
  height: 20px;
}

::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-thumb {
  background: rgba(90, 90, 90);
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.2);
}
</style>

<body>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

</body>
</html></code>```

Best way to test it is to create a local html file, I guess.

You can also apply that on other elements, such as any scrolling box. While using inspector mode, it could be that you have to put the overflow to hidden and then back to anything else. It probably needed to refresh. After that it should be possible working on scrollbar without having to refresh it again. Just note that was for the inspector mode.

Title: Transparent scrollbar with css

Body:
Edit:

The solution that I gave with overflow: overlay still works in browsers like Google Chrome and you can still see my answer below. However, overflow: overlay was marked depreciated.

Whether an alternative solution exists, is unknown, but the one mentioned below still works for Google Chrome.
From what I understood from https://github.com/w3c/csswg-drafts, is that the alternative was ment to be scrollbar-gutter. But there's actually nothing pointing towards an alternative solution, except people saying that there would be.

The documention of scrollbar-gutter says, that the user agent is able to control whether it shows classic or overlay scrollbars. And the people at the csswg-drafts say that the people that would implement such a feature, don't seem to be interested into it.

If we want an alternative solution, then we have to tell them, here: https://github.com/w3c/csswg-drafts/issues/7716

I can't suggest this alone, they need more people that would be interested in having a "feature" to let the website author control whether a classic or a overlay scrollbar should be used.

Regarding Google Chrome's overlay scrollbars. They've made an experiment that allows the user to enable it at chrome://flags/ and then searching for "Overlay Scrollbars".

Answer:

If you use this for "body":

body {
    overflow: overlay;
}

The scrollbar will then also take transparent backgrounds across the page.
This will also put the scrollbar inside the page instead of removing some of the width to put in the scrollbar.

Here is a demo code. I wasn't able to put it inside any of the codepen or jsfiddle, apparently it took me a while until I figured out, but they don't show the transparency, and I don't know why.

But putting this in a HTML file should go fine.

Was able to put it on fiddle: https://jsfiddle.net/3awLgj5v/

<!DOCTYPE html>
<html>
<style>
html, body {
  margin: 0;
  padding: 0;
}

body {
  overflow: overlay;
}

.div1 {
  background: grey;
  margin-top: 200px;
  margin-bottom: 20px;
  height: 20px;
}

::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-thumb {
  background: rgba(90, 90, 90);
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.2);
}
</style>

<body>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

</body>
</html>

Best way to test it is to create a local html file, I guess.

You can also apply that on other elements, such as any scrolling box. While using inspector mode, it could be that you have to put the overflow to hidden and then back to anything else. It probably needed to refresh. After that it should be possible working on scrollbar without having to refresh it again. Just note that was for the inspector mode.


问:
How to return results from stored procedure as a List?
Previously this worked well and recently the line stop working. This code uses the DB context to run a procedure and return it in List format. For some reason I am not seeing the error, I just see the action fail because it is not executing.

I ran the stored procedure in SQL Server and see the desired results, just not seeing it happening from the application layer.

```<code>[Http.Route("postsearch")]
public async Task<IHttpActionResult> PostSearch(SearchInputDTO srequest)
{
   var searchString = srequest.SearchValue.ToString();
   List<output> seResult = new List<output>(_output.searchLog(searchString)); /*This line stopped working*/
   return Ok(seResult);
}
</code>```

Stored procedure:

```<code>SET FMTONLY OFF
GO
SET NOCOUNT ON
GO

ALTER PROCEDURE [dbo].[searchLog]
    @searchValue VARCHAR(150)
AS
    SELECT *
    FROM [dbo].[output]
    WHERE CONTAINS (*, @searchValue)
</code>```

Implementation in Entity Framework

```<code>public virtual int searchLog(string searchValue)
{
    var searchValueParameter = searchValue != null ?
            new ObjectParameter("searchValue", searchValue) :
            new ObjectParameter("searchValue", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("searchLog", searchValueParameter);
}
</code>```

This should return the rows from the query.

答: The Solution I found was to modify the output of the stored procedure in Visual Studio. </p>

Body:
Previously this worked well and recently the line stop working. This code uses the DB context to run a procedure and return it in List format. For some reason I am not seeing the error, I just see the action fail because it is not executing.

I ran the stored procedure in SQL Server and see the desired results, just not seeing it happening from the application layer.

[Http.Route("postsearch")]
public async Task<IHttpActionResult> PostSearch(SearchInputDTO srequest)
{
   var searchString = srequest.SearchValue.ToString();
   List<output> seResult = new List<output>(_output.searchLog(searchString)); /*This line stopped working*/
   return Ok(seResult);
}

Stored procedure:

SET FMTONLY OFF
GO
SET NOCOUNT ON
GO

ALTER PROCEDURE [dbo].[searchLog]
    @searchValue VARCHAR(150)
AS
    SELECT *
    FROM [dbo].[output]
    WHERE CONTAINS (*, @searchValue)

Implementation in Entity Framework

public virtual int searchLog(string searchValue)
{
    var searchValueParameter = searchValue != null ?
            new ObjectParameter("searchValue", searchValue) :
            new ObjectParameter("searchValue", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("searchLog", searchValueParameter);
}

This should return the rows from the query.


问:
How can I read only the header column of a CSV file using Python?
I am looking for a a way to read just the header row of a large number of large CSV files.

Using Pandas, I have this method available, for each csv file:

```<code>>>> df = pd.read_csv(PATH_TO_CSV)
>>> df.columns
</code>```

I could do this with just the csv module:

```<code>>>> reader = csv.DictReader(open(PATH_TO_CSV))
>>> reader.fieldnames
</code>```

The problem with these is that each CSV file is 500MB+ in size, and it seems to be a gigantic waste to read in the entire file of each just to pull the header lines.

My end goal of all of this is to pull out unique column names. I can do that once I have a list of column headers that are in each of these files.

How can I extract only the header row of a CSV file, quickly?

答:
you have missed nrows=1 param to read_csv

```<code>>>> df= pd.read_csv(PATH_TO_CSV, nrows=1)
>>> df.columns
</code>```

Body:
I am looking for a a way to read just the header row of a large number of large CSV files.

Using Pandas, I have this method available, for each csv file:

>>> df = pd.read_csv(PATH_TO_CSV)
>>> df.columns

I could do this with just the csv module:

>>> reader = csv.DictReader(open(PATH_TO_CSV))
>>> reader.fieldnames

The problem with these is that each CSV file is 500MB+ in size, and it seems to be a gigantic waste to read in the entire file of each just to pull the header lines.

My end goal of all of this is to pull out unique column names. I can do that once I have a list of column headers that are in each of these files.

How can I extract only the header row of a CSV file, quickly?

Body:
you have missed nrows=1 param to read_csv

>>> df= pd.read_csv(PATH_TO_CSV, nrows=1)
>>> df.columns


问:
Rotate a 3D object on 3 axis in JavaFX properly
So the method that I've used so far to rotate objects in JavaFX was that I layered it in 3 groups, each of them with a Rotate attached and locked to a single axis like so:

```<code>    Rotate heading, roll, pitch;
    Group normalrotate, rollrotate, verticalrotate;

    heading.setAxis(new Point3D(0,1,0));
    normalrotate.getTransforms().add(heading);

    roll.setAxis(new Point3D(0,0,1));
    rollrotate.getTransforms().add(roll);

    pitch.setAxis(new Point3D(1,0,0));
    verticalrotate.getTransforms().add(pitch);
</code>```

and did a setAngle() for each time I needed to rotate the object. This worked very well for only heading and roll until i decided that I need pitch too. Now a lot of tutorials for OpenGL and alike say that rotational matixes or quaternions are best for these type of rotations, but the javadoc lacks any usefull data regaring this.

Example: What happens when I rotate an object by 180 degrees on the y axis (and what should actually have happened in transparent blue)

Am I missing something?
All help would be appreciated.

答:
I can offer a solution. But it is a bit uncivilized and might be a discouraged practice.</p>

```<code>Node[] my3dModel = get3DModel();//the method creates a mesh (I suppose that you used Interactive mesh, but it's not important here)
Pane paneForMyModel = new Pane();
paneForMyModel.getChildren.addAll(my3dModel);//you add your model to this pane
//and now
paneForMyModel.getTransforms().add(new Rotate(angle, axis));
</code>```

Body:
So the method that I've used so far to rotate objects in JavaFX was that I layered it in 3 groups, each of them with a Rotate attached and locked to a single axis like so:

    Rotate heading, roll, pitch;
    Group normalrotate, rollrotate, verticalrotate;

    heading.setAxis(new Point3D(0,1,0));
    normalrotate.getTransforms().add(heading);

    roll.setAxis(new Point3D(0,0,1));
    rollrotate.getTransforms().add(roll);

    pitch.setAxis(new Point3D(1,0,0));
    verticalrotate.getTransforms().add(pitch);

and did a setAngle() for each time I needed to rotate the object. This worked very well for only heading and roll until i decided that I need pitch too. Now a lot of tutorials for OpenGL and alike say that rotational matixes or quaternions are best for these type of rotations, but the javadoc lacks any usefull data regaring this.

Example: What happens when I rotate an object by 180 degrees on the y axis (and what should actually have happened in transparent blue)

Am I missing something?
All help would be appreciated.

Body:
I can offer a solution. But it is a bit uncivilized and might be a discouraged practice.

Node[] my3dModel = get3DModel();//the method creates a mesh (I suppose that you used Interactive mesh, but it's not important here)
Pane paneForMyModel = new Pane();
paneForMyModel.getChildren.addAll(my3dModel);//you add your model to this pane
//and now
paneForMyModel.getTransforms().add(new Rotate(angle, axis));


问:
How can I count a specific value in a mysql table and echo with php, how many times the varchar is in the table?
I have a MySQL table with several varchars in a column. Now I want to count how many times specific varchar is in this column. Then I want to echo the number that was counted. Can someone tell me what SQL Code I have to use and how I can convert the SQL result to an integer in PHP?

My table:

答:
Let's suppose you have a table with customers data called CUSTOMERS, one of its columns being "NAME".

You could do something like this:

```<code>SELECT NAME, COUNT(NAME) AS TOTAL FROM CUSTOMERS GROUP BY NAME
</code>```

So you will get something like this:

```<code>    NAME | TOTAL
    -----+------
    John | 5
    Mary | 3
    Bort | 9999
</code>```

If you want to filter by a specific name, you could do something like this:

```<code>SELECT NAME, COUNT(NAME) AS TOTAL FROM CUSTOMERS WHERE NAME = 'John' GROUP BY NAME

    NAME | TOTAL
    -----+------
    John | 5
</code>```

For the second part, it would depend how are you accessing data from your database. For example if you are iterating every row using mysql_fetch_array, and saving the row in a variable $row, you only need to do this:

```<code>$name = $row['NAME'];
$total = $row['TOTAL'];
</code>```

Body:
Let's suppose you have a table with customers data called CUSTOMERS, one of its columns being "NAME".

You could do something like this:

SELECT NAME, COUNT(NAME) AS TOTAL FROM CUSTOMERS GROUP BY NAME

So you will get something like this:

    NAME | TOTAL
    -----+------
    John | 5
    Mary | 3
    Bort | 9999

If you want to filter by a specific name, you could do something like this:

SELECT NAME, COUNT(NAME) AS TOTAL FROM CUSTOMERS WHERE NAME = 'John' GROUP BY NAME

    NAME | TOTAL
    -----+------
    John | 5

For the second part, it would depend how are you accessing data from your database. For example if you are iterating every row using mysql_fetch_array, and saving the row in a variable $row, you only need to do this:

$name = $row['NAME'];
$total = $row['TOTAL'];


答:
If our date is right after the slash, we can simply use this expression:

```<code>.+\/(\d{4})(\d{2})(\d{2}).+
</code>```

Then, if necessary, and we wish to add more boundaries, we can surely do so, such as:

```<code>.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}).+
</code>```

DEMO

or:

```<code>^.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\/.+$
</code>```

DEMO

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+\/(\d{4})(\d{2})(\d{2}).+"

test_str = "date file /20190529050003/folder "

subst = "\\1-\\2-\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

If we might want to get all the numbers, then we could use another expression:

```<code>.+\/(\d+)\/.+
</code>```

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+\/(\d+)\/.+"

test_str = "date file /20190529050003/folder "

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I am trying to get the date (format is yyyymmddhhmmss) from a string using Regex but I cannot find the pattern to use.

I am trying with the code below:

import re
string = "date file /20190529050003/folder "
regex = re.compile(r'\b\d{4}\d{2}\d{2}\s\d{2}\d{2}\d{2}\b')
result = regex.findall(string)[0],
print(result)

But I am getting the following error:

result = regex.findall(string)[0],
IndexError: list index out of range

How can I use regex to return "20190529050003" from the string that I have on my script?

Thanks!

Body:
If our date is right after the slash, we can simply use this expression:

.+\/(\d{4})(\d{2})(\d{2}).+

Then, if necessary, and we wish to add more boundaries, we can surely do so, such as:

.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}).+

DEMO

or:

^.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\/.+$

DEMO

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+\/(\d{4})(\d{2})(\d{2}).+"

test_str = "date file /20190529050003/folder "

subst = "\\1-\\2-\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

If we might want to get all the numbers, then we could use another expression:

.+\/(\d+)\/.+

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+\/(\d+)\/.+"

test_str = "date file /20190529050003/folder "

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


答:
Got rid of \s from the expression.

```<code>string = "date file /20190529050003/folder "
regex = re.compile(r'\b\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}\b')
result = regex.findall(string)[0]
'20190529050003'
</code>```

Body:
Got rid of \s from the expression.

string = "date file /20190529050003/folder "
regex = re.compile(r'\b\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}\b')
result = regex.findall(string)[0]
'20190529050003'