问:
java.lang.IllegalStateException: Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM
When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8., Intellij IDEA on Windows 10. Even Though I have mentioned the the Quasar.jar in VM options.

RUN >> Edit Configurations >> Junit>> Required Test Class >>VM options:-ea -javaagent:lib\quasar.jar
enter image description here

```<code>package com.template;

import com.google.common.collect.ImmutableList;
import com.template.contracts.MetalContract;
import com.template.flows.Responder;
import com.template.states.MetalState;
import net.corda.core.concurrent.CordaFuture;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.TransactionState;
import net.corda.core.transactions.SignedTransaction;
import net.corda.testing.node.MockNetwork;
import net.corda.testing.node.MockNetworkParameters;
import net.corda.testing.node.StartedMockNode;
import net.corda.testing.node.TestCordapp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.template.flows.IssueMetal;
import com.template.flows.TransferMetal;

import static org.junit.Assert.assertEquals;
import static junit.framework.TestCase.assertTrue;

public class FlowTests {
    private final MockNetwork network = new MockNetwork(new MockNetworkParameters(ImmutableList.of(
        TestCordapp.findCordapp("com.template.contracts"),
        TestCordapp.findCordapp("com.template.flows")
    )));

    private final StartedMockNode Mint = network.createNode();
    private final StartedMockNode A = network.createNode();
    private final StartedMockNode B = network.createNode();

    @Before
    public void setup() {
        network.runNetwork();
    }

    @After
    public void tearDown() {
        network.stopNodes();
    }

    // ------------------------------------------ Issue Metal Flow Tests ----------------------------------------

    @Test
    public void transactionHasNoInputsHasOneMetalStateOutputWithTheCorrectOwner() throws Exception {

        IssueMetal flow = new IssueMetal("Gold", 10, A.getInfo().getLegalIdentities().get(0));
        CordaFuture<SignedTransaction> future = Mint.startFlow(flow);
        setup();
        SignedTransaction signedTransaction = future.get();

        assertEquals (0, signedTransaction.getTx().getInputs().size());

        assertEquals (1, signedTransaction.getTx().getOutputStates().size());
        MetalState output = signedTransaction.getTx().outputsOfType(MetalState.class).get(0);

        assertEquals(A.getInfo().getLegalIdentities().get(0), output.getOwner());

    }
}
</code>```

The Error is :

```<code>java.lang.IllegalStateException: Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM.
See https://docs.corda.net/head/testing.html#running-tests-in-intellij - 'Fiber classes not instrumented' for more details.

    at net.corda.node.services.statemachine.SingleThreadedStateMachineManager.checkQuasarJavaAgentPresence(SingleThreadedStateMachineManager.kt:317)
    at net.corda.node.services.statemachine.SingleThreadedStateMachineManager.start(SingleThreadedStateMachineManager.kt:135)
    at net.corda.node.internal.AbstractNode$start$8.invoke(AbstractNode.kt:409)
    at net.corda.node.internal.AbstractNode$start$8.invoke(AbstractNode.kt:122)
    at net.corda.nodeapi.internal.persistence.CordaPersistence.inTopLevelTransaction(CordaPersistence.kt:268)
    at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:237)
    at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:254)
    at net.corda.node.internal.AbstractNode.start(AbstractNode.kt:388)
    at net.corda.testing.node.internal.InternalMockNetwork$MockNode.start(InternalMockNetwork.kt:346)
    at net.corda.testing.node.internal.InternalMockNetwork.createNodeImpl(InternalMockNetwork.kt:471)
    at net.corda.testing.node.internal.InternalMockNetwork.createNode(InternalMockNetwork.kt:449)
    at net.corda.testing.node.internal.InternalMockNetwork.createNode(InternalMockNetwork.kt:444)
    at net.corda.testing.node.internal.InternalMockNetwork.createNotaries$node_driver(InternalMockNetwork.kt:253)
    at net.corda.testing.node.internal.InternalMockNetwork.<init>(InternalMockNetwork.kt:236)
    at net.corda.testing.node.internal.InternalMockNetwork.<init>(InternalMockNetwork.kt:149)
    at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:305)
    at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:294)
    at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:303)
    at com.template.FlowTests.<init>(FlowTests.java:25)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
</code>```

答:
I would recommend using the Gradle Test Runner so that you don't have to set the javaagent flag manually.

To use Gradle Test Runner Click the Run/Debug configuration drop down > Edit Configurations... > + > Gradle In the form that appears, fill in the details:

Gradle-Project : [path to your project]

Task: :cleanTest :test

Arguments: --tests ""

Reference below:

Body:
When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8., Intellij IDEA on Windows 10. Even Though I have mentioned the the Quasar.jar in VM options.

RUN >> Edit Configurations >> Junit>> Required Test Class >>VM options:-ea -javaagent:lib\quasar.jar
enter image description here

package com.template;

import com.google.common.collect.ImmutableList;
import com.template.contracts.MetalContract;
import com.template.flows.Responder;
import com.template.states.MetalState;
import net.corda.core.concurrent.CordaFuture;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.TransactionState;
import net.corda.core.transactions.SignedTransaction;
import net.corda.testing.node.MockNetwork;
import net.corda.testing.node.MockNetworkParameters;
import net.corda.testing.node.StartedMockNode;
import net.corda.testing.node.TestCordapp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.template.flows.IssueMetal;
import com.template.flows.TransferMetal;

import static org.junit.Assert.assertEquals;
import static junit.framework.TestCase.assertTrue;

public class FlowTests {
    private final MockNetwork network = new MockNetwork(new MockNetworkParameters(ImmutableList.of(
        TestCordapp.findCordapp("com.template.contracts"),
        TestCordapp.findCordapp("com.template.flows")
    )));

    private final StartedMockNode Mint = network.createNode();
    private final StartedMockNode A = network.createNode();
    private final StartedMockNode B = network.createNode();

    @Before
    public void setup() {
        network.runNetwork();
    }

    @After
    public void tearDown() {
        network.stopNodes();
    }

    // ------------------------------------------ Issue Metal Flow Tests ----------------------------------------

    @Test
    public void transactionHasNoInputsHasOneMetalStateOutputWithTheCorrectOwner() throws Exception {

        IssueMetal flow = new IssueMetal("Gold", 10, A.getInfo().getLegalIdentities().get(0));
        CordaFuture<SignedTransaction> future = Mint.startFlow(flow);
        setup();
        SignedTransaction signedTransaction = future.get();

        assertEquals (0, signedTransaction.getTx().getInputs().size());

        assertEquals (1, signedTransaction.getTx().getOutputStates().size());
        MetalState output = signedTransaction.getTx().outputsOfType(MetalState.class).get(0);

        assertEquals(A.getInfo().getLegalIdentities().get(0), output.getOwner());

    }
}

The Error is :

java.lang.IllegalStateException: Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM.
See https://docs.corda.net/head/testing.html#running-tests-in-intellij - 'Fiber classes not instrumented' for more details.

    at net.corda.node.services.statemachine.SingleThreadedStateMachineManager.checkQuasarJavaAgentPresence(SingleThreadedStateMachineManager.kt:317)
    at net.corda.node.services.statemachine.SingleThreadedStateMachineManager.start(SingleThreadedStateMachineManager.kt:135)
    at net.corda.node.internal.AbstractNode$start$8.invoke(AbstractNode.kt:409)
    at net.corda.node.internal.AbstractNode$start$8.invoke(AbstractNode.kt:122)
    at net.corda.nodeapi.internal.persistence.CordaPersistence.inTopLevelTransaction(CordaPersistence.kt:268)
    at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:237)
    at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:254)
    at net.corda.node.internal.AbstractNode.start(AbstractNode.kt:388)
    at net.corda.testing.node.internal.InternalMockNetwork$MockNode.start(InternalMockNetwork.kt:346)
    at net.corda.testing.node.internal.InternalMockNetwork.createNodeImpl(InternalMockNetwork.kt:471)
    at net.corda.testing.node.internal.InternalMockNetwork.createNode(InternalMockNetwork.kt:449)
    at net.corda.testing.node.internal.InternalMockNetwork.createNode(InternalMockNetwork.kt:444)
    at net.corda.testing.node.internal.InternalMockNetwork.createNotaries$node_driver(InternalMockNetwork.kt:253)
    at net.corda.testing.node.internal.InternalMockNetwork.<init>(InternalMockNetwork.kt:236)
    at net.corda.testing.node.internal.InternalMockNetwork.<init>(InternalMockNetwork.kt:149)
    at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:305)
    at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:294)
    at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:303)
    at com.template.FlowTests.<init>(FlowTests.java:25)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)


