问:
texts_to_sequences return empty string after loading the tokenizer
I'm working on a project, I've trained and saved my model as well as tokenizer

```<code>tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)

# save tokenizer
import pickle
# saving
with open('english_tokenizer_test.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

total_words = len(tokenizer.word_index) +1
</code>```
```<code>from keras.models import load_model

model2.save('model.h5')
</code>```

and loading the model and the tokenizer

```<code>with open('../input/shyaridatasettesting/english_tokenizer_test.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)

tokenizer = Tokenizer()
max_sequence_len = 24
model = tf.keras.models.load_model('../input/model.h5')
print(model);
</code>```

So when I'm doing tokenizer using loaded tokenizer it returns an empty string

```<code>token_list = tokenizer.texts_to_sequences(["this is something"])[0]
</code>```

I want to use my model and tokenizer on my website but I'm getting an empty token_list whenever I pass text in into my tokenizer?

please help me if I'm doing something wrong.

答:
The problem is you are creating a new Tokenizer with the same name after loading your original tokenizer and therefore it is overwritten. Here is a working example:

import tensorflow as tf
import pickle

corpus = ['this is something', 'this is something more', 'this is nothing']
tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(corpus)

### Save tokenizer
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

### Load tokenizer
with open('/content/tokenizer.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)
token_list = tokenizer.texts_to_sequences(["this is something"])[0]
print(token_list)
```
```[1, 2, 3]
```

Body:
I'm working on a project, I've trained and saved my model as well as tokenizer

tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)

# save tokenizer
import pickle
# saving
with open('english_tokenizer_test.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

total_words = len(tokenizer.word_index) +1

from keras.models import load_model

model2.save('model.h5')

and loading the model and the tokenizer

with open('../input/shyaridatasettesting/english_tokenizer_test.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)

tokenizer = Tokenizer()
max_sequence_len = 24
model = tf.keras.models.load_model('../input/model.h5')
print(model);

So when I'm doing tokenizer using loaded tokenizer it returns an empty string

token_list = tokenizer.texts_to_sequences(["this is something"])[0]

I want to use my model and tokenizer on my website but I'm getting an empty token_list whenever I pass text in into my tokenizer?

please help me if I'm doing something wrong.

Body:
The problem is you are creating a new Tokenizer with the same name after loading your original tokenizer and therefore it is overwritten. Here is a working example:

import tensorflow as tf
import pickle

corpus = ['this is something', 'this is something more', 'this is nothing']
tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(corpus)

### Save tokenizer
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

### Load tokenizer
with open('/content/tokenizer.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)
token_list = tokenizer.texts_to_sequences(["this is something"])[0]
print(token_list)

[1, 2, 3]


来源: stackexchange

问:
How to cumsum the elements of a vector under certain condition in R?
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

```<code>vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)
</code>```

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

```<code>vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)
</code>```

How can I achieve this?

答:
You can use a custom function instead of cumsum and accumulate results using e.g. purrr::accumulate:

library(purrr)
vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

purrr::accumulate(vector_A, function(a,b) {
  if (sign(a) == sign(b))
    a+b
  else
    b
  })

[1]  1  2 -1 -2 -3  1 -1 -2  1 -1
```
<p>or if you want to avoid any branch:</p>
<pre class="lang-r prettyprint-override"><code>purrr::accumulate(vector_A, function(a,b) { b + a*(sign(a) == sign(b))})

[1]  1  2 -1 -2 -3  1 -1 -2  1 -1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)

How can I achieve this?

Body:
You can use a custom function instead of cumsum and accumulate results using e.g. purrr::accumulate:

library(purrr)
vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

purrr::accumulate(vector_A, function(a,b) {
  if (sign(a) == sign(b))
    a+b
  else
    b
  })

[1]  1  2 -1 -2 -3  1 -1 -2  1 -1

or if you want to avoid any branch:

purrr::accumulate(vector_A, function(a,b) { b + a*(sign(a) == sign(b))})

[1]  1  2 -1 -2 -3  1 -1 -2  1 -1


