问:
AWS Lambda (.NET) + SQS: Error converting the Lambda event JSON payload to a string
i use AWS Lambda (.NET Core 2.1 environment) + SQS as trigger

The problem is that my lambda cannot parse my SQS message.

Error converting the Lambda event JSON payload to a string. JSON
  strings must be quoted, for example "Hello World" in order to be
  converted to a string: Unexpected character encountered while parsing
  value: {. Path '', line 1, position 1.: JsonSerializerException

Here is declaration of my handler:

```<code>public async Task<string> FunctionHandler(DummyMessage message, ILambdaContext context)
</code>```

Model:

```<code>public class DummyMessage {
  public string Label { get; set; }
}
</code>```

SQS input from AWS Console that I tried: {"Label":"qwerty"}, "{"Label":"qwerty"}", "{\"Label\":\"qwerty\"}", but same error occurs.

Could you please help with this issue?

答:
Also, do not forget to add/change aws serializer :</p>

```<code>[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace AwsLambdaHandleTelegramWebhooks
{
   public class Function
   {
      public  APIGatewayProxyResponse FunctionHandler(JObject input,ILambdaContext context)
      {
</code>```

Body:
i use AWS Lambda (.NET Core 2.1 environment) + SQS as trigger

The problem is that my lambda cannot parse my SQS message.

Error converting the Lambda event JSON payload to a string. JSON
  strings must be quoted, for example "Hello World" in order to be
  converted to a string: Unexpected character encountered while parsing
  value: {. Path '', line 1, position 1.: JsonSerializerException

Here is declaration of my handler:

public async Task<string> FunctionHandler(DummyMessage message, ILambdaContext context)

Model:

public class DummyMessage {
  public string Label { get; set; }
}

SQS input from AWS Console that I tried: {"Label":"qwerty"}, "{"Label":"qwerty"}", "{\"Label\":\"qwerty\"}", but same error occurs.

Could you please help with this issue?

Body:
Also, do not forget to add/change aws serializer :

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace AwsLambdaHandleTelegramWebhooks
{
   public class Function
   {
      public  APIGatewayProxyResponse FunctionHandler(JObject input,ILambdaContext context)
      {


来源: stackexchange

问:
How to draw a perfect squiggle in set card game with objective-c?
I'm trying to draw squiggle in Set Card Game. The output is not even close to what I want. How should I improve the drawing?

Please ignore the shading in "What I want" picture. I have figured out how to do that. The question is how to drawing the shape of squiggle

The purpose of this is to practice drawing with objective-c. So just using png picture is not a solution here...

..

```<code>#define SQUIGGLE_CURVE_FACTOR 0.5
 - (UIBezierPath *)drawSquiggleAtPoint:(CGPoint)point
{
    CGFloat dx = self.bounds.size.width * SYMBOL_WIDTH_RATIO / 2;
    CGFloat dy = self.bounds.size.height * SYMBOL_HEIGHT_RATIO / 2;

    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGFloat dsqx = dx * SQUIGGLE_CURVE_FACTOR;
    CGFloat dsqy = dy * SQUIGGLE_CURVE_FACTOR;
    [path moveToPoint:CGPointMake(point.x - dx, point.y)];
    [path addQuadCurveToPoint:CGPointMake(point.x - dsqx, point.y + dsqy) controlPoint:CGPointMake(point.x - dx, point.y + dy + dsqy)];
    [path addCurveToPoint:CGPointMake(point.x + dx, point.y) controlPoint1:point controlPoint2:CGPointMake(point.x + dx, point.y + dy * 2)];
    [path addQuadCurveToPoint:CGPointMake(point.x + dsqx, point.y - dsqy) controlPoint:CGPointMake(point.x + dx, point.y - dy - dsqy)];
    [path addCurveToPoint:CGPointMake(point.x - dx, point.y) controlPoint1:point controlPoint2:CGPointMake(point.x - dx, point.y - dy * 2)];

    return path;
}
</code>```

What I got:

What I want:

final version

```<code>- (UIBezierPath *)drawSquiggleAtPoint:(CGPoint)point
{
    CGSize size = CGSizeMake(self.bounds.size.width * SYMBOL_WIDTH_RATIO, self.bounds.size.height * SYMBOL_HEIGHT_RATIO);

    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(104, 15)];
    [path addCurveToPoint:CGPointMake(63, 54) controlPoint1:CGPointMake(112.4, 36.9) controlPoint2:CGPointMake(89.7, 60.8)];
    [path addCurveToPoint:CGPointMake(27, 53) controlPoint1:CGPointMake(52.3, 51.3) controlPoint2:CGPointMake(42.2, 42)];
    [path addCurveToPoint:CGPointMake(5, 40) controlPoint1:CGPointMake(9.6, 65.6) controlPoint2:CGPointMake(5.4, 58.3)];
    [path addCurveToPoint:CGPointMake(36, 12) controlPoint1:CGPointMake(4.6, 22) controlPoint2:CGPointMake(19.1, 9.7)];
    [path addCurveToPoint:CGPointMake(89, 14) controlPoint1:CGPointMake(59.2, 15.2) controlPoint2:CGPointMake(61.9, 31.5)];
    [path addCurveToPoint:CGPointMake(104, 15) controlPoint1:CGPointMake(95.3, 10) controlPoint2:CGPointMake(100.9, 6.9)];

    [path applyTransform:CGAffineTransformMakeScale(0.9524*size.width/100, 0.9524*size.height/50)];
    [path applyTransform:CGAffineTransformMakeTranslation(point.x - size.width/2 - 3 * size.width /100, point.y - size.height/2 - 8 * size.height/50)];

    return path;
}
</code>```

答: I'm not familiar with the formal definition of a "perfect" squiggle, in any domain? I am aware that the Set Card Game is, of course, set, but it's hardly perfect.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to draw squiggle in Set Card Game. The output is not even close to what I want. How should I improve the drawing?

Please ignore the shading in "What I want" picture. I have figured out how to do that. The question is how to drawing the shape of squiggle

The purpose of this is to practice drawing with objective-c. So just using png picture is not a solution here...

..

#define SQUIGGLE_CURVE_FACTOR 0.5
 - (UIBezierPath *)drawSquiggleAtPoint:(CGPoint)point
{
    CGFloat dx = self.bounds.size.width * SYMBOL_WIDTH_RATIO / 2;
    CGFloat dy = self.bounds.size.height * SYMBOL_HEIGHT_RATIO / 2;

    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGFloat dsqx = dx * SQUIGGLE_CURVE_FACTOR;
    CGFloat dsqy = dy * SQUIGGLE_CURVE_FACTOR;
    [path moveToPoint:CGPointMake(point.x - dx, point.y)];
    [path addQuadCurveToPoint:CGPointMake(point.x - dsqx, point.y + dsqy) controlPoint:CGPointMake(point.x - dx, point.y + dy + dsqy)];
    [path addCurveToPoint:CGPointMake(point.x + dx, point.y) controlPoint1:point controlPoint2:CGPointMake(point.x + dx, point.y + dy * 2)];
    [path addQuadCurveToPoint:CGPointMake(point.x + dsqx, point.y - dsqy) controlPoint:CGPointMake(point.x + dx, point.y - dy - dsqy)];
    [path addCurveToPoint:CGPointMake(point.x - dx, point.y) controlPoint1:point controlPoint2:CGPointMake(point.x - dx, point.y - dy * 2)];

    return path;
}

What I got:

What I want:

final version

- (UIBezierPath *)drawSquiggleAtPoint:(CGPoint)point
{
    CGSize size = CGSizeMake(self.bounds.size.width * SYMBOL_WIDTH_RATIO, self.bounds.size.height * SYMBOL_HEIGHT_RATIO);

    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(104, 15)];
    [path addCurveToPoint:CGPointMake(63, 54) controlPoint1:CGPointMake(112.4, 36.9) controlPoint2:CGPointMake(89.7, 60.8)];
    [path addCurveToPoint:CGPointMake(27, 53) controlPoint1:CGPointMake(52.3, 51.3) controlPoint2:CGPointMake(42.2, 42)];
    [path addCurveToPoint:CGPointMake(5, 40) controlPoint1:CGPointMake(9.6, 65.6) controlPoint2:CGPointMake(5.4, 58.3)];
    [path addCurveToPoint:CGPointMake(36, 12) controlPoint1:CGPointMake(4.6, 22) controlPoint2:CGPointMake(19.1, 9.7)];
    [path addCurveToPoint:CGPointMake(89, 14) controlPoint1:CGPointMake(59.2, 15.2) controlPoint2:CGPointMake(61.9, 31.5)];
    [path addCurveToPoint:CGPointMake(104, 15) controlPoint1:CGPointMake(95.3, 10) controlPoint2:CGPointMake(100.9, 6.9)];

    [path applyTransform:CGAffineTransformMakeScale(0.9524*size.width/100, 0.9524*size.height/50)];
    [path applyTransform:CGAffineTransformMakeTranslation(point.x - size.width/2 - 3 * size.width /100, point.y - size.height/2 - 8 * size.height/50)];

    return path;
}


问:
Using the lag function with two different columns R
I have data such as this.

```<code>data.input <-read_table2("user.id   problem.id  first.correct   cwa_prob    prob.seq
540995  PRABNBZQ    0   1   problem.id.problem.1
540995  PRABNBZ2    1   0   problem.id.problem.2
540995  PRABNBZK    0   1   problem.id.problem.3
540995  PRABNB2B    0   1   problem.id.problem.4
540995  PRABNBWE    0   1   problem.id.problem.5
565662  PRABNB2B    1   0   problem.id.problem.1
565662  PRABNBZQ    1   1   problem.id.problem.2
565662  PRABNBZ9    1   0   problem.id.problem.3
565662  PRABNBZV    1   0   problem.id.problem.4
565662  PRABNBWG    1   0   problem.id.problem.5
")
</code>```

I am trying to use the lag function to compare the occurrence of a flag in two separate columns. I want to see how a person fairs sequentially from one problem to the next. Specifically, if cwa_prob is 1 for problem.id.problem.1 (user 540995), is it the case that first.correct==1 in problem.id.problem.2 (user 540995).

I tried something like this, but it throws me an error.

```<code>input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1),1,0))
</code>```

I would like my output to look something like this:

```<code>data.output <-read_table2("user.id  problem.id  first.correct   cwa_prob    prob.seq    post.cwa.correct
540995  PRABNBZQ    0   1   problem.id.problem.1    NA
540995  PRABNBZ2    1   0   problem.id.problem.2    1
540995  PRABNBZK    0   1   problem.id.problem.3    NA
540995  PRABNB2B    0   1   problem.id.problem.4    0
540995  PRABNBWE    0   1   problem.id.problem.5    0
565662  PRABNB2B    1   0   problem.id.problem.1    1
565662  PRABNBZQ    1   1   problem.id.problem.2    NA
565662  PRABNBZ9    1   0   problem.id.problem.3    1
565662  PRABNBZV    1   0   problem.id.problem.4    NA
565662  PRABNBWG    1   0   problem.id.problem.5    NA
")
</code>```

Maybe the lag function isn't the best function for this? Any help is appreciated!

答:
Take a look at the lag documentation. There is an order_by argument that determines the sort order of your records.

Unless you sent this argument, R uses the existing/default order for your dataset. So different ordering will produce different answers. This is a likely explanation for why your code has not worked, but @James founds that the code ran fine.

input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1, order_by = "prob.seq"),1,0))
```

Note that as the format of prob_seq is most likely character, the order_by clause will sort alphabetically. This means 'problem.10' will come before 'problem.2'. So you'll need to extract and convert the problem number to numeric if this occurs in your data.

Body:
I have data such as this.

data.input <-read_table2("user.id   problem.id  first.correct   cwa_prob    prob.seq
540995  PRABNBZQ    0   1   problem.id.problem.1
540995  PRABNBZ2    1   0   problem.id.problem.2
540995  PRABNBZK    0   1   problem.id.problem.3
540995  PRABNB2B    0   1   problem.id.problem.4
540995  PRABNBWE    0   1   problem.id.problem.5
565662  PRABNB2B    1   0   problem.id.problem.1
565662  PRABNBZQ    1   1   problem.id.problem.2
565662  PRABNBZ9    1   0   problem.id.problem.3
565662  PRABNBZV    1   0   problem.id.problem.4
565662  PRABNBWG    1   0   problem.id.problem.5
")

I am trying to use the lag function to compare the occurrence of a flag in two separate columns. I want to see how a person fairs sequentially from one problem to the next. Specifically, if cwa_prob is 1 for problem.id.problem.1 (user 540995), is it the case that first.correct==1 in problem.id.problem.2 (user 540995).

I tried something like this, but it throws me an error.

input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1),1,0))

I would like my output to look something like this:

data.output <-read_table2("user.id  problem.id  first.correct   cwa_prob    prob.seq    post.cwa.correct
540995  PRABNBZQ    0   1   problem.id.problem.1    NA
540995  PRABNBZ2    1   0   problem.id.problem.2    1
540995  PRABNBZK    0   1   problem.id.problem.3    NA
540995  PRABNB2B    0   1   problem.id.problem.4    0
540995  PRABNBWE    0   1   problem.id.problem.5    0
565662  PRABNB2B    1   0   problem.id.problem.1    1
565662  PRABNBZQ    1   1   problem.id.problem.2    NA
565662  PRABNBZ9    1   0   problem.id.problem.3    1
565662  PRABNBZV    1   0   problem.id.problem.4    NA
565662  PRABNBWG    1   0   problem.id.problem.5    NA
")

Maybe the lag function isn't the best function for this? Any help is appreciated!

Body:
Take a look at the lag documentation. There is an order_by argument that determines the sort order of your records.

Unless you sent this argument, R uses the existing/default order for your dataset. So different ordering will produce different answers. This is a likely explanation for why your code has not worked, but @James founds that the code ran fine.

input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1, order_by = "prob.seq"),1,0))

Note that as the format of prob_seq is most likely character, the order_by clause will sort alphabetically. This means 'problem.10' will come before 'problem.2'. So you'll need to extract and convert the problem number to numeric if this occurs in your data.


问:
Why does calling a Bash command from Ruby throw an error?
I'm attempting to execute the following bash command on some images using Ruby:

```<code>class Pingcrush
  def initialize
    Dir.foreach('drawable') do |item|
      next if item == '.' or item == '..'
      # do work on real items
      if item.end_with?(".png") then
        %x["wine pngcrush.exe -brute drawable/#{item} new/#{item}"]
      end
    end
  end
end
Pingcrush.new
</code>```

The directory I am in is the parent to both drawable and new, however, when when I attempt to run the script I always get the same error:

```<code>sh: wine pngcrush.exe -brute drawable/feed_cl.png new/feed_cl.png: not found
</code>```

Why is this happening? I tried switching around the path I'm calling in Ruby and can't seem to make this work.

答: Don't put quotes around your command.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to execute the following bash command on some images using Ruby:

class Pingcrush
  def initialize
    Dir.foreach('drawable') do |item|
      next if item == '.' or item == '..'
      # do work on real items
      if item.end_with?(".png") then
        %x["wine pngcrush.exe -brute drawable/#{item} new/#{item}"]
      end
    end
  end
end
Pingcrush.new

The directory I am in is the parent to both drawable and new, however, when when I attempt to run the script I always get the same error:

sh: wine pngcrush.exe -brute drawable/feed_cl.png new/feed_cl.png: not found

Why is this happening? I tried switching around the path I'm calling in Ruby and can't seem to make this work.

Body: Don't put quotes around your command.


问:
Lost information getting pdf page as image
I am not an expert in any sense, I am trying to extract a pdf page as an image to do some processing later. I used the following code for that, that I built from other recommendations in this page.

```<code>import fitz
from PIL import Image

dir = r'C:\Users\...'
files =  os.listdir(dir)
print(dir+files[21])
doc = fitz.open(dir+files[21])
page = doc.loadPage(2)
zoom = 2
mat = fitz.Matrix(zoom, zoom)
pix = page.getPixmap(matrix = mat)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)