来源: stackexchange

问:
How to call a function from html button
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

```<code><html>
    <head>
        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

     <script>
             function delete(id){

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                        var available = this.responseText;
                      }
                  };
                xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
                xhttp.send();
            }
        </script>
    </head>

    <body>
        <button type="button" onclick="delete(9)">Erase</button>
    </body>

</html>
</code>```

答:
delete is an operator. You cannot use it as the name of a variable.

Rename the function.

ContentLicense: CC BY-SA 4.0

Title: How to call a function from html button

Body:
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

        <button type="button" onclick="delete(9)">Erase</button>


问:
How to call affected_rows method from ci4 model
I have a model that extends CI4 builtin Model..

```<code>use CodeIgniter\Model;
use CodeIgniter\I18n\Time;

class ArticleModel extends Model { .. }
</code>```

Any idea how do i perform the following?

```<code>$this->db->affected_rows();
</code>```

thinking of getting it after deleting a row, most of the example using custom model, not extending ci4 model.

答:
First, be sure to set your database connection up correctly in app/Config/App.php or in your .env file.

Then $this->db from the core Model in CI4 doesn't create the connection. You have to create it first then you can perform queries.

affected_rows() method doesn't exist in CI4, it's now called affectedRows(). So to call it you will enventually come up with something like this :

```<code>    // your db connection
    $this->db = \Config\Database::connect();
    // your query
    $this->db->query('MY QUERY');
    // number of affected rows
    $affected_rows = $this->db->affectedRows();
</code>```

Body:
I have a model that extends CI4 builtin Model..

use CodeIgniter\Model;
use CodeIgniter\I18n\Time;

class ArticleModel extends Model { .. }

Any idea how do i perform the following?

$this->db->affected_rows();

thinking of getting it after deleting a row, most of the example using custom model, not extending ci4 model.

Body:
First, be sure to set your database connection up correctly in app/Config/App.php or in your .env file.

Then $this->db from the core Model in CI4 doesn't create the connection. You have to create it first then you can perform queries.

affected_rows() method doesn't exist in CI4, it's now called affectedRows(). So to call it you will enventually come up with something like this :

    // your db connection
    $this->db = \Config\Database::connect();
    // your query
    $this->db->query('MY QUERY');
    // number of affected rows
    $affected_rows = $this->db->affectedRows();


问:
Serilog Dynamically enrich a context
Is there any possibility to dynamically override or extend the log template in Serilog?

I have a parser class which parses XML line by line and I want to extend the log entry with the line number. I have already written an enricher that does that, but I have to globally override the default logger at the start of the function and reset it at the end, which is difficult to even look at (from a programming perspective) :D

What are the other options with Serilog or have I missed something?

答:
After some more digging I finally found a solution that fit my needs.

I used the LogContext.PushProperty mechanism to push the XmlReader (or rather a wrapper object, because the type-matching with the destructuring is exact and XmlReader is a factory which returns many different classes) into the LogContext and added a custom destructuring to LoggerConfiguration to detect objects of that wrapper type and then format it to my liking.

Title: Serilog Dynamically enrich a context


问:
GRPC web client with angular 6
I have worked with grpc .net client and a grpc server created with java, how can i implement grpc web client on angular 6 with typescript? Also how can i create proto files and it's typing's for typescript?
I am following this repo but not able to generate proto files.</p>

答:
Cannot use on on Windows

```<code>"compile": "./node_modules/protoc/protoc/bin/protoc
--plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts --js_out=import_style=commonjs,binary:src/app/proto-gen --ts_out=service=true:src/app/proto -I ./src/app/proto ./src/app/proto/**/*.proto",
</code>```

I get '.' is not recognized as an internal or external command

This works fine: package.json

```<code>"scripts": {
"compile": "node_modules\\protoc\\protoc\\bin\\protoc --plugin=protoc-gen-ts=node_modules\\.bin\\protoc-gen-ts.cmd --js_out=import_style=commonjs,binary:./proto/generated --ts_out=service=grpc-web:./proto/generated -I ./proto ./proto/*.proto"
}
</code>```

npm run compile

Title: GRPC web client with angular 6

Body:
Cannot use on on Windows

"compile": "./node_modules/protoc/protoc/bin/protoc
--plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts --js_out=import_style=commonjs,binary:src/app/proto-gen --ts_out=service=true:src/app/proto -I ./src/app/proto ./src/app/proto/**/*.proto",

I get '.' is not recognized as an internal or external command

This works fine: package.json

"scripts": {
"compile": "node_modules\\protoc\\protoc\\bin\\protoc --plugin=protoc-gen-ts=node_modules\\.bin\\protoc-gen-ts.cmd --js_out=import_style=commonjs,binary:./proto/generated --ts_out=service=grpc-web:./proto/generated -I ./proto ./proto/*.proto"
}

npm run compile


问:
Polly retry with different url
I am trying to create a solution with polly where I request an other api.

I have a list of URLs to multiple instances of the same service.

I want that when the first request failes, an other should automaticly start with the next url from my list.

Here is an example where i try this behaviour with two static addresses

The Problem with this solution is that the url does not change until i start the next request.
I want that the urls changes on every retry

```<code> public static void ConfigureUserServiceClient(this IServiceCollection services)
    {

        _userServiceUri = new Uri("https://localhost:5001");

        services.AddHttpClient("someService", client =>
        {
            client.BaseAddress = _userServiceUri;
            client.DefaultRequestHeaders.Add("Accept", "application/json");
        }).AddPolicyHandler(retryPolicy());
    }

    private static IAsyncPolicy<HttpResponseMessage> retryPolicy()
    {
        return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.RequestTimeout)
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt),
            onRetry: (result, span, ctx) =>
            {
                _userServiceUri = new Uri("https://localhost:5002");
            });
    }
</code>```

答:
You should consider to use the Fallback policy instead.

Like this:

```<code>private static HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
    var addressIterator = GetUrls().GetEnumerator();

    var retryLikePolicy = Policy<string>
        .Handle<HttpRequestException>()
        .FallbackAsync(fallbackAction: async (ct) =>
        {
            if (addressIterator.MoveNext())
               return await GetData(addressIterator.Current);
            return null;
        });

    addressIterator.MoveNext();
    var data = await retryLikePolicy.ExecuteAsync(
       async () => await GetData(addressIterator.Current));

    Console.WriteLine("End");
}

static async Task<string> GetData(string uri)
{
    Console.WriteLine(uri);
    var response = await client.GetAsync(uri);
    return await response.Content.ReadAsStringAsync();
}

static IEnumerable<string> GetUrls()
{
    yield return "http://localhost:5500/index.html";
    yield return "http://localhost:5600/index.html";
    yield return "http://localhost:5700/index.html";
}
</code>```

Please note that this code is just for demonstration.

UPDATE #1: Multiple fallback

If you have more than one fallback urls then you can alter the above code like this:

```<code>private static HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
    var retryInCaseOfHRE = Policy
        .Handle<HttpRequestException>()
        .WaitAndRetryForeverAsync(_ => TimeSpan.FromSeconds(1));

    var response = await retryInCaseOfHRE.ExecuteAsync(
         async () => await GetNewAddressAndPerformRequest());

    if (response == null)
    {
        Console.WriteLine("All requests failed");
        Environment.Exit(1);
    }

    Console.WriteLine("End");
}

static IEnumerable<string> GetAddresses()
{
    yield return "http://localhost:5500/index.html";
    yield return "http://localhost:5600/index.html";
    yield return "http://localhost:5700/index.html";
    yield return "http://localhost:5800/index.html";
}

static readonly IEnumerator<string> AddressIterator = GetAddresses().GetEnumerator();

static async Task<string> GetNewAddressAndPerformRequest()
    => AddressIterator.MoveNext() ? await GetData(AddressIterator.Current) : null;

static async Task<string> GetData(string uri)
{
    Console.WriteLine(uri);
    var response = await client.GetAsync(uri);
    return await response.Content.ReadAsStringAsync();
}
</code>```

The trick: the retry policy wraps a method which is responsible to retrieve the next url and then call the GetData

In other word we need to move the iteration process into the to be wrapped method (GetNewAddressAndPerformRequest)

I've replaced the Fallback policy to Retry since we need to perform (potentially) more than 1 fallback actions