问:
Flutter golden tests failing on CI
I recently added a bunch of golden file tests (and generated the goldens by running flutter test --generate-goldens) to my Flutter plugin. All of the tests successfully pass on my development device, but consistently fail when they run on Circle CI (for example: https://circleci.com/gh/Sub6Resources/flutter_html/78).

Am I missing a step in creating the golden tests? Or is there maybe a configuration option I need to add to Circle CI in order for the image files to be added correctly?

答:
I think you are using an old Flutter ORB on CircleCI. Flutter ORB is set to 1.0.2 and it looks like your code needs 3.0.0. I took the liberty to run your code using that ORB and it worked. I mean, I saw some errors but they are related to the tests.

You just need to update your https://github.com/Sub6Resources/flutter_html/blob/master/.circleci/config.yml#L3 to:

```<code>  codecov: codecov/codecov@3.0.0
</code>```

Title: Flutter golden tests failing on CI

Body:
I think you are using an old Flutter ORB on CircleCI. Flutter ORB is set to 1.0.2 and it looks like your code needs 3.0.0. I took the liberty to run your code using that ORB and it worked. I mean, I saw some errors but they are related to the tests.

You just need to update your https://github.com/Sub6Resources/flutter_html/blob/master/.circleci/config.yml#L3 to:

  codecov: codecov/codecov@3.0.0


问:
throw checked exception as unchecked in java instead of wrapping
I have the following code and i need to scan the Exception thrown. If it satisfies a particular condition i ignore the exception. Else i re-throw. The exception being thrown is a checked exception that means re-throwing is the hard part. Including the fact that i had to catch it and the operation is taking place inside an overridden method whose base class' method did not use the throws clause. Stuck between reprogramming the whole enormous library or wrapping the exception as RuntimeException (Which is not an option, as the checked exception we will have wrapped, is expected somewhere in future (derived class) by a catch clause during its propagation - its some kind of signal), i hope to get some advice on such an implementation. Or maybe just the implementation.

    /*
     * Translated from c++11_7.3.19 AIEDs schemes >${ref[213]:`through}.
     * guarantees learning, re-learning and 'un-learning'. programmed intelligence is not
     * altered whatsover and is made as root of bias [x:~y]. fetch cycle is omitted.
     */
    @Override
    public void intelligenceSync()// No throws clause here
    {
        try {
            super.intelligenceSync();
            // the throwing culprit.
            global_contribution.acceptOrReformState(this);
            generateMetaLogicReforms(this);
        } catch (Throwable t_) {
            if (t_ instanceof Signalx) {
                Signalx sx = (Signalx) t_;
                // Note how bias inreases propagation speed by ~12.21 >${ref[371]:exp2}.
                applyBias(sx);
                stopInvalidation(sx);
                // check if x neuron is almost proved.
                if (sx.neuronSP() > sx.threshold()) {
                    // We'll find other ways of completing our proofs.
                    // Note the algorithm is not so complete.
                    netsync(sx);
                    while (sx.pushDeeper()) {
                        sx.enhance(Metrics.COMPLETION.esteem());
                        sx.suspendSubPathTraversal(Suspender.IN_DREAM_RESOLVE, Handler.NULL_LOGIC);
                    }
                    generateSubLogicReforms(sx);
                } else {
                    restore(sx);
                    continueInvalidation(sx);
                    // We rethrow.
                    uncheckedThrow(sx);
                    // exception thrown
                }
            } else if (t_ instanceof Signaly) {
                // Reforms must be handle explicitly.otherwise RelationalAttender will complain
                // .
                // ... blah blah blah.
            } else {
                // We rethrow
                uncheckedThrow(t_);
            }
            //
        }
    }

```

答:
I needed something similar, but my method was expecting a return value, which caused me to return null or something similar.

Thus, I made a small adaption:

```<code>private static <T extends Throwable> RuntimeException unchecked(Throwable t) throws T {
    throw (T) t;
}
</code>```

The method is now returning a RuntimeException, which allows us to "throw" the unchecked exception, which bypasses the compiler, and does not longer expect to return any value.

```<code>private static String yourIOOperationThatReturnsSomething() {
    throw unchecked(new IOException("test"));
}

public static void main(String []args) {
    System.out.println(yourIOOperationThatReturnsSomething());
}
</code>```

A running example can be found here: http://tpcg.io/VIC7A6

Body:
I needed something similar, but my method was expecting a return value, which caused me to return null or something similar.

Thus, I made a small adaption:

private static <T extends Throwable> RuntimeException unchecked(Throwable t) throws T {
    throw (T) t;
}

The method is now returning a RuntimeException, which allows us to "throw" the unchecked exception, which bypasses the compiler, and does not longer expect to return any value.

private static String yourIOOperationThatReturnsSomething() {
    throw unchecked(new IOException("test"));
}

public static void main(String []args) {
    System.out.println(yourIOOperationThatReturnsSomething());
}

A running example can be found here: http://tpcg.io/VIC7A6


问:
IfxBulkCopy class doesn't exist?
Q:

I face the following problem.

I wanna to create an object from the following class IfxBulkCopy but it doesn't appear at all.

I do the following:

1- Add a reference IBM.Data.Informix .

2- Add using IBM.Data.Informix;

but in vain .

I search in the documentation and it exists .but i can't find it .

Please help .if there is a different version or some error i made?

答:
I think you need the Common IDS .NET provider.
Basically there are two different providers that implement classes in the IBM.Data.Informix namespace.

More info here

ContentLicense: CC BY-SA 3.0

Title: IfxBulkCopy class doesn't exist?


问:
Import Error: cannot import 'mdss_bias_scan' from 'aif360.sklearn.metrics'
I would like to use the mdss_bias_scan function of aif360 for detecting the combination of variables that make up the privileged group and the non-privileged group.

When I try to import the function:
from aif360.sklearn.metrics import mdss_bias_scan

I get the following error:
Import error: cannot import 'mdss_bias_scan' from 'aif360.sklearn.metrics'.

Can you help me to fix it?

答:
Update

The function mdss_bias_scan is not available in the version of aif360 you're using (v0.4.0).

Here's the source code of the file metrics.py at tag v0.4.0.

The function mdss_bias_scan was added via this commit which has not yet been released.

From the GitHub Source, it seems that you should import it as:

```<code>from aif360.sklearn.metrics.metrics import mdss_bias_scan
</code>```

Also, make sure you have aif360 package installed in your Python environment. If not, install it using:

```<code>pip install aif360
</code>```

Body:
Update

The function mdss_bias_scan is not available in the version of aif360 you're using (v0.4.0).

Here's the source code of the file metrics.py at tag v0.4.0.

The function mdss_bias_scan was added via this commit which has not yet been released.

From the GitHub Source, it seems that you should import it as:

from aif360.sklearn.metrics.metrics import mdss_bias_scan

Also, make sure you have aif360 package installed in your Python environment. If not, install it using:

pip install aif360


问:
Why does mutableStateOf without remember work sometimes?
I've been playing with Jetpack Compose Desktop. I noticed something I really don't understand:

```<code>import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    MaterialTheme {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}
</code>```

Why am I able to change the text in the TextField? I thought, that on every recompose the mutable state get reinstanciated with the initial Value: so the Text should not be able to change

```<code>import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    Column {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}
</code>```

However, if you replace the MaterialTheme with an Column it suddendly works as expected and you aren't able to change the text in the TextField.

Why is that? Is that a bug or a feature?

答:
I thought, that on every recompose the mutable state get reinstanciated with the initial Value: so the Text should not be able to change

The point of having a state when recomposing is to prevent a variable from being re-initialized. The initial state is used only once when the first composition occurs and isn't used again when further recompositions occur. If however the composable is removed from the UI tree and then reinstated later on, the state of the variable will be destroyed and re-initialized as this is not really a recomposition but a composition (as if it were happening for the first time).

Body:
I've been playing with Jetpack Compose Desktop. I noticed something I really don't understand:

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    MaterialTheme {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}

Why am I able to change the text in the TextField? I thought, that on every recompose the mutable state get reinstanciated with the initial Value: so the Text should not be able to change

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    Column {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}

However, if you replace the MaterialTheme with an Column it suddendly works as expected and you aren't able to change the text in the TextField.

Why is that? Is that a bug or a feature?


问:
How does the browser reach an IP address?
When I type a domain URL in the browser (or send a ping or write code that fetches a particular IP) the browser gets the associated IP address based on DNS lookup in a distributed database system - the DNS name servers.

But once the IP is obtained - how does the browser know how to go to the particular computer that this IP represents?

```<code>import urllib.request
nf = urllib.request.urlopen("http://192.168.1.2")
</code>```

答:
The operating system will compare the target IP address with its own IP address. If both addresses are part of the same network, the OS will issue an ARP request to obtain the physical address (the MAC) of the target interface.

If both IP addresses are not part of the same network, the OS will forward the traffic to the gateway responsible for the subnet that is addressed. If it has no such a route, the OS will forward the traffic to the default gateway.

From there the game starts anew.

Body:
When I type a domain URL in the browser (or send a ping or write code that fetches a particular IP) the browser gets the associated IP address based on DNS lookup in a distributed database system - the DNS name servers.

But once the IP is obtained - how does the browser know how to go to the particular computer that this IP represents?

import urllib.request
nf = urllib.request.urlopen("http://192.168.1.2")


问:
Add CSS if font does not load
With document.fonts.ready.then, it is possible to change CSS if a font is loaded.

Example:

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  src: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/133207/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}</code>```

Lorem ipusm
```

Now my question is:
Does something like document.fonts.NOT.ready.then exist? Or how can I change the CSS if the font gets not loaded?

Would be very thankful for help.

答:
MDN suggests you can check for

```<code>document.fonts.status == 'loading'
</code>```

or .check() for specific font(s).

For errors add an event handler for onloadingerror

In the test snippet below, .status changes to loaded immediately, there's a Failed to load resource immediately, but neither .ready nor .onloadingerror are called at that time, instead wait for 2 minutes then you get both .ready and .onloadingerror events fire along with another GET ERR_CONNECTION_TIMED_OUT error (ensure browser console is open)

This is likely just due to the url for the font - a closer match to a valid font may return quicker or a 403 may return quicker etc

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
  $("div").text(document.fonts.status);
});

document.fonts.onloadingerror = () => {
  $("div").css("background-color", "pink");
}

$("div").text(document.fonts.status);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  src: url("https://badurl.com/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}</code>```

Lorem ipusm
```

Title: Add CSS if font does not load

Body:
With document.fonts.ready.then, it is possible to change CSS if a font is loaded.

Example:

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
});

@font-face {
  src: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/133207/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}

Lorem ipusm

Now my question is:
Does something like document.fonts.NOT.ready.then exist? Or how can I change the CSS if the font gets not loaded?

Would be very thankful for help.

Body:
MDN suggests you can check for

document.fonts.status == 'loading'

or .check() for specific font(s).

For errors add an event handler for onloadingerror

In the test snippet below, .status changes to loaded immediately, there's a Failed to load resource immediately, but neither .ready nor .onloadingerror are called at that time, instead wait for 2 minutes then you get both .ready and .onloadingerror events fire along with another GET ERR_CONNECTION_TIMED_OUT error (ensure browser console is open)

This is likely just due to the url for the font - a closer match to a valid font may return quicker or a 403 may return quicker etc

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
  $("div").text(document.fonts.status);
});

document.fonts.onloadingerror = () => {
  $("div").css("background-color", "pink");
}

$("div").text(document.fonts.status);

@font-face {
  src: url("https://badurl.com/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Lorem ipusm</div>


问:
Running .NET 6 project in Docker throws Globalization.CultureNotFoundException
I have upgraded API project from .NET 5 to .NET 6 successfully and running fine when executed locally (without Docker).

I have also updated the version in Dockerfile from "5.0-alpine3.13" to "6.0-alpine3.14" as below (only change I made).

```<code>ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]
</code>```

But when I run this .NET 6 project in Docker it throws the below Azure.Storage exception in the Startup.cs file.

Full stack trace is here.

```<code>Microsoft.Azure.Storage.StorageException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
---> System.Globalization.CultureNotFoundException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
at Microsoft.Azure.Storage.Core.Util.AuthenticationUtility.AppendCanonicalizedCustomHeaders(CanonicalizedString canonicalizedString, HttpRequestMessage request)
at Microsoft.Azure.Storage.Core.Auth.SharedKeyCanonicalizer.CanonicalizeHttpRequest(HttpRequestMessage request, String accountName)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.GetSharedKeyAuthenticationTask(StorageRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
--- End of inner exception stack trace ---
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at RM.Api.Startup.ConfigureServices(IServiceCollection services) in /src/src/RM.Api/Startup.cs:line 91
</code>```

I have updated the Dockerfile as below but it did not work.
Can any one help here?

```<code>ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

RUN apk add --no-cache icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib

ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]
</code>```

答:
Making the following two changes resolved the issue.

Updating the Dockerfile as below

```<code>    ARG VERSION=6.0-alpine3.14

    #Runtime stage
    FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
    EXPOSE 8080

    ENV DOTNET_RUNNING_IN_CONTAINER=true \
      ASPNETCORE_URLS=http://+:8080

    RUN apk add --no-cache icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib

    ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
</code>```

Added the below in .csproj file

  <PropertyGroup>
    <InvariantGlobalization>false</InvariantGlobalization>
  </PropertyGroup>```

Body:
I have upgraded API project from .NET 5 to .NET 6 successfully and running fine when executed locally (without Docker).

I have also updated the version in Dockerfile from "5.0-alpine3.13" to "6.0-alpine3.14" as below (only change I made).

ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]

But when I run this .NET 6 project in Docker it throws the below Azure.Storage exception in the Startup.cs file.

Full stack trace is here.

Microsoft.Azure.Storage.StorageException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
---> System.Globalization.CultureNotFoundException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
at Microsoft.Azure.Storage.Core.Util.AuthenticationUtility.AppendCanonicalizedCustomHeaders(CanonicalizedString canonicalizedString, HttpRequestMessage request)
at Microsoft.Azure.Storage.Core.Auth.SharedKeyCanonicalizer.CanonicalizeHttpRequest(HttpRequestMessage request, String accountName)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.GetSharedKeyAuthenticationTask(StorageRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
--- End of inner exception stack trace ---
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at RM.Api.Startup.ConfigureServices(IServiceCollection services) in /src/src/RM.Api/Startup.cs:line 91

I have updated the Dockerfile as below but it did not work.
Can any one help here?

ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

RUN apk add --no-cache icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib

ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]

Body:
Making the following two changes resolved the issue.

