问:
Failed to create Blob container in Microsoft Azure
I followed the tutorial of Azure Blob storage service here and supplied the connection string from my storage account to create a container but it did not work as the container is not created and the application runs until I terminate it manually. I used azure-blob-storage API version 12.4.0.

Here is the code:

```<code>// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();

//Create a unique name for the container
String containerName = "quickstartblobs" + java.util.UUID.randomUUID();

// Create the container and return a container client object
BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);
</code>```

Here is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aaaa</groupId>
    <artifactId>ddada</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.327</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.cloud/google-cloud-storage -->
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-storage</artifactId>
            <version>1.108.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>de.hpi.cloudraid</groupId>
            <artifactId>erasure</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.hiramsoft.commons</groupId>
            <artifactId>jsalparser</artifactId>
            <version>0.2-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>com.google.googlejavaformat</groupId>
            <artifactId>google-java-format</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>com.google.crypto.tink</groupId>
            <artifactId>tink</artifactId>
            <version>1.3.0-rc3</version>
        </dependency>
        <dependency>
            <groupId>dev.morphia.morphia</groupId>
            <artifactId>core</artifactId>
            <version>1.5.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-csv</artifactId>
            <version>2.11.0.rc1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.0.rc1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.1</version>
        </dependency>
        <dependency>
            <groupId>com.hierynomus</groupId>
            <artifactId>sshj</artifactId>
            <version>0.27.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.azure/azure-storage-blob -->
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-storage-blob</artifactId>
            <version>12.4.0</version>
        </dependency>
    </dependencies>

</project>
</code>```

It also showed another error message like this:

```<code>May 29, 2020 3:39:49 PM io.netty.channel.AbstractChannelHandlerContext invokeExceptionCaught
WARNING: An exception 'java.lang.NoSuchMethodError: 'java.lang.String io.netty.handler.codec.http.HttpUtil.formatHostnameForHttp(java.net.InetSocketAddress)'' [enable DEBUG level for full stacktrace] was thrown by a user handler's exceptionCaught() method while handling the following exception:
java.lang.NoSuchMethodError: 'java.lang.String io.netty.handler.codec.http.HttpUtil.formatHostnameForHttp(java.net.InetSocketAddress)'
    at reactor.netty.http.client.HttpClientConnect$HttpClientHandler.resolveHostHeaderValue(HttpClientConnect.java:593)
    at reactor.netty.http.client.HttpClientConnect$HttpClientHandler.requestWithBody(HttpClientConnect.java:552)
    at reactor.netty.http.client.HttpClientConnect$HttpIOHandlerObserver.lambda$onStateChange$0(HttpClientConnect.java:429)
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)
    at reactor.netty.http.client.HttpClientConnect$HttpIOHandlerObserver.onStateChange(HttpClientConnect.java:430)
    at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:473)
    at reactor.netty.resources.PooledConnectionProvider$DisposableAcquire.onStateChange(PooledConnectionProvider.java:525)
    at reactor.netty.resources.PooledConnectionProvider$PooledConnection.onStateChange(PooledConnectionProvider.java:434)
    at reactor.netty.channel.ChannelOperationsHandler.channelActive(ChannelOperationsHandler.java:62)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)
    at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelActive(CombinedChannelDuplexHandler.java:414)
    at io.netty.channel.ChannelInboundHandlerAdapter.channelActive(ChannelInboundHandlerAdapter.java:64)
    at io.netty.channel.CombinedChannelDuplexHandler.channelActive(CombinedChannelDuplexHandler.java:213)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)
    at reactor.netty.tcp.SslProvider$SslReadHandler.userEventTriggered(SslProvider.java:731)
    at io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(AbstractChannelHandlerContext.java:329)
    at io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(AbstractChannelHandlerContext.java:315)
    at io.netty.channel.AbstractChannelHandlerContext.fireUserEventTriggered(AbstractChannelHandlerContext.java:307)
    at io.netty.handler.ssl.SslHandler.setHandshakeSuccess(SslHandler.java:1480)
    at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1318)
    at io.netty.handler.ssl.SslHandler.decodeNonJdkCompatible(SslHandler.java:1170)
    at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1195)
    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:138)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at java.base/java.lang.Thread.run(Thread.java:830)
</code>```

Any reasons why it did not work?

答:
Update:

Thanks to Ihsan Haikal for sharing. If anyone who faces similar problems cannot create a container using the following method, please check the content of pom.xml The problem should not be the code but the configuration part.

Original Answer:

With this steps I can create container on my storage:

First, import:

```<code>import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
</code>```

And this is the code in my pom.xml:

```<code><dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>12.0.0</version>
</dependency>
</code>```

Second, use code:

```<code>// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString("DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net").buildClient();

//Create a unique name for the container
String containerName = "quickstartblobs";

// Create the container and return a container client object
BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);
</code>```

You should get connection string from this place:

Then, it creates the container:

You can check what different between you and me.:)

Body:
I followed the tutorial of Azure Blob storage service here and supplied the connection string from my storage account to create a container but it did not work as the container is not created and the application runs until I terminate it manually. I used azure-blob-storage API version 12.4.0.

Here is the code:

// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();

//Create a unique name for the container
String containerName = "quickstartblobs" + java.util.UUID.randomUUID();

// Create the container and return a container client object
BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aaaa</groupId>
    <artifactId>ddada</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.327</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-storage</artifactId>
            <version>1.108.0</version>
        </dependency>

        <dependency>
            <groupId>de.hpi.cloudraid</groupId>
            <artifactId>erasure</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.hiramsoft.commons</groupId>
            <artifactId>jsalparser</artifactId>
            <version>0.2-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>com.google.googlejavaformat</groupId>
            <artifactId>google-java-format</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>com.google.crypto.tink</groupId>
            <artifactId>tink</artifactId>
            <version>1.3.0-rc3</version>
        </dependency>
        <dependency>
            <groupId>dev.morphia.morphia</groupId>
            <artifactId>core</artifactId>
            <version>1.5.8</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-csv</artifactId>
            <version>2.11.0.rc1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.0.rc1</version>
        </dependency>

        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.1</version>
        </dependency>
        <dependency>
            <groupId>com.hierynomus</groupId>
            <artifactId>sshj</artifactId>
            <version>0.27.0</version>
        </dependency>

        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-storage-blob</artifactId>
            <version>12.4.0</version>
        </dependency>
    </dependencies>

</project>

It also showed another error message like this:

May 29, 2020 3:39:49 PM io.netty.channel.AbstractChannelHandlerContext invokeExceptionCaught
WARNING: An exception 'java.lang.NoSuchMethodError: 'java.lang.String io.netty.handler.codec.http.HttpUtil.formatHostnameForHttp(java.net.InetSocketAddress)'' [enable DEBUG level for full stacktrace] was thrown by a user handler's exceptionCaught() method while handling the following exception:
java.lang.NoSuchMethodError: 'java.lang.String io.netty.handler.codec.http.HttpUtil.formatHostnameForHttp(java.net.InetSocketAddress)'
    at reactor.netty.http.client.HttpClientConnect$HttpClientHandler.resolveHostHeaderValue(HttpClientConnect.java:593)
    at reactor.netty.http.client.HttpClientConnect$HttpClientHandler.requestWithBody(HttpClientConnect.java:552)
    at reactor.netty.http.client.HttpClientConnect$HttpIOHandlerObserver.lambda$onStateChange$0(HttpClientConnect.java:429)
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)
    at reactor.netty.http.client.HttpClientConnect$HttpIOHandlerObserver.onStateChange(HttpClientConnect.java:430)
    at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:473)
    at reactor.netty.resources.PooledConnectionProvider$DisposableAcquire.onStateChange(PooledConnectionProvider.java:525)
    at reactor.netty.resources.PooledConnectionProvider$PooledConnection.onStateChange(PooledConnectionProvider.java:434)
    at reactor.netty.channel.ChannelOperationsHandler.channelActive(ChannelOperationsHandler.java:62)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)
    at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelActive(CombinedChannelDuplexHandler.java:414)
    at io.netty.channel.ChannelInboundHandlerAdapter.channelActive(ChannelInboundHandlerAdapter.java:64)
    at io.netty.channel.CombinedChannelDuplexHandler.channelActive(CombinedChannelDuplexHandler.java:213)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)
    at reactor.netty.tcp.SslProvider$SslReadHandler.userEventTriggered(SslProvider.java:731)
    at io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(AbstractChannelHandlerContext.java:329)
    at io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(AbstractChannelHandlerContext.java:315)
    at io.netty.channel.AbstractChannelHandlerContext.fireUserEventTriggered(AbstractChannelHandlerContext.java:307)
    at io.netty.handler.ssl.SslHandler.setHandshakeSuccess(SslHandler.java:1480)
    at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1318)
    at io.netty.handler.ssl.SslHandler.decodeNonJdkCompatible(SslHandler.java:1170)
    at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1195)
    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:138)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at java.base/java.lang.Thread.run(Thread.java:830)

Any reasons why it did not work?

Body:
Update:

Thanks to Ihsan Haikal for sharing. If anyone who faces similar problems cannot create a container using the following method, please check the content of pom.xml The problem should not be the code but the configuration part.

Original Answer:

With this steps I can create container on my storage:

First, import:

import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;

And this is the code in my pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>12.0.0</version>
</dependency>

Second, use code:

// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString("DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net").buildClient();

//Create a unique name for the container
String containerName = "quickstartblobs";

// Create the container and return a container client object
BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);

You should get connection string from this place:

Then, it creates the container:

You can check what different between you and me.:)


来源: stackexchange

问:
How to format a date value for Hubspot API using Python
I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:

```<code>    from pytz import timezone, utc
    from hubspot.crm.contacts import SimplePublicObject,

    created_dt = # datetime from sqlalchemy query
    utcdt = utc.localize(
        datetime(
            year=created_dt.year,
            month=created_dt.month,
            day=created_dt.day
            )
    )
    ts = int(utcdt.timestamp())
    props = SimplePublicObjectInput({"last_booking": str(ts)})
    return client.crm.companies.basic_api.update(
        hs_id, simple_public_object_input=props
    )
