问:
In Ruby, can you decide from a main method to return or continue when calling a submethod?
I'm using Pundit gem for my authorization classes, where each controller action is checked against the model policy, to see if action is allowed by the user.

These methods are sometimes becoming quite bloated and unreadable, because I'm checking quite some stuff for some objects.

Now I'm thinking to refactor those methods, and place every "validation" in it's own method:

Previous:

```<code>class PostPolicy < ApplicationPolicy

 def update
   return true if @user.has_role? :admin
   return true if @object.owner == user
   return true if 'some other reason'

   false
 end
end
</code>```

Now ideally, I want to refactor this in something like:

```<code>class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin
   allow_if_user_owns_record
   allow_for_some_other_reason

   false
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end
</code>```

The problem now is, that the mane update method will keep on going, even if the user is admin, as there's no return. If I would inlcude a return, then the other methods will never be evalutaed. Is there a way in ruby to do kind of a "superreturn", so that when the user is an admin, the main update method would stop evaluting?

Thanks!

答:
Given your example and this comment: "...no native way to do kind of a 'super return' in Ruby? It feels like kind of a "raise" but then with a positive outcome... could I use that perhaps?".

While there are usually other ways to solve the issue that could be considered "more idiomatic", ruby does have a Kernel#throw and Kernel#catch implementation that can be very useful for control flow when navigating through numerous and possibly disparate methods and operations.

The throw and corresponding catch will short circuit the result of the block which appears to be the syntax you are looking for.

VERY Basic Example:

```<code>class PostPolicy
  def initialize(n)
    @n = n
  end
  def update
    catch(:fail) do
      stop_bad_actor!
      catch(:success) do
        allow_if_user_is_admin
        allow_if_user_owns_record
        stop_bad_actor!(2)
        allow_for_some_other_reason
        false
      end
    end
  end

 private

  def allow_if_user_is_admin
   puts "Is User Admin?"
   throw(:success, true) if @n == 1
  end

  def allow_if_user_owns_record
    puts "Is User Owner?"
    throw(:success,true) if @n == 2
  end

  def allow_for_some_other_reason
    puts "Is User Special?"
    throw(:success,true) if @n == 3
  end

  def stop_bad_actor!(m=1)
    puts "Is a Bad Actor?"
    throw(:fail, false) if @n == 6 || @n ** m == 64
  end
end
</code>```

Example Output:

```<code>PostPolicy.new(1).update
# Is a Bad Actor?
# Is User Admin?
#=> true
PostPolicy.new(2).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
#=> true
PostPolicy.new(3).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
# Is a Bad Actor?
# Is User Special?
#=> true
PostPolicy.new(4).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
# Is a Bad Actor?
# Is User Special?
#=> false
PostPolicy.new(6).update
# Is a Bad Actor?
#=> false
PostPolicy.new(8).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
# Is a Bad Actor?
#=> false
</code>```

Body:
I'm using Pundit gem for my authorization classes, where each controller action is checked against the model policy, to see if action is allowed by the user.

These methods are sometimes becoming quite bloated and unreadable, because I'm checking quite some stuff for some objects.

Now I'm thinking to refactor those methods, and place every "validation" in it's own method:

Previous:

class PostPolicy < ApplicationPolicy

 def update
   return true if @user.has_role? :admin
   return true if @object.owner == user
   return true if 'some other reason'

   false
 end
end

Now ideally, I want to refactor this in something like:

class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin
   allow_if_user_owns_record
   allow_for_some_other_reason

   false
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end

The problem now is, that the mane update method will keep on going, even if the user is admin, as there's no return. If I would inlcude a return, then the other methods will never be evalutaed. Is there a way in ruby to do kind of a "superreturn", so that when the user is an admin, the main update method would stop evaluting?

Thanks!

Body:
Given your example and this comment: "...no native way to do kind of a 'super return' in Ruby? It feels like kind of a "raise" but then with a positive outcome... could I use that perhaps?".

While there are usually other ways to solve the issue that could be considered "more idiomatic", ruby does have a Kernel#throw and Kernel#catch implementation that can be very useful for control flow when navigating through numerous and possibly disparate methods and operations.

The throw and corresponding catch will short circuit the result of the block which appears to be the syntax you are looking for.

VERY Basic Example:

class PostPolicy
  def initialize(n)
    @n = n
  end
  def update
    catch(:fail) do
      stop_bad_actor!
      catch(:success) do
        allow_if_user_is_admin
        allow_if_user_owns_record
        stop_bad_actor!(2)
        allow_for_some_other_reason
        false
      end
    end
  end

 private

  def allow_if_user_is_admin
   puts "Is User Admin?"
   throw(:success, true) if @n == 1
  end

  def allow_if_user_owns_record
    puts "Is User Owner?"
    throw(:success,true) if @n == 2
  end

  def allow_for_some_other_reason
    puts "Is User Special?"
    throw(:success,true) if @n == 3
  end

  def stop_bad_actor!(m=1)
    puts "Is a Bad Actor?"
    throw(:fail, false) if @n == 6 || @n ** m == 64
  end
end

Example Output:

PostPolicy.new(1).update
# Is a Bad Actor?
# Is User Admin?
#=> true
PostPolicy.new(2).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
#=> true
PostPolicy.new(3).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
# Is a Bad Actor?
# Is User Special?
#=> true
PostPolicy.new(4).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
# Is a Bad Actor?
# Is User Special?
#=> false
PostPolicy.new(6).update
# Is a Bad Actor?
#=> false
PostPolicy.new(8).update
# Is a Bad Actor?
# Is User Admin?
# Is User Owner?
# Is a Bad Actor?
#=> false


来源: stackexchange

问:
How do I link to a static library (libtiff) using CMake in my wxWidgets project?
For my wxWidgets project, I am trying to make the switch from my self-written Makefile to Cmake. I develop on macOS.

When I was writing that Makefile I ran into an issue with libtiff. I wanted to statically link my application so that I don't have to distribute any dylibs myself or rely on my users to install them. I built wxWidgets as a static library but when I compiled my code and checked my binary with otool I always found that my binary required a local dylib.

```<code>/usr/local/opt/libtiff/lib/libtiff.5.dylib
</code>```

Finally I found a solution on here. In essence, in the linking line of my Makefile I replaced wx-config –-libs with LDFLAGS. LDFLAGS looks like this:

```<code>WXCONFIGLIBS := $(shell wx-config --libs)
WXCONFIGLIBS := $(WXCONFIGLIBS:-ltiff=/usr/local/opt/libtiff//lib/libtiff.a)
# I am not sure whether the double slash is a typo but it works so I don't change it
LDFLAGS := $(WXCONFIGLIBS)
</code>```

Basically, I search-and-replaced -ltiff with the path to my static libtiff library.

Now I've managed to compile my project using Cmake. However, I'm getting the same warning message as I did when I battled my original issue.

```<code>ld: warning: dylib (/usr/local/lib/libtiff.dylib) was built for newer macOS version (11.0) than being linked (10.11)
</code>```

How do I fix this? My CMakeLists contains these sections pertaining to wxWidgets:

```<code>find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
...
add_executable(myapp ${SOURCES})
target_link_libraries(myapp ${wxWidgets_LIBRARIES})
set_property(TARGET myapp PROPERTY CXX_STANDARD 17)
</code>```

I already tried running some search-and-replace shenanigans like

```<code>string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})
</code>```

But that doesn't work. It does replace -ltiff but also seems to remove the semicolons and whitespaces separating the different libraries.

I've been scouring the web for any clues as to what to do, but I don't seem to have a good enough grasp of libraries to fix this.

Any help would be greatly appreciated.

答:
Set wxWidgets_USE_STATIC=ON before calling find_package(wxWidgets). See the documentation for wxWidgets here: https://cmake.org/cmake/help/latest/module/FindwxWidgets.html

```<code>option(wxWidgets_USE_STATIC "Link to wxWidgets statically" ON)

find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
...
add_executable(myapp ${SOURCES})
target_link_libraries(myapp PRIVATE ${wxWidgets_LIBRARIES})
target_compile_features(myapp PRIVATE cxx_std_17)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For my wxWidgets project, I am trying to make the switch from my self-written Makefile to Cmake. I develop on macOS.

When I was writing that Makefile I ran into an issue with libtiff. I wanted to statically link my application so that I don't have to distribute any dylibs myself or rely on my users to install them. I built wxWidgets as a static library but when I compiled my code and checked my binary with otool I always found that my binary required a local dylib.

/usr/local/opt/libtiff/lib/libtiff.5.dylib

Finally I found a solution on here. In essence, in the linking line of my Makefile I replaced wx-config –-libs with LDFLAGS. LDFLAGS looks like this:

WXCONFIGLIBS := $(shell wx-config --libs)
WXCONFIGLIBS := $(WXCONFIGLIBS:-ltiff=/usr/local/opt/libtiff//lib/libtiff.a)
# I am not sure whether the double slash is a typo but it works so I don't change it
LDFLAGS := $(WXCONFIGLIBS)

Basically, I search-and-replaced -ltiff with the path to my static libtiff library.

Now I've managed to compile my project using Cmake. However, I'm getting the same warning message as I did when I battled my original issue.

ld: warning: dylib (/usr/local/lib/libtiff.dylib) was built for newer macOS version (11.0) than being linked (10.11)

How do I fix this? My CMakeLists contains these sections pertaining to wxWidgets:

find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
...
add_executable(myapp ${SOURCES})
target_link_libraries(myapp ${wxWidgets_LIBRARIES})
set_property(TARGET myapp PROPERTY CXX_STANDARD 17)

I already tried running some search-and-replace shenanigans like

string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})

But that doesn't work. It does replace -ltiff but also seems to remove the semicolons and whitespaces separating the different libraries.

I've been scouring the web for any clues as to what to do, but I don't seem to have a good enough grasp of libraries to fix this.

Any help would be greatly appreciated.

Body:
Set wxWidgets_USE_STATIC=ON before calling find_package(wxWidgets). See the documentation for wxWidgets here: https://cmake.org/cmake/help/latest/module/FindwxWidgets.html

option(wxWidgets_USE_STATIC "Link to wxWidgets statically" ON)

find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
...
add_executable(myapp ${SOURCES})
target_link_libraries(myapp PRIVATE ${wxWidgets_LIBRARIES})
target_compile_features(myapp PRIVATE cxx_std_17)


问:
Best way to loop through a filtered pandas Dataframe
I need to loop through a pandas DataFrame, but first I have to filter it. I need to look at how many "old_id"s are attached to each new ID.

I wrote this code and is working fine, but it doesn't scale really well.

```<code>d = dict()