Updating the Dockerfile as below

    ARG VERSION=6.0-alpine3.14

    #Runtime stage
    FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
    EXPOSE 8080

    ENV DOTNET_RUNNING_IN_CONTAINER=true \
      ASPNETCORE_URLS=http://+:8080

    RUN apk add --no-cache icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib

    ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false

Added the below in .csproj file

  <PropertyGroup>
    <InvariantGlobalization>false</InvariantGlobalization>
  </PropertyGroup>


问:
Is NPM package's type declaration files must be .d.ts file?
In my eyes, we can put type declaration in any typescript file ( such as '.d.ts', '.ts', '.tsx' ).

But I found that almost every npm package's type declaration file is .d.ts file.

Is this necessary?

My real world scene is that I just want my npm package been used by some typescript project, so I publish my package without compile (all .ts files)

I'm not sure is there any problem?

答:
When publishing a package you generate .js files and .d.ts files. This guarantees that people can install your package in a 'normal' JavaScript project and do not have to use TypeScript if they don't want to. They can not interpret .ts or .tsx files. The .d.ts files alongside your .js files can then be ignored.

If you only want to use this package in your own TypeScript projects. You will have to tell your bundler (like Webpack) to also compile this package by using the ts-loader, as a browser cannot interpret TypeScript. Also, if it is a Node.js app, Node itself is a lot faster than ts-node. In my opinion this would be unnecessary overhead.


问:
memstat HeapInuse and TotalAlloc need explain
i want dump golang memstat

package main

import (
    "fmt"
    "github.com/dustin/go-humanize"
    "runtime"
    "time"
)

func main() {
    for {
        var mem = new(runtime.MemStats)
        runtime.ReadMemStats(mem)
        fmt.Println("HeapInuse:", humanize.Bytes(mem.HeapInuse), "TotalAlloc:", humanize.Bytes(mem.TotalAlloc))

        allocate()
        time.Sleep(100 * time.Millisecond)
    }

}

func allocate() {
    //  0.25MB
    _ = make([]byte, int((1<<20)*0.25))
}

