问:
Is there a way to make this Wordle-like SQL query using advanced BigQuery features?
I'm trying to do some word/letter analysis using BigQuery using rules similar to Wordle.

You know the drill:

 letter present but in other position

 letter in correct position

⬜ letter not present.

I have a working query but I'm not really satisfied for three reasons:

It doesn't look too BigQuery-y

For large sets of words, the query doesn't scale well

Extending to, say, 7 letter words would look really, REALLY, REALLY horrible, messy and any number of nasty adjectives could easily describe it

The way I'm doing this vaguely reminds me of recursive CTE, but sadly those are totally elusive to me...

Making it faster is not really a concern but I'm wondering if there's a more advanced/elegant way (for lack of a better term) to accomplish the same result: recursive CTE, TVFs I guess using Javascript UDFs is an option, but I'd like to stay away from them and instead explore an SQL-only alternative.

This is the ugly query:

```<code>with words as (
    select normalized_word as word, 'solution' word_type
    from unnest(["SCAPE","PETER","SMACK","MAMMA"]) as normalized_word
),
split_word as (
    select word,letter,word_type,
    row_number() over(partition by word) as pos
    from words, unnest(split(word,'')) as letter
),
check_correct as (
    select a.word word1,any_value(a.word_type) as word_type,b.word word2,
     string_agg(if(a.letter=b.letter,'',a.letter),'' order by a.pos) w1,
     string_agg(if(a.letter=b.letter,'❌',b.letter),'' order by a.pos) w2,
     sum(if(a.letter=b.letter,1,0)) c,0 p
    from split_word as a, split_word as b
    where a.word <> b.word
    and b.word_type = 'solution'
    and a.pos = b.pos
    group by a.word,b.word
),
check_first as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,1,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,1,1))>0,concat('',right(w1,4)),w1) w1,
    if(instr(w2,substring(w1,1,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,1,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,1,1)))),
      w2) w2,
    from check_correct
),
check_second as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,2,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,2,1))>0,concat(left(w1,1),'',right(w1,3)),w1) w1,
    if(instr(w2,substring(w1,2,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,2,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,2,1)))),
      w2) w2,
    from check_first
),
check_third as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,3,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,3,1))>0,concat(left(w1,2),'',right(w1,2)),w1) w1,
    if(instr(w2,substring(w1,3,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,3,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,3,1)))),
      w2) w2,
    from check_second
),
check_fourth as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,4,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,4,1))>0,concat(left(w1,3),'',right(w1,1)),w1) w1,
    if(instr(w2,substring(w1,4,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,4,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,4,1)))),
      w2) w2,
    from check_third
),
check_fifth as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,5,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,5,1))>0,concat(left(w1,4),''),w1) w1,
    if(instr(w2,substring(w1,5,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,5,1)) - 1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,5,1)))),
      w2) w2, -- for completeness
    from check_fourth
),
final_result as (
    select word1 as guess, word_type as guess_type, word2 as solution, c as correct, p as present,
    length(w1)-c-p as absent,
    regexp_replace(w1, r'([A-Z])', '⬜') as wordle, w1, w2
    from check_fifth
)

select *
from final_result
order by guess
</code>```

The result looks like this:

Note some interesting edge cases with repeated letters in the guess word: 2, 3, 5. My ugly query manages this by "consuming" matched letters in solution and replacing them with ❌ to avoid further matches. That's the sole purpose of w2: avoid more than one match.

Update

Mikhail's solution almost works, but fails when guess word has repeated letters:

答:
Consider below approach  - will work for any number of letters

```<code>with words as (
    select normalized_word as word, 'solution' word_type
    from unnest(["SHAPE","PETER","TAPES","JUMBO","NINJA","MAMMA"]) as normalized_word
), pairs as (
  select t1.word as guess, t2.word as solution
  from words t1, words t2
), greens as (
  select guess, solution, x, offset, color
  from pairs t, unnest(array(
      select as struct x, offset, if(x=y, '', '⬜') color
      from unnest(split(guess, '')) x with offset
      left join unnest(split(solution, '')) y with offset
      using(offset)
    ))
  where guess != solution
), yellows_temp as (
  select guess, solution, x, color
  from pairs t, unnest(array(
      select as struct x, '' color
      from unnest(split(guess, '')) x with offset as pos1
      join unnest(split(solution, '')) y with offset as pos2
      on x = y and pos1 != pos2
      group by x, color
    ))
  where guess != solution
), yellows as (
  select guess, solution, x, '' color
  from yellows_temp y
  left join (
    select guess, solution, x
    from greens
    where color = ''
  ) g
  using (guess, solution, x)
  where g.x is null
)
select guess, solution,
  countif(g.color = '') correct,
  count(distinct if(g.color = '⬜' and y.color = '', y.x, null)) present,
  string_agg(if(g.color = '⬜' and y.color = '', '', g.color), '' order by offset) as wordle,
  string_agg(if(g.color = '⬜' and y.color = '', '', if(g.color = '', '', g.x)), '' order by offset) as w1
from greens g
left join yellows y
using(guess, solution, x)
group by guess, solution
-- order by guess, solution
</code>```

with output

Leaving w2 for you - should be relatively simple using above as a starting point :o)

Body:
I'm trying to do some word/letter analysis using BigQuery using rules similar to Wordle.

You know the drill:

 letter present but in other position

 letter in correct position

⬜ letter not present.

I have a working query but I'm not really satisfied for three reasons:

It doesn't look too BigQuery-y

For large sets of words, the query doesn't scale well

Extending to, say, 7 letter words would look really, REALLY, REALLY horrible, messy and any number of nasty adjectives could easily describe it

The way I'm doing this vaguely reminds me of recursive CTE, but sadly those are totally elusive to me...

Making it faster is not really a concern but I'm wondering if there's a more advanced/elegant way (for lack of a better term) to accomplish the same result: recursive CTE, TVFs I guess using Javascript UDFs is an option, but I'd like to stay away from them and instead explore an SQL-only alternative.

This is the ugly query:

with words as (
    select normalized_word as word, 'solution' word_type
    from unnest(["SCAPE","PETER","SMACK","MAMMA"]) as normalized_word
),
split_word as (
    select word,letter,word_type,
    row_number() over(partition by word) as pos
    from words, unnest(split(word,'')) as letter
),
check_correct as (
    select a.word word1,any_value(a.word_type) as word_type,b.word word2,
     string_agg(if(a.letter=b.letter,'',a.letter),'' order by a.pos) w1,
     string_agg(if(a.letter=b.letter,'❌',b.letter),'' order by a.pos) w2,
     sum(if(a.letter=b.letter,1,0)) c,0 p
    from split_word as a, split_word as b
    where a.word <> b.word
    and b.word_type = 'solution'
    and a.pos = b.pos
    group by a.word,b.word
),
check_first as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,1,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,1,1))>0,concat('',right(w1,4)),w1) w1,
    if(instr(w2,substring(w1,1,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,1,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,1,1)))),
      w2) w2,
    from check_correct
),
check_second as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,2,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,2,1))>0,concat(left(w1,1),'',right(w1,3)),w1) w1,
    if(instr(w2,substring(w1,2,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,2,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,2,1)))),
      w2) w2,
    from check_first
),
check_third as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,3,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,3,1))>0,concat(left(w1,2),'',right(w1,2)),w1) w1,
    if(instr(w2,substring(w1,3,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,3,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,3,1)))),
      w2) w2,
    from check_second
),
check_fourth as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,4,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,4,1))>0,concat(left(w1,3),'',right(w1,1)),w1) w1,
    if(instr(w2,substring(w1,4,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,4,1))-1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,4,1)))),
      w2) w2,
    from check_third
),
check_fifth as (
    select word1,word_type,word2,c,
    if(instr(w2,substring(w1,5,1))>0,p+1,p) p,
    if(instr(w2,substring(w1,5,1))>0,concat(left(w1,4),''),w1) w1,
    if(instr(w2,substring(w1,5,1))>0,
      concat(
        left(w2,instr(w2,substring(w1,5,1)) - 1),
        '❌',
        right(w2,length(w2)-instr(w2,substring(w1,5,1)))),
      w2) w2, -- for completeness
    from check_fourth
),
final_result as (
    select word1 as guess, word_type as guess_type, word2 as solution, c as correct, p as present,
    length(w1)-c-p as absent,
    regexp_replace(w1, r'([A-Z])', '⬜') as wordle, w1, w2
    from check_fifth
)

select *
from final_result
order by guess

The result looks like this:

Note some interesting edge cases with repeated letters in the guess word: 2, 3, 5. My ugly query manages this by "consuming" matched letters in solution and replacing them with ❌ to avoid further matches. That's the sole purpose of w2: avoid more than one match.

Update

Mikhail's solution almost works, but fails when guess word has repeated letters:

Body:
Consider below approach  - will work for any number of letters