I've used null to indicate we have run out of fallback urls but it might be a better solution to use a custom exception for that

Title: Polly retry with different url

Body:
I am trying to create a solution with polly where I request an other api.

I have a list of URLs to multiple instances of the same service.

I want that when the first request failes, an other should automaticly start with the next url from my list.

Here is an example where i try this behaviour with two static addresses

The Problem with this solution is that the url does not change until i start the next request.
I want that the urls changes on every retry

 public static void ConfigureUserServiceClient(this IServiceCollection services)
    {

        _userServiceUri = new Uri("https://localhost:5001");

        services.AddHttpClient("someService", client =>
        {
            client.BaseAddress = _userServiceUri;
            client.DefaultRequestHeaders.Add("Accept", "application/json");
        }).AddPolicyHandler(retryPolicy());
    }

    private static IAsyncPolicy<HttpResponseMessage> retryPolicy()
    {
        return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.RequestTimeout)
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt),
            onRetry: (result, span, ctx) =>
            {
                _userServiceUri = new Uri("https://localhost:5002");
            });
    }

Body:
You should consider to use the Fallback policy instead.

Like this:

private static HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
    var addressIterator = GetUrls().GetEnumerator();

    var retryLikePolicy = Policy<string>
        .Handle<HttpRequestException>()
        .FallbackAsync(fallbackAction: async (ct) =>
        {
            if (addressIterator.MoveNext())
               return await GetData(addressIterator.Current);
            return null;
        });

    addressIterator.MoveNext();
    var data = await retryLikePolicy.ExecuteAsync(
       async () => await GetData(addressIterator.Current));

    Console.WriteLine("End");
}

static async Task<string> GetData(string uri)
{
    Console.WriteLine(uri);
    var response = await client.GetAsync(uri);
    return await response.Content.ReadAsStringAsync();
}

static IEnumerable<string> GetUrls()
{
    yield return "http://localhost:5500/index.html";
    yield return "http://localhost:5600/index.html";
    yield return "http://localhost:5700/index.html";
}

Please note that this code is just for demonstration.

UPDATE #1: Multiple fallback

If you have more than one fallback urls then you can alter the above code like this:

private static HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
    var retryInCaseOfHRE = Policy
        .Handle<HttpRequestException>()
        .WaitAndRetryForeverAsync(_ => TimeSpan.FromSeconds(1));

    var response = await retryInCaseOfHRE.ExecuteAsync(
         async () => await GetNewAddressAndPerformRequest());

    if (response == null)
    {
        Console.WriteLine("All requests failed");
        Environment.Exit(1);
    }

    Console.WriteLine("End");
}

static IEnumerable<string> GetAddresses()
{
    yield return "http://localhost:5500/index.html";
    yield return "http://localhost:5600/index.html";
    yield return "http://localhost:5700/index.html";
    yield return "http://localhost:5800/index.html";
}

static readonly IEnumerator<string> AddressIterator = GetAddresses().GetEnumerator();

static async Task<string> GetNewAddressAndPerformRequest()
    => AddressIterator.MoveNext() ? await GetData(AddressIterator.Current) : null;

static async Task<string> GetData(string uri)
{
    Console.WriteLine(uri);
    var response = await client.GetAsync(uri);
    return await response.Content.ReadAsStringAsync();
}

The trick: the retry policy wraps a method which is responsible to retrieve the next url and then call the GetData

In other word we need to move the iteration process into the to be wrapped method (GetNewAddressAndPerformRequest)

I've replaced the Fallback policy to Retry since we need to perform (potentially) more than 1 fallback actions

I've used null to indicate we have run out of fallback urls but it might be a better solution to use a custom exception for that


问:
Django not create database table
Hey,
I've a database already created. Now I've updated UserProfile with:

```<code>class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True, related_name = 'user')
    follows = models.ManyToManyField("self", related_name = 'follows') <-- NEW LINE
</code>```

so python manage.py sqlall myapp returns me:

```<code>[...]
CREATE TABLE "myapp_userprofile_follows" (
    "id" integer NOT NULL PRIMARY KEY,
    "from_userprofile_id" integer NOT NULL,
    "to_userprofile_id" integer NOT NULL,
    UNIQUE ("from_userprofile_id", "to_userprofile_id")
)
[...]
</code>```

When I run python manage.py syncdb:

```<code>Creating tables ...
Installing custom SQL ...
Installing indexes ...
No fixtures found.
</code>```

But the table is not created when I try to insert data into. Why? (I'm testing locally, with sqlite3)

答:
have you added your app to INSTALLED_APPS in settings.pys:

settings.py

```<code>INSTALLED_APPS = (
    ... ,
    'my_app',
)
</code>```

https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#installed-apps

ContentLicense: CC BY-SA 3.0

Title: Django not create database table

Body:
Hey,
I've a database already created. Now I've updated UserProfile with:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True, related_name = 'user')
    follows = models.ManyToManyField("self", related_name = 'follows') <-- NEW LINE

so python manage.py sqlall myapp returns me:

[...]
CREATE TABLE "myapp_userprofile_follows" (
    "id" integer NOT NULL PRIMARY KEY,
    "from_userprofile_id" integer NOT NULL,
    "to_userprofile_id" integer NOT NULL,
    UNIQUE ("from_userprofile_id", "to_userprofile_id")
)
[...]

When I run python manage.py syncdb:

Creating tables ...
Installing custom SQL ...
Installing indexes ...
No fixtures found.

But the table is not created when I try to insert data into. Why? (I'm testing locally, with sqlite3)

Body:
have you added your app to INSTALLED_APPS in settings.pys:

settings.py

INSTALLED_APPS = (
    ... ,
    'my_app',
)

https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#installed-apps


问:
Stored procedure - Use array list in SQL query for insert in snowflake
If i have created/generated a list of elements during processing in stored procedure say rownum = [1,2,3,4].
Now i want to use this list in a sql statement to filter out rows say select * from mytable where rownum not in (1,2,3,4) in same stored procedure.
How can i achieve this ?
Please guide.
Thanks</p>

答:
Snowflake has the ARRAY_CONTAINS(  ,  ) function.

example:
Array_Contains( 5, array_construct( 1,2,3,4))


问:
Ocelot post request not going through
I have implemented Ocelot API gateway in my project which was working fine for 'GET' requests but when I tried to send 'POST' request I am getting the error:

previousRequestId: no previous request id, message: Error Code: UnableToFindDownstreamRouteError Message: Failed to match ReRoute configuration for upstream path: /api/patient/CreateAppointment, verb: POST. errors found in ResponderMiddleware. Setting error response for request path:/api/patient/CreateAppointment, request method: POST

Following is my ocelot.json:

```<code>{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/patient/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "patientservice",
          "Port": 81
        }
      ],
      "UpstreamPathTemplate": "/api/patient/{everything}",
      "UpstreamHttpMethod": [ "GET", "POST" ],
      "UpstreamHost": "*"
    },
    {
      "DownstreamPathTemplate": "/api/actor",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "postgresqldapper",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/actor",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/product/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "productservice",
          "Port": 80
        }
      ],
      "UpstreamPathTemplate": "/api/product/{everything}",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/weatherforecast",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "postgresqldapper",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/weatherforecast",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/user",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "loginservicedapr",
          "Port": 80
        }
      ],
      "UpstreamPathTemplate": "/api/user",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/user/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "loginservicedapr",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/user/{id}",
      "UpstreamHttpMethod": [ "GET" ]
    }

  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}
</code>```

The API to which I am doing the 'POST' request is working fine for the 'POST' request when invoked directly from Swagger or Postman.

Please let me know what I should change in ocelot.json file so that the 'POST' request can through?

答:
Your error is effectively saying that Ocelot is unable to route requests to

```<code>POST /api/patient/CreateAppointment
</code>```

In your screenshot, your curl command (which is working) is a request to:

```<code>POST /api/patient
</code>```

Your /{everything} path suffix is telling Ocelot that whatever suffix you call into the gateway with will be present on the downstream service.

My theory is that you have not defined a CreateAppointment endpoint operation on your downstream patient service API. Once you define this path on your service, your /api/patient/{everything} route mapping should work fine.

Title: Ocelot post request not going through

Body:
I have implemented Ocelot API gateway in my project which was working fine for 'GET' requests but when I tried to send 'POST' request I am getting the error:

previousRequestId: no previous request id, message: Error Code: UnableToFindDownstreamRouteError Message: Failed to match ReRoute configuration for upstream path: /api/patient/CreateAppointment, verb: POST. errors found in ResponderMiddleware. Setting error response for request path:/api/patient/CreateAppointment, request method: POST

Following is my ocelot.json:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/patient/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "patientservice",
          "Port": 81
        }
      ],
      "UpstreamPathTemplate": "/api/patient/{everything}",
      "UpstreamHttpMethod": [ "GET", "POST" ],
      "UpstreamHost": "*"
    },
    {
      "DownstreamPathTemplate": "/api/actor",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "postgresqldapper",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/actor",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/product/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "productservice",
          "Port": 80
        }
      ],
      "UpstreamPathTemplate": "/api/product/{everything}",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/weatherforecast",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "postgresqldapper",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/weatherforecast",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/user",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "loginservicedapr",
          "Port": 80
        }
      ],
      "UpstreamPathTemplate": "/api/user",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/user/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "loginservicedapr",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/user/{id}",
      "UpstreamHttpMethod": [ "GET" ]
    }

  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}