for new_id in (new_id_list):

    d[new_id] = df[df['new_id_col'] == new_id]['old_id'].nunique()
</code>```

How can I make this more efficient?

答:
Looks like you're looking for groupby + nunique. This fetches the number of unique "old_id"s per "new_id_col":

```<code>out = df.groupby('new_id_col')['old_id'].nunique().to_dict()
</code>```

Body:
I need to loop through a pandas DataFrame, but first I have to filter it. I need to look at how many "old_id"s are attached to each new ID.

I wrote this code and is working fine, but it doesn't scale really well.

d = dict()

for new_id in (new_id_list):

    d[new_id] = df[df['new_id_col'] == new_id]['old_id'].nunique()

How can I make this more efficient?

Body:
Looks like you're looking for groupby + nunique. This fetches the number of unique "old_id"s per "new_id_col":

out = df.groupby('new_id_col')['old_id'].nunique().to_dict()


问:
How to wait for future inside Kafka Stream map()?
I am implementing Spring Boot application in Java, using Spring Cloud Stream with Kafka Streams binder.

I need to implement blocking operation inside of KStream map method like so:

public Consumer<KStream<?, ?>> sink() {
    return input -> input
        .mapValues(value -> methodReturningCompletableFuture(value).get())
        .foreach((key, value) -> otherMethod(key, value));
}
```

completableFuture.get() throws exceptions (InterruptedException, ExecutionException)

How to handle these exceptions so that the chained method doesn't get executed and the Kafka message is not acknowledged? I cannot afford message loss, sending it to a dead letter topic is not an option.

Is there a better way of blocking inside map()?

答:
You can try the branching feature in Kafka Streams to control the execution of the chained methods. For example, here is a pseudo-code that you can try.
You can possibly use this as a starting point and adapt this to your particular use case.

```<code>final Map<String, ? extends KStream<?, String>> branches =
input.split()
     .branch(k, v) -> {
        try {
          methodReturningCompletableFuture(value).get();
          return true;
        }
        catch (Exception e) {
          return false;
        }
      }, Branched.as("good-records"))
      .defaultBranch();

final KStream<?, String> kStream = branches.get("good-records");

 kStream.foreach((key, value) -> otherMethod(key, value));
</code>```

The idea here is that you will only send the records that didn't throw an exception to the named branch good-records, everything else goes into a default branch which we simply ignore in this pseudo-code. Then you invoke additional chained methods (as this foreach call shows) only for those "good" records.

This does not solve the problem of not acknowledging the message after an exception is thrown. That seems to be a bit challenging. However, I am curious about that use case. When an exception happens and you handle it, why don't you want to ack the message? The requirements seem to be a bit rigid without using a DLT. The ideal solution here is that you might want to introduce some retries and once exhausted from the retries, send the record to a DLT which makes Kafka Streams consumer acknowledges the message. Then the application moves on to the next offset.

The call methodReturningCompletableFuture(value).get() simply waits until a default or configured timeout is reached, assuming that methodReturningCompletableFuture() returns a Future object. Therefore, that is already a good approach to wait inside the KStream map operation. I don't think anything else is necessary to make it wait further.

Body:
I am implementing Spring Boot application in Java, using Spring Cloud Stream with Kafka Streams binder.

I need to implement blocking operation inside of KStream map method like so:

public Consumer<KStream<?, ?>> sink() {
    return input -> input
        .mapValues(value -> methodReturningCompletableFuture(value).get())
        .foreach((key, value) -> otherMethod(key, value));
}

completableFuture.get() throws exceptions (InterruptedException, ExecutionException)

How to handle these exceptions so that the chained method doesn't get executed and the Kafka message is not acknowledged? I cannot afford message loss, sending it to a dead letter topic is not an option.

Is there a better way of blocking inside map()?

Body:
You can try the branching feature in Kafka Streams to control the execution of the chained methods. For example, here is a pseudo-code that you can try.
You can possibly use this as a starting point and adapt this to your particular use case.

final Map<String, ? extends KStream<?, String>> branches =
input.split()
     .branch(k, v) -> {
        try {
          methodReturningCompletableFuture(value).get();
          return true;
        }
        catch (Exception e) {
          return false;
        }
      }, Branched.as("good-records"))
      .defaultBranch();

final KStream<?, String> kStream = branches.get("good-records");

 kStream.foreach((key, value) -> otherMethod(key, value));

The idea here is that you will only send the records that didn't throw an exception to the named branch good-records, everything else goes into a default branch which we simply ignore in this pseudo-code. Then you invoke additional chained methods (as this foreach call shows) only for those "good" records.

This does not solve the problem of not acknowledging the message after an exception is thrown. That seems to be a bit challenging. However, I am curious about that use case. When an exception happens and you handle it, why don't you want to ack the message? The requirements seem to be a bit rigid without using a DLT. The ideal solution here is that you might want to introduce some retries and once exhausted from the retries, send the record to a DLT which makes Kafka Streams consumer acknowledges the message. Then the application moves on to the next offset.

The call methodReturningCompletableFuture(value).get() simply waits until a default or configured timeout is reached, assuming that methodReturningCompletableFuture() returns a Future object. Therefore, that is already a good approach to wait inside the KStream map operation. I don't think anything else is necessary to make it wait further.


问:
How to know the number of characters in utf8 string
i want to know is there a simple way to determine the number of characters in UTF8 string.
For example, in windows it can be done by:

converting UTF8 string to wchar_t string

use wcslen function and get result

But I need more simpler and crossplatform solution.

Thanks in advance.

答:
The entire concept of a "number of characters" does not really apply to Unicode, as codes do not map 1:1 to glyphs. The method proposed by @borrible is fine if you want to establish storage requirements in uncompressed form, but that is all that it can tell you.

For example, there are code points like the "zero width space", which do not take up space on the screen when rendered, but occupy a code point, or modifiers for diacritics or vowels. So any statistic would have to be specific to the concrete application.

A proper Unicode renderer will have a function that can tell you how many pixels will be used for rendering a string if that information is what you're after.

ContentLicense: CC BY-SA 3.0


问:
Android build.gradle ERROR: ParseError at [row,col]:[65,9] Message: expected start or end tag Affected Modules: app
build.gradle:

Android build.gradle shows following error

```<code>ERROR: ParseError at [row,col]:[65,9] Message: expected start or end tag Affected Modules: app
</code>```

答:
It seems like those kind of errors are general and even if they pinpoint the location of the error, they don't mention in which file the error occurs.

A good way to resolve this error is to check inside the latest .xml files you modified.

Body:
build.gradle:

Android build.gradle shows following error

ERROR: ParseError at [row,col]:[65,9] Message: expected start or end tag Affected Modules: app


问:
html2canvas doesn't capture the whole
 with bootstrap
I'm working on building a meme generator web app using bootstrap to make the web page responsive.

Here is the image that supposed to be captured (works well on phone screens):

The image that I usually get (happens on PC screens) It's a white image:

here is my html code for the div that I need to capture:

```<code><div class="container">
    <div id="theUserMeme">

        <div class="row">

            <p id="memeWords">
                When I see something lol

            </p>

        </div>

        <div class="row">
            <img id = "memeImage" src="images/init meme.jpg">
        </div>

    </div>
</div>
</code>```

Also, this is my JavaScript function that is called when the button is clicked to capture the div:

```<code>function generateMeme(){

    window.scrollTo(0,0);

    html2canvas(document.querySelector("#theUserMeme")).then(canvas => {

        var image = canvas.toDataURL('image/jpeg', 1);
        console.log(image);

        alert(image);

        document.getElementById("finalImageCopy").src = image;
    });

}
</code>```

Why this happens depending on the size of the screen? What should I do to make it working in every screen size? If bootstrap is not a good choice for html2canvas, what should be better?

答:
for external images try using  useCORS: true,
enter link description here

Title: html2canvas doesn't capture the whole <div> with bootstrap