with words as (
    select normalized_word as word, 'solution' word_type
    from unnest(["SHAPE","PETER","TAPES","JUMBO","NINJA","MAMMA"]) as normalized_word
), pairs as (
  select t1.word as guess, t2.word as solution
  from words t1, words t2
), greens as (
  select guess, solution, x, offset, color
  from pairs t, unnest(array(
      select as struct x, offset, if(x=y, '', '⬜') color
      from unnest(split(guess, '')) x with offset
      left join unnest(split(solution, '')) y with offset
      using(offset)
    ))
  where guess != solution
), yellows_temp as (
  select guess, solution, x, color
  from pairs t, unnest(array(
      select as struct x, '' color
      from unnest(split(guess, '')) x with offset as pos1
      join unnest(split(solution, '')) y with offset as pos2
      on x = y and pos1 != pos2
      group by x, color
    ))
  where guess != solution
), yellows as (
  select guess, solution, x, '' color
  from yellows_temp y
  left join (
    select guess, solution, x
    from greens
    where color = ''
  ) g
  using (guess, solution, x)
  where g.x is null
)
select guess, solution,
  countif(g.color = '') correct,
  count(distinct if(g.color = '⬜' and y.color = '', y.x, null)) present,
  string_agg(if(g.color = '⬜' and y.color = '', '', g.color), '' order by offset) as wordle,
  string_agg(if(g.color = '⬜' and y.color = '', '', if(g.color = '', '', g.x)), '' order by offset) as w1
from greens g
left join yellows y
using(guess, solution, x)
group by guess, solution
-- order by guess, solution

with output

Leaving w2 for you - should be relatively simple using above as a starting point :o)


来源: stackexchange

问:
Regex expression to match last numerical component, but exclude file extension
I'm stumped trying to figure out a regex expression. Given a file path, I need to match the last numerical component of the path ("frame" number in an image sequence), but also ignore any numerical component in the file extension.

For example, given path:

/path/to/file/abc123/GCAM5423.xmp

The following expression will correctly match 5423.

((?P<index>(?P<padding>0*)\d+)(?!.*(0*)\d+))

However, this expression fails if for example the file extension contains a number as follows:

/path/to/file/abc123/GCAM5423.cr2

In this case the expression will match the 2 in the file extension, when I still need it to match 5423. How can I modify the above expression to ignore file extensions that have a numerical component?

Using python flavor of regex. Thanks in advance!

Edit: Thanks all for your help! To clarify, I specifically need to modify the above expression to only capture the last group. I am passing this pattern to an external library so it needs to include the named groups and to only match the last number prior to the extension.

ContentLicense: CC BY-SA 4.0

Body:
You can try this one:

\/[a-zA-Z]*(\d*)\.[a-zA-Z0-9]{3,4}$


Title: formatting a dataframe with coordinate points

Body:
This is a beginner question, but I have a set of coordinate points formatted like

[ [ -75.526844, 39.655713 ], [ -75.526344, 39.656413 ], [ -75.522343, 39.660813 ], [ -75.518343, 39.663913 ], [ -75.514643, 39.668613 ], [ -75.511743, 39.674313 ], [ -75.509342, 39.685313 ], [ -75.509742, 39.686113 ], [ -75.509042, 39.694513 ], [ -75.507162, 39.696961 ], [ -75.504042, 39.698313 ], [ -75.496241, 39.701413 ], [ -75.491341, 39.711113 ], [ -75.488553, 39.714833 ], [ -75.485241, 39.715813 ], [ -75.483141, 39.715513 ], [ -75.481741, 39.714546 ], [ -75.478940, 39.713813 ], [ -75.477640, 39.715013 ], [ -75.476888, 39.718337 ], [ -75.477432, 39.720561 ], [ -75.477240, 39.724713 ], [ -75.475440, 39.728713 ], [ -75.475384, 39.731057 ], [ -75.474168, 39.735473 ], [ -75.469239, 39.743613 ], [ -75.466263, 39.750737 ], [ -75.466249, 39.750769 ], [ -75.463039, 39.758313 ], [ -75.463339, 39.761213 ]]

I want to make a dataframe that has one column for longitude and one for latitude for this data. How should I go about doing this?

Body:
Here's another possibility with tidyverse, where I read in the data as a string, then I extract only numeric, ., and -, then I make the values numeric and turn into a dataframe column. Next, I create an index, ind, that has the same value every other row (this will be the 2 columns). Next, I create a row number column, then pivot the data wide to get into two columns, then rename.

text <- "[
[ -75.526844, 39.655713 ], [ -75.526344, 39.656413 ],
[ -75.522343, 39.660813 ], [ -75.518343, 39.663913 ],
[ -75.514643, 39.668613 ], [ -75.511743, 39.674313 ],
[ -75.509342, 39.685313 ], [ -75.509742, 39.686113 ],
[ -75.509042, 39.694513 ], [ -75.507162, 39.696961 ],
[ -75.504042, 39.698313 ], [ -75.496241, 39.701413 ],
[ -75.491341, 39.711113 ], [ -75.488553, 39.714833 ],
[ -75.485241, 39.715813 ], [ -75.483141, 39.715513 ],
[ -75.481741, 39.714546 ], [ -75.478940, 39.713813 ],
[ -75.477640, 39.715013 ], [ -75.476888, 39.718337 ],
[ -75.477432, 39.720561 ], [ -75.477240, 39.724713 ],
[ -75.475440, 39.728713 ], [ -75.475384, 39.731057 ],
[ -75.474168, 39.735473 ], [ -75.469239, 39.743613 ],
[ -75.466263, 39.750737 ], [ -75.466249, 39.750769 ],
[ -75.463039, 39.758313 ], [ -75.463339, 39.761213 ]]"

library(tidyverse)

data.frame(Column = as.numeric(str_extract_all(text, "[0-9.-]+")[[1]])) %>%
  group_by(ind = rep(1:2, length.out = n())) %>%
  mutate(rn = row_number()) %>%
  ungroup %>%
  pivot_wider(names_from = ind, values_from = Column) %>%
  select(-rn) %>%
  rename("longitude" = 1, "latitude" = 2)

Output

   longitude latitude
1  -75.52684 39.65571
2  -75.52634 39.65641
3  -75.52234 39.66081
4  -75.51834 39.66391
5  -75.51464 39.66861
6  -75.51174 39.67431
7  -75.50934 39.68531
8  -75.50974 39.68611
9  -75.50904 39.69451
10 -75.50716 39.69696
11 -75.50404 39.69831
12 -75.49624 39.70141
13 -75.49134 39.71111
14 -75.48855 39.71483
15 -75.48524 39.71581
16 -75.48314 39.71551
17 -75.48174 39.71455
18 -75.47894 39.71381
19 -75.47764 39.71501
20 -75.47689 39.71834
21 -75.47743 39.72056
22 -75.47724 39.72471
23 -75.47544 39.72871
24 -75.47538 39.73106
25 -75.47417 39.73547
26 -75.46924 39.74361
27 -75.46626 39.75074
28 -75.46625 39.75077
29 -75.46304 39.75831
30 -75.46334 39.76121

If you have access to the GEOJson, then it is a little easier to convert. For example, if the data is hosted on a URL, then you could do something like below. You can also convert the excel file with the data into a .txt, then use that to bring in the data (e.g., geojsonsf::geojson_sf("~/Downloads/Alaska.txt"))

library(geojsonsf)
library(sf)

sf <- geojsonsf::geojson_sf("https://raw.githubusercontent.com/glynnbird/usstatesgeojson/master/california.geojson")
# Or if you have a local file, then you could put that here instead, e.g., geojsonsf::geojson_sf("~/Downloads/Alaska.geojson")

as.data.frame( sf::st_coordinates( sf ) ) %>%
  select(1:2) %>%
  rename("longitude" = 1, "latitude" = 2) %>%
  head()

  longitude latitude
1 -120.2485 33.99933
2 -120.2474 34.00191
3 -120.2387 34.00759
4 -120.2300 34.01014
5 -120.2213 34.01037
6 -120.2085 34.00565


问:
How to declare a variable in a template in Angular
I have the following template :

```<code><div>
  <span>{{aVariable}}</span>
</div>
</code>```

and would like to end up with :

```<code><div "let a = aVariable">
  <span>{{a}}</span>
</div>
</code>```

Is there a way to do it ?

答:
I'm the author of https://www.npmjs.com/package/ng-let

Structural directive for sharing data as local variable into html component template.

Source code:

```<code>import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface NgLetContext<T> {
    ngLet: T;
    $implicit: T;
}

@Directive({
    // tslint:disable-next-line: directive-selector
    selector: '[ngLet]'
})
export class NgLetDirective<T> {

    private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
    private hasView: boolean = false;

    // eslint-disable-next-line no-unused-vars
    constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }

    @Input()
    set ngLet(value: T) {
        this.context.$implicit = this.context.ngLet = value;
        if (!this.hasView) {
            this.viewContainer.createEmbeddedView(this.templateRef, this.context);
            this.hasView = true;
        }
    }

    /** @internal */
    public static ngLetUseIfTypeGuard: void;

    /**
     * Assert the correct type of the expression bound to the `NgLet` input within the template.
     *
     * The presence of this static field is a signal to the Ivy template type check compiler that
     * when the `NgLet` structural directive renders its template, the type of the expression bound
     * to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
     * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
     */
    static ngTemplateGuard_ngLet: 'binding';

    /**
     * Asserts the correct type of the context for the template that `NgLet` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgLet` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
        return true;
    }
}
</code>```

Usage:

```<code>import { Component } from '@angular/core';
import { defer, Observable, timer } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
  <ng-container *ngLet="timer$ | async as time"> <!-- single subscription -->
    <div>
      1: {{ time }}
    </div>
    <div>
      2: {{ time }}
    </div>
  </ng-container>
  `,
})
export class AppComponent {
  timer$: Observable<number> = defer(() => timer(3000, 1000));
}
</code>```

Body:
I have the following template :

  {{aVariable}}

and would like to end up with :

  {{a}}

Is there a way to do it ?

Body:
I'm the author of https://www.npmjs.com/package/ng-let

Structural directive for sharing data as local variable into html component template.

Source code:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface NgLetContext<T> {
    ngLet: T;
    $implicit: T;
}

@Directive({
    // tslint:disable-next-line: directive-selector
    selector: '[ngLet]'
})
export class NgLetDirective<T> {

    private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
    private hasView: boolean = false;