The API to which I am doing the 'POST' request is working fine for the 'POST' request when invoked directly from Swagger or Postman.

Please let me know what I should change in ocelot.json file so that the 'POST' request can through?

Body:
Your error is effectively saying that Ocelot is unable to route requests to

POST /api/patient/CreateAppointment

In your screenshot, your curl command (which is working) is a request to:

POST /api/patient

Your /{everything} path suffix is telling Ocelot that whatever suffix you call into the gateway with will be present on the downstream service.

My theory is that you have not defined a CreateAppointment endpoint operation on your downstream patient service API. Once you define this path on your service, your /api/patient/{everything} route mapping should work fine.


问:
Make POST request from HTML
I want to make an HTTP POST request from an HTML anchor tag that has the URL in its href attribute.

How can I make it use POST instead of GET?

```<code><a href='http:/test_url:5002/api/GetFile'></a>
</code>```

I also want to set parameters in the body of the request. How can I do that?

I want to find a way to include them in the HTML tag itself, not in a JavaScript file.

答:
Links are designed to GET a URL. You cannot make a POST request directly with them.

Use a form with a submit button instead.

Title: Make POST request from HTML

Body:
I want to make an HTTP POST request from an HTML anchor tag that has the URL in its href attribute.

How can I make it use POST instead of GET?

I also want to set parameters in the body of the request. How can I do that?

I want to find a way to include them in the HTML tag itself, not in a JavaScript file.


问:
Query 2 sets of Sheets data & identify discrepancies
I am trying to use Apps Script to query 2 datasets and compare certain columns across them.  I am hoping to...

a) identify missing ID values;

b) reconcile differences in other fields, when the ID values match.

INPUT:

Spreadsheet with 2 tabs (tab1, tab2).

The key ID in each B column (Btab1, Btab2)

I want to identify instances where a unique value (B) is in one dataset but not in the other (the rows are not in the same order)

Run a function & push to an output tab if Btab1 is not in tab2 || Btab2 is not in tab1

When a value of B is in both tabs (the majority of the time), I want to identify instances of data discrepancies in a few columns...

For all instances of B, push B and the relevant columns below to the output tab if...

Column M in tab1 doesn't match column E in tab2

Column P in tab1 <> column F in tab2

Column AN tab1 <> Column G tab2

OUTPUT:
tab that displays problem areas in the datasets.

First column is ID Key.

Second column explains the issue via text string

Again, the challenge here is that the values are not sorted the same, and there could be a slight difference in total # rows

```<code>function compare() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
   ss.insertSheet(1);
   ss.getActiveSheet().setName('output');
  var sheet1 = ss.getSheetByName('sheet1');
  var sheet2 = ss.getSheetByName('sheet2');
  var sheet_output = ss.getSheetByName('output');

  var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
  var output1 = [];
  var a1;
  var b1;
  var h1;
  var i1;
  var j1;
  var m1;
  var o1;
  var p1;
  var an1;
  var ao1;
  var x;

  var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
  var output2 = [];
  var a2;
  var b2;
  var c2;
  var d2;
  var e2;
  var f2;
  var g2;
  var h2;
  var y;

  /// can i do for(x in range1; y in range2) { all in one function??  If so, what is the proper syntax?

  for(x in range1, y in range2) {
    a1 = range1[x][0];
    b1 = range1[x][1];
    h1 = range1[x][7];
    i1 = range1[x][8];
    j1 = range1[x][9];
    m1 = range1[x][12];
    o1 = range1[x][14];
    p1 = range1[x][15];
    an1 = range1[x][39];
    ao1 = range1[x][40];

    a2 = range2[y][0];
    b2 = range2[y][1];
    c2 = range2[y][2];
    d2 = range2[y][3];
    e2 = range2[y][4];
    f2 = range2[y][5];
    g2 = range2[y][6];
    h2 = range2[y][7];

    if (

      (b1 != b2) ||
      (m1 != e2) // etc etc etc
       )
    {

  //push to output
  }}

</code>```

答:
Whilst your syntax for(x in range1, y in range2) will not return an error, it won't give you the desired result neither if the rows are not in the same order

Reason:

During each iteration both x and y will change, e.g. if var range1 = [1,2,3] and var range2 = [4,5,6], your loop will iterate 3 times and the values in your sample loop iterations will be:

iteration

range1[x] = 1 and range2[y] = 4

iteration

range1[x] = 2 and range2[y] = 5

iteration

range1[x] = 3 and range2[y] = 6

In this case you will not retrieve the combination

range1[x] = 1 and range2[y] = 4

or

range1[x] = 2 and range2[y] = 6

and so on.

Instead you need to use two nested for loops, which would iterate through all possible combinations of x and y:

```<code> for(x in range1) {
    for(y in range2){
      ...
    }
  }
</code>```

Sidenote:

Even if your rows would be in the same order, you still need to be careful. Because for(x in range1) opposed to for(x = 0; x < range1.length; i++) gives you no control about in which folder the loop will iterate over the range.

Now to your query for duplicates

A possible way to implement the functionality in a not too complicated manner would be the following:

Define boolean variable and use it to check for each x either it has a duplicate

If a duplicate (for column B) is found - further criteria will be evaluated

If two rows match by all criteria, the inner loop will be exited with break and the function will jump to the next x

If rows with identical key IDs, but discrepancies in other columns are found - both rows will be pushed into sheet output for comparison purposes (this is easier to implement than specifying what exactly is discrepant)

After this the inner loop will also be exited

In oth cases above duplicate will be set to true

If a unique Id is found in sheet1 (duplicate = false) - it will be immediately pushed into output

Sample

```<code>function compare() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
   ss.insertSheet(1);
    ss.getActiveSheet().setName('output');
  var sheet1 = ss.getSheetByName('sheet1');
  var sheet2 = ss.getSheetByName('sheet2');
  var sheet_output = ss.getSheetByName('output');

  var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
  var output1 = [];
  var b1;
  var m1;
  var p1;
  var an1;
  var x;

  var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
  var output2 = [];
  var b2;
  var e2;
  var f2;
  var g2;
  var y;

  var array = [];
  for(x in range1) {
    var duplicate = false;
    for(y in range2){
      b1 = range1[x][1];
      m1 = range1[x][12];
      p1 = range1[x][15];
      an1 = range1[x][39];

      b2 = range2[y][1];
      e2 = range2[y][4];
      f2 = range2[y][5];
      g2 = range2[y][6];

      if (
        (b1 == b2)
      )
      {
        Logger.log("found");
        duplicate = true;
        if((m1 != e2)||
        (p1 != f2) ||
        (an1 != g2)){
          array.push(range1[x]);
          array.push(range2[y]);
        }
        break;
      }
    }
    if (duplicate == false){
      Logger.log("duplicate false");
      array.push(range1[x]);
    }
  }
  //push to output
  if(array[0]){
    sheet_output.getRange(sheet_output.getLastRow()+1, 1, array.length, array[0].length).setValues(array);
  }
}
</code>```

Body:
I am trying to use Apps Script to query 2 datasets and compare certain columns across them.  I am hoping to...

a) identify missing ID values;

b) reconcile differences in other fields, when the ID values match.

INPUT:

Spreadsheet with 2 tabs (tab1, tab2).

The key ID in each B column (Btab1, Btab2)

I want to identify instances where a unique value (B) is in one dataset but not in the other (the rows are not in the same order)

Run a function & push to an output tab if Btab1 is not in tab2 || Btab2 is not in tab1