density=img.getdata()
</code>```

Usually this would give me the pixel information of the image, but in this case it returns a list of white pixels. I have no clue as for what is the reason of this... The image (img) is displayed if asked, but not its data.

I will appreciate any help?

答:
If you want to convert pdf to image, and process, you might use something along these lines.  This particular simple example reads in 5 pages of the PDF, and for the last page, looks at what percentage of the image is a particular color; the slow way and fast way.

import pdf2image
import numpy as np

# details:
# https://pypi.org/project/pdf2image/
images = pdf2image.convert_from_path('test.pdf')

# Get first five pages, just for testing
i = 1
for image in images:
    print(i," shape: ", image.size)
    image.save('output' + str(i) + '.jpg', 'JPEG')
    i = i + 1
    if(i>5):
        break

color_test=(128,128,128)
other=0
specific_color=0

# Look at last image
for i in range(image.width):
    for j in range(image.height):
        x=image.getpixel((i,j))
        if(x[0]==color_test[0] and x[1]==color_test[1] and x[2]==color_test[2]):
            specific_color=specific_color+1
        else:
            other=other+1

print("frac of specific color = ", specific_color/(specific_color+other))

# faster!
x=np.asarray(image)
a=np.where(np.all(x==color_test,axis=-1))
print("(faster) frac of color = ", len(a[0])/((image.width)*(image.height)))
```

Body:
I am not an expert in any sense, I am trying to extract a pdf page as an image to do some processing later. I used the following code for that, that I built from other recommendations in this page.

import fitz
from PIL import Image

dir = r'C:\Users\...'
files =  os.listdir(dir)
print(dir+files[21])
doc = fitz.open(dir+files[21])
page = doc.loadPage(2)
zoom = 2
mat = fitz.Matrix(zoom, zoom)
pix = page.getPixmap(matrix = mat)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)

density=img.getdata()

Usually this would give me the pixel information of the image, but in this case it returns a list of white pixels. I have no clue as for what is the reason of this... The image (img) is displayed if asked, but not its data.

I will appreciate any help?


问:
AWS S3 API list-multipart-uploads what is the timezone of the timestamp?
I am viewing multipart uploads using AWS CLI v2 like so:

aws s3api list-multipart-uploads --bucket my-bucket-name
```

<p>The <code>Uploads</code> key of the response has an <code>Initiated</code> key.  From the <code>list-multipart-uploads</code> docs:</p>

<blockquote>
  <p>Date and time at which the multipart upload was initiated.</p>
</blockquote>

<p>For me (I'm located in the Pacific Time Zone (PT)), it looks like this:</p>

```"Initiated": "2020-06-02T02:20:49+00:00"
```

What is the timezone of this timestamp?

Background

I am located in the Pacific Time Zone (PT).

The region the upload was initiated from and where I ran the list-multipart-uploads command is us-west-2 (see Regions, Availability Zones, and Local Zones).

To me, it looks like the beginning format is: yyyy-mm-dd'T'HH:mm:ss (based on these)

Is this timestamp supposed to be pre-converted to pacific time, or is it given in UTC?

答:
It will be an ISO 8601 format timestamp.

If it ends in +hh:mm, which your example does, then that indicates that it is hh hours and mm minutes ahead of UTC. In your case of +00:00, it is UTC.

If it ends in Z e.g. 2020-06-02T02:20:49Z then it is UTC.

Body:
I am viewing multipart uploads using AWS CLI v2 like so:

aws s3api list-multipart-uploads --bucket my-bucket-name

The Uploads key of the response has an Initiated key.  From the list-multipart-uploads docs:

Date and time at which the multipart upload was initiated.

For me (I'm located in the Pacific Time Zone (PT)), it looks like this:

"Initiated": "2020-06-02T02:20:49+00:00"

What is the timezone of this timestamp?

Background

I am located in the Pacific Time Zone (PT).

The region the upload was initiated from and where I ran the list-multipart-uploads command is us-west-2 (see Regions, Availability Zones, and Local Zones).

To me, it looks like the beginning format is: yyyy-mm-dd'T'HH:mm:ss (based on these)

Is this timestamp supposed to be pre-converted to pacific time, or is it given in UTC?


问:
Stream to generate Map with Integer key and Set of values
I recently stumbled across an interesting Stream challenge, having the requirement to
create a Java (8) Stream that reads integers from an input file and generates a Map that maps the numbers to their corresponding smallest prime factors.

My take so far:

```<code>Map<Integer, String> map = Files.lines(Path.of("nums.txt")).filter(s -> Integer.parseInt(s) > 2).map(Integer::parseInt)
                    .collect(Collectors.toMap(i -> {
                        if(i == 2) return 2;
                        var divisors = IntStream.rangeClosed(2, i).filter(j -> i % j== 0).boxed()
                                .collect(Collectors.toList());
                        return divisors.stream().filter(integer -> {
                            for(int ii = 2; ii < Math.sqrt(integer); ii++) {
                                if(integer % ii == 0) return false;
                            }
                            return true;
                        }).findFirst().orElse(-1);
                    }, String::valueOf
                    , (s1, s2) -> s1 + ";" + s2));