```
<p>when i dump the mem info</p>
```HeapInuse: 418 kB TotalAlloc: 154 kB ? why  HeapInuse bigger than TotalAlloc
HeapInuse: 688 kB TotalAlloc: 417 kB
HeapInuse: 950 kB TotalAlloc: 680 kB
HeapInuse: 1.2 MB TotalAlloc: 942 kB
HeapInuse: 1.5 MB TotalAlloc: 1.2 MB
HeapInuse: 1.8 MB TotalAlloc: 1.5 MB
HeapInuse: 2.0 MB TotalAlloc: 1.7 MB
HeapInuse: 2.3 MB TotalAlloc: 2.0 MB
HeapInuse: 2.5 MB TotalAlloc: 2.3 MB
HeapInuse: 2.8 MB TotalAlloc: 2.5 MB
HeapInuse: 3.1 MB TotalAlloc: 2.8 MB
HeapInuse: 3.3 MB TotalAlloc: 3.0 MB
HeapInuse: 3.6 MB TotalAlloc: 3.3 MB
HeapInuse: 3.9 MB TotalAlloc: 3.6 MB
HeapInuse: 4.1 MB TotalAlloc: 3.8 MB
HeapInuse: 4.4 MB TotalAlloc: 4.1 MB
HeapInuse: 410 kB TotalAlloc: 4.4 MB
```

i found    HeapInuse bigger than TotalAlloc? but i cannt understand reason ? i think the totalAlloc should include HeapInuse.

答:
Let's read the official comments below:

TotalAlloc

```<code>// TotalAlloc is cumulative bytes allocated for heap objects.
//
// TotalAlloc increases as heap objects are allocated, but
// unlike Alloc and HeapAlloc, it does not decrease when
// objects are freed.
TotalAlloc uint64
</code>```

HeapInuse

```<code>// HeapInuse is bytes in in-use spans.
//
// In-use spans have at least one object in them. These spans
// can only be used for other objects of roughly the same
// size.
//
// HeapInuse minus HeapAlloc estimates the amount of memory
// that has been dedicated to particular size classes, but is
// not currently being used. This is an upper bound on
// fragmentation, but in general this memory can be reused
// efficiently.
HeapInuse uint64
</code>```

HeapInuse is memory allocated (from the OS), may not be used by objects

TotalAlloc is memory allocated for heap objects

Let's try HeapAlloc

```<code>// HeapAlloc is bytes of allocated heap objects.
//
// "Allocated" heap objects include all reachable objects, as
// well as unreachable objects that the garbage collector has
// not yet freed. Specifically, HeapAlloc increases as heap
// objects are allocated and decreases as the heap is swept
// and unreachable objects are freed. Sweeping occurs
// incrementally between GC cycles, so these two processes
// occur simultaneously, and as a result HeapAlloc tends to
// change smoothly (in contrast with the sawtooth that is
// typical of stop-the-world garbage collectors).
HeapAlloc uint64
</code>```

Result

```<code>HeapAlloc: 148 kB HeapInuse: 401 kB TotalAlloc: 148 kB
HeapAlloc: 412 kB HeapInuse: 664 kB TotalAlloc: 412 kB
HeapAlloc: 675 kB HeapInuse: 926 kB TotalAlloc: 675 kB
HeapAlloc: 937 kB HeapInuse: 1.2 MB TotalAlloc: 937 kB
HeapAlloc: 1.2 MB HeapInuse: 1.5 MB TotalAlloc: 1.2 MB
HeapAlloc: 1.5 MB HeapInuse: 1.7 MB TotalAlloc: 1.5 MB
HeapAlloc: 1.7 MB HeapInuse: 2.0 MB TotalAlloc: 1.7 MB
HeapAlloc: 2.0 MB HeapInuse: 2.2 MB TotalAlloc: 2.0 MB
HeapAlloc: 2.2 MB HeapInuse: 2.5 MB TotalAlloc: 2.2 MB
HeapAlloc: 2.5 MB HeapInuse: 2.8 MB TotalAlloc: 2.5 MB
HeapAlloc: 2.8 MB HeapInuse: 3.0 MB TotalAlloc: 2.8 MB
HeapAlloc: 3.0 MB HeapInuse: 3.3 MB TotalAlloc: 3.0 MB
HeapAlloc: 3.3 MB HeapInuse: 3.6 MB TotalAlloc: 3.3 MB
HeapAlloc: 3.6 MB HeapInuse: 3.8 MB TotalAlloc: 3.6 MB
HeapAlloc: 3.8 MB HeapInuse: 4.1 MB TotalAlloc: 3.8 MB
HeapAlloc: 4.1 MB HeapInuse: 4.3 MB TotalAlloc: 4.1 MB
HeapAlloc: 134 kB HeapInuse: 393 kB TotalAlloc: 4.4 MB
HeapAlloc: 398 kB HeapInuse: 664 kB TotalAlloc: 4.6 MB
HeapAlloc: 660 kB HeapInuse: 926 kB TotalAlloc: 4.9 MB
HeapAlloc: 923 kB HeapInuse: 1.2 MB TotalAlloc: 5.1 MB
HeapAlloc: 1.2 MB HeapInuse: 1.4 MB TotalAlloc: 5.4 MB
HeapAlloc: 1.4 MB HeapInuse: 1.7 MB TotalAlloc: 5.7 MB
HeapAlloc: 1.7 MB HeapInuse: 2.0 MB TotalAlloc: 5.9 MB
HeapAlloc: 2.0 MB HeapInuse: 2.2 MB TotalAlloc: 6.2 MB
HeapAlloc: 2.2 MB HeapInuse: 2.5 MB TotalAlloc: 6.5 MB
HeapAlloc: 2.5 MB HeapInuse: 2.8 MB TotalAlloc: 6.7 MB
HeapAlloc: 2.8 MB HeapInuse: 3.0 MB TotalAlloc: 7.0 MB
HeapAlloc: 3.0 MB HeapInuse: 3.3 MB TotalAlloc: 7.2 MB
HeapAlloc: 3.3 MB HeapInuse: 3.5 MB TotalAlloc: 7.5 MB
HeapAlloc: 3.5 MB HeapInuse: 3.8 MB TotalAlloc: 7.8 MB
HeapAlloc: 3.8 MB HeapInuse: 4.1 MB TotalAlloc: 8.0 MB
HeapAlloc: 4.1 MB HeapInuse: 4.3 MB TotalAlloc: 8.3 MB
HeapAlloc: 136 kB HeapInuse: 401 kB TotalAlloc: 8.6 MB
HeapAlloc: 400 kB HeapInuse: 664 kB TotalAlloc: 8.8 MB
HeapAlloc: 662 kB HeapInuse: 926 kB TotalAlloc: 9.1 MB
HeapAlloc: 924 kB HeapInuse: 1.2 MB TotalAlloc: 9.3 MB
HeapAlloc: 1.2 MB HeapInuse: 1.4 MB TotalAlloc: 9.6 MB
HeapAlloc: 1.4 MB HeapInuse: 1.7 MB TotalAlloc: 9.9 MB
HeapAlloc: 1.7 MB HeapInuse: 2.0 MB TotalAlloc: 10 MB
HeapAlloc: 2.0 MB HeapInuse: 2.2 MB TotalAlloc: 10 MB
HeapAlloc: 2.2 MB HeapInuse: 2.5 MB TotalAlloc: 11 MB
HeapAlloc: 2.5 MB HeapInuse: 2.8 MB TotalAlloc: 11 MB
HeapAlloc: 2.8 MB HeapInuse: 3.0 MB TotalAlloc: 11 MB
HeapAlloc: 3.0 MB HeapInuse: 3.3 MB TotalAlloc: 11 MB
HeapAlloc: 3.3 MB HeapInuse: 3.5 MB TotalAlloc: 12 MB
HeapAlloc: 3.5 MB HeapInuse: 3.8 MB TotalAlloc: 12 MB
HeapAlloc: 3.8 MB HeapInuse: 4.1 MB TotalAlloc: 12 MB
HeapAlloc: 4.1 MB HeapInuse: 4.3 MB TotalAlloc: 12 MB
HeapAlloc: 136 kB HeapInuse: 401 kB TotalAlloc: 13 MB
HeapAlloc: 400 kB HeapInuse: 664 kB TotalAlloc: 13 MB
HeapAlloc: 663 kB HeapInuse: 926 kB TotalAlloc: 13 MB
HeapAlloc: 925 kB HeapInuse: 1.2 MB TotalAlloc: 14 MB
HeapAlloc: 1.2 MB HeapInuse: 1.4 MB TotalAlloc: 14 MB
HeapAlloc: 1.4 MB HeapInuse: 1.7 MB TotalAlloc: 14 MB
</code>```

Body:
i want dump golang memstat

package main

import (
    "fmt"
    "github.com/dustin/go-humanize"
    "runtime"
    "time"
)

func main() {
    for {
        var mem = new(runtime.MemStats)
        runtime.ReadMemStats(mem)
        fmt.Println("HeapInuse:", humanize.Bytes(mem.HeapInuse), "TotalAlloc:", humanize.Bytes(mem.TotalAlloc))

        allocate()
        time.Sleep(100 * time.Millisecond)
    }

}

func allocate() {
    //  0.25MB
    _ = make([]byte, int((1<<20)*0.25))
}

when i dump the mem info

HeapInuse: 418 kB TotalAlloc: 154 kB ? why  HeapInuse bigger than TotalAlloc
HeapInuse: 688 kB TotalAlloc: 417 kB
HeapInuse: 950 kB TotalAlloc: 680 kB
HeapInuse: 1.2 MB TotalAlloc: 942 kB
HeapInuse: 1.5 MB TotalAlloc: 1.2 MB
HeapInuse: 1.8 MB TotalAlloc: 1.5 MB
HeapInuse: 2.0 MB TotalAlloc: 1.7 MB
HeapInuse: 2.3 MB TotalAlloc: 2.0 MB
HeapInuse: 2.5 MB TotalAlloc: 2.3 MB
HeapInuse: 2.8 MB TotalAlloc: 2.5 MB
HeapInuse: 3.1 MB TotalAlloc: 2.8 MB
HeapInuse: 3.3 MB TotalAlloc: 3.0 MB
HeapInuse: 3.6 MB TotalAlloc: 3.3 MB
HeapInuse: 3.9 MB TotalAlloc: 3.6 MB
HeapInuse: 4.1 MB TotalAlloc: 3.8 MB
HeapInuse: 4.4 MB TotalAlloc: 4.1 MB
HeapInuse: 410 kB TotalAlloc: 4.4 MB

i found    HeapInuse bigger than TotalAlloc? but i cannt understand reason ? i think the totalAlloc should include HeapInuse.

Body:
Let's read the official comments below:

TotalAlloc

// TotalAlloc is cumulative bytes allocated for heap objects.
//
// TotalAlloc increases as heap objects are allocated, but
// unlike Alloc and HeapAlloc, it does not decrease when
// objects are freed.
TotalAlloc uint64

HeapInuse

// HeapInuse is bytes in in-use spans.
//
// In-use spans have at least one object in them. These spans
// can only be used for other objects of roughly the same
// size.
//
// HeapInuse minus HeapAlloc estimates the amount of memory
// that has been dedicated to particular size classes, but is
// not currently being used. This is an upper bound on
// fragmentation, but in general this memory can be reused
// efficiently.
HeapInuse uint64

HeapInuse is memory allocated (from the OS), may not be used by objects

TotalAlloc is memory allocated for heap objects

Let's try HeapAlloc

// HeapAlloc is bytes of allocated heap objects.
//
// "Allocated" heap objects include all reachable objects, as
// well as unreachable objects that the garbage collector has
// not yet freed. Specifically, HeapAlloc increases as heap
// objects are allocated and decreases as the heap is swept
// and unreachable objects are freed. Sweeping occurs
// incrementally between GC cycles, so these two processes
// occur simultaneously, and as a result HeapAlloc tends to
// change smoothly (in contrast with the sawtooth that is
// typical of stop-the-world garbage collectors).
HeapAlloc uint64

Result

HeapAlloc: 148 kB HeapInuse: 401 kB TotalAlloc: 148 kB
HeapAlloc: 412 kB HeapInuse: 664 kB TotalAlloc: 412 kB
HeapAlloc: 675 kB HeapInuse: 926 kB TotalAlloc: 675 kB
HeapAlloc: 937 kB HeapInuse: 1.2 MB TotalAlloc: 937 kB
HeapAlloc: 1.2 MB HeapInuse: 1.5 MB TotalAlloc: 1.2 MB
HeapAlloc: 1.5 MB HeapInuse: 1.7 MB TotalAlloc: 1.5 MB
HeapAlloc: 1.7 MB HeapInuse: 2.0 MB TotalAlloc: 1.7 MB
HeapAlloc: 2.0 MB HeapInuse: 2.2 MB TotalAlloc: 2.0 MB
HeapAlloc: 2.2 MB HeapInuse: 2.5 MB TotalAlloc: 2.2 MB
HeapAlloc: 2.5 MB HeapInuse: 2.8 MB TotalAlloc: 2.5 MB
HeapAlloc: 2.8 MB HeapInuse: 3.0 MB TotalAlloc: 2.8 MB
HeapAlloc: 3.0 MB HeapInuse: 3.3 MB TotalAlloc: 3.0 MB
HeapAlloc: 3.3 MB HeapInuse: 3.6 MB TotalAlloc: 3.3 MB
HeapAlloc: 3.6 MB HeapInuse: 3.8 MB TotalAlloc: 3.6 MB
HeapAlloc: 3.8 MB HeapInuse: 4.1 MB TotalAlloc: 3.8 MB
HeapAlloc: 4.1 MB HeapInuse: 4.3 MB TotalAlloc: 4.1 MB
HeapAlloc: 134 kB HeapInuse: 393 kB TotalAlloc: 4.4 MB
HeapAlloc: 398 kB HeapInuse: 664 kB TotalAlloc: 4.6 MB
HeapAlloc: 660 kB HeapInuse: 926 kB TotalAlloc: 4.9 MB
HeapAlloc: 923 kB HeapInuse: 1.2 MB TotalAlloc: 5.1 MB
HeapAlloc: 1.2 MB HeapInuse: 1.4 MB TotalAlloc: 5.4 MB
HeapAlloc: 1.4 MB HeapInuse: 1.7 MB TotalAlloc: 5.7 MB
HeapAlloc: 1.7 MB HeapInuse: 2.0 MB TotalAlloc: 5.9 MB
HeapAlloc: 2.0 MB HeapInuse: 2.2 MB TotalAlloc: 6.2 MB
HeapAlloc: 2.2 MB HeapInuse: 2.5 MB TotalAlloc: 6.5 MB
HeapAlloc: 2.5 MB HeapInuse: 2.8 MB TotalAlloc: 6.7 MB
HeapAlloc: 2.8 MB HeapInuse: 3.0 MB TotalAlloc: 7.0 MB
HeapAlloc: 3.0 MB HeapInuse: 3.3 MB TotalAlloc: 7.2 MB
HeapAlloc: 3.3 MB HeapInuse: 3.5 MB TotalAlloc: 7.5 MB
HeapAlloc: 3.5 MB HeapInuse: 3.8 MB TotalAlloc: 7.8 MB
HeapAlloc: 3.8 MB HeapInuse: 4.1 MB TotalAlloc: 8.0 MB
HeapAlloc: 4.1 MB HeapInuse: 4.3 MB TotalAlloc: 8.3 MB
HeapAlloc: 136 kB HeapInuse: 401 kB TotalAlloc: 8.6 MB
HeapAlloc: 400 kB HeapInuse: 664 kB TotalAlloc: 8.8 MB
HeapAlloc: 662 kB HeapInuse: 926 kB TotalAlloc: 9.1 MB
HeapAlloc: 924 kB HeapInuse: 1.2 MB TotalAlloc: 9.3 MB
HeapAlloc: 1.2 MB HeapInuse: 1.4 MB TotalAlloc: 9.6 MB
HeapAlloc: 1.4 MB HeapInuse: 1.7 MB TotalAlloc: 9.9 MB
HeapAlloc: 1.7 MB HeapInuse: 2.0 MB TotalAlloc: 10 MB
HeapAlloc: 2.0 MB HeapInuse: 2.2 MB TotalAlloc: 10 MB
HeapAlloc: 2.2 MB HeapInuse: 2.5 MB TotalAlloc: 11 MB
HeapAlloc: 2.5 MB HeapInuse: 2.8 MB TotalAlloc: 11 MB
HeapAlloc: 2.8 MB HeapInuse: 3.0 MB TotalAlloc: 11 MB
HeapAlloc: 3.0 MB HeapInuse: 3.3 MB TotalAlloc: 11 MB
HeapAlloc: 3.3 MB HeapInuse: 3.5 MB TotalAlloc: 12 MB
HeapAlloc: 3.5 MB HeapInuse: 3.8 MB TotalAlloc: 12 MB
HeapAlloc: 3.8 MB HeapInuse: 4.1 MB TotalAlloc: 12 MB
HeapAlloc: 4.1 MB HeapInuse: 4.3 MB TotalAlloc: 12 MB
HeapAlloc: 136 kB HeapInuse: 401 kB TotalAlloc: 13 MB
HeapAlloc: 400 kB HeapInuse: 664 kB TotalAlloc: 13 MB
HeapAlloc: 663 kB HeapInuse: 926 kB TotalAlloc: 13 MB
HeapAlloc: 925 kB HeapInuse: 1.2 MB TotalAlloc: 14 MB
HeapAlloc: 1.2 MB HeapInuse: 1.4 MB TotalAlloc: 14 MB
HeapAlloc: 1.4 MB HeapInuse: 1.7 MB TotalAlloc: 14 MB


问:
Convert nested list to JSON using Python
I'm using the following SQL query to get data for every month in a given year:

```<code>SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')
</code>```

When I'm returning this via Python, I'm getting the following result:

```<code>[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]
</code>```

Also, there are \n everywhere in the result.
I need the result in JSON format, but I can't get it right. How can I do it?

答:
If you simply want to convert this list to a JSON you can do the following:</p>
```<code>import json
dates = [
[
    [
        "April",
        9
    ],
    [
        "August",
        5
    ],
    [
        "February",
        3
    ],
    [
        "July",
        6
    ],
    [
        "June",
        3
    ],
    [
        "March",
        1
    ],
    [
        "May",
        8
    ],
    [
        "November",
        1
    ],
    [
        "October",
        2
    ],
    [
        "September",
        4
    ]
]
]

 dates_json = json.dumps(dates)

 print(type(dates_json)) # prints <class 'str'>