    // eslint-disable-next-line no-unused-vars
    constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }

    @Input()
    set ngLet(value: T) {
        this.context.$implicit = this.context.ngLet = value;
        if (!this.hasView) {
            this.viewContainer.createEmbeddedView(this.templateRef, this.context);
            this.hasView = true;
        }
    }

    /** @internal */
    public static ngLetUseIfTypeGuard: void;

    /**
     * Assert the correct type of the expression bound to the `NgLet` input within the template.
     *
     * The presence of this static field is a signal to the Ivy template type check compiler that
     * when the `NgLet` structural directive renders its template, the type of the expression bound
     * to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
     * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
     */
    static ngTemplateGuard_ngLet: 'binding';

    /**
     * Asserts the correct type of the context for the template that `NgLet` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgLet` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
        return true;
    }
}

Usage:

import { Component } from '@angular/core';
import { defer, Observable, timer } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
  <ng-container *ngLet="timer$ | async as time"> <!-- single subscription -->
    <div>
      1: {{ time }}
    </div>
    <div>
      2: {{ time }}
    </div>
  </ng-container>
  `,
})
export class AppComponent {
  timer$: Observable<number> = defer(() => timer(3000, 1000));
}


问:
Won't let me find average of the dictionary
I need to have a dictionary created by what the user inputs. I then need to allow them to input a name and time length which I have managed successfully. I also think I got it to tell me the shortest and longest length correctly. However, for some reason it won't let me calculate an average. I have spent hours researching it on youtube and trying different things, so my hypothesis is that something is incorrect at the top of my code which isn't allowing the calculation of an average.</p>
```<code>n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(v)

print("Your average length is", average)
</code>```

答:
I have changed the logic to calculate the sum. It is working now.</p>
```<code>n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

sum = 0
for value in my_dict.values():
    sum = sum + int(value)

average = sum/ len(my_dict.values())

print("Your average length is", average)
</code>```

Body:
I need to have a dictionary created by what the user inputs. I then need to allow them to input a name and time length which I have managed successfully. I also think I got it to tell me the shortest and longest length correctly. However, for some reason it won't let me calculate an average. I have spent hours researching it on youtube and trying different things, so my hypothesis is that something is incorrect at the top of my code which isn't allowing the calculation of an average.

n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(v)

print("Your average length is", average)

Body:
I have changed the logic to calculate the sum. It is working now.

n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

sum = 0
for value in my_dict.values():
    sum = sum + int(value)

average = sum/ len(my_dict.values())

print("Your average length is", average)


问:
UICollectionViewCompositionalLayout, but not a repeating pattern
Here is the preview of layout

As you can see this layout has a pattern of cells 0, 1, 2, 0, 1, 2, 0, 1, 2 with respect to the size. I want my layout to depict 0, 1, 2, 1, 2, 1, 2, 1, 2 as the pattern with respect to size.
In other words, just have the first cell to be of large size and the others should take up a size to fit the row of 2.
My current code for the layout:

import UIKit

struct Layout {

    private struct LayoutConstants {
        static let largeGroupHeight: CGFloat = 406
        static let leadingInset: CGFloat = 8
        static let topInset: CGFloat = 10
        static let bottomInset: CGFloat = 15
        static let itemCount = 2
        static let fractionalConstant: CGFloat = 1.0
        static let fractionalWidthLeading: CGFloat = 0.67
        static let fractionalWidthTrailing: CGFloat = 1.0
        static let fractionalHeightTrailing: CGFloat = 0.3
        static let fractionalContainerWidth: CGFloat = 1.2
        static let groupFractionalHeight: CGFloat = 0.33
    }

    func layoutSection() -> NSCollectionLayoutSection {
        let leadingItem = NSCollectionLayoutItem(
            layoutSize: NSCollectionLayoutSize(
                widthDimension: .fractionalWidth(LayoutConstants.fractionalWidthLeading),
                heightDimension: .fractionalHeight(LayoutConstants.fractionalConstant)))
        leadingItem.contentInsets = NSDirectionalEdgeInsets(top: LayoutConstants.topInset,
                                                            leading: LayoutConstants.topInset,
                                                            bottom: LayoutConstants.bottomInset,
                                                            trailing: LayoutConstants.leadingInset)

        let trailingItem = NSCollectionLayoutItem(
            layoutSize: NSCollectionLayoutSize(
                widthDimension: .fractionalWidth(LayoutConstants.fractionalWidthTrailing),
                heightDimension: .fractionalHeight(LayoutConstants.fractionalHeightTrailing)))
        trailingItem.contentInsets = NSDirectionalEdgeInsets(top: LayoutConstants.topInset,
                                                             leading: LayoutConstants.leadingInset,
                                                             bottom: LayoutConstants.bottomInset,
                                                             trailing: LayoutConstants.leadingInset)

        let trailingGroup = NSCollectionLayoutGroup.vertical(
            layoutSize: NSCollectionLayoutSize(
                widthDimension: .fractionalWidth(LayoutConstants.groupFractionalHeight),
                heightDimension: .fractionalHeight(LayoutConstants.fractionalConstant)),
            subitem: trailingItem,
            count: LayoutConstants.itemCount)

        var subitems: [NSCollectionLayoutItem] = []
        subitems.append(leadingItem)
        subitems.append(trailingGroup)

        let containerGroup = NSCollectionLayoutGroup.horizontal(
            layoutSize: NSCollectionLayoutSize(
                widthDimension: .fractionalWidth(LayoutConstants.fractionalContainerWidth),
                heightDimension: .absolute(LayoutConstants.largeGroupHeight)),
            subitems: subitems)
        let section = NSCollectionLayoutSection(group: containerGroup)
        section.orthogonalScrollingBehavior = .continuous
        return section
    }
}
```

答:
I found different approach to do it as following:

I will use two sections.

Section1 for the first number, it will hold a group of one item.

Section2 for everything else, it will hold a group of two items (stacked vertically).

We need to change the scroll direction of collection view to horizontal.

Normally all sections are stacked vertically, so the two sections will be stacked vertically and won't give us what we want.

We need to change the layout configurations for groups and items so it can work correctly for the horizontal scroll direction.

That's it, now for the code.

ADVICE: Please try to gradually move from your solution to mine to learn the different issues I learned while testing, it will help you understand why for each piece.

NOTE: I used values instead of your constants so it doesn't confuse you, because now constants need to be changed/renamed to fit this approach.

Section1 (One group of one item)

func createSection1() -> NSCollectionLayoutSection {
    let item = NSCollectionLayoutItem(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalHeight(1.0)
        )
    )
    item.contentInsets = NSDirectionalEdgeInsets(
        top: 10,
        leading: 10,
        bottom: 15,
        trailing: 8
    )

    let group = NSCollectionLayoutGroup.horizontal(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(0.67),
            heightDimension: .absolute(406)
        ),
        subitem: item,
        count: 1
    )

    return NSCollectionLayoutSection(group: group)
}
```
<ul>
<li>Section2 (One group of two items stacked vertically)</li>
</ul>
<pre class="lang-swift prettyprint-override"><code>func createSection2() -> NSCollectionLayoutSection {

    let item = NSCollectionLayoutItem(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalHeight(0.3)
        )
    )
    item.contentInsets = NSDirectionalEdgeInsets(
        top: 10,
        leading: 8,
        bottom: 15,
        trailing: 8
    )

    let group = NSCollectionLayoutGroup.vertical(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(0.33),
            heightDimension: .absolute(406)
        ),
        subitem: item,
        count: 2
    )

    let section = NSCollectionLayoutSection(group: group)
    return section
}
</code>```

The final layout

Please notice the line indicating scrollDirection change

func createLayout() -> UICollectionViewLayout {
    let layout = UICollectionViewCompositionalLayout {
        [weak self] (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
        guard let self = self else { return nil }

        if sectionIndex == 0 {
            return self.createSection1()
        } else {
            return self.createSection2()
        }
    }

    // Changing scrollDirection
    let config = UICollectionViewCompositionalLayoutConfiguration()
    config.scrollDirection = .horizontal
    layout.configuration = config

    return layout
}
```
<ul>
<li>Finally, here as suggession of how to handle it in datasource</li>
</ul>
<pre class="lang-swift prettyprint-override"><code>func numberOfSections(in collectionView: UICollectionView) -> Int {
    2
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    data.isEmpty
        ? 0
        : section == 0 ? 1 : data.count - 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(
        withReuseIdentifier: String(describing: Cell.self),
        for: indexPath
    ) as! Cell

    if indexPath.section == 0 {
        cell.number = data[0]
        cell.color = colors[0]
    } else {
        cell.number = data[indexPath.row + 1]
        cell.color = colors[indexPath.row + 1]
    }

    return cell
}
</code>```

Demo

That's it, please let me know if you have any question.

Reference:
Side-by-side sections in UICollectionViewCompositionalLayout?

Body:
I found different approach to do it as following:

I will use two sections.

Section1 for the first number, it will hold a group of one item.

Section2 for everything else, it will hold a group of two items (stacked vertically).

We need to change the scroll direction of collection view to horizontal.

Normally all sections are stacked vertically, so the two sections will be stacked vertically and won't give us what we want.

We need to change the layout configurations for groups and items so it can work correctly for the horizontal scroll direction.

That's it, now for the code.

ADVICE: Please try to gradually move from your solution to mine to learn the different issues I learned while testing, it will help you understand why for each piece.

NOTE: I used values instead of your constants so it doesn't confuse you, because now constants need to be changed/renamed to fit this approach.

Section1 (One group of one item)

func createSection1() -> NSCollectionLayoutSection {
    let item = NSCollectionLayoutItem(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalHeight(1.0)
        )
    )
    item.contentInsets = NSDirectionalEdgeInsets(
        top: 10,
        leading: 10,
        bottom: 15,
        trailing: 8
    )

    let group = NSCollectionLayoutGroup.horizontal(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(0.67),
            heightDimension: .absolute(406)
        ),
        subitem: item,
        count: 1
    )

    return NSCollectionLayoutSection(group: group)
}

Section2 (One group of two items stacked vertically)

func createSection2() -> NSCollectionLayoutSection {

    let item = NSCollectionLayoutItem(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalHeight(0.3)
        )
    )
    item.contentInsets = NSDirectionalEdgeInsets(
        top: 10,
        leading: 8,
        bottom: 15,
        trailing: 8
    )

    let group = NSCollectionLayoutGroup.vertical(
        layoutSize: NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(0.33),
            heightDimension: .absolute(406)
        ),
        subitem: item,
        count: 2
    )

    let section = NSCollectionLayoutSection(group: group)
    return section
}

The final layout

Please notice the line indicating scrollDirection change

func createLayout() -> UICollectionViewLayout {
    let layout = UICollectionViewCompositionalLayout {
        [weak self] (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
        guard let self = self else { return nil }

        if sectionIndex == 0 {
            return self.createSection1()
        } else {
            return self.createSection2()
        }
    }

    // Changing scrollDirection
    let config = UICollectionViewCompositionalLayoutConfiguration()
    config.scrollDirection = .horizontal
    layout.configuration = config

    return layout
}

Finally, here as suggession of how to handle it in datasource

func numberOfSections(in collectionView: UICollectionView) -> Int {
    2
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    data.isEmpty
        ? 0
        : section == 0 ? 1 : data.count - 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(
        withReuseIdentifier: String(describing: Cell.self),
        for: indexPath
    ) as! Cell

    if indexPath.section == 0 {
        cell.number = data[0]
        cell.color = colors[0]
    } else {
        cell.number = data[indexPath.row + 1]
        cell.color = colors[indexPath.row + 1]
    }

    return cell
}

Demo

That's it, please let me know if you have any question.

Reference:
Side-by-side sections in UICollectionViewCompositionalLayout?


问:
Flutter show/hide widget
I'm trying to show a widget onFinished countdown timer but I can't seem to make it work.
I've added var reqPIN = false;

And here is my code:

```<code>        children [
         Countdown(
            seconds: 3,
            build: (_, double time) =>
                RichText(
                  text: TextSpan(
                    text: 'Reset PIN in ',
                    style: TextStyle(
                      color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: time.toString(),
                      style: TextStyle(
                        color: Color(0xFF2481CF),
                        fontWeight: FontWeight.bold
                      )),
                      TextSpan(text: ' sec',
                      style: TextStyle(
                        color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                      ))
                    ]
                  ),
                ),
            onFinished: () {
              setState(() {
                reqPIN = true;
              });
            },
          ),
          SizedBox(
            child: Visibility(
              visible: reqPIN,
              child: Text('Resend PIN',
              style: TextStyle(
                color: Colors.black
              ),),
            ),
          )
        ]
</code>```

Is there any solution?

答:
Try this one.</p>
```<code>if (reqPIN)
   SizedBox(
     child: Text('Resend PIN', style: TextStyle(color: Colors.black)),
    ),
</code>```

Title: Flutter show/hide widget

Body:
I'm trying to show a widget onFinished countdown timer but I can't seem to make it work.
I've added var reqPIN = false;

And here is my code:

        children [
         Countdown(
            seconds: 3,
            build: (_, double time) =>
                RichText(
                  text: TextSpan(
                    text: 'Reset PIN in ',
                    style: TextStyle(
                      color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: time.toString(),
                      style: TextStyle(
                        color: Color(0xFF2481CF),
                        fontWeight: FontWeight.bold
                      )),
                      TextSpan(text: ' sec',
                      style: TextStyle(
                        color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                      ))
                    ]
                  ),
                ),
            onFinished: () {
              setState(() {
                reqPIN = true;
              });
            },
          ),
          SizedBox(
            child: Visibility(
              visible: reqPIN,
              child: Text('Resend PIN',
              style: TextStyle(
                color: Colors.black
              ),),
            ),
          )
        ]

Is there any solution?

Body:
Try this one.

if (reqPIN)
   SizedBox(
     child: Text('Resend PIN', style: TextStyle(color: Colors.black)),
    ),


问:
Intelligent code-completion? Is there AI to write code by learning?
I am asking this question because I know there are a lot of well-read CS types on here who can give a clear answer.

I am wondering if such an AI exists (or is being researched/developed) that it writes programs by generating and compiling code all on it's own and then progresses by learning from former iterations.  I am talking about working to make us, programmers, obsolete.  I'm imagining something that learns what works and what doesn't in a programming languages by trial and error.

I know this sounds pie-in-the-sky so I'm asking to find out what's been done, if anything.

Of course even a human programmer needs inputs and specifications, so such an experiment has to have carefully defined parameters.  Like if the AI was going to explore different timing functions, that aspect has to be clearly defined.

But with a sophisticated learning AI I'd be curious to see what it might generate.

I know there are a lot of human qualities computers can't replicate like our judgement, tastes and prejudices.  But my imagination likes the idea of a program that spits out a web site after a day of thinking and lets me see what it came up with, and even still I would often expect it to be garbage; but maybe once a day I maybe give it feedback and help it learn.

Another avenue of this thought is it would be nice to give a high-level description like "menued website" or "image tools" and it generates code with enough depth that would be useful as a code completion module for me to then code in the details.  But I suppose that could be envisioned as a non-intelligent static hierarchical code completion scheme.

How about it?

答:
Such tools exist. They are the subject of a discipline called Genetic Programming. How you evaluate their success depends on the scope of their application.

They have been extremely successful (orders of magnitude more efficient than humans) to design optimal programs for the management of industrial process, automated medical diagnosis, or integrated circuit design. Those processes are well constrained, with an explicit and immutable success measure, and a great amount of "universe knowledge", that is a large set of rules on what is a valid, working, program and what is not.

They have been totally useless in trying to build mainstream programs, that require user interaction, because the main item a system that learns needs is an explicit "fitness function", or evaluation of the quality of the current solution it has come up with.

Another domain that can be seen in dealing with "program learning" is Inductive Logic Programming, although it is more used to provide automatic demonstration or language / taxonomy learning.

OwnerDisplayName: tkotitan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Neil N

OwnerDisplayName: Varkhan

LastEditorDisplayName: Varkhan


问:
Video playing in html div
I have following definition.

```<code><video controls="controls" autoplay="false" style="width:95%; height:300px;">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/mp4">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/ogg">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/webm">
    <object data="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
          <embed src="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
              Your browser does not support video
    </object>
</video>
</code>```

Video is not playing at all.

Note:

I have got a list of 200 videos to be shown which are pointing to different sources, in addition to Youtube. Also, I will not know the type of the video (ie: MP4 or AVI or webM, etc).

答:
(1) Regarding "Video is not playing at all."

Youtube links are pointing to a web page not a video file.

You cannot use an HTML page in a video tag.

For Youtube, replace the <video> .... </video> code with an iframe pointing to their embed player.

Example where your Youtube link has a video ID of 4aYVLpY5FYU :

```<code><iframe width="600" height="400" frameborder="0"
src="https://www.youtube.com/embed/4aYVLpY5FYU"
></iframe>
</code>```

(2)  Regarding "I have got a list of 200 videos to be shown which are pointing to different sources".

The most reliable solution is to just give the iframe an ID so you can target it by JS code later on.

This means when your are ready to change the video to another link:

target the  by its ID then change it's source src= ...

Example of a iframe with ID.

```<code><iframe id="vid_container" width="600" height="400" frameborder="0"
src="https://www.youtube.com/embed/4aYVLpY5FYU"
></iframe>
</code>```

At this point you could have a change_video( someParams ); function that expects a link as the function parameter. The function then changes the source of the iframe to the newly specified video URL (the function parameter).

```<code>change_video( "https://youtu.be/drQWopZDEEY" ); //# call the function
</code>```

When called, the function does something like this.

```<code>function change_vid( inputPath )
{
    let container = document.getElementById("vid_container");
    container.src = inputPath;

}
</code>```

Title: Video playing in html div

Body:
I have following definition.

<video controls="controls" autoplay="false" style="width:95%; height:300px;">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/mp4">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/ogg">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/webm">
    <object data="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
          <embed src="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
              Your browser does not support video
    </object>
</video>

Video is not playing at all.

Note:

I have got a list of 200 videos to be shown which are pointing to different sources, in addition to Youtube. Also, I will not know the type of the video (ie: MP4 or AVI or webM, etc).

Body:
(1) Regarding "Video is not playing at all."

Youtube links are pointing to a web page not a video file.

You cannot use an HTML page in a video tag.

For Youtube, replace the <video> .... </video> code with an iframe pointing to their embed player.

Example where your Youtube link has a video ID of 4aYVLpY5FYU :

<iframe width="600" height="400" frameborder="0"
src="https://www.youtube.com/embed/4aYVLpY5FYU"
></iframe>

(2)  Regarding "I have got a list of 200 videos to be shown which are pointing to different sources".

The most reliable solution is to just give the iframe an ID so you can target it by JS code later on.

This means when your are ready to change the video to another link:

target the <iframe> by its ID then change it's source src= ...

Example of a iframe with ID.

<iframe id="vid_container" width="600" height="400" frameborder="0"
src="https://www.youtube.com/embed/4aYVLpY5FYU"
></iframe>

At this point you could have a change_video( someParams ); function that expects a link as the function parameter. The function then changes the source of the iframe to the newly specified video URL (the function parameter).

change_video( "https://youtu.be/drQWopZDEEY" ); //# call the function

When called, the function does something like this.

function change_vid( inputPath )
{
    let container = document.getElementById("vid_container");
    container.src = inputPath;

}


问:
TypeError: Cannot read properties of undefined (reading 'total')
I've been working on a React project along with fetching Data from rapidAPI.
But whenever I rum my project I've been getting this error again and again.

```<code>TypeError: Cannot read properties of undefined (reading 'total')
Homepage
src/components/Homepage.jsx:23
  20 | <>
  21 |   <Title level={2} className="heading">Global Crypto Stats</Title>
  22 |   <Row gutter={[32, 32]}>
> 23 |     <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
     | ^  24 |     <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
  25 |     <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
  26 |     <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
</code>```

Here are the files that I've been looking in to debug.

App.js

```<code>import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import { Layout, Typography, Space } from 'antd';

import { Exchanges, Homepage, News, Cryptocurrencies, CryptoDetails, Navbar } from './components';
import './App.css';

const App = () => (
  <div className="app">
    <div className="navbar">
      <Navbar />
    </div>
    <div className="main">
      <Layout>
        <div className="routes">
          <Switch>
            <Route exact path="/">
              <Homepage />
            </Route>
            <Route exact path="/exchanges">
              <Exchanges />
            </Route>
            <Route exact path="/cryptocurrencies">
              <Cryptocurrencies />
            </Route>
            <Route exact path="/crypto/:coinId">
              <CryptoDetails />
            </Route>
            <Route exact path="/news">
              <News />
            </Route>
          </Switch>
        </div>
      </Layout>
      <div className="footer">
        <Typography.Title level={5} style={{ color: 'white', textAlign: 'center' }}>Copyright © 2021
          <Link to="/">
            Cryptoverse Inc.
          </Link> <br />
          All Rights Reserved.
        </Typography.Title>
        <Space>
          <Link to="/">Home</Link>
          <Link to="/exchanges">Exchanges</Link>
          <Link to="/news">News</Link>
        </Space>
      </div>
    </div>
  </div>
);

export default App;
</code>```

Homepage.jsx

```<code>import React from 'react';
import millify from 'millify';
import { Typography, Row, Col, Statistic } from 'antd';
import { Link } from 'react-router-dom';

import { useGetCryptosQuery } from '../services/cryptoApi';
import Cryptocurrencies from './Cryptocurrencies';
import News from './News';
import Loader from './Loader';

const { Title } = Typography;

const Homepage = () => {
  const { data, isFetching } = useGetCryptosQuery(10);
  const globalStats = data?.data?.stats;

  if (isFetching) return <Loader />;

  return (
    <>
      <Title level={2} className="heading">Global Crypto Stats</Title>
      <Row gutter={[32, 32]}>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
        <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
        <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Markets" value={millify(globalStats.totalMarkets)} /></Col>
      </Row>
      <div className="home-heading-container">
        <Title level={2} className="home-title">Top 10 Cryptos In The World</Title>
        <Title level={3} className="show-more"><Link to="/cryptocurrencies">Show more</Link></Title>
      </div>
      <Cryptocurrencies simplified />
      <div className="home-heading-container">
        <Title level={2} className="home-title">Latest Crypto News</Title>
        <Title level={3}><Link to="/news">Show more</Link></Title>
      </div>
      <News simplified />
    </>
  );
};

export default Homepage;
</code>```

services/cryptoApi.js

```<code>import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
    'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
    'x-rapidapi-key': '268c978691mshf443e1a9132dfdep1f3fe3jsn953b6183c440',
};

const baseUrl = 'https://coinranking1.p.rapidapi.com';

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
    reducerPath: 'cryptoApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
      getCryptos: builder.query({
        query: (count) => createRequest(`/coins/?limit=${count}`),
      }),
      getExchanges: builder.query({
        query: () => createRequest('/exchanges'),
      }),
      getCryptoDetails: builder.query({
        query: (coinId) => createRequest(`/coin/${coinId}`),
      }),
      getCryptoHistory: builder.query({
        query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history/${timeperiod}`),
      }),
    }),
  });

export const {
    useGetCryptosQuery,
    useGetCryptoDetailsQuery,
    useGetCryptoHistoryQuery,
    useGetExchangesQuery,
} = cryptoApi;
</code>```

I've tried a lot but the situation continues.
Any help would be highly appreciated.
Thank You in advance.

答:
Not sure if this is gonna help but have you tried rendering only when there is globalStats?
example :</p>
```<code> return (
    <>
{globalstats?  <>
      <Title level={2} className="heading">Global Crypto Stats</Title>
      <Row gutter={[32, 32]}>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
        <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
        <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Markets" value={millify(globalStats.totalMarkets)} /></Col>
      </Row>
      <div className="home-heading-container">
        <Title level={2} className="home-title">Top 10 Cryptos In The World</Title>
        <Title level={3} className="show-more"><Link to="/cryptocurrencies">Show more</Link></Title>
      </div>
      <Cryptocurrencies simplified />
      <div className="home-heading-container">
        <Title level={2} className="home-title">Latest Crypto News</Title>
        <Title level={3}><Link to="/news">Show more</Link></Title>
      </div>
      <News simplified />
</> : <> "" </> }
    </>
  );
</code>```

Body:
I've been working on a React project along with fetching Data from rapidAPI.
But whenever I rum my project I've been getting this error again and again.

TypeError: Cannot read properties of undefined (reading 'total')
Homepage
src/components/Homepage.jsx:23
  20 | <>
  21 |   <Title level={2} className="heading">Global Crypto Stats</Title>
  22 |   <Row gutter={[32, 32]}>
> 23 |     <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
     | ^  24 |     <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
  25 |     <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
  26 |     <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>

Here are the files that I've been looking in to debug.

App.js

import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import { Layout, Typography, Space } from 'antd';

import { Exchanges, Homepage, News, Cryptocurrencies, CryptoDetails, Navbar } from './components';
import './App.css';

const App = () => (

      <Navbar />

      <Layout>

          <Switch>
            <Route exact path="/">
              <Homepage />
            </Route>
            <Route exact path="/exchanges">
              <Exchanges />
            </Route>
            <Route exact path="/cryptocurrencies">
              <Cryptocurrencies />
            </Route>
            <Route exact path="/crypto/:coinId">
              <CryptoDetails />
            </Route>
            <Route exact path="/news">
              <News />
            </Route>
          </Switch>

      </Layout>

        <Typography.Title level={5} style={{ color: 'white', textAlign: 'center' }}>Copyright © 2021
          <Link to="/">
            Cryptoverse Inc.
          </Link>

          All Rights Reserved.
        </Typography.Title>
        <Space>
          <Link to="/">Home</Link>
          <Link to="/exchanges">Exchanges</Link>
          <Link to="/news">News</Link>
        </Space>

);

export default App;

Homepage.jsx

import React from 'react';
import millify from 'millify';
import { Typography, Row, Col, Statistic } from 'antd';
import { Link } from 'react-router-dom';

import { useGetCryptosQuery } from '../services/cryptoApi';
import Cryptocurrencies from './Cryptocurrencies';
import News from './News';
import Loader from './Loader';

const { Title } = Typography;

const Homepage = () => {
  const { data, isFetching } = useGetCryptosQuery(10);
  const globalStats = data?.data?.stats;

  if (isFetching) return <Loader />;

  return (
    <>
      <Title level={2} className="heading">Global Crypto Stats</Title>
      <Row gutter={[32, 32]}>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
        <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
        <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Markets" value={millify(globalStats.totalMarkets)} /></Col>
      </Row>

        <Title level={2} className="home-title">Top 10 Cryptos In The World</Title>
        <Title level={3} className="show-more"><Link to="/cryptocurrencies">Show more</Link></Title>

      <Cryptocurrencies simplified />

        <Title level={2} className="home-title">Latest Crypto News</Title>
        <Title level={3}><Link to="/news">Show more</Link></Title>

      <News simplified />
    </>
  );
};

export default Homepage;

services/cryptoApi.js

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
    'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
    'x-rapidapi-key': '268c978691mshf443e1a9132dfdep1f3fe3jsn953b6183c440',
};

const baseUrl = 'https://coinranking1.p.rapidapi.com';

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
    reducerPath: 'cryptoApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
      getCryptos: builder.query({
        query: (count) => createRequest(`/coins/?limit=${count}`),
      }),
      getExchanges: builder.query({
        query: () => createRequest('/exchanges'),
      }),
      getCryptoDetails: builder.query({
        query: (coinId) => createRequest(`/coin/${coinId}`),
      }),
      getCryptoHistory: builder.query({
        query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history/${timeperiod}`),
      }),
    }),
  });

export const {
    useGetCryptosQuery,
    useGetCryptoDetailsQuery,
    useGetCryptoHistoryQuery,
    useGetExchangesQuery,
} = cryptoApi;

I've tried a lot but the situation continues.
Any help would be highly appreciated.
Thank You in advance.

Body:
Not sure if this is gonna help but have you tried rendering only when there is globalStats?
example :

 return (
    <>
{globalstats?  <>
      <Title level={2} className="heading">Global Crypto Stats</Title>
      <Row gutter={[32, 32]}>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
        <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
        <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Markets" value={millify(globalStats.totalMarkets)} /></Col>
      </Row>
      <div className="home-heading-container">
        <Title level={2} className="home-title">Top 10 Cryptos In The World</Title>
        <Title level={3} className="show-more"><Link to="/cryptocurrencies">Show more</Link></Title>
      </div>
      <Cryptocurrencies simplified />
      <div className="home-heading-container">
        <Title level={2} className="home-title">Latest Crypto News</Title>
        <Title level={3}><Link to="/news">Show more</Link></Title>
      </div>
      <News simplified />
</> : <> "" </> }
    </>
  );


问:
How to make a container extend to the bottom without adding more length

body {
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

background: linear-gradient(to right, yellow, black);

}
.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: 35%;
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="middle-checklist-box-social">

    <div class="middle-checklist-box-social">
        <label class="container" >
            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
        </label>
        <!-- Put in a grey line that seperates the checkbox from the others  -->
        <p class="chkbxLowerLine"></p>
        <!-- New Checkbox here under the line  -->
        <label class="container" >
            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
        </label>

    </div>

</div></code>```

I want a column in the middle to extend to the bottom of the page.  without adding more page content or space where you don't have to scroll to the bottom. I looked around for clues or if anyone has solved this, but of no luck.

I have tried 100vh, but it adds more content making me scroll down which I don't want.

Here is the picture because there is a lot of code in it, but I have position relative,

But I want the end of the white box with the checkbox to reach the bottom of the page

答:
You using 2 times the same wrapper class for this box .middle-checklist-box-social, setting it to 100vh + the paddings included will extend it.
Browsers by default also include margin, which you can change by setting a value or simply setting it to zero.

If you are applying dimensions to an element and want to make sure they don't exceed this width/height because of added padding, you can set the box model of that element to box-sizing: border-box; or set it globally like this: *, *::before, *::after {box-sizing: border-box;}

@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

*, *::before, *::after {box-sizing: border-box;}

body {
  background: linear-gradient(to right, yellow, black);
  padding: 1rem;
  margin: 0;
}

.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: calc(100vh - 2rem);
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="middle-checklist-box-social">

    <label class="container" >
        <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
        <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
    </label>
    <!-- Put in a grey line that seperates the checkbox from the others  -->
    <p class="chkbxLowerLine"></p>
    <!-- New Checkbox here under the line  -->
    <label class="container" >
        <input id="chkbx002" class="giannisCheckbox" type="checkbox">
        <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
    </label>

</div></code>```

Body:
body {
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

background: linear-gradient(to right, yellow, black);

}
.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: 35%;
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}

            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            Social Studies Unit 8 Review (Graded)

            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            Georgia 3.2.1. GO Project

I want a column in the middle to extend to the bottom of the page.  without adding more page content or space where you don't have to scroll to the bottom. I looked around for clues or if anyone has solved this, but of no luck.

I have tried 100vh, but it adds more content making me scroll down which I don't want.

Here is the picture because there is a lot of code in it, but I have position relative,

But I want the end of the white box with the checkbox to reach the bottom of the page

Body:
You using 2 times the same wrapper class for this box .middle-checklist-box-social, setting it to 100vh + the paddings included will extend it.
Browsers by default also include margin, which you can change by setting a value or simply setting it to zero.

If you are applying dimensions to an element and want to make sure they don't exceed this width/height because of added padding, you can set the box model of that element to box-sizing: border-box; or set it globally like this: *, *::before, *::after {box-sizing: border-box;}

@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

*, *::before, *::after {box-sizing: border-box;}

body {
  background: linear-gradient(to right, yellow, black);
  padding: 1rem;
  margin: 0;
}

.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: calc(100vh - 2rem);
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}

<div class="middle-checklist-box-social">

    <label class="container" >
        <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
        <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
    </label>
    <!-- Put in a grey line that seperates the checkbox from the others  -->
    <p class="chkbxLowerLine"></p>
    <!-- New Checkbox here under the line  -->
    <label class="container" >
        <input id="chkbx002" class="giannisCheckbox" type="checkbox">
        <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
    </label>

</div>


问:
why I cannot sum all number between two rows?
I am trying to write a code that sum all the data in a column named AMOUNT between two rows in a column named DATA in a table named PERSON and I used the sum function and I use between function
and I got the following error:

```<code>java.sql.SQLSyntaxErrorException: Syntax error:
    Encountered "BETWEEN" at line 1, column 45.
</code>```

the code :

```<code>  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

       Connection con = null;
       ResultSet rs = null;
       PreparedStatement ps = null;
       try {
           String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT " +
               "FROM PERSON BETWEEN DATE=? AND DATE=?";
           con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices",
                                             "user1", "password");
           ps = con.prepareStatement(sql);
           ps.setString(1, jTextField1.getText());
           ps.setString(2, jTextField2.getText());
           rs = ps.executeQuery();
           if (rs.next()) {
               String sum = rs.getString("sumAmount");
               jLabel3.setText(sum);
           }
       } catch(Exception ex) {
           ex.printStackTrace();
       }
   }
</code>```

答:
Try something like this:</p>
```<code>String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT FROM PERSON " +
    "WHERE (col_name) between '2020-05-01 00:58:26' " +
    "and '2021-06-18 19:53:17'";
</code>```

Body:
I am trying to write a code that sum all the data in a column named AMOUNT between two rows in a column named DATA in a table named PERSON and I used the sum function and I use between function
and I got the following error:

java.sql.SQLSyntaxErrorException: Syntax error:
    Encountered "BETWEEN" at line 1, column 45.

the code :

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

       Connection con = null;
       ResultSet rs = null;
       PreparedStatement ps = null;
       try {
           String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT " +
               "FROM PERSON BETWEEN DATE=? AND DATE=?";
           con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices",
                                             "user1", "password");
           ps = con.prepareStatement(sql);
           ps.setString(1, jTextField1.getText());
           ps.setString(2, jTextField2.getText());
           rs = ps.executeQuery();
           if (rs.next()) {
               String sum = rs.getString("sumAmount");
               jLabel3.setText(sum);
           }
       } catch(Exception ex) {
           ex.printStackTrace();
       }
   }

Body:
Try something like this:

String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT FROM PERSON " +
    "WHERE (col_name) between '2020-05-01 00:58:26' " +
    "and '2021-06-18 19:53:17'";


问:
Problems with android Compose
I am trying to work through a tutorial on android compose. It works well while I use:kotlin-gradle-plugin:1.5.31, but the android studio has updated to :kotlin-gradle-plugin:1.6.10, and when I try running the program again it doesn't compile. I don't understand what the problem is. but even in the original run with the old version, I get the following message:

w: ATTENTION!
This build uses unsafe internal compiler arguments:
-XXLanguage:+NonParenthesizedAnnotationsOnFunctionalTypes
This mode is not recommended for production use,
as no stability/compatibility guarantees are given on
compiler or generated code. Use it at your own risk!

when I try the new version it tells me that I must migrate the code, but when I do this I get the following message:

e: This version (1.0.5) of the Compose Compiler requires Kotlin version 1.5.31 but you appear to be using Kotlin version 1.6.10 which is not known to be compatible.  Please fix your configuration (or suppressKotlinVersionCompatibilityCheck but don't say I didn't warn you!).

Task :app:mergeExtDexDebug
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org
BUILD FAILED in 10s
25 actionable tasks: 23 executed, 2 up-to-date

and you can't migrate back even if you want to.

I don't know what to do with this or how to proceed forward.

答:
Finally, Figure out and fix the issue to run compose version

Currently Stable version 1.1.0

So here is my code for build.gradle(Project:app)

```<code>buildscript {
    ext {
        compose_version = '1.1.0'
    }

    dependencies {

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

build.gradle(Module)

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.dreammeanings"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}
</code>```

Title: Problems with android Compose

Body:
Finally, Figure out and fix the issue to run compose version

Currently Stable version 1.1.0

So here is my code for build.gradle(Project:app)

buildscript {
    ext {
        compose_version = '1.1.0'
    }

    dependencies {

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(Module)

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.dreammeanings"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}


问:
How to make fields optional in Kotlin serialization in using it in retrofit?
I have an API which its response is kind of dynamic. I mean sometimes it return a Jason object with "token" value, and sometimes it returns with "message" value. For handling this scenario I decided to have both field in my data class like below:

```<code>data class response {
   val message:String;
   val token:String;
}
</code>```

Now I want to make both fields optional in Kotlin serialization. I mean, I want to tell Kotlin serialization that if you couldn't find token in response JSON it's ok to ignore it.
How can I achieve this?

答:
All Kotlin properties with default values are automatically optional.
All I need to do is this:</p>
```<code>data class response {
   val message:String="";
   val token:String="";
}
</code>```

Body:
I have an API which its response is kind of dynamic. I mean sometimes it return a Jason object with "token" value, and sometimes it returns with "message" value. For handling this scenario I decided to have both field in my data class like below:

data class response {
   val message:String;
   val token:String;
}

Now I want to make both fields optional in Kotlin serialization. I mean, I want to tell Kotlin serialization that if you couldn't find token in response JSON it's ok to ignore it.
How can I achieve this?

Body:
All Kotlin properties with default values are automatically optional.
All I need to do is this:

data class response {
   val message:String="";
   val token:String="";
}


问:
how can get part of link very important
how can i get from this link http://127.0.0.1:4000/resetPassword/3067a7a5b300f90ee593508647a7dbf7aa38a47b15808e69aa8b5421ea0f1408 the number after resetPassword/
can any one help me??</p>

答:
const str = 'http://127.0.0.1:4000/resetPassword/3067a7a5b300f90ee593508647a7dbf7aa38a47b15808e69aa8b5421ea0f1408';

const regex = /(?<=resetPassword\/).+/;
const result  = str.match(regex);
console.log(result?.[0]);```

Title: how can get part of link very important


问:
getting and storing user ip address javascript
I am a newby of javascript and in general programming. I have a google site and I would like to record the ip of the users submitting a form from the site. I saw, googling around that it is possible to use external service to obtain the ip address but I am trying to figure out how to set up a script (a javascript i suppose) in my site to accomplish the task.

In particular, what i need is the following:

1) a script from within the site has to get the ip address. I have found the following code in your forum that should do the job.

```<code><script type="application/javascript">
  function getip(json){
    alert(json); // alerts the ip address
  }

</script>

<script type="application/javascript"
       src="http://www.anotherdomain.com/file.php? callback=getip">
</script>
</code>```

How can I call it from a javascript function?

2) after getting the ip address I would like to fill with it a text area of the form and at its submission it should be sent to a google spreadsheet.
How can I get the ip output and send it to the textbox using javascript code?

答:
You are absolutley right that you can get a users IP address only by using external sources. Let's do it using ipify.org!

So the check out the documentation here. There you will find that you need 2 things.

set the

notice that the

ContentLicense: CC BY-SA 3.0

Body:
I am a newby of javascript and in general programming. I have a google site and I would like to record the ip of the users submitting a form from the site. I saw, googling around that it is possible to use external service to obtain the ip address but I am trying to figure out how to set up a script (a javascript i suppose) in my site to accomplish the task.

In particular, what i need is the following:

1) a script from within the site has to get the ip address. I have found the following code in your forum that should do the job.

How can I call it from a javascript function?

2) after getting the ip address I would like to fill with it a text area of the form and at its submission it should be sent to a google spreadsheet.
How can I get the ip output and send it to the textbox using javascript code?

Body:
You are absolutley right that you can get a users IP address only by using external sources. Let's do it using ipify.org!

So the check out the documentation here. There you will find that you need 2 things.

set the <script> after your HTML body has loaded as follows;

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP" defer></script>

notice that the <script> tag will contact ipify.com and return the users IP address that is then pass to our JavaScript function called getIP() as JSONP.

Set the function below, here is one that I wrote that sets the value of a <textarea> in a <div>;

         function getIP(json){
            document.getElementById("ipaddress").value = json.ip;
         }

this is the <div>:

<div style="display: none;">
    <label>Ip address is:</label>
    <textarea id="ipaddress"></textarea>
</div>

Notice that I set the <style> to be; display: none; and the id="ipaddress" for the <textarea>. This will set that <div> to not display to your user and It makes it much easer to pass our IP address to our server/database. Like this:

function submit(){
        let someValue = document.getElementById('someValue').value;
        let someotherValue = document.getElementById('someotherValue').value;
        let ip = document.getElementById('ipaddress').value;
       var formData = {
         someValue,someotherValue,ip
       }
       google.script.run.serverSideFunction(formData)
       }


答:
globalStats is undefined here; at the time of this error. You can use the optional chaining operator ?. (value={globalStats?.total}):

```<code><Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats?.total} /></Col>
</code>```

or you can return null when globalStats is not defined:

```<code>if (!globalStats) return null;
</code>```

Title: TypeError: Cannot read properties of undefined (reading 'total')

Body:
globalStats is undefined here; at the time of this error. You can use the optional chaining operator ?. (value={globalStats?.total}):

<Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats?.total} /></Col>

or you can return null when globalStats is not defined:

if (!globalStats) return null;


问:
ActCtx + manifest + comhost + .NET 6.0: does it work, does anyone has a working example?
My goal is to expose a .NET 6.0 library to COM, in order to use it from VBA in MS Access. And to use the manifest approach rather than using the registry.

Got article "Exposing .NET Core components to COM" working, using their "COM server sample" example code.

This example however requires that a manifest file is present in the folder containing the executable. When using the COM object from MS Access we do not want to place the manifest file and other files in the MS installation folders.

The suggested solution is to create an Microsoft.Windows.ActCtx object and let that object create my COM object, using the Manifest property of the ActCtx object to specify the manifest file.

This is the part that continues to fail. actCtx.CreateObject("") gives an Invalid Cast exception, even without assignment of the result to a variable, hence it is an internal issue. No additional details, no information in the event log. Tried this in C# and from VBA.

I have a few questions:

Is ActCtx the way to specify the manifest path, or is there a better way to do this from VBA in MS Office?

The example uses a COM host, which seems to be some COM class / object factory, which in turn helps creating my COM object. As opposed to .NET Framework this COM host seems to be introduced for .NET Core; .NET 6.0 in my case. Is the COM host required? Is the simpler direct instantiation possible?

Does anyone has answers to these questions, tips, or even better: a working example?

答:
Some progress but I am still not happy. Abandoned the ActCtx approach for a while and tried to create the COM server object of the sample directly in MS Access VBA. Added a reference to the com host, say COMServer.comhost.dll, as opposed to the implementation COMServer.dll. Created the object, simply with New. Error: class not registered. Performed a regsvr32 COMServer.comhost.dll and the sample works.

Although the sample works there are now again registry entries: the guid of the server class has been added to the registry. Regfree COM not achieved.

This is despite COMServer.comhost.dll looking promising. A tlb type library built separately and embedded in the .dll is seen by VBA: intellisense works and the object browser works. The manifest seems to be correctly embedded in the .dll too, and takes precedence over the manifest on disk.

The question remains how to avoid the regsvr32 step and make the solution working by just adding the reference to COMServer.comhost.dll, in MS Access VBA.


问:
How do you create an ACF custom location rule to compare post meta keys to meta values?
Let's say you create a WordPress post and assign it a meta key foo with value bar. You only want to display an ACF field if foo is equal to bar. However, there's no built-in location rule in ACF to do this. How would you solve this problem by creating an ACF custom location rule?

答:
In order to display ACF fields if a post meta key is equal or not equal to some value, use the following snippet. It's based off of the ACF Custom Location Rules guide.

if( ! defined( 'ABSPATH' ) ) exit;

class My_ACF_Location_Post_Meta extends ACF_Location {

    public function initialize() {
        $this->name = 'post_meta';
        $this->label = __( "Post Meta", 'acf' );
        $this->category = 'post';
        $this->object_type = 'post';
    }

    public function rule_values($choices, $rule){

        if(!acf_is_screen('acf-field-group') && !acf_is_ajax('acf/field_group/render_location_rule')){

            return array(
                $rule['meta_key']   => $rule['meta_key'],
                $rule['meta_value'] => $rule['meta_value']
            );

        }

        ob_start();

        acf_render_field(array(
            'type'        => 'text',
            'name'        => 'meta_key',
            'prefix'      => 'acf_field_group[location]['.$rule['group'].']['.$rule['id'].']',
            'value'       => (isset($rule['meta_key']) ? $rule['meta_key'] : ''),
            'placeholder' => 'Meta Key'
        ));

        acf_render_field(array(
            'type'        => 'text',
            'name'        => 'meta_value',
            'prefix'      => 'acf_field_group[location]['.$rule['group'].']['.$rule['id'].']',
            'value'       => (isset($rule['meta_value']) ? $rule['meta_value'] : ''),
            'placeholder' => 'Meta Value'
        ));

        return ob_get_clean();

    }

    public function rule_operators($choices, $rule){

        $choices = [];
        $choices['key_is_equal_to_value']    = __('key is equal to value', 'acf');
        $choices['key_is_not_equal_to_value']   = __('key is not equal to value', 'acf');

        return $choices;

    }

    public function match( $rule, $screen, $field_group ) {

        // Check screen args for "post_id" which will exist when editing a post.
        // Return false for all other edit screens.
        if( isset($screen['post_id']) ) {
            $post_id = $screen['post_id'];
        } elseif (isset($screen['attachment_id'])) {
            $post_id = $screen['attachment_id'];
        } else {
            return false;
        }

        // Load the post meta object for this edit screen.
        $post_meta_value = get_post_meta( $post_id, $rule['meta_key'], true );
        if( !$post_meta_value ) {
            return false;
        }

        // Compare the Post's meta value to rule meta value.
        $result = ( strval($post_meta_value) == $rule['meta_value'] );

        // Return result taking into account the operator type.
        if( $rule['operator'] == 'key_is_not_equal_to_value' ) {
            return !$result;
        }
        return $result;
    }
}

add_action('acf/init', 'my_acf_init_location_types');
function my_acf_init_location_types() {
    // Check function exists, then include and register the custom location type class.
    if( function_exists('acf_register_location_type') ) {
        acf_register_location_type( 'My_ACF_Location_Post_Meta' );
    }
}
```


问:
Convert DateTime 1/20/2022 8:48:30 PM to 20/01/2022 8:48:30 PM C#
I basically have two DateTime variables

```<code> DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
 DateTime dateFinish;
</code>```

dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:

```<code>if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}
</code>```

I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.

答:
Try and keep things as simple as possible.

As stated above you can compare date time with the > operator. But I would go further and ask why you're using that api to get the current date and time when you could just use this

```<code>DateTime today = DateTime.Now;
</code>```

This should fix your problem, because you should be initialising date time in the same way now. If not, then I suggest you take a look at this other questions answers:

Convert DateTime to a specified Format

Body:
I basically have two DateTime variables

 DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
 DateTime dateFinish;

dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:

if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}

I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.

Body:
Try and keep things as simple as possible.

As stated above you can compare date time with the > operator. But I would go further and ask why you're using that api to get the current date and time when you could just use this

DateTime today = DateTime.Now;

This should fix your problem, because you should be initialising date time in the same way now. If not, then I suggest you take a look at this other questions answers:

Convert DateTime to a specified Format


答:
when you are passing value to your <Col /> tag in src/components/Homepage.jsx:23 , you passed globalStats.total

but when the application arrives at this line, globalStats is still empty.
you should handle what to do in this situation

for example, you can check null condition when you are reading it like this :

```<code>value={globalStats?.total}
</code>```

or maybe you want to declare a default value when you are declaring your main variable like this :

```<code>  const globalStats = data?.data?.stats ?? {}
  // globalStats will be an empty object if your data?.data?.stats be empty

</code>```

or maybe you want to show loading if it was empty like this :

```<code>  const globalStats = data?.data?.stats;
  if (isFetching || !globalStats) return <Loader />;
</code>```

Body:
when you are passing value to your <Col /> tag in src/components/Homepage.jsx:23 , you passed globalStats.total

but when the application arrives at this line, globalStats is still empty.
you should handle what to do in this situation

for example, you can check null condition when you are reading it like this :

value={globalStats?.total}

or maybe you want to declare a default value when you are declaring your main variable like this :

  const globalStats = data?.data?.stats ?? {}
  // globalStats will be an empty object if your data?.data?.stats be empty

or maybe you want to show loading if it was empty like this :

  const globalStats = data?.data?.stats;
  if (isFetching || !globalStats) return <Loader />;


问:
Time sorting in python
I have searched the questions on here and found that some questions are very similar to my question but not exactly what I'm after. Apologies if this has indeed been asked for before.

I would like to be able to time the bubble sort and insertion sort options in my programme and have the time it took to sort printed below the sorted array of random integers. I have tried a couple of things but to be honest I don't even know where to start with this part of the challenge. Any help you could give me would be so appreciated

```<code>import random
import time

listnum = int(input("What size list would you like? "))
randomlist = random.sample(range(0, 5000), listnum)
print(randomlist)
sort_i = input("Would you like to sort your list Y or N? ")

if sort_i == "Y":
    search_i = input("Bubble sort or Insertion sort? ")
    if search_i == "Bubble sort":

        for i in range(len(randomlist) - 1, 0, -1):
            for j in range(i):
                if randomlist[j] > randomlist[j + 1]:
                    randomlist[j], randomlist[j + 1] = randomlist[j + 1], randomlist[j]

    if search_i == "Insertion sort":
        for i in range(1, len(randomlist)):
            key = randomlist[i]
            j = i - 1
            while j >= 0 and key < randomlist[j]:
                randomlist[j + 1] = randomlist[j]
                j -= 1
            randomlist[j + 1] = key
    print(randomlist)
elif sort_i == "N":

    lin_search_num = int(input("What number would you like to linear search? "))
    for s in range(len(randomlist)):
        if randomlist[s] == lin_search_num:
            print("Your number is at index " + str(s + 1))
</code>```

答:
May I suggest this?

```<code>import time

start = time.time() # in seconds since epoch
# your code
end = time.time()

print("{:.3f}".format(end - start), "seconds")
</code>```

Actually, it would be better to use time.process_time() instead of time.time().

Title: Time sorting in python

Body:
I have searched the questions on here and found that some questions are very similar to my question but not exactly what I'm after. Apologies if this has indeed been asked for before.

I would like to be able to time the bubble sort and insertion sort options in my programme and have the time it took to sort printed below the sorted array of random integers. I have tried a couple of things but to be honest I don't even know where to start with this part of the challenge. Any help you could give me would be so appreciated

import random
import time

listnum = int(input("What size list would you like? "))
randomlist = random.sample(range(0, 5000), listnum)
print(randomlist)
sort_i = input("Would you like to sort your list Y or N? ")

if sort_i == "Y":
    search_i = input("Bubble sort or Insertion sort? ")
    if search_i == "Bubble sort":

        for i in range(len(randomlist) - 1, 0, -1):
            for j in range(i):
                if randomlist[j] > randomlist[j + 1]:
                    randomlist[j], randomlist[j + 1] = randomlist[j + 1], randomlist[j]

    if search_i == "Insertion sort":
        for i in range(1, len(randomlist)):
            key = randomlist[i]
            j = i - 1
            while j >= 0 and key < randomlist[j]:
                randomlist[j + 1] = randomlist[j]
                j -= 1
            randomlist[j + 1] = key
    print(randomlist)
elif sort_i == "N":

    lin_search_num = int(input("What number would you like to linear search? "))
    for s in range(len(randomlist)):
        if randomlist[s] == lin_search_num:
            print("Your number is at index " + str(s + 1))

Body:
May I suggest this?

import time

start = time.time() # in seconds since epoch
# your code
end = time.time()

print("{:.3f}".format(end - start), "seconds")

Actually, it would be better to use time.process_time() instead of time.time().