问:
Vertical smooth scroll with snap effect on the next or previous section
I need help replicating this https://swiper-master.webflow.io/full-page-vertical in pure vanilla js. I cannot figure out how to implement this. Kindly assist.

Expected output, smooth scroll from one section to the next either upwards or downwards based on mouse scroll or keyboard arrow down up keys.

I have 6 sections in my html, but I want to target only the first 3 sections with this animation shown in this link https://swiper-master.webflow.io/full-page-vertical then the rest of the sections should just scroll "normal" without the scroll snap effect.

```<code><div>
    <section data-section="section1">
        <h2>Section 1</h2>
        <p>Content for section 1 goes here.</p>
    </section>
    <section data-section="section2">
        <h2>Section 2</h2>
        <p>Content for section 2 goes here.</p>
    </section>
    <section data-section="section3">
        <h2>Section 3</h2>
        <p>Content for section 3 goes here.</p>
    </section>
    <section>
        <h2>Section 4</h2>
        <p>Content for section 4 goes here.</p>
    </section>
    <section>
        <h2>Section 5</h2>
        <p>Content for section 5 goes here.</p>
    </section>
    <section>
        <h2>Section 6</h2>
        <p>Content for section 6 goes here.</p>
    </section>
</div>
</code>```
```<code>const winHeight = window.innerHeight;
  const pages = document.querySelectorAll("[data-section]");
  let currentPage = 0;

  window.addEventListener("mousewheel", function (e) {
    scrollPages(e.wheelDelta);
  });
  window.addEventListener("DOMMouseScroll", function (e) {
    scrollPages(-1 * e.detail);
  });

  function scrollPages(delta) {
    const direction = delta > 0 ? "up" : "down";
    const currentPageOffset = currentPage * winHeight;

    if (direction == "down" && currentPage <= pages.length - 2) {
      // scroll into view centered
      window.scrollTo({
        top: currentPageOffset + winHeight,
        behavior: "smooth",
      });
      currentPage++;
    } else if (direction == "up" && currentPage > 0) {
      window.scrollTo({
        top: currentPageOffset - winHeight,
        behavior: "smooth",
      });
      currentPage--;
    }
  }
</code>```

This however does not really give the intended scroll snap output whenever mouse or arrow is used, scroll immediately to the next/previous section.

Body:
I need help replicating this https://swiper-master.webflow.io/full-page-vertical in pure vanilla js. I cannot figure out how to implement this. Kindly assist.

Expected output, smooth scroll from one section to the next either upwards or downwards based on mouse scroll or keyboard arrow down up keys.

I have 6 sections in my html, but I want to target only the first 3 sections with this animation shown in this link https://swiper-master.webflow.io/full-page-vertical then the rest of the sections should just scroll "normal" without the scroll snap effect.

Section 1

Content for section 1 goes here.

Section 2

Content for section 2 goes here.

Section 3

Content for section 3 goes here.

Section 4

Content for section 4 goes here.

Section 5

Content for section 5 goes here.

Section 6

Content for section 6 goes here.

const winHeight = window.innerHeight;
  const pages = document.querySelectorAll("[data-section]");
  let currentPage = 0;

  window.addEventListener("mousewheel", function (e) {
    scrollPages(e.wheelDelta);
  });
  window.addEventListener("DOMMouseScroll", function (e) {
    scrollPages(-1 * e.detail);
  });

  function scrollPages(delta) {
    const direction = delta > 0 ? "up" : "down";
    const currentPageOffset = currentPage * winHeight;

    if (direction == "down" && currentPage <= pages.length - 2) {
      // scroll into view centered
      window.scrollTo({
        top: currentPageOffset + winHeight,
        behavior: "smooth",
      });
      currentPage++;
    } else if (direction == "up" && currentPage > 0) {
      window.scrollTo({
        top: currentPageOffset - winHeight,
        behavior: "smooth",
      });
      currentPage--;
    }
  }

This however does not really give the intended scroll snap output whenever mouse or arrow is used, scroll immediately to the next/previous section.


来源: stackexchange

问:
URL.revokeObjectURL doesn't remove blobs from "Sources" panel and from chrome://blob-internals/
The problem is basically what the title says. The minimal example to demonstrate it is below.

This function accepts a File object as an argument from <input type='file' /> field. It creates a URL and revokes it 5 seconds later.

```<code>const compress = (file) => {
  const img = new Image();
  img.src = URL.createObjectURL(file);
  console.log('url created');
  setTimeout(() => {
    URL.revokeObjectURL(img.src);
    console.log("url revoked");
  }, 5000);
};
</code>```

The blob appears in the Sources panel and I would expect it to disappear (to be garbage collected) after 5 seconds, but it doesn't.

What could be the reason it's not garbage collected?

It's also not removed from chrome://blob-internals/

As far as I understand it's a memory leak. How can I fix it?

ContentLicense: CC BY-SA 4.0

Body:
The problem is basically what the title says. The minimal example to demonstrate it is below.

This function accepts a File object as an argument from <input type='file' /> field. It creates a URL and revokes it 5 seconds later.

const compress = (file) => {
  const img = new Image();
  img.src = URL.createObjectURL(file);
  console.log('url created');
  setTimeout(() => {
    URL.revokeObjectURL(img.src);
    console.log("url revoked");
  }, 5000);
};

The blob appears in the Sources panel and I would expect it to disappear (to be garbage collected) after 5 seconds, but it doesn't.

What could be the reason it's not garbage collected?

It's also not removed from chrome://blob-internals/

As far as I understand it's a memory leak. How can I fix it?


问:
React Native Expo Error with Apollo Graphql / Graphql after setting up Firebase SDK
I just followed the instructions to set up the firebase SDK on Expo and for some reason, it seems to be breaking Apollo Graphql. If I remove the metro config it fails with an issue from Firebase as would be expected as it says it's needed in the Expo docs.

So I am stuck I don't really know where to go from here as I need both. And I have tried the fetch API but it results in the same issue even with the apollo queries being commented.

Screenshot of Error

Metro Config

```<code>const { getDefaultConfig } = require('@expo/metro-config');

const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('cjs');

module.exports = defaultConfig;

</code>```

Followed Docs
Expo Firebase setup

I have tried removing the metro config however I just get an issue with firebase which I would expect as its required for the new version of Firebase.

Console image

Body:
I just followed the instructions to set up the firebase SDK on Expo and for some reason, it seems to be breaking Apollo Graphql. If I remove the metro config it fails with an issue from Firebase as would be expected as it says it's needed in the Expo docs.

So I am stuck I don't really know where to go from here as I need both. And I have tried the fetch API but it results in the same issue even with the apollo queries being commented.

Screenshot of Error

Metro Config

const { getDefaultConfig } = require('@expo/metro-config');

const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('cjs');

module.exports = defaultConfig;

Followed Docs
Expo Firebase setup

I have tried removing the metro config however I just get an issue with firebase which I would expect as its required for the new version of Firebase.

Console image


问:
For a given child div, how can I properly mask a parents div background so that I only see the gradient in the masked content?
I don't have enough rep to include images, so I've had to make do with plain old hyperlinks

I am trying to create a cool visual effect for my personal website. I want my socials and name to mask a background gradient. Later I will be adding simple animation with Javascript, so I need all my child divs to be masking the same overall gradient - I do not want them to each have their own mini gradient.

Basically, I would like the following gradient but masked to the text and images its children contain:
orange gradient background displayed containing text and three logos, all of which are black

My relevant CSS is broken up into four parts. One for the parent div, one for my name, and then two for the icons (the grid wrapper and the individual grid squares). To get the above result I insert my gradient like so:

```<code>#quick-info {
    background: linear-gradient(to right, #f06d06, #ffa800);
    ...
}

#main-name {
    ...
}

#connections {
    ...
}

.connections-icons {
    ...
}
</code>```

According to my online research, if I want to mask a background I would do something like so:

```<code>#quick-info {
    ...
}

#main-name {
    background: linear-gradient(to right, #f06d06, #ffa800);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    ...
}

#connections {
    ...
}

.connections-icons {
    ...
}

</code>```

Which gives a result like:
my name is displayed in an orange gradient, the background is transparent and the logos are black

The same research told me that if I want to mask a parent background, I just need to move the declaration of the background gradient to the parent div:

```<code>#quick-info {
    background: linear-gradient(to right, #f06d06, #ffa800);
    ...
}

#main-name {

    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    ...
}

#connections {
    ...
}

.connections-icons {
    ...
}

</code>```

This kinda works, as I can tell the text is being "filled" with the background, but the parent background is not really being masked in the same way as before so it's entirely invisible unless you highlight it:
text is invisible...
..unless highlighted

I am also struggling to understand how to use my images as a mask. I am using PNG at the moment but can swap to SVG if that is easier to use. I cannot even get a singular mask working (which I could easily do when it came to text)

Note in this attempt I am putting the background in the child as I have already established my current approach to putting the gradient in the parent means even if I do mask properly, I won't be able to see as such:

```<code>#quick-info {

    ...
}

#main-name {
    ...
}

#connections {
    ...
}

.connections-icons {
    background: linear-gradient(to right, #f06d06, #ffa800);
    ...
}
</code>```

Gives me:
each icon has an individual gradient

But when I add the mask everything is transparent/gone (using the same mask for each element is obviously wrong, but for the sake of this question is it clear to see that not even the actual email icon was masked properly):

```<code>#quick-info {

    ...
}

#main-name {
    ...
}

#connections {
    ...
}

.connections-icons {
    background: linear-gradient(to right, #f06d06, #ffa800);
    -webkit-mask-image: url(img/email.png);
    ...
}
</code>```

icons are invisible

How can I make it so that the parent background is only visible in the masks created by the children?

Body:
I don't have enough rep to include images, so I've had to make do with plain old hyperlinks

I am trying to create a cool visual effect for my personal website. I want my socials and name to mask a background gradient. Later I will be adding simple animation with Javascript, so I need all my child divs to be masking the same overall gradient - I do not want them to each have their own mini gradient.

Basically, I would like the following gradient but masked to the text and images its children contain:
orange gradient background displayed containing text and three logos, all of which are black

My relevant CSS is broken up into four parts. One for the parent div, one for my name, and then two for the icons (the grid wrapper and the individual grid squares). To get the above result I insert my gradient like so:

#quick-info {
    background: linear-gradient(to right, #f06d06, #ffa800);
    ...
}

#main-name {
    ...
}

#connections {
    ...
}

.connections-icons {
    ...
}

According to my online research, if I want to mask a background I would do something like so:

#quick-info {
    ...
}

#main-name {
    background: linear-gradient(to right, #f06d06, #ffa800);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    ...
}

#connections {
    ...
}

.connections-icons {
    ...
}

Which gives a result like:
my name is displayed in an orange gradient, the background is transparent and the logos are black

The same research told me that if I want to mask a parent background, I just need to move the declaration of the background gradient to the parent div:

#quick-info {
    background: linear-gradient(to right, #f06d06, #ffa800);
    ...
}

#main-name {

    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    ...
}

#connections {
    ...
}

.connections-icons {
    ...
}

This kinda works, as I can tell the text is being "filled" with the background, but the parent background is not really being masked in the same way as before so it's entirely invisible unless you highlight it:
text is invisible...
..unless highlighted