</code>```

this returns this error:

```<code>{"status":"error",
 "message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
 }
</code>```

答:
Ah, the answer was right there. Python timestamp returns the time in seconds, and HubSpot expects milliseconds. I just had to multiply by 1000:

```<code>ts = int(utcdt.timestamp()*1000)
</code>```

now all looks good.

ContentLicense: CC BY-SA 4.0

Body:
I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:

    from pytz import timezone, utc
    from hubspot.crm.contacts import SimplePublicObject,

    created_dt = # datetime from sqlalchemy query
    utcdt = utc.localize(
        datetime(
            year=created_dt.year,
            month=created_dt.month,
            day=created_dt.day
            )
    )
    ts = int(utcdt.timestamp())
    props = SimplePublicObjectInput({"last_booking": str(ts)})
    return client.crm.companies.basic_api.update(
        hs_id, simple_public_object_input=props
    )

this returns this error:

{"status":"error",
 "message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
 }

Body:
Ah, the answer was right there. Python timestamp returns the time in seconds, and HubSpot expects milliseconds. I just had to multiply by 1000:

ts = int(utcdt.timestamp()*1000)

now all looks good.


问:
how to search through a json response and compare a variable to existing key - value and get results of a different key - value
I want to display a polygon in a bing map. I've got this part down. I'm wondering how I would go about accessing a value from a different key in my json response once I've identified which key's sibling i'm trying to access?

I have this variable on the page:

var = 273972;

I want to match that variable to polygons.sections.id[] in my json response and grab the sibling COORDS value then store that value in a new varaible.

I have jquery and _underscore.js available.

Here is my JSON

```
"polygons":[
    {
        "id":46327,
        "name":"first set",
        "sections":[
            {
            "id":"273971",
            "name":"202",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273972",
            "name":"203",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273973",
            "name":"204",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            }
        ]
    }
]
```

答:
Assuming your var is named id:

```<code>var coords = _.detect(polygons[0].sections,
                      function(val) { return val.id == id; }).coords;
</code>```

See example →

ContentLicense: CC BY-SA 3.0

Body:
I want to display a polygon in a bing map. I've got this part down. I'm wondering how I would go about accessing a value from a different key in my json response once I've identified which key's sibling i'm trying to access?

I have this variable on the page:

var = 273972;

I want to match that variable to polygons.sections.id[] in my json response and grab the sibling COORDS value then store that value in a new varaible.

I have jquery and _underscore.js available.

Here is my JSON

"polygons":[
    {
        "id":46327,
        "name":"first set",
        "sections":[
            {
            "id":"273971",
            "name":"202",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273972",
            "name":"203",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273973",
            "name":"204",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            }
        ]
    }
]

Body:
Assuming your var is named id:

var coords = _.detect(polygons[0].sections,
                      function(val) { return val.id == id; }).coords;

See example →


问:
How to make Screen Background Data visible in swift?
I want to make the screen like the following.

In source class, I write this code and push to side menu controller.

```<code>let vc = self.storyboard?.instantiateViewController(withIdentifier: "SidemenuController")as! SidemenuController

self.navigationController?.pushViewController(vc, animated: false)
</code>```

I write the following code in destination controller view did load method but just color opacity is decreased data is not visible.

```<code>override func viewDidLoad() {
    self.view.backgroundColor = self.hexStringToUIColor(hex: "BE8790").withAlphaComponent(0.4)
}
</code>```

答:
You show present your SideViewController. Maybe custom how it shows

```<code> let sideVC = // Your init
 sideVC.modalPresentationStyle = .fullScreen
 present(sideVC, animated: true, completion: nil)
</code>```

In your SideViewController,

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        view.alpha = 0.5
        view.backgroundColor = // Your color
        tableView.backgroundColor = .clear
}
</code>```

Body:
I want to make the screen like the following.

In source class, I write this code and push to side menu controller.

let vc = self.storyboard?.instantiateViewController(withIdentifier: "SidemenuController")as! SidemenuController

self.navigationController?.pushViewController(vc, animated: false)

I write the following code in destination controller view did load method but just color opacity is decreased data is not visible.

override func viewDidLoad() {
    self.view.backgroundColor = self.hexStringToUIColor(hex: "BE8790").withAlphaComponent(0.4)
}

Body:
You show present your SideViewController. Maybe custom how it shows

 let sideVC = // Your init
 sideVC.modalPresentationStyle = .fullScreen
 present(sideVC, animated: true, completion: nil)

In your SideViewController,

override func viewDidLoad() {
        super.viewDidLoad()
        view.alpha = 0.5
        view.backgroundColor = // Your color
        tableView.backgroundColor = .clear
}


问:
Pyspark: Parallelize a UDF
I want to loop through two lists, pass the the combos to a function, and get the following output:

```<code>ru = ['a', 'b', 'c']
ni = ['x', 'y', 'z']

def my_func(ru, ni):
    print("{} + {}".format(ru, ni))

for i in ru:
    for j in ni:
        my_func(i,j)

# Output

a + x
a + y
a + z
b + x
b + y
b + z
c + x
c + y
c + z
</code>```

Since this is Pyspark, I would like to parallelize it, since each iteration of the function can run independently.

Note: My actual function is a long complicated algorithm in pyspark. Just wanted to post an easy example to generalize.

What is the best way to do this?

答:
Use cartesian:

```<code>ru = sc.parallelize(['a', 'b', 'c'])
ni = sc.parallelize(['x', 'y', 'z'])
print(ru.cartesian(ni).collect())
</code>```

For your case,

```<code>ru.cartesian(ni).map(some_func)
</code>```

Or:

```<code>def my_func(ru, ni):
    print("{} + {}".format(ru, ni))

ru.cartesian(ni).foreach(lambda t: my_func(t[0], t[1]))

a + z
a + y
a + x
b + y
b + x
b + z
c + y
c + x
c + z
</code>```

Title: Pyspark: Parallelize a UDF

Body:
I want to loop through two lists, pass the the combos to a function, and get the following output:

ru = ['a', 'b', 'c']
ni = ['x', 'y', 'z']

def my_func(ru, ni):
    print("{} + {}".format(ru, ni))

for i in ru:
    for j in ni:
        my_func(i,j)

# Output

a + x
a + y
a + z
b + x
b + y
b + z
c + x
c + y
c + z

Since this is Pyspark, I would like to parallelize it, since each iteration of the function can run independently.

Note: My actual function is a long complicated algorithm in pyspark. Just wanted to post an easy example to generalize.

What is the best way to do this?

Body:
Use cartesian:

ru = sc.parallelize(['a', 'b', 'c'])
ni = sc.parallelize(['x', 'y', 'z'])
print(ru.cartesian(ni).collect())

For your case,

ru.cartesian(ni).map(some_func)

Or:

def my_func(ru, ni):
    print("{} + {}".format(ru, ni))

ru.cartesian(ni).foreach(lambda t: my_func(t[0], t[1]))

a + z
a + y
a + x
b + y
b + x
b + z
c + y
c + x
c + z


问:
Octave Code for Minimum and Max and finding index
Hello everyone,
I've been trying to code this program to find the max and min values in a row vector and I had a problem with assigning their dimension indexes
I can't figure out what's wrong
C and D always show to be "1"
i'm a beginner can you please help me

```<code>function [low,high,index1,index2] = Q1(x)
low = x(1);
high = x(1);
  index1 = x(1,2);
  index2 = x(1,2);
    for i = 2:length(x),
        if x(i) < low,
            low = x(i);
        index1 = find(low);
        elseif x(i) > high,

        high = x(i);
    index2 = find(high);

endif;
    endfor;
endfunction
</code>```

答:
the index1 and index2 should start with 1 as low and high start with element x(1). When you detect a condition assign x(i) to the value and i to the relative index.