</code>```

Body:
I'm using the following SQL query to get data for every month in a given year:

SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')

When I'm returning this via Python, I'm getting the following result:

[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]

Also, there are \n everywhere in the result.
I need the result in JSON format, but I can't get it right. How can I do it?

Body:
If you simply want to convert this list to a JSON you can do the following:

import json
dates = [
[
    [
        "April",
        9
    ],
    [
        "August",
        5
    ],
    [
        "February",
        3
    ],
    [
        "July",
        6
    ],
    [
        "June",
        3
    ],
    [
        "March",
        1
    ],
    [
        "May",
        8
    ],
    [
        "November",
        1
    ],
    [
        "October",
        2
    ],
    [
        "September",
        4
    ]
]
]

 dates_json = json.dumps(dates)

 print(type(dates_json)) # prints <class 'str'>


问:
Best way to develop asp.net web application with specific user rights
I'm developing a web application wich needs access to a specific directory on one of our servers. When the application is deployed it will run as a specific 'user' (configured in the IIS Application Pool) with access permissions to the given directory.

While developing/debugging the application with Visual Studio 2010's built-in webserver, the application has no permissions to the directory.

What would be the best way to develop/debug this application?

答:
By "built-in webserver" you mean cassini?
If so just deploy the site on the machine's IIS the website project properties.

IIS Express is also an option but I prefer to develop on an environment closest as possible to the one I have in production and IIS is the key service I want to make sure won't give me any deployment problems.

Cheers,
Alex


问:
How can we get the Suspension time of an account using Admin Directory API
I'm trying to get the reports for all the Suspended accounts with a field "SuspensionTime" like the "creationTime". I'm unable to fetch the "SuspensionTime" of an account though the API.

I'm using the following Documentation referred by the Google.
https://developers.google.com/admin-sdk/reports/v1/guides/manage-audit-admin

答:
Apart from the Activities API: https://developers.google.com/admin-sdk/reports/reference/rest/v1/activities/list?apix_params=%7B%22userKey%22%3A%22all%22%2C%22applicationName%22%3A%22admin%22%2C%22eventName%22%3A%22SUSPEND_USER%22%7D

If the suspension comes from Google you can inspect the Users Usage Reports: https://developers.google.com/admin-sdk/reports/v1/appendix/usage/user/accounts

The field disabled_reason usually contains the date of the suspension.


问:
Add integer value from another column to date in postgresql
I want to add the value of another colum (which is an an integer representing miliseconds) to a date value in an update query.
I tried what this answer suggests but I can't find a way to not hardcode the value in the query but instead read it from the other column.

The two relevant fields are:

```<code>ScheduledExecuteDate: DATE(6)
RecurringInterval: INTEGER representing the number of miliseconds to add to the date
</code>```

My query looks something like this:

```<code>UPDATE "Tasks" SET
"ScheduledExecuteDate"="ScheduledExecuteDate" + interval ("RecurringInterval" / 1000) second
WHERE "id" = 62
</code>```

I've also tried 'second'. In both cases it throws an syntax error "at or near second"
Also note that I have to wrap the column names in quotes since they are case sensitive.

I also tried

```<code>"scheduledExecuteDate"=DATE_ADD("scheduledExecuteDate", interval ("Tasks"."recurringInterval" / 1000) seconds)
</code>```

like answered here

答:
You can use make_interval() passing fractional seconds:

```<code>UPDATE "Tasks"
  SET "ScheduledExecuteDate" = "ScheduledExecuteDate"
                               + make_interval(secs => "RecurringInterval"::double precision / 1000) second
WHERE "id" = 62
</code>```

Body:
I want to add the value of another colum (which is an an integer representing miliseconds) to a date value in an update query.
I tried what this answer suggests but I can't find a way to not hardcode the value in the query but instead read it from the other column.

The two relevant fields are:

ScheduledExecuteDate: DATE(6)
RecurringInterval: INTEGER representing the number of miliseconds to add to the date

My query looks something like this:

UPDATE "Tasks" SET
"ScheduledExecuteDate"="ScheduledExecuteDate" + interval ("RecurringInterval" / 1000) second
WHERE "id" = 62

I've also tried 'second'. In both cases it throws an syntax error "at or near second"
Also note that I have to wrap the column names in quotes since they are case sensitive.

I also tried

"scheduledExecuteDate"=DATE_ADD("scheduledExecuteDate", interval ("Tasks"."recurringInterval" / 1000) seconds)

like answered here

Body:
You can use make_interval() passing fractional seconds:

UPDATE "Tasks"
  SET "ScheduledExecuteDate" = "ScheduledExecuteDate"
                               + make_interval(secs => "RecurringInterval"::double precision / 1000) second
WHERE "id" = 62


问:
Python - Expanding a group using selenium
I'm new to python and I'm trying to automate a few tasks.

My issue is when I log in to my server I need to expand the group and select the form inside the group, I'm using find_element By Xpath and ID and keep getting this error "Unable to locate element:", I tried to use sleep or WebDriverWait but didn't work.

My element code in image now (the arrow):

When I open it manual the aria-expanded changed to ="true"

My group code:

Main group

Forms

The website login details (dummy server):
server: https://new2001.surveycto.com/
user: taevion.ezrael@alldrys.com
password: Stackoverflow_example

答:
```<code>driver.get(" https://new2001.surveycto.com/")
time.sleep(5)
driver.find_element(By.ID, "login-username").send_keys("taevion.ezrael@alldrys.com")
driver.find_element(By.XPATH, "//button[text()='Next']").click()
time.sleep(1)
driver.find_element(By.ID, "login-password").send_keys("Stackoverflow_example")
time.sleep(1)
driver.find_element(By.XPATH, "//button[text()='Log in']").click()
time.sleep(10)
ActionChains(driver).move_to_element(driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]")).perform()
time.sleep(1)
driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]//button[@data-original-title='Add form, group or dataset']").click()
time.sleep(1)
driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]//div[@class='primary-actions']//a[contains(@data-original-title, 'start from scratch')]").click()
time.sleep(5)
x = driver.find_element(By.XPATH, "//form[@method='post']//h3").text
print(x)
driver.save_screenshot('snapshot.png')
driver.quit()
</code>```

This code logs in to the website with the credentials and then clicks on the + icon of the Foundation form, and after the expansion occurs, it clicks on the Start New Form button, and just to verify for you, it takes the snapshot of the screen and extracts the form header.

Output:

```<code>Start new form - Step 1