I am also struggling to understand how to use my images as a mask. I am using PNG at the moment but can swap to SVG if that is easier to use. I cannot even get a singular mask working (which I could easily do when it came to text)

Note in this attempt I am putting the background in the child as I have already established my current approach to putting the gradient in the parent means even if I do mask properly, I won't be able to see as such:

#quick-info {

    ...
}

#main-name {
    ...
}

#connections {
    ...
}

.connections-icons {
    background: linear-gradient(to right, #f06d06, #ffa800);
    ...
}

Gives me:
each icon has an individual gradient

But when I add the mask everything is transparent/gone (using the same mask for each element is obviously wrong, but for the sake of this question is it clear to see that not even the actual email icon was masked properly):

#quick-info {

    ...
}

#main-name {
    ...
}

#connections {
    ...
}

.connections-icons {
    background: linear-gradient(to right, #f06d06, #ffa800);
    -webkit-mask-image: url(img/email.png);
    ...
}

icons are invisible

How can I make it so that the parent background is only visible in the masks created by the children?


问:
Postgres SQL to split values from a string into multiple columns based on the format
I have a data in Telephone column, something as below:

```<code>with t (id,telephone) as (values
(1234560,'(345) 908-1234 '),
(1234561,'(345) 908-1234;ext=1234'),
(1234562 ,'(345) 908-1234;ext=12345'),
(1234563 ,'(345) 908-12345;ext=12345'),
(1234564 ,'1234567;ext=12345'),
(1234565 ,'123ABC;ext=12345'),
(1234566 ,'Ext=12345'),
(1234567 ,'+1123456789')
)
select * from t
</code>```

Only  telephone numbers with (XXX) XXX-XXXX or (XXX) XXX-XXXX;ext=XXX(ext can be unlimited) formats should be considered as Valid and remaining all are considered as invalid

Used REGEXP_MATCHES for identifying the valid format of telephone.

Case #1
If its valid then we need to split values as below :
first 3 chars - Area
next  3 chars - Exchange
last 4  chars - Line
Anything chars after ;Ext= should be into Ext number

This above case#1 working as expected

Case #2

Scenario 1 : If invalid format contains any chars between A-Z or only EXT=XXXX it should be ignored(NULL) out entirely

Scenario 2 : If its any other invalid format any chars before EXT should be inserted into Alternate number and any chars after EXT should be inserted into  EXT column

I am stuck with above scenario 1  related to Case2(for ids 65,66)

Please find below DB Fiddle for the code and expected output : link

Body:
I have a data in Telephone column, something as below:

with t (id,telephone) as (values
(1234560,'(345) 908-1234 '),
(1234561,'(345) 908-1234;ext=1234'),
(1234562 ,'(345) 908-1234;ext=12345'),
(1234563 ,'(345) 908-12345;ext=12345'),
(1234564 ,'1234567;ext=12345'),
(1234565 ,'123ABC;ext=12345'),
(1234566 ,'Ext=12345'),
(1234567 ,'+1123456789')
)
select * from t

Only  telephone numbers with (XXX) XXX-XXXX or (XXX) XXX-XXXX;ext=XXX(ext can be unlimited) formats should be considered as Valid and remaining all are considered as invalid

Used REGEXP_MATCHES for identifying the valid format of telephone.

Case #1
If its valid then we need to split values as below :
first 3 chars - Area
next  3 chars - Exchange
last 4  chars - Line
Anything chars after ;Ext= should be into Ext number

This above case#1 working as expected

Case #2

Scenario 1 : If invalid format contains any chars between A-Z or only EXT=XXXX it should be ignored(NULL) out entirely

Scenario 2 : If its any other invalid format any chars before EXT should be inserted into Alternate number and any chars after EXT should be inserted into  EXT column

I am stuck with above scenario 1  related to Case2(for ids 65,66)

Please find below DB Fiddle for the code and expected output : link


问:
What's wrong with my "Greedy Motif Search" code?
I'm studying bioinformatics at coursera. Here's me in "Greedy Motif Search" code.

Input ans Output is like this.

# Input:  A list of kmers Dna, and integers k and t (where t is the number of kmers in Dna)

# Output: GreedyMotifSearch(Dna, k, t)

Sample Input:

```<code>3 5
GGCGTTCAGGCA
AAGAATCAGTCA
CAAGGAGTTCGC
CACGTCAATCAC
CAATAATATTCG
</code>```

Sample Output:

```<code>CAG
CAG
CAA
CAA
CAA
</code>```

Correct answer is this.

```<code># Score(Motifs), Count(Motifs), Profile(Motifs), and Consensus(Motifs)

def Consensus(Motifs):
    k = len(Motifs[0])
    count = Count(Motifs)
    consensus = ""
    for j in range(k):
        m = 0
        frequentSymbol = ""
        for symbol in "ACGT":
            if count[symbol][j] > m:
                m = count[symbol][j]
                frequentSymbol = symbol
        consensus += frequentSymbol
    return consensus

def Count(Motifs):
    count = {}  # initializing the count dictionary
    k = len(Motifs[0])
    for symbol in "ACGT":
        count[symbol] = []
        for j in range(k):
            count[symbol].append(0)
    t = len(Motifs)
    for i in range(t):
        for j in range(k):
            symbol = Motifs[i][j]
            count[symbol][j] += 1
    return count

def Score(Motifs):
    result = 0
    count = Count(Motifs)
    consensus = Consensus(Motifs)
    k = len(Motifs[0])
    for j in range(k):
        for symbol in "ACGT":
            result += count[symbol][j]
        result -= count[consensus[j]][j]
    return result

def Profile(Motifs):
    t = len(Motifs)
    k = len(Motifs[0])
    profile = {}
    profile = Count(Motifs)
    for i in profile:
        for j in range(k):
            profile[i][j] = profile[i][j] / t
    return profile

# ProfileMostProbableKmer(Text, k, Profile) and Pr(Text, Profile) functions

def Pr(Text, Profile):
    result = 1
    for i in range(len(Text)):
        result *= Profile[Text[i]][i]
    return result

def ProfileMostProbableKmer(text, k, profile):
    n = len(text)
    probabilities = []
    for i in range(n - k + 1):
        probabilities.append(Pr(text[i:i + k], profile))
    most_probable_kmer_start_idx = probabilities.index(max(probabilities))
    result = text[most_probable_kmer_start_idx: most_probable_kmer_start_idx + k]
    return result

def ProfileMostProbableKmer(Text, k, Profile):
    helperdict = {}
    for i in range(len(Text) - k + 1):
        helperdict[Text[i:i+k]] = Pr(Text[i:i+k], Profile)
    return max(helperdict, key=helperdict.get)

def GreedyMotifSearch(Dna, k, t):
    BestMotifs = []
    for i in range(0, t):
        BestMotifs.append(Dna[i][0:k])
    n = len(Dna[0])
    for i in range(n-k+1):
        Motifs = []
        Motifs.append(Dna[0][i:i+k])
        for j in range(1, t):
            P = Profile(Motifs[0:j])
            Motifs.append(ProfileMostProbableKmer(Dna[j], k, P))
        if Score(Motifs) < Score(BestMotifs):
            BestMotifs = Motifs
    return BestMotifs
</code>```

The code below is my wrong answer. (Other auxiliary functions are the same.)

```<code>def GreedyMotifSearch(Dna, k, t):
    # type your GreedyMotifSearch code here.
    greedymotifs = []
    for i in range(t):
        greedymotifs.append(ProfileMostProbableKmer(Dna[i], k, Profile(Dna)))
    return greedymotifs
</code>```

When I enter a Sample Input into my code, only the fourth value is different. Like this.

Output:

```<code>CAG
CAG
CAA
CAC
CAA
</code>```

What's wrong with my code? Am I misunderstanding? Then what am I misunderstanding? Please, help me

Body:
I'm studying bioinformatics at coursera. Here's me in "Greedy Motif Search" code.

Input ans Output is like this.

# Input:  A list of kmers Dna, and integers k and t (where t is the number of kmers in Dna)

# Output: GreedyMotifSearch(Dna, k, t)

Sample Input:

3 5
GGCGTTCAGGCA
AAGAATCAGTCA
CAAGGAGTTCGC
CACGTCAATCAC
CAATAATATTCG

Sample Output:

CAG
CAG
CAA
CAA
CAA

Correct answer is this.

# Score(Motifs), Count(Motifs), Profile(Motifs), and Consensus(Motifs)

def Consensus(Motifs):
    k = len(Motifs[0])
    count = Count(Motifs)
    consensus = ""
    for j in range(k):
        m = 0
        frequentSymbol = ""
        for symbol in "ACGT":
            if count[symbol][j] > m:
                m = count[symbol][j]
                frequentSymbol = symbol
        consensus += frequentSymbol
    return consensus

def Count(Motifs):
    count = {}  # initializing the count dictionary
    k = len(Motifs[0])
    for symbol in "ACGT":
        count[symbol] = []
        for j in range(k):
            count[symbol].append(0)
    t = len(Motifs)
    for i in range(t):
        for j in range(k):
            symbol = Motifs[i][j]
            count[symbol][j] += 1
    return count

def Score(Motifs):
    result = 0
    count = Count(Motifs)
    consensus = Consensus(Motifs)
    k = len(Motifs[0])
    for j in range(k):
        for symbol in "ACGT":
            result += count[symbol][j]
        result -= count[consensus[j]][j]
    return result

def Profile(Motifs):
    t = len(Motifs)
    k = len(Motifs[0])
    profile = {}
    profile = Count(Motifs)
    for i in profile:
        for j in range(k):
            profile[i][j] = profile[i][j] / t
    return profile

# ProfileMostProbableKmer(Text, k, Profile) and Pr(Text, Profile) functions

def Pr(Text, Profile):
    result = 1
    for i in range(len(Text)):
        result *= Profile[Text[i]][i]
    return result

def ProfileMostProbableKmer(text, k, profile):
    n = len(text)
    probabilities = []
    for i in range(n - k + 1):
        probabilities.append(Pr(text[i:i + k], profile))
    most_probable_kmer_start_idx = probabilities.index(max(probabilities))
    result = text[most_probable_kmer_start_idx: most_probable_kmer_start_idx + k]
    return result

def ProfileMostProbableKmer(Text, k, Profile):
    helperdict = {}
    for i in range(len(Text) - k + 1):
        helperdict[Text[i:i+k]] = Pr(Text[i:i+k], Profile)
    return max(helperdict, key=helperdict.get)

def GreedyMotifSearch(Dna, k, t):
    BestMotifs = []
    for i in range(0, t):
        BestMotifs.append(Dna[i][0:k])
    n = len(Dna[0])
    for i in range(n-k+1):
        Motifs = []
        Motifs.append(Dna[0][i:i+k])
        for j in range(1, t):
            P = Profile(Motifs[0:j])
            Motifs.append(ProfileMostProbableKmer(Dna[j], k, P))
        if Score(Motifs) < Score(BestMotifs):
            BestMotifs = Motifs
    return BestMotifs

The code below is my wrong answer. (Other auxiliary functions are the same.)

def GreedyMotifSearch(Dna, k, t):
    # type your GreedyMotifSearch code here.
    greedymotifs = []
    for i in range(t):
        greedymotifs.append(ProfileMostProbableKmer(Dna[i], k, Profile(Dna)))
    return greedymotifs

When I enter a Sample Input into my code, only the fourth value is different. Like this.

Output:

CAG
CAG
CAA
CAC
CAA

What's wrong with my code? Am I misunderstanding? Then what am I misunderstanding? Please, help me


问:
How to create 2D Table with Row and Column headers and content Scrollable on Jetpakcompose
I'm facing a logical problem in Jetapck compose, how can Ive the black bock scrolling horizontally and vertically with respectively the green and redbox.

Green and red box can be considered like headers,black box like a content. So :

When scrolling horizontally the red box must remains fixed and visible but the black and green box must scroll together horizontally

When scrolling vertically the green box must remains fixed and visible but the red and green box must scroll together vertically

This the code for the vertical scrolling, in top of that i would like to achieve the horizontal scrolling:

```<code>
@Composable()
fun MyScrollBox(){
    MaterialTheme {
        Surface(color = Color.White) {
            Box(modifier = Modifier.fillMaxSize()) {
                Column {
                    Row {
                        Box(modifier = Modifier
                            .height(50.dp)
                            .width(50.dp)
                            .background(Color.Yellow)){
                            Text(text = "YELLOW BOX")
                        }
                        Box(modifier = Modifier
                            .height(50.dp)
                            .width(800.dp)
                            .background(Color.Green)){
                            Text(text = "GREEN BOX")

                        }
                    }
                    Row(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
                        Box(modifier = Modifier
                            .width(50.dp)
                            .height(800.dp)
                            .fillMaxHeight().fillMaxSize()
                            .background(Color.Red)){
                            Text(text = "RED BOX")

                        }
                        Box(modifier = Modifier
                            .width(800.dp).height(800.dp)
                            .background(Color.Black)){
                            Text(text = "BLACK BOX", color = Color.White)

                        }
                    }
                }
            }
        }
    }
}
</code>```

Thanks for your help

Body:
I'm facing a logical problem in Jetapck compose, how can Ive the black bock scrolling horizontally and vertically with respectively the green and redbox.

Green and red box can be considered like headers,black box like a content. So :

When scrolling horizontally the red box must remains fixed and visible but the black and green box must scroll together horizontally

When scrolling vertically the green box must remains fixed and visible but the red and green box must scroll together vertically

This the code for the vertical scrolling, in top of that i would like to achieve the horizontal scrolling:

@Composable()
fun MyScrollBox(){
    MaterialTheme {
        Surface(color = Color.White) {
            Box(modifier = Modifier.fillMaxSize()) {
                Column {
                    Row {
                        Box(modifier = Modifier
                            .height(50.dp)
                            .width(50.dp)
                            .background(Color.Yellow)){
                            Text(text = "YELLOW BOX")
                        }
                        Box(modifier = Modifier
                            .height(50.dp)
                            .width(800.dp)
                            .background(Color.Green)){
                            Text(text = "GREEN BOX")

                        }
                    }
                    Row(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
                        Box(modifier = Modifier
                            .width(50.dp)
                            .height(800.dp)
                            .fillMaxHeight().fillMaxSize()
                            .background(Color.Red)){
                            Text(text = "RED BOX")

                        }
                        Box(modifier = Modifier
                            .width(800.dp).height(800.dp)
                            .background(Color.Black)){
                            Text(text = "BLACK BOX", color = Color.White)

                        }
                    }
                }
            }
        }
    }
}

Thanks for your help


问:
Failed to launch Anaconda navigator
i'm unable to launch anaconda navigator when i try to open end with nothing while try to open with anaconda prompt the following error appear;

```<code>(base) C:\Users\SahibXada>anaconda-navigator
Traceback (most recent call last):
  File "C:\Users\SahibXada\anaconda3\Scripts\anaconda-navigator-script.py", line 6, in <module>
    from anaconda_navigator.app.main import main
  File "C:\Users\SahibXada\anaconda3\lib\site-packages\anaconda_navigator\app\main.py", line 19, in <module>
    from anaconda_navigator.app.start import start_app
  File "C:\Users\SahibXada\anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 22, in <module>
    from anaconda_navigator.utils import misc
  File "C:\Users\SahibXada\anaconda3\lib\site-packages\anaconda_navigator\utils\misc.py", line 16, in <module>
    import psutil
  File "C:\Users\SahibXada\AppData\Roaming\Python\Python39\site-packages\psutil\__init__.py", line 109, in <module>
    from . import _pswindows as _psplatform
  File "C:\Users\SahibXada\AppData\Roaming\Python\Python39\site-packages\psutil\_pswindows.py", line 35, in <module>
    from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
ImportError: DLL load failed while importing _psutil_windows: %1 is not a valid Win32 application.
</code>```

i had uninstall anaconda and and then reinstall it but still facing the same issue go through every procedure i found at internet but i'm been unable to solve this

Title: Failed to launch Anaconda navigator

Body:
i'm unable to launch anaconda navigator when i try to open end with nothing while try to open with anaconda prompt the following error appear;

(base) C:\Users\SahibXada>anaconda-navigator
Traceback (most recent call last):
  File "C:\Users\SahibXada\anaconda3\Scripts\anaconda-navigator-script.py", line 6, in <module>
    from anaconda_navigator.app.main import main
  File "C:\Users\SahibXada\anaconda3\lib\site-packages\anaconda_navigator\app\main.py", line 19, in <module>
    from anaconda_navigator.app.start import start_app
  File "C:\Users\SahibXada\anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 22, in <module>
    from anaconda_navigator.utils import misc
  File "C:\Users\SahibXada\anaconda3\lib\site-packages\anaconda_navigator\utils\misc.py", line 16, in <module>
    import psutil
  File "C:\Users\SahibXada\AppData\Roaming\Python\Python39\site-packages\psutil\__init__.py", line 109, in <module>
    from . import _pswindows as _psplatform
  File "C:\Users\SahibXada\AppData\Roaming\Python\Python39\site-packages\psutil\_pswindows.py", line 35, in <module>
    from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
ImportError: DLL load failed while importing _psutil_windows: %1 is not a valid Win32 application.

i had uninstall anaconda and and then reinstall it but still facing the same issue go through every procedure i found at internet but i'm been unable to solve this


问:
If pyparsing is not thread safe，why use RLock in _parseCache?
I found in core.py _parseCache function, it seems that a lock is used to make cache read/write mutual exclusion(I am noob in concurrency development). But pyparsing is not thread safe, when use multple threads to packrat parsing multiple string, corruption happens. So why use RLock?</p>


问:
how large storage do I need for postgres comparing to data size
I did some analysis using some sample data and found table size is usually 2 twice as much as raw data (by importing a csv file into a postgres table, then csv file size is raw data size).
And the disk space seems 4 times as raw data most likely because of WAL log.

Is there any commonly used formulator to estimate how much disk space I need if we want to store like 1G size of data.

I know there are many factors affecting this, I just would like to have a quick estimate.


问:
Python/Tkinter: triggering an event in the main app from an imported class module
Following is code for a tkinter listbox, created as a class, and saved as a module named ModListbox:

```<code>import tkinter as tk
class Lstbox(tk.Listbox):
  def __init__(self,master,listname):
    super().__init__(master)

    # insert list
    self.insert(0,*listname)
    # place listbox
    self.place(x=10,y=10)
</code>```

Likewise, following is the simplest code for a main app that imports the module and displays the listbox.

```<code>import tkinter as tk
root=tk.Tk()

MyList = ['first','second','third','fourth','fifth']

import ModListbox
NewListbox = ModListbox.Lstbox(master=root,listname=MyList)

root.mainloop()
</code>```

In order to add functionality to the listbox, the obvious approach is to load the module and create an instance of the class, then to bind the listbox to a function, as follows, within the main application code. So clicking on the listbox triggers an event.

```<code>import tkinter as tk
root=tk.Tk()

# function on user selection in listbox
def UserClickedNewListbox(event):
    SelectedIndex = NewListbox.curselection()[0]
    SelectedText = NewListbox.get(SelectedIndex)
    print("You selected ", SelectedText)

MyList = ['first','second','third','fourth','fifth']

import ModListbox
NewListbox = ModListbox.Lstbox(master=root,listname=MyList)

# bind listbox to function
NewListbox.bind('<<ListboxSelect>>',UserClickedNewListbox)

root.mainloop()
</code>```

However, one reason among many that I'm creating tkinter widgets as classes is to keep as much code in the modules as possible, and reduce the code in the main app. So here is the same module, but with the binding and function included inside the module.

```<code>import tkinter as tk

class Lstbox(tk.Listbox):
  def __init__(self,master,listname):
    super().__init__(master)

    # insert list
    self.insert(0,*listname)
    # place listbox
    self.place(x=10,y=10)
    # bind user selection to function
    self.bind('<<ListboxSelect>>',self.UserClickedListbox)

  def UserClickedListbox(self,event):
    SelectedIndex = self.curselection()[0]
    # How do I trigger an action inside the main app from here?
</code>```

So now, inside the module itself, a user click on the listbox triggers the function. The function 'knows' the index of the listbox clicked by the user. How, if it is possible at all, would I trigger an event inside the main application, while also passing the selected index? Is this possible? Any advice appreciated.

Body:
Following is code for a tkinter listbox, created as a class, and saved as a module named ModListbox:

import tkinter as tk
class Lstbox(tk.Listbox):
  def __init__(self,master,listname):
    super().__init__(master)

    # insert list
    self.insert(0,*listname)
    # place listbox
    self.place(x=10,y=10)

Likewise, following is the simplest code for a main app that imports the module and displays the listbox.

import tkinter as tk
root=tk.Tk()

MyList = ['first','second','third','fourth','fifth']

import ModListbox
NewListbox = ModListbox.Lstbox(master=root,listname=MyList)

root.mainloop()

In order to add functionality to the listbox, the obvious approach is to load the module and create an instance of the class, then to bind the listbox to a function, as follows, within the main application code. So clicking on the listbox triggers an event.

import tkinter as tk
root=tk.Tk()

# function on user selection in listbox
def UserClickedNewListbox(event):
    SelectedIndex = NewListbox.curselection()[0]
    SelectedText = NewListbox.get(SelectedIndex)
    print("You selected ", SelectedText)

MyList = ['first','second','third','fourth','fifth']

import ModListbox
NewListbox = ModListbox.Lstbox(master=root,listname=MyList)

# bind listbox to function
NewListbox.bind('<<ListboxSelect>>',UserClickedNewListbox)

root.mainloop()

However, one reason among many that I'm creating tkinter widgets as classes is to keep as much code in the modules as possible, and reduce the code in the main app. So here is the same module, but with the binding and function included inside the module.

import tkinter as tk

class Lstbox(tk.Listbox):
  def __init__(self,master,listname):
    super().__init__(master)

    # insert list
    self.insert(0,*listname)
    # place listbox
    self.place(x=10,y=10)
    # bind user selection to function
    self.bind('<<ListboxSelect>>',self.UserClickedListbox)

  def UserClickedListbox(self,event):
    SelectedIndex = self.curselection()[0]
    # How do I trigger an action inside the main app from here?

So now, inside the module itself, a user click on the listbox triggers the function. The function 'knows' the index of the listbox clicked by the user. How, if it is possible at all, would I trigger an event inside the main application, while also passing the selected index? Is this possible? Any advice appreciated.


问:
Next js conflict between dynamic pages with nested routes and fixed pages
I have dynamic pages with nested routes and fixed pages in the pages folder for example

The name of the page is dynamic

```<code>pages/[model]/[slug]
</code>```

fixed name

```<code>pages/about
</code>```

so in this way what is the best solution

Body:
I have dynamic pages with nested routes and fixed pages in the pages folder for example

The name of the page is dynamic

pages/[model]/[slug]

fixed name

pages/about

so in this way what is the best solution


问:
Access information from a previous Kubeflow component
I have a ModelBatchPredictOp component in my pipeline. This component generates 3 artifacts: batchpredictionjob, big_query_table, and gcs_output_directory. The pipeline is running fine.

What I need is a way to access the tableId property of artifact big_query_table, so I can use it in the next component (a BigqueryQueryJobOp).

That is what I want:

The URI information would be good as well since it contains the full path for the created table and I can extract the desired part.

This is my 2nd component which is creating the batch prediction and the 3rd component which should consume the previous outputs.

```<code># Component to do the batch prediction
batch_predict_op = ModelBatchPredictOp(
   project=project_id,
   location=DEFAULT_VERTEX_REGION,
   instances_format = 'bigquery',
   predictions_format = 'bigquery',
   model=importer_spec.outputs['artifact'],
   job_display_name='teste_batch_predict',
   bigquery_source_input_uri=f'bq://{input_data_table_ref}',
   bigquery_destination_output_uri= f'bq://{output_bq}',
   ).after(input_data_table_op)

   top_predictions_table_ref = f'{project_id}.{bigquery_dataset}.test'

# Component to create the table based on previous component
top_predictions_op = bq.BigqueryQueryJobOp(
   project_id,
   location = bigquery_job_location,
   query = predict_dataset.get_query(
   output_table = top_predictions_table_ref,
   source_table = batch_predict_op.outputs['bigquery_output_table'],
   query_name = 'query_top_100.sql',
   DEBUG = DEBUG)
   ).after(batch_predict_op)
</code>```

Body:
I have a ModelBatchPredictOp component in my pipeline. This component generates 3 artifacts: batchpredictionjob, big_query_table, and gcs_output_directory. The pipeline is running fine.

What I need is a way to access the tableId property of artifact big_query_table, so I can use it in the next component (a BigqueryQueryJobOp).

That is what I want:

The URI information would be good as well since it contains the full path for the created table and I can extract the desired part.

This is my 2nd component which is creating the batch prediction and the 3rd component which should consume the previous outputs.

# Component to do the batch prediction
batch_predict_op = ModelBatchPredictOp(
   project=project_id,
   location=DEFAULT_VERTEX_REGION,
   instances_format = 'bigquery',
   predictions_format = 'bigquery',
   model=importer_spec.outputs['artifact'],
   job_display_name='teste_batch_predict',
   bigquery_source_input_uri=f'bq://{input_data_table_ref}',
   bigquery_destination_output_uri= f'bq://{output_bq}',
   ).after(input_data_table_op)

   top_predictions_table_ref = f'{project_id}.{bigquery_dataset}.test'

# Component to create the table based on previous component
top_predictions_op = bq.BigqueryQueryJobOp(
   project_id,
   location = bigquery_job_location,
   query = predict_dataset.get_query(
   output_table = top_predictions_table_ref,
   source_table = batch_predict_op.outputs['bigquery_output_table'],
   query_name = 'query_top_100.sql',
   DEBUG = DEBUG)
   ).after(batch_predict_op)


问:
How to execute API call on flutter and send response to native side Android / IOS using method channel onBackground?
I want to show OnesSignal background notification based on condition which requires to call API and based on API response will decide to show/hide the notification from native Android / IOS side using method channel onBackground ?

Note : the background handler method are only available at native side Android / IOS.


问:
The program expected this account to be already initialized (anchor solana)
When I do anchor build, the compiler return this error caused by mint, ownerTokenAccount and buyerTokenAccount. Here is my code:

```<code>    let minter = await splToken.createMint(connection, wallet.payer, wallet.publicKey, null, 1)
    const tokenAccount = // create token account
    // minted 1 nft
    const buyer: anchor.web3.Keypair = // get keypair from file
    const buyerTokenAddress = await anchor.utils.token.associatedAddress({
      mint: minter,
      owner: buyer.publicKey,
    });
    await program.methods.buyNft(
      new anchor.BN(saleAmount)
    )
      .accounts({
        mint: minter,
        ownerTokenAccount: tokenAccount.address,
        ownerAuthority: wallet.publicKey,
        buyerTokenAccount: buyerTokenAddress,
        buyerAuthority: buyer.publicKey,
      }).signers([buyer]).rpc();
</code>```

and this is the code in my contract:

```<code>pub fn buy_nft(
        ctx: Context<BuyNft>,
        // amount: Option<u64>,
        lamports: Option<u64>,
    ) -> Result<()> {
        system_program::transfer(
            CpiContext::new(
                ctx.accounts.system_program.to_account_info(),
                system_program::Transfer {
                    from: ctx.accounts.buyer_authority.to_account_info(),
                    to: ctx.accounts.owner_authority.to_account_info(),
                },
            ),
            lamports.unwrap(),
        )?;
        associated_token::create(CpiContext::new(
            ctx.accounts.owner_token_account.to_account_info(),
            associated_token::Create {
                payer: ctx.accounts.buyer_authority.to_account_info(),
                associated_token: ctx.accounts.buyer_token_account.to_account_info(),
                authority: ctx.accounts.buyer_authority.to_account_info(),
                mint: ctx.accounts.mint.to_account_info(),
                system_program: ctx.accounts.system_program.to_account_info(),
                token_program: ctx.accounts.token_program.to_account_info(),
            },
        ))?;
        token::transfer(
            CpiContext::new(
                ctx.accounts.token_program.to_account_info(),
                token::Transfer {
                    from: ctx.accounts.owner_token_account.to_account_info(),
                    to: ctx.accounts.buyer_token_account.to_account_info(),
                    authority: ctx.accounts.owner_authority.to_account_info(),
                },
            ),
            1,
        )?;
        Ok(())
    }
#[derive(Accounts)]
pub struct BuyNft<'info> {
    #[account(mut)]
    pub mint: Account<'info, token::Mint>,
    #[account(mut)]
    pub owner_token_account: Account<'info, token::TokenAccount>,
    #[account(mut)]
    pub owner_authority: Signer<'info>,
    #[account(mut)]
    pub buyer_token_account: Account<'info, token::TokenAccount>,
    #[account(mut)]
    pub buyer_authority: Signer<'info>,
    pub system_program: Program<'info, System>,
    pub token_program: Program<'info, token::Token>,
}

</code>```

In my version, the rent param in associated_token::Create is not existed so I remove it. So can you help me fixing this bug? Thanks

Body:
When I do anchor build, the compiler return this error caused by mint, ownerTokenAccount and buyerTokenAccount. Here is my code:

    let minter = await splToken.createMint(connection, wallet.payer, wallet.publicKey, null, 1)
    const tokenAccount = // create token account
    // minted 1 nft
    const buyer: anchor.web3.Keypair = // get keypair from file
    const buyerTokenAddress = await anchor.utils.token.associatedAddress({
      mint: minter,
      owner: buyer.publicKey,
    });
    await program.methods.buyNft(
      new anchor.BN(saleAmount)
    )
      .accounts({
        mint: minter,
        ownerTokenAccount: tokenAccount.address,
        ownerAuthority: wallet.publicKey,
        buyerTokenAccount: buyerTokenAddress,
        buyerAuthority: buyer.publicKey,
      }).signers([buyer]).rpc();

and this is the code in my contract:

pub fn buy_nft(
        ctx: Context<BuyNft>,
        // amount: Option<u64>,
        lamports: Option<u64>,
    ) -> Result<()> {
        system_program::transfer(
            CpiContext::new(
                ctx.accounts.system_program.to_account_info(),
                system_program::Transfer {
                    from: ctx.accounts.buyer_authority.to_account_info(),
                    to: ctx.accounts.owner_authority.to_account_info(),
                },
            ),
            lamports.unwrap(),
        )?;
        associated_token::create(CpiContext::new(
            ctx.accounts.owner_token_account.to_account_info(),
            associated_token::Create {
                payer: ctx.accounts.buyer_authority.to_account_info(),
                associated_token: ctx.accounts.buyer_token_account.to_account_info(),
                authority: ctx.accounts.buyer_authority.to_account_info(),
                mint: ctx.accounts.mint.to_account_info(),
                system_program: ctx.accounts.system_program.to_account_info(),
                token_program: ctx.accounts.token_program.to_account_info(),
            },
        ))?;
        token::transfer(
            CpiContext::new(
                ctx.accounts.token_program.to_account_info(),
                token::Transfer {
                    from: ctx.accounts.owner_token_account.to_account_info(),
                    to: ctx.accounts.buyer_token_account.to_account_info(),
                    authority: ctx.accounts.owner_authority.to_account_info(),
                },
            ),
            1,
        )?;
        Ok(())
    }
#[derive(Accounts)]
pub struct BuyNft<'info> {
    #[account(mut)]
    pub mint: Account<'info, token::Mint>,
    #[account(mut)]
    pub owner_token_account: Account<'info, token::TokenAccount>,
    #[account(mut)]
    pub owner_authority: Signer<'info>,
    #[account(mut)]
    pub buyer_token_account: Account<'info, token::TokenAccount>,
    #[account(mut)]
    pub buyer_authority: Signer<'info>,
    pub system_program: Program<'info, System>,
    pub token_program: Program<'info, token::Token>,
}