When a value of B is in both tabs (the majority of the time), I want to identify instances of data discrepancies in a few columns...

For all instances of B, push B and the relevant columns below to the output tab if...

Column M in tab1 doesn't match column E in tab2

Column P in tab1 <> column F in tab2

Column AN tab1 <> Column G tab2

OUTPUT:
tab that displays problem areas in the datasets.

First column is ID Key.

Second column explains the issue via text string

Again, the challenge here is that the values are not sorted the same, and there could be a slight difference in total # rows

function compare() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
   ss.insertSheet(1);
   ss.getActiveSheet().setName('output');
  var sheet1 = ss.getSheetByName('sheet1');
  var sheet2 = ss.getSheetByName('sheet2');
  var sheet_output = ss.getSheetByName('output');

  var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
  var output1 = [];
  var a1;
  var b1;
  var h1;
  var i1;
  var j1;
  var m1;
  var o1;
  var p1;
  var an1;
  var ao1;
  var x;

  var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
  var output2 = [];
  var a2;
  var b2;
  var c2;
  var d2;
  var e2;
  var f2;
  var g2;
  var h2;
  var y;

  /// can i do for(x in range1; y in range2) { all in one function??  If so, what is the proper syntax?

  for(x in range1, y in range2) {
    a1 = range1[x][0];
    b1 = range1[x][1];
    h1 = range1[x][7];
    i1 = range1[x][8];
    j1 = range1[x][9];
    m1 = range1[x][12];
    o1 = range1[x][14];
    p1 = range1[x][15];
    an1 = range1[x][39];
    ao1 = range1[x][40];

    a2 = range2[y][0];
    b2 = range2[y][1];
    c2 = range2[y][2];
    d2 = range2[y][3];
    e2 = range2[y][4];
    f2 = range2[y][5];
    g2 = range2[y][6];
    h2 = range2[y][7];

    if (

      (b1 != b2) ||
      (m1 != e2) // etc etc etc
       )
    {

  //push to output
  }}

Body:
Whilst your syntax for(x in range1, y in range2) will not return an error, it won't give you the desired result neither if the rows are not in the same order

Reason:

During each iteration both x and y will change, e.g. if var range1 = [1,2,3] and var range2 = [4,5,6], your loop will iterate 3 times and the values in your sample loop iterations will be:

iteration

range1[x] = 1 and range2[y] = 4

iteration

range1[x] = 2 and range2[y] = 5

iteration

range1[x] = 3 and range2[y] = 6

In this case you will not retrieve the combination

range1[x] = 1 and range2[y] = 4

or

range1[x] = 2 and range2[y] = 6

and so on.

Instead you need to use two nested for loops, which would iterate through all possible combinations of x and y:

 for(x in range1) {
    for(y in range2){
      ...
    }
  }

Sidenote:

Even if your rows would be in the same order, you still need to be careful. Because for(x in range1) opposed to for(x = 0; x < range1.length; i++) gives you no control about in which folder the loop will iterate over the range.

Now to your query for duplicates

A possible way to implement the functionality in a not too complicated manner would be the following:

Define boolean variable and use it to check for each x either it has a duplicate

If a duplicate (for column B) is found - further criteria will be evaluated

If two rows match by all criteria, the inner loop will be exited with break and the function will jump to the next x

If rows with identical key IDs, but discrepancies in other columns are found - both rows will be pushed into sheet output for comparison purposes (this is easier to implement than specifying what exactly is discrepant)

After this the inner loop will also be exited

In oth cases above duplicate will be set to true

If a unique Id is found in sheet1 (duplicate = false) - it will be immediately pushed into output

Sample

function compare() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
   ss.insertSheet(1);
    ss.getActiveSheet().setName('output');
  var sheet1 = ss.getSheetByName('sheet1');
  var sheet2 = ss.getSheetByName('sheet2');
  var sheet_output = ss.getSheetByName('output');

  var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
  var output1 = [];
  var b1;
  var m1;
  var p1;
  var an1;
  var x;

  var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
  var output2 = [];
  var b2;
  var e2;
  var f2;
  var g2;
  var y;

  var array = [];
  for(x in range1) {
    var duplicate = false;
    for(y in range2){
      b1 = range1[x][1];
      m1 = range1[x][12];
      p1 = range1[x][15];
      an1 = range1[x][39];

      b2 = range2[y][1];
      e2 = range2[y][4];
      f2 = range2[y][5];
      g2 = range2[y][6];

      if (
        (b1 == b2)
      )
      {
        Logger.log("found");
        duplicate = true;
        if((m1 != e2)||
        (p1 != f2) ||
        (an1 != g2)){
          array.push(range1[x]);
          array.push(range2[y]);
        }
        break;
      }
    }
    if (duplicate == false){
      Logger.log("duplicate false");
      array.push(range1[x]);
    }
  }
  //push to output
  if(array[0]){
    sheet_output.getRange(sheet_output.getLastRow()+1, 1, array.length, array[0].length).setValues(array);
  }
}


问:
Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Ok, so I decided to use selenium for some code, but it doesn't work. When I put the chromedriver in my path, manually, it still doesn't work. can anyone help. PS: I already pip installed selenium.

Also, I watch/read the other article on stack overflow about this problem, but it didn't help me.

答: If you put chromedriver in the home directory of the user running it, that should work.  Would be helpful if you stated in your question what OS/version you are using.


问:
Android Studio 4 cannot detect java code and Cannot open SDK Manager,Settings
I just updated to latest android studio and had invalidated caches and restart but after that my project files are all red and android studio cannot detect java.
Whenever I hover on red line, It shows a configure JDK option.
I had downloaded latest jdk from oracle website and selected that in java path but that also didn't work. I am not able to open settings, SDK manager, neither can I configure SDK.

Below is the error dialog

I tried all the options below but cannot solve the issue

答: I think you have not setup JDK.Try to setup JDK and i think it will help you to solve the problem.</p>


问:
Bookmarklet to add a parameter at end of each URL
I'm trying to have a simple bookmarklet which adds a short parameter at end of any URL

I use ?clearcache to empty an internal cache, so in order not to type it each time, I'm looking for a simple solution

My site is

```<code>http://subdomain.mysite.net/
</code>```

and with the bookmarklet I want to make the URL go to

```<code>http://subdomain.mysite.net/?clearcache
</code>```

Same with deeper pages, as I would like it to go to

```<code>http://subdomain.mysite.net/some-page/?clearcache
</code>```

I'm currently trying with

```<code>javascript:location=location.href.replace(/http:/g,"/?clearcache")
</code>```

but it isn't working

When I click on that bookmarklet, my URL becomes

```<code>http://subdomain.mysite.net/?clearcache//subdomain.mysite.net/
</code>```

I feel I am close to it, but I just need a small tip from experts.
I hope for a a reply.
Thanks

答:
Building on Vikram Deshmukh's answer here is a version that uses a varying cache-busting parameter and replaces it every time it is used.

Expanded version:

javascript:void((function () {
    'use strict';
    let href;
    if (document.location.search === '') {
        href = document.location.href + '?_=' + Date.now();
    } else {
        let params = new URLSearchParams(document.location.search.substring(1));
        if (params.get('_') === null) {
            href = document.location.href + '&_=' + Date.now();
        } else {
            params.set('_', Date.now());
            href= document.location.href.substring(0, document.location.href.indexOf('?') + 1) + params.toString();
        }
    }
    document.location.assign(href);
})());
```

<p>Compact version:</p>

<pre class="lang-js prettyprint-override"><code>javascript:void((function () { let href; if (document.location.search === '') { href = document.location.href + '?_=' + Date.now(); } else { let params = new URLSearchParams(document.location.search.substring(1)); if (params.get('_') === null) { href = document.location.href + '&_=' + Date.now(); } else { params.set('_', Date.now()); href= document.location.href.substring(0, document.location.href.indexOf('?') + 1) + params.toString(); } } document.location.assign(href); })());
</code>```

Body:
I'm trying to have a simple bookmarklet which adds a short parameter at end of any URL

I use ?clearcache to empty an internal cache, so in order not to type it each time, I'm looking for a simple solution

My site is

http://subdomain.mysite.net/

and with the bookmarklet I want to make the URL go to

http://subdomain.mysite.net/?clearcache

Same with deeper pages, as I would like it to go to

http://subdomain.mysite.net/some-page/?clearcache

I'm currently trying with

javascript:location=location.href.replace(/http:/g,"/?clearcache")