```<code>function [low,high,index1,index2] = Q1(x)
low = x(1);
high = x(1);
index1 = 1;
index2 = 1;
    for i = 2:length(x),
        if (x(i) < low)
            low = x(i);
            index1 = i;
        elseif (x(i) > high)
            high = x(i);
            index2 = i;
        endif
    endfor;
endfunction
</code>```

using random data for testing

```<code>octave:1> x=rand(10,1)
x =

   0.90588
   0.20695
   0.46777
   0.67169
   0.69547
   0.24960
   0.16570
   0.62231
   0.18489
   0.36467

octave:2> Q1(x)
ans =  0.16570
octave:3> [low,high,index_low,index_high]=Q1(x)
low =  0.16570
high =  0.90588
index_low =  7
index_high =  1
</code>```

Body:
Hello everyone,
I've been trying to code this program to find the max and min values in a row vector and I had a problem with assigning their dimension indexes
I can't figure out what's wrong
C and D always show to be "1"
i'm a beginner can you please help me

function [low,high,index1,index2] = Q1(x)
low = x(1);
high = x(1);
  index1 = x(1,2);
  index2 = x(1,2);
    for i = 2:length(x),
        if x(i) < low,
            low = x(i);
        index1 = find(low);
        elseif x(i) > high,

        high = x(i);
    index2 = find(high);

endif;
    endfor;
endfunction

Body:
the index1 and index2 should start with 1 as low and high start with element x(1). When you detect a condition assign x(i) to the value and i to the relative index.

function [low,high,index1,index2] = Q1(x)
low = x(1);
high = x(1);
index1 = 1;
index2 = 1;
    for i = 2:length(x),
        if (x(i) < low)
            low = x(i);
            index1 = i;
        elseif (x(i) > high)
            high = x(i);
            index2 = i;
        endif
    endfor;
endfunction

using random data for testing

octave:1> x=rand(10,1)
x =

   0.90588
   0.20695
   0.46777
   0.67169
   0.69547
   0.24960
   0.16570
   0.62231
   0.18489
   0.36467

octave:2> Q1(x)
ans =  0.16570
octave:3> [low,high,index_low,index_high]=Q1(x)
low =  0.16570
high =  0.90588
index_low =  7
index_high =  1


问:
Is it possible to use if...else... statement in React render function?
Basically, I have a react component, its render() function body is as below: (It is my ideal one, which means it currently does not work)

render(){
    return (

            <Element1/>
            <Element2/>

            // note: logic only, code does not work here
            if (this.props.hasImage) <ElementWithImage/>
            else <ElementWithoutImage/>

    )
}
```

答:
Type 1: If statement style

```<code>{props.hasImage &&

  <MyImage />

}
</code>```

Type 2: If else statement style

```<code>   {props.hasImage ?

      <MyImage /> :

      <OtherElement/>

    }
</code>```

Body:
Type 1: If statement style

{props.hasImage &&

  <MyImage />

}

Type 2: If else statement style

   {props.hasImage ?

      <MyImage /> :

      <OtherElement/>

    }


问:
Can't fill the height of the window with my navbar
I'm having this problem with the menu in my code.
I wanted to do a navbar that on the PC screen fill the height on the left side, and make it scrolleable on the top in mobile version.

The problem is that my flex container doesn't fill the height of the screen,it's getting off on the bottom..
Here's my code:

/* css */

body {
  margin: 0;
}

#main-doc {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
}

#container-nav {
  position: fixed;
  height: 100%;
  width: 13.35em;
  display: flex;
  flex-direction: column;
  background-color: red;
}

#nav-header {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
}

.nav-link {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
  background: green;
}

#container-nav {
  padding: 1em;
  display: flex;
  flex-direction: column;
}

@media screen and (max-width: 780px) {
  #container-nav {
    position: absolute;
    width: 100%;
    padding: 0;
    overflow-y: scroll;
    height: 20%;
    border-right: none;
  }
  #main-doc {
    display: flex;
    flex-flow: column wrap;
  }
  #nav-header {
    flex: 0;
  }
  .nav-link {
    flex: 0;
    padding: 1em;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- html -->
<main id="main-doc">

  <nav id="navbar">
    <div id="container-nav">
      <header class="nav-link" id="nav-header">Flexbox Documentation</header>

      About
      Basics
      Flex Container Properties
      Flex Items Properties
      Examples

    </div>
  </nav>
</main></code>```

答:
Have you tried using vh?

1vh is relative to 1% of the screen's height, so trying setting your height to 100vw

E.G. #container-nav { height: 100vh; }

More Info Here

Body:
I'm having this problem with the menu in my code.
I wanted to do a navbar that on the PC screen fill the height on the left side, and make it scrolleable on the top in mobile version.

The problem is that my flex container doesn't fill the height of the screen,it's getting off on the bottom..
Here's my code:

/* css */

body {
  margin: 0;
}

#main-doc {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
}

#container-nav {
  position: fixed;
  height: 100%;
  width: 13.35em;
  display: flex;
  flex-direction: column;
  background-color: red;
}

#nav-header {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
}

.nav-link {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
  background: green;
}

#container-nav {
  padding: 1em;
  display: flex;
  flex-direction: column;
}

@media screen and (max-width: 780px) {
  #container-nav {
    position: absolute;
    width: 100%;
    padding: 0;
    overflow-y: scroll;
    height: 20%;
    border-right: none;
  }
  #main-doc {
    display: flex;
    flex-flow: column wrap;
  }
  #nav-header {
    flex: 0;
  }
  .nav-link {
    flex: 0;
    padding: 1em;
  }
}

      Flexbox Documentation

      About
      Basics
      Flex Container Properties
      Flex Items Properties
      Examples


问:
Autoplay just one time when you access the page
I am a beginner in web development, i want put a youtube iframe with autoplay, but just for the first visit, using something cookie or variable for control it.

When i visit the site for the second time, the video wont autoplay.

Is it posible?

答:
Logic should be easy.
When a user visits the website, check the user has the cookie.
If not, assign him the cookie.
If yes, do nothing.

And on adding parameters to Youtube Iframe, you should check the cookie is set or not and depending on that add the autoplay parameter.

The below links will help and have the complete solution you are looking for. I am not reinventing the solution since they are already been posted.

Youtube Documentation:

https://developers.google.com/youtube/player_parameters

For Setting and Retrieving Cookie with Vanilla JavaScript:

Set cookie and get cookie with JavaScript


问:
Get HomeTeam ID and AwayTeam ID of each game for a specific date
I have 2 tables:

Table 1 called teams: that contains different columns like Team_ID, Team_Name... etc.

table 2 called matches: that contains different columns like Match_ID, Home, Away, Match_Date.

Home and away are the names of 2 teams that I generated,
I tried different queries to generate a result where I have teams ID instead of teams names
for example:

```<code>SELECT t1.Home,t2.Away from

(SELECT a.Team_ID AS Home, b.Match_Date from teams a
INNER JOIN matches b ON a.Team_Name=b.Home
Where b.Match_Date="2020-05-29 23:59:59") t1,

(SELECT a.Team_ID AS Away, b.Match_Date from teams a
INNER JOIN matches b on a.Team_Name=b.Away
Where b.Match_Date="2020-05-29 23:59:59") t2;
</code>```

But it didn't give me the result that I'm looking for
and After getting the result, I just to want filter it using a specific date like WHERE Match_Date= "date"

An image to clarify what I'm trying to do:

答:
You want two joins on teams (one for the home team and the other for the away team), and a where clause to filter on the match date:

```<code>select th.team_id home, ta.team_id away, m.match_date
from matches m
inner join teams th on th.team_name = m.home
inner join teams ta on ta.team_name = m.away
where m.match_date = 'date1'
</code>```

Note that you should not be storing the team name in matches, but the team id instead (which, presumably, is the primary key of teams).

Body:
I have 2 tables:

Table 1 called teams: that contains different columns like Team_ID, Team_Name... etc.

table 2 called matches: that contains different columns like Match_ID, Home, Away, Match_Date.

Home and away are the names of 2 teams that I generated,
I tried different queries to generate a result where I have teams ID instead of teams names
for example:

SELECT t1.Home,t2.Away from

(SELECT a.Team_ID AS Home, b.Match_Date from teams a
INNER JOIN matches b ON a.Team_Name=b.Home
Where b.Match_Date="2020-05-29 23:59:59") t1,

(SELECT a.Team_ID AS Away, b.Match_Date from teams a
INNER JOIN matches b on a.Team_Name=b.Away
Where b.Match_Date="2020-05-29 23:59:59") t2;

But it didn't give me the result that I'm looking for
and After getting the result, I just to want filter it using a specific date like WHERE Match_Date= "date"

An image to clarify what I'm trying to do:

Body:
You want two joins on teams (one for the home team and the other for the away team), and a where clause to filter on the match date:

select th.team_id home, ta.team_id away, m.match_date
from matches m
inner join teams th on th.team_name = m.home
inner join teams ta on ta.team_name = m.away
where m.match_date = 'date1'

Note that you should not be storing the team name in matches, but the team id instead (which, presumably, is the primary key of teams).


问:
MVC razor view @model - is it possible to define multiple interfaces
Have Interface1 and Interface2, the question is it possible to use them in partial view as following

```<code>@model Interface1, Interface2
</code>```

my studio underline everything as wrong statement.

I do realize that I can define Interface which inherited from Interface1, Interface2 as a workaround this limitation. But it would be nice to know if there some special syntax to do it directly.

Thanks.

答: Just use a single interface that that implements 2 or more interfaces</p>

Body:
Have Interface1 and Interface2, the question is it possible to use them in partial view as following

@model Interface1, Interface2

my studio underline everything as wrong statement.

I do realize that I can define Interface which inherited from Interface1, Interface2 as a workaround this limitation. But it would be nice to know if there some special syntax to do it directly.

Thanks.


问:
Why 'bundler gem' adds 'rake' and 'rspec' to Gemfile and not to .gemspec file as a development dependencies?
I am not well familiar with Ruby world. Java build tools usually use test scope for things like jUnit.

I initialized a new project with command: bundle gem new_gem_from_bundler and the content of Gemfile is

```<code>source "https://rubygems.org"

# Specify your gem's dependencies in new_gem_from_bundler.gemspec
gemspec

gem "rake", "~> 12.0"
gem "rspec", "~> 3.0"
</code>```

Why not:

```<code>group :development do
  gem "rspec", "~> 3.9.0"
  gem "rake", "~> 3.0"
end
</code>```

Also since there is a .gemspec file I would expect rake and rspec to be defined like this:

```<code>spec.add_development_dependency 'rake', '~> 12.0'
spec.add_development_dependency 'rspec', '~> 3.0'
</code>```

Why are they declared as a regular 'gem' dependencies?

答:
Bundler uses template files for creating new gems. You could change the template files Gemfile.tt and newgem.gemspec.tt according to your needs. For example you could use this Gemfile.tt:

source "https://rubygems.org"

# Specify your gem's dependencies in <%= config[:name] %>.gemspec
gemspec
```

<p>To find where the template files are you could use this shell command:</p>

<pre class="lang-sh prettyprint-override"><code>find $(dirname $(gem which -g bundler)) -name Gemfile.tt
</code>```

Body:
I am not well familiar with Ruby world. Java build tools usually use test scope for things like jUnit.

I initialized a new project with command: bundle gem new_gem_from_bundler and the content of Gemfile is

source "https://rubygems.org"

# Specify your gem's dependencies in new_gem_from_bundler.gemspec
gemspec

gem "rake", "~> 12.0"
gem "rspec", "~> 3.0"

Why not:

group :development do
  gem "rspec", "~> 3.9.0"
  gem "rake", "~> 3.0"
end

Also since there is a .gemspec file I would expect rake and rspec to be defined like this:

spec.add_development_dependency 'rake', '~> 12.0'
spec.add_development_dependency 'rspec', '~> 3.0'

Why are they declared as a regular 'gem' dependencies?

Body:
Bundler uses template files for creating new gems. You could change the template files Gemfile.tt and newgem.gemspec.tt according to your needs. For example you could use this Gemfile.tt:

source "https://rubygems.org"

# Specify your gem's dependencies in <%= config[:name] %>.gemspec
gemspec

To find where the template files are you could use this shell command:

find $(dirname $(gem which -g bundler)) -name Gemfile.tt


问:
What is the best way to style a vertical table with split background
How can I organize and style this data on a split background using css and html?