In my version, the rent param in associated_token::Create is not existed so I remove it. So can you help me fixing this bug? Thanks


问:
How to add Likes without asking user for Authentication?
I have a pretty simple Django app for quotes. I want to add likes to every single quote but I don't want user to login for that.
How can I achieve this without Logging in the user?

I tried to uniquely identify users without logging in.


问:
When trying to access response data sent from the server using AJAX done function, it returns undefined
Ive created a backbone.js view that will submit user login details to a codeigniter controller and after verifying it will send a response of boolean value true or false as the authentication status back to ajax.

```<code>$data = array(
                'status' => true
            );

            // Send the response back to the client
            print json_encode($data);
</code>```

When I try to retrieve the response "status" value inside the ondone function of ajax, I get the status value as undefined.

```<code>.done(function(data) {
        alert("data: " + data)
        alert("status: " + data.status)
        if (data.status) {
          alert("authenticated")
        } else {
          alert("unauthenticated")
        }
        window.location = '/CW2/ASSWDCW2/cw2app/index.php/Home/';
      });
</code>```

How can I get the status value inside the on done function of ajax?

Body:
Ive created a backbone.js view that will submit user login details to a codeigniter controller and after verifying it will send a response of boolean value true or false as the authentication status back to ajax.

$data = array(
                'status' => true
            );

            // Send the response back to the client
            print json_encode($data);

