问:
Restart Docker container during build process
I need to restart the Docker container during the build process due dotnetfx. Dockerfile:

```<code>FROM mcr.microsoft.com/windows/servercore:ltsc2019

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Install Chocolatey
RUN Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Universal Windows Platform build tools workload for Visual Studio 2019 Build Tools (https://chocolatey.org/packages/visualstudio2019-workload-universalbuildtools#dependencies)
RUN choco install visualstudio2019-workload-universalbuildtools --package-parameters "--includeOptional" --confirm
</code>```

But I'm facing this error:

```<code>Packages requiring reboot:
 - dotnetfx (exit code 3010) # <--- it means a reboot is needed!
</code>```

I tried to run both commands in the same RUN and adding Restart-Computer between them (separte by \) and executing a RUN command after each installation command either but when I do it looks like Docker output get lost.

Can I restart the current container during the build process without make Docker get lost and keep the installation process?

UPDATE 1

Tried to install this dotnetfx before run the last command but I get the same error.

```<code># Microsoft .NET Framework (https://chocolatey.org/packages/dotnetfx)
RUN choco install dotnetfx --confirm
</code>```

Error:

```<code>Packages requiring reboot:
 - dotnetfx (exit code 3010)
</code>```

UPDATE 2 (WORKAROUND)

I've manage to workaround this problem using a base image with .NET already installed:

```<code>FROM mcr.microsoft.com/dotnet/framework/sdk:4.8
</code>```

答:
one way to solve this issue is to use multi-stage build. In the first stage, you can install the binary and in the second one, you copy the binary and build the docker image.

Here is how you can do this: https://docs.docker.com/develop/develop-images/multistage-build/

example

```<code>FROM mcr.microsoft.com/windows/servercore:ltsc2019 as baseimage

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Install Chocolatey
RUN Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Universal Windows Platform build tools workload for Visual Studio 2019 Build Tools (https://chocolatey.org/packages/visualstudio2019-workload-universalbuildtools#dependencies)
FROM baseimage
RUN choco install visualstudio2019-workload-universalbuildtools --package-parameters "--includeOptional" --confirm
</code>```

Body:
I need to restart the Docker container during the build process due dotnetfx. Dockerfile:

FROM mcr.microsoft.com/windows/servercore:ltsc2019

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Install Chocolatey
RUN Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Universal Windows Platform build tools workload for Visual Studio 2019 Build Tools (https://chocolatey.org/packages/visualstudio2019-workload-universalbuildtools#dependencies)
RUN choco install visualstudio2019-workload-universalbuildtools --package-parameters "--includeOptional" --confirm

But I'm facing this error:

Packages requiring reboot:
 - dotnetfx (exit code 3010) # <--- it means a reboot is needed!

I tried to run both commands in the same RUN and adding Restart-Computer between them (separte by \) and executing a RUN command after each installation command either but when I do it looks like Docker output get lost.

Can I restart the current container during the build process without make Docker get lost and keep the installation process?

UPDATE 1

Tried to install this dotnetfx before run the last command but I get the same error.

# Microsoft .NET Framework (https://chocolatey.org/packages/dotnetfx)
RUN choco install dotnetfx --confirm

Error:

Packages requiring reboot:
 - dotnetfx (exit code 3010)

UPDATE 2 (WORKAROUND)

I've manage to workaround this problem using a base image with .NET already installed:

FROM mcr.microsoft.com/dotnet/framework/sdk:4.8

Body:
one way to solve this issue is to use multi-stage build. In the first stage, you can install the binary and in the second one, you copy the binary and build the docker image.

Here is how you can do this: https://docs.docker.com/develop/develop-images/multistage-build/

example

FROM mcr.microsoft.com/windows/servercore:ltsc2019 as baseimage

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Install Chocolatey
RUN Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Universal Windows Platform build tools workload for Visual Studio 2019 Build Tools (https://chocolatey.org/packages/visualstudio2019-workload-universalbuildtools#dependencies)
FROM baseimage
RUN choco install visualstudio2019-workload-universalbuildtools --package-parameters "--includeOptional" --confirm


来源: stackexchange

问:
Where to find a list of all jQuery events?
I really did try Google and jQuery documentation for this and I give up.

I need event names. No - I don't need to load them with code, I need them as HTML page, you know, to read and check what was the exact name of this event I've just forgotten. I'm sure there are hidden somwhere around the web laughing at me :)

It's pointless for me (or anyone) to ask here, "hey, how to attach a code when jQuery.ajax starts". I know, jQuery .ajax() triggers some global and local events, I know, if I'll waste another 15 minutes for reading whole .ajax() documentation I'll find it, but it's not my point. If you forget rarely used HTML tag name or syntax you just type "HTML tags" in google and find your tag in less than 10 seconds. Try it with jQuery event names :) "Window events" returns quite good documetation by Microsoft.

I'd rather waste my time for really good question: where to find a list of all jQuery events? It would be cool if they had some sort of description, but the most important are names.

I don't need any particular one of them. I need all of them in one place.

It's braindead easy when it comes to "class methods and properties". I know the code can define any number of custom events, but first: DOMDocument defines its defaults, JavaScript window defines its own and jQuery itself defines its own. Is there a list?

答: Check out my jQuery cheat sheet at http://learningcsharpnet.blogspot.com/2011/05/and-now-for-something-completely.html </p>

ContentLicense: CC BY-SA 3.0


问:
Weird artifacts on Safari when using -webkit-background-clip, -webkit-text-fill-color and gradient
So, I have this title text here:

And as you can see, there's a weird line above the text with gradient.
The CSS for that text is the following:

```<code>color: #fff;
background: -webkit-linear-gradient(180deg, #8dc9fb 0, #fff 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
</code>```

I'm using MacOS Sierra and Safari 10.1. I've tried many thing but nothing seems to fix it. Any ideas?

Edit: Another image to show it really is part of the text:

答:
Nothing suggested here worked for me, unfortunately. However, I was also lucky enough to have my gradient text over a solid color that I would know in advance - so I used a mask using the "::after" pseudo-selector to hide the line:

```<code>&::after {
    position: absolute;
    content: "";
    top: 0;
    right: 0;
    width: 1px;
    height: 100%;
    background-color: black;
}
</code>```

Hope this helps others!

Body:
So, I have this title text here:

And as you can see, there's a weird line above the text with gradient.
The CSS for that text is the following:

color: #fff;
background: -webkit-linear-gradient(180deg, #8dc9fb 0, #fff 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;

I'm using MacOS Sierra and Safari 10.1. I've tried many thing but nothing seems to fix it. Any ideas?

Edit: Another image to show it really is part of the text:

Body:
Nothing suggested here worked for me, unfortunately. However, I was also lucky enough to have my gradient text over a solid color that I would know in advance - so I used a mask using the "::after" pseudo-selector to hide the line:

&::after {
    position: absolute;
    content: "";
    top: 0;
    right: 0;
    width: 1px;
    height: 100%;
    background-color: black;
}

Hope this helps others!

ContentLicense: CC BY-SA 4.0


问:
How can I make a new column by adding two columns with a priority given to one of them?
I have the following dataframe and I want to get C as shown. Checking if there is a value for A then it would appear in C. If there is no value in A, then C will take B value.

```<code>data <-
structure(list(A = c(15L, 20L, NA, 8L), B = c(7L, NA, 9L, 6L),
    C = c(15L, 20L, 9L, 8L)), class = "data.frame", row.names = c(NA,
-4L))
</code>```

I tried something like:

```<code>data$C <- coalesce(data$A, data$B)
</code>```

答:
Here is a base R solution using ifelse

```<code>data$C <- with(data,ifelse(is.na(A),B,A))
</code>```

or which + aggregate

```<code>data$C <- data[as.matrix(aggregate(col~row,which(!is.na(data),arr.ind = TRUE),FUN = min))]
</code>```

Body:
I have the following dataframe and I want to get C as shown. Checking if there is a value for A then it would appear in C. If there is no value in A, then C will take B value.

data <-
structure(list(A = c(15L, 20L, NA, 8L), B = c(7L, NA, 9L, 6L),
    C = c(15L, 20L, 9L, 8L)), class = "data.frame", row.names = c(NA,
-4L))

I tried something like:

data$C <- coalesce(data$A, data$B)

Body:
Here is a base R solution using ifelse

data$C <- with(data,ifelse(is.na(A),B,A))

or which + aggregate

data$C <- data[as.matrix(aggregate(col~row,which(!is.na(data),arr.ind = TRUE),FUN = min))]


问:
Filter out objects in array if one value is the same
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

```<code>  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]
</code>```

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

```<code>  arrayName[eachObject].Language === "English"
</code>```

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().

答:
The below snippets stores the languages that have been encountered in an array. If the current objects language is in the array then it is filtered out. It makes the assumption that the first object encountered with the language is stored.

const objs = [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ],
 presentLanguages = [];
 let languageIsNotPresent;
 const objsFilteredByLanguage = objs.filter(function (o) {
  languageIsNotPresent = presentLanguages.indexOf(o.Language) == -1;
  presentLanguages.push(o.Language);
  return languageIsNotPresent;
 });
 console.log(objsFilteredByLanguage);```

Body:
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

  arrayName[eachObject].Language === "English"

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().


问:
How to find total number of points in each polygon in an image
I have a binary image as shown here. I want to find total number of points each polygon have.For a given image , each polygon has one point. I guess that the approach to solve this problem is to first find polygons in the image for that I used cv2.findContours but not able to get polygons. Any help would be appreciated.</p>

答:
As a first step I would try out corner detection.

OpenCV demo of the Harris corner detecor is available here.

```<code># Detecting corners
dst = cv.cornerHarris(src_gray, blockSize, apertureSize, k)
</code>```

The documentation of the function is to be found here.

Body:
As a first step I would try out corner detection.

OpenCV demo of the Harris corner detecor is available here.

# Detecting corners
dst = cv.cornerHarris(src_gray, blockSize, apertureSize, k)

The documentation of the function is to be found here.


问:
How to disable a user from firebase?
In the firebase API

```<code>https://firebase.google.com/docs/auth/web/manage-users
</code>```

we can delete users, but how could we prevent users from simply registering again, in the GUI for firebase we have the option to disable users , how could we do this in the program, for example if we are building a admin panel that checks posts for a listing site that have been reported, and we want to disable the creator or the reporter for spamming as part of availiable actions.

Thanks.

I develop in react if that changes the answer.

答:
Well they can always register again (in case the website is public/ not invite-only), with completely different credentials.

You can do a matching of the new data and existing blocked users, and if it matches above a threshold, flag them.

And you can improve your reporting, the faster you detect a user who should be blocked, the better.

Title: How to disable a user from firebase?

Body:
In the firebase API

https://firebase.google.com/docs/auth/web/manage-users

we can delete users, but how could we prevent users from simply registering again, in the GUI for firebase we have the option to disable users , how could we do this in the program, for example if we are building a admin panel that checks posts for a listing site that have been reported, and we want to disable the creator or the reporter for spamming as part of availiable actions.

Thanks.

I develop in react if that changes the answer.


问:
Style appliance in combobox
I have simple window:

```<code><Window.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red"/>
    </Style>
</Window.Resources>

<StackPanel>
    <ComboBox VerticalAlignment="Top" HorizontalAlignment="Left">
        <ComboBoxItem IsSelected="True" Content="1"/>
        <ComboBoxItem Content="2"/>
        <ComboBoxItem Content="3"/>
    </ComboBox>
</StackPanel>
</code>```

But this style is not applyed to combobox. If I move it to app.xaml it starts works.
Could someone to explain this strange behaviour?

答:
The styles in App.xaml are applied inside templates, this means that if the ComboBoxItem internally creates a TextBlock that only is affected by those global styles.

To change text colours you should set Foreground or TextElement.Foreground on the ComboBox itself (for which you can also use a style).

Title: Style appliance in combobox

Body:
I have simple window:

<Window.Resources>

</Window.Resources>

<StackPanel>
    <ComboBox VerticalAlignment="Top" HorizontalAlignment="Left">
        <ComboBoxItem IsSelected="True" Content="1"/>
        <ComboBoxItem Content="2"/>
        <ComboBoxItem Content="3"/>
    </ComboBox>
</StackPanel>

But this style is not applyed to combobox. If I move it to app.xaml it starts works.
Could someone to explain this strange behaviour?


问:
Ideal configuration setting for max.tasks for Kafka Source Connector
I'm trying to run a HDFS Source Connector and a FileStream Source Connector. I was wondering how it would work if we set tasks.max > 1. Isn't it the connector's job to make sure that the parallelism is handled correctly?

For example, would it not be a problem for FileStream Source Connector if there are more than 1 tasks accessing the file? How will the connector know which line is being read by which task and how to make sure that there is no clash among tasks?

OR

Is it that the setting should be tasks.max=1 for such connectors where such a problem can occur?

答:
There is no such problem, since according the docs:

tasks.max - The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism.

For example, for File Stream Source Connector max.tasks is simple ignored, while for JDBC Source Connector the real number of tasks is defined as minimum of tasks.max and tables count.


问:
How to traverse a 2D array using recursion
I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.

```<code>void display(int** matrix1,int row, int column)
</code>```

This is what I am doing for the 1D array:

```<code>void print_array(int arr[], int size, int i)
{

    if (i == size) {
        cout << endl;
        return;
    }
    cout << arr[i] << " ";
    print_array(arr, size, i+1);
}
</code>```

I know how to traverse 1D array but unable to do this.
I want to display each element in the matrix using recursion.

答:
First of all, it is not quite clear why you want a recursive solution. Perhaps it is a matter of tase, but I find recursion difficult to write, read and debug. Anyhow, I allowed myself to modify your 1d version:

```<code>#include <iostream>
#include <vector>

void print_array(const std::vector<int>& arr,size_t i = 0) {
    if (i == arr.size()) {
        std::cout << '\n';
        return;
    }
    std::cout << arr[i] << " ";
    print_array(arr, i+1);
}
</code>```

I use size_t instead of int, because thats the type to be used when comparing with a containers size. I supplied a default for i because when you call it you dont want to pass the index, but just print the whole array. std::endl is not only printing a new line, but it also flushes the stream. This is unnecessary in most cases.

For the 2D case all you need to add is a second index and a condition to go to the next row.

That is, if the signature of the function is

```<code>void print_array(const std::vector<std::vector<int>>& arr,size_t i=0,size_t j=0)
</code>```

and it prints arr[i][j] then you need to return without printing anything when i == arr.size() and you have to skip to the next row when j== arr[i].size(). This can be done with a condition along the line of:

```<code>    if (j == arr[i].size()) {
        std::cout << '\n';
        print_array( arr, i+1,0);  // start with the first element of next row
        return;
    }
</code>```

PS is you insist on a int**, it should be straightforward to adapt, but I would strongly suggest to use a vector and perhaps even a std::vector<std::array> if the inner arrays all have same size.

Body:
I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.

void display(int** matrix1,int row, int column)

This is what I am doing for the 1D array:

void print_array(int arr[], int size, int i)
{

    if (i == size) {
        cout << endl;
        return;
    }
    cout << arr[i] << " ";
    print_array(arr, size, i+1);
}

I know how to traverse 1D array but unable to do this.
I want to display each element in the matrix using recursion.

Body:
First of all, it is not quite clear why you want a recursive solution. Perhaps it is a matter of tase, but I find recursion difficult to write, read and debug. Anyhow, I allowed myself to modify your 1d version:

#include <iostream>
#include <vector>

void print_array(const std::vector<int>& arr,size_t i = 0) {
    if (i == arr.size()) {
        std::cout << '\n';
        return;
    }
    std::cout << arr[i] << " ";
    print_array(arr, i+1);
}

I use size_t instead of int, because thats the type to be used when comparing with a containers size. I supplied a default for i because when you call it you dont want to pass the index, but just print the whole array. std::endl is not only printing a new line, but it also flushes the stream. This is unnecessary in most cases.

For the 2D case all you need to add is a second index and a condition to go to the next row.

That is, if the signature of the function is

void print_array(const std::vector<std::vector<int>>& arr,size_t i=0,size_t j=0)

and it prints arr[i][j] then you need to return without printing anything when i == arr.size() and you have to skip to the next row when j== arr[i].size(). This can be done with a condition along the line of:

    if (j == arr[i].size()) {
        std::cout << '\n';
        print_array( arr, i+1,0);  // start with the first element of next row
        return;
    }

PS is you insist on a int**, it should be straightforward to adapt, but I would strongly suggest to use a vector and perhaps even a std::vector<std::array> if the inner arrays all have same size.


问:
Expressing "almost Properness" under option type
Suppose we have a type A with an equivalence relation (===) : A -> A -> Prop on it.

On top of that there is a function f : A -> option A.

It so happens that this function f is "almost" Proper with respect to equiv. By "almost" I mean the following:

```<code>Lemma almost_proper :
  forall a1 a2 b1 b2 : A,
    a1 === a2 ->
    f a1 = Some b1 -> f a2 = Some b2 ->
    b1 === b2.
</code>```

In other words, if f succeeds on both inputs, the relation is preserved, but f might still fail on one and succeed on the other. I would like to express this concept concisely but came up with a few questions when trying to do so.

I see three solutions to the problem:

Leave everything as is. Do not use typeclasses, prove lemmas like the one above. This doesn't look good, because of the proliferation of preconditions like x = Some y, which create complications when proving lemmas.

It is possible to prove Proper ((===) ==> equiv_if_Some) f when equiv_if_Some is defined as follows:

```<code>Inductive equiv_if_Some {A : Type} {EqA : relation A} `{Equivalence A EqA} : relation (option A) :=
| equiv_Some_Some : forall a1 a2, a1 === a2 -> equiv_if_Some (Some a1) (Some a2)
| equiv_Some_None : forall a, equiv_if_Some (Some a) None
| equiv_None_Some : forall a, equiv_if_Some None (Some a)
| equiv_None_None : equiv_if_Some None None.
</code>```

One problem here is that this is no longer an equivalence relation (it is not transitive).

It might be possible to prove Almost_Proper ((===) ==> (===)) f if some reasonable Almost_Proper class is used. I am not sure how that would work.

What would be the best way to express this concept? I am leaning toward the second one, but perhaps there are more options?

For variants 2 and 3, are there preexisting common names (and therefore possibly premade definitions) for the relations I describe? (equiv_if_Some and Almost_Proper)

答:
2 if it simplifies your proofs.

The fact that it's not an equivalence relation is not a deal breaker, but it does limit the contexts in which it can be used.

equiv_if_Some might be nicer to define as an implication (similar to how it appears in the almost_proper lemma) than as an inductive type.

You may also consider using other relations (as an alternative to, or in combination with equiv_if_Some):

A partial order, that can only relate None to Some but not Some to None

A partial equivalence relation, that can only relate Somes.

Body:
Suppose we have a type A with an equivalence relation (===) : A -> A -> Prop on it.

On top of that there is a function f : A -> option A.

It so happens that this function f is "almost" Proper with respect to equiv. By "almost" I mean the following:

Lemma almost_proper :
  forall a1 a2 b1 b2 : A,
    a1 === a2 ->
    f a1 = Some b1 -> f a2 = Some b2 ->
    b1 === b2.

In other words, if f succeeds on both inputs, the relation is preserved, but f might still fail on one and succeed on the other. I would like to express this concept concisely but came up with a few questions when trying to do so.

I see three solutions to the problem:

Leave everything as is. Do not use typeclasses, prove lemmas like the one above. This doesn't look good, because of the proliferation of preconditions like x = Some y, which create complications when proving lemmas.

It is possible to prove Proper ((===) ==> equiv_if_Some) f when equiv_if_Some is defined as follows:

Inductive equiv_if_Some {A : Type} {EqA : relation A} `{Equivalence A EqA} : relation (option A) :=
| equiv_Some_Some : forall a1 a2, a1 === a2 -> equiv_if_Some (Some a1) (Some a2)
| equiv_Some_None : forall a, equiv_if_Some (Some a) None
| equiv_None_Some : forall a, equiv_if_Some None (Some a)
| equiv_None_None : equiv_if_Some None None.

One problem here is that this is no longer an equivalence relation (it is not transitive).

It might be possible to prove Almost_Proper ((===) ==> (===)) f if some reasonable Almost_Proper class is used. I am not sure how that would work.

What would be the best way to express this concept? I am leaning toward the second one, but perhaps there are more options?

For variants 2 and 3, are there preexisting common names (and therefore possibly premade definitions) for the relations I describe? (equiv_if_Some and Almost_Proper)


答:
Can't say I'm super familiar with Firebase but ill try and help (can't hurt).

Have you tried to blacklist the IP of the user in question?

Hope I helped :)

Have a good day!

Title: How to disable a user from firebase?


问:
Splitting of an RGB image to R G B using OpenCv Python
When i am splitting my image I am not getting the frames in colors of Red,Green,Blue. The frames I got in output are three Gray color images.</p>

```<code>import numpy as np
import cv2
img=cv2.imread("C:\\Users\\Pavan\\Desktop\\bird.jpg")
#display an image
cv2.imshow('image',img)
b,g,r=cv2.split(img)
cv2.imshow('b',b)
cv2.imshow('g',g)
cv2.imshow('r',r)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
Here are two ways to do that in Python/OpenCV/Numpy.

```<code>Method 1 is to copy the image 3 times and set the appropriate other channels to black

Method 2 is to split the image merge each with a black image for the other channels (suggested in comments by Mark Setchell)
</code>```

Input:

```<code>import cv2
import numpy as np

img = cv2.imread('mandril3.jpg')

# Method 1: copy image and set other channels to black
r = img.copy()
r[:,:,0] = r[:,:,1] = 0

g = img.copy()
g[:,:,0] = g[:,:,2] = 0

b = img.copy()
b[:,:,1] = b[:,:,2] = 0

cv2.imshow("red",r)
cv2.imshow("green",g)
cv2.imshow("blue",b)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Method 2: split channels and merge with black channels
b,g,r = cv2.split(img)
k = np.zeros_like(b)
b = cv2.merge([b,k,k])
g = cv2.merge([k,g,k])
r = cv2.merge([k,k,r])

cv2.imshow("red",r)
cv2.imshow("green",g)
cv2.imshow("blue",b)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite("mandril3_red.jpg", r)
cv2.imwrite("mandril3_green.jpg", g)
cv2.imwrite("mandril3_blue.jpg", b)
</code>```

Red:

Green:

Blue:

Body:
When i am splitting my image I am not getting the frames in colors of Red,Green,Blue. The frames I got in output are three Gray color images.

import numpy as np
import cv2
img=cv2.imread("C:\\Users\\Pavan\\Desktop\\bird.jpg")
#display an image
cv2.imshow('image',img)
b,g,r=cv2.split(img)
cv2.imshow('b',b)
cv2.imshow('g',g)
cv2.imshow('r',r)
cv2.waitKey(0)
cv2.destroyAllWindows()

Body:
Here are two ways to do that in Python/OpenCV/Numpy.

Method 1 is to copy the image 3 times and set the appropriate other channels to black

Method 2 is to split the image merge each with a black image for the other channels (suggested in comments by Mark Setchell)

Input:

import cv2
import numpy as np

img = cv2.imread('mandril3.jpg')

# Method 1: copy image and set other channels to black
r = img.copy()
r[:,:,0] = r[:,:,1] = 0

g = img.copy()
g[:,:,0] = g[:,:,2] = 0

b = img.copy()
b[:,:,1] = b[:,:,2] = 0

cv2.imshow("red",r)
cv2.imshow("green",g)
cv2.imshow("blue",b)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Method 2: split channels and merge with black channels
b,g,r = cv2.split(img)
k = np.zeros_like(b)
b = cv2.merge([b,k,k])
g = cv2.merge([k,g,k])
r = cv2.merge([k,k,r])

cv2.imshow("red",r)
cv2.imshow("green",g)
cv2.imshow("blue",b)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite("mandril3_red.jpg", r)
cv2.imwrite("mandril3_green.jpg", g)
cv2.imwrite("mandril3_blue.jpg", b)

Red:

Green:

Blue:


问:
Custom Address for Google Autocomplete Search Box
I have an autocomplete (Places Autocomplete by Google) on my website that works fine and is restricted to the boundaries I have. But there are some locations that are missing when somebody types it in the search box, even though these locations do exist on the actual Google Maps. The javascript implementation for the Autocomplete is below.

```<code>function initAutocomplete(){
      var areaboundary = new google.maps.LatLngBounds(
          new google.maps.LatLng(51.377809, -3.508688),
          new google.maps.LatLng(51.628119, -2.954925)
      );

  var options = {
    bounds: areaboundary,
    strictBounds: true,
    types: ['geocode'],
    componentRestrictions: {country: 'uk'}
  };
  var input = document.getElementById('property-location');
  autocomplete = new google.maps.places.Autocomplete(input, options);

  autocomplete.addListener('place_changed', function(){
    var place = autocomplete.getPlace();

    if(place.length === 0){
      return;
    }

    if(place.formatted_address == "Cardiff, UK"){
      jQuery("#property-radius-sale option[value=5]").prop("selected", true);
      jQuery("#property-radius-rent option[value=5]").prop("selected", true);
    }

    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    var coordinates = [lat, lng];

    var hidden_input = document.getElementById("lat-lng-location");
    hidden_input.value = coordinates;
  });
}
</code>```

The location I am trying to add is this one:

Location to be added

The reason why I need this specific address is because the addresses the come up on the website do include Cardiff Bay as well.

My question is, how can one add a custom address/location with the lng and lat to the Places Autocomplete?

答:
The specific issue you have with Cardiff Bay, UK is caused by the types parameter. The place is considered as a natural feature and is not returned by the API if you specify the geocode type.

It will be listed though if you don't specify a type, or use types: ['geocode', 'establishment'] which according to the docs is identical to specifying no type.

function initialize() {

  var ac = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')), {
      componentRestrictions: {
        country: 'uk'
      }
    });

  ac.addListener('place_changed', function() {

    var place = ac.getPlace();

    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    var html = '
Latitude: ' + place.geometry.location.lat() + '
';
    html += '
Longitude: ' + place.geometry.location.lng() + '
';

    document.getElementById('geometry').innerHTML = html;
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,
html {
  padding: 10px;
}

#autocomplete {
  width: 400px;
}

#geometry {
  margin-top: 10px;
  background: lightblue;
  padding: 10px 20px;
}</code>```

<input id="autocomplete" value="Cardiff Bay" type="text">

```

Body:
I have an autocomplete (Places Autocomplete by Google) on my website that works fine and is restricted to the boundaries I have. But there are some locations that are missing when somebody types it in the search box, even though these locations do exist on the actual Google Maps. The javascript implementation for the Autocomplete is below.

function initAutocomplete(){
      var areaboundary = new google.maps.LatLngBounds(
          new google.maps.LatLng(51.377809, -3.508688),
          new google.maps.LatLng(51.628119, -2.954925)
      );

  var options = {
    bounds: areaboundary,
    strictBounds: true,
    types: ['geocode'],
    componentRestrictions: {country: 'uk'}
  };
  var input = document.getElementById('property-location');
  autocomplete = new google.maps.places.Autocomplete(input, options);

  autocomplete.addListener('place_changed', function(){
    var place = autocomplete.getPlace();

    if(place.length === 0){
      return;
    }

    if(place.formatted_address == "Cardiff, UK"){
      jQuery("#property-radius-sale option[value=5]").prop("selected", true);
      jQuery("#property-radius-rent option[value=5]").prop("selected", true);
    }

    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    var coordinates = [lat, lng];

    var hidden_input = document.getElementById("lat-lng-location");
    hidden_input.value = coordinates;
  });
}

The location I am trying to add is this one:

Location to be added

The reason why I need this specific address is because the addresses the come up on the website do include Cardiff Bay as well.

My question is, how can one add a custom address/location with the lng and lat to the Places Autocomplete?

Body:
The specific issue you have with Cardiff Bay, UK is caused by the types parameter. The place is considered as a natural feature and is not returned by the API if you specify the geocode type.

It will be listed though if you don't specify a type, or use types: ['geocode', 'establishment'] which according to the docs is identical to specifying no type.

function initialize() {

  var ac = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')), {
      componentRestrictions: {
        country: 'uk'
      }
    });

  ac.addListener('place_changed', function() {

    var place = ac.getPlace();

    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    var html = '<div>Latitude: ' + place.geometry.location.lat() + '</div>';
    html += '<div>Longitude: ' + place.geometry.location.lng() + '</div>';

    document.getElementById('geometry').innerHTML = html;
  });
}