答:
that layout of yours (if that's what you want right?), you need to collapse your table border for that, to avoid white gaps. add a special class for tr that represents the thead and style it accordingly. follow the pattern with

. use text-align to center them with right to th and left to td.

td, th {
  padding: 8px;
  font-size: 12px;
  width: 250px;
}

th { background: #E9EADA; text-align: right; }
td { background: #FCFCFC; text-align: left; }

.table-header > * {
  font-size: 16px;
  color: #238E98;
}

table { border-collapse: collapse; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>First name</th>
    <td>John</td>
  </tr>
  <tr>
    <th>Last Name</th>
    <td>Doe</td>
  </tr>
  <tr class="table-header">
    <th>Details</th>
    <td>---</td>
  </tr>
  <tr>
    <th>Age</th>
    <td>33</td>
  </tr>
</table></code>```

Body:
that layout of yours (if that's what you want right?), you need to collapse your table border for that, to avoid white gaps. add a special class for tr that represents the thead and style it accordingly. follow the pattern with <tr><th></th><td></td></tr>. use text-align to center them with right to th and left to td.

td, th {
  padding: 8px;
  font-size: 12px;
  width: 250px;
}

th { background: #E9EADA; text-align: right; }
td { background: #FCFCFC; text-align: left; }

.table-header > * {
  font-size: 16px;
  color: #238E98;
}

table { border-collapse: collapse; }

<table>
  <tr>
    <th>First name</th>
    <td>John</td>
  </tr>
  <tr>
    <th>Last Name</th>
    <td>Doe</td>
  </tr>
  <tr class="table-header">
    <th>Details</th>
    <td>---</td>
  </tr>
  <tr>
    <th>Age</th>
    <td>33</td>
  </tr>
</table>


问:
Kubernetes Ingress gets Error while it works in minikube ssh
I am testing kubernetes with minikube on centOS 7, following the follow progress:

Build 2 docker images running simple backend with express.js

Running deployment to serve totally 4 pods, 2 of each image respectively

Serving service with the pods

Using ingress to access the services

When I gets into the minikube by minikube ssh, the APIs all work properly.
However, outside of it, it always get error.
So guess it must be error in 3 or 4?  But it doesn't get connection error (as it once was before setup properly).  Can it be security settings or what?

Settings & results as below:

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: abc
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: abc
    spec:
      containers:
        - name: nginx
          image: image/abc
          imagePullPolicy: Never
          ports:
            - containerPort: 3000
  selector:
    matchLabels:
      app: abc
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: efg
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: efg
    spec:
      containers:
        - name: nginx
          image: image/efg
          imagePullPolicy: Never
          ports:
            - containerPort: 3000
  selector:
    matchLabels:
      app: efg
```

<ul>
<li>service.yaml</li>
</ul>

<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
  name: abc-service
spec:
  type: NodePort
  selector:
    app: abc
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: efg-service
spec:
  type: NodePort
  selector:
    app: efg
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
</code>```

ingress.yaml

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: web
spec:
  rules:
    - host: my.host.com
      http:
        paths:
          - path: /abc
            backend:
              serviceName: abc-service
              servicePort: 80
          - path: /efg
            backend:
              serviceName: efg-service
              servicePort: 80
```

<ul>
<li><code>kubectl describe</code> result:</li>
</ul>

```Name:             web
Namespace:        default
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host         Path    Backends
  ----         ----    --------
  my.host.com
               /abc    abc-service:80 (172.18.0.4:3000,172.18.0.6:3000)
               /efg    efg-service:80 (172.18.0.5:3000,172.18.0.7:3000)
Annotations:   Events
  Type         Reason  Age               From                      Message
  ----         ------  ----              ----                      -------
  Normal       CREATE  24m               nginx-ingress-controller  Ingress default/web
  Normal       UPDATE  3s (x4 over 23m)  nginx-ingress-controller  Ingress default/web
```

<ul>
<li><p><code>minikube ip</code> gets <code>172.17.0.4</code></p></li>
<li><p>/etc/hosts</p></li>
</ul>

```172.17.0.4    my.host.com
```

<ul>
<li>Running <code>curl 172.18.0.4:3000</code> gets the expected result (json) successfully</li>
<li>Running <code>curl my.host.com/abc</code>, it gets</li>
</ul>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
```Cannot GET /abc```
</body>
</html>
</code>```

答:
Finally my kubernetes works.  Here to sum up the progress:

As suggestion in comments above, add nginx.ingress.kubernetes.io/rewrite-target: / in annotations of ingress.yaml

But then the new issue was that, every route maps samely to the root api of each service.  Here's the solution: ingress routing api prefix issue

Finally my new ingress.yaml:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: web
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - host: my.host.com
      http:
        paths:
          - path: /abc/?(.*)
            backend:
              serviceName: abc-service
              servicePort: 80
          - path: /efg/?(.*)
            backend:
              serviceName: efg-service
              servicePort: 80
</code>```

Then I can now access my APIs:

my.host.com/abc/ (one thing to highlight is that the final / is required here, otherwise it gets 404 Error)

my.host.com/abc/child

my.host.com/efg/

my.host.com/efg/child

May be somehow helpful for others also new to K8s now or after.

Body:
I am testing kubernetes with minikube on centOS 7, following the follow progress:

Build 2 docker images running simple backend with express.js

Running deployment to serve totally 4 pods, 2 of each image respectively

Serving service with the pods

Using ingress to access the services

When I gets into the minikube by minikube ssh, the APIs all work properly.
However, outside of it, it always get error.
So guess it must be error in 3 or 4?  But it doesn't get connection error (as it once was before setup properly).  Can it be security settings or what?

Settings & results as below:

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: abc
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: abc
    spec:
      containers:
        - name: nginx
          image: image/abc
          imagePullPolicy: Never
          ports:
            - containerPort: 3000
  selector:
    matchLabels:
      app: abc
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: efg
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: efg
    spec:
      containers:
        - name: nginx
          image: image/efg
          imagePullPolicy: Never
          ports:
            - containerPort: 3000
  selector:
    matchLabels:
      app: efg

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: abc-service
spec:
  type: NodePort
  selector:
    app: abc
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: efg-service
spec:
  type: NodePort
  selector:
    app: efg
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000

ingress.yaml

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: web
spec:
  rules:
    - host: my.host.com
      http:
        paths:
          - path: /abc
            backend:
              serviceName: abc-service
              servicePort: 80
          - path: /efg
            backend:
              serviceName: efg-service
              servicePort: 80

kubectl describe result:

Name:             web
Namespace:        default
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host         Path    Backends
  ----         ----    --------
  my.host.com
               /abc    abc-service:80 (172.18.0.4:3000,172.18.0.6:3000)
               /efg    efg-service:80 (172.18.0.5:3000,172.18.0.7:3000)
Annotations:   Events
  Type         Reason  Age               From                      Message
  ----         ------  ----              ----                      -------
  Normal       CREATE  24m               nginx-ingress-controller  Ingress default/web
  Normal       UPDATE  3s (x4 over 23m)  nginx-ingress-controller  Ingress default/web

minikube ip gets 172.17.0.4

/etc/hosts

172.17.0.4    my.host.com

Running curl 172.18.0.4:3000 gets the expected result (json) successfully

Running curl my.host.com/abc, it gets

<!DOCTYPE html>

<meta charset="utf-8">
<title>Error</title>

Cannot GET /abc

Body:
Finally my kubernetes works.  Here to sum up the progress:

As suggestion in comments above, add nginx.ingress.kubernetes.io/rewrite-target: / in annotations of ingress.yaml

But then the new issue was that, every route maps samely to the root api of each service.  Here's the solution: ingress routing api prefix issue

Finally my new ingress.yaml:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: web
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - host: my.host.com
      http:
        paths:
          - path: /abc/?(.*)
            backend:
              serviceName: abc-service
              servicePort: 80
          - path: /efg/?(.*)
            backend:
              serviceName: efg-service
              servicePort: 80

Then I can now access my APIs:

my.host.com/abc/ (one thing to highlight is that the final / is required here, otherwise it gets 404 Error)

my.host.com/abc/child

my.host.com/efg/

my.host.com/efg/child

May be somehow helpful for others also new to K8s now or after.


问:
Specifying the Source of Toolbox-parsed AST
I'm using a toolbox from Scala's compiler API to compile code into ASTs and then dissecting/splicing them and combining them into a single tree.  For debugging purposes I'm trying to track which nodes came from which source code.

Example:

```<code>import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

// obtain toolbox
val tb = runtimeMirror(this.getClass.getClassLoader).mkToolBox()
// get and parse source code from file
val myCode = scala.io.Source.fromFile("MyCode.scala").mkString
val myTree = tb.parse(myCode)
// get and parse dynamically-generated source code
val genCode = com.example.CodeGenerator.gimmeCode
val genTree = tb.parse(genCode)
// get and parse source code from a string literal
val literalCode = """println("to life, the universe, and everything")"""
val literalTree = tb.parse(literalCode)
// an over-simplified combination of the trees
val frankensteinsTree = q"$myTree;$genTree;$literalTree"

// walk the tree an print the source of each element
val traverser = new Traverser() {

  override def traverse(tree: Tree): Unit = {

    println("This node originated from " + tree.pos.source)
    super.traverse(tree)
  }
}

// the root element prints "This node originated from <no source file>"
// the rest print "This node originated from <toolbox>"
traverser.traverse(frankensteinsTree)
</code>```

In the above example all but the root node show that the source is the <toolbox>.  (The root node says <no source file>.)  Before dissecting and recombining them, is there a way to specify tree.pos.source to identify each node's actual origin instead?

答: No, it can't currently (as of 2020-05-28) be done.</p>

Body:
I'm using a toolbox from Scala's compiler API to compile code into ASTs and then dissecting/splicing them and combining them into a single tree.  For debugging purposes I'm trying to track which nodes came from which source code.

Example:

import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

// obtain toolbox
val tb = runtimeMirror(this.getClass.getClassLoader).mkToolBox()
// get and parse source code from file
val myCode = scala.io.Source.fromFile("MyCode.scala").mkString
val myTree = tb.parse(myCode)
// get and parse dynamically-generated source code
val genCode = com.example.CodeGenerator.gimmeCode
val genTree = tb.parse(genCode)
// get and parse source code from a string literal
val literalCode = """println("to life, the universe, and everything")"""
val literalTree = tb.parse(literalCode)
// an over-simplified combination of the trees
val frankensteinsTree = q"$myTree;$genTree;$literalTree"

// walk the tree an print the source of each element
val traverser = new Traverser() {

  override def traverse(tree: Tree): Unit = {

    println("This node originated from " + tree.pos.source)
    super.traverse(tree)
  }
}

// the root element prints "This node originated from <no source file>"
// the rest print "This node originated from <toolbox>"
traverser.traverse(frankensteinsTree)

In the above example all but the root node show that the source is the <toolbox>.  (The root node says <no source file>.)  Before dissecting and recombining them, is there a way to specify tree.pos.source to identify each node's actual origin instead?


问:
camel gcp pubsub attributes maxMessagesPerPoll is creating problems when I have the number more than 1
My Apache Camel app takes messages from gcp pubsub  subscrption producer-sub , and then after processing and translating the messages puts them in a gcp pubsub topic1

Here is my camel subscription code

from("google-pubsub://mygcpcloudpubsub-270721:producer-sub?concurrentConsumers=10&maxMessagesPerPoll=1") .process(new TranslationProcessor(route)). to("google-pubsub://mygcpcloudpubsub-270721:topic1").end

All looks good as long as maxMessagesPerPoll=1

Moment I make it say 100 i.e. maxMessagesPerPoll=100,all hell breaks loose.

For example if my test code pumps 1000 messages to producer-topic (producer-sub is the subscriber) ,now my app ends up publishing 1300 messages to topic1.Sometimes 1430...etc.My camel route is messed up !

It appears there is a bug in maxMessagesPerPoll parameter of gcp pubsub component of apache camel.

Please let me know if I am missing anything.

答:
I found the problem.For huge amount of messages,my ack deadline of 10 seconds was too small.Hence the messages were redelivered by pubsub.I increase the deadline to 10 minutes....now there are no duplicate messages !!!

Thanks again


问:
Creating 10 categorical and 10 continuous random variables and save them as a data frame
I would like to create a data frame with 10 categorical and 10 continuous random variables. I can do it using the following loop.

```<code>   p_val=rbeta(10,1,1)   #10 probabilities
    n=20
    library(truncnorm)
    mu_val=rtruncnorm(length(p_val),0,Inf, mean = 100, sd=5)#rnorm(length(p))
    d_mat_cat=matrix(NA, nrow = n, ncol = length(p))
    d_mat_cont= matrix(NA, nrow = n, ncol = length(p))
      for ( j in 1:length(p)){
        d_mat_cat[,j]=rbinom(n,1,p[j]) #Binary RV
        d_mat_cont[,j]=rnorm(n,mu_val[j]) #Cont. RV
      }
    d_mat=cbind(d_mat_cat, d_mat_cont)
</code>```

Any alternative options are appreciated.

答:
You can try using sapply to run rbinom and rnorm and cbind the data.

```<code>cbind(sapply(p_val, rbinom, n = n, size = 1), sapply(mu_val, rnorm, n = n))
</code>```

Body:
I would like to create a data frame with 10 categorical and 10 continuous random variables. I can do it using the following loop.

   p_val=rbeta(10,1,1)   #10 probabilities
    n=20
    library(truncnorm)
    mu_val=rtruncnorm(length(p_val),0,Inf, mean = 100, sd=5)#rnorm(length(p))
    d_mat_cat=matrix(NA, nrow = n, ncol = length(p))
    d_mat_cont= matrix(NA, nrow = n, ncol = length(p))
      for ( j in 1:length(p)){
        d_mat_cat[,j]=rbinom(n,1,p[j]) #Binary RV
        d_mat_cont[,j]=rnorm(n,mu_val[j]) #Cont. RV
      }
    d_mat=cbind(d_mat_cat, d_mat_cont)

Any alternative options are appreciated.

Body:
You can try using sapply to run rbinom and rnorm and cbind the data.

cbind(sapply(p_val, rbinom, n = n, size = 1), sapply(mu_val, rnorm, n = n))


问:
How do you copy project files into build folder post-build in azure devops pipeline?
We have a build pipeline set up with a "Visual Studio Build" step. I just need it to copy one of the project files into the build folder before publishing it to our server. Trying to copy a .runsettings project file for unit testing.
So far I've tried setting the file to "Copy to Output Directory" in its properties, I've tried using both copy and xcopy in the post-build event command line and tried a few different syntaxes for that in the xml csproj project file. Everything that seems to work fine locally, doesn't do anything through azure. My brain has been wracked thoroughly!

Any help would be greatly appreciated!

Edit:
This is what the copy settings look like:

I tried this as well as ***.runsettings in contents as suggested.

Here is the log from my last copy attempt

2020-05-29T20:07:01.3481827Z ##[section]Starting: Copy .runsettings to: E:\Backend_work\116\a
  2020-05-29T20:07:01.3669241Z ==============================================================================
  2020-05-29T20:07:01.3669530Z Task         : Copy files
  2020-05-29T20:07:01.3669781Z Description  : Copy files from a source folder to a target folder using patterns matching file paths (not folder paths)
  2020-05-29T20:07:01.3670032Z Version      : 2.164.1
  2020-05-29T20:07:01.3670179Z Author       : Microsoft Corporation
  2020-05-29T20:07:01.3670406Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/copy-files
  2020-05-29T20:07:01.3670656Z ==============================================================================
  2020-05-29T20:07:01.9575993Z found 1 files
  2020-05-29T20:07:01.9583367Z Copying E:\Backend_work\116\s\UnitTests.runsettings to E:\Backend_work\116\a.runsettings
  2020-05-29T20:07:01.9674455Z ##[section]Finishing: Copy .runsettings to: E:\Backend_work\116\a

答:
I've tested with the following post-build event command line and it copied the file in pipeline as expected:

copy "$(ProjectDir)Settings1.runsettings" "$(SolutionDir)TestCaseProject\bin\$(ConfigurationName)\*"

Pipeline log:

Including using enter image description here, you can also try adding a Copy files task in Pipeline to copy the file:


问:
run local script with flags to remote machine using ssh
I need to achieve similar functionality in a go program as below.

ssh user@host "python" -  < ./test.py -f bar

I'm able to achieve the highlighted part now I just need to pass flags with the script file.

below is the code for highlighted part.

```<code>package main
import (
    "log"
    "os"

    "golang.org/x/crypto/ssh"
)

func main()  {
    user := "user"
    hostport := "10.10.10.10:22"
    script, _ := os.OpenFile("test.py", os.O_RDWR|os.O_CREATE, 0755)
    interpreter := "python3"
    client, session, err := connectToHost(user, hostport)
    session.Stdin = script
    session.Stdout = os.Stdout
    err = session.Run(interpreter)
    if err != nil {
        log.Fatal(err)
    }
    client.Close()
    defer session.Close()
}
</code>```

答:
As you're using redirection, you could let bash handle it:

```<code>bash -c "<command>"
</code>```

Pass this to session.Run(...)

Body:
I need to achieve similar functionality in a go program as below.

ssh user@host "python" -  < ./test.py -f bar

I'm able to achieve the highlighted part now I just need to pass flags with the script file.

below is the code for highlighted part.

package main
import (
    "log"
    "os"

    "golang.org/x/crypto/ssh"
)

func main()  {
    user := "user"
    hostport := "10.10.10.10:22"
    script, _ := os.OpenFile("test.py", os.O_RDWR|os.O_CREATE, 0755)
    interpreter := "python3"
    client, session, err := connectToHost(user, hostport)
    session.Stdin = script
    session.Stdout = os.Stdout
    err = session.Run(interpreter)
    if err != nil {
        log.Fatal(err)
    }
    client.Close()
    defer session.Close()
}

Body:
As you're using redirection, you could let bash handle it:

bash -c "<command>"

Pass this to session.Run(...)


问:
Split 1TB file using Azure Data Lake Analytics / U-SQL
I have a 1TB Text file which has some text data in it. I want to split it into smaller chunks of data using Azure Data Lake Analytics / U-SQL. </p>

<p>How can I achieve this? </p>

答:
I recommend to use ADF’s Mapping Data Flow feature which is built on Spark in the Cloud

1.Create a new Data Flow

2.Add a Source file

3.Add a Sink folder by defining partitioning

4.Save the data flow

5.Then add a Execute Data Flow activity and select your new file split data flow

Body:
I have a 1TB Text file which has some text data in it. I want to split it into smaller chunks of data using Azure Data Lake Analytics / U-SQL.

How can I achieve this?


问:
User defined rest endpoints in Spring Boot
So i am trying to allow the user to define a rest API and deploy it without having to restart the server. Essentially, they should be able to define endpoint: /customInfo followed by listing out the expected inputs and outputs and some command it should run. The command processing is handled in the back. It is not something i am worried about.

From whatever research I have done, the only approach i found is to use a controller with a wildcard \* like this. But this seems like a slightly janky approach.  Any help would be useful.

答:
This is something I've never seen anyone try before but...maybe you can fiddle around with something like this:

Have a single endpoint that takes in a "command" as the path variable. It can take  "freeform" Json as input and return freeform Json as the output. My example below uses the common Map approach.

This way, that "command" path variable will be whatever the client defines and the input and output are totally up to the client and the backend process.

```<code>@PostMapping("{command}")
public Map<String, Object> runCommand(@PathVariable String command, @RequestBody Map<String, Object> input) {
     return yourProcessingService.process(command, input);
}

</code>```

Body:
This is something I've never seen anyone try before but...maybe you can fiddle around with something like this:

Have a single endpoint that takes in a "command" as the path variable. It can take  "freeform" Json as input and return freeform Json as the output. My example below uses the common Map approach.

This way, that "command" path variable will be whatever the client defines and the input and output are totally up to the client and the backend process.

@PostMapping("{command}")
public Map<String, Object> runCommand(@PathVariable String command, @RequestBody Map<String, Object> input) {
     return yourProcessingService.process(command, input);
}


问:
Android custom views not being draw and canvas maximum size
I'm developing an application that has an embedded chat on it.
In order to draw the bubbles* where the text is displayed, I'm using a custom view which extends from FrameLayout, just like in here:

https://github.com/florent37/ShapeOfView/blob/master/shapeofview/src/main/java/com/github/florent37/shapeofview/ShapeOfView.java

or here:

https://github.com/MasayukiSuda/BubbleLayout/blob/master/bl/src/main/java/com/daasuu/bl/BubbleLayout.java

*bubbles -> you know: the rounded corner rectangle with a little arrow at the left or right, depending on who wrote the message

The thing is that, if the message to be shown is long enough (a couple of thousands of characters depending on the phone's memory) the background drawable is not shown anymore.

I found that this is expected because I'm exceeding the maximum canvas size (the maximum height, in this case)

I know that the canvas maximum size in android depends on the phone on which you are measuring it.
For example, this is the limit for an old phone (Moto G 1st gen):

And this is the limit for a newer phone, with more memory:

Question: Is there another way you can think of, to define a view with an arbitrary shape as the background which overcomes this limitation?

PD: Yes, the code looks strange because I'm using xamarin to develop, but the question is general enough, and I don't care the language of the solution if it does exist :)

UPDATE
Added example code to reproduce this issue.

You just have to create any background in xml, let's say that we call it "bubble_background.xml":

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
</code>```

And then use it as background for a TextView, like in :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bubble"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
   <TextView
        android:id="@+id/cell_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        android:autoLink="all"
        android:linksClickable="true"
        android:textSize="@dimen/atlas_text_size_message_item"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        android:background="@drawable/bubble_background" />
</LinearLayout>
</code>```

Now, if your text is long enough, the background won't be visible (it is a good idea to wrap the TextView in a ScrollView...)

UPDATE
This is the result of testing the background that was suggested by @cherryBu
Of course, I've got the same result because it is exactly what I was doing, but still, I had to test it, just in case, you know how this is.... :)

The top and bottom thin rectangles with round corners and the little triangle at the right (all in blue) are part of my current solution (one which doesn't make me happy but works: I'm "drawing" the bubble by composing it using those 3 partial images and setting the background of the text to the same color). The text is white, that's why you can't really see much of it. In the current code I'm setting the background to blue (not an image, because it can't be drawn -again :) -, only a plain color; the same as you can see in the other parts of the "bubble")

答:
I'm the one who originally posted the question and the same which suggests the hacky and ugly solution from below.

I found a better and proper solution to this issue: the canvas size limit is only a problem when you have the Hardware acceleration turned on; so once I turned it off, I was able to render bubbles of any size.

The hardware acceleration can be customized in different ways and at different levels: Application, Activity, Window, or even at the View level, with some limitations.

For more information about what can and can't be done, please refer to the Goggle's documentation about this topic: https://developer.android.com/guide/topics/graphics/hardware-accel

Body:
I'm developing an application that has an embedded chat on it.
In order to draw the bubbles* where the text is displayed, I'm using a custom view which extends from FrameLayout, just like in here:

https://github.com/florent37/ShapeOfView/blob/master/shapeofview/src/main/java/com/github/florent37/shapeofview/ShapeOfView.java

or here:

https://github.com/MasayukiSuda/BubbleLayout/blob/master/bl/src/main/java/com/daasuu/bl/BubbleLayout.java

*bubbles -> you know: the rounded corner rectangle with a little arrow at the left or right, depending on who wrote the message

The thing is that, if the message to be shown is long enough (a couple of thousands of characters depending on the phone's memory) the background drawable is not shown anymore.

I found that this is expected because I'm exceeding the maximum canvas size (the maximum height, in this case)

I know that the canvas maximum size in android depends on the phone on which you are measuring it.
For example, this is the limit for an old phone (Moto G 1st gen):

And this is the limit for a newer phone, with more memory:

Question: Is there another way you can think of, to define a view with an arbitrary shape as the background which overcomes this limitation?

PD: Yes, the code looks strange because I'm using xamarin to develop, but the question is general enough, and I don't care the language of the solution if it does exist :)

UPDATE
Added example code to reproduce this issue.

You just have to create any background in xml, let's say that we call it "bubble_background.xml":

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

And then use it as background for a TextView, like in :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bubble"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
   <TextView
        android:id="@+id/cell_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        android:autoLink="all"
        android:linksClickable="true"
        android:textSize="@dimen/atlas_text_size_message_item"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        android:background="@drawable/bubble_background" />
</LinearLayout>

Now, if your text is long enough, the background won't be visible (it is a good idea to wrap the TextView in a ScrollView...)

UPDATE
This is the result of testing the background that was suggested by @cherryBu
Of course, I've got the same result because it is exactly what I was doing, but still, I had to test it, just in case, you know how this is.... :)

The top and bottom thin rectangles with round corners and the little triangle at the right (all in blue) are part of my current solution (one which doesn't make me happy but works: I'm "drawing" the bubble by composing it using those 3 partial images and setting the background of the text to the same color). The text is white, that's why you can't really see much of it. In the current code I'm setting the background to blue (not an image, because it can't be drawn -again :) -, only a plain color; the same as you can see in the other parts of the "bubble")