When I try to retrieve the response "status" value inside the ondone function of ajax, I get the status value as undefined.

.done(function(data) {
        alert("data: " + data)
        alert("status: " + data.status)
        if (data.status) {
          alert("authenticated")
        } else {
          alert("unauthenticated")
        }
        window.location = '/CW2/ASSWDCW2/cw2app/index.php/Home/';
      });

How can I get the status value inside the on done function of ajax?


问:
Relation between Hibernate and MySQL in Spring Boot?
When we use JPA API in a String Boot project by extending repository class with JpaRepository and use MySQL database instead of hibernate's H2 database, I wanted to know is there hibernate still involved behind the scenes or, is it that JPA works with MySQL?

From what I have researched, Hibernate is implementation of JPA but I can't find any reference how MySQL works with JPA?


问:
How can I create a notification through Chrome API in JavaScript every time I press a specific button?
I am essentially creating a Budget Manager Chrome Extension by following this Youtube playlist and one of the features is that whenever you reset the total a notification would be created which would say "Oh, you've reset the total." But, this only occurs once. For example, a couple minutes later, when testing, I tried to reset the total again but this time the notification did not come and I am not so familiar with JavaScript so I'm not sure how I can make it so that every time I reset the total, a notification pops up every time (through the Chrome Notifications API).