Body:
I'm working on building a meme generator web app using bootstrap to make the web page responsive.

Here is the image that supposed to be captured (works well on phone screens):

The image that I usually get (happens on PC screens) It's a white image:

here is my html code for the div that I need to capture:

                When I see something lol

Also, this is my JavaScript function that is called when the button is clicked to capture the div:

function generateMeme(){

    window.scrollTo(0,0);

    html2canvas(document.querySelector("#theUserMeme")).then(canvas => {

        var image = canvas.toDataURL('image/jpeg', 1);
        console.log(image);

        alert(image);

        document.getElementById("finalImageCopy").src = image;
    });

}

Why this happens depending on the size of the screen? What should I do to make it working in every screen size? If bootstrap is not a good choice for html2canvas, what should be better?


问:
How to read json response string into Document object of Document AI from java?
I'm working with another API which calls the google Document AI API. I'm trying to read the JSON String from the file into a Document object. How should this be done?

I tried the following but it is not working.

```<code>import com.google.cloud.documentai.v1.Document;
import java.io.FileInputStream;

Document document = Document.parseFrom(new FileInputStream("src/main/resources/responseFromAPICall.json"));
System.out.println(document.getText());
</code>```

I'm getting this error:

```<code>Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
    at com.google.protobuf.InvalidProtocolBufferException.invalidEndTag(InvalidProtocolBufferException.java:129)
    at com.google.protobuf.CodedInputStream$StreamDecoder.checkLastTagWas(CodedInputStream.java:2124)
    at com.google.protobuf.CodedInputStream$StreamDecoder.readGroup(CodedInputStream.java:2358)
</code>```

答:
Today I came across this issue as well. This answer gave me the starting point for a solution.

If your json file was saved from a call to Document AI and looks like:

{
  "document": {
    ...
    "text": "...",
    ...
  },
  "humanReviewStatus": {...}
}
```
<p>you may use the following code snippet:</p>
<pre class="lang-java prettyprint-override"><code>import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.protobuf.util.JsonFormat;

Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");
ProcessResponse.Builder responseBuilder = ProcessResponse.newBuilder();
JsonFormat.parser().merge(Files.newBufferedReader(filePath), responseBuilder);
Document document = responseBuilder.getDocument();
System.out.println(document.getText());
</code>```

If your json file only contains the "document" object:

{
  ...
  "text": "...",
  ...
}
```
<p>This code will do the trick:</p>
<pre class="lang-java prettyprint-override"><code>import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.cloud.documentai.v1.Document;
import com.google.protobuf.util.JsonFormat;

Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");
Document.Builder docBuilder = Document.newBuilder();
JsonFormat.parser().merge(Files.newBufferedReader(filePath), docBuilder);
System.out.println(docBuilder.getText());
</code>```

Body:
I'm working with another API which calls the google Document AI API. I'm trying to read the JSON String from the file into a Document object. How should this be done?

I tried the following but it is not working.

import com.google.cloud.documentai.v1.Document;
import java.io.FileInputStream;

Document document = Document.parseFrom(new FileInputStream("src/main/resources/responseFromAPICall.json"));
System.out.println(document.getText());

I'm getting this error:

Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
    at com.google.protobuf.InvalidProtocolBufferException.invalidEndTag(InvalidProtocolBufferException.java:129)
    at com.google.protobuf.CodedInputStream$StreamDecoder.checkLastTagWas(CodedInputStream.java:2124)
    at com.google.protobuf.CodedInputStream$StreamDecoder.readGroup(CodedInputStream.java:2358)

Body:
Today I came across this issue as well. This answer gave me the starting point for a solution.

If your json file was saved from a call to Document AI and looks like:

{
  "document": {
    ...
    "text": "...",
    ...
  },
  "humanReviewStatus": {...}
}

you may use the following code snippet:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.protobuf.util.JsonFormat;

Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");
ProcessResponse.Builder responseBuilder = ProcessResponse.newBuilder();
JsonFormat.parser().merge(Files.newBufferedReader(filePath), responseBuilder);
Document document = responseBuilder.getDocument();
System.out.println(document.getText());

If your json file only contains the "document" object:

{
  ...
  "text": "...",
  ...
}

This code will do the trick:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.cloud.documentai.v1.Document;
import com.google.protobuf.util.JsonFormat;

Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");
Document.Builder docBuilder = Document.newBuilder();
JsonFormat.parser().merge(Files.newBufferedReader(filePath), docBuilder);
System.out.println(docBuilder.getText());


问:
How to use an information sent on httpResponse?
I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.

Let me clarify this for you.

I HAVE THIS CODE TO MAKE THE REQUEST

```<code>try
{
    //Set Basic Auth
    var userPagarme = test_key;
    var password = "";
    var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var clienteToAdd = new PagarmeCliente()
    {
        Name = registerUser.Name,
        Code = registerUser.Code,
        Document = registerUser.Document,
        Type = registerUser.Type,
        Document_Type = registerUser.Document_Type,
        Birthdate = registerUser.Birthdate,
        Email = registerUser.Email,
        Gender = registerUser.Gender,
        Address = new PagarmeClienteEndereco()
        {
            city = registerUser.City,
            country = registerUser.Country,
            line_1 = registerUser.Line_1,
            line_2 = registerUser.Line_2,
            state = registerUser.State,
            zip_code = registerUser.Zip_Code
        },
        Phones = new PagarmeClienteTelefone()
        {
            mobile_phone = new PagarmeClienteTelefoneMobile()
            {
                area_code = registerUser.Mobile_phone_area_code,
                country_code = registerUser.Mobile_phone_country_code,
                number = registerUser.Mobile_phone_number
            },
        }
    };

    var jsonString = JsonConvert.SerializeObject(clienteToAdd);

    HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);

    response.EnsureSuccessStatusCode();

    string responseBody = await response.Content.ReadAsStringAsync();

    this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
    return BadRequest("\nException Caught - Message :{0} " + e.Message);
}
</code>```

That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:

string idThatIWant = responseBodyJSON.id... or something like that.

答:
```<code> var jsonString = JsonConvert.SerializeObject(clienteToAdd);

 HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
</code>```

You converted your model to JSON but you didn't use that jsonString. This could be the cause of the problem.

Body:
I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.

Let me clarify this for you.

I HAVE THIS CODE TO MAKE THE REQUEST

try
{
    //Set Basic Auth
    var userPagarme = test_key;
    var password = "";
    var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var clienteToAdd = new PagarmeCliente()
    {
        Name = registerUser.Name,
        Code = registerUser.Code,
        Document = registerUser.Document,
        Type = registerUser.Type,
        Document_Type = registerUser.Document_Type,
        Birthdate = registerUser.Birthdate,
        Email = registerUser.Email,
        Gender = registerUser.Gender,
        Address = new PagarmeClienteEndereco()
        {
            city = registerUser.City,
            country = registerUser.Country,
            line_1 = registerUser.Line_1,
            line_2 = registerUser.Line_2,
            state = registerUser.State,
            zip_code = registerUser.Zip_Code
        },
        Phones = new PagarmeClienteTelefone()
        {
            mobile_phone = new PagarmeClienteTelefoneMobile()
            {
                area_code = registerUser.Mobile_phone_area_code,
                country_code = registerUser.Mobile_phone_country_code,
                number = registerUser.Mobile_phone_number
            },
        }
    };

    var jsonString = JsonConvert.SerializeObject(clienteToAdd);

    HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);

    response.EnsureSuccessStatusCode();

    string responseBody = await response.Content.ReadAsStringAsync();

    this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
    return BadRequest("\nException Caught - Message :{0} " + e.Message);
}

That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:

string idThatIWant = responseBodyJSON.id... or something like that.

Body:
 var jsonString = JsonConvert.SerializeObject(clienteToAdd);

 HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);

You converted your model to JSON but you didn't use that jsonString. This could be the cause of the problem.


问:
Why is robot framework returning 'While' is a reserved keyword
I'm trying to setup a simple while loop, but I keep getting this error:

'While' is a reserved keyword.

Robot Framework 4.1.3 (Python 3.8.10 on linux)