问:
Microsoft Graph API Access Token Issue
I'm having an issue getting an access token through Postman.

I'm following this process "Flow 2".
http://codematters.tech/getting-access-token-for-microsoft-graph-using-oauth-rest-api/

"Flow 1" worked for me.

This is the given scenario. I am sending a post request with body.

POST https://login.microsoftonline.com/e0xxxxxx-xxxx-xxxx-xxxx-xxxx09d53164/oauth2/v2.0/token

{

client_id:id

client_secret:secret

grant_type:password

username:user

password:pass

scope:openid

}

Response -> "AADSTS90002: Tenant ' ' not found. This may happen if there are no active subscriptions for the tenant.

Why would the Tenant be blank given it was populated?

Thank you for your help.

答:
The URL that you send is wrong. This parameter should not be AAD_name, but tenant.

Try this:

```<code>POST: https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id=xxxxx
&scope=openid
&username=user
&password=pass
&grant_type=password
</code>```

You could find your tenant in App registrations:

For more information, you could see here.

If you want to use {{AAD_name}}, you need to set Environment in postman firstly.

Then you could send the post request like the link shows.

Title: Microsoft Graph API Access Token Issue

Body:
The URL that you send is wrong. This parameter should not be AAD_name, but tenant.

Try this:

POST: https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id=xxxxx
&scope=openid
&username=user
&password=pass
&grant_type=password