Here is my code so far in the .js file:

```<code>$('#resetTotal').click(function() {
    chrome.storage.sync.set({'total': 0}, function() {
        var notifOptions = {
            type: 'basic',
            iconUrl: 'icons48.png',
            title: 'Total Reset!',
            message: "Clean slate - your total has been reset to zero!"
        };
        chrome.notifications.create('limitNotif', notifOptions);
    });
    close();
});
</code>```

But, it only creates a notification once. How can I make it that it creates a notification every time the button is pressed.

Body:
I am essentially creating a Budget Manager Chrome Extension by following this Youtube playlist and one of the features is that whenever you reset the total a notification would be created which would say "Oh, you've reset the total." But, this only occurs once. For example, a couple minutes later, when testing, I tried to reset the total again but this time the notification did not come and I am not so familiar with JavaScript so I'm not sure how I can make it so that every time I reset the total, a notification pops up every time (through the Chrome Notifications API).

Here is my code so far in the .js file:

$('#resetTotal').click(function() {
    chrome.storage.sync.set({'total': 0}, function() {
        var notifOptions = {
            type: 'basic',
            iconUrl: 'icons48.png',
            title: 'Total Reset!',
            message: "Clean slate - your total has been reset to zero!"
        };
        chrome.notifications.create('limitNotif', notifOptions);
    });
    close();
});

But, it only creates a notification once. How can I make it that it creates a notification every time the button is pressed.


问:
how to find the arn of sso federated user in aws
In our organization we give saml based access to users. I am trying to whitelist a particular user (say abc) to access a specific folder in s3 bucket and no other user (apart from abc) should be able to access that folder.

I have tried putting arn in this format arn:aws:sts::<account-id>:assumed-role/<role-name>/abc@org.com

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::<test-bucket>/critical/*",
            "Condition": {
                "ArnNotEquals": {
                    "aws:PrincipalArn": "arn:aws:sts::<account-id>:assumed-role/<role-        name>/abc@org.com "
                }
            }
        }
    ]
    }
```

This is the policy that i am using. I am trying to restrict all other user to perform put operation apart from abc@org.com.

But it seems there is some problem with the arn that I have specified.

I also tried to use wildcards in the arn like (*) but was not able to resolve the problem.

Body:
In our organization we give saml based access to users. I am trying to whitelist a particular user (say abc) to access a specific folder in s3 bucket and no other user (apart from abc) should be able to access that folder.

I have tried putting arn in this format arn:aws:sts::<account-id>:assumed-role/<role-name>/abc@org.com

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::<test-bucket>/critical/*",
            "Condition": {
                "ArnNotEquals": {
                    "aws:PrincipalArn": "arn:aws:sts::<account-id>:assumed-role/<role-        name>/abc@org.com "
                }
            }
        }
    ]
    }

This is the policy that i am using. I am trying to restrict all other user to perform put operation apart from abc@org.com.

But it seems there is some problem with the arn that I have specified.

I also tried to use wildcards in the arn like (*) but was not able to resolve the problem.


问:
In a development environment, is it possible to bind mount package installation in docker containers?
We can configure the docker files to install packages from an already prepared list(such as package.json, go.mod) of dependencies.

Consider a situation where npm is not installed in the host machine. A developer runs a node application in a docker container in a development environment. If they want to install a package from the host machine, how'll they perform it?

I know they can modify the package.json and restart the container or get into the container and install the package there. But it'll be a hassle for developers who needs a seamless workflow.

Is there any way to bind the npm install <package> from the host to the container?


问:
I tried to insert json data into room database for displaying dummy contacts in UI using mvvm its showing null object reference in java
Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference

I can't fix the problem


问:
Applying Tailwind overflow behavior to only one child element
I'm using Tailwind to style a React component called "BlurImage" which displays an image by default and then on hover removes the image and displays a button at the bottom of the component and a text box at the top that has overflow-y-auto behavior to allow for scrolling if the text grows too long.

By default, the overflow responsibility is given to the body as discussed here and so I need to give the parent top-level div of BlurImage overflow as well. This causes both the text and the button to be scrollable. Is there a way to avoid having the button scroll?

This seems like it should be a common situation - I can imagine using this concept to write self-contained components that have a header/footer and some scrollable content as well. Unfortunately, I can't find much addressing this in the Tailwind docs or online.

I appreciate any suggestions! Here is the component code that I currently have:

```<code>import Image from 'next/image';
import cn from 'classnames';
import { useState } from 'react';
import { ImageInfo } from '../../types/images';
import Button from './button';
import { useRouter } from 'next/router';

type BlurImageProps = {
    image: ImageInfo;
};

const BlurImage = ({ image }: BlurImageProps): JSX.Element => {
    const [isLoading, setLoading] = useState(true);

    return (
        <div className="group shrink-0 h-40 w-40 relative aspect-w-1 aspect-h-1 overflow-hidden rounded-lg xl:aspect-w-7 xl:aspect-h-8 drop-shadow-xl bg-black">
            <Image
                alt=""
                src={image.url}
                width={512}
                height={512}
                className={cn(
                    'flex h-full duration-700 ease-in-out group-hover:opacity-20',
                    {
                        'scale-110 blur-2xl grayscale': isLoading,
                        'scale-100 blur-0 grayscale-0': !isLoading,
                    },
                )}
                onLoadingComplete={() => setLoading(false)}
            />
            {!isLoading && (
                <div className="absolute bottom-0 left-0 overflow-y-scroll items-center justify-center w-full h-full align-middle text-center px-2 opacity-0 duration-700 ease-in-out group-hover:opacity-100">
                    <a href={image.url}>
                        <p className="text-base text-white mb-2">
                            {image.prompt}
                        </p>
                    </a>

                    <Button
                        className="flex-shrink-0 px-2 py-2 text-sm font-bold text-white rounded bg-green-500"
                        type="button"
                        text="click me"
                        isSubmit={true}
                        onClick={() => console.log("clicked")}
                    />
                </div>
            )}
        </div>
    );
};

export default BlurImage;
</code>```

Body:
I'm using Tailwind to style a React component called "BlurImage" which displays an image by default and then on hover removes the image and displays a button at the bottom of the component and a text box at the top that has overflow-y-auto behavior to allow for scrolling if the text grows too long.

By default, the overflow responsibility is given to the body as discussed here and so I need to give the parent top-level div of BlurImage overflow as well. This causes both the text and the button to be scrollable. Is there a way to avoid having the button scroll?

This seems like it should be a common situation - I can imagine using this concept to write self-contained components that have a header/footer and some scrollable content as well. Unfortunately, I can't find much addressing this in the Tailwind docs or online.

I appreciate any suggestions! Here is the component code that I currently have:

import Image from 'next/image';
import cn from 'classnames';
import { useState } from 'react';
import { ImageInfo } from '../../types/images';
import Button from './button';
import { useRouter } from 'next/router';

type BlurImageProps = {
    image: ImageInfo;
};

const BlurImage = ({ image }: BlurImageProps): JSX.Element => {
    const [isLoading, setLoading] = useState(true);

    return (

            <Image
                alt=""
                src={image.url}
                width={512}
                height={512}
                className={cn(
                    'flex h-full duration-700 ease-in-out group-hover:opacity-20',
                    {
                        'scale-110 blur-2xl grayscale': isLoading,
                        'scale-100 blur-0 grayscale-0': !isLoading,
                    },
                )}
                onLoadingComplete={() => setLoading(false)}
            />
            {!isLoading && (

                            {image.prompt}

                    <Button
                        className="flex-shrink-0 px-2 py-2 text-sm font-bold text-white rounded bg-green-500"
                        type="button"
                        text="click me"
                        isSubmit={true}
                        onClick={() => console.log("clicked")}
                    />

            )}

    );
};

export default BlurImage;


问:
tRPC AppRouter is defined as "any" on import
I am currently using a monorepo with Turborepo to store all my microservices code in a single repository, each with a package.json and a tsconfig.json, all of them written in nodejs.

in each tsconfig.json, the config is identical

{
  "extends": "@tsconfig/node18-strictest-esm",
  "compilerOptions": {
    "outDir": "build",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"],
      "@folder-a/*": ["./folder-a/*"], // masked
      "@folder-b/*": ["folder-b/*"] // masked
    }
  },
  "exclude": ["node_modules", "build"]
}
```

I have one service A as a tRPC server, and one service B as a tRPC client.

When I imported the type definition of AppRouter from A to B, the type definition becomes any in B when it is properly typed in A.

I researched about it and found similar issue, and it seems like path alias may cause this issue.

Is there any solution/alternate cause to this

Body:
I am currently using a monorepo with Turborepo to store all my microservices code in a single repository, each with a package.json and a tsconfig.json, all of them written in nodejs.

in each tsconfig.json, the config is identical

{
  "extends": "@tsconfig/node18-strictest-esm",
  "compilerOptions": {
    "outDir": "build",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"],
      "@folder-a/*": ["./folder-a/*"], // masked
      "@folder-b/*": ["folder-b/*"] // masked
    }
  },
  "exclude": ["node_modules", "build"]
}

I have one service A as a tRPC server, and one service B as a tRPC client.

When I imported the type definition of AppRouter from A to B, the type definition becomes any in B when it is properly typed in A.

I researched about it and found similar issue, and it seems like path alias may cause this issue.

Is there any solution/alternate cause to this


问:
Unable to find component: [mes] using laravel livewire
I have a component using Laravel livewire which disappear please help me how can i resolve that thank u.

please check this error
https://flareapp.io/share/DPyDBeDm

\app\Http\Livewire\Messaging.php

```<code>  public function render()
    {

          return view('livewire.messaging');
    }
</code>```

Body:
I have a component using Laravel livewire which disappear please help me how can i resolve that thank u.

please check this error
https://flareapp.io/share/DPyDBeDm

\app\Http\Livewire\Messaging.php

  public function render()
    {

          return view('livewire.messaging');
    }


问:
cURL use the first request Redirect URL as the URL for the next request within the same curl command
So basically I have an API that's quite complicated to be implemented.

First URL: http://127.0.0.1

Second URL: http://127.0.0.1/{sessionId}

First, I have to log in to the first URL with POST along with username and password as the request body. The server will then return a Redirect URL with a session ID (E.g. http://127.0.0.1/005000). I will then need to use this new URL as the main URL for the next subsequent requests to tell the server that I'm authenticated. All this must be done within the same curl command because I found out that executing 2 different curl commands resulted in 2 different connections. The server doesn't treat different connections as the same even when using the authenticated redirect URL (http://127.0.0.1/005000).

Because of that I have come to a few conclusions and I will make them as questions:

How to keep the cURL connection open between 2 curl commands?

Is it possible to use the first cURL redirect URL response as the second cURL URL?

If it can't be done with cURL, is there an alternative?

Please note that I'm using the curl command line not curl PHP.

I tried sending request with 2 different curl commands but it didn't work as the server expected single connection after logging in and when actually requesting a resource in the server.


问:
How to install/uninstall service using .NET classes?
I'm trying to make an updater service, which will be updating another c#-written service on computer.

So I need to stop_service > uninstall_service > replace_exe > install_service > start_service in my code. Apparently I care about install_service/uninstall_service part.

I've read the tutorial about service app which is using installutil.exe to do stuff, but it feels kinda lame to call dotNet external app to do quite basic dotNet stuff.

So, how can I install/uninstall service utilizing .NET classes instead of external app?


问:
How to add markers to react-google-maps?
```<code>import GoogleMapReact from 'google-map-react';

const AnyReactComponent = ({ text }) => <div>{text}</div>;
const markers = [
  {
    id: 1,
    name: "Chicago, Illinois",
    position: { lat: 41.881832, lng: -87.623177 }
  },
  {
    id: 2,
    name: "Denver, Colorado",
    position: { lat: 39.739235, lng: -104.99025 }
  },
  {
    id: 3,
    name: "Los Angeles, California",
    position: { lat: 34.052235, lng: -118.243683 }
  },
  {
    id: 4,
    name: "New York, New York",
    position: { lat: 40.712776, lng: -74.005974 }
  }
];

export default function Map(){
  const defaultProps = {
    center: {
      lat: 19.0760,
      lng: 72.8777
    },
    zoom: 13
  };

  return (
    // Important! Always set the container height explicitly
    <div style={{ height: '100vh', width: '100%' }}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: "AIzaSyDhDJuGDDoMk9bmVvimMzp76ZbaIjn2Wk8" }}
        defaultCenter={defaultProps.center}
        defaultZoom={defaultProps.zoom}
      >
        {/* <AnyReactComponent
          lat={59.955413}
          lng={30.337844}
          text="My Marker"
        /> */}

        {markers.map((place)=>{
            <div className="container">
              lat = {Number(place.position.lat)}
              lng = {Number(place.position.lng)}
            </div>
        })}
      </GoogleMapReact>
    </div>
  );
}