</code>```

Now without a merge BiFunction I would be getting duplicate key exceptions, so to avoid that I
did the workaround from above, it concatenates similarly mapping values with a semicolon.

I find this solution kind of lame however and would like to know, whether it is possible for my map to have a Set
implementation for its second type argument and collect the similarly mapping values into a set.

The main problem is that if eg. I instantiate the new HashMap in the KeyMapper function, it's always going to return for each duplicate key a new one, therefore the merging attempt of the two HashSets was always in vain.

P.s. Feedback about the stream itself is also well-received, I am not sure if this approach is unnecessarily complex.

答:
Unfortunately, questions like this are subject to interpretation.  For example, what if one did something like this?

```<code>String file = "<number file>";
try {
    Map<Integer, List<Integer>> factors = new HashMap<>();
            Files.lines(Path.of(file)).map(Integer::parseInt).forEach(n-> {

                //code here to fill the map factors
            });
} catch (IOException ie) {
    ie.printStackTrace();
}
</code>```

Or something like this

```<code>String file = "<number file>";
try {
    Map<Integer, List<Integer>> factors =
            Files.lines(Path.of(file)).map(Integer::parseInt)
                    .collect(Collectors.toMap(i -> i,
                            i -> primeFactors(i)));
} catch (IOException ie) {
    ie.printStackTrace();
}

public static List<Integer> primeFactors(int i) {
    List<Integer> factors = new ArrayList<>();
    // code here to find the factors
    return factors;
}
</code>```

There are several advanced algorithms that exist to factor composite numbers.  These algorithms do not necessarily lend themselves to stream processing.

Body:
I recently stumbled across an interesting Stream challenge, having the requirement to
create a Java (8) Stream that reads integers from an input file and generates a Map that maps the numbers to their corresponding smallest prime factors.

My take so far:

Map<Integer, String> map = Files.lines(Path.of("nums.txt")).filter(s -> Integer.parseInt(s) > 2).map(Integer::parseInt)
                    .collect(Collectors.toMap(i -> {
                        if(i == 2) return 2;
                        var divisors = IntStream.rangeClosed(2, i).filter(j -> i % j== 0).boxed()
                                .collect(Collectors.toList());
                        return divisors.stream().filter(integer -> {
                            for(int ii = 2; ii < Math.sqrt(integer); ii++) {
                                if(integer % ii == 0) return false;
                            }
                            return true;
                        }).findFirst().orElse(-1);
                    }, String::valueOf
                    , (s1, s2) -> s1 + ";" + s2));

Now without a merge BiFunction I would be getting duplicate key exceptions, so to avoid that I
did the workaround from above, it concatenates similarly mapping values with a semicolon.

I find this solution kind of lame however and would like to know, whether it is possible for my map to have a Set
implementation for its second type argument and collect the similarly mapping values into a set.

The main problem is that if eg. I instantiate the new HashMap in the KeyMapper function, it's always going to return for each duplicate key a new one, therefore the merging attempt of the two HashSets was always in vain.

P.s. Feedback about the stream itself is also well-received, I am not sure if this approach is unnecessarily complex.

Body:
Unfortunately, questions like this are subject to interpretation.  For example, what if one did something like this?

String file = "<number file>";
try {
    Map<Integer, List<Integer>> factors = new HashMap<>();
            Files.lines(Path.of(file)).map(Integer::parseInt).forEach(n-> {

                //code here to fill the map factors
            });
} catch (IOException ie) {
    ie.printStackTrace();
}

Or something like this

String file = "<number file>";
try {
    Map<Integer, List<Integer>> factors =
            Files.lines(Path.of(file)).map(Integer::parseInt)
                    .collect(Collectors.toMap(i -> i,
                            i -> primeFactors(i)));
} catch (IOException ie) {
    ie.printStackTrace();
}

public static List<Integer> primeFactors(int i) {
    List<Integer> factors = new ArrayList<>();
    // code here to find the factors
    return factors;
}

There are several advanced algorithms that exist to factor composite numbers.  These algorithms do not necessarily lend themselves to stream processing.


问:
How can I run fade my loading div out after the main div has loaded?
I have two main div tags within my code: one is the main display (id = 'test') and the other is a loading screen (id = 'loading') that covers the whole screen while the main display is being fetched. The main display's div code is all being done through a javascript function. So far, here's what I have:

```<code><body>
       <div class="container" id="test"></div>

       <div class="loader-wrapper" id="loading">
            <span class="loader"><span class="loader-inner"></span></span>
        </div>

    <script>
        $(window).on('load', function(){
          $('#loading').fadeOut();
        });
    </script>
</body>
</code>```

For reference, "test" is handled by a js class I've created that fetches data from a localhost, which contains certain data to be displayed. The data is returned in the form of a dictionary. Based on the length of this dictionary, my code loops that many times and creates the innerHTML of test in a user-friendly format. If the data is empty, an else-statement is in place to display a different innerHTML for test. The code from the js function is as follows:

```<code>const renderTest = async function(){
    var row_string = "";
    var response = await fetch(`http://localhost:3000/getData`);
    const data = await response.json();
    //create the innerHTML of test
}
renderTest();
</code>```

The issue I am having trouble solving is that the jquery function I made finishes before the "test" div is done being loaded. I tried substituting window with "#test" but found that the loading screen is always present with that. What's the best way to solve this? I would love to have a way where I can simply fadeOut the loading screen once renderTest is complete.

答:
As @epascarello says you should hide the loader from the function that is loading/fetching your div's content

If you're using Promises it should be like this

```<code>fetchData()
.then(ok => $('#loading').fadeOut(), er => alert("something went wrong: "+er)
</code>```

If you are not using promises add your function that is loading your data so we can help.

Btw, is a good practice to use Promises when using loaders nowadays

Body:
I have two main div tags within my code: one is the main display (id = 'test') and the other is a loading screen (id = 'loading') that covers the whole screen while the main display is being fetched. The main display's div code is all being done through a javascript function. So far, here's what I have:

For reference, "test" is handled by a js class I've created that fetches data from a localhost, which contains certain data to be displayed. The data is returned in the form of a dictionary. Based on the length of this dictionary, my code loops that many times and creates the innerHTML of test in a user-friendly format. If the data is empty, an else-statement is in place to display a different innerHTML for test. The code from the js function is as follows:

const renderTest = async function(){
    var row_string = "";
    var response = await fetch(`http://localhost:3000/getData`);
    const data = await response.json();
    //create the innerHTML of test
}
renderTest();

The issue I am having trouble solving is that the jquery function I made finishes before the "test" div is done being loaded. I tried substituting window with "#test" but found that the loading screen is always present with that. What's the best way to solve this? I would love to have a way where I can simply fadeOut the loading screen once renderTest is complete.

Body:
As @epascarello says you should hide the loader from the function that is loading/fetching your div's content

If you're using Promises it should be like this