body,
html {
  padding: 10px;
}

#autocomplete {
  width: 400px;
}

#geometry {
  margin-top: 10px;
  background: lightblue;
  padding: 10px 20px;
}

<input id="autocomplete" value="Cardiff Bay" type="text">
<div id="geometry">

</div>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initialize">
</script>


问:
Conditionally assign multiple columns to another DataFrame (the condition determines which set of columns in that row are assigned)
I need to reformat some data. I've never used pandas before, and could use some help.

I have two DataFrames:
df1
dfTarget

df1 is the un-formatted data, dfTarget is how I need the data to be formatted

Based on a condition, I need one group of columns in df1 to be copied to certain columns in dfTarget. If the condition is false, I need another group of columns in df1 to be copied to certain columns in dfTarget.

Simplified df1:

```<code>    city   state   condition   city2   state2
0
1
2
3
4
</code>```

Simplified dfTarget:

```<code>    mCity   mState
0
1
2
3
4
</code>```

Basically, if the condition is true, I need to move 'city' and 'state' into 'mCity' and 'mState' respectively. If the condition is false, I need to move 'city2' and 'state2' into 'mCity' and 'mState'.

dfTarget is starting off empty, and needs to be filled row by row based on a bunch of conditions in df1.

I've never used pandas, and tried to research this myself, but got lost quickly in all the different methods. Please, what's the best way to do this?