</code>```

I am trying to Display markers on react map , but not able to do so...
I tried Different docs and examples but couldnt find a similar one , all of them were mostly class based and i tried to replicate that to functional but failed to do so.

Can someone help me plotting the markers on the map using functional component . Thanks

Body:
import GoogleMapReact from 'google-map-react';

const AnyReactComponent = ({ text }) =>
{text}
;
const markers = [
  {
    id: 1,
    name: "Chicago, Illinois",
    position: { lat: 41.881832, lng: -87.623177 }
  },
  {
    id: 2,
    name: "Denver, Colorado",
    position: { lat: 39.739235, lng: -104.99025 }
  },
  {
    id: 3,
    name: "Los Angeles, California",
    position: { lat: 34.052235, lng: -118.243683 }
  },
  {
    id: 4,
    name: "New York, New York",
    position: { lat: 40.712776, lng: -74.005974 }
  }
];

export default function Map(){
  const defaultProps = {
    center: {
      lat: 19.0760,
      lng: 72.8777
    },
    zoom: 13
  };

  return (
    // Important! Always set the container height explicitly

      <GoogleMapReact
        bootstrapURLKeys={{ key: "AIzaSyDhDJuGDDoMk9bmVvimMzp76ZbaIjn2Wk8" }}
        defaultCenter={defaultProps.center}
        defaultZoom={defaultProps.zoom}
      >
        {/* <AnyReactComponent
          lat={59.955413}
          lng={30.337844}
          text="My Marker"
        /> */}

        {markers.map((place)=>{

              lat = {Number(place.position.lat)}
              lng = {Number(place.position.lng)}

        })}
      </GoogleMapReact>

  );
}

I am trying to Display markers on react map , but not able to do so...
I tried Different docs and examples but couldnt find a similar one , all of them were mostly class based and i tried to replicate that to functional but failed to do so.

Can someone help me plotting the markers on the map using functional component . Thanks


问:
Android Dagger after convert code from support android to Androidx Dependency class not working
error: [ComponentProcessor:MiscError] dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code

I have try to update dagger library to latest 2.28.3 and target sdk to 32. but when I run project error: [ComponentProcessor:MiscError]  occurs.


问:
get original file name and extension for TemporaryUploadedFile for django
i am uploading file from react form to django rest framework.In django, i am using following code to get uploaded files array.

```<code>images_data =dict((self.context['request'].data).lists()).get('images', None)
</code>```

in settings.py file, i am using TemporaryFileUploadHandler

```<code> FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler']
</code>```

i want to know the original name of the file that was sent to server. in name i just get a random string with no extension. i want to save the file with original extension and name.
how can i get the original name and extension of the file?
i am using python 3.7.12

Body:
i am uploading file from react form to django rest framework.In django, i am using following code to get uploaded files array.

images_data =dict((self.context['request'].data).lists()).get('images', None)

in settings.py file, i am using TemporaryFileUploadHandler

 FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler']

i want to know the original name of the file that was sent to server. in name i just get a random string with no extension. i want to save the file with original extension and name.
how can i get the original name and extension of the file?
i am using python 3.7.12


问:
App icon not displaying after installing APK in OPPO A55
I am installing apk on my device OPPO A55 (Android 12), but after a successful install message, the app icon does not display in the menu list or Application Manager.

Below are some screenshots of the process and configuration of the device.


问:
How to read RLLib results? It seem they indicate that training does not happen within each training iteration but it does train
I am a looking at the example code for RLLib from

https://docs.ray.io/en/latest/rllib/rllib-training.html#rllib-config-framework

with modified line .rollouts(num_rollout_workers=10, horizon = 50000) to use as many workers as I have CPU cores and test if this implementation can achieve performance of my best BOT for cart-pole environment https://github.com/sebtac/MLxE which learns on 8 cores in 6 minutes to keep the pole up for 50K steps and, when fully trained, does so for 1M+ steps.

analyzing the outputs generated by print(pretty_print(result)) it seems that training "freezes" as the reported numbers do not change after each iteration (see details below). But after couple iterations the training "re-starts" with generally better performance indicators than in the last iteration. Why this might be the case? I assume that it has to do sth with the way the training algorithm is coded within RLLib. Maybe asking it to run episodes as long as 50K steps does not update all values in the results before results are printed in the next iteration?

Code:

```<code>start_time = time.time()
from ray.rllib.algorithms.ppo import PPOConfig
from ray.tune.logger import pretty_print

print("LOADED")
algo = (
    PPOConfig()
    .rollouts(num_rollout_workers=10, horizon = 50000)
    .resources(num_gpus=0)
    .environment(env="CartPole-v1")
    .build()
)
print("ALGO DONE")

for i in range(100):
    result = algo.train()
    print(pretty_print(result))

    if i % 5 == 0:
        checkpoint_dir = algo.save()
        print(f"Checkpoint saved in directory {checkpoint_dir}")

print("DONE!")
end_time = time.time()
print(end_time-start_time)
</code>```

Results:

```<code>agent_timesteps_total: 400000
counters:
  num_agent_steps_sampled: 400000
  num_agent_steps_trained: 400000
  num_env_steps_sampled: 400000
  num_env_steps_trained: 400000
custom_metrics: {}
date: 2022-12-29_22-13-37
done: false
episode_len_mean: 2430.73
episode_media: {}
episode_reward_max: 13961.0
episode_reward_mean: 2430.73
episode_reward_min: 65.0
episodes_this_iter: 0
episodes_total: 382
experiment_id: d2a7bd4c67654d7790cfb8655fa78a8f
hostname: Sebastians-MacBook-Pro-2.local
info:
  learner:
    default_policy:
      custom_metrics: {}
      diff_num_grad_updates_vs_sampler_policy: 464.5
      learner_stats:
        cur_kl_coeff: 1.6653346031121838e-17
        cur_lr: 4.999999873689376e-05
        entropy: 0.42701029777526855
        entropy_coeff: 0.0
        kl: -8.940913009958251e-10
        model: {}
        policy_loss: 0.0
        total_loss: -1.4889612459834557e-26
        vf_explained_var: -1.0
        vf_loss: 0.0
      num_agent_steps_trained: 128.0
      num_grad_updates_lifetime: 92535.5
  num_agent_steps_sampled: 400000
  num_agent_steps_trained: 400000
  num_env_steps_sampled: 400000
  num_env_steps_trained: 400000
iterations_since_restore: 100
node_ip: 127.0.0.1
num_agent_steps_sampled: 400000
num_agent_steps_trained: 400000
num_env_steps_sampled: 400000
num_env_steps_sampled_this_iter: 4000
num_env_steps_trained: 400000
num_env_steps_trained_this_iter: 4000
num_faulty_episodes: 0
num_healthy_workers: 10
num_in_flight_async_reqs: 0
num_remote_worker_restarts: 0
num_steps_trained_this_iter: 4000
perf:
  cpu_util_percent: 43.44375
  ram_util_percent: 46.568749999999994
pid: 21391
policy_reward_max: {}
policy_reward_mean: {}
policy_reward_min: {}
sampler_perf:
  mean_action_processing_ms: 0.07180588214674852
  mean_env_render_ms: 0.0
  mean_env_wait_ms: 0.051468155449639424
  mean_inference_ms: 8.535723368819935
  mean_raw_obs_processing_ms: 0.19257008707362022