You could find your tenant in App registrations:

For more information, you could see here.

If you want to use {{AAD_name}}, you need to set Environment in postman firstly.

Then you could send the post request like the link shows.


问:
Trying to search entity with association Many to Many Sequelize
PROBLEM RESUME:
I'm having trouble when I try to do a findOne or findAll.
At the findOne or findAll answer I catch all the informations from the user but in the answer there aren't any data of "t_roles" associated to this user.
But the stranger issue is that if I use raw: true inside the findOne for example, the informations of roles are shown.

I Have two models

User:

```<code>const dbUser = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_date_created: {
    type: Sequelize.DATE,
    allowNull: false,
  },
  a_first_name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_last_name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_email: {
    type: Sequelize.TEXT,
    unique: true,
    allowNull: false,
  },
  a_password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_birthday: {
    type: Sequelize.DATE,
    allowNull: false,
  },
  a_is_active: {
    type: Sequelize.BOOLEAN,
    allowNull: false,
  },
};

User.init(dbUser, {
  sequelize: db,
  modelName: 't_user',
  timestamps: false,
  tableName: 't_users',
});

User.associate = (models) => {
  console.log('ASSOCIADO')
  User.belongsToMany(models.Role, {
    through: { model: UserRole, unique: false },
    as: 'roles',
    foreignKey: 'a_user',
    otherKey: 'a_role',
  });
};
</code>```

and Role:

```<code>const dbRole = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_role: {
    type: Sequelize.STRING,
    allowNull: false,
  },
};

Role.init(dbRole, {
  sequelize: db,
  modelName: 't_role',
  timestamps: false,
  tableName: 't_roles',
});

Role.associate = (models) => {
  Role.belongsToMany(models.User, {
    through: { model: UserRole, unique: false },
    as: 'UserOfRoles',
    foreignKey: 'a_role',
    otherKey: 'a_user',
  });
};
</code>```

As you can see I'm associating them using another model, UserRole:

```<code>const dbUserRole = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_role: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: false,
    references: {
      model: Role,
      key: 'a_id',
    },
    onDelete: 'CASCADE',
  },
  a_user: {
    type: Sequelize.INTEGER,
    allowNull: false,
    references: {
      model: User,
      key: 'a_id',
    },
    onDelete: 'CASCADE',
  },
};

UserRole.init(dbUserRole, {
  sequelize: db,
  modelName: 't_user_role',
  timestamps: false,
  tableName: 't_user_role',
});

UserRole.associate = (models) => {
  UserRole.belongsTo(models.User, { targetKey: 'a_id', foreignKey: 'a_user' });
  UserRole.belongsTo(models.Role, { targetKey: 'a_id', foreignKey: 'a_role' });
};
</code>```

To create a user with a role (admin) I do like the code below:

```<code>onst createAdmin = async (body) => {
  try {
    const userResult = await createUser(body);
    if (userResult.error) {
      return {
        ok: false,
        error: userResult.error,
      };
    }
    const isAdmin = await UserRole.create({
      a_role: 1,
      a_user: userResult.a_user_id,
    });

    return {
      ok: true,
    };
  } catch (error) {
    return {
      ok: false,
      error,
    };
  }
</code>```

Seems to be working fine, because the user are being created, and the association using the "t_user_role" too, because the data is also being created at the table.
As I sad at the problem resume, my trouble is when I'm trying to do a findOne or findAll.
For example, when I try the code below, I catch all the informations from the user but in the answer there aren't any data of "t_roles" associated to this user.

```<code>const { body } = req;
  try {
    const result = await User.findOne({
      where: {
        a_id: 1,
      },
      include: [
        {
          association: 'roles',
          attributes: ['a_role'],
          through: {
            attributes: [],
          },
        },
      ],
    });
    console.log('====================================');
    console.log(JSON.stringify(result, null, 2));
    console.log('====================================');
  } catch (error) {
    console.error(error);
  }
</code>```

If I use raw: true inside the findOne for example, the informations of roles are shown, so I presume that the association is correct.
I really appreciate any help to find what I'm missing here.
Thanks

答: Well, after days working on and trying different ways to solve this problem, a friend of mine just helped me starting again the entire project, following the documentation of Sequelize and the exact structure we did before, but a little bit more simple, and surprisingly ... worked. So I suppose that was something with migrations ore models or whatever, but we can't really say.</p>

Body:
PROBLEM RESUME:
I'm having trouble when I try to do a findOne or findAll.
At the findOne or findAll answer I catch all the informations from the user but in the answer there aren't any data of "t_roles" associated to this user.
But the stranger issue is that if I use raw: true inside the findOne for example, the informations of roles are shown.

I Have two models

User:

const dbUser = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_date_created: {
    type: Sequelize.DATE,
    allowNull: false,
  },
  a_first_name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_last_name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_email: {
    type: Sequelize.TEXT,
    unique: true,
    allowNull: false,
  },
  a_password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_birthday: {
    type: Sequelize.DATE,
    allowNull: false,
  },
  a_is_active: {
    type: Sequelize.BOOLEAN,
    allowNull: false,
  },
};

User.init(dbUser, {
  sequelize: db,
  modelName: 't_user',
  timestamps: false,
  tableName: 't_users',
});