but it isn't working

When I click on that bookmarklet, my URL becomes

http://subdomain.mysite.net/?clearcache//subdomain.mysite.net/

I feel I am close to it, but I just need a small tip from experts.
I hope for a a reply.
Thanks

Body:
Building on Vikram Deshmukh's answer here is a version that uses a varying cache-busting parameter and replaces it every time it is used.

Expanded version:

javascript:void((function () {
    'use strict';
    let href;
    if (document.location.search === '') {
        href = document.location.href + '?_=' + Date.now();
    } else {
        let params = new URLSearchParams(document.location.search.substring(1));
        if (params.get('_') === null) {
            href = document.location.href + '&_=' + Date.now();
        } else {
            params.set('_', Date.now());
            href= document.location.href.substring(0, document.location.href.indexOf('?') + 1) + params.toString();
        }
    }
    document.location.assign(href);
})());

Compact version:

javascript:void((function () { let href; if (document.location.search === '') { href = document.location.href + '?_=' + Date.now(); } else { let params = new URLSearchParams(document.location.search.substring(1)); if (params.get('_') === null) { href = document.location.href + '&_=' + Date.now(); } else { params.set('_', Date.now()); href= document.location.href.substring(0, document.location.href.indexOf('?') + 1) + params.toString(); } } document.location.assign(href); })());


问:
In a Vue app how do I check if a component tag is available?
Let's say I have this collection:

```<code>products: [
  { name: "ProductOne", value: 20 },
  { name: "ProductTwo", value: 30 },
  { name: "ProductRandom", value: 50 }
]
</code>```

I want to be able to use a specific component based on the product name, or fall back to a default:

```<code><div v-for="product in products">
  <product-one-and-two :product="product" v-if="componentExists(product.name)"></product-one-and-two>
  <default-product v-else :product="product"></default-product>
</div>
</code>```

This is an over-simplified example, in real life I have thousands of products and we'd like to just create product or category-specific template files without having to pollute the main app with conditionals. We want the component authors to not have to go through another team to have their new template added to the pipeline.

Is this possible at all with Vue?

答:
I would do it with dynamic compontens <component :is=""></component>

```<code>  <component :product="product" :is="product.name"></component>
</code>```

At :is you can dynamically add the component name, and it will be rendered.

If you create a new template for a product you just need to do 2 things.

Add a new object to your array products

```<code>products: [
  { name: "ProductOne", value: 20 },
  { name: "ProductTwo", value: 30 },
  { name: "ProductRandom", value: 50},
  { name: "newProduct", value: 34 }
]
</code>```

and register the new component.

```<code>import newProduct from "../path/to/newProduct.vue";
components: {
   newProduct
}
</code>```

Body:
Let's say I have this collection:

products: [
  { name: "ProductOne", value: 20 },
  { name: "ProductTwo", value: 30 },
  { name: "ProductRandom", value: 50 }
]

I want to be able to use a specific component based on the product name, or fall back to a default:

  <product-one-and-two :product="product" v-if="componentExists(product.name)"></product-one-and-two>
  <default-product v-else :product="product"></default-product>

This is an over-simplified example, in real life I have thousands of products and we'd like to just create product or category-specific template files without having to pollute the main app with conditionals. We want the component authors to not have to go through another team to have their new template added to the pipeline.

Is this possible at all with Vue?

Body:
I would do it with dynamic compontens <component :is=""></component>

  <component :product="product" :is="product.name"></component>

At :is you can dynamically add the component name, and it will be rendered.

If you create a new template for a product you just need to do 2 things.

Add a new object to your array products

products: [
  { name: "ProductOne", value: 20 },
  { name: "ProductTwo", value: 30 },
  { name: "ProductRandom", value: 50},
  { name: "newProduct", value: 34 }
]

and register the new component.

import newProduct from "../path/to/newProduct.vue";
components: {
   newProduct
}


问:
How to extract information from multiple XML nodes and hierarchies using python?
I have the following structure:

```<code><population>
    <person id="101">
        <attributes>
            <attribute name="age" class="java.lang.Integer" >53</attribute>
        </attributes>
        <plan score="-0.38" selected="yes">
            <activity type="outside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="car" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="car" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
        <plan score="-0.38" selected="no">
            <activity type="inside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="shopping" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="pt" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
    </person>
    <person id="102">
        <attributes>
            <attribute name="age" class="java.lang.Integer" >53</attribute>
        </attributes>
        <plan score="-0.38" selected="yes">
            <activity type="inside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="pt" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
    </person>
    <person id="103">
        <attributes>
            <attribute name="age" class="java.lang.Integer" >53</attribute>
        </attributes>
        <plan score="-0.38" selected="yes">
            <activity type="inside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="shopping" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="pt" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
    </person>
</population>
</code>```

What I want is to extract the value of person id  and in case plan selected ="yes" i further want to extract all activity type and leg mode. It should be stored in the existing order as a dictionary for example (or data frame, it doesn't matter really).

So the ideal outcome would look like this:

```<code>id    leg_activity
101   outside; car; work; car; outside
102   inside; bike; work; bike; work ...
...
</code>```

So far I've only worked with JMSPath and I know it is not the most suitable, so I'm happy to see other approaches with elementtree or so:) Also, I was unable to find a way to extract activityand leg information in one step. This is my approach so far:

```<code>import gzip
import xmltodict
import pandas as pd
import jmespath

box = xmltodict.parse(gzip.open(gzipfile, 'r'))

expression = jmespath.compile('population.person[].plan[?"@selected"==`yes`].activity[*].["@type"]')

coords = expression.search(box)
coords = pd.DataFrame.from_dict(coords)
</code>```

答:
Assuming that your xml is inside test.xml, the following should work:

from bs4 import BeautifulSoup
import pandas as pd
soup = BeautifulSoup(open('test.xml'), features='lxml')
plan_log = []
for person in soup.find_all('person'):
    log = {'id': person.get('id')}
    activities = []
    for plan in person.find_all('plan', attrs={'selected': 'yes'}):
        for detail in plan.children:
            if detail.name == 'activity':
                activities.append(detail.get('type'))
            elif detail.name == 'leg':
                activities.append(detail.get('mode'))
            # activities.append(detail.get('type') or detail.get('mode'))
    log['leg_activity'] = ', '.join(activities)
    plan_log.append(log)
df = pd.DataFrame(plan_log)
print(df)
```

<p>Output:</p>

```    id                                     leg_activity
0  101                 outside, car, work, car, outside
1  102      inside, bike, work, bike, work, pt, outside
2  103  inside, bike, shopping, bike, work, pt, outside
```

Body:
I have the following structure:

<population>
    <person id="101">
        <attributes>
            <attribute name="age" class="java.lang.Integer" >53</attribute>
        </attributes>
        <plan score="-0.38" selected="yes">
            <activity type="outside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="car" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="car" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
        <plan score="-0.38" selected="no">
            <activity type="inside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="shopping" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="pt" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
    </person>
    <person id="102">
        <attributes>
            <attribute name="age" class="java.lang.Integer" >53</attribute>
        </attributes>
        <plan score="-0.38" selected="yes">
            <activity type="inside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="pt" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
    </person>
    <person id="103">
        <attributes>
            <attribute name="age" class="java.lang.Integer" >53</attribute>
        </attributes>
        <plan score="-0.38" selected="yes">
            <activity type="inside" link="81312" facility="outside_208" x="649324.9906891582" y="6866581.699995641" end_time="08:22:00" >
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="shopping" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="bike" dep_time="08:22:00" trav_time="00:10:13">
                <route type="links" start_link="81312" end_link="138852" trav_time="00:10:13" distance="6046.54932060571" vehicleRefId="7262234">81312</route>
            </leg>
            <activity type="work" link="138852" facility="38407" x="651680.6" y="6863892.5" start_time="08:45:22" end_time="17:15:22" >
                <attributes>
                    <attribute name="innerParis" class="java.lang.Boolean" >true</attribute>
                </attributes>
            </activity>
            <leg mode="pt" dep_time="17:15:22" trav_time="00:07:05">
                <route type="links" start_link="138852" end_link="189898" trav_time="00:07:05" distance="4604.544053407517" vehicleRefId="7262234">138852</route>
            </leg>
            <activity type="outside" link="189898" facility="outside_249" x="648729.9598002436" y="6866057.250182923" end_time="17:20:35" >
            </activity>
        </plan>
    </person>
</population>

What I want is to extract the value of person id  and in case plan selected ="yes" i further want to extract all activity type and leg mode. It should be stored in the existing order as a dictionary for example (or data frame, it doesn't matter really).

So the ideal outcome would look like this:

id    leg_activity
101   outside; car; work; car; outside
102   inside; bike; work; bike; work ...
...

So far I've only worked with JMSPath and I know it is not the most suitable, so I'm happy to see other approaches with elementtree or so:) Also, I was unable to find a way to extract activityand leg information in one step. This is my approach so far:

import gzip
import xmltodict
import pandas as pd
import jmespath

box = xmltodict.parse(gzip.open(gzipfile, 'r'))

expression = jmespath.compile('population.person[].plan[?"@selected"==`yes`].activity[*].["@type"]')

coords = expression.search(box)
coords = pd.DataFrame.from_dict(coords)

Body:
Assuming that your xml is inside test.xml, the following should work:

from bs4 import BeautifulSoup
import pandas as pd
soup = BeautifulSoup(open('test.xml'), features='lxml')
plan_log = []
for person in soup.find_all('person'):
    log = {'id': person.get('id')}
    activities = []
    for plan in person.find_all('plan', attrs={'selected': 'yes'}):
        for detail in plan.children:
            if detail.name == 'activity':
                activities.append(detail.get('type'))
            elif detail.name == 'leg':
                activities.append(detail.get('mode'))
            # activities.append(detail.get('type') or detail.get('mode'))
    log['leg_activity'] = ', '.join(activities)
    plan_log.append(log)
df = pd.DataFrame(plan_log)
print(df)

Output:

    id                                     leg_activity
0  101                 outside, car, work, car, outside
1  102      inside, bike, work, bike, work, pt, outside
2  103  inside, bike, shopping, bike, work, pt, outside


问:
Why do I get unexpected behavior in Python isinstance after pickling?
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:

```<code>from __future__ import with_statement
import pickle