sampler_results:
  custom_metrics: {}
  episode_len_mean: 2430.73
  episode_media: {}
  episode_reward_max: 13961.0
  episode_reward_mean: 2430.73
  episode_reward_min: 65.0
  episodes_this_iter: 0
  hist_stats:
    episode_lengths: [243, 199, 228, 82, 213, 338, 174, 485, 65, 84, 241, 347, 87,
      211, 271, 123, 379, 430, 315, 366, 305, 294, 275, 372, 264, 409, 239, 386, 235,
      321, 371, 151, 129, 491, 319, 859, 375, 318, 625, 594, 714, 622, 360, 2613,
      1473, 2520, 971, 2727, 2675, 3172, 3138, 2559, 2219, 5523, 2478, 2276, 3264,
      2491, 2418, 5696, 4909, 322, 744, 2535, 2508, 2422, 4157, 1797, 4350, 4334,
      4229, 3523, 4170, 4415, 2028, 2006, 1252, 2496, 2620, 5257, 5763, 4102, 5463,
      6000, 9156, 9189, 6292, 5792, 6237, 11669, 11629, 6299, 1704, 1856, 1887, 2206,
      7746, 2047, 1879, 13961]
    episode_reward: [243.0, 199.0, 228.0, 82.0, 213.0, 338.0, 174.0, 485.0, 65.0,
      84.0, 241.0, 347.0, 87.0, 211.0, 271.0, 123.0, 379.0, 430.0, 315.0, 366.0, 305.0,
      294.0, 275.0, 372.0, 264.0, 409.0, 239.0, 386.0, 235.0, 321.0, 371.0, 151.0,
      129.0, 491.0, 319.0, 859.0, 375.0, 318.0, 625.0, 594.0, 714.0, 622.0, 360.0,
      2613.0, 1473.0, 2520.0, 971.0, 2727.0, 2675.0, 3172.0, 3138.0, 2559.0, 2219.0,
      5523.0, 2478.0, 2276.0, 3264.0, 2491.0, 2418.0, 5696.0, 4909.0, 322.0, 744.0,
      2535.0, 2508.0, 2422.0, 4157.0, 1797.0, 4350.0, 4334.0, 4229.0, 3523.0, 4170.0,
      4415.0, 2028.0, 2006.0, 1252.0, 2496.0, 2620.0, 5257.0, 5763.0, 4102.0, 5463.0,
      6000.0, 9156.0, 9189.0, 6292.0, 5792.0, 6237.0, 11669.0, 11629.0, 6299.0, 1704.0,
      1856.0, 1887.0, 2206.0, 7746.0, 2047.0, 1879.0, 13961.0]
  num_faulty_episodes: 0
  policy_reward_max: {}
  policy_reward_mean: {}
  policy_reward_min: {}
  sampler_perf:
    mean_action_processing_ms: 0.07180588214674852
    mean_env_render_ms: 0.0
    mean_env_wait_ms: 0.051468155449639424
    mean_inference_ms: 8.535723368819935
    mean_raw_obs_processing_ms: 0.19257008707362022
time_since_restore: 1137.2171549797058
time_this_iter_s: 11.495001077651978
time_total_s: 1137.2171549797058
timers:
  learn_throughput: 514.515
  learn_time_ms: 7774.316
  load_throughput: 38164731.574
  load_time_ms: 0.105
  synch_weights_time_ms: 8.647
  training_iteration_time_ms: 11505.094
timestamp: 1672373617
timesteps_since_restore: 0
timesteps_total: 400000
training_iteration: 100
trial_id: default
warmup_time: 9.37411093711853}
</code>```

While entries like learner_timsteps_toatal and learner_stats do change from iteration to iteration elements like Hist_Stats do not. I assume that it means that learning (parameter updates) continues from iteration to iteration but the evaluation games played in subsequent iteration result in the same results as in the previous iteration. Does it mean that the policy becomes at certain moment deterministic? an/or that initial states are the same across multiple iterations? or that it take longer time for episode generation to finish than the time needed for another reporting of the results?

Body:
I am a looking at the example code for RLLib from

https://docs.ray.io/en/latest/rllib/rllib-training.html#rllib-config-framework

with modified line .rollouts(num_rollout_workers=10, horizon = 50000) to use as many workers as I have CPU cores and test if this implementation can achieve performance of my best BOT for cart-pole environment https://github.com/sebtac/MLxE which learns on 8 cores in 6 minutes to keep the pole up for 50K steps and, when fully trained, does so for 1M+ steps.

analyzing the outputs generated by print(pretty_print(result)) it seems that training "freezes" as the reported numbers do not change after each iteration (see details below). But after couple iterations the training "re-starts" with generally better performance indicators than in the last iteration. Why this might be the case? I assume that it has to do sth with the way the training algorithm is coded within RLLib. Maybe asking it to run episodes as long as 50K steps does not update all values in the results before results are printed in the next iteration?

Code:

start_time = time.time()
from ray.rllib.algorithms.ppo import PPOConfig
from ray.tune.logger import pretty_print

print("LOADED")
algo = (
    PPOConfig()
    .rollouts(num_rollout_workers=10, horizon = 50000)
    .resources(num_gpus=0)
    .environment(env="CartPole-v1")
    .build()
)
print("ALGO DONE")

for i in range(100):
    result = algo.train()
    print(pretty_print(result))

    if i % 5 == 0:
        checkpoint_dir = algo.save()
        print(f"Checkpoint saved in directory {checkpoint_dir}")

print("DONE!")
end_time = time.time()
print(end_time-start_time)

Results:

agent_timesteps_total: 400000
counters:
  num_agent_steps_sampled: 400000
  num_agent_steps_trained: 400000
  num_env_steps_sampled: 400000
  num_env_steps_trained: 400000
custom_metrics: {}
date: 2022-12-29_22-13-37
done: false
episode_len_mean: 2430.73
episode_media: {}
episode_reward_max: 13961.0
episode_reward_mean: 2430.73
episode_reward_min: 65.0
episodes_this_iter: 0
episodes_total: 382
experiment_id: d2a7bd4c67654d7790cfb8655fa78a8f
hostname: Sebastians-MacBook-Pro-2.local
info:
  learner:
    default_policy:
      custom_metrics: {}
      diff_num_grad_updates_vs_sampler_policy: 464.5
      learner_stats:
        cur_kl_coeff: 1.6653346031121838e-17
        cur_lr: 4.999999873689376e-05
        entropy: 0.42701029777526855
        entropy_coeff: 0.0
        kl: -8.940913009958251e-10
        model: {}
        policy_loss: 0.0
        total_loss: -1.4889612459834557e-26
        vf_explained_var: -1.0
        vf_loss: 0.0
      num_agent_steps_trained: 128.0
      num_grad_updates_lifetime: 92535.5
  num_agent_steps_sampled: 400000
  num_agent_steps_trained: 400000
  num_env_steps_sampled: 400000
  num_env_steps_trained: 400000
iterations_since_restore: 100
node_ip: 127.0.0.1
num_agent_steps_sampled: 400000
num_agent_steps_trained: 400000
num_env_steps_sampled: 400000
num_env_steps_sampled_this_iter: 4000
num_env_steps_trained: 400000
num_env_steps_trained_this_iter: 4000
num_faulty_episodes: 0
num_healthy_workers: 10
num_in_flight_async_reqs: 0
num_remote_worker_restarts: 0
num_steps_trained_this_iter: 4000
perf:
  cpu_util_percent: 43.44375
  ram_util_percent: 46.568749999999994
pid: 21391
policy_reward_max: {}
policy_reward_mean: {}
policy_reward_min: {}
sampler_perf:
  mean_action_processing_ms: 0.07180588214674852
  mean_env_render_ms: 0.0
  mean_env_wait_ms: 0.051468155449639424
  mean_inference_ms: 8.535723368819935
  mean_raw_obs_processing_ms: 0.19257008707362022
sampler_results:
  custom_metrics: {}
  episode_len_mean: 2430.73
  episode_media: {}
  episode_reward_max: 13961.0
  episode_reward_mean: 2430.73
  episode_reward_min: 65.0
  episodes_this_iter: 0
  hist_stats:
    episode_lengths: [243, 199, 228, 82, 213, 338, 174, 485, 65, 84, 241, 347, 87,
      211, 271, 123, 379, 430, 315, 366, 305, 294, 275, 372, 264, 409, 239, 386, 235,
      321, 371, 151, 129, 491, 319, 859, 375, 318, 625, 594, 714, 622, 360, 2613,
      1473, 2520, 971, 2727, 2675, 3172, 3138, 2559, 2219, 5523, 2478, 2276, 3264,
      2491, 2418, 5696, 4909, 322, 744, 2535, 2508, 2422, 4157, 1797, 4350, 4334,
      4229, 3523, 4170, 4415, 2028, 2006, 1252, 2496, 2620, 5257, 5763, 4102, 5463,
      6000, 9156, 9189, 6292, 5792, 6237, 11669, 11629, 6299, 1704, 1856, 1887, 2206,
      7746, 2047, 1879, 13961]
    episode_reward: [243.0, 199.0, 228.0, 82.0, 213.0, 338.0, 174.0, 485.0, 65.0,
      84.0, 241.0, 347.0, 87.0, 211.0, 271.0, 123.0, 379.0, 430.0, 315.0, 366.0, 305.0,
      294.0, 275.0, 372.0, 264.0, 409.0, 239.0, 386.0, 235.0, 321.0, 371.0, 151.0,
      129.0, 491.0, 319.0, 859.0, 375.0, 318.0, 625.0, 594.0, 714.0, 622.0, 360.0,
      2613.0, 1473.0, 2520.0, 971.0, 2727.0, 2675.0, 3172.0, 3138.0, 2559.0, 2219.0,
      5523.0, 2478.0, 2276.0, 3264.0, 2491.0, 2418.0, 5696.0, 4909.0, 322.0, 744.0,
      2535.0, 2508.0, 2422.0, 4157.0, 1797.0, 4350.0, 4334.0, 4229.0, 3523.0, 4170.0,
      4415.0, 2028.0, 2006.0, 1252.0, 2496.0, 2620.0, 5257.0, 5763.0, 4102.0, 5463.0,
      6000.0, 9156.0, 9189.0, 6292.0, 5792.0, 6237.0, 11669.0, 11629.0, 6299.0, 1704.0,
      1856.0, 1887.0, 2206.0, 7746.0, 2047.0, 1879.0, 13961.0]
  num_faulty_episodes: 0
  policy_reward_max: {}
  policy_reward_mean: {}
  policy_reward_min: {}
  sampler_perf:
    mean_action_processing_ms: 0.07180588214674852
    mean_env_render_ms: 0.0
    mean_env_wait_ms: 0.051468155449639424
    mean_inference_ms: 8.535723368819935
    mean_raw_obs_processing_ms: 0.19257008707362022
time_since_restore: 1137.2171549797058
time_this_iter_s: 11.495001077651978
time_total_s: 1137.2171549797058
timers:
  learn_throughput: 514.515
  learn_time_ms: 7774.316
  load_throughput: 38164731.574
  load_time_ms: 0.105
  synch_weights_time_ms: 8.647
  training_iteration_time_ms: 11505.094
timestamp: 1672373617
timesteps_since_restore: 0
timesteps_total: 400000
training_iteration: 100
trial_id: default
warmup_time: 9.37411093711853}

While entries like learner_timsteps_toatal and learner_stats do change from iteration to iteration elements like Hist_Stats do not. I assume that it means that learning (parameter updates) continues from iteration to iteration but the evaluation games played in subsequent iteration result in the same results as in the previous iteration. Does it mean that the policy becomes at certain moment deterministic? an/or that initial states are the same across multiple iterations? or that it take longer time for episode generation to finish than the time needed for another reporting of the results?


Title: Getting error in subtraction of floating numbers in PHP. Same code with similar data returns different results

Body:
Need to understand this error and resolve it:

<?php
$a = 204.95 + 204.95 + 204.95;
$b = 614.85;
echo $a ."->" .$b ."->" . ($b - $a)."\n";

$a = 204.93 + 204.93 + 204.93;
$b = 614.79;

echo $a ."->" .$b ."->" . ($b - $a)."\n";
?>

Getting output:

614.85->614.85->1.1368683772162E-13
614.79->614.79->0

Expected Result is:

614.85->614.85->0
614.79->614.79->0


问:
Selecting single Element from Drop Down List DDL
First time poster.

Having trouble in slecting one of the element/itmes from a dropped down items without using select class ?

And the list of the size is showing currently as 1 whilst the are numerous.

Moreover, Send keys option is also inoperative/inresponsive.

TIA

Initially these dropdown list is not developed by the developers.

These list would vary for different users based on their roles within the project.


问:
How to reload <ui:include>
We included a page with ui:include. And when a button is clicked we want to rerender ui:included page too. Here is parent page;

```<code><h:form id="mainForm">
        <a4j:region rendered="#{dealHome.editMode}">
            <ui:include src="/createEditDeal.xhtml">
                <ui:param name="id" value="#{dealHome.instance.id}" />
            </ui:include>
        </a4j:region>
        <a4j:region rendered="#{not dealHome.editMode}">
            <ui:include src="/readDeal.xhtml">
                <ui:param name="id" value="#{dealHome.instance.id}" />
            </ui:include>
        </a4j:region>
        <s:div rendered="#{dealHome.editMode}">
            <a4j:commandButton action="#{dealHome.persist()}" value="+"
                id="btnTagAdd" reRender="mainForm" />
        </s:div>
        <s:div rendered="#{not dealHome.editMode}">
            <a4j:commandButton id="btnModeChange" value="Edit"
                action="#{dealHome.changeMode()}" reRender="mainForm" />
        </s:div>
    </h:form>