User.associate = (models) => {
  console.log('ASSOCIADO')
  User.belongsToMany(models.Role, {
    through: { model: UserRole, unique: false },
    as: 'roles',
    foreignKey: 'a_user',
    otherKey: 'a_role',
  });
};

and Role:

const dbRole = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_role: {
    type: Sequelize.STRING,
    allowNull: false,
  },
};

Role.init(dbRole, {
  sequelize: db,
  modelName: 't_role',
  timestamps: false,
  tableName: 't_roles',
});

Role.associate = (models) => {
  Role.belongsToMany(models.User, {
    through: { model: UserRole, unique: false },
    as: 'UserOfRoles',
    foreignKey: 'a_role',
    otherKey: 'a_user',
  });
};

As you can see I'm associating them using another model, UserRole:

const dbUserRole = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_role: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: false,
    references: {
      model: Role,
      key: 'a_id',
    },
    onDelete: 'CASCADE',
  },
  a_user: {
    type: Sequelize.INTEGER,
    allowNull: false,
    references: {
      model: User,
      key: 'a_id',
    },
    onDelete: 'CASCADE',
  },
};

UserRole.init(dbUserRole, {
  sequelize: db,
  modelName: 't_user_role',
  timestamps: false,
  tableName: 't_user_role',
});

UserRole.associate = (models) => {
  UserRole.belongsTo(models.User, { targetKey: 'a_id', foreignKey: 'a_user' });
  UserRole.belongsTo(models.Role, { targetKey: 'a_id', foreignKey: 'a_role' });
};

To create a user with a role (admin) I do like the code below:

onst createAdmin = async (body) => {
  try {
    const userResult = await createUser(body);
    if (userResult.error) {
      return {
        ok: false,
        error: userResult.error,
      };
    }
    const isAdmin = await UserRole.create({
      a_role: 1,
      a_user: userResult.a_user_id,
    });

    return {
      ok: true,
    };
  } catch (error) {
    return {
      ok: false,
      error,
    };
  }

Seems to be working fine, because the user are being created, and the association using the "t_user_role" too, because the data is also being created at the table.
As I sad at the problem resume, my trouble is when I'm trying to do a findOne or findAll.
For example, when I try the code below, I catch all the informations from the user but in the answer there aren't any data of "t_roles" associated to this user.

const { body } = req;
  try {
    const result = await User.findOne({
      where: {
        a_id: 1,
      },
      include: [
        {
          association: 'roles',
          attributes: ['a_role'],
          through: {
            attributes: [],
          },
        },
      ],
    });
    console.log('====================================');
    console.log(JSON.stringify(result, null, 2));
    console.log('====================================');
  } catch (error) {
    console.error(error);
  }

If I use raw: true inside the findOne for example, the informations of roles are shown, so I presume that the association is correct.
I really appreciate any help to find what I'm missing here.
Thanks


问:
Google Place API Json data with python
Update:
after many hours of trial & error.

I was able to get my google Places API json called return data and reduce it  into a list that i can parse.  It most likely is not the best way.  which I know there must be to directly grap the data from the first json data return??????

Here is my code to take return from google api json data.  I take that and reduced fields  and grab the fields I want into shortlist .)

shortlist = []  # list

results is json data from the google api call.

for place in places_result['results']:

#define my place id

```<code>my_place_id = place['place_id']

#define the fields we want sent back to us
my_fields = ['name', 'formatted_phone_number', 'type']

#make a request for the details  drop some fields
place_details = gmaps.place(place_id = my_place_id, fields = my_fields)
</code>```

#save results outside loop in list
    shortlist.append(place_details) # is a list

Sample of Shortlist data:

shortlist data:  just 2 list items just to see format:

{'html_attributions': [], 'result': {'formatted_phone_number': '(760) 864-9900', 'name': 'Palm Greens Cafe', 'types': ['cafe', 'restaurant', 'food', 'point_of_interest', 'store', 'establishment']}, 'status': 'OK'}
{'html_attributions': [], 'result': {'formatted_phone_number': '(760) 459-4555', 'name': 'Townie Bagels | Bakery | Cafe', 'types': ['bakery', 'grocery_or_supermarket', 'cafe', 'restaurant', 'food', 'point_of_interest', 'store', 'establishment']}, 'status': 'OK'}

I am able to grab the fields I need in this loop from shortlist

#### works  list of short results

i = 0
for x in  shortlist:
    try:
        find_name = shortlist[i]['result']['name']
        print(find_name)
        i = i+1

```<code>except(KeyError):
    print('name error')
    i= i+1
    continue
</code>```

#

output from for loop:

Palm Greens Cafe
Townie Bagels | Bakery | Cafe
Starbucks Reserve
McDonald's
Cafe Jasmin
Koffi South Palm Springs
Starbucks
MidMod Café
Gré Coffee House & Art Gallery
Vinny's Italian Ice, Frozen Custard + Ice Cream, Gelato and More
L'Atelier Cafe
Broken Yolk Cafe Palm Springs
Ristretto
Peninsula Pastries Palm Springs
Camelot Internationale Cafe
Rick's Restaurant & Bakery
Starbucks
Swiss Donut
Starbucks
Starbucks

I spent 2 days finally getting this fare.   Just wanted suggestions if there is a more streamline way of doing this?

I could not get the suggested samples to work from reply before this post.

Thanks for the Help.
bill s.

答:
Depending on which library you're using, it may already be parsing the data for you and putting it in a .json field. Otherwise, if it doesn't do it for you, you will indeed need to use json.loads.

Not sure what you mean — most of the time, you would access particular fields in the data, such as: data.json['result']['name']

If you want all the name: value pairs in a dictionary, you can use: for name, value in data.json['result'].items()

Title: Google Place API Json data with python

Body:
Update:
after many hours of trial & error.

I was able to get my google Places API json called return data and reduce it  into a list that i can parse.  It most likely is not the best way.  which I know there must be to directly grap the data from the first json data return??????

Here is my code to take return from google api json data.  I take that and reduced fields  and grab the fields I want into shortlist .)

shortlist = []  # list

results is json data from the google api call.

for place in places_result['results']:

#define my place id

my_place_id = place['place_id']

#define the fields we want sent back to us
my_fields = ['name', 'formatted_phone_number', 'type']

#make a request for the details  drop some fields
place_details = gmaps.place(place_id = my_place_id, fields = my_fields)

#save results outside loop in list
    shortlist.append(place_details) # is a list

Sample of Shortlist data:

shortlist data:  just 2 list items just to see format:

{'html_attributions': [], 'result': {'formatted_phone_number': '(760) 864-9900', 'name': 'Palm Greens Cafe', 'types': ['cafe', 'restaurant', 'food', 'point_of_interest', 'store', 'establishment']}, 'status': 'OK'}
{'html_attributions': [], 'result': {'formatted_phone_number': '(760) 459-4555', 'name': 'Townie Bagels | Bakery | Cafe', 'types': ['bakery', 'grocery_or_supermarket', 'cafe', 'restaurant', 'food', 'point_of_interest', 'store', 'establishment']}, 'status': 'OK'}

I am able to grab the fields I need in this loop from shortlist

#### works  list of short results

i = 0
for x in  shortlist:
    try:
        find_name = shortlist[i]['result']['name']
        print(find_name)
        i = i+1

except(KeyError):
    print('name error')
    i= i+1
    continue

#

output from for loop:

Palm Greens Cafe
Townie Bagels | Bakery | Cafe
Starbucks Reserve
McDonald's
Cafe Jasmin
Koffi South Palm Springs
Starbucks
MidMod Café
Gré Coffee House & Art Gallery
Vinny's Italian Ice, Frozen Custard + Ice Cream, Gelato and More
L'Atelier Cafe
Broken Yolk Cafe Palm Springs
Ristretto
Peninsula Pastries Palm Springs
Camelot Internationale Cafe
Rick's Restaurant & Bakery
Starbucks
Swiss Donut
Starbucks
Starbucks

I spent 2 days finally getting this fare.   Just wanted suggestions if there is a more streamline way of doing this?

I could not get the suggested samples to work from reply before this post.

Thanks for the Help.
bill s.


问:
Mobile Safari like scrolling of UIWebView (with navigationbar stuck at top)
How would I go about making a browser window that has the same scrolling properties as Mobile Safari? If you scroll Mobile Safari the navigationbar up top follows with it. If there is no more content it stops scrolling, and it has a very special way of zooming. Mobile Safari has it, and now even Opera mini for iPhone has it. Any ideas? I have tried hooking in to the scrolldelegate of the UIWebView, but that's not perfect at all. I'm out of ideas. How have the Opera Mini guys solved this issue?

答: I haven't done this myself but it seems to me that you could create a holder view that has your a view handling the navigation and the UIWebView, this would be tucked into a UIScrollView to facilitate the scrolling and then in the UIScrollView delegate pass the UIWebView as the view for zooming in viewForZoomingInScrolView.