答:
It should be simple enough to conditionally assign the columns, assuming the indices and/or number of rows is the same.

If the condition comes from a column, you can try np.where:

```<code>dfTarget[['mCity', 'mState']] = np.where(
    df1[['condition']], df1[['city', 'state']], df1[['city2', 'state2']])
</code>```

Minimal Example

```<code>df1 = pd.DataFrame({
    'city': list('abc'),
    'state': list('def'),
    'condition': [True, False, True],
    'city2': list('hij'),
    'state2': list('klm')})
dfTarget = pd.DataFrame(index=df1.index, columns=['mCity', 'mState'])

dfTarget[['mCity', 'mState']] = np.where(
    df1[['condition']], df1[['city', 'state']], df1[['city2', 'state2']])

  mCity mState
0     a      d
1     i      l    # comes from second group of columns
2     c      f
</code>```

Body:
I need to reformat some data. I've never used pandas before, and could use some help.

I have two DataFrames:
df1
dfTarget

df1 is the un-formatted data, dfTarget is how I need the data to be formatted

Based on a condition, I need one group of columns in df1 to be copied to certain columns in dfTarget. If the condition is false, I need another group of columns in df1 to be copied to certain columns in dfTarget.

Simplified df1:

    city   state   condition   city2   state2
0
1
2
3
4

Simplified dfTarget:

    mCity   mState
0
1
2
3
4

Basically, if the condition is true, I need to move 'city' and 'state' into 'mCity' and 'mState' respectively. If the condition is false, I need to move 'city2' and 'state2' into 'mCity' and 'mState'.

dfTarget is starting off empty, and needs to be filled row by row based on a bunch of conditions in df1.

I've never used pandas, and tried to research this myself, but got lost quickly in all the different methods. Please, what's the best way to do this?

Body:
It should be simple enough to conditionally assign the columns, assuming the indices and/or number of rows is the same.

If the condition comes from a column, you can try np.where:

dfTarget[['mCity', 'mState']] = np.where(
    df1[['condition']], df1[['city', 'state']], df1[['city2', 'state2']])

Minimal Example

df1 = pd.DataFrame({
    'city': list('abc'),
    'state': list('def'),
    'condition': [True, False, True],
    'city2': list('hij'),
    'state2': list('klm')})
dfTarget = pd.DataFrame(index=df1.index, columns=['mCity', 'mState'])

dfTarget[['mCity', 'mState']] = np.where(
    df1[['condition']], df1[['city', 'state']], df1[['city2', 'state2']])

  mCity mState
0     a      d
1     i      l    # comes from second group of columns
2     c      f


问:
What is the purpose of child in Consumer Provider Flutter
I have a question about Consumer, of Provider package, in Flutter.
I don't understand the purpose of argument "child" in the builder of Consumer

```<code>Consumer<MyModel>(builder: (context, myModel, child) {
// doing stuff using myModel variable
});
</code>```

I could not find any doc about it.

答:
You can pass child widget in consumer. What ever widget you pass as a child will not rebuild when data is changed.

You can avoid unnecessary rebuild of widget using child.

Body:
I have a question about Consumer, of Provider package, in Flutter.
I don't understand the purpose of argument "child" in the builder of Consumer

Consumer<MyModel>(builder: (context, myModel, child) {
// doing stuff using myModel variable
});

I could not find any doc about it.


问:
Flink timer async
I have a question regarding Flink and its timer service.

I have a keyBy stream which uses a timer,
When the timer is called I need to send an http request which might take time to respond.
My question is, should I make the http call async?
or flink is making the timer call already as a new thread with async per key?

Thanks in advance

答: You can use a ProcessFunction that stores the data required for the HTTP request, and that can have a timer. When it fires, you emit a record that has the request data, which a subsequent AsyncFunction will use to make the periodic request that you need.

Title: Flink timer async


答:
To prevent the user from re-registering, you should disable account instead of deleting it. This will prevent the user from signing in again, and from refreshing their ID token. If you want to do this programmatically, have a look at updating a user with the Admin SDKs. For example, in Node.js it'd be:

```<code>admin.auth().updateUser(uid, { disabled: true })
</code>```

Keep in mind however that even after disabling the account, their existing ID token will remain valid until it expires (typically within an hour), and cannot be revoked. If you want to prevent them from posting in the meantime, you'll also want to keep a list of blacklisted/blocked UIDs somewhere, and check against that list before allowing them to write/access the data.

Title: How to disable a user from firebase?

Body:
To prevent the user from re-registering, you should disable account instead of deleting it. This will prevent the user from signing in again, and from refreshing their ID token. If you want to do this programmatically, have a look at updating a user with the Admin SDKs. For example, in Node.js it'd be:

admin.auth().updateUser(uid, { disabled: true })

Keep in mind however that even after disabling the account, their existing ID token will remain valid until it expires (typically within an hour), and cannot be revoked. If you want to prevent them from posting in the meantime, you'll also want to keep a list of blacklisted/blocked UIDs somewhere, and check against that list before allowing them to write/access the data.


问:
Delete using checkbox in codeigniter
I am having trouble regarding my checkbox delete in codeigniter. I have a form in which a table is displayed and populated with data from the database and there are two submit buttons. The first is the adduser button which I already did.

My problem is that I don't have any idea how to get the value of the checkbox in the displayed table. Here’s the snippet to understand more my problem:

Controller:

```<code>public function options()
    {
        $data['meta_title']="Users";
        $data['meta_desc']="Find your friends from our members";

        if ($this->input->post('AddUser'))
        {
            $this->load->view('template/header',$data);
            $this->load->view('users/add_view');
            $this->load->view('template/footer');
        }
        elseif($this->input->post('Delete'))
        {
            /// i have troubles with my logic here
        }
    }
</code>```

View:

```<code><?php foreach($query->result_array() as $row): ?>
        <tr class="even gradeC">
            <td><?php echo anchor('users/edit/'.$row['usrID'],$row['usrName']);?></td>
            <td><?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?></td>
            <td><?php echo $row['usrpBday'];?></td>
            <td><?php echo $row['usrpSex'];?></td>
            <td><?php echo $row['usrpAddress'];?></td>
            <td><input type="checkbox" name="checkID[]" id="checkID" value="<?php echo $row['usrID'];?>" />

              <label for="checkID"></label></td>
        </tr>
<? endforeach; ?>
</code>```

答:
It would have been easier to understand your question if you'd actually add the submit button as well.

I'll try to explain you the principles;
You need to have a form to wrap the data you want to send, so for example:

```<code><form action="whereToSendTheData.php" method="post">
    <table>
        <tr class="even gradeC">
            <td><?php echo anchor('users/edit/'.$row['usrID'],$row['usrName']);?></td>
            <td><?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?></td>
            <td><?php echo $row['usrpBday'];?></td>
            <td><?php echo $row['usrpSex'];?></td>
            <td><?php echo $row['usrpAddress'];?></td>
            <td><input type="checkbox" name="checkID" id="checkID" value="<?php echo $row['usrID'];?>" />

            <label for="checkID"></label></td>
        </tr>
    </table>
    <input type="submit" value="Add user">
</form>
</code>```

this script will send the data within your form to the page "whereToSendTheData.php", which i defined in the "action" attribute above.

on "whereToSendData.php"
you need to have a script to process/fetch this data.
for example:

```<code><?php
echo "hello $_POST['checkID']";
?>
</code>```

which will output "hello" and the value of checkID.

you can read more about the subject, here:
http://www.w3schools.com/php/php_post.asp

Title: Delete using checkbox in codeigniter

Body:
I am having trouble regarding my checkbox delete in codeigniter. I have a form in which a table is displayed and populated with data from the database and there are two submit buttons. The first is the adduser button which I already did.

My problem is that I don't have any idea how to get the value of the checkbox in the displayed table. Here’s the snippet to understand more my problem:

Controller:

public function options()
    {
        $data['meta_title']="Users";
        $data['meta_desc']="Find your friends from our members";

        if ($this->input->post('AddUser'))
        {
            $this->load->view('template/header',$data);
            $this->load->view('users/add_view');
            $this->load->view('template/footer');
        }
        elseif($this->input->post('Delete'))
        {
            /// i have troubles with my logic here
        }
    }

View:

<?php foreach($query->result_array() as $row): ?>

            <?php echo anchor('users/edit/'.$row['usrID'],$row['usrName']);?>
            <?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?>
            <?php echo $row['usrpBday'];?>
            <?php echo $row['usrpSex'];?>
            <?php echo $row['usrpAddress'];?>
            <input type="checkbox" name="checkID[]" id="checkID" value="<?php echo $row['usrID'];?>" />

<? endforeach; ?>

Body:
It would have been easier to understand your question if you'd actually add the submit button as well.

I'll try to explain you the principles;
You need to have a form to wrap the data you want to send, so for example:

<form action="whereToSendTheData.php" method="post">
    <table>
        <tr class="even gradeC">
            <td><?php echo anchor('users/edit/'.$row['usrID'],$row['usrName']);?></td>
            <td><?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?></td>
            <td><?php echo $row['usrpBday'];?></td>
            <td><?php echo $row['usrpSex'];?></td>
            <td><?php echo $row['usrpAddress'];?></td>
            <td><input type="checkbox" name="checkID" id="checkID" value="<?php echo $row['usrID'];?>" />

            <label for="checkID"></label></td>
        </tr>
    </table>
    <input type="submit" value="Add user">
</form>

this script will send the data within your form to the page "whereToSendTheData.php", which i defined in the "action" attribute above.

on "whereToSendData.php"
you need to have a script to process/fetch this data.
for example:

<?php
echo "hello $_POST['checkID']";
?>

which will output "hello" and the value of checkID.

you can read more about the subject, here:
http://www.w3schools.com/php/php_post.asp


问:
GCP zone northamerica-northeast1-a does not have enough resources available to fulfill the request
When I run gcloud compute instances create test --zone=northamerica-northeast1-a I get:

```<code>ERROR: (gcloud.compute.instances.create) Could not fetch resource:
 - The zone 'projects/PROJECT/zones/northamerica-northeast1-a' does not have enough resources available to fulfill the request.  Try a different zone, or try again later.
</code>```

I ran into this error in production where a service tried to spin up resources there.

This only affects that specific zone. Is there a way to get more information about this? Is this an outage?

Cheers,
Kim

答:
At the time you tried to provision the instance, that zone had insufficient resources to 'make it so'.

You may retry the request (please do so increasingly infrequently) until there are sufficient resources for you to acquire. There are others also trying to secure these resources and, everyone hammering the request concurrently exacerbates the issue.

There's only ever finite resources available and, unfortunately, you hit Google's capacity for that zone (for available resources to fulfill your need) for that period of time.

The error is unambiguous and you're unlikely to get much more from Google by way of admission that it had insufficient capacity (available) because customers don't want to experience this.

Body:
When I run gcloud compute instances create test --zone=northamerica-northeast1-a I get:

ERROR: (gcloud.compute.instances.create) Could not fetch resource:
 - The zone 'projects/PROJECT/zones/northamerica-northeast1-a' does not have enough resources available to fulfill the request.  Try a different zone, or try again later.

I ran into this error in production where a service tried to spin up resources there.

This only affects that specific zone. Is there a way to get more information about this? Is this an outage?

Cheers,
Kim


问:
Enumerate @font-face URLs using Javascript/JQuery
Is there a way of enumerating all the @font-face URLs (web font URLs) of a given HTML page using JavaScript or JQuery?</p>

答:
You can also get font-family with variants and URL's.

Following is the code in jQuery

var fontArray = [];
$.get("https://www.googleapis.com/webfonts/v1/webfonts?key={your key}&sort=popularity", {}, function (data) {
    var count = 0;
    $.each(data.items, function (index, value) {
        count++
        fontArray.push(value);
    });
});
```


问:
Testing (if..Else if...Else) statement (not working)
Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work</p>

```<code>//package Driver2;

import java.util.Scanner;

class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
    this.name = name;
    this.address = address;
    this.number = number;
    this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
    return this.name;
}

public String getAddress(){
    return this.address;
}

public String getNumber(){
    return this.number;
}

public int getcustomerPurchase(){
    return this.customerPurchase;
}

//Mutators
public void setName(String n){
    this.name = n;
}

public void setAddress(String a){
    this.address = a;
}

public void setNumber(String n){
    this.number = n;
}

public void setcustomerPurchase(int a){
    this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
   r =  this.customerPurchase;
    if (r > 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}

}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    super(name, address, number, customerPurchase);
    this.customerNumber = customerN;
    this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
    return this.customerNumber;
}

public boolean getRecieveMail(){
    return this.recieveMail;
}
public int getcustomerDiscount()
{
    return customerDiscount;
}

//Mutators
public void setCustomerNumber(String c){
    this.customerNumber = c;
}

public void setRecieveMail(boolean r){
    this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;

//Constructors
   /* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
    super();
    this.customerPurchase = customerPurchase;
    //this.customerDiscount = customerDiscount;
}*/
    public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    //super(name, address, number, customerPurchase, customerN, rm);
    //this.customerPurchase = customerN;
    //this.customerDiscount = pc;
}

public Driver1()
{}

//Accessors
/*
public int getcustomerDiscount()
{
    return this.customerDiscount;
}
/*
@Override
public int getcustomerPurchase()
{
    return this.customerPurchase;
}

//Mutators

@Override
public void setcustomerPurchase(int c)
{
    this.customerPurchase = c;
}*/

/*
public void setcustomerDiscount(int r)
{
    this.customerPurchase = r;
    if (r >= 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter name of customer:");
    String name1 = scanner.nextLine();
    System.out.print("Enter address of customer:");
    String address1 = scanner.nextLine();
    System.out.print("Enter phone number of customer:");
    String number1 = scanner.nextLine();
    System.out.print("Enter customer number:");
    String customerNumber = scanner.nextLine();
    System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
    String answer = scanner.nextLine();
    boolean recieveMail = (answer.equals("yes"));
    System.out.print("Enter amount customer has spent:");
    int customerPurchase = scanner.nextInt();

    Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

    System.out.println("\nCustomer: ");
    System.out.println("Name: "+customer.getName());
    System.out.println("Address: "+customer.getAddress());
    System.out.println("Phone Number: "+customer.getNumber());
    System.out.println("Customer Number: "+customer.getCustomerNumber());
    System.out.println("Recieve Mail?: "+customer.getRecieveMail());
    System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
    System.out.println("Percent off:  "+customer.getcustomerDiscount());

}
}
</code>```

答:
The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.

1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.

2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.

3) Another thing is your order of the if/else if conditions should be in descending order.

Once you fix them, you can get your output as expected.
Below I have made those changes:

```<code>import java.util.Scanner;

class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
  this.name = name;
  this.address = address;
  this.number = number;
  this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
  return this.name;
}

public String getAddress(){
  return this.address;
}

public String getNumber(){
  return this.number;
}

public int getcustomerPurchase(){
  return this.customerPurchase;
}

//Mutators
public void setName(String n){
  this.name = n;
}

public void setAddress(String a){
  this.address = a;
}

public void setNumber(String n){
  this.number = n;
}

public void setcustomerPurchase(int a){
  this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{

}

}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
  super(name, address, number, customerPurchase);
  this.customerNumber = customerN;
  this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
  return this.customerNumber;
}

public boolean getRecieveMail(){
  return this.recieveMail;
}
public String getcustomerDiscount()
{
  return customerDiscount;
}

//Mutators
public void setCustomerNumber(String c){
  this.customerNumber = c;
}

public void setRecieveMail(boolean r){
  this.recieveMail = r;
}

public void setcustomerDiscount(int r)
{
  String customerDiscount = "";

  if (r >= 2000)
  {
    customerDiscount="10%";
      System.out.print("10%");
  }
  else if (r >= 1500)
  {
    customerDiscount="7%";
      System.out.print("7%");
  }
  else if (r >= 1000)
  {
   customerDiscount="6%";
      System.out.print("6%");
  }
  else if (r > 500)
  {
    customerDiscount="5%";
      System.out.print("5%");
  }
  else
  {

      System.out.print("");
  }
  this.customerDiscount = customerDiscount;
}
}

public class TestMain
{

public static void main(String args[]){

  Scanner scanner = new Scanner(System.in);

  System.out.print("Enter name of customer:");
  String name1 = scanner.nextLine();
  System.out.print("Enter address of customer:");
  String address1 = scanner.nextLine();
  System.out.print("Enter phone number of customer:");
  String number1 = scanner.nextLine();
  System.out.print("Enter customer number:");
  String customerNumber = scanner.nextLine();
  System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
  String answer = scanner.nextLine();
  boolean recieveMail = (answer.equals("yes"));
  System.out.print("Enter amount customer has spent:");
  int customerPurchase = scanner.nextInt();
  scanner.close();

  Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

  System.out.println("\nCustomer: ");
  System.out.println("Name: "+customer.getName());
  System.out.println("Address: "+customer.getAddress());
  System.out.println("Phone Number: "+customer.getNumber());
  System.out.println("Customer Number: "+customer.getCustomerNumber());
  System.out.println("Recieve Mail?: "+customer.getRecieveMail());
  System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
  customer.setcustomerDiscount(customerPurchase);
  System.out.println("Percent off:  "+ customer.getcustomerDiscount());

}
}
</code>```

Hope it helps...

Body:
Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work

//package Driver2;

import java.util.Scanner;

class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
    this.name = name;
    this.address = address;
    this.number = number;
    this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
    return this.name;
}

public String getAddress(){
    return this.address;
}

public String getNumber(){
    return this.number;
}

public int getcustomerPurchase(){
    return this.customerPurchase;
}

//Mutators
public void setName(String n){
    this.name = n;
}

public void setAddress(String a){
    this.address = a;
}

public void setNumber(String n){
    this.number = n;
}

public void setcustomerPurchase(int a){
    this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
   r =  this.customerPurchase;
    if (r > 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}

}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    super(name, address, number, customerPurchase);
    this.customerNumber = customerN;
    this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
    return this.customerNumber;
}

public boolean getRecieveMail(){
    return this.recieveMail;
}
public int getcustomerDiscount()
{
    return customerDiscount;
}

//Mutators
public void setCustomerNumber(String c){
    this.customerNumber = c;
}

public void setRecieveMail(boolean r){
    this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;

//Constructors
   /* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
    super();
    this.customerPurchase = customerPurchase;
    //this.customerDiscount = customerDiscount;
}*/
    public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    //super(name, address, number, customerPurchase, customerN, rm);
    //this.customerPurchase = customerN;
    //this.customerDiscount = pc;
}