Process finished with exit code 0
</code>```

Form Snapshot

Body:
driver.get(" https://new2001.surveycto.com/")
time.sleep(5)
driver.find_element(By.ID, "login-username").send_keys("taevion.ezrael@alldrys.com")
driver.find_element(By.XPATH, "//button[text()='Next']").click()
time.sleep(1)
driver.find_element(By.ID, "login-password").send_keys("Stackoverflow_example")
time.sleep(1)
driver.find_element(By.XPATH, "//button[text()='Log in']").click()
time.sleep(10)
ActionChains(driver).move_to_element(driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]")).perform()
time.sleep(1)
driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]//button[@data-original-title='Add form, group or dataset']").click()
time.sleep(1)
driver.find_element(By.XPATH, "(//*[@data-form-field-id='foundation'])[1]//div[@class='primary-actions']//a[contains(@data-original-title, 'start from scratch')]").click()
time.sleep(5)
x = driver.find_element(By.XPATH, "//form[@method='post']//h3").text
print(x)
driver.save_screenshot('snapshot.png')
driver.quit()

This code logs in to the website with the credentials and then clicks on the + icon of the Foundation form, and after the expansion occurs, it clicks on the Start New Form button, and just to verify for you, it takes the snapshot of the screen and extracts the form header.

Output:

Start new form - Step 1

Process finished with exit code 0

Form Snapshot


问:
How can I use UserDefaults in Swift?
How can I use UserDefaults to save/retrieve strings, booleans and other data in Swift?</p>

答: use UserDefault to store any settings value you want your application to remember between start ups, maybe you want to know ifs its been started before, maybe you want some values the user has set to be remembers so they don't have to be set very time, on Mac windows frames are stored in there for you, maybe you want to control the behaviour of the app, but you don't want it available to end users, you just want to choose just before your release. Be careful what you store in UserDefaults, it's not protected.</p>

Title: How can I use UserDefaults in Swift?


问:
Use input parameter within lambda schedule in Cloudformation
I'm trying to enable/disable lambda scheduled event based on environment, and not having much luck. If the env is prod, it should enable the schedule, and if it's dev it should disable it. However, the schedule status doesn't obey the condition. It's currently enabled in dev, but the template doesn't disable it. If I set the Enabled property to false manually, the schedule status does change to disable. So not sure where I'm going wrong (or if what I'm trying to do is possible). Any help is greatly appreciated!

```<code>Parameters:
  env:
    Type: String

Conditions:
  isProd:
    !Equals [!Ref env, prod]

Resources:
  func:
    Type: AWS::Serverless::Function
    Properties:
      Events:
        ScheduledEvent:
          Type: Schedule
          Properties:
            Schedule: rate(5 minutes)
            Enabled: !If [isProd, true, false]
</code>```

答:
Okay, so after a bit more searching, it looks like setting the Enabled property with conditional statements doesn't work so nice. The workaround I've put in place is to use conditional statements in the Schedule property.

```<code>ScheduledEvent:
  Type: Schedule
  Properties:
    Schedule: !If [isProd, "rate(5 minutes)", "cron(00 00 01 01 ? 1970)"]
</code>```

Thanks to these posts for point me in the right direction:

Conditionally enabling an event schedule in AWS sam template file

Dynamically change event properties on aws cloudformation templates

Body:
I'm trying to enable/disable lambda scheduled event based on environment, and not having much luck. If the env is prod, it should enable the schedule, and if it's dev it should disable it. However, the schedule status doesn't obey the condition. It's currently enabled in dev, but the template doesn't disable it. If I set the Enabled property to false manually, the schedule status does change to disable. So not sure where I'm going wrong (or if what I'm trying to do is possible). Any help is greatly appreciated!

Parameters:
  env:
    Type: String

Conditions:
  isProd:
    !Equals [!Ref env, prod]

Resources:
  func:
    Type: AWS::Serverless::Function
    Properties:
      Events:
        ScheduledEvent:
          Type: Schedule
          Properties:
            Schedule: rate(5 minutes)
            Enabled: !If [isProd, true, false]

Body:
Okay, so after a bit more searching, it looks like setting the Enabled property with conditional statements doesn't work so nice. The workaround I've put in place is to use conditional statements in the Schedule property.

ScheduledEvent:
  Type: Schedule
  Properties:
    Schedule: !If [isProd, "rate(5 minutes)", "cron(00 00 01 01 ? 1970)"]

Thanks to these posts for point me in the right direction:

Conditionally enabling an event schedule in AWS sam template file

Dynamically change event properties on aws cloudformation templates


问:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource

Possible Duplicate:

  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.

The code basically prints messages from a db
Here is the code:

```<code>$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some <a   href=\"/social/suggestions\">suggestions</a>";
}
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages
</code>```

$username is got further up the file.

Here is the error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34

Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.

One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)

Any idea??

Have I done the mysql_fetch_array wrong when getting $row??
thanks

答:
```<code>$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
</code>```

This will create the following query:

```<code>SELECT * FROM messages WHERE `sender` IN (Array)
</code>```

This is obviously not a valid MySQL query. You have to process the array.

```<code>$sqlx = "SELECT * FROM `messages` WHERE `sender` IN ("; // start of query

foreach($row as $r)
    $sqlx .= "'".$r['username']."',"; // insert all returned usernames

$sqlx = substr($sqlx,0,-1).')'; // substract the last comma and close the query
</code>```

Or, as RiaD pointed out in the comments:

```<code>$sqlx = "SELECT * FROM `messages` WHERE `sender` IN (".
        implode(',',array_map(function($x){return "'".$x['username']."'"; }, $row)).
        ")";
</code>```

PS: Riad, it should be $x['username'] instead of $x and you forgot the semicolon ;)

Body:
Possible Duplicate:

  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.

The code basically prints messages from a db
Here is the code:

$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some suggestions";
}
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages

$username is got further up the file.

Here is the error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34

Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.

One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)

Any idea??

Have I done the mysql_fetch_array wrong when getting $row??
thanks

Body:
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";

This will create the following query:

SELECT * FROM messages WHERE `sender` IN (Array)

This is obviously not a valid MySQL query. You have to process the array.

$sqlx = "SELECT * FROM `messages` WHERE `sender` IN ("; // start of query

foreach($row as $r)
    $sqlx .= "'".$r['username']."',"; // insert all returned usernames

$sqlx = substr($sqlx,0,-1).')'; // substract the last comma and close the query

Or, as RiaD pointed out in the comments:

$sqlx = "SELECT * FROM `messages` WHERE `sender` IN (".
        implode(',',array_map(function($x){return "'".$x['username']."'"; }, $row)).
        ")";

PS: Riad, it should be $x['username'] instead of $x and you forgot the semicolon ;)


问:
Flutter: unable to install "Runner" error when trying to install flutter app to real iOS device
I am using iPhone 8 (Version 13.3.1), and a MacBook air (Version 10.14.6). I have set 'team' to personal team in Xcode > general. Then I click the button on the top left corner to run it.
I received error like this even I have deleted the apps that I have installed before on the same phone with the sample apple id: </p>

```<code>Details

Unable to install "Runner"
Domain: com.apple.dtdevicekit
Code: -402620383
--
App installation failed
Domain: com.apple.dtdevicekit
Code: -402620383
Failure Reason: The maximum number of apps for free development profiles has been reached.
User Info: {
    DVTRadarComponentKey = 487927;
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x00000001263006e7 DTDKCreateNSError + 109
    1   DTDeviceKitBase                     0x0000000126300de9 DTDK_AMDErrorToNSError + 792
    2   DTDeviceKitBase                     0x000000012634056a __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 164
    3   DVTFoundation                       0x000000010ba8dc12 DVTInvokeWithStrongOwnership + 73
    4   DTDeviceKitBase                     0x0000000126340301 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1589
    5   IDEiOSSupportCore                   0x00000001261c8a25 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4523
    6   DVTFoundation                       0x000000010bbbee7a __DVT_CALLING_CLIENT_BLOCK__ + 7
    7   DVTFoundation                       0x000000010bbc0552 __DVTDispatchAsync_block_invoke + 809
    8   libdispatch.dylib                   0x00007fff6734f5f8 _dispatch_call_block_and_release + 12
    9   libdispatch.dylib                   0x00007fff6735063d _dispatch_client_callout + 8
    10  libdispatch.dylib                   0x00007fff673568e0 _dispatch_lane_serial_drain + 602
    11  libdispatch.dylib                   0x00007fff67357396 _dispatch_lane_invoke + 385
    12  libdispatch.dylib                   0x00007fff6735f6ed _dispatch_workloop_worker_thread + 598
    13  libsystem_pthread.dylib             0x00007fff67590611 _pthread_wqthread + 421
    14  libsystem_pthread.dylib             0x00007fff675903fd start_wqthread + 13
);
}
--