# Simple class definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Create an instance of the class
x = myclass(100)

# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
    pickle.dump(x, f)

# Replace class with exact same definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
    x2 = pickle.load(f)

# The class names appear to match
print x.__class__
print x2.__class__

# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
</code>```

Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.

答:
The obvious answer, because its not the same class.

Its a similar class, but not the same.

```<code>class myclass(object):
    pass

x = myclass()

class myclass(object):
    pass

y = myclass()

assert id(x.__class__) == id(y.__class__) # Will fail, not the same object

x.__class__.foo = "bar"

assert y.__class__.foo == "bar" # will raise AttributeError
</code>```

OwnerDisplayName: Ben Hoffstein

ContentLicense: CC BY-SA 2.5

Body:
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:

from __future__ import with_statement
import pickle

# Simple class definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Create an instance of the class
x = myclass(100)

# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
    pickle.dump(x, f)

# Replace class with exact same definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
    x2 = pickle.load(f)

# The class names appear to match
print x.__class__
print x2.__class__

# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)

Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.

LastEditorDisplayName: Rich B

Body:
The obvious answer, because its not the same class.

Its a similar class, but not the same.

class myclass(object):
    pass

x = myclass()

class myclass(object):
    pass

y = myclass()

assert id(x.__class__) == id(y.__class__) # Will fail, not the same object

x.__class__.foo = "bar"

assert y.__class__.foo == "bar" # will raise AttributeError

OwnerDisplayName: truppo


问:
How to loop multiple form input and assign into sql query in php?
```<code>public function add_employee($input)
{
    $key_array = null;
    $value_array = null;
    $bind_array = null;
    foreach ($input as $column => $value) {
        if ($value) {
            #$bind_array => ?, ?, ?;
            #$value_array => [$value1, $value2, $value3];
            #$key_array => column1, column2, column3;
        }
    }
    $sql = "INSERT INTO ol_employee ($key_array) VALUES ($bind_array)";
    $this->db->query($sql, $value_array);
}
</code>```

Refer to comment in the function, how to achieve that output?
the idea is, from the input POST i get which over 27 fields, i just want to fill in into the $sql query i prepared as you can see. I don't think writing each table column manually is a good way.

im using Codeigniter 4 php framework + postgresql.

答:
by the insight of Alex Granados, this is the query i use:

```<code>public function add_employee($input)
{
    foreach ($input as $column => $value) {
        if ($value) {
            $data[$column] = $value;
        }
    }

    $this->db->table('ol_employee')->insert($data);
}
</code>```

this will eliminate null field  and regardless how many field, still working good.
as long the input name field from form is same as db column. Else, need to do some changes on that.

Thanks guys.

Body:
public function add_employee($input)
{
    $key_array = null;
    $value_array = null;
    $bind_array = null;
    foreach ($input as $column => $value) {
        if ($value) {
            #$bind_array => ?, ?, ?;
            #$value_array => [$value1, $value2, $value3];
            #$key_array => column1, column2, column3;
        }
    }
    $sql = "INSERT INTO ol_employee ($key_array) VALUES ($bind_array)";
    $this->db->query($sql, $value_array);
}

Refer to comment in the function, how to achieve that output?
the idea is, from the input POST i get which over 27 fields, i just want to fill in into the $sql query i prepared as you can see. I don't think writing each table column manually is a good way.

im using Codeigniter 4 php framework + postgresql.

Body:
by the insight of Alex Granados, this is the query i use:

public function add_employee($input)
{
    foreach ($input as $column => $value) {
        if ($value) {
            $data[$column] = $value;
        }
    }

    $this->db->table('ol_employee')->insert($data);
}

this will eliminate null field  and regardless how many field, still working good.
as long the input name field from form is same as db column. Else, need to do some changes on that.

Thanks guys.


问:
SQL server week ending Thursday range
I'm trying to show the DateTimeRaised field as a week ending Thursday. The FkIssueGroupID isn't unique but each row should have the same date. The MAX is being used to bring back a single row.

```<code>Select distinct w.fkIssueGroupID
,[FormDateTimeRaised] =MAX ([DateTimeRaised])
,[WEnd Raised - Thur]= max (CONVERT (date, DATEADD(dd, 5 - (DATEPART(dw, [DateTimeRaised])), [DateTimeRaised]) ))
</code>```

Whilst the week ending value for Thursday is correct the week days contained within it don't line up i.e.:

Week ending Thursday will have a date of the 21/05/20 (Thursday) but the date values covered by the data are 18/05 to 24/05 (Mon-Sun). I want the date range covered to be  15/05 to 21/05 (Fri-Thur). How do i get the date range to shift from Mon-Sun to Fri-Thur?

答:
You can set the first day of the week to Friday like this:</p>

```<code>SET DATEFIRST 5;
</code>```

Title: SQL server week ending Thursday range

Body:
I'm trying to show the DateTimeRaised field as a week ending Thursday. The FkIssueGroupID isn't unique but each row should have the same date. The MAX is being used to bring back a single row.

Select distinct w.fkIssueGroupID
,[FormDateTimeRaised] =MAX ([DateTimeRaised])
,[WEnd Raised - Thur]= max (CONVERT (date, DATEADD(dd, 5 - (DATEPART(dw, [DateTimeRaised])), [DateTimeRaised]) ))

Whilst the week ending value for Thursday is correct the week days contained within it don't line up i.e.:

Week ending Thursday will have a date of the 21/05/20 (Thursday) but the date values covered by the data are 18/05 to 24/05 (Mon-Sun). I want the date range covered to be  15/05 to 21/05 (Fri-Thur). How do i get the date range to shift from Mon-Sun to Fri-Thur?

Body:
You can set the first day of the week to Friday like this:

SET DATEFIRST 5;


问:
What is a bare repository and why would I need one?
This maybe has been answered, but I didn't find a good answer.

I come from centralized repositories, such as SVN, where usually you only perform checkouts, updates, commits, reverts, merges and not much more.

Git is driving me crazy. There are tons of commands, but the most difficult to understand is why many things work as they do.

According to "What is a bare git repository?":

Repositories created with git init --bare are called bare repos. They are structured a bit differently from working directories. First off, they contain no working or checked out copy of your source files.

…

A bare repository created with git init --bare is for… sharing. …developers will clone the shared bare repo, make changes locally in their working copies of the repo, then push back to the shared bare repo to make their changes available to other users.

– Jon Saints, http://www.saintsjd.com/2011/01/what-is-a-bare-git-repository/

However, from the accepted answer to "what's the difference between github repository and git bare repository?":

Git repos on GitHub are bare, like any remote repo to which you want to push to [sic].

– VonC, https://stackoverflow.com/a/20855207

However, in GitHub there are source files. I can see them. If I create a bare repository, there are no source files, only the contents for .git directory of a working repository.

How is this possible? What don't I understand?

Can you give an example about why I would need a bare repository and its motivation to work that way?

UPDATE

Edward Thomson's answer is, in part, what I wanted to know. Nevertheless, I will rephrase my question:

First link I posted states("What is a bare git repository?"):

they [bare repositories] contain no working or checked out copy of your source files.

VonC's answer:

Git repos on GitHub are bare

Both statements implies

Github has no working copy.

Edward Thomson says:

it renders the web page based on the data as you navigate through it - pulling the data directly out of the repo and out to your web browser, not writing it to a disk on the fileserver first

Somehow, a bare repository has to contain all data and source code. If not, it wouldn't be possible to render anything, because I can see all source code updated (commited), all branches (with their respective source), the whole log of a repo, etc.

Is there the whole data of a repository always within .git directory (or in a bare repo), in some kind of format which is able to render all files at any time? Is this the reason of bare repository, while working copy only has the files at a given time?

答:
Why would I need one ?

The link "but why do I need a bare repo?" from the VonC answer could be completed with two use cases I have found recently.

The first is essential to know imho, while the second could be criticized.

A - To sync your home dot files

No more symlinks which point to you git repo. Just use:

```<code>git init --bare $HOME/.myconf
alias config='/usr/bin/git --git-dir=$HOME/.myconf/ --work-tree=$HOME'
config config status.showUntrackedFiles no
</code>```

where my ~/.myconf directory is a git bare repository. Then any file within the home folder can be versioned with normal commands like:

```<code>    config status
    config add .vimrc
    config commit -m "Add vimrc"
    config add .config/redshift.conf
    config commit -m "Add redshift config"
    config push