</code>```

Any help or advice would be appreciated.

ContentLicense: CC BY-SA 3.0

Title: How to reload <ui:include>

Body:
We included a page with ui:include. And when a button is clicked we want to rerender ui:included page too. Here is parent page;

<h:form id="mainForm">
        <a4j:region rendered="#{dealHome.editMode}">
            <ui:include src="/createEditDeal.xhtml">
                <ui:param name="id" value="#{dealHome.instance.id}" />
            </ui:include>
        </a4j:region>
        <a4j:region rendered="#{not dealHome.editMode}">
            <ui:include src="/readDeal.xhtml">
                <ui:param name="id" value="#{dealHome.instance.id}" />
            </ui:include>
        </a4j:region>
        <s:div rendered="#{dealHome.editMode}">
            <a4j:commandButton action="#{dealHome.persist()}" value="+"
                id="btnTagAdd" reRender="mainForm" />
        </s:div>
        <s:div rendered="#{not dealHome.editMode}">
            <a4j:commandButton id="btnModeChange" value="Edit"
                action="#{dealHome.changeMode()}" reRender="mainForm" />
        </s:div>
    </h:form>

Any help or advice would be appreciated.


问:
How to update the key value of json string in python
I have a script where I will get the data from the following JSON string:

```<code>Process_details = { "process_dtls":[{"process_name":"process1","process_id":1},{"process_name":"process2","process_id":2},
{"process_name":"process1","process_id":3}]}
</code>```

I want to loop all the process and I should be able to update the key values.

Below is the code I have now, but it is not updating the key value.

```<code>for i in Process_details["process_dtls"]:
     i['process_id']= 0
</code>```

Body:
I have a script where I will get the data from the following JSON string:

Process_details = { "process_dtls":[{"process_name":"process1","process_id":1},{"process_name":"process2","process_id":2},
{"process_name":"process1","process_id":3}]}

I want to loop all the process and I should be able to update the key values.

Below is the code I have now, but it is not updating the key value.

for i in Process_details["process_dtls"]:
     i['process_id']= 0


问:
Resizing images in pysimplegui without pillow
For a course, I need to create a gui using pysimplegui.

I cannot install pillow--it is installed against C:/users/python310 while VS studio Code is using python311. I have tried modifying the environment variables, using -m when using pip, etc and nothing has worked.

so I have given up (after spending over a day trying to fix the pillow installation) and was looking for a way to resize the image element without using pillow.

My code so far:

def ColumnFixedSize(layout, size=(None, None), *args, **kwargs):
    # An addition column is needed to wrap the column with the Sizers because the colors will not be set on the space the sizers take
    return sg.Column([[sg.Column([[sg.Sizer(0, size[1]-1), sg.Column([[sg.Sizer(size[0]-2, 0)]] + layout, *args, **kwargs, pad=(0, 0))]], *args, **kwargs)]], pad=(0, 0))

col_interior = [[sg.Text('Welcome', size=(
    80, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE),
    sg.Image('C:\\Users\\Documents\\Logo.png')]
```

I have tried the size=(400,400) in the sg.Image properties though this only crops the image.

is there a way to adjust the image size without affecting the aspect ratio and not cropping the image?

Body:
For a course, I need to create a gui using pysimplegui.

I cannot install pillow--it is installed against C:/users/python310 while VS studio Code is using python311. I have tried modifying the environment variables, using -m when using pip, etc and nothing has worked.

so I have given up (after spending over a day trying to fix the pillow installation) and was looking for a way to resize the image element without using pillow.

My code so far:

def ColumnFixedSize(layout, size=(None, None), *args, **kwargs):
    # An addition column is needed to wrap the column with the Sizers because the colors will not be set on the space the sizers take
    return sg.Column([[sg.Column([[sg.Sizer(0, size[1]-1), sg.Column([[sg.Sizer(size[0]-2, 0)]] + layout, *args, **kwargs, pad=(0, 0))]], *args, **kwargs)]], pad=(0, 0))

col_interior = [[sg.Text('Welcome', size=(
    80, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE),
    sg.Image('C:\\Users\\Documents\\Logo.png')]

I have tried the size=(400,400) in the sg.Image properties though this only crops the image.

is there a way to adjust the image size without affecting the aspect ratio and not cropping the image?


问:
"FAILED TO DECODE IMAGE" Flutter Base64 Image Decode not working Properly some base64, though that base64 is converting on online tools
I am using flutter and decoding the image from base64 while decoding the image flutter shows me the images of almost every images but it is not showing me the images of some base64. What could be the possible solution.

I have used

```<code>      signatureImage = Image.memory(base64Decode(base64data));

</code>```

Image.memory() I have used. I want to know more methods where I can set base64 to Image

Body:
I am using flutter and decoding the image from base64 while decoding the image flutter shows me the images of almost every images but it is not showing me the images of some base64. What could be the possible solution.

I have used

      signatureImage = Image.memory(base64Decode(base64data));

Image.memory() I have used. I want to know more methods where I can set base64 to Image


问:
FastAPI Test Case not running
I am trying to run FastAPI test case's but it is showing - no tests ran

This is Main.py -

```<code>import psycopg2
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    age: int

def get_db_connection():
    connection = psycopg2.connect(
        host="localhost",
        user="********",
        password="********",
        database="user"
    )

    return connection

# Create a user
@app.post("/users")
def create_user(user: User, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "INSERT INTO users (name, age) VALUES (%s, %s)",
        (user.name, user.age)
    )

    db_conn.commit()
    cursor.close()
    return {"id": cursor.lastrowid, "name": user.name, "age": user.age}

# Read a user
@app.get("/users/{user_id}")
def read_user(user_id: int, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "SELECT id, name, age FROM users WHERE id=%s",
        (user_id,)
    )

    user = cursor.fetchone()
    cursor.close()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return {"id": user[0], "name": user[1], "age": user[2]}

@app.put("/users/{user_id}")
def update_user(user_id: int, user: User, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "UPDATE users SET name=%s, age=%s WHERE id=%s",
        (user.name, user.age, user_id)
    )

    db_conn.commit()
    cursor.close()
    return {"id": user_id, "name": user.name, "age": user.age}

@app.delete("/users/{user_id}")
def delete_user(user_id: int, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "DELETE FROM users WHERE id=%s",
        (user_id,)
    )
    db_conn.commit()
    cursor.close()
    return {"message": "user deleted"}
</code>```

This is unit_test.py

```<code>from fastapi.testclient import TestClient
from main import app

client = TestClient(app=app)

def test_create_user():
    data = {"name": "John", "age": 30}
    response = client.post("/users")
    assert response.status_code == 201
    assert response.json() == {"id": 1, "name": "John", "age": 30}

def test_read_user():
    response = client.get("/users/1")
    assert response.status_code == 200
    assert response.json() == {"id": 1, "name": "John", "age": 30}

def test_read_non_existent_user():
    response = client.get("/users/2")
    assert response.status_code == 404

def test_update_user():
    data = {"name": "Jane", "age": 35}
    response = client.put("/users/1")
    assert response.status_code == 200
    assert response.json() == {"id": 1, "name": "Jane", "age": 35}

def test_delete_user():
    response = client.delete("/users/1")
    assert response.status_code == 200
    assert response.json() == {"message": "user deleted"}
</code>```

I tried to run the file but it is showing no tests ran and collected 0 items. I used pytest command to run this test inside the same directory where my 2 files are present.

Here the problem is no test case is collecting and running. Where did I do wrong here?

Title: FastAPI Test Case not running

Body:
I am trying to run FastAPI test case's but it is showing - no tests ran

This is Main.py -

import psycopg2
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    age: int

def get_db_connection():
    connection = psycopg2.connect(
        host="localhost",
        user="********",
        password="********",
        database="user"
    )

    return connection

# Create a user
@app.post("/users")
def create_user(user: User, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "INSERT INTO users (name, age) VALUES (%s, %s)",
        (user.name, user.age)
    )

    db_conn.commit()
    cursor.close()
    return {"id": cursor.lastrowid, "name": user.name, "age": user.age}

# Read a user
@app.get("/users/{user_id}")
def read_user(user_id: int, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "SELECT id, name, age FROM users WHERE id=%s",
        (user_id,)
    )

    user = cursor.fetchone()
    cursor.close()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return {"id": user[0], "name": user[1], "age": user[2]}

@app.put("/users/{user_id}")
def update_user(user_id: int, user: User, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "UPDATE users SET name=%s, age=%s WHERE id=%s",
        (user.name, user.age, user_id)
    )

    db_conn.commit()
    cursor.close()
    return {"id": user_id, "name": user.name, "age": user.age}

@app.delete("/users/{user_id}")
def delete_user(user_id: int, db_conn = Depends(get_db_connection)):
    cursor = db_conn.cursor()
    cursor.execute(
        "DELETE FROM users WHERE id=%s",
        (user_id,)
    )
    db_conn.commit()
    cursor.close()
    return {"message": "user deleted"}

This is unit_test.py

from fastapi.testclient import TestClient
from main import app

client = TestClient(app=app)

def test_create_user():
    data = {"name": "John", "age": 30}
    response = client.post("/users")
    assert response.status_code == 201
    assert response.json() == {"id": 1, "name": "John", "age": 30}

def test_read_user():
    response = client.get("/users/1")
    assert response.status_code == 200
    assert response.json() == {"id": 1, "name": "John", "age": 30}

def test_read_non_existent_user():
    response = client.get("/users/2")
    assert response.status_code == 404

def test_update_user():
    data = {"name": "Jane", "age": 35}
    response = client.put("/users/1")
    assert response.status_code == 200
    assert response.json() == {"id": 1, "name": "Jane", "age": 35}

def test_delete_user():
    response = client.delete("/users/1")
    assert response.status_code == 200
    assert response.json() == {"message": "user deleted"}

I tried to run the file but it is showing no tests ran and collected 0 items. I used pytest command to run this test inside the same directory where my 2 files are present.

Here the problem is no test case is collecting and running. Where did I do wrong here?