fetchData()
.then(ok => $('#loading').fadeOut(), er => alert("something went wrong: "+er)

If you are not using promises add your function that is loading your data so we can help.

Btw, is a good practice to use Promises when using loaders nowadays


问:
How to create keyspace in start of cassandra docker image or on start of spring boot app
I need to connect a spring boot app with Cassandra DB in docker container and i need to create keyspace on spring app startup or even on Cassandra container start. How can i achieve this?</p>

答:
In your spring-boot java config you can have a bean which does this.

```<code>@Configuration
@PropertySource("classpath:cassandra.properties")
public class DaoConfig {
     @Bean
     public CassandraSessionManager getCassandraSessionManager() {
         return new CassandraSessionManager();
     }
}
</code>```

If you are using datastax's cassandra java-driver, you can create your keyspace like below.

```<code>String query = "CREATE KEYSPACE mykeyspace WITH replication =
{'class':'SimpleStrategy','replication_factor':1};";
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect();
session.execute(query);
</code>```

More common usecase is to connect to an existing keyspace, you can do that like https://github.com/joychakravarty/JNotes/blob/jnotes_withSpring/src/main/java/com/jc/jnotes/dao/remote/cassandra/CassandraSessionManager.java

Body:
In your spring-boot java config you can have a bean which does this.

@Configuration
@PropertySource("classpath:cassandra.properties")
public class DaoConfig {
     @Bean
     public CassandraSessionManager getCassandraSessionManager() {
         return new CassandraSessionManager();
     }
}

If you are using datastax's cassandra java-driver, you can create your keyspace like below.

String query = "CREATE KEYSPACE mykeyspace WITH replication =
{'class':'SimpleStrategy','replication_factor':1};";
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect();
session.execute(query);

More common usecase is to connect to an existing keyspace, you can do that like https://github.com/joychakravarty/JNotes/blob/jnotes_withSpring/src/main/java/com/jc/jnotes/dao/remote/cassandra/CassandraSessionManager.java


问:
QObjectPicker not working with custom geometry mesh and renderer
I have set up a simple 3d scene with a custom QGeometryRenderer and QGeometry. The custom QGeometry is loaded from a ply file.

```<code>class ColorMeshGeometry : public Qt3DRender::QGeometry
{
  Q_OBJECT
public:
  ColorMeshGeometry(QString meshFile, ColorMeshRenderer *parent);
  ~ColorMeshGeometry();
  void GeometryCenter(QVector3D* center);
};

class ColorMeshRenderer : public Qt3DRender::QGeometryRenderer
{
  ColorMeshGeometry* m_geometry;
  Q_OBJECT
public:
  explicit ColorMeshRenderer(QString meshFile, Qt3DCore::QNode *parent = 0)
  {
    m_geometry = new ColorMeshGeometry(meshFile, this);
    setGeometry(m_geometry);
  }

  ~ColorMeshRenderer();
  void ViewCenter(QVector3D* center);
};
</code>```

And here is the code to set it all up:

```<code>uto view = new Qt3DExtras::Qt3DWindow();
auto container = createWindowContainer(view, this);
auto rootEntity = new Qt3DCore::QEntity();

ColorMeshRenderer* mesh = new ColorMeshRenderer(filename, rootEntity);
view->defaultFrameGraph()->setClearColor(QColor(QRgb(0x111111)));
view->camera()->lens()->setPerspectiveProjection(45.0f, view->width()/view->height(), 0.01f, 100000.0f);
view->camera()->setPosition(QVector3D(0.f, -512.f, 500.0f));
view->camera()->setViewCenter(QVector3D(0, 0, 0));

auto material = new Qt3DExtras::QPerVertexColorMaterial(rootEntity);

auto picker = new Qt3DRender::QObjectPicker(rootEntity);
picker->setHoverEnabled(false);
picker->setDragEnabled(false);

auto plyEntity = new Qt3DCore::QEntity(rootEntity);
plyEntity->addComponent(mesh);
plyEntity->addComponent(material);
plyEntity->addComponent(picker);

connect(picker, &Qt3DRender::QObjectPicker::pressed, this, &ViewerWidget::picker_Clicked);

Qt3DExtras::QOrbitCameraController *camController = new Qt3DExtras::QOrbitCameraController(rootEntity);
camController->setCamera(view->camera());

view->setRootEntity(rootEntity);
</code>```

The QObjectPicker::pressed event is never fired. If I use the Qt3DExtras::QTorusMesh instead, the pressed event is fired. What else needs to be implemented for the QObjectPicker to work with a custom mesh?

Edit:

Full sample code can be found here.

答:
The fix for this ended up being the Perspective Projection. The back pane of the project ended up being way to far way, the fix is:</p>

```<code>view->camera()->lens()->setPerspectiveProjection(45.0f, view->width()/view->height(), 0.01f, 5000.0f);
</code>```

Body:
I have set up a simple 3d scene with a custom QGeometryRenderer and QGeometry. The custom QGeometry is loaded from a ply file.

class ColorMeshGeometry : public Qt3DRender::QGeometry
{
  Q_OBJECT
public:
  ColorMeshGeometry(QString meshFile, ColorMeshRenderer *parent);
  ~ColorMeshGeometry();
  void GeometryCenter(QVector3D* center);
};

class ColorMeshRenderer : public Qt3DRender::QGeometryRenderer
{
  ColorMeshGeometry* m_geometry;
  Q_OBJECT
public:
  explicit ColorMeshRenderer(QString meshFile, Qt3DCore::QNode *parent = 0)
  {
    m_geometry = new ColorMeshGeometry(meshFile, this);
    setGeometry(m_geometry);
  }

  ~ColorMeshRenderer();
  void ViewCenter(QVector3D* center);
};

And here is the code to set it all up:

uto view = new Qt3DExtras::Qt3DWindow();
auto container = createWindowContainer(view, this);
auto rootEntity = new Qt3DCore::QEntity();

ColorMeshRenderer* mesh = new ColorMeshRenderer(filename, rootEntity);
view->defaultFrameGraph()->setClearColor(QColor(QRgb(0x111111)));
view->camera()->lens()->setPerspectiveProjection(45.0f, view->width()/view->height(), 0.01f, 100000.0f);
view->camera()->setPosition(QVector3D(0.f, -512.f, 500.0f));
view->camera()->setViewCenter(QVector3D(0, 0, 0));

auto material = new Qt3DExtras::QPerVertexColorMaterial(rootEntity);

auto picker = new Qt3DRender::QObjectPicker(rootEntity);
picker->setHoverEnabled(false);
picker->setDragEnabled(false);

auto plyEntity = new Qt3DCore::QEntity(rootEntity);
plyEntity->addComponent(mesh);
plyEntity->addComponent(material);
plyEntity->addComponent(picker);

connect(picker, &Qt3DRender::QObjectPicker::pressed, this, &ViewerWidget::picker_Clicked);

Qt3DExtras::QOrbitCameraController *camController = new Qt3DExtras::QOrbitCameraController(rootEntity);
camController->setCamera(view->camera());

view->setRootEntity(rootEntity);

The QObjectPicker::pressed event is never fired. If I use the Qt3DExtras::QTorusMesh instead, the pressed event is fired. What else needs to be implemented for the QObjectPicker to work with a custom mesh?

Edit:

Full sample code can be found here.

Body:
The fix for this ended up being the Perspective Projection. The back pane of the project ended up being way to far way, the fix is:

view->camera()->lens()->setPerspectiveProjection(45.0f, view->width()/view->height(), 0.01f, 5000.0f);


问:
Detect when dialog sets focus to various combo controls using PreTranslateMessage
I have a CDialog and I am trying to override PreTranslateMessage like this:

```<code>BOOL CWeekendMeetingDlg::PreTranslateMessage(MSG* pMsg)
{

    if (pMsg->message == WM_SETFOCUS)
    {
        if (::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_PT_CHAIRMAN &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_PT_OPEN_PRAYER &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_WT_CLOSE_PRAYER &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_WEEKEND_HOST &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_WEEKEND_COHOST &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_PT_READER)
        {
            if (m_gridAssignHist.GetRowCount() != 1)
            {
                m_gridAssignHist.SetRowCount(1);
            }
        }
    }

    return CDialog::PreTranslateMessage(pMsg);
}
</code>```

It is not working. What I want to do is reset my CGridCtrl row count to 1 when other controls gain focus (eg: edit combo). But if I put a breakpoint inside the first if it is never intercepted.

At the moment the only thing I can think of is to renumber all of the combo IDs on the dialog so they are sequential and then use a command range for OnSetFocus and detect in that handler. But there are also some CEdit controls.

Can't I use PTM though and avoid that? For me it seems it would be the easiest.

Here is the dialog:

At the moment I have 7 combo OnSetFocus handlers. When they fire the display specific assignment history in the grid on the right.

So if the user moves to any other control on the dialog, the assignment history control will not apply. And that was why i wanted to reset the history to just the header row. And I was hoping to do this with PTM.

答:
Child control notifications are received in the parent dialog via WM_COMMAND messages. Overriding MFC dialog's OnCommand catches those notifications (CBN_SETFOCUS, EN_SETFOCUS etc).

```<code>void DoSomething()
{   /* ... */ }

BOOL CWeekendMeetingDlg::OnCommand(WPARAM wParam, LPARAM /*unused*/)
{
    switch (HIWORD(wParam))
    {
    case CBN_SETFOCUS:
        switch (LOWORD(wParam))
        {
        case IDC_COMBO_PT_CHAIRMAN:
        // ...more combobox IDCs
            DoSomething();
            break; // or return TRUE to bypass any message map handlers
        }
        break;

    case EN_SETFOCUS:
        switch (LOWORD(wParam))
        {
        case IDC_EDIT_WHATEVER:
        // ...more editbox IDCs
            DoSomething();
            break;
        }
        break;

    // ...more notification codes
    }
    return CDialog::OnCommand(wParam, lParam);
}
</code>```

Body:
I have a CDialog and I am trying to override PreTranslateMessage like this:

BOOL CWeekendMeetingDlg::PreTranslateMessage(MSG* pMsg)
{

    if (pMsg->message == WM_SETFOCUS)
    {
        if (::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_PT_CHAIRMAN &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_PT_OPEN_PRAYER &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_WT_CLOSE_PRAYER &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_WEEKEND_HOST &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_WEEKEND_COHOST &&
            ::GetDlgCtrlID(pMsg->hwnd) != IDC_COMBO_PT_READER)
        {
            if (m_gridAssignHist.GetRowCount() != 1)
            {
                m_gridAssignHist.SetRowCount(1);
            }
        }
    }

    return CDialog::PreTranslateMessage(pMsg);
}

It is not working. What I want to do is reset my CGridCtrl row count to 1 when other controls gain focus (eg: edit combo). But if I put a breakpoint inside the first if it is never intercepted.

At the moment the only thing I can think of is to renumber all of the combo IDs on the dialog so they are sequential and then use a command range for OnSetFocus and detect in that handler. But there are also some CEdit controls.

Can't I use PTM though and avoid that? For me it seems it would be the easiest.

Here is the dialog:

At the moment I have 7 combo OnSetFocus handlers. When they fire the display specific assignment history in the grid on the right.

So if the user moves to any other control on the dialog, the assignment history control will not apply. And that was why i wanted to reset the history to just the header row. And I was hoping to do this with PTM.

Body:
Child control notifications are received in the parent dialog via WM_COMMAND messages. Overriding MFC dialog's OnCommand catches those notifications (CBN_SETFOCUS, EN_SETFOCUS etc).

void DoSomething()
{   /* ... */ }

BOOL CWeekendMeetingDlg::OnCommand(WPARAM wParam, LPARAM /*unused*/)
{
    switch (HIWORD(wParam))
    {
    case CBN_SETFOCUS:
        switch (LOWORD(wParam))
        {
        case IDC_COMBO_PT_CHAIRMAN:
        // ...more combobox IDCs
            DoSomething();
            break; // or return TRUE to bypass any message map handlers
        }
        break;

    case EN_SETFOCUS:
        switch (LOWORD(wParam))
        {
        case IDC_EDIT_WHATEVER:
        // ...more editbox IDCs
            DoSomething();
            break;
        }
        break;

    // ...more notification codes
    }
    return CDialog::OnCommand(wParam, lParam);
}


问:
How to make the jquery datepicker default date to mm-yyyy (literally)
I'm using the jquery datepicker.  The changeYear and changeMonth options are set to true.  This link is exactly how my date picker looks if you click on the date input box.  See how they have to select month and year?

In my testing group about 20% of the users are forgetting to select the year (it's their birth date...dumb I know).  I'm trying to find a way to set the month and year drop down to 'mm' and 'yyyy' as to prompt the user to select both.  However, it seems the defaultDate option won't accept that kind of input and it just defaults to the current date.

I'm stuck.  Anyone care to drop some wisdom on me?

EDIT

I guess I didn't make it clear.  I want "mm" "yyyy" (the letters) to display in the drop downs as default.

答:
Edit: Original post deleted. Sorry, misread your Question..

I do not believe what you are trying to do is available through the plugin options..


问:
no module named tkinter, when using cx-freeze, even I specified the path of the module
I have a python script, which I am trying to make it executable using cx-freeze. This is my script.py file

```<code> from cx_Freeze import setup,Executable
 import tkinter
 import sys
 import os

 os.environ['TCL_LIBRARY'] = "C:\\Users\\Admin\\Anaconda3\\tcl\\tcl8.6"
 os.environ['TCL_LIBRARY'] = "C:\\Users\\Admin\\Anaconda3\\tcl\\tk8.6"

 includes = []
 excludes = ['tkinter']
 packages = []
 base = "Win32GUI"
 setup(
     name = 'myapp',version = '0.1',description = 'app',author = 'user',
     options = {'build_exe': {'excludes':excludes,'packages':packages}},
     executables = [Executable('emetor1.py')]
 )
</code>```

When executed with "python script.py build", the build folder is created with the .exe file. But when I execute the .exe file it gives me "ModuleNotFoundError: No module named tkinter". I put on the os.environ the path of the package, but I still dont understand why it does not recognize it. Please if someone know how to fix this, I would be very thankful.

I am using Windows, and I used "import tkinter" in my main python script. The main python fyle executes normally with the comand python mainprog.py, but the problem is in the .exe file when created by build command.

答:
```<code>from cx_Freeze import setup, Executable
import tkinter
import sys
import os

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "includes": ["tkinter"],"include_files": ["ico.png"]}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(name="merge",
      version="0.1",
      description="My GUI application!",
      options={"build_exe": build_exe_options},
      executables=[Executable("merge.py", base=base)])

</code>```

Had similar issue. This format for setup.py solved it for me.

Body:
I have a python script, which I am trying to make it executable using cx-freeze. This is my script.py file

 from cx_Freeze import setup,Executable
 import tkinter
 import sys
 import os

 os.environ['TCL_LIBRARY'] = "C:\\Users\\Admin\\Anaconda3\\tcl\\tcl8.6"
 os.environ['TCL_LIBRARY'] = "C:\\Users\\Admin\\Anaconda3\\tcl\\tk8.6"

 includes = []
 excludes = ['tkinter']
 packages = []
 base = "Win32GUI"
 setup(
     name = 'myapp',version = '0.1',description = 'app',author = 'user',
     options = {'build_exe': {'excludes':excludes,'packages':packages}},
     executables = [Executable('emetor1.py')]
 )

When executed with "python script.py build", the build folder is created with the .exe file. But when I execute the .exe file it gives me "ModuleNotFoundError: No module named tkinter". I put on the os.environ the path of the package, but I still dont understand why it does not recognize it. Please if someone know how to fix this, I would be very thankful.

I am using Windows, and I used "import tkinter" in my main python script. The main python fyle executes normally with the comand python mainprog.py, but the problem is in the .exe file when created by build command.

Body:
from cx_Freeze import setup, Executable
import tkinter
import sys
import os

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "includes": ["tkinter"],"include_files": ["ico.png"]}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(name="merge",
      version="0.1",
      description="My GUI application!",
      options={"build_exe": build_exe_options},
      executables=[Executable("merge.py", base=base)])

Had similar issue. This format for setup.py solved it for me.


问:
How to create dropdown dependencies
I have a dropdown taking distinct values from a database. Depending on the selected value in this dropdown, I want a second dropdown to be updated with other distinct values from the same table. As an example, let's say that I have a table with 'Continents' and 'Countries' fields, if I select 'Europe' for instance, I want the second dropdown to show the countries in my db which belong to this continent.

I managed to create the first dropdown and connect it to the db, but I'm struggling with the second step, which is to retrieve the first dropdown's selection and use it to update the second one.

Here is my views.py:

```<code>def MyView(request):

    query_results = data_world.objects.all()
    continents_list = ContinentsChoiceField()
    countries_list = CountriesChoiceField()

    query_results_dict = {
        'query_results': query_results,
        'continents_list': continents_list ,
        'countries_list': countries_list ,
    }

    return render(request,'home.html', query_results_dict)
</code>```

models.py:

```<code>class data_world(models.Model):

    id = models.AutoField(primary_key=True)
    continent_name= models.TextField(db_column='CONTINENTS', blank=True, null=True)
    country_name = models.TextField(db_column='COUNTRIES', blank=True, null=True)
    city_name = models.TextField(db_column='CITIES', blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'world'
</code>```

forms.py:

```<code>
class ContinentsChoiceField(forms.Form):

    continents = forms.ModelChoiceField(
        queryset=data_world.objects.values_list("continent_name", flat=True).distinct(),
        empty_label=None
    )

class CountriesChoiceField(forms.Form):

    countries = forms.ModelChoiceField(
        queryset=data_world.objects.values_list("country_name", flat=True).distinct(),
        empty_label=None
    )
</code>```

home.html:

```<code><select id="continents">
    {% for item in continents_list %}
    <option val="{{ item.continent_name }}"> {{ item }} </option>
    {% endfor %}
  </select>

  <script type="text/javascript">
    function GetSelectedText(){
      var ct = document.getElementById("continents");
      var result_ct = ct.options[ct.selectedIndex].text;

      document.getElementById("result_ct").innerHTML = result_ct;
      }
  </script>

<button type="button" onclick="GetSelectedText()">Get Selected Value</button>

<select id="countries">
  {% for item in countries_list %}
  <option val="{{ item.country_name }}"> {{ item }} </option>
  {% endfor %}
</select>
</code>```

Edit 1: updated my html page with some Js code which helps me to retrieve the chosen continent. Now I would need to use it to display the corresponding countries in the second dropdown.

答:
The django-select2 package does exactly this.

Take a look at https://django-select2.readthedocs.io/en/latest/extra.html

In models.py

```<code>class Country(models.Model):
     name = models.CharField(max_length=255)

class City(models.Model):
     name = models.CharField(max_length=255)
    country = models.ForeignKey('Country', related_name="cities")
</code>```

Then customise a form:

```<code>...
from django_select2.forms import ModelSelect2Widget
class AddressForm(forms.Form):
    country = forms.ModelChoiceField(
        queryset=Country.objects.all(),
        label=u"Country",
        widget=ModelSelect2Widget(
            model=Country,
            search_fields=['name__icontains'],
        )
)

city = forms.ModelChoiceField(
    queryset=City.objects.all(),
    label=u"City",
    widget=ModelSelect2Widget(
        model=City,
        search_fields=['name__icontains'],
        dependent_fields={'country': 'country'},
        max_results=500,
    )
)
</code>```

Title: How to create dropdown dependencies

Body:
I have a dropdown taking distinct values from a database. Depending on the selected value in this dropdown, I want a second dropdown to be updated with other distinct values from the same table. As an example, let's say that I have a table with 'Continents' and 'Countries' fields, if I select 'Europe' for instance, I want the second dropdown to show the countries in my db which belong to this continent.

I managed to create the first dropdown and connect it to the db, but I'm struggling with the second step, which is to retrieve the first dropdown's selection and use it to update the second one.

Here is my views.py:

def MyView(request):

    query_results = data_world.objects.all()
    continents_list = ContinentsChoiceField()
    countries_list = CountriesChoiceField()

    query_results_dict = {
        'query_results': query_results,
        'continents_list': continents_list ,
        'countries_list': countries_list ,
    }

    return render(request,'home.html', query_results_dict)

models.py:

class data_world(models.Model):

    id = models.AutoField(primary_key=True)
    continent_name= models.TextField(db_column='CONTINENTS', blank=True, null=True)
    country_name = models.TextField(db_column='COUNTRIES', blank=True, null=True)
    city_name = models.TextField(db_column='CITIES', blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'world'

forms.py:

class ContinentsChoiceField(forms.Form):

    continents = forms.ModelChoiceField(
        queryset=data_world.objects.values_list("continent_name", flat=True).distinct(),
        empty_label=None
    )

class CountriesChoiceField(forms.Form):

    countries = forms.ModelChoiceField(
        queryset=data_world.objects.values_list("country_name", flat=True).distinct(),
        empty_label=None
    )

home.html:

<select id="continents">
    {% for item in continents_list %}
    <option val="{{ item.continent_name }}"> {{ item }} </option>
    {% endfor %}
  </select>

<button type="button" onclick="GetSelectedText()">Get Selected Value</button>

<select id="countries">
  {% for item in countries_list %}
  <option val="{{ item.country_name }}"> {{ item }} </option>
  {% endfor %}
</select>

Edit 1: updated my html page with some Js code which helps me to retrieve the chosen continent. Now I would need to use it to display the corresponding countries in the second dropdown.

Body:
The django-select2 package does exactly this.

Take a look at https://django-select2.readthedocs.io/en/latest/extra.html

In models.py

class Country(models.Model):
     name = models.CharField(max_length=255)

class City(models.Model):
     name = models.CharField(max_length=255)
    country = models.ForeignKey('Country', related_name="cities")

Then customise a form:

...
from django_select2.forms import ModelSelect2Widget
class AddressForm(forms.Form):
    country = forms.ModelChoiceField(
        queryset=Country.objects.all(),
        label=u"Country",
        widget=ModelSelect2Widget(
            model=Country,
            search_fields=['name__icontains'],
        )
)

city = forms.ModelChoiceField(
    queryset=City.objects.all(),
    label=u"City",
    widget=ModelSelect2Widget(
        model=City,
        search_fields=['name__icontains'],
        dependent_fields={'country': 'country'},
        max_results=500,
    )
)


问:
How can I make sure that after declaring a delegate of a protocol in Swift 5.2, that delegate is not nil when it is called?
I am trying to clear a textfield in MainViewController from the DetailViewController. I have the following code in a Swift Playground.

```<code>
import UIKit
import PlaygroundSupport

protocol DetailViewControllerDelegate: class {
    func bar()
}

class DetailViewController: UIViewController {

    var detailViewControllerDelegate: DetailViewControllerDelegate!

    override func loadView() {

        let view = UIView()
        view.backgroundColor = .white

        let button = UIButton()
        button.frame = CGRect(x: 100, y: 200, width: 180, height: 20)
        button.setTitle("Hello World!", for: .normal)
        button.backgroundColor = .blue

        button.addTarget(self, action: #selector(handlePress), for: .touchUpInside)

        view.addSubview(button)
        self.view = view

    }

    @objc func handlePress() {
        print("\(#function)")

        if let vrvc = detailViewControllerDelegate {
            vrvc.bar()
        } else {
            print("detailViewControllerDelegate is NIL")
        }
    }

}

class MainViewController : UIViewController, DetailViewControllerDelegate {
    func bar() {
        print("Inside Bar")
    }

    override func loadView() {
        let detailViewController = DetailViewController()
        detailViewController.detailViewControllerDelegate = self
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = DetailViewController()
</code>```

When the button is pressed, detailViewController is nil. How can I make sure that detailViewController is NOT nil when the button is pressed?

答:
You have two distinct DetailViewControllers:

```<code>    override func loadView() {
        let detailViewController = DetailViewController()
</code>```

detailViewController now references a new instance of DetailViewController

```<code>        detailViewController.detailViewControllerDelegate = self
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = DetailViewController()
</code>```

liveView now references a new instance of DetailViewController which is different from the one above and in which you have not set detailViewControllerDelegate.

If you need to create a DetailViewController in one place and reference it in another you need to store a reference to it in a property that is accessible in both places.

That said, the second instance of DetailViewController is being created in a statement which looks like an attempt to test code in the Playground so maybe you just need to think about how you are testing.

Body:
I am trying to clear a textfield in MainViewController from the DetailViewController. I have the following code in a Swift Playground.

import UIKit
import PlaygroundSupport

protocol DetailViewControllerDelegate: class {
    func bar()
}

class DetailViewController: UIViewController {

    var detailViewControllerDelegate: DetailViewControllerDelegate!

    override func loadView() {

        let view = UIView()
        view.backgroundColor = .white

        let button = UIButton()
        button.frame = CGRect(x: 100, y: 200, width: 180, height: 20)
        button.setTitle("Hello World!", for: .normal)
        button.backgroundColor = .blue

        button.addTarget(self, action: #selector(handlePress), for: .touchUpInside)

        view.addSubview(button)
        self.view = view

    }

    @objc func handlePress() {
        print("\(#function)")

        if let vrvc = detailViewControllerDelegate {
            vrvc.bar()
        } else {
            print("detailViewControllerDelegate is NIL")
        }
    }

}

class MainViewController : UIViewController, DetailViewControllerDelegate {
    func bar() {
        print("Inside Bar")
    }

    override func loadView() {
        let detailViewController = DetailViewController()
        detailViewController.detailViewControllerDelegate = self
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = DetailViewController()

When the button is pressed, detailViewController is nil. How can I make sure that detailViewController is NOT nil when the button is pressed?

Body:
You have two distinct DetailViewControllers:

    override func loadView() {
        let detailViewController = DetailViewController()

detailViewController now references a new instance of DetailViewController

        detailViewController.detailViewControllerDelegate = self
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = DetailViewController()

liveView now references a new instance of DetailViewController which is different from the one above and in which you have not set detailViewControllerDelegate.

If you need to create a DetailViewController in one place and reference it in another you need to store a reference to it in a property that is accessible in both places.

That said, the second instance of DetailViewController is being created in a statement which looks like an attempt to test code in the Playground so maybe you just need to think about how you are testing.


问:
problem capturing keyboard input for Sprite
I an trying to capture keyboard and mouse events for square area on my UI, represented by Sprite. The mouse capture works, the keyboard capture doesn't work at all:

```<code>private var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000, 1);
square.graphics.drawRect(0, 0, 1024, 720);
square.graphics.endFill();
square.buttonMode = true;
...
square.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);

private function reportKeyDown(event:KeyboardEvent):void
{
trace("==>reportKeyDown: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " +         event.charCode + ")");
}
</code>```

I never see reportKeyDown executed, even though Sprite object has a focus.
Any idea what the problem is?
Thanks,
-V

答: Keyboard events are only dispatched from controls that accept user input, such a a TextInput.  This is a bit confusing in the docs; because the events are listed on most Flex components.  Your approach looks right, you just need something inside the Sprite that will dispatch those keyboard events.  </p>

Body:
I an trying to capture keyboard and mouse events for square area on my UI, represented by Sprite. The mouse capture works, the keyboard capture doesn't work at all:

private var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000, 1);
square.graphics.drawRect(0, 0, 1024, 720);
square.graphics.endFill();
square.buttonMode = true;
...
square.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);

private function reportKeyDown(event:KeyboardEvent):void
{
trace("==>reportKeyDown: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " +         event.charCode + ")");
}

I never see reportKeyDown executed, even though Sprite object has a focus.
Any idea what the problem is?
Thanks,
-V


问:
java.lang.NoSuchMethodError: BigQuery Java API throws com.google.api.services.bigquery.model.JobStatistics2.getDdlTargetRoutine() not found
I'm trying to run the BigQuery APIs in a Dataflow job to execute a custom query against BigQuery. I tried to follow the instructions from here. But every time I'm running the job I get the below error:

```<code>{
   "@timestamp":"2019-11-20T16:12:51.008Z",
   "severity":"ERROR",
   "pid":"40364",
   "thread":"main",
   "class":"o.s.b.d.LoggingFailureAnalysisReporter",
   "msg":"\r\n\r\n
***************************\r\nAPPLICATION FAILED TO START\r\n***************************\r\n
    Description:

    An attempt was made to call a method that does not exist. The attempt was made from the following location:
        com.google.cloud.bigquery.JobStatistics$Builder.<init>(JobStatistics.java:1066)

        The following method did not exist:
com.google.api.services.bigquery.model.JobStatistics.getNumChildJobs()Ljava/lang/Long;

        The method's class, com.google.api.services.bigquery.model.JobStatistics, is available from the following locations:
            jar:file:/C:/Users/{user}/.m2/repository/com/google/apis/google-api-services-bigquery/v2-rev20181104-1.27.0/google-api-services-bigquery-v2-rev20181104-1.27.0.jar!/com/google/api/services/bigquery/model/JobStatistics.class

        It was loaded from the following location:
            file:/C:/Users/{user}/.m2/repository/com/google/apis/google-api-services-bigquery/v2-rev20181104-1.27.0/google-api-services-bigquery-v2-rev20181104-1.27.0.jar

    Action:
        Correct the classpath of your application so that it contains a single, compatible version of com.google.api.services.bigquery.model.JobStatistics"
}
</code>```

Here are the dependencies added:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>libraries-bom</artifactId>
            <version>2.8.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
</dependency>
```

<p>And this is the code to execute the query and issue seems to be in the <code>bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build())</code> line.</p>

<pre class="lang-java prettyprint-override"><code>BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
QueryJobConfiguration queryConfig = QueryJobConfiguration
    .newBuilder(query)
    .setUseLegacySql(false).build();
// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
System.out.println("created the job id");

Job queryJob = bigquery.create(
    JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
queryJob = queryJob.waitFor();
</code>```

答:
I had the same issue.
Got resolved after upgrading google-cloud-bigquery to 1.116.0

```<code><dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
    <version>1.116.0</version>
</dependency>
</code>```

Body:
I'm trying to run the BigQuery APIs in a Dataflow job to execute a custom query against BigQuery. I tried to follow the instructions from here. But every time I'm running the job I get the below error:

{
   "@timestamp":"2019-11-20T16:12:51.008Z",
   "severity":"ERROR",
   "pid":"40364",
   "thread":"main",
   "class":"o.s.b.d.LoggingFailureAnalysisReporter",
   "msg":"\r\n\r\n
***************************\r\nAPPLICATION FAILED TO START\r\n***************************\r\n
    Description:

    An attempt was made to call a method that does not exist. The attempt was made from the following location:
        com.google.cloud.bigquery.JobStatistics$Builder.<init>(JobStatistics.java:1066)

        The following method did not exist:
com.google.api.services.bigquery.model.JobStatistics.getNumChildJobs()Ljava/lang/Long;

        The method's class, com.google.api.services.bigquery.model.JobStatistics, is available from the following locations:
            jar:file:/C:/Users/{user}/.m2/repository/com/google/apis/google-api-services-bigquery/v2-rev20181104-1.27.0/google-api-services-bigquery-v2-rev20181104-1.27.0.jar!/com/google/api/services/bigquery/model/JobStatistics.class

        It was loaded from the following location:
            file:/C:/Users/{user}/.m2/repository/com/google/apis/google-api-services-bigquery/v2-rev20181104-1.27.0/google-api-services-bigquery-v2-rev20181104-1.27.0.jar

    Action:
        Correct the classpath of your application so that it contains a single, compatible version of com.google.api.services.bigquery.model.JobStatistics"
}

Here are the dependencies added:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>libraries-bom</artifactId>
            <version>2.8.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
</dependency>

And this is the code to execute the query and issue seems to be in the bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build()) line.

BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
QueryJobConfiguration queryConfig = QueryJobConfiguration
    .newBuilder(query)
    .setUseLegacySql(false).build();
// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
System.out.println("created the job id");

Job queryJob = bigquery.create(
    JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
queryJob = queryJob.waitFor();

Body:
I had the same issue.
Got resolved after upgrading google-cloud-bigquery to 1.116.0

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
    <version>1.116.0</version>
</dependency>


问:
How to check if a variable is in specific range
I have a list of lists that looks like this:

```<code> mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]
</code>```

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

```<code>for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])
</code>```

But of course this did not work.

答:
Your conditional is just written incorrectly - it is choosing sublists whose 2nd element is

>= user_input + 0.6 (which evaluates to >= 4.0, but you want the 2nd element to be between 3.4 and 4.0. So I believe all you need to do is change it like this:

```<code>for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= user_input + 0.6:
        new_list.append(mylists[i])
</code>```

Hope that helps, happy coding!

Body:
I have a list of lists that looks like this:

 mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])

But of course this did not work.

Body:
Your conditional is just written incorrectly - it is choosing sublists whose 2nd element is

>= user_input + 0.6 (which evaluates to >= 4.0, but you want the 2nd element to be between 3.4 and 4.0. So I believe all you need to do is change it like this:

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= user_input + 0.6:
        new_list.append(mylists[i])

Hope that helps, happy coding!


问:
How to extract the headers of the individual search items using Selenium and Python
I am learning python and trying to paste the search results from python.org. I'm using Selenium.

Steps I want to do:

open python.org

Search for term "array" (Displays the results)

paste the list of search items (print("searchResults"))

My Code:

```<code>from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")

#waiting to find the element before throwing error no element found
driver.implicitly_wait(10)
#driver.maximize_window()

#getting the website
driver.get("https://www.python.org/")
driver.implicitly_wait(5)
#finding element by id
driver.find_element_by_id("id-search-field").send_keys("arrays")
driver.find_element_by_id("submit").click()
print("Test Successful")

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
print(SearchResults.text)
</code>```

-> This pastes all results.

Now I want individual results items and their headers. When I inspect the searchresults on site, I get this: PEP 209 -- Multi-dimensional Arrays

There is no Tag, no Class and no Name to use.

How do I use this to just get all the headers?

答:
Your SearchResults are retrieving an static xpath that of the "main" tag that contains the list of results you want: the

```<code>SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
</code>```

If you inspect that search result page you will see that inside this UL tag there are several "
", each one containing a "
" with "" containing the row "head line". From what you asked I reckon those are the elements you are trying to capture, so you could try:

```<code>SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul/li[*]/h3/a")
</code>```

or even something like:

```<code>SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
ChildResults = SearchResults.find_elements_by_xpath('.//*')
</code>```

I did not really tested the code, but the idea is supposed to work. At least for your first trial with Selenium. My main point here is: you are trying to read a list of elements looking only for their parent element, you should go one step further and look for the children ones.

Although I do recommend you to search online about Selenium best practices to use xpaths and searching elements, those kind of "huge static" xpaths can become a nightmare in the long run. The more flexible your elements identifiers are, the easier will be to maintain your code and make it robust for the future.

Body:
I am learning python and trying to paste the search results from python.org. I'm using Selenium.

Steps I want to do:

open python.org

Search for term "array" (Displays the results)

paste the list of search items (print("searchResults"))

My Code:

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")

#waiting to find the element before throwing error no element found
driver.implicitly_wait(10)
#driver.maximize_window()

#getting the website
driver.get("https://www.python.org/")
driver.implicitly_wait(5)
#finding element by id
driver.find_element_by_id("id-search-field").send_keys("arrays")
driver.find_element_by_id("submit").click()
print("Test Successful")

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
print(SearchResults.text)

-> This pastes all results.

Now I want individual results items and their headers. When I inspect the searchresults on site, I get this: PEP 209 -- Multi-dimensional Arrays

There is no Tag, no Class and no Name to use.

How do I use this to just get all the headers?

Body:
Your SearchResults are retrieving an static xpath that of the "main" tag that contains the list of results you want: the

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")

If you inspect that search result page you will see that inside this UL tag there are several "< li >", each one containing a "< h3 >" with "< a >" containing the row "head line". From what you asked I reckon those are the elements you are trying to capture, so you could try:

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul/li[*]/h3/a")

or even something like:

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
ChildResults = SearchResults.find_elements_by_xpath('.//*')

I did not really tested the code, but the idea is supposed to work. At least for your first trial with Selenium. My main point here is: you are trying to read a list of elements looking only for their parent element, you should go one step further and look for the children ones.

Although I do recommend you to search online about Selenium best practices to use xpaths and searching elements, those kind of "huge static" xpaths can become a nightmare in the long run. The more flexible your elements identifiers are, the easier will be to maintain your code and make it robust for the future.


问:
Xamarin forms Custom Cell diplays only first row
I am newbie to Xamarin forms and I would like to create app useful for drivers. I am trying to create custom cell with multiple stacklayouts inside. But in listview there is only first row of my custom cell displayed. Here is my Custom cell code:

```<code><ListView x:Name="ListViewRides">
<ListView.ItemTemplate>
  <DataTemplate>
    <ViewCell>
      <StackLayout Orientation="Vertical" Margin="15">
        <StackLayout Orientation="Horizontal">
          <Label x:Name="LabelLocationFrom" Text="{Binding PlaceFrom}" Margin="0, 0, 5,0"/>
          <Label Text="->"/>
          <Label x:Name="LabelLocationTo" Text="{Binding PlaceTo}" Margin="5, 0, 0, 0"/>
        </StackLayout>
        <StackLayout Orientation="Horizontal">
          <Label x:Name="LabelTimeFrom" Text="{Binding TimeFrom}" Margin="0, 0, 5,0"/>
          <Label Text="->"/>
          <Label x:Name="LabelTimeTo" Text="{Binding TimeTo}" Margin="5, 0, 0, 0"/>
        </StackLayout>
        <Label x:Name="LabelCustomer" Text="{Binding Customer}"></Label>
      </StackLayout>
    </ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>
</code>```

Here is the result in displayed in Simulator

I do not understand where I am making the mistake, Could someone please help me? For complete overview I am also adding the ViewModel Code:

```<code>public class RidesViewModel:Bindable
{
    public string PlaceFrom { get; set; }
    public string PlaceTo { get; set; }
    public DateTime TimeFrom { get; set; }
    public DateTime TimeTo { get; set; }
    public string Load { get; set; }
    public int Weight { get; set; }
    public string Note { get; set; }
    public string ContactPersonFrom { get; set; }
    public string ContactPersonTo { get; set; }
    public string Customer { get; set; }
    public string Trailer { get; set; }
    public bool IsReadyToShow { get; set; }
    public string RideState { get; set; }
}
</code>```

Thank you for advices. I suppose that it is something obvious which I can't see right now.

答:
After a so much Research i created below Listview with Test data.

just copy and paste the code and check the result.

```<code>    <ListView HasUnevenRows="true"
              RowHeight="200">
        <ListView.ItemsSource>
            <x:Array Type="{x:Type x:String}">
                <x:String>Item One</x:String>
                <x:String>Item Two</x:String>
                <x:String>Item Three</x:String>
                <x:String>Item Four</x:String>
                <x:String>Item Five</x:String>
            </x:Array>
        </ListView.ItemsSource>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Frame BorderColor="Red" Padding="0">
                        <Grid Margin="10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="90" />
                                <RowDefinition Height="90"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <BoxView Grid.Row="0"
                                     Grid.Column="0"
                                     Color="Yellow" />
                            <BoxView Grid.Row="0"
                                     Grid.Column="1"
                                     Color="Black" />
                            <BoxView Grid.Row="1"
                                     Grid.Column="0"
                                     Color="Green" />
                            <BoxView Grid.Row="1"
                                     Grid.Column="1"
                                     Color="Blue" />
                            <Label Text="{Binding}"
                                   FontAttributes="Bold"
                                   TextColor="Red"
                                   HorizontalOptions="CenterAndExpand"
                                   VerticalOptions="CenterAndExpand"/>
                        </Grid>
                    </Frame>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

Body:
I am newbie to Xamarin forms and I would like to create app useful for drivers. I am trying to create custom cell with multiple stacklayouts inside. But in listview there is only first row of my custom cell displayed. Here is my Custom cell code:

<ListView x:Name="ListViewRides">
<ListView.ItemTemplate>
  <DataTemplate>
    <ViewCell>
      <StackLayout Orientation="Vertical" Margin="15">
        <StackLayout Orientation="Horizontal">

          "/>

        </StackLayout>
        <StackLayout Orientation="Horizontal">

          "/>

        </StackLayout>

      </StackLayout>
    </ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>

Here is the result in displayed in Simulator

I do not understand where I am making the mistake, Could someone please help me? For complete overview I am also adding the ViewModel Code:

public class RidesViewModel:Bindable
{
    public string PlaceFrom { get; set; }
    public string PlaceTo { get; set; }
    public DateTime TimeFrom { get; set; }
    public DateTime TimeTo { get; set; }
    public string Load { get; set; }
    public int Weight { get; set; }
    public string Note { get; set; }
    public string ContactPersonFrom { get; set; }
    public string ContactPersonTo { get; set; }
    public string Customer { get; set; }
    public string Trailer { get; set; }
    public bool IsReadyToShow { get; set; }
    public string RideState { get; set; }
}

Thank you for advices. I suppose that it is something obvious which I can't see right now.

Body:
After a so much Research i created below Listview with Test data.

just copy and paste the code and check the result.

    <ListView HasUnevenRows="true"
              RowHeight="200">
        <ListView.ItemsSource>
            <x:Array Type="{x:Type x:String}">
                <x:String>Item One</x:String>
                <x:String>Item Two</x:String>
                <x:String>Item Three</x:String>
                <x:String>Item Four</x:String>
                <x:String>Item Five</x:String>
            </x:Array>
        </ListView.ItemsSource>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Frame BorderColor="Red" Padding="0">
                        <Grid Margin="10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="90" />
                                <RowDefinition Height="90"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <BoxView Grid.Row="0"
                                     Grid.Column="0"
                                     Color="Yellow" />
                            <BoxView Grid.Row="0"
                                     Grid.Column="1"
                                     Color="Black" />
                            <BoxView Grid.Row="1"
                                     Grid.Column="0"
                                     Color="Green" />
                            <BoxView Grid.Row="1"
                                     Grid.Column="1"
                                     Color="Blue" />
                            <Label Text="{Binding}"
                                   FontAttributes="Bold"
                                   TextColor="Red"
                                   HorizontalOptions="CenterAndExpand"
                                   VerticalOptions="CenterAndExpand"/>
                        </Grid>
                    </Frame>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>


问:
There is a way to batch archive GitHub repositories based off of a search?
From the answer to a related question I know it's possible to batch clone repositories based on a GitHub search result:

```<code># cheating knowing we currently have 9 pages
for i in {1..9}
do
    curl "https://api.github.com/search/repositories?q=blazor+language:C%23&per_page=100&page=$i" \
     | jq -r '.items[].ssh_url' >> urls.txt
done

cat urls.txt | xargs -P8 -L1 git clone
</code>```

I also know that the Hub client allows me to make API calls.

hub api [-it] [-X METHOD] [-H HEADER] [--cache TTL] ENDPOINT [-F FIELD|--input FILE]

I guess the last step is, how do I archive a repository with Hub?

答:
You can update a repository using the Update a Repository API call.

I put all my repositories in a TMP variable in the following way, and ran the following:

```<code>echo $TMP | xargs -P8 -L1 hub api -X PATCH -F archived=true
</code>```

Here is a sample of what the $TMP variable looked like:

```<code>echo $TMP
/repos/amingilani/9bot
/repos/amingilani/advent-of-code-2019
/repos/amingilani/alan
/repos/amingilani/annotate_models
</code>```

Body:
From the answer to a related question I know it's possible to batch clone repositories based on a GitHub search result:

# cheating knowing we currently have 9 pages
for i in {1..9}
do
    curl "https://api.github.com/search/repositories?q=blazor+language:C%23&per_page=100&page=$i" \
     | jq -r '.items[].ssh_url' >> urls.txt
done

cat urls.txt | xargs -P8 -L1 git clone

I also know that the Hub client allows me to make API calls.

hub api [-it] [-X METHOD] [-H HEADER] [--cache TTL] ENDPOINT [-F FIELD|--input FILE]

I guess the last step is, how do I archive a repository with Hub?

Body:
You can update a repository using the Update a Repository API call.

I put all my repositories in a TMP variable in the following way, and ran the following:

echo $TMP | xargs -P8 -L1 hub api -X PATCH -F archived=true

Here is a sample of what the $TMP variable looked like:

echo $TMP
/repos/amingilani/9bot
/repos/amingilani/advent-of-code-2019
/repos/amingilani/alan
/repos/amingilani/annotate_models


问:
React doesn't start if page reloaded on route with parameter
I have problem with my app in development mode on localhost. If I reload the app on a route with param, e.g.:

```<code>localhost:8080/item/2
</code>```

React doesnt even start, only blank page is rendered.

But If I do reload page on any other page without params, e.g.:

```<code>/home
/about
</code>```

the page is rendered correctly and React app starts successfully.

Note: Im not getting any errrors in console, the app basically doesnt even start, the root id for React is simply empty.

Edit:

my route for the item page:

```<code><Route path={['/', '/item/:id']} exact component={ItemPage} />
</code>```

答:
Could you split that into two Routes and wrap it with Switch?

```<code><Switch>
<Route path={'/'} exact component={ItemPage} />
<Route path={'/item/:id'} component={ItemPage} />
<Switch>
</code>```

Honestly I haven't seen exact and '/item/:id' prop used together and that might be an issue

Body:
I have problem with my app in development mode on localhost. If I reload the app on a route with param, e.g.:

localhost:8080/item/2

React doesnt even start, only blank page is rendered.

But If I do reload page on any other page without params, e.g.:

/home
/about

the page is rendered correctly and React app starts successfully.

Note: Im not getting any errrors in console, the app basically doesnt even start, the root id for React is simply empty.

Edit:

my route for the item page:

<Route path={['/', '/item/:id']} exact component={ItemPage} />

Body:
Could you split that into two Routes and wrap it with Switch?

<Switch>
<Route path={'/'} exact component={ItemPage} />
<Route path={'/item/:id'} component={ItemPage} />
<Switch>

Honestly I haven't seen exact and '/item/:id' prop used together and that might be an issue


问:
Get the latest data from ADLS Gen 2 blob storage to table mounted in Azure DataBricks
I have created an unmanaged table in Azure DataBricks using mount path as below:

```<code>CREATE TABLE <Table-Name> using org.apache.spark.sql.parquet OPTIONS (path "/mnt/<folder>/<subfolder>/")
</code>```

Source of mount path is parquet files stored in ADLS Gen2.
I see if the underlying data is changed in ADLS Gen 2 blob storage path, it is not reflected in the unmanaged table created in ADB. This ADB table still holds the data which was available in blob storage at time of creation of table
Is there any way to get the latest data from blob storage into table in ADB?

答:
There are many who suggest to use ,

```<code>   REFRESH TABLE <table-name>
</code>```

https://docs.databricks.com/data/tables.html#update-a-table

But it never worked for me .

The below think it worked .

```<code>yourdataframe.write.mode("overwrite").saveAsTable("test_table")
</code>```

Body:
I have created an unmanaged table in Azure DataBricks using mount path as below:

CREATE TABLE
 using org.apache.spark.sql.parquet OPTIONS (path "/mnt/<folder>/<subfolder>/")

Source of mount path is parquet files stored in ADLS Gen2.
I see if the underlying data is changed in ADLS Gen 2 blob storage path, it is not reflected in the unmanaged table created in ADB. This ADB table still holds the data which was available in blob storage at time of creation of table
Is there any way to get the latest data from blob storage into table in ADB?

Body:
There are many who suggest to use ,

   REFRESH TABLE <table-name>

https://docs.databricks.com/data/tables.html#update-a-table

But it never worked for me .

The below think it worked .

yourdataframe.write.mode("overwrite").saveAsTable("test_table")


问:
Return new Array that adds up every 2 values?
I am trying to create a method that will take in an array and return a new array that adds every 2 values to create one new value and move on to the next 2 values. If I have an array of {5,8,4,2} I want that array to become {13,6}. So far in my code I have it set up to where it creates an array of {5,8,4,2} and makes it into {13, 12, 6, 0} However, I don't want it to add that way. So I was wondering how do I get my program to skip over the 2nd value after doing the first addition? Also, how do I get rid of that useless zero at the end?</p>

```<code>import java.util.*;
import java.io.*;
public class reduceArray{
   public static int[] reduce(int[] currentArray){
   int[] newArray = new int[currentArray.length];

   for(int i = 0; i < currentArray.length -1; i++){

     newArray[i] = currentArray[i] + currentArray[i+1];

      }

     return newArray;

   }

   public static void main(String[] args){
       int[] arrayANew;
       int[] arrayA = {5,8,4,2};

       arrayANew= reduce(arrayA);

       System.out.println(Arrays.toString(arrayANew) );

    }
}
</code>```

答:
You didn't specifically address whether the current array is always even in length, but we can handle odd-length arrays without too much trouble:

```<code>public static int[] reduce(int[] currentArray) {
    int[] newArray = new int[(currentArray.length + 1) / 2];

    for(int i=0; i<currentArray.length; i++) {
        newArray[i/2] += currentArray[i];
    }

    return newArray;
}
</code>```

Test:

```<code>System.out.println(Arrays.toString(reduce(new int[] {5, 8, 4, 2})));
System.out.println(Arrays.toString(reduce(new int[] {5, 8, 4, 2, 7})));
</code>```

Output:

```<code>[13, 6]
[13, 6, 7]
</code>```

Body:
I am trying to create a method that will take in an array and return a new array that adds every 2 values to create one new value and move on to the next 2 values. If I have an array of {5,8,4,2} I want that array to become {13,6}. So far in my code I have it set up to where it creates an array of {5,8,4,2} and makes it into {13, 12, 6, 0} However, I don't want it to add that way. So I was wondering how do I get my program to skip over the 2nd value after doing the first addition? Also, how do I get rid of that useless zero at the end?

import java.util.*;
import java.io.*;
public class reduceArray{
   public static int[] reduce(int[] currentArray){
   int[] newArray = new int[currentArray.length];

   for(int i = 0; i < currentArray.length -1; i++){

     newArray[i] = currentArray[i] + currentArray[i+1];

      }

     return newArray;

   }

   public static void main(String[] args){
       int[] arrayANew;
       int[] arrayA = {5,8,4,2};

       arrayANew= reduce(arrayA);

       System.out.println(Arrays.toString(arrayANew) );

    }
}

Body:
You didn't specifically address whether the current array is always even in length, but we can handle odd-length arrays without too much trouble:

public static int[] reduce(int[] currentArray) {
    int[] newArray = new int[(currentArray.length + 1) / 2];

    for(int i=0; i<currentArray.length; i++) {
        newArray[i/2] += currentArray[i];
    }

    return newArray;
}

Test:

System.out.println(Arrays.toString(reduce(new int[] {5, 8, 4, 2})));
System.out.println(Arrays.toString(reduce(new int[] {5, 8, 4, 2, 7})));

Output:

[13, 6]
[13, 6, 7]


问:
How to access sqlite database inside the widget class?
How to access the sqlite databases inside the widget class. The widget class which extends the appwidgetprovider does not have an activity hence i am not able to access the databases inside it.</p>

答:
There are 2 approaches for such a problem :

1) you say you don't have an activity inside a widget provider but actually the appwidget will execute inside the application context of your app declaring the widget.
When you override

```<code>onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
</code>```

you receive a context that could be used to get access to a database.

2) however, it would be more androidy to declare a service that would perform the query to the database, manage exceptions, retries, and so on and would provide its data either through a call back to an intent to update your widget, or, better, through a content provider that your widget could address.

Regards,
 Stéphane

Body:
There are 2 approaches for such a problem :

1) you say you don't have an activity inside a widget provider but actually the appwidget will execute inside the application context of your app declaring the widget.
When you override

onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)

you receive a context that could be used to get access to a database.

2) however, it would be more androidy to declare a service that would perform the query to the database, manage exceptions, retries, and so on and would provide its data either through a call back to an intent to update your widget, or, better, through a content provider that your widget could address.

Regards,
 Stéphane


答:
Can you give this a try? Instead of using Xpath try using a CSS selector and break down each element:

from selenium import webdriver
import json
import time

driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")

# Getting the website
driver.get("https://www.python.org/")
# Finding element by id
driver.find_element_by_id("id-search-field").send_keys("arrays")
driver.find_element_by_id("submit").click()
print("Test Successful")
for elem in driver.find_elements_by_css_selector("section.main-content ul li"):
    elem_data = {
        'title': elem.find_element_by_css_selector("h3").text,
        'content': elem.find_element_by_css_selector("p").text,
        'link': elem.find_element_by_css_selector("h3 a").get_attribute('href'),
    }
    print(json.dumps(elem_data, indent=4))
    break
# {
#     "title": "PEP 209 -- Multi-dimensional Arrays",
#     "content": "...arrays comprised of simple types, like numeric. How are masked-arrays implemented? Masked-arrays in Numeric 1 are implemented as a separate array class. With the ability to add new array types to Numeric 2, it is possible that masked-arrays in Numeric 2 could be implemented as a new array type instead of an array class. How are numerical errors handled (IEEE floating-point errors in particular)? It is not clear to the proposers (Paul Barrett and Travis Oliphant) what is the best or preferre...",
#     "link": "https://www.python.org/dev/peps/pep-0209/"
# }
```

Title: How to extract the headers of the individual search items using Selenium and Python