</code>```

One of the major benefits is that it prevents nested git repos. More details on the source

B - To host a Git project inside a cloud-synced folder

It is not a good idea to create a .git/ dir inside a cloud-synced folder because the synchronization could mess everything up. But using the same technique as above you can use a bare repository outside the synced dir to use versioning and still have the comfort of a synced dir.

Body:
Why would I need one ?

The link "but why do I need a bare repo?" from the VonC answer could be completed with two use cases I have found recently.

The first is essential to know imho, while the second could be criticized.

A - To sync your home dot files

No more symlinks which point to you git repo. Just use:

git init --bare $HOME/.myconf
alias config='/usr/bin/git --git-dir=$HOME/.myconf/ --work-tree=$HOME'
config config status.showUntrackedFiles no

where my ~/.myconf directory is a git bare repository. Then any file within the home folder can be versioned with normal commands like:

    config status
    config add .vimrc
    config commit -m "Add vimrc"
    config add .config/redshift.conf
    config commit -m "Add redshift config"
    config push

One of the major benefits is that it prevents nested git repos. More details on the source

B - To host a Git project inside a cloud-synced folder

It is not a good idea to create a .git/ dir inside a cloud-synced folder because the synchronization could mess everything up. But using the same technique as above you can use a bare repository outside the synced dir to use versioning and still have the comfort of a synced dir.


问:
How to call a function from html button
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

```<code><html>
    <head>
        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

     <script>
             function delete(id){

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                        var available = this.responseText;
                      }
                  };
                xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
                xhttp.send();
            }
        </script>
    </head>

    <body>
        <button type="button" onclick="delete(9)">Erase</button>
    </body>

</html>
</code>```

答: You cant call the function delete. Just Rename it :)</p>

Title: How to call a function from html button

Body:
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

        <button type="button" onclick="delete(9)">Erase</button>


问:
php implode breaks on spaces

I have an array of strings, and these strings have spaces in them. For example:

```<code>$arr = array('bob', 'john smith', 'grease monkey', 'etc');
</code>```

Why is it when I try to $str = implode('|', $arr);, it stops at the first space it finds??
I'm left with a string like:

```<code>$str = "bob|john";
</code>```

If I try:

```<code>$arr = array('bob', 'john', 'grease monkey', 'etc');
</code>```

and implode, I get:

```<code>$str = "bob|john|grease";
</code>```

Edit: I'm actually trying to set it to the value of a hidden field:

```<code><input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />
</code>```

答:
You must have an error somewhere else in your code, implode() does not break on spaces.

```<code>$arr = array('bob', 'john', 'grease monkey', 'etc');
$str = implode('|', $arr);
var_dump($str);
// gives
string(26) "bob|john|grease monkey|etc"
</code>```

As for your edit, you need quotes around attributes in html:

```<code><input id="hidLblFields" name="hidLblFields" type="text" value="<?php echo implode('|', $myFields);?>" />
</code>```

Title: php implode breaks on spaces

Body:
I have an array of strings, and these strings have spaces in them. For example:

$arr = array('bob', 'john smith', 'grease monkey', 'etc');

Why is it when I try to $str = implode('|', $arr);, it stops at the first space it finds??
I'm left with a string like:

$str = "bob|john";

If I try:

$arr = array('bob', 'john', 'grease monkey', 'etc');

and implode, I get:

$str = "bob|john|grease";

Edit: I'm actually trying to set it to the value of a hidden field:

<input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />

Body:
You must have an error somewhere else in your code, implode() does not break on spaces.

$arr = array('bob', 'john', 'grease monkey', 'etc');
$str = implode('|', $arr);
var_dump($str);
// gives
string(26) "bob|john|grease monkey|etc"

As for your edit, you need quotes around attributes in html:

<input id="hidLblFields" name="hidLblFields" type="text" value="<?php echo implode('|', $myFields);?>" />


问:
How can I access mongodb count results in nodejs with a callback?
How do you access mongodb count results in nodejs so the result can be accessible to the asynchronous request? I can get the result and update the database but the asynchronous request fails to access the vars or the vars are empty and the vars appear to be updated when the next asynchronous request is made. The request must not be waiting for the query to finish and the next request is filled with the previous request's variables.

```<code>testOne.increment = function(request) {
    var MongoClient = require('mongodb').MongoClient,
        format = require('util').format;
    MongoClient.connect('mongodb://127.0.0.1:27017/bbb_tracking', function(err, db) {
    if (err) throw err;
    collection = db.collection('bbb_tio');
        collection.count({vio_domain:dom}, function(err, docs) {
    if (err) throw err;
    if (docs > 0) {
            var vio_val = 3;
        } else {
            var vio_val = 0;
        }
        if (vio_val === 3) {
                event = "New_Event";
        var inf = 3;
            }
        db.close();

        console.log("docs " + docs);
        });
   });
};
</code>```

In the above, even when the vars are set in scope they are not defined asynchronously. Can I get some guidance on structuring this properly so the vars are populated in the callback.  Thank you!

答:
length give you count of result array </p>

```<code>  const userdata = await User.find({ role: role, 'name': new RegExp(searchkey, 'i')  },{date: 0,__v:0,password:0}).
      sort(orderObj)
      .limit(limit)
      .skip(skip);

      console.log(userdata.length);
</code>```

Body:
How do you access mongodb count results in nodejs so the result can be accessible to the asynchronous request? I can get the result and update the database but the asynchronous request fails to access the vars or the vars are empty and the vars appear to be updated when the next asynchronous request is made. The request must not be waiting for the query to finish and the next request is filled with the previous request's variables.

testOne.increment = function(request) {
    var MongoClient = require('mongodb').MongoClient,
        format = require('util').format;
    MongoClient.connect('mongodb://127.0.0.1:27017/bbb_tracking', function(err, db) {
    if (err) throw err;
    collection = db.collection('bbb_tio');
        collection.count({vio_domain:dom}, function(err, docs) {
    if (err) throw err;
    if (docs > 0) {
            var vio_val = 3;
        } else {
            var vio_val = 0;
        }
        if (vio_val === 3) {
                event = "New_Event";
        var inf = 3;
            }
        db.close();

        console.log("docs " + docs);
        });
   });
};

In the above, even when the vars are set in scope they are not defined asynchronously. Can I get some guidance on structuring this properly so the vars are populated in the callback.  Thank you!

Body:
length give you count of result array

  const userdata = await User.find({ role: role, 'name': new RegExp(searchkey, 'i')  },{date: 0,__v:0,password:0}).
      sort(orderObj)
      .limit(limit)
      .skip(skip);

      console.log(userdata.length);