</code>```

答: I simply changed the build number, it worked just fine.</p>

Body:
I am using iPhone 8 (Version 13.3.1), and a MacBook air (Version 10.14.6). I have set 'team' to personal team in Xcode > general. Then I click the button on the top left corner to run it.
I received error like this even I have deleted the apps that I have installed before on the same phone with the sample apple id:

Details

Unable to install "Runner"
Domain: com.apple.dtdevicekit
Code: -402620383
--
App installation failed
Domain: com.apple.dtdevicekit
Code: -402620383
Failure Reason: The maximum number of apps for free development profiles has been reached.
User Info: {
    DVTRadarComponentKey = 487927;
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x00000001263006e7 DTDKCreateNSError + 109
    1   DTDeviceKitBase                     0x0000000126300de9 DTDK_AMDErrorToNSError + 792
    2   DTDeviceKitBase                     0x000000012634056a __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 164
    3   DVTFoundation                       0x000000010ba8dc12 DVTInvokeWithStrongOwnership + 73
    4   DTDeviceKitBase                     0x0000000126340301 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1589
    5   IDEiOSSupportCore                   0x00000001261c8a25 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4523
    6   DVTFoundation                       0x000000010bbbee7a __DVT_CALLING_CLIENT_BLOCK__ + 7
    7   DVTFoundation                       0x000000010bbc0552 __DVTDispatchAsync_block_invoke + 809
    8   libdispatch.dylib                   0x00007fff6734f5f8 _dispatch_call_block_and_release + 12
    9   libdispatch.dylib                   0x00007fff6735063d _dispatch_client_callout + 8
    10  libdispatch.dylib                   0x00007fff673568e0 _dispatch_lane_serial_drain + 602
    11  libdispatch.dylib                   0x00007fff67357396 _dispatch_lane_invoke + 385
    12  libdispatch.dylib                   0x00007fff6735f6ed _dispatch_workloop_worker_thread + 598
    13  libsystem_pthread.dylib             0x00007fff67590611 _pthread_wqthread + 421
    14  libsystem_pthread.dylib             0x00007fff675903fd start_wqthread + 13
);
}
--


问:
Google App Script Web app conflict when recording data on spreadsheet
I am building a user interface thanks to a GAS web app.
This script is connected to a spreadsheet to read and record data.
I am able to record data from the user entry to the spreadsheet thanks to my current code but my concern is about the reliability of this app when multiple users will be connected to this app and will try to record data.
In order to test the tool, I have created a 10 iterations loop on client side which send pre formatted data to the server side for recording into the spreadsheet.
When I launch the function on one computer it works (10 lines are properly recorded) but when a second user activate the same function on its session the total number of lines recorded is random  (15 or 17 instead of 20).
When having a look to the spreadsheet when scriptS are running, I see that sometimes values on a line is overwritten by an other value (just like if the new row was not recorded at the proper place).
The Web app is share as execute as me (so the server side code is executed with my account)
In order to control what s going on, a lockservice has been implemented on the server side script (the part which records the data on the spreadsheet) and a new promise / async function on the client side.</p>
```<code>function recordDataOnSheet(data){ // server side function to record data in the spreadsheet

  var lock='';
  lock = LockService.getScriptLock();
  var success = lock.tryLock(10000);//Throws exception if fail wait 10s  max to get a lock

  if (success){
    var dat =dataSheet.getDataRange().getValues();
    lsRow++;
    data[0].length);
    dat.push(data);
    dataSheet.getRange(1, 1, dat.length, dat[0].length).setValues(dat);
    Logger.log(dat.length);

  } else {Logger.log("Lock failed")};
lock.releaseLock();
} ```

and client side piece of script:

</code>```
```<code> function runGoogleSript(serverFunc,dat){ // function to mange the asynchronous call of a server sdide function

    return new Promise((resolve, reject) => {
    google.script.run.withSuccessHandler(data => {
    resolve(data)
    }).withFailureHandler(er => {
    reject(er)
    })[serverFunc](dat)
    });
  }

async function test (){

  for (i=0;i<10;i++){
  let d = new Date();
  setTimeout(() => { console.log(i) }, 2000);

  try {
    const data = await runGoogleSript("recordDataOnSheet",["06323","XX:",user.id,"2022-02-07", d.getMinutes() , d.getSeconds() ] );
  }
  catch (er) {alert(er);}
  }
  }
</code>```

答:
After dozen of test and tests, I have discovered that it was only an issue with the spreadsheet call.
As I am calling the same file/sheet in a loop sometimes the previous activity (to update the data in the sheet) were not over. This was at the origin of the issue.
I have simply added a SpreadsheetApp.flush(); at the end of my function recordDataOnSheet and it works and it is reliable

Body:
I am building a user interface thanks to a GAS web app.
This script is connected to a spreadsheet to read and record data.
I am able to record data from the user entry to the spreadsheet thanks to my current code but my concern is about the reliability of this app when multiple users will be connected to this app and will try to record data.
In order to test the tool, I have created a 10 iterations loop on client side which send pre formatted data to the server side for recording into the spreadsheet.
When I launch the function on one computer it works (10 lines are properly recorded) but when a second user activate the same function on its session the total number of lines recorded is random  (15 or 17 instead of 20).
When having a look to the spreadsheet when scriptS are running, I see that sometimes values on a line is overwritten by an other value (just like if the new row was not recorded at the proper place).
The Web app is share as execute as me (so the server side code is executed with my account)
In order to control what s going on, a lockservice has been implemented on the server side script (the part which records the data on the spreadsheet) and a new promise / async function on the client side.

function recordDataOnSheet(data){ // server side function to record data in the spreadsheet

  var lock='';
  lock = LockService.getScriptLock();
  var success = lock.tryLock(10000);//Throws exception if fail wait 10s  max to get a lock

  if (success){
    var dat =dataSheet.getDataRange().getValues();
    lsRow++;
    data[0].length);
    dat.push(data);
    dataSheet.getRange(1, 1, dat.length, dat[0].length).setValues(dat);
    Logger.log(dat.length);

  } else {Logger.log("Lock failed")};
lock.releaseLock();
} ```

and client side piece of script:

 function runGoogleSript(serverFunc,dat){ // function to mange the asynchronous call of a server sdide function

    return new Promise((resolve, reject) => {
    google.script.run.withSuccessHandler(data => {
    resolve(data)
    }).withFailureHandler(er => {
    reject(er)
    })[serverFunc](dat)
    });
  }

async function test (){

  for (i=0;i<10;i++){
  let d = new Date();
  setTimeout(() => { console.log(i) }, 2000);

  try {
    const data = await runGoogleSript("recordDataOnSheet",["06323","XX:",user.id,"2022-02-07", d.getMinutes() , d.getSeconds() ] );
  }
  catch (er) {alert(er);}
  }
  }


问:
Mapping interval using map function in python
Given a sequence of numbers, first convert to interval and convert to dictionary as per sequence of number and then after that map it with a column in DataFrame as shown in DataFrame below.

Query-1 how to create interval from above sequence into dictionary

```<code>given_sequence = [-100, 2, 5, 8, 10, 15]# Given sequence

idict = {-100: '<2',
2:'2-5',
5:'5-8',
8:'8-10',
10:'10-15',
15:'>15'}
</code>```

Query-2 how to map to a column as shown in below screen shot with dictionary and map function

```<code>import pandas as pd
import random
# create an Empty DataFrame object
df = pd.DataFrame()
df['col1'] = [random.randint(1, 10) for i in range(0, 10)]
df['mapped']  = df['col1'].map(idict)
</code>```

** Expected Output**

答:
If values in dictionary are sorted like in sample data add bins and labels parameters from dictionary keys and values in cut:

```<code>#if necessary sorting dict by keys
#idict = {k: v for k, v in sorted(idict.items(), key=lambda item: item[0])}

df['mapped'] = pd.cut(df['col1'],
                      right=False,
                      bins=[*list(idict.keys()), np.inf],
                      labels=list(idict.values()))
</code>```

Body:
Given a sequence of numbers, first convert to interval and convert to dictionary as per sequence of number and then after that map it with a column in DataFrame as shown in DataFrame below.

Query-1 how to create interval from above sequence into dictionary

given_sequence = [-100, 2, 5, 8, 10, 15]# Given sequence

idict = {-100: '<2',
2:'2-5',
5:'5-8',
8:'8-10',
10:'10-15',
15:'>15'}

Query-2 how to map to a column as shown in below screen shot with dictionary and map function

import pandas as pd
import random
# create an Empty DataFrame object
df = pd.DataFrame()
df['col1'] = [random.randint(1, 10) for i in range(0, 10)]
df['mapped']  = df['col1'].map(idict)

** Expected Output**

Body:
If values in dictionary are sorted like in sample data add bins and labels parameters from dictionary keys and values in cut:

#if necessary sorting dict by keys
#idict = {k: v for k, v in sorted(idict.items(), key=lambda item: item[0])}

df['mapped'] = pd.cut(df['col1'],
                      right=False,
                      bins=[*list(idict.keys()), np.inf],
                      labels=list(idict.values()))


问:
selecting second string point using js substring
i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?

example

```<code>var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))
</code>```

from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'

how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?

thanks in advance!

答:
use string.split.

e.g.

```<code>name.split(".")[1]
</code>```

Body:
i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?

example

var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))

from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'

how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?

thanks in advance!

Body:
use string.split.

e.g.

name.split(".")[1]


问:
Shift+F10 Function in VB.Net
Please help me figure out for Shift+F10 in VB.NET, Escape and F1 work but Shift+F10 doesn’t work.

Here’s my code:

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Select Case keyData
            Case Keys.Escape
                Me.Dispose()
            Case Keys.F1
                MsgBox("You have pressed F1")
            Case Keys.ShiftKey = Keys.F10
                MsgBox("You have pressed Shift+F10")
            Case Else
                Return MyBase.ProcessCmdKey(msg, keyData)
        End Select

        Return True
End Function
```

答:
You can use

Case Keys.F10 + Keys.Shift
    MsgBox("You have pressed Shift+F10")
```

Result:

Title: Shift+F10 Function in VB.Net

Body:
You can use

Case Keys.F10 + Keys.Shift
    MsgBox("You have pressed Shift+F10")

Result:


问:
Get file from GCS and load to bigquery based on file name pattern
We have requirement of loading file from gcs bucket to different bigquery table based on file name pattern.
eg

```<code>bucket/folder/test_a_20221023.csv  -> should go to table a
bucket/folder/file_a_20221023_2.csv  -> should go to table a
bucket/folder/control_b_20221023.csv  -> should go to table b
bucket/folder/test_b_20221023_2.csv  -> should go to table b
</code>```

So prefix can be anything before a or b pattern in the filename and based on a or b we have to load to specific table in bigquery. Is there any way to get the file in gcs based on some pattern other than gsutil command

```<code>gsutil ls gs://[BUCKET_NAME]/** | grep string
</code>```

答:
An approach you can consider is by using a Python script. Basically, the logic would be to:

List the objects in your bucket or folder and sort it according to their category or group.

Create a loop and use the load_table_from_uri function to load data according to the lists created from step 1.

Here is a sample code based on your use case:

```<code>from google.cloud import storage
from google.cloud import bigquery
import re