For sanity, I stripped everything out and created the following test with examples straight from the robotcorp docs (https://robocorp.com/docs/languages-and-frameworks/robot-framework/while-loops)

While.robot

```<code>*** Settings ***

*** Variables ***
@{ROBOTS}=        Bender    Johnny5    Terminator    Robocop

*** Keywords ***

*** Test Cases ***

Loop Over A List Of Items And Log Each Of Them
    FOR    ${robot}    IN    @{ROBOTS}
        Log    ${robot}
    END

Testing While Loop
    ${x}=    Set Variable    ${0}
    WHILE    ${x} < 3
        ${x}=    Evaluate    ${x} + 1
        IF    ${x} == 2
            CONTINUE    #  Skip this iteration.
        END
        Log    x = ${x}    # x = 1, x = 3
    END
</code>```

The result:

```<code>$ robot tests/While.robot
==============================================================================
While
==============================================================================
Loop Over A List Of Items And Log Each Of Them                        | PASS |
------------------------------------------------------------------------------
Testing While Loop                                                    | FAIL |
'While' is a reserved keyword.
------------------------------------------------------------------------------
While                                                                 | FAIL |
2 tests, 1 passed, 1 failed
==============================================================================
</code>```

Am I missing something or is this broken?

答:
Yes, WHILE is a reserved keyword, but not working on that version of Robot Framework, 4.1.3.

You probably are seeing the documentation of the future version, 5.0.

The first Beta version was just released today. See this post on the Forum:

pekkaklarck
Pekka Klärck

Robot Framework 5.0 is a big new major release with lot of interesting
new features such as TRY/EXCEPT, WHILE, inline IF, RETURN, BREAK and
CONTINUE syntax, support for custom argument conversion in libraries
and various enhancements to xUnit outputs. Robot Framework 5.0 only
works with Python 3.6 or newer. Robot Framework 5.0 beta 1 is the
second preview release and contains the majority of the planned new
features. For more details see the full release notes 4. (...)

Body:
I'm trying to setup a simple while loop, but I keep getting this error:

'While' is a reserved keyword.

Robot Framework 4.1.3 (Python 3.8.10 on linux)

For sanity, I stripped everything out and created the following test with examples straight from the robotcorp docs (https://robocorp.com/docs/languages-and-frameworks/robot-framework/while-loops)

While.robot

*** Settings ***

*** Variables ***
@{ROBOTS}=        Bender    Johnny5    Terminator    Robocop

*** Keywords ***

*** Test Cases ***

Loop Over A List Of Items And Log Each Of Them
    FOR    ${robot}    IN    @{ROBOTS}
        Log    ${robot}
    END

Testing While Loop
    ${x}=    Set Variable    ${0}
    WHILE    ${x} < 3
        ${x}=    Evaluate    ${x} + 1
        IF    ${x} == 2
            CONTINUE    #  Skip this iteration.
        END
        Log    x = ${x}    # x = 1, x = 3
    END

The result:

$ robot tests/While.robot
==============================================================================
While
==============================================================================
Loop Over A List Of Items And Log Each Of Them                        | PASS |
------------------------------------------------------------------------------
Testing While Loop                                                    | FAIL |
'While' is a reserved keyword.
------------------------------------------------------------------------------
While                                                                 | FAIL |
2 tests, 1 passed, 1 failed
==============================================================================

Am I missing something or is this broken?


问:
jQuery serialize does not register checkboxes
I'm using jQuery.serialize to retrieve all data fields in a form.

My problem is that it does not retriev checkboxes that is not checked.

It includes this:

```<code><input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />
</code>```

but not this

```<code><input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />
</code>```

How can I get "values" of checkboxes that is not checked?

答:
To build on azatoth's genius answer, I have slightly extended it for my scenario:</p>

```<code>    /* Get input values from form */
    values = jQuery("#myform").serializeArray();

    /* Because serializeArray() ignores unset checkboxes and radio buttons: */
    values = values.concat(
            jQuery('#myform input[type=checkbox]:not(:checked)').map(
                    function() {
                        return {"name": this.name, "value": false}
                    }).get()
    );
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using jQuery.serialize to retrieve all data fields in a form.

My problem is that it does not retriev checkboxes that is not checked.

It includes this:

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />

but not this

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />

How can I get "values" of checkboxes that is not checked?

Body:
To build on azatoth's genius answer, I have slightly extended it for my scenario:

    /* Get input values from form */
    values = jQuery("#myform").serializeArray();

    /* Because serializeArray() ignores unset checkboxes and radio buttons: */
    values = values.concat(
            jQuery('#myform input[type=checkbox]:not(:checked)').map(
                    function() {
                        return {"name": this.name, "value": false}
                    }).get()
    );


问:
using loops to create a new array that gets its values from a different array, starting on the second element and multiplying by the previous element
I am trying to make a function that creates an array from the functions original array, that starts on the second element and multiplies by the previous element.
Example

```<code>input: [2,3,4,5]
output: [6,12,20]
</code>```

I am trying to use a loop to get this done and here is my code so far

```<code>def funct(array1):
     newarray = []
     for x in array1[1:]:
          newarray.append(x*array1)
     return newarray
</code>```

I am at a loss as I am just learning python, and i've tried various other options but with no success. Any help is appreciated

Body:
I am trying to make a function that creates an array from the functions original array, that starts on the second element and multiplies by the previous element.
Example

input: [2,3,4,5]
output: [6,12,20]

I am trying to use a loop to get this done and here is my code so far

def funct(array1):
     newarray = []
     for x in array1[1:]:
          newarray.append(x*array1)
     return newarray

I am at a loss as I am just learning python, and i've tried various other options but with no success. Any help is appreciated

Body:
try

A = [2, 3, 4, 5]
output = [a*b for a, b in zip(A[1:], A[:-1])]


问:
Rounded corner Card Widget with right border in flutter
I have to create a Card like this:

I had written below code to achieve the desired UI, but it didn't work as expected.

Card(
  elevation: 5,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.only(
      bottomRight: Radius.circular(10),
      topRight: Radius.circular(10)),
    side: BorderSide(width: 5, color: Colors.green)),
  child: ListTile(),
)
```
<p>The code above produced this:</p>
<p><img src="https://i.stack.imgur.com/Gub8q.png" alt="enter image description here" /></p>
<p>Whereas using the code below:</p>
<pre class="lang-dart prettyprint-override"><code>Card(
  elevation: 5,
  shape: Border(right: BorderSide(color: Colors.red, width: 5)),
  child: ListTile(),
)
</code>```

Generated this output:

How can I create the required UI in flutter?

答:
You can use the clipBehavior in the Card and move the BorderSide to a Container.

```<code>      Card(
            clipBehavior: Clip.antiAlias,
            child: Container(
              height: 100,
              decoration: BoxDecoration(
                  border: Border(
                      right: BorderSide(color: Colors.green, width: 5))),
            ),
          )
</code>```

Body:
I have to create a Card like this:

I had written below code to achieve the desired UI, but it didn't work as expected.

Card(
  elevation: 5,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.only(
      bottomRight: Radius.circular(10),
      topRight: Radius.circular(10)),
    side: BorderSide(width: 5, color: Colors.green)),
  child: ListTile(),
)

The code above produced this:

Whereas using the code below:

Card(
  elevation: 5,
  shape: Border(right: BorderSide(color: Colors.red, width: 5)),
  child: ListTile(),
)

Generated this output:

How can I create the required UI in flutter?

Body:
You can use the clipBehavior in the Card and move the BorderSide to a Container.

      Card(
            clipBehavior: Clip.antiAlias,
            child: Container(
              height: 100,
              decoration: BoxDecoration(
                  border: Border(
                      right: BorderSide(color: Colors.green, width: 5))),
            ),
          )


问:
How to implement a nonblocking future processor in Java in order to retrieve processed results later
I am using an external library that has the code from below.  I am sending a lot of commands and am interesed in the result for statistics to check how many calls failed and how many succeeded

```<code>public Future<CommandResult> sendCommand(Command command) {
    return command.execute();
}
CommandResult can be success or failure
</code>```

However, if I use client.sendCommand(command).get(); then, I am waiting for the result synchronously, meanwhile the app is being blocked.

I would like to check only later (after 30 seconds which calls succeded and which failed). I am guaranteed to get an answer in 10 seconds.
The problem is that the app waits for the computation to complete, and then retrieves its result.

I was thinking about this approach based on the answers:

```<code>List<Future< CommandResult >> futures = new ArrayList<>();
for(Command command: commands) {
   futures.add(client.sendCommand(command));
}

//in a scheduler, 30+ seconds later
for (Future<Boolean> future : futures) {
   saveResult(future.get());
}
</code>```

答:
I would like to check only later (after 30 seconds which calls succeeded and which failed). I am guaranteed to get an answer in 10 seconds. The problem is that the app waits for the computation to complete, and then retrieves its result.

If you want check on the results at a later time then your solution with Future<Boolean> should be fine.  The jobs will run in the background and you will get the results form then when you call future.get().  Each of those get() calls do block however.

If you want to get the results as they come in, I would use an ExecutorCompletionService which you can poll anytime to see if you have results.  The poll is non-blocking.

```<code>// create your thread pool using fixed or other pool
Executor<Result> threadPool = Executors.newFixedThreadPool(5);
// wrap the Executor in a CompletionService
CompletionService<Boolean> completionService =
   new ExecutorCompletionService<>(e);
// submit jobs to the pool through the ExecutorCompletionService
for (Job job : jobs) {
   completionService.submit(job);
}
// after we have submitted all of the jobs we can shutdown the Executor
// the jobs submitted will continue to run
threadPool.shutdown();
...
// some point later you can do
int jobsRunning = jobs.size();
for (int jobsRunning = jobs.size(); jobsRunning > 0; ) {
   // do some processing ...
   // are any results available?
   Boolean result = completionService.poll();
   if (result != null) {
      // process a result if available
      jobsRunning--;
   }
}
</code>```

Note that you will need to track how many jobs you submitted to the CompletionService.

Body:
I am using an external library that has the code from below.  I am sending a lot of commands and am interesed in the result for statistics to check how many calls failed and how many succeeded

public Future<CommandResult> sendCommand(Command command) {
    return command.execute();
}
CommandResult can be success or failure

However, if I use client.sendCommand(command).get(); then, I am waiting for the result synchronously, meanwhile the app is being blocked.

I would like to check only later (after 30 seconds which calls succeded and which failed). I am guaranteed to get an answer in 10 seconds.
The problem is that the app waits for the computation to complete, and then retrieves its result.

I was thinking about this approach based on the answers:

List<Future< CommandResult >> futures = new ArrayList<>();
for(Command command: commands) {
   futures.add(client.sendCommand(command));
}

//in a scheduler, 30+ seconds later
for (Future<Boolean> future : futures) {
   saveResult(future.get());
}

Body:
I would like to check only later (after 30 seconds which calls succeeded and which failed). I am guaranteed to get an answer in 10 seconds. The problem is that the app waits for the computation to complete, and then retrieves its result.

If you want check on the results at a later time then your solution with Future<Boolean> should be fine.  The jobs will run in the background and you will get the results form then when you call future.get().  Each of those get() calls do block however.

If you want to get the results as they come in, I would use an ExecutorCompletionService which you can poll anytime to see if you have results.  The poll is non-blocking.

// create your thread pool using fixed or other pool
Executor<Result> threadPool = Executors.newFixedThreadPool(5);
// wrap the Executor in a CompletionService
CompletionService<Boolean> completionService =
   new ExecutorCompletionService<>(e);
// submit jobs to the pool through the ExecutorCompletionService
for (Job job : jobs) {
   completionService.submit(job);
}
// after we have submitted all of the jobs we can shutdown the Executor
// the jobs submitted will continue to run
threadPool.shutdown();
...
// some point later you can do
int jobsRunning = jobs.size();
for (int jobsRunning = jobs.size(); jobsRunning > 0; ) {
   // do some processing ...
   // are any results available?
   Boolean result = completionService.poll();
   if (result != null) {
      // process a result if available
      jobsRunning--;
   }
}

Note that you will need to track how many jobs you submitted to the CompletionService.


问:
SQL - Multiple records into one line with conditions
I have two tables that look like this

Account Table

```<code>| Account Number | Account Name   |
| -------------- | -------------- |
| 12345          | Bob Jones      |
| 12346          | Jenny Smith    |
| 12347          | Mary Frederick |
</code>```

Email Table

```<code>| Account Number         | Email Type    |Email                  | IsPrimary       |
| ---------------------- | --------------|-----------------------|-----------------|
| 12345                  | WORK          | BOBSMITH@STACK.COM    | 0               |
| 12345                  | HOME          | BOBSMITH@GMAIL.COM    | 0               |
| 12345                  | WORK          | BOBSMITH@APPLE.COM    | 1               |
| 12345                  | HOME          | BOBSMITH@HOTMAIL.COM  | 0               |
| 12346                  | HOME          | JMSMITH@GMAIL.COM     | 1               |
| 12346                  | WORK          | JMSMITH@DISNEY.COM    | 0               |
| 12346                  | HOME          | JMSMITH@HOTMAIL.COM   | 0               |
| 12347                  | HOME          | MFRED@HOTMAIL.COM     | 0               |
</code>```

I need to end up with results like this:

```<code>| Account Number           | Account Name      | Home Email         | Work Email         | Alternate Email      |
| ------------------------ | ----------------- |--------------------|--------------------|----------------------|
| 12345                    | Bob Jones         | BOBSMITH@GMAIL.COM | BOBSMITH@APPLE.COM | BOBSMITH@HOTMAIL.COM |
| 12346                    | Jenny Smith       | JMSMITH@GMAIL.COM  | JMSMITH@DISNEY.COM | JMSMITH@HOTMAIL.COM  |
| 12347                    | Mary Frederick    | MFRED@HOTMAIL.COM  |                    |                      |
</code>```

I have all possible combinations of emails such as multiple work and no home, no primaries at all, multiple primaries... etc.

I need the logic to be:

Home Email: When type is Home. If there is a primary, choose the first one. If there is no primary, choose the first non-primary home email. Otherwise make it blank

Work Email: Same as above but for work

Alternate Email: Any third email on the list. If there are more than 3, choose home over work.

I have tried a ton of things and nothing has worked well. Here is my top attempt -two things don't work about it. The 'top 1' returns a lot of nulls and the code for alternates isn't always mutually exclusive to the home and work email, especially for people that have no primary checked:

```<code>select distinct
A01.AccountNumber,
A01.FirstName,
A01.LastName,
(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'HOME' and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'HOME')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as HomeEmail
,(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'WORK'  and A07.EmailType is not null)--and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'WORK')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as WorkEmail
,(
    select top 1 (A07.EmailAddress)
    from A07_AccountEmails A07
    where A07.AccountNumber = A01.AccountNumber
    and A07.Active = 1 and A07.UseAsPrimary = 0
) as AlternateEmailMulti
from A01_AccountMaster A01
left outer join A07_AccountEmails A07 on A07.AccountNumber = A01.AccountNumber
where
A01.[Status] = 'A'
</code>```

答:
It seems a simple sub-query per email address should do the trick? I have added them in an OUTER APPLY to allow the values to be used twice, once in the select, and once to be excluded from the alternate email column.

```<code>declare @Account table (Number int, [Name] varchar(64));
declare @Email table (AccountNumber int, [Type] varchar(4), Email varchar(256), IsPrimary bit);

insert into @Account (Number, [Name])
values
(12345, 'Bob Jones'),
(12346, 'Jenny Smith'),
(12347, 'Mary Frederick');

insert into @Email (AccountNumber, [Type], Email, IsPrimary)
values
(12345, 'WORK', 'BOBSMITH@STACK.COM', 0),
(12345, 'HOME', 'BOBSMITH@GMAIL.COM', 0),
(12345, 'WORK', 'BOBSMITH@APPLE.COM', 1),
(12345, 'HOME', 'BOBSMITH@HOTMAIL.COM', 0),
(12346, 'HOME', 'JMSMITH@GMAIL.COM', 1),
(12346, 'WORK', 'JMSMITH@DISNEY.COM', 0),
(12346, 'HOME', 'JMSMITH@HOTMAIL.COM', 0),
(12347, 'HOME', 'MFRED@HOTMAIL.COM', 0);

select A.Number, A.[Name]
  , E.Home [Home Email]
  , E.Work [Work Email]
  , (
    select top 1 Email
    from @Email
    where AccountNumber = A.Number
    and Email not in (E.Home, E.Work)
    order by case when [Type] = 'HOME' then 1 else 0 end desc
  )
from @Account A
outer apply (
  select
    (select top 1 Email from @Email where AccountNumber = A.Number and [Type] = 'HOME' order by IsPrimary desc),
    (select top 1 Email from @Email where AccountNumber = A.Number and [Type] = 'WORK' order by IsPrimary desc)
) E (Home, Work);
</code>```

Returns your desired results:

Account Number
Account Name
Home Email
Work Email
Alternate Email

12345
Bob Jones
BOBSMITH@HOTMAIL.COM
BOBSMITH@APPLE.COM
BOBSMITH@GMAIL.COM

12346
Jenny Smith
JMSMITH@GMAIL.COM
JMSMITH@DISNEY.COM
JMSMITH@HOTMAIL.COM

12347
Mary Frederick
MFRED@HOTMAIL.COM
NULL
NULL

Note: If you provide your sample data as DDL+DML (as I have here) it makes it much easier for people to assist.

Body:
I have two tables that look like this

Account Table

| Account Number | Account Name   |
| -------------- | -------------- |
| 12345          | Bob Jones      |
| 12346          | Jenny Smith    |
| 12347          | Mary Frederick |

Email Table

| Account Number         | Email Type    |Email                  | IsPrimary       |
| ---------------------- | --------------|-----------------------|-----------------|
| 12345                  | WORK          | BOBSMITH@STACK.COM    | 0               |
| 12345                  | HOME          | BOBSMITH@GMAIL.COM    | 0               |
| 12345                  | WORK          | BOBSMITH@APPLE.COM    | 1               |
| 12345                  | HOME          | BOBSMITH@HOTMAIL.COM  | 0               |
| 12346                  | HOME          | JMSMITH@GMAIL.COM     | 1               |
| 12346                  | WORK          | JMSMITH@DISNEY.COM    | 0               |
| 12346                  | HOME          | JMSMITH@HOTMAIL.COM   | 0               |
| 12347                  | HOME          | MFRED@HOTMAIL.COM     | 0               |

I need to end up with results like this:

| Account Number           | Account Name      | Home Email         | Work Email         | Alternate Email      |
| ------------------------ | ----------------- |--------------------|--------------------|----------------------|
| 12345                    | Bob Jones         | BOBSMITH@GMAIL.COM | BOBSMITH@APPLE.COM | BOBSMITH@HOTMAIL.COM |
| 12346                    | Jenny Smith       | JMSMITH@GMAIL.COM  | JMSMITH@DISNEY.COM | JMSMITH@HOTMAIL.COM  |
| 12347                    | Mary Frederick    | MFRED@HOTMAIL.COM  |                    |                      |

I have all possible combinations of emails such as multiple work and no home, no primaries at all, multiple primaries... etc.

I need the logic to be:

Home Email: When type is Home. If there is a primary, choose the first one. If there is no primary, choose the first non-primary home email. Otherwise make it blank

Work Email: Same as above but for work

Alternate Email: Any third email on the list. If there are more than 3, choose home over work.

I have tried a ton of things and nothing has worked well. Here is my top attempt -two things don't work about it. The 'top 1' returns a lot of nulls and the code for alternates isn't always mutually exclusive to the home and work email, especially for people that have no primary checked:

select distinct
A01.AccountNumber,
A01.FirstName,
A01.LastName,
(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'HOME' and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'HOME')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as HomeEmail
,(
    select top 1
    case
       when (A07.Active = 1 and A07.EmailType = 'WORK'  and A07.EmailType is not null)--and A07.UseAsPrimary = 1)
        then A07.EmailAddress
       when (A07.Active = 1 and A07.EmailType = 'WORK')
        then A07.EmailAddress
    end
    from A07_AccountEmails AS A07
    where A07.AccountNumber = A01.AccountNumber

) as WorkEmail
,(
    select top 1 (A07.EmailAddress)
    from A07_AccountEmails A07
    where A07.AccountNumber = A01.AccountNumber
    and A07.Active = 1 and A07.UseAsPrimary = 0
) as AlternateEmailMulti
from A01_AccountMaster A01
left outer join A07_AccountEmails A07 on A07.AccountNumber = A01.AccountNumber
where
A01.[Status] = 'A'

Body:
It seems a simple sub-query per email address should do the trick? I have added them in an OUTER APPLY to allow the values to be used twice, once in the select, and once to be excluded from the alternate email column.

declare @Account table (Number int, [Name] varchar(64));
declare @Email table (AccountNumber int, [Type] varchar(4), Email varchar(256), IsPrimary bit);

insert into @Account (Number, [Name])
values
(12345, 'Bob Jones'),
(12346, 'Jenny Smith'),
(12347, 'Mary Frederick');

insert into @Email (AccountNumber, [Type], Email, IsPrimary)
values
(12345, 'WORK', 'BOBSMITH@STACK.COM', 0),
(12345, 'HOME', 'BOBSMITH@GMAIL.COM', 0),
(12345, 'WORK', 'BOBSMITH@APPLE.COM', 1),
(12345, 'HOME', 'BOBSMITH@HOTMAIL.COM', 0),
(12346, 'HOME', 'JMSMITH@GMAIL.COM', 1),
(12346, 'WORK', 'JMSMITH@DISNEY.COM', 0),
(12346, 'HOME', 'JMSMITH@HOTMAIL.COM', 0),
(12347, 'HOME', 'MFRED@HOTMAIL.COM', 0);

select A.Number, A.[Name]
  , E.Home [Home Email]
  , E.Work [Work Email]
  , (
    select top 1 Email
    from @Email
    where AccountNumber = A.Number
    and Email not in (E.Home, E.Work)
    order by case when [Type] = 'HOME' then 1 else 0 end desc
  )
from @Account A
outer apply (
  select
    (select top 1 Email from @Email where AccountNumber = A.Number and [Type] = 'HOME' order by IsPrimary desc),
    (select top 1 Email from @Email where AccountNumber = A.Number and [Type] = 'WORK' order by IsPrimary desc)
) E (Home, Work);

Returns your desired results:

Account Number
Account Name
Home Email
Work Email
Alternate Email

12345
Bob Jones
BOBSMITH@HOTMAIL.COM
BOBSMITH@APPLE.COM
BOBSMITH@GMAIL.COM

12346
Jenny Smith
JMSMITH@GMAIL.COM
JMSMITH@DISNEY.COM
JMSMITH@HOTMAIL.COM

12347
Mary Frederick
MFRED@HOTMAIL.COM
NULL
NULL

Note: If you provide your sample data as DDL+DML (as I have here) it makes it much easier for people to assist.


问:
Get real value or None from a HashMap
I have a struct that I would like to fill based on a potentially incomplete hash map:

```<code>#[derive(Debug)]
struct Sue {
    children: Option<u8>,
    cats: Option<u8>,
    samoyeds: Option<u8>,
    pomeranians: Option<u8>,
    akitas: Option<u8>,
    vizslas: Option<u8>,
    goldfish: Option<u8>,
    trees: Option<u8>,
    cars: Option<u8>,
    perfumes: Option<u8>,
}

impl Sue {
    fn from_line(line: &str) -> Sue {
        let data: Vec<&str> = line.split(" ").collect();

        let items: HashMap<String, u8> = data[2..data.len()]
            .chunks(2)
            .map(|item| {
                (
                    String::from(item[0].trim_end_matches(":")),
                    String::from(item[1].trim_end_matches(",")).parse().unwrap(),
                )
            })
            .collect();

        println!("{:?}\n", items);

        Sue {
            // children: match items.get("children"){
                // Some(val) => Some(*val),
                // None => None,
            // },
            children: *items.get("children"),
            // cats: Some(0),
            // samoyeds: Some(0),
            // pomeranians: Some(0),
            // akitas: Some(0),
            // vizslas: Some(0),
            // goldfish: Some(0),
            // trees: Some(0),
            // cars: Some(0),
            // perfumes: Some(0),
        }
    }
}
</code>```

In the snippet above, the items hash map may or may not contain a key for each field of the Sue struct. My idea was to build a hash map with the input, and then for each field of the struct, try to access the corresponding key of the hashmap. If the key is in the hashmap, return the dereferenced value. If the key isn't in the hashmap, return None.

I know I can do that with a match (there is a couple of lines commented showing how I would do this), but I was wondering if there is a more efficient way to do this (it's a lot of boilerplate; one match for each field).

If I run the code above, I'll get:

```<code>error[E0614]: type `Option<&u8>` cannot be dereferenced
</code>```

Any idea? I do want to keep None if the key isn't found. Also for reference, this snippet is for advent of code 2015 day 16.

答:
Use copied or cloned to convert an Option<&T> to Option<T>. The first is available if T: Copy, the second if T: Clone.

u8 implements both so you can use either method.

```<code>children: items.get("children").copied(),
</code>```

Title: Get real value or None from a HashMap

Body:
I have a struct that I would like to fill based on a potentially incomplete hash map:

#[derive(Debug)]
struct Sue {
    children: Option<u8>,
    cats: Option<u8>,
    samoyeds: Option<u8>,
    pomeranians: Option<u8>,
    akitas: Option<u8>,
    vizslas: Option<u8>,
    goldfish: Option<u8>,
    trees: Option<u8>,
    cars: Option<u8>,
    perfumes: Option<u8>,
}

impl Sue {
    fn from_line(line: &str) -> Sue {
        let data: Vec<&str> = line.split(" ").collect();

        let items: HashMap<String, u8> = data[2..data.len()]
            .chunks(2)
            .map(|item| {
                (
                    String::from(item[0].trim_end_matches(":")),
                    String::from(item[1].trim_end_matches(",")).parse().unwrap(),
                )
            })
            .collect();

        println!("{:?}\n", items);

        Sue {
            // children: match items.get("children"){
                // Some(val) => Some(*val),
                // None => None,
            // },
            children: *items.get("children"),
            // cats: Some(0),
            // samoyeds: Some(0),
            // pomeranians: Some(0),
            // akitas: Some(0),
            // vizslas: Some(0),
            // goldfish: Some(0),
            // trees: Some(0),
            // cars: Some(0),
            // perfumes: Some(0),
        }
    }
}

In the snippet above, the items hash map may or may not contain a key for each field of the Sue struct. My idea was to build a hash map with the input, and then for each field of the struct, try to access the corresponding key of the hashmap. If the key is in the hashmap, return the dereferenced value. If the key isn't in the hashmap, return None.

I know I can do that with a match (there is a couple of lines commented showing how I would do this), but I was wondering if there is a more efficient way to do this (it's a lot of boilerplate; one match for each field).

If I run the code above, I'll get:

error[E0614]: type `Option<&u8>` cannot be dereferenced

Any idea? I do want to keep None if the key isn't found. Also for reference, this snippet is for advent of code 2015 day 16.

Body:
Use copied or cloned to convert an Option<&T> to Option<T>. The first is available if T: Copy, the second if T: Clone.

u8 implements both so you can use either method.

children: items.get("children").copied(),


问:
How do I resolve an Entity Framework error creating the db context
I have created my first (Blazer) project with Entity Framework.  I got enable-migrations and update-database to work.  Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton

ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction.  Here is the db service in my startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}
</code>```

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

```<code>using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
</code>```

答:
I found the answer to my error (along with moving the builder.Build() as suggested above.  I changed the db service builder to use the ContextFactory

```<code>var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContextFactory<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));
</code>```

and removed this builder from higher up in my startup
builder.Services.AddSingleton<DatabaseContext>();

I was trying to construct my startup from a combination of scaffolding from EF6 and copying a project that was built in EF5.  I guess there are some diffs which I still need to study to understand.

Body:
I have created my first (Blazer) project with Entity Framework.  I got enable-migrations and update-database to work.  Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton

ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction.  Here is the db service in my startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

Body:
I found the answer to my error (along with moving the builder.Build() as suggested above.  I changed the db service builder to use the ContextFactory

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContextFactory<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

and removed this builder from higher up in my startup
builder.Services.AddSingleton<DatabaseContext>();

I was trying to construct my startup from a combination of scaffolding from EF6 and copying a project that was built in EF5.  I guess there are some diffs which I still need to study to understand.


问:
django UserChangeForm not rendering "this form" link correctly with form.as_p
I'm trying to render it with form.as_p and it is rendering mostly as it should. However, the link to the change password section isn't rendering properly. Instead of the blue link on "this form" I get...

"Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form."
anyone ever deal with this problem?

here's my HTML:

```<code>{% extends 'base.html' %}
{% block title %}Edit Profile{% endblock %}
{% block content %}

<h1>Edit Profile...</h1>
<br/>
<div class="form-group">
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button class="btn btn-secondary">Update Profile</button>
    </form>
</div>

{% endblock %}
</code>```

And my forms.py:

```<code>from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django import forms

class EditProfileForm(UserChangeForm):
    email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))
    first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_login = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'}))
    is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'}))
    is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'}))
    date_joined = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password', 'last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined')
</code>```

Views.py:

```<code>from django.shortcuts import render
from django.views import generic
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.urls import reverse_lazy
from .forms import SignUpForm, EditProfileForm

from members.forms import SignUpForm

class UserRegisterView(generic.CreateView):
    form_class = SignUpForm
    template_name = 'registration/register.html'
    success_url = reverse_lazy('login')

class UserEditView(generic.UpdateView):
    form_class = EditProfileForm
    template_name = 'registration/edit_profile.html'
    success_url = reverse_lazy('home')

    def get_object(self):
        return self.request.user
</code>```

urls.py:

```<code>from django.urls import path
from .views import UserRegisterView, UserEditView
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('register/', UserRegisterView.as_view(), name="register"),
    path('edit_profile/', UserEditView.as_view(), name="edit_profile"),
    path('password/', auth_views.PasswordChangeView.as_view())
</code>```

Everything renders properly, except I get this on the page for the password section:

Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form.

Anyone know a fix for this?

答:
In latest versions of Django, help text is not safe by default and  UserChangeForm was not updated to reflect this change.

In order to obtain the desired output you must override password with mark_safe in UserChangeForm:

from django.contrib.auth.forms import ReadOnlyPasswordHashField, UserChangeForm
from django.utils.safestring import mark_safe

class UserEditView(UserChangeForm):
    password = ReadOnlyPasswordHashField(
        label=("Password"),
        help_text=mark_safe(
            'Raw passwords are not stored, so there is no way to see this '
            'user’s password, but you can change the password using '
            'this form.'
        ),
    )

    ...
```

Body:
I'm trying to render it with form.as_p and it is rendering mostly as it should. However, the link to the change password section isn't rendering properly. Instead of the blue link on "this form" I get...

"Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form."
anyone ever deal with this problem?

here's my HTML:

{% extends 'base.html' %}
{% block title %}Edit Profile{% endblock %}
{% block content %}

Edit Profile...

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button class="btn btn-secondary">Update Profile</button>
    </form>

{% endblock %}

And my forms.py:

from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django import forms

class EditProfileForm(UserChangeForm):
    email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))
    first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_login = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'}))
    is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'}))
    is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'}))
    date_joined = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password', 'last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined')

Views.py:

from django.shortcuts import render
from django.views import generic
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.urls import reverse_lazy
from .forms import SignUpForm, EditProfileForm

from members.forms import SignUpForm

class UserRegisterView(generic.CreateView):
    form_class = SignUpForm
    template_name = 'registration/register.html'
    success_url = reverse_lazy('login')

class UserEditView(generic.UpdateView):
    form_class = EditProfileForm
    template_name = 'registration/edit_profile.html'
    success_url = reverse_lazy('home')

    def get_object(self):
        return self.request.user

urls.py:

from django.urls import path
from .views import UserRegisterView, UserEditView
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('register/', UserRegisterView.as_view(), name="register"),
    path('edit_profile/', UserEditView.as_view(), name="edit_profile"),
    path('password/', auth_views.PasswordChangeView.as_view())

Everything renders properly, except I get this on the page for the password section:

Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form.

Anyone know a fix for this?

Body:
In latest versions of Django, help text is not safe by default and  UserChangeForm was not updated to reflect this change.

In order to obtain the desired output you must override password with mark_safe in UserChangeForm:

from django.contrib.auth.forms import ReadOnlyPasswordHashField, UserChangeForm
from django.utils.safestring import mark_safe

class UserEditView(UserChangeForm):
    password = ReadOnlyPasswordHashField(
        label=("Password"),
        help_text=mark_safe(
            'Raw passwords are not stored, so there is no way to see this '
            'user’s password, but you can change the password using '
            '<a href="{}">this form</a>.'
        ),
    )

    ...


问:
Getopt::Long getting a string with spaces into a variable
I'm making a perl script which uses Getopt::Long to parse command line arguments. However, I have an argument which can accept a string (with spaces). How can I get the whole string into a variable. For example:

```<code>./script.pl --string=blah blah blah blah yup --another-opt
</code>```

I need "blah blah blah blah yup" in variable $string. I know Getopt::Long supports multiple inputs for one argument when you know how many you will have (which I do not). Is this possible?

答:
This is really a reply to MaxMackie's question on Ernest's answer, but it's too long, so here goes:

Your script never sees the quotes, only the shell that is passing the arguments. When you call a script (or program), what is happening on a lower level is that the command is called with several arguments in an array. The shell normally splits arguments up based on whitespace. What your program sees right now is:

```<code>[0]./script.pl
[1]--string=blah
[2]blah
[3]blah
[4]blah
[5]yup
[6]--another-opt
</code>```

Putting quotes around the string or escaping it results in in this:

```<code>[0]./script.pl
[1]--string=blah blah blah blah yup
[2]--another-opt
</code>```

Shells (bash in particular, others I'm sure) allows interspersing quotes without spaces as much as you like. ls -"l""h" is the same as ls -lh, hence you an do "--string=blah blah" or --string="blah blah". The parsing of the individual arguments with getopt that lets you put them out of order and use --long-name or -l happens after everything is turned into an array item and passed to the program. The shell has nothing to do with that.

Body:
I'm making a perl script which uses Getopt::Long to parse command line arguments. However, I have an argument which can accept a string (with spaces). How can I get the whole string into a variable. For example:

./script.pl --string=blah blah blah blah yup --another-opt

I need "blah blah blah blah yup" in variable $string. I know Getopt::Long supports multiple inputs for one argument when you know how many you will have (which I do not). Is this possible?

Body:
This is really a reply to MaxMackie's question on Ernest's answer, but it's too long, so here goes:

Your script never sees the quotes, only the shell that is passing the arguments. When you call a script (or program), what is happening on a lower level is that the command is called with several arguments in an array. The shell normally splits arguments up based on whitespace. What your program sees right now is:

[0]./script.pl
[1]--string=blah
[2]blah
[3]blah
[4]blah
[5]yup
[6]--another-opt

Putting quotes around the string or escaping it results in in this:

[0]./script.pl
[1]--string=blah blah blah blah yup
[2]--another-opt

Shells (bash in particular, others I'm sure) allows interspersing quotes without spaces as much as you like. ls -"l""h" is the same as ls -lh, hence you an do "--string=blah blah" or --string="blah blah". The parsing of the individual arguments with getopt that lets you put them out of order and use --long-name or -l happens after everything is turned into an array item and passed to the program. The shell has nothing to do with that.


问:
Determine if two objects have an identical structure with Jest
I'm working on a React application which has multiple themes. Each theme should have the same structure, which can feature deeply-nested properties, but will have different values. It's the structure I'm wanting to add a test case for.

I'm wanting to use Jest to determine if the structure of each of my themes are identical to ensure that no properties have been missed.

All of my theme objects have an identical structure but with different properties. They're set up similar to this:

{
  brand: '...',
  navigation: {
    background: '...',
    link: {
      background: '...',
    },
    ...
  },
  ...
}
```

<p>I'm aware of properties like <code>toEqual</code> and <code>toMatchObject</code>, but both of these fail if I directly try to compare two themes with one another:</p>

<pre class="lang-js prettyprint-override"><code>expect(themeA).toMatchObject(themeB);
</code>```

This fails because the values of each property are different. For example, themeA has a brand property set to '#ABC' whereas themeB has the same property set to  '#DEF'.

I'm also aware that a structure can be defined using Jest like this:

expect(themeA).toEqual({
  brand: expect.any(String),
  navigation: {
    background: expect.any(String),
    ...
  },
  ...
})
```

...but this would require updating the test case every time a new property is added or removed, which I feel complicates the purpose of the test.

Is there a simple way to test if two objects have the same structure but different values?

答:
This is what Typescript will catch everywhere, automatically.  You won't really need to write tests for this type of thing.</p>
```<code>type ThemeA = {
  brand: string,
  navigation: {
    background: string,
    link?: {
      background: string,
    },
    ...
  },
  ...
}

myStyle = { ... }

myStyle: ThemeA   // this will be highlighted by your IDE
                  // if it's not a match, even in tests.
</code>```

Body:
I'm working on a React application which has multiple themes. Each theme should have the same structure, which can feature deeply-nested properties, but will have different values. It's the structure I'm wanting to add a test case for.

I'm wanting to use Jest to determine if the structure of each of my themes are identical to ensure that no properties have been missed.

All of my theme objects have an identical structure but with different properties. They're set up similar to this:

{
  brand: '...',
  navigation: {
    background: '...',
    link: {
      background: '...',
    },
    ...
  },
  ...
}

I'm aware of properties like toEqual and toMatchObject, but both of these fail if I directly try to compare two themes with one another:

expect(themeA).toMatchObject(themeB);

This fails because the values of each property are different. For example, themeA has a brand property set to '#ABC' whereas themeB has the same property set to  '#DEF'.

I'm also aware that a structure can be defined using Jest like this:

expect(themeA).toEqual({
  brand: expect.any(String),
  navigation: {
    background: expect.any(String),
    ...
  },
  ...
})

...but this would require updating the test case every time a new property is added or removed, which I feel complicates the purpose of the test.

Is there a simple way to test if two objects have the same structure but different values?

Body:
This is what Typescript will catch everywhere, automatically.  You won't really need to write tests for this type of thing.

type ThemeA = {
  brand: string,
  navigation: {
    background: string,
    link?: {
      background: string,
    },
    ...
  },
  ...
}

myStyle = { ... }

myStyle: ThemeA   // this will be highlighted by your IDE
                  // if it's not a match, even in tests.


问:
Swift TableView Cell Unable to Display the data from API
I created four label inside the table view cell to fetch the data from Api . The link is https://coinmap.org/api/v1/venues/ . I have two swift file one is to define the tabelview property and other one is for Label with cell . When I run the app it displaying the tableview cell but not displaying the data with label . Here is the model .

```<code>// MARK: - Welcome
struct Coin: Codable {
    let venues: [Venue]
}

// MARK: - Venue
struct Venue: Codable {
    let id: Int
    let lat, lon: Double
    let category, name: String
    let createdOn: Int
    let geolocationDegrees: String

    enum CodingKeys: String, CodingKey {
        case id, lat, lon, category, name
        case createdOn = "created_on"
        case geolocationDegrees = "geolocation_degrees"
    }
}
</code>```

Here is the Network Manager .

```<code>class NetworkManager {

    func getCoins(from url: String, completion: @escaping (Result<Coin, NetworkError>) -> Void ) {

        guard let url = URL(string: url) else {
            completion(.failure(.badURL))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error {
                completion(.failure(.other(error)))
                return
            }

            if let data = data {
                //decode
                do {
                    let response = try JSONDecoder().decode(Coin.self, from: data)
                    completion(.success(response))
                } catch let error {
                    completion(.failure(.other(error)))
                }
            }
        }
        .resume()
    }

}
</code>```

Here is the presenter .

```<code>class VenuePresenter : VanueProtocol{

    // creating instance of the class
    private let view : VanueViewProtocol
    private let networkManager: NetworkManager
    private var vanues = [Venue]()
    var rows: Int{
        return vanues.count
    }
    // initilanize the class
    init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
        self.view = view
        self.networkManager = networkmanager
    }

    func getVanue(){

        let url  = "https://coinmap.org/api/v1/venues/"

        networkManager.getCoins(from: url) { result in

            switch result {
            case.success(let respone):
                self.vanues = respone.venues
                           DispatchQueue.main.async {
                               self.view.resfreshTableView()
                           }
                       case .failure(let error):
                           DispatchQueue.main.async {
                               self.view.displayError(error.errorDescription ?? "")
                               print(error)
                           }
            }
        }
    }

    func getId(by row: Int) -> Int {
        return vanues[row].id
    }

    func getLat(by row: Int) -> Double {
        return vanues[row].lat
    }

    func getCreated(by row: Int) -> Int {
        return vanues[row].createdOn
    }

    func getLon(by row: Int) -> Double? {
        return vanues[row].lon
    }

}
</code>```

Here is the view controller .

```<code>class ViewController: UIViewController{

    private var presenter : VenuePresenter!

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpUI()
        presenter = VenuePresenter(view: self)
        presenter.getVanue()
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DisplayView1")
        // Do any additional setup after loading the view.
    }
    private func setUpUI() {
        tableView.dataSource = self
        tableView.delegate = self
    }

}

extension ViewController : VanueViewProtocol{
    func resfreshTableView() {
        tableView.reloadData()

    }
       func displayError(_ message: String) {
            let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
            alert.addAction(doneButton)
            present(alert, animated: true, completion: nil)
        }
    }
extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        presenter.rows
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: DisplayView.identifier, for: indexPath) as? DisplayView
          else { return UITableViewCell() }

        let row = indexPath.row
        let id   = presenter.getId(by: row)
         let lat = presenter.getLat(by: row)
        guard let lon = presenter.getLon(by: row) else { return UITableViewCell() }
        let createdOn = presenter.getCreated(by: row)
        cell.configureCell(id: id, lat: lat, lon: lon, createdOn: createdOn)
        return cell
    }
}
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

</code>```

Here is the display view swift .

```<code>class DisplayView: UITableViewCell{

    static let identifier = "DisplayView1"

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!

    func configureCell(id: Int ,lat : Double , lon : Double , createdOn: Int){
        label1.text = String(id)
        label2.text = String(lat)
        label3.text = String(lon)
        label4.text = String(createdOn)

    }

}
</code>```

Here is the screenshot is empty not displaying the data .

答:
You are registering a generic cell:

```<code>self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DisplayView1")
</code>```

You need to register your custom cell:

```<code>self.tableView.register(DisplayView.self, forCellReuseIdentifier: DisplayView.identifier)
</code>```

Body:
I created four label inside the table view cell to fetch the data from Api . The link is https://coinmap.org/api/v1/venues/ . I have two swift file one is to define the tabelview property and other one is for Label with cell . When I run the app it displaying the tableview cell but not displaying the data with label . Here is the model .

// MARK: - Welcome
struct Coin: Codable {
    let venues: [Venue]
}

// MARK: - Venue
struct Venue: Codable {
    let id: Int
    let lat, lon: Double
    let category, name: String
    let createdOn: Int
    let geolocationDegrees: String

    enum CodingKeys: String, CodingKey {
        case id, lat, lon, category, name
        case createdOn = "created_on"
        case geolocationDegrees = "geolocation_degrees"
    }
}

Here is the Network Manager .

class NetworkManager {

    func getCoins(from url: String, completion: @escaping (Result<Coin, NetworkError>) -> Void ) {

        guard let url = URL(string: url) else {
            completion(.failure(.badURL))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error {
                completion(.failure(.other(error)))
                return
            }

            if let data = data {
                //decode
                do {
                    let response = try JSONDecoder().decode(Coin.self, from: data)
                    completion(.success(response))
                } catch let error {
                    completion(.failure(.other(error)))
                }
            }
        }
        .resume()
    }

}

Here is the presenter .

class VenuePresenter : VanueProtocol{

    // creating instance of the class
    private let view : VanueViewProtocol
    private let networkManager: NetworkManager
    private var vanues = [Venue]()
    var rows: Int{
        return vanues.count
    }
    // initilanize the class
    init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
        self.view = view
        self.networkManager = networkmanager
    }

    func getVanue(){

        let url  = "https://coinmap.org/api/v1/venues/"

        networkManager.getCoins(from: url) { result in

            switch result {
            case.success(let respone):
                self.vanues = respone.venues
                           DispatchQueue.main.async {
                               self.view.resfreshTableView()
                           }
                       case .failure(let error):
                           DispatchQueue.main.async {
                               self.view.displayError(error.errorDescription ?? "")
                               print(error)
                           }
            }
        }
    }

    func getId(by row: Int) -> Int {
        return vanues[row].id
    }

    func getLat(by row: Int) -> Double {
        return vanues[row].lat
    }

    func getCreated(by row: Int) -> Int {
        return vanues[row].createdOn
    }

    func getLon(by row: Int) -> Double? {
        return vanues[row].lon
    }

}

Here is the view controller .

class ViewController: UIViewController{

    private var presenter : VenuePresenter!

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpUI()
        presenter = VenuePresenter(view: self)
        presenter.getVanue()
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DisplayView1")
        // Do any additional setup after loading the view.
    }
    private func setUpUI() {
        tableView.dataSource = self
        tableView.delegate = self
    }

}

extension ViewController : VanueViewProtocol{
    func resfreshTableView() {
        tableView.reloadData()

    }
       func displayError(_ message: String) {
            let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
            alert.addAction(doneButton)
            present(alert, animated: true, completion: nil)
        }
    }
extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        presenter.rows
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: DisplayView.identifier, for: indexPath) as? DisplayView
          else { return UITableViewCell() }

        let row = indexPath.row
        let id   = presenter.getId(by: row)
         let lat = presenter.getLat(by: row)
        guard let lon = presenter.getLon(by: row) else { return UITableViewCell() }
        let createdOn = presenter.getCreated(by: row)
        cell.configureCell(id: id, lat: lat, lon: lon, createdOn: createdOn)
        return cell
    }
}
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

Here is the display view swift .

class DisplayView: UITableViewCell{

    static let identifier = "DisplayView1"

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!

    func configureCell(id: Int ,lat : Double , lon : Double , createdOn: Int){
        label1.text = String(id)
        label2.text = String(lat)
        label3.text = String(lon)
        label4.text = String(createdOn)

    }

}

Here is the screenshot is empty not displaying the data .

Body:
You are registering a generic cell:

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DisplayView1")

You need to register your custom cell:

self.tableView.register(DisplayView.self, forCellReuseIdentifier: DisplayView.identifier)