public Driver1()
{}

//Accessors
/*
public int getcustomerDiscount()
{
    return this.customerDiscount;
}
/*
@Override
public int getcustomerPurchase()
{
    return this.customerPurchase;
}

//Mutators

@Override
public void setcustomerPurchase(int c)
{
    this.customerPurchase = c;
}*/

/*
public void setcustomerDiscount(int r)
{
    this.customerPurchase = r;
    if (r >= 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter name of customer:");
    String name1 = scanner.nextLine();
    System.out.print("Enter address of customer:");
    String address1 = scanner.nextLine();
    System.out.print("Enter phone number of customer:");
    String number1 = scanner.nextLine();
    System.out.print("Enter customer number:");
    String customerNumber = scanner.nextLine();
    System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
    String answer = scanner.nextLine();
    boolean recieveMail = (answer.equals("yes"));
    System.out.print("Enter amount customer has spent:");
    int customerPurchase = scanner.nextInt();

    Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

    System.out.println("\nCustomer: ");
    System.out.println("Name: "+customer.getName());
    System.out.println("Address: "+customer.getAddress());
    System.out.println("Phone Number: "+customer.getNumber());
    System.out.println("Customer Number: "+customer.getCustomerNumber());
    System.out.println("Recieve Mail?: "+customer.getRecieveMail());
    System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
    System.out.println("Percent off:  "+customer.getcustomerDiscount());

}
}

Body:
The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.

1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.

2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.

3) Another thing is your order of the if/else if conditions should be in descending order.

Once you fix them, you can get your output as expected.
Below I have made those changes:

import java.util.Scanner;

class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
  this.name = name;
  this.address = address;
  this.number = number;
  this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
  return this.name;
}

public String getAddress(){
  return this.address;
}

public String getNumber(){
  return this.number;
}

public int getcustomerPurchase(){
  return this.customerPurchase;
}

//Mutators
public void setName(String n){
  this.name = n;
}

public void setAddress(String a){
  this.address = a;
}

public void setNumber(String n){
  this.number = n;
}

public void setcustomerPurchase(int a){
  this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{

}

}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
  super(name, address, number, customerPurchase);
  this.customerNumber = customerN;
  this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
  return this.customerNumber;
}

public boolean getRecieveMail(){
  return this.recieveMail;
}
public String getcustomerDiscount()
{
  return customerDiscount;
}

//Mutators
public void setCustomerNumber(String c){
  this.customerNumber = c;
}

public void setRecieveMail(boolean r){
  this.recieveMail = r;
}

public void setcustomerDiscount(int r)
{
  String customerDiscount = "";

  if (r >= 2000)
  {
    customerDiscount="10%";
      System.out.print("10%");
  }
  else if (r >= 1500)
  {
    customerDiscount="7%";
      System.out.print("7%");
  }
  else if (r >= 1000)
  {
   customerDiscount="6%";
      System.out.print("6%");
  }
  else if (r > 500)
  {
    customerDiscount="5%";
      System.out.print("5%");
  }
  else
  {

      System.out.print("");
  }
  this.customerDiscount = customerDiscount;
}
}

public class TestMain
{

public static void main(String args[]){

  Scanner scanner = new Scanner(System.in);

  System.out.print("Enter name of customer:");
  String name1 = scanner.nextLine();
  System.out.print("Enter address of customer:");
  String address1 = scanner.nextLine();
  System.out.print("Enter phone number of customer:");
  String number1 = scanner.nextLine();
  System.out.print("Enter customer number:");
  String customerNumber = scanner.nextLine();
  System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
  String answer = scanner.nextLine();
  boolean recieveMail = (answer.equals("yes"));
  System.out.print("Enter amount customer has spent:");
  int customerPurchase = scanner.nextInt();
  scanner.close();

  Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

  System.out.println("\nCustomer: ");
  System.out.println("Name: "+customer.getName());
  System.out.println("Address: "+customer.getAddress());
  System.out.println("Phone Number: "+customer.getNumber());
  System.out.println("Customer Number: "+customer.getCustomerNumber());
  System.out.println("Recieve Mail?: "+customer.getRecieveMail());
  System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
  customer.setcustomerDiscount(customerPurchase);
  System.out.println("Percent off:  "+ customer.getcustomerDiscount());

}
}

Hope it helps...


问:
Suppressing Some SBCL Debugger Output on Break
The debugger can be programmatically invoked by executing (break). For example, the debugging banner then displays what caused the interrupt, the HELP line, the available restarts, some related info, and finally the source of the interrupt:

```<code>debugger invoked on a SIMPLE-CONDITION in thread
#<THREAD "main thread" RUNNING {10010B0523}>:
  break

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [CONTINUE] Return from BREAK.
  1: [ABORT   ] Exit debugger, returning to top level.

#(
NODE: STATE=<NIL NIL NIL 0.0 0.0
(         )> DEPTH=0)
#(
NODE: STATE=<NIL NIL NIL 0.0 0.0
((ACTIVE GATE1) (ACTIVE GATE2) (COLOR RECEIVER1 BLUE) (COLOR RECEIVER2 RED) (COLOR TRANSMITTER1 BLUE) (COLOR TRANSMITTER2 RED) (FREE ME) (LOC CONNECTOR1 AREA5) (LOC CONNECTOR2 AREA7) (LOC ME AREA5))> DEPTH=0)
(DF-BNB1 )
   source: (BREAK)
0]
</code>```

I don't understand the related info between the restarts and the source. Can this info be suppressed, as
sometimes it is many lines long in my application. I've tried changing the debug & safety optimization settings, but to no effect.

答:
The output you are confused with is related to the place in the code where break was invoked. When I call it from the vanilla Lisp REPL (without SLIME), it displays:

```<code>(SB-INT:SIMPLE-EVAL-IN-LEXENV (BREAK) #<NULL-LEXENV>)
</code>```

However, if I do something wrong in the debugger, here's what happens:

```<code>0] q
; in: PROGN (PRINT 1)
;     (PROGN Q)
;
; caught WARNING:
;   undefined variable: COMMON-LISP-USER::Q
;
; compilation unit finished
;   Undefined variable:
;     Q
;   caught 1 WARNING condition

debugger invoked on a UNBOUND-VARIABLE in thread
#<THREAD "main thread" RUNNING {10005204C3}>:
  The variable Q is unbound.

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [CONTINUE   ] Retry using Q.
  1: [USE-VALUE  ] Use specified value.
  2: [STORE-VALUE] Set specified value and use it.
  3: [ABORT      ] Reduce debugger level (to debug level 1).
  4:               Return from BREAK.
  5:               Exit debugger, returning to top level.

((LAMBDA (#:G498)) #<unused argument>)
   source: (PROGN Q)
</code>```

You can see that the last line resembles the output you got with the line starting at source:. Actually, the output we saw consists of 3 main parts:
1. Description of the condition
2. Listing of the available restarts
3. Debug REPL prompt printed by debug-loop-fun

The last output is part of the prompt and it is generated by the invocation of:

```<code>(print-frame-call *current-frame* *debug-io* :print-frame-source t)
</code>```

So, you can recompile the call providing :print-frame-source nil or try to understand why your current frame looks this way...

Body:
The debugger can be programmatically invoked by executing (break). For example, the debugging banner then displays what caused the interrupt, the HELP line, the available restarts, some related info, and finally the source of the interrupt:

debugger invoked on a SIMPLE-CONDITION in thread
#<THREAD "main thread" RUNNING {10010B0523}>:
  break

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [CONTINUE] Return from BREAK.
  1: [ABORT   ] Exit debugger, returning to top level.

#(
NODE: STATE=<NIL NIL NIL 0.0 0.0
(         )> DEPTH=0)
#(
NODE: STATE=<NIL NIL NIL 0.0 0.0
((ACTIVE GATE1) (ACTIVE GATE2) (COLOR RECEIVER1 BLUE) (COLOR RECEIVER2 RED) (COLOR TRANSMITTER1 BLUE) (COLOR TRANSMITTER2 RED) (FREE ME) (LOC CONNECTOR1 AREA5) (LOC CONNECTOR2 AREA7) (LOC ME AREA5))> DEPTH=0)
(DF-BNB1 )
   source: (BREAK)
0]

I don't understand the related info between the restarts and the source. Can this info be suppressed, as
sometimes it is many lines long in my application. I've tried changing the debug & safety optimization settings, but to no effect.

Body:
The output you are confused with is related to the place in the code where break was invoked. When I call it from the vanilla Lisp REPL (without SLIME), it displays:

(SB-INT:SIMPLE-EVAL-IN-LEXENV (BREAK) #<NULL-LEXENV>)

However, if I do something wrong in the debugger, here's what happens:

0] q
; in: PROGN (PRINT 1)
;     (PROGN Q)
;
; caught WARNING:
;   undefined variable: COMMON-LISP-USER::Q
;
; compilation unit finished
;   Undefined variable:
;     Q
;   caught 1 WARNING condition

debugger invoked on a UNBOUND-VARIABLE in thread
#<THREAD "main thread" RUNNING {10005204C3}>:
  The variable Q is unbound.

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [CONTINUE   ] Retry using Q.
  1: [USE-VALUE  ] Use specified value.
  2: [STORE-VALUE] Set specified value and use it.
  3: [ABORT      ] Reduce debugger level (to debug level 1).
  4:               Return from BREAK.
  5:               Exit debugger, returning to top level.

((LAMBDA (#:G498)) #<unused argument>)
   source: (PROGN Q)

You can see that the last line resembles the output you got with the line starting at source:. Actually, the output we saw consists of 3 main parts:
1. Description of the condition
2. Listing of the available restarts
3. Debug REPL prompt printed by debug-loop-fun

The last output is part of the prompt and it is generated by the invocation of:

(print-frame-call *current-frame* *debug-io* :print-frame-source t)

So, you can recompile the call providing :print-frame-source nil or try to understand why your current frame looks this way...


问:
MappedBirthYear......ok, MappedBirthDay?? and MappedBirthMonth?
Greetings

I'm using MappedBirthYear in my signupXhtml

```<code>  object birth_year extends MappedBirthYear(this, 18) {
    //
  }
</code>```

based on the api

http://scala-tools.org/mvnsites/liftweb-2.2/framework/scaladocs/lift-persistence/lift-mapper/src/main/scala/net/liftweb/mapper/MappedUniqueId.scala.html#Some%2851%29

What options do I have to put birth_day and birth_month, to set the date: dd/mm/aaaa, in my signupXhtml

help me please

答:
```<code>object birth_month extends MappedInt(this) {  // adapted from MappedUniqueId.scala
  override def defaultValue = 1

  override def _toForm: Box[NodeSeq] = {
    val start = 1
    val end = 31
    Full(SHtml.selectObj((start to end).
          toList.
          map(y => (y, y.toString)),
          Full(is), this.set) % ("id" -> fieldId))
  }
}
</code>```

or you simply take a MappedDate…

Body:
Greetings

I'm using MappedBirthYear in my signupXhtml

  object birth_year extends MappedBirthYear(this, 18) {
    //
  }

based on the api

http://scala-tools.org/mvnsites/liftweb-2.2/framework/scaladocs/lift-persistence/lift-mapper/src/main/scala/net/liftweb/mapper/MappedUniqueId.scala.html#Some%2851%29

What options do I have to put birth_day and birth_month, to set the date: dd/mm/aaaa, in my signupXhtml

help me please

Body:
object birth_month extends MappedInt(this) {  // adapted from MappedUniqueId.scala
  override def defaultValue = 1

  override def _toForm: Box[NodeSeq] = {
    val start = 1
    val end = 31
    Full(SHtml.selectObj((start to end).
          toList.
          map(y => (y, y.toString)),
          Full(is), this.set) % ("id" -> fieldId))
  }
}

or you simply take a MappedDate…


问:
AWS Beanstalk: Exponential backoff for SQS?
We are using the worker tier on Beanstalk to send out webhooks. We need to use exponential backoff in case any error when contacting the third party. However, it is unclear to me how this would work.

If the job fails and I invoke a ChangeMessageVisibility to some increasing time backoff time I have two choices:

Return a success 200. Then SQS will remove it from the queue - not good.

Return an error code. Then SQS will override the message visibility to the default value?

From Environment Tiers - AWS Beanstalk:

A web application in a worker environment tier should only listen on
  the local host. When the web application in the worker environment
  tier returns a 200 OK response to acknowledge that it has received and
  successfully processed the request, the daemon sends a DeleteMessage
  call to the SQS queue so that the message will be deleted from the
  queue. (SQS automatically deletes messages that have been in a queue
  for longer than the configured RetentionPeriod.) If the application
  returns any response other than 200 OK, then Elastic Beanstalk waits
  to put the message back in the queue after the configured
  VisibilityTimeout period. If there is no response, then Elastic
  Beanstalk waits to put the message back in the queue after the
  InactivityTimeout period so that the message is available for another
  attempt at processing.

答:
There are pros and cons to increasing the ChangeMessageVisibility of a failing job:

Pros:

you wont loose the job in the process of removing it & requeuing it.

Cons:

the 12h limit for a job to be inflight.

you can only have 20k inflights job at a time

So one idea to mitigate the cons would be to setup a redrive policy to a dlq if the job fails too many times.


答:
The child is any widget that doesn't need the data inside of the provider, so when the data gets updated, they don't get re-created since they don't need the data, rather they are passed as a reference to the builder.

```<code>
    Consumer(
       builder: (context, myModel, child) {
       // child will refer to the MaterialButton provided as the child argument in the
       // Consumer named parameter,
       // doing stuff using myModel variable
       }
       child: MaterialButton(
              child: Text("Do some action"),
              onPressed: () {
              // do some actions
    },),);
</code>```

Since the MaterialButton doesn't need the state of the provider, but its in the descendant tree, there is no need to re-render that, so it gets passed back to the builder, to save memory and increase performance

Title: What is the purpose of child in Consumer Provider Flutter

Body:
The child is any widget that doesn't need the data inside of the provider, so when the data gets updated, they don't get re-created since they don't need the data, rather they are passed as a reference to the builder.

    Consumer(
       builder: (context, myModel, child) {
       // child will refer to the MaterialButton provided as the child argument in the
       // Consumer named parameter,
       // doing stuff using myModel variable
       }
       child: MaterialButton(
              child: Text("Do some action"),
              onPressed: () {
              // do some actions
    },),);

Since the MaterialButton doesn't need the state of the provider, but its in the descendant tree, there is no need to re-render that, so it gets passed back to the builder, to save memory and increase performance


问:
API calls fail with Rate limit exceeded in OneLogin
I am trying to make a API call to Onelogin (which is a third-party identity platform), it fails with "Rate limit exceeded", after 5000 request. How can I increase the request or reset the counter?</p>

答:
There is an account level rate limit of 5,000 calls per hour regardless of how many access tokens you have. If an access token surpasses this limit, API calls will return an error. After the hour has passed, the count will be reset to a full 5,000 available calls.

https://developers.onelogin.com/api-docs/1/oauth20-tokens/get-rate-limit


问:
How to develop responsive layer container in Leaflet?
I'm using leaflet.js to develop a drawing layer tool with the full-page map. Users will draw a group of layers to describe an industrial product's parts.

The leaflet map and its layers should be fit to screen. For example, if a user draws a circle to the left bottom corner with 1920x1080 resolution pc, I should see it in the left bottom corner with my 1366x768 resolution pc. The leaflet map is resizing with the page correctly but the circle is being out of the screen in my pc because of its latitude-longitude in this example.

I tried to develop this example with invalidateSize, maxBounds, fitBounds, etc. but haven't succeeded yet. How can I develop this scenario?

Saved GeoJSON from 1920x1080 with layers looking:

Loaded same GeoJSON from 1366x768 looking (attention to left corner):

Map (React):

```<code>  const corner1 = L.latLng(-180, -180);
  const corner2 = L.latLng(180, 180);
  const bounds = L.latLngBounds(corner1, corner2);

        <Map
        ref={map => {
          this.tryToCreate(map);
        }}
        className="c-leaflet-map-map"
        center={[0, 0]}
        zoom={0}
        maxZoom={10}
        zoomControl={false}
        onzoomend={this.zoomLevelsChange}
        maxBounds={bounds}
        maxBoundsViscosity={1.0}
        zoomSnap={0}
        crs={L.CRS.Simple}
      >
        <ImageOverlay
          bounds={map.backgroundImageBounds || map.bounds}
          attribution="&copy TofnaTech"
          url={
            map.backgroundImage ||
            map.backgroundImageURL ||
            TransparentImage
          }
          opacity={map.opacity}
          className={cn({ transparentImage: !map.backgroundImage })}
        />
        <FeatureGroup
          ref={controller => {
            this.controller = controller;
            this.tryToCreate();
          }}
        >
          <EditControl
            position="topleft"
            onCreated={this._onCreated}
            onEditStart={this.onEditStart}
            onEditStop={this.onEditStop}
            onEdited={this.onEdited}
            draw={{
              polyline: false,
              polygon: {
                shapeOptions: { ...defaultShapeOptions }
              },
              rectangle: {
                shapeOptions: { ...defaultShapeOptions }
              },
              circle: {
                shapeOptions: { ...defaultShapeOptions }
              },
              marker: false,
              circlemarker: false
            }}
            edit={{
              remove: false
            }}
          /></Map>
</code>```

答:
Using React-Leaflet is a little different.  You can accomplish what you're trying to do in componentDidMount, where you can make a reference to your map and then call fitBounds on that.

Edit: Adding the rectangle

However, the next issue is resolution.  Leaflet will maintain the aspect ratio so you actually need to render your circle (or rectangle)in the corner dynamically if you always want it to show up in the bottom left corner of the screen regardless of the aspect ratio of the screen and browser.  So in componentDidMount, just after you set the new bounds, you can get those bounds, and define a rectangle (or anything) to always render in the same spot relative to say, the getBounds()._southWest bound.  In this code I wrapped this code in a setTimeout because the animation takes a moment and that moment needs to pass to get the new bounds values from getBounds().  I'm sure there's a way to reduce or remove that animation time.

To keep the rectangle in the same spot, I wrote a onMove function for the map to always recalculate the position regardless of moving the map around or resizing the window.

Note that the size of the rectangle is a little slapdash in this example, but I think you'll have an easier time getting a consistent size using CRS, as CRS is a lot more uniform than lats and lngs.

class Map extends React.Component {

  state = {
    rectCoords: null
  };

  componentDidMount() {
    const map = this.mapReference.leafletElement;
    window.map = map;
    console.log("Initiates with bounds:", map.getBounds());

    map.fitBounds([[32.852169, -90.5322], [33.852169, -85.5322]]);

    setTimeout(() => {
      console.log("Bounds immediately reset to", map.getBounds());

      const rectCoords = [
        [
          map.getBounds()._southWest.lat + 0.1,
          map.getBounds()._southWest.lng + 0.1
        ],
        [
          map.getBounds()._southWest.lat + 1,
          map.getBounds()._southWest.lng + 1
        ]
      ];

      this.setState({ rectCoords });
    }, 500);
  }

  onMapmove = () => {
    const map = this.mapReference.leafletElement;
    const rectCoords = [
      [
        map.getBounds()._southWest.lat + 0.1,
        map.getBounds()._southWest.lng + 0.1
      ],
      [map.getBounds()._southWest.lat + 1, map.getBounds()._southWest.lng + 1]
    ];

    this.setState({ rectCoords });
  }

  render() {

    return (
      <LeafletMap
        ref={mapReference => this.mapReference = mapReference}
        zoom={4}
        center={[33.852169, -100.5322]}
        onMove={() => this.onMapmove() } >

        <TileLayer ... />

        {this.state.rectCoords && (
          <Rectangle
            bounds={this.state.rectCoords}
            color={"#ff7800"}
            weight={1}
          />
        )}

      </LeafletMap>
    );

  }

}
```

So even though the map initiates with certain bounds, it immediately fits it to your desired bounds, and renders the rectangle always in the bottom left corner in the same spot.

Here is a working codesandbox.  I'm sure this can be adapted to using CRS Simple as well.

Body:
I'm using leaflet.js to develop a drawing layer tool with the full-page map. Users will draw a group of layers to describe an industrial product's parts.

The leaflet map and its layers should be fit to screen. For example, if a user draws a circle to the left bottom corner with 1920x1080 resolution pc, I should see it in the left bottom corner with my 1366x768 resolution pc. The leaflet map is resizing with the page correctly but the circle is being out of the screen in my pc because of its latitude-longitude in this example.

I tried to develop this example with invalidateSize, maxBounds, fitBounds, etc. but haven't succeeded yet. How can I develop this scenario?

Saved GeoJSON from 1920x1080 with layers looking:

Loaded same GeoJSON from 1366x768 looking (attention to left corner):

Map (React):

  const corner1 = L.latLng(-180, -180);
  const corner2 = L.latLng(180, 180);
  const bounds = L.latLngBounds(corner1, corner2);

        <Map
        ref={map => {
          this.tryToCreate(map);
        }}
        className="c-leaflet-map-map"
        center={[0, 0]}
        zoom={0}
        maxZoom={10}
        zoomControl={false}
        onzoomend={this.zoomLevelsChange}
        maxBounds={bounds}
        maxBoundsViscosity={1.0}
        zoomSnap={0}
        crs={L.CRS.Simple}
      >
        <ImageOverlay
          bounds={map.backgroundImageBounds || map.bounds}
          attribution="&copy TofnaTech"
          url={
            map.backgroundImage ||
            map.backgroundImageURL ||
            TransparentImage
          }
          opacity={map.opacity}
          className={cn({ transparentImage: !map.backgroundImage })}
        />
        <FeatureGroup
          ref={controller => {
            this.controller = controller;
            this.tryToCreate();
          }}
        >
          <EditControl
            position="topleft"
            onCreated={this._onCreated}
            onEditStart={this.onEditStart}
            onEditStop={this.onEditStop}
            onEdited={this.onEdited}
            draw={{
              polyline: false,
              polygon: {
                shapeOptions: { ...defaultShapeOptions }
              },
              rectangle: {
                shapeOptions: { ...defaultShapeOptions }
              },
              circle: {
                shapeOptions: { ...defaultShapeOptions }
              },
              marker: false,
              circlemarker: false
            }}
            edit={{
              remove: false
            }}
          /></Map>

Body:
Using React-Leaflet is a little different.  You can accomplish what you're trying to do in componentDidMount, where you can make a reference to your map and then call fitBounds on that.

Edit: Adding the rectangle

However, the next issue is resolution.  Leaflet will maintain the aspect ratio so you actually need to render your circle (or rectangle)in the corner dynamically if you always want it to show up in the bottom left corner of the screen regardless of the aspect ratio of the screen and browser.  So in componentDidMount, just after you set the new bounds, you can get those bounds, and define a rectangle (or anything) to always render in the same spot relative to say, the getBounds()._southWest bound.  In this code I wrapped this code in a setTimeout because the animation takes a moment and that moment needs to pass to get the new bounds values from getBounds().  I'm sure there's a way to reduce or remove that animation time.

To keep the rectangle in the same spot, I wrote a onMove function for the map to always recalculate the position regardless of moving the map around or resizing the window.

Note that the size of the rectangle is a little slapdash in this example, but I think you'll have an easier time getting a consistent size using CRS, as CRS is a lot more uniform than lats and lngs.

class Map extends React.Component {

  state = {
    rectCoords: null
  };

  componentDidMount() {
    const map = this.mapReference.leafletElement;
    window.map = map;
    console.log("Initiates with bounds:", map.getBounds());

    map.fitBounds([[32.852169, -90.5322], [33.852169, -85.5322]]);

    setTimeout(() => {
      console.log("Bounds immediately reset to", map.getBounds());

      const rectCoords = [
        [
          map.getBounds()._southWest.lat + 0.1,
          map.getBounds()._southWest.lng + 0.1
        ],
        [
          map.getBounds()._southWest.lat + 1,
          map.getBounds()._southWest.lng + 1
        ]
      ];

      this.setState({ rectCoords });
    }, 500);
  }

  onMapmove = () => {
    const map = this.mapReference.leafletElement;
    const rectCoords = [
      [
        map.getBounds()._southWest.lat + 0.1,
        map.getBounds()._southWest.lng + 0.1
      ],
      [map.getBounds()._southWest.lat + 1, map.getBounds()._southWest.lng + 1]
    ];

    this.setState({ rectCoords });
  }

  render() {

    return (
      <LeafletMap
        ref={mapReference => this.mapReference = mapReference}
        zoom={4}
        center={[33.852169, -100.5322]}
        onMove={() => this.onMapmove() } >

        <TileLayer ... />

        {this.state.rectCoords && (
          <Rectangle
            bounds={this.state.rectCoords}
            color={"#ff7800"}
            weight={1}
          />
        )}

      </LeafletMap>
    );

  }

}

So even though the map initiates with certain bounds, it immediately fits it to your desired bounds, and renders the rectangle always in the bottom left corner in the same spot.

Here is a working codesandbox.  I'm sure this can be adapted to using CRS Simple as well.


问:
How to disable a user from firebase?
In the firebase API

```<code>https://firebase.google.com/docs/auth/web/manage-users
</code>```

we can delete users, but how could we prevent users from simply registering again, in the GUI for firebase we have the option to disable users , how could we do this in the program, for example if we are building a admin panel that checks posts for a listing site that have been reported, and we want to disable the creator or the reporter for spamming as part of availiable actions.

Thanks.

I develop in react if that changes the answer.

答: You will not be able to programmatically disable a user from the frontend of your app.  You will need a backend, and use the Firebase Admin SDK to update the user account to become disabled.  The API is updateUser.</p>

Title: How to disable a user from firebase?

Body:
In the firebase API

https://firebase.google.com/docs/auth/web/manage-users

we can delete users, but how could we prevent users from simply registering again, in the GUI for firebase we have the option to disable users , how could we do this in the program, for example if we are building a admin panel that checks posts for a listing site that have been reported, and we want to disable the creator or the reporter for spamming as part of availiable actions.

Thanks.

I develop in react if that changes the answer.


问:
Why the CPU usage of a GKE Workload is not equal to the sum of the CPU usage of its pods?
I'm trying to figure out why a GKE "Workload" CPU usage is not equivalent to the sum of cpu usage of its pods.

Following image shows a Workload CPU usage.

Service Workload CPU Usage

Following images show pods CPU usage for the above Workload.

Pod #1 CPU Usage

Pod #2 CPU Usage

For example, at 9:45, the Workload cpu usage was around 3.7 cores, but at the same time Pod#1 CPU usage was around 0.9 cores and Pod#2 CPU usage was around 0.9 cores too. It means, the service Workload CPU Usage should have been around 1.8 cores, but it wasn't.

Does anyone have an idea of this behavior?

Thanks.

答:
On your VM, the node managed by Kubernetes, you have the deployed pods (that you manage) but also several services that run on it for the supervision, the management, the logs ingestion,... A basic description here

You can see all these basic services by performing this command kubctl get all --namespace kube-system.

If you have installed additional components, like Istio or Knative, you have additional services and namespaces. All of these get a part of the resources of the node.


问:
Concise way to check nested pointer struct for nil in Go?
I have a nested struct coming from JSON. This struct has many optional properties and to successfully walk it, I need to check if properties exist. When properties are defined as pointer structs, it becomes very inconvenient: I have to instantiate an empty type and compare it using reflect.DeepEqual.

Is there more concise way to do this?

Example:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func unmarshalNested(data []byte) (nested, error) {
    var r nested
    err := json.Unmarshal(data, &r)
    return r, err
}

type nested struct {
    Alfa alfa `json:"alfa"`
}

type alfa struct {
    Bravo *bravo `json:"bravo,omitempty"`
}

type bravo struct {
    Charlie string `json:"charlie"`
}

func main() {

    json := `
{
    "alfa": {
        "bravo": {
            "charlie": "foobar"
        }
    }
}
`
    /*
        json := "{"alfa": {}}
    */

    n := nested{}
    n, _ = unmarshalNested([]byte(json))

    fmt.Println("-- Alfa --")
    fmt.Printf("  %+v\n", n)

    fmt.Println("-- *Bravo --")

    var b *bravo = nil
    if reflect.DeepEqual(b, n.Alfa.Bravo) {
        fmt.Println("  nil")
    } else {
        fmt.Printf("  %+v\n", n.Alfa.Bravo)
    }
}
```

答:
You can compare any pointer value to nil, no need reflection:

```<code>if n.Alpha.Bravo == nil {
    fmt.Println("  nil")
} else {
    fmt.Printf("  %+v\n", n.Alfa.Bravo)
}
</code>```

Body:
You can compare any pointer value to nil, no need reflection:

if n.Alpha.Bravo == nil {
    fmt.Println("  nil")
} else {
    fmt.Printf("  %+v\n", n.Alfa.Bravo)
}