def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name, prefix=prefix, delimiter=delimiter)

    a_list = []
    b_list = []
    for blob in blobs:
        is_a = re.search("\w+\/\w+_a_\d+\_?\d+?.csv", blob.name)
        is_b = re.search("\w+\/\w+_b_\d+\_?\d+?.csv", blob.name)
        if is_a:
            a_list.append(f'gs://{bucket_name}/{blob.name}')
        elif is_b:
            b_list.append(f'gs://{bucket_name}/{blob.name}')

    return a_list,b_list

def load_to_bq():
    bucket_name="your-bucket"
    prefix="folder/"

    table_a = "PROJECT_ID.dataset.gcs_csv_a"
    table_b = "PROJECT_ID.dataset.gcs_csv_b"

    a_list,b_list = list_blobs_with_prefix(bucket_name, prefix,delimiter="/")

    client = bigquery.Client()

    job_config = bigquery.LoadJobConfig(
        autodetect=True,
        skip_leading_rows=1,
    # The source format defaults to CSV, so the line below is optional.
        source_format=bigquery.SourceFormat.CSV,
    )

    for csv_file_a in a_list:
        load_job = client.load_table_from_uri(
                csv_file_a, table_a, job_config=job_config
                )
        load_job.result()

    for csv_file_b in b_list:
        load_job = client.load_table_from_uri(
                csv_file_b, table_b, job_config=job_config
                )
        load_job.result()

load_to_bq()

</code>```
```<code>Folder structure: gs://bucket_name/folder/control_b_20221023.csv
</code>```

Body:
We have requirement of loading file from gcs bucket to different bigquery table based on file name pattern.
eg

bucket/folder/test_a_20221023.csv  -> should go to table a
bucket/folder/file_a_20221023_2.csv  -> should go to table a
bucket/folder/control_b_20221023.csv  -> should go to table b
bucket/folder/test_b_20221023_2.csv  -> should go to table b

So prefix can be anything before a or b pattern in the filename and based on a or b we have to load to specific table in bigquery. Is there any way to get the file in gcs based on some pattern other than gsutil command

gsutil ls gs://[BUCKET_NAME]/** | grep string

Body:
An approach you can consider is by using a Python script. Basically, the logic would be to:

List the objects in your bucket or folder and sort it according to their category or group.

Create a loop and use the load_table_from_uri function to load data according to the lists created from step 1.

Here is a sample code based on your use case:

from google.cloud import storage
from google.cloud import bigquery
import re

def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name, prefix=prefix, delimiter=delimiter)

    a_list = []
    b_list = []
    for blob in blobs:
        is_a = re.search("\w+\/\w+_a_\d+\_?\d+?.csv", blob.name)
        is_b = re.search("\w+\/\w+_b_\d+\_?\d+?.csv", blob.name)
        if is_a:
            a_list.append(f'gs://{bucket_name}/{blob.name}')
        elif is_b:
            b_list.append(f'gs://{bucket_name}/{blob.name}')

    return a_list,b_list

def load_to_bq():
    bucket_name="your-bucket"
    prefix="folder/"

    table_a = "PROJECT_ID.dataset.gcs_csv_a"
    table_b = "PROJECT_ID.dataset.gcs_csv_b"

    a_list,b_list = list_blobs_with_prefix(bucket_name, prefix,delimiter="/")

    client = bigquery.Client()

    job_config = bigquery.LoadJobConfig(
        autodetect=True,
        skip_leading_rows=1,
    # The source format defaults to CSV, so the line below is optional.
        source_format=bigquery.SourceFormat.CSV,
    )

    for csv_file_a in a_list:
        load_job = client.load_table_from_uri(
                csv_file_a, table_a, job_config=job_config
                )
        load_job.result()

    for csv_file_b in b_list:
        load_job = client.load_table_from_uri(
                csv_file_b, table_b, job_config=job_config
                )
        load_job.result()

load_to_bq()

Folder structure: gs://bucket_name/folder/control_b_20221023.csv


问:
TikTok Login Kit: Status=Temporary Redirect, StatusCode=307
I am trying to implement the new TikTok Login Kit for Web and am stuck on the getting the access token.
Here's this specific step described in TikTok's doc.
https://developers.tiktok.com/doc/manage-user-access-tokens

I have registered the app.

I am able to reach the OAuth login screens.

I'm also able auth. and get a response from the auth. endpoint with an authorization code.

But when fetching the access token using the said authorization code my POST request comes back to my redirect URL with a "Status=Temporary Redirect, StatusCode=307" in the response.

I assume 307 means there's something missing on the tiktok server, but their support isn't very responsive unfortunately.
Perhaps someone in the community has dealt with this before?

I'm sending my POST request with the following parameters.

```<code>URL: https://open-api.tiktok.com/oauth/access_token
?code=atGaIopCm2M9L2vfad0l4IJzzX8qFfg7aButDrjqerJqs5rhIqmWZLLGk1YRJZUZ6-mGBaYxX_asSdw1TNe7NHhvysS99Yz5o4MtkNv2-nA*1
&client_key= <client key in plain text>
&client_secret=<secret in plain text>
&grant_type=authorization_code
</code>```

Any ideas what could that 307 Error be hinting at in general?

答:
Add -L in your curl command to enable redirections automatically

```<code>curl -X -L POST  -H 'Content-Type:application/json' --data '{"secret": "xxx","app_id":"xxx","auth_code":"xxx" }' "https://business-api.tiktok.com/open_api/v1.2/oauth2/access_token/"
</code>```

See the document here:
https://ads.tiktok.com/marketing_api/docs?id=1709207085043713

Body:
I am trying to implement the new TikTok Login Kit for Web and am stuck on the getting the access token.
Here's this specific step described in TikTok's doc.
https://developers.tiktok.com/doc/manage-user-access-tokens

I have registered the app.

I am able to reach the OAuth login screens.

I'm also able auth. and get a response from the auth. endpoint with an authorization code.

But when fetching the access token using the said authorization code my POST request comes back to my redirect URL with a "Status=Temporary Redirect, StatusCode=307" in the response.

I assume 307 means there's something missing on the tiktok server, but their support isn't very responsive unfortunately.
Perhaps someone in the community has dealt with this before?

I'm sending my POST request with the following parameters.

URL: https://open-api.tiktok.com/oauth/access_token
?code=atGaIopCm2M9L2vfad0l4IJzzX8qFfg7aButDrjqerJqs5rhIqmWZLLGk1YRJZUZ6-mGBaYxX_asSdw1TNe7NHhvysS99Yz5o4MtkNv2-nA*1
&client_key= <client key in plain text>
&client_secret=<secret in plain text>
&grant_type=authorization_code

Any ideas what could that 307 Error be hinting at in general?

Body:
Add -L in your curl command to enable redirections automatically

curl -X -L POST  -H 'Content-Type:application/json' --data '{"secret": "xxx","app_id":"xxx","auth_code":"xxx" }' "https://business-api.tiktok.com/open_api/v1.2/oauth2/access_token/"

See the document here:
https://ads.tiktok.com/marketing_api/docs?id=1709207085043713


问:
S3 to Pandas with local variable authentication
I'm downloading a file (to be precise a parquet set of files) from S3 and converting that to a Pandas DataFrame. I'm doing that with the Pandas function read_parquet and s3fs, as described here:

```<code>df = pd.read_parquet(f's3://{bucket}/{path}')
</code>```

However, I could only do that so far if I authenticate via environment variable or AWS config file. Because of company standards I would like instead to authenticate via local variables, such as the way we do with pyarrow.parquet:

```<code>fs = s3fs.S3FileSystem(key=config.AWS_ACCESS_KEY_ID, secret=config.AWS_SECRET_ACCESS_KEY)
df = pq.ParquetDataset(f's3://{bucket}/{path}', filesystem=fs).read().to_pandas()
</code>```

Is there a way to do that with read_parquet? Can't I use something like a filesystem argument with it?

In case anyone is curious, I'm not using pq.ParquetDataset because it is too slow (I have no idea why).

答:
I think you can pass a file-like object to pandas.read_parquet:

```<code>with fs.open(f's3://{bucket}/{path}') as fp:
  pq.read_parquet(fp)
</code>```

Body:
I'm downloading a file (to be precise a parquet set of files) from S3 and converting that to a Pandas DataFrame. I'm doing that with the Pandas function read_parquet and s3fs, as described here:

df = pd.read_parquet(f's3://{bucket}/{path}')

However, I could only do that so far if I authenticate via environment variable or AWS config file. Because of company standards I would like instead to authenticate via local variables, such as the way we do with pyarrow.parquet:

fs = s3fs.S3FileSystem(key=config.AWS_ACCESS_KEY_ID, secret=config.AWS_SECRET_ACCESS_KEY)
df = pq.ParquetDataset(f's3://{bucket}/{path}', filesystem=fs).read().to_pandas()

Is there a way to do that with read_parquet? Can't I use something like a filesystem argument with it?

In case anyone is curious, I'm not using pq.ParquetDataset because it is too slow (I have no idea why).

Body:
I think you can pass a file-like object to pandas.read_parquet:

with fs.open(f's3://{bucket}/{path}') as fp:
  pq.read_parquet(fp)