问:
I have error after updating my powershell on windows 7 64bit
Please I updated powershell 2 to powershell 5 then I got this error in cmd. What does it mean?
Also powershell window stopped working after updated I can't see if I got version 5 or not
What should I do
Error

After updating I restert my machine and tried too many times to open powershell window but it doesn't work. Also I downloaded Net-framework 4.5 but it stopped while installing


来源: stackexchange

问:
Can I monitor problems in the TCP/IP stack from C#
We run a number of services, which expose data on https listeners
Lately we have seen issues which might be related to problems with low-level TCP/IP packets

Could be a client is not responding timely with ACK to our network packets
Or filling up our TCP/IP stack by sending us requests and only receiving the response very slowly
Or maybe even lost network packets and retransmit

Is it possible to monitor and capture problems with TCP/IP messages in a C# service?

ContentLicense: CC BY-SA 4.0


问:
Negative integers multiplication in arithmetic shifts
When we multiply a negative integer by 2, the method is still working.

Example: -36 * 2

```<code>     11011100 (*2 by shifting one step to left)
     10111000
</code>```

This method doesn't work for further calculations such as 4,  8, etc.
Example: -36 * 4

```<code>     11011100 (*4 shifting two steps to left)
     01110000 (the answer is totally wrong)
</code>```

I would be very pleased to have a solution for this since I can't get enough information online.

I tried putting 1 in front for negative condition but the shifting thing isn't working.

Body:
When we multiply a negative integer by 2, the method is still working.

Example: -36 * 2

     11011100 (*2 by shifting one step to left)
     10111000

This method doesn't work for further calculations such as 4,  8, etc.
Example: -36 * 4

     11011100 (*4 shifting two steps to left)
     01110000 (the answer is totally wrong)

I would be very pleased to have a solution for this since I can't get enough information online.

I tried putting 1 in front for negative condition but the shifting thing isn't working.


问:
Used PHP sessions with JS XMLHttpRequest
I've got a couple of PHP scripts which I call functions from using XMLHttpRequest in JS from my front end.

If I hit the PHP scripts directly in the browser, the session (session_start();$_SESSION["working"] = "true";) and session variables are retained, but if I call them from the webpage using XMLHttpRequest they are not.

Is this expected behaviour, as PHP has no way of knowing the session is still active when calling it with XMLHttpRequest?

I was hoping (not expecting), that PHP would somehow know the session was still active.

Works fine if I access the PHP files directly in the browser, even if I switch between different files, but not when called from JS.


问:
Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'
```<code>library(dplyr)

dend1 <- df %>%
 dist %>%
 hclust("complete") %>%
 as.dendrogram
</code>```

Error in as.vector(x, mode) :
cannot coerce type 'closure' to vector of type 'any'

Why is this error popping out? Thanks

I have tried multiple ways but couldn't manage to solve the issue.

Body:
library(dplyr)

dend1 <- df %>%
 dist %>%
 hclust("complete") %>%
 as.dendrogram

Error in as.vector(x, mode) :
cannot coerce type 'closure' to vector of type 'any'

Why is this error popping out? Thanks

I have tried multiple ways but couldn't manage to solve the issue.


问:
Want to create S3 Filesystem in python with stable library
I want to create s3 file system for uploading files to s3 bucket using the pyarrows write_to_dataset function

```<code>fs = s3fs.S3FileSystem()
pa.parquet.write_to_dataset(table, root_path=output_folder, filesystem=fs,
                            compression='snappy', partition_filename_cb=lambda x: filename)
</code>```

but I got to know that s3fs library is still in the beta phase.

is there any production/stable library available for creating a s3 file system?

if not is there other way like boto3 to create s3 file system?

Body:
I want to create s3 file system for uploading files to s3 bucket using the pyarrows write_to_dataset function

fs = s3fs.S3FileSystem()
pa.parquet.write_to_dataset(table, root_path=output_folder, filesystem=fs,
                            compression='snappy', partition_filename_cb=lambda x: filename)

but I got to know that s3fs library is still in the beta phase.

is there any production/stable library available for creating a s3 file system?

if not is there other way like boto3 to create s3 file system?


问:
Sharding not enabled on MongoDB
On a Kubernetes Clusters, using a bitnami helm ,On a Database mongo 6.0.1,I have created a database previously and applied a new collection on it and it was working but recently the sh.enableSharding() is working on a database which i have created but by applying sh.ShardCollection it displays "MongoServerError: sharding not enabled for db".

I have created different databases for testing purpose but all of them are facing the same issue.

Command:

```<code>[direct: mongos] my_db> sh.enableSharding("my_db")
</code>```

Output:
{
ok: 1,
'$clusterTime':

```<code>{     clusterTime: Timestamp(\{ t: 1678966557, i: 1 }
),
signature:

{       hash:
Binary(Buffer.from("b5da1b9a2539ecdaf77096012e36a014b51c492b",
"hex"), 0),       keyId: Long("7925145979144201565")     }
},
operationTime: Timestamp({ t: 1678966557, i: 1 })
}
</code>```

Command:

```<code>[direct: mongos] my_db> sh.shardCollection("my_db.my_collection", {"_id": "hashed"})
</code>```

Output:

```<code>`MongoServerError: sharding not enabled for db my_db`
</code>```

Title: Sharding not enabled on MongoDB

Body:
On a Kubernetes Clusters, using a bitnami helm ,On a Database mongo 6.0.1,I have created a database previously and applied a new collection on it and it was working but recently the sh.enableSharding() is working on a database which i have created but by applying sh.ShardCollection it displays "MongoServerError: sharding not enabled for db".

I have created different databases for testing purpose but all of them are facing the same issue.

Command:

[direct: mongos] my_db> sh.enableSharding("my_db")

Output:
{
ok: 1,
'$clusterTime':

{     clusterTime: Timestamp(\{ t: 1678966557, i: 1 }
),
signature:

{       hash:
Binary(Buffer.from("b5da1b9a2539ecdaf77096012e36a014b51c492b",
"hex"), 0),       keyId: Long("7925145979144201565")     }
},
operationTime: Timestamp({ t: 1678966557, i: 1 })
}

Command:

[direct: mongos] my_db> sh.shardCollection("my_db.my_collection", {"_id": "hashed"})

Output:

`MongoServerError: sharding not enabled for db my_db`


问:
How to replace STRING_AGG and CONCAT in MS SQL Server 2008?
```<code>
              ,(SELECT
                  STRING_AGG(per.Descripcion,' , ') as Permisos
                  FROM [Jose].[dbo].[Usuarios] usua
                  left join dbo.permisos_has_usuarios perUsu
                  on perUsu.usuario_id = usua.id
                  left join dbo.Permisos per
                  on per.Id = perUsu.permiso_id
                  where usua.id = usu.[Id] ) as Permisos
              ,usu.[FechaNacimiento]
              ,usu.[HoraEntrada]
              ,usu.[HoraSalida]
          FROM [Jose].[dbo].[Usuarios] usu
          left join dbo.Cargos car
          on usu.Cargo = car.Id
</code>```

I need renplaced the "STRING_AGG" to concat the sql server 2008

Body:
              ,(SELECT
                  STRING_AGG(per.Descripcion,' , ') as Permisos
                  FROM [Jose].[dbo].[Usuarios] usua
                  left join dbo.permisos_has_usuarios perUsu
                  on perUsu.usuario_id = usua.id
                  left join dbo.Permisos per
                  on per.Id = perUsu.permiso_id
                  where usua.id = usu.[Id] ) as Permisos
              ,usu.[FechaNacimiento]
              ,usu.[HoraEntrada]
              ,usu.[HoraSalida]
          FROM [Jose].[dbo].[Usuarios] usu
          left join dbo.Cargos car
          on usu.Cargo = car.Id

I need renplaced the "STRING_AGG" to concat the sql server 2008


问:
How To Enable PHP Zip module?
I just installed a new theme to my site and am now attempting to load the demo site pages that came with the theme. I am getting an error message before I ever even attempt to do anything that says the following:

Oops, Unyson Backup requires PHP Zip module but it is not enabled on your server. If you are not familiar with PHP Zip module, please contact your hosting provider.

Can anyone tell me how to enable PHP Zip module im using virtualmin i don't use a regular cpanel
Thank you

im looking for php but

Title: How To Enable PHP Zip module?


问:
Keep Excel from inserting "@" into formula
I feel like I'm missing something basic, but I have the following bit of code that is referring to a table on another sheet.

```<code>Sub availabilityTab()
Dim cell As String
Dim i As Integer

With Sheets("Availability")
.Cells.Clear
.Range("A3") = "=BackgroundData[#Headers]"

    For i = 1 To 5
    cell = .Cells(3, i)
    .Cells(4, i) = "=BackgroundData[" & cell & "]"
    Next i

End With
End Sub
</code>```

Unfortunately, when it inserts the formula in these cells it inserts an "@" that keeps the result from spilling, such as

```<code>=@BackgroundData[#Headers]
</code>```

in A3. Or

```<code>=BackgroundData[@ID]
</code>```

in A4. How do I keep it from inserting the @?
Thanks!

Body:
I feel like I'm missing something basic, but I have the following bit of code that is referring to a table on another sheet.

Sub availabilityTab()
Dim cell As String
Dim i As Integer

With Sheets("Availability")
.Cells.Clear
.Range("A3") = "=BackgroundData[#Headers]"

    For i = 1 To 5
    cell = .Cells(3, i)
    .Cells(4, i) = "=BackgroundData[" & cell & "]"
    Next i

End With
End Sub

Unfortunately, when it inserts the formula in these cells it inserts an "@" that keeps the result from spilling, such as

=@BackgroundData[#Headers]

in A3. Or

=BackgroundData[@ID]

in A4. How do I keep it from inserting the @?
Thanks!


问:
Error "Bad gRPC response. HTTP status code: 500" when set $var in NGINX grpc_pass
When i set $var in grpc_pass i can't connect grpc-client to server,  I get the FAIL error

```<code>   [Microsoft.Extensions.Hosting.Internal.Host)
   [BackgroundServiceFaulted status   BackgroundServledGrpc.Co.RpcException
(StatusCode="Unknown", Detail="Bad gRPC response. HTTP status code: 500")
</code>```

The purpose of setting a variable is to bypass the situation where one of the services that proxies NGINX crashes, and when NGINX restarts, the other services continue to work.

With proxy_pass directive all works and tests are successful (Setup nginx not to crash if host in upstream is not found), with grpc_pass - no, BUT in manual says that

Parameter value can contain variables (1.17.8). In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.

version:

```<code># nginx -v
nginx version: nginx/1.23.2
</code>```

path myexamplenginx_conf:

```<code>  location / {
        resolver 127.0.0.11 valid=30s;
        set $webuidev https://dev_webuidev;
        proxy_pass $webuidev;

        #proxy_pass https://dev_webuidev;
        # Configuration for WebSockets
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache off;
        # WebSockets were implemented after http/1.0
        proxy_http_version 1.1;
        # Configuration for ServerSentEvents
        proxy_buffering off;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-URL-SCHEME https;
    }
    location /App.Room.Api.Contract.ApiService/UpdateOpcDaTags {
        resolver 127.0.0.11 valid=30s;
        set $grpc_webuidev grpcs://dev_webuidev;
        grpc_pass $grpc_webuidev;

        #grpc_pass grpcs://dev_webuidev;
    }
</code>```

Body:
When i set $var in grpc_pass i can't connect grpc-client to server,  I get the FAIL error

   [Microsoft.Extensions.Hosting.Internal.Host)
   [BackgroundServiceFaulted status   BackgroundServledGrpc.Co.RpcException
(StatusCode="Unknown", Detail="Bad gRPC response. HTTP status code: 500")

The purpose of setting a variable is to bypass the situation where one of the services that proxies NGINX crashes, and when NGINX restarts, the other services continue to work.

With proxy_pass directive all works and tests are successful (Setup nginx not to crash if host in upstream is not found), with grpc_pass - no, BUT in manual says that

Parameter value can contain variables (1.17.8). In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.

version:

# nginx -v
nginx version: nginx/1.23.2

path myexamplenginx_conf:

  location / {
        resolver 127.0.0.11 valid=30s;
        set $webuidev https://dev_webuidev;
        proxy_pass $webuidev;

        #proxy_pass https://dev_webuidev;
        # Configuration for WebSockets
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache off;
        # WebSockets were implemented after http/1.0
        proxy_http_version 1.1;
        # Configuration for ServerSentEvents
        proxy_buffering off;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-URL-SCHEME https;
    }
    location /App.Room.Api.Contract.ApiService/UpdateOpcDaTags {
        resolver 127.0.0.11 valid=30s;
        set $grpc_webuidev grpcs://dev_webuidev;
        grpc_pass $grpc_webuidev;

        #grpc_pass grpcs://dev_webuidev;
    }


问:
Bootstrap 5.2 add margin increments
I have been trying to implement additional spacing increments to Bootstrap, however the SASS map-merge seems to have no impact of the available classes.

I have followed the Boostrap 5.2 documentation on how the $spacers map should be formatted, and I have added a map-merge to my SASS file:

```<code>@import "../../src/bootstrap/scss/functions";
@import "../../src/bootstrap/scss/variables";
@import "../../src/bootstrap/scss/mixins";
@import "../../src/bootstrap/scss/_maps.scss";
@import "../../src/bootstrap/scss/_utilities.scss";

$spacer: 1rem;
$custom-spacers: ( 6: $spacer * 4, 7: $spacer * 5, 8: $spacer * 6,);

$spacers: map-merge($spacers, $custom-spacers);

@import "../../src/bootstrap/scss/bootstrap.scss";
</code>```

I have then been checking the resulting .css file once compiled with gulp and it has no instance of any -6 spacing elements.

What am I missing?

Title: Bootstrap 5.2 add margin increments

Body:
I have been trying to implement additional spacing increments to Bootstrap, however the SASS map-merge seems to have no impact of the available classes.

I have followed the Boostrap 5.2 documentation on how the $spacers map should be formatted, and I have added a map-merge to my SASS file:

@import "../../src/bootstrap/scss/functions";
@import "../../src/bootstrap/scss/variables";
@import "../../src/bootstrap/scss/mixins";
@import "../../src/bootstrap/scss/_maps.scss";
@import "../../src/bootstrap/scss/_utilities.scss";

$spacer: 1rem;
$custom-spacers: ( 6: $spacer * 4, 7: $spacer * 5, 8: $spacer * 6,);

$spacers: map-merge($spacers, $custom-spacers);

@import "../../src/bootstrap/scss/bootstrap.scss";

I have then been checking the resulting .css file once compiled with gulp and it has no instance of any -6 spacing elements.

What am I missing?


问:
I have problem in dropDownButton in Flutter. Can anyone help me?
here is my code of dropDownButton.I'm trying to making select GenderList dropDownButton but when I assign variable selectedGender to value of dropDownButton it's hide hint text and default select first index value Male.
I want this output

But I'm getting this output when i assign selectedGender variable type int to value in dropDownButton

Here is my code when I comment on the value then it shows a hint text let's see my code below.

```<code>import'package:flutter/material.dart';

class DropDownButton extends StatefulWidget {
  const DropDownButton({Key? key}) : super(key: key);

  @override
  State<DropDownButton> createState() => _DropDownButtonState();
}

class _DropDownButtonState extends State<DropDownButton> {

  List<DropdownMenuItem<int>> genderList=[];

  void loadGenderlist(){
    genderList=[];

    genderList.add(const DropdownMenuItem(
        child: Text('Male'),
        value: 0,));

    genderList.add(const DropdownMenuItem(
      child: Text('Female'),
      value: 1,));

    genderList.add(const DropdownMenuItem(
      child: Text('Other'),
      value: 2,));

  }

  String selectval = "United Kingdom";
  int selectedGender = 0;

  @override
  Widget build(BuildContext context) {
    loadGenderlist();
    return Scaffold(
        appBar: AppBar(
            title: Text("Form Validation with All Controls"),
            backgroundColor: Colors.redAccent
        ),
        body: SafeArea(
          child: ListView(
            children: [
              DecoratedBox(
                decoration: BoxDecoration(
                  color: Colors.green,
                  border: Border.all(color: Colors.black38,width: 3)
                ),
                child: DropdownButton(
                    hint: Text("Select Gender"),
                    items: genderList,
                    //value: selectedGender,
                    onChanged: (value){
                      setState(() {
                        selectedGender =int.parse(value.toString()) ;
                      });
                    },
                  underline: Container(),
                ),
              )
            ],
          ),
        )
    );
  }
}
</code>```

I want this output:

Body:
here is my code of dropDownButton.I'm trying to making select GenderList dropDownButton but when I assign variable selectedGender to value of dropDownButton it's hide hint text and default select first index value Male.
I want this output

But I'm getting this output when i assign selectedGender variable type int to value in dropDownButton

Here is my code when I comment on the value then it shows a hint text let's see my code below.

import'package:flutter/material.dart';

class DropDownButton extends StatefulWidget {
  const DropDownButton({Key? key}) : super(key: key);

  @override
  State<DropDownButton> createState() => _DropDownButtonState();
}

class _DropDownButtonState extends State<DropDownButton> {

  List<DropdownMenuItem<int>> genderList=[];

  void loadGenderlist(){
    genderList=[];

    genderList.add(const DropdownMenuItem(
        child: Text('Male'),
        value: 0,));

    genderList.add(const DropdownMenuItem(
      child: Text('Female'),
      value: 1,));

    genderList.add(const DropdownMenuItem(
      child: Text('Other'),
      value: 2,));

  }

  String selectval = "United Kingdom";
  int selectedGender = 0;

  @override
  Widget build(BuildContext context) {
    loadGenderlist();
    return Scaffold(
        appBar: AppBar(
            title: Text("Form Validation with All Controls"),
            backgroundColor: Colors.redAccent
        ),
        body: SafeArea(
          child: ListView(
            children: [
              DecoratedBox(
                decoration: BoxDecoration(
                  color: Colors.green,
                  border: Border.all(color: Colors.black38,width: 3)
                ),
                child: DropdownButton(
                    hint: Text("Select Gender"),
                    items: genderList,
                    //value: selectedGender,
                    onChanged: (value){
                      setState(() {
                        selectedGender =int.parse(value.toString()) ;
                      });
                    },
                  underline: Container(),
                ),
              )
            ],
          ),
        )
    );
  }
}

I want this output:


问:
I can't do search option in react-select after adding max option for showing in text area

This file is used to select all project options

```<code>import React from "react";
import ReactSelect from "react-select";

const ProjectSelection = props => {
  if (props.allowSelectAll) {
    return (
      <ReactSelect
        {...props}
        options={[props.allOption, ...props.options]}

        onChange={selected => {
          if (
            selected !== null &&
            selected.length > 0 &&
            selected[selected.length - 1].value === props.allOption.value
          ) {
            return props.onChange(props.options);
          }
          return props.onChange(selected);
        }}
      />
    );
  }

  return <ReactSelect {...props} />;
};

export default ProjectSelection

</code>```

Here I have used ProjectSelection component

```<code><ProjectSelection
      value={values.projectsList}
      onChange={(selectedOptions) =>
      setFieldValue("projectsList", selectedOptions || [])}
      options={projectsList}
      isSearchable={true}
      isMulti
      closeMenuOnSelect={true}
      hideSelectedOptions={true}
      components={{ValueContainer}}
      allowSelectAll={true}
/>
</code>```
```<code>const ValueContainer = ({ children, getValue, ...props }) => {
      let maxToShow = 3;
      var length = getValue().length;
      let displayChips = React.Children.toArray(children).slice(0, maxToShow);
      let shouldBadgeShow = length > maxToShow;
      let displayLength = length - maxToShow;

      return (
        <components.ValueContainer {...props}>
          {!props.selectProps.inputValue && displayChips}
          <div>
            {shouldBadgeShow && `+ ${displayLength} item${length != 1 ? "s" : ""} selected`}
          </div>
        </components.ValueContainer>
      );
    };

</code>```

I have added ValueContainer to show max 3 options in the text-area but after adding this, I am unable to perform search option in my dropdown list. please help!!!

Body:
This file is used to select all project options

import React from "react";
import ReactSelect from "react-select";

const ProjectSelection = props => {
  if (props.allowSelectAll) {
    return (
      <ReactSelect
        {...props}
        options={[props.allOption, ...props.options]}

        onChange={selected => {
          if (
            selected !== null &&
            selected.length > 0 &&
            selected[selected.length - 1].value === props.allOption.value
          ) {
            return props.onChange(props.options);
          }
          return props.onChange(selected);
        }}
      />
    );
  }

  return <ReactSelect {...props} />;
};

export default ProjectSelection

Here I have used ProjectSelection component

<ProjectSelection
      value={values.projectsList}
      onChange={(selectedOptions) =>
      setFieldValue("projectsList", selectedOptions || [])}
      options={projectsList}
      isSearchable={true}
      isMulti
      closeMenuOnSelect={true}
      hideSelectedOptions={true}
      components={{ValueContainer}}
      allowSelectAll={true}
/>

const ValueContainer = ({ children, getValue, ...props }) => {
      let maxToShow = 3;
      var length = getValue().length;
      let displayChips = React.Children.toArray(children).slice(0, maxToShow);
      let shouldBadgeShow = length > maxToShow;
      let displayLength = length - maxToShow;

      return (
        <components.ValueContainer {...props}>
          {!props.selectProps.inputValue && displayChips}

            {shouldBadgeShow && `+ ${displayLength} item${length != 1 ? "s" : ""} selected`}

        </components.ValueContainer>
      );
    };

I have added ValueContainer to show max 3 options in the text-area but after adding this, I am unable to perform search option in my dropdown list. please help!!!


问:
Determining number of stalls added by BTB in a processor with 5-stage pipeline and 2-stage BTB for nested loops
[I know that chatgpt isn't allowed, but I've used chat gpt to make the question easier to understand, because it's a complex argument for me but I need to ask it to understand this topic. I double checked the questions multiple times, and I manually edited the question, and therefore I can say it's 100% coherent to what I was asking]

I am trying to solve an exercise that involves a processor with a pipeline of 5 stages and a BTB of 2 stages. The exercise asks me to determine the number of stalls that the BTB will add for control areas, as well as the percentage of stalls that I will need when executing a program with two nested loops. The loops have a certain number of instructions and are executed a certain number of times, and the BTB introduces a certain number of stalls in cases of hit and miss.

I am not sure how to approach this problem, and I would appreciate any help or advice on how to determine the number of stalls and the percentage of stalls needed in this scenario. Thank you in advance for your help. [important note: don't provide me the full solution, because I need to be able to grasp the concept on my own, because I'm still learning this stuff]

this is the full problem I need to solve: "a processor has a pipeline of 5 stages, and a BTB of 2 stages. I need to execute a program with 2 nested loops, loop1, and loop2. loop1 has a number of instructions, N1, equals to 20. loop2 is the external loop with N2=(40 + N1). loop1 is the internal loop, and it's executed L1 = 30 times, and loop2 is exectuted L2 = 100 times. in cases of hit, BTB introduces a number of stalls equal to S1 = 2 if predictions is wrong, and it doesn't introduce any stalls if predictions is right. BTB introduces a number of stalls SM = 3, if I have a compulsory miss, and then it doesn't substitute jumps that the program have to execute. how many stalls does BTB add for control areas? how many stalls (expressed in percentage) do I need?" what is your modus operandi when solving an exercise like this one? moreover, what do you do to visualize the situations described by the problem?


问:
React infinite scroll in an Unsplash image app
I am building an image search app using Unsplash API and trying to implement react infinite scroll (https://www.npmjs.com/package/react-infinite-scroll-component), but it is not working properly.

Now, the search form works fine and it displays 10 images(which is the default number of images using Unsplash API) when you search something,  but when I scroll down to the end of of the page, it only displays the loader (h4 'Loading') but it does not display more images.

App.js

```<code>
import './App.css';
import Main from './components/Main';

function App() {
  return (
    <div className="App">
      <Main />
    </div>
  );
}

export default App;
</code>```

Main.js

```<code>import React from 'react'
import Header from './Header'
import Image from './Image'
import { useState, useEffect } from 'react'
import InfiniteScroll from 'react-infinite-scroll-component';

function Main() {
  const [input, setInput] = useState('')
  const [allImages, setAllImages] = useState([])
  const [favorites, setFavorites] = useState(() => JSON.parse(localStorage.getItem("favorites")) || [])

  useEffect(() => {
    localStorage.setItem("favorites", JSON.stringify(favorites))
    console.log(favorites)
  }, [favorites])

  function handleChange(event) {
    setInput(event.target.value)
  }

  async function fetchImages() {
    try {
      const res = await fetch(`https://api.unsplash.com/search/photos?&query=${input}&client_id=${process.env.REACT_APP_UNSPLASH_API_KEY}`)
      const data = await res.json();
      setAllImages(data.results)
    } catch(error) {
      alert("Sum ting wong");
    }
  }

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchImages()
  }
  console.log(`allImages: ${allImages.length}`);

  // use parameter 'id' to read specific one
  function isLiked(id) {
    return favorites.find(el => el.id === id) ? true : false
  }

  return (
    <main>
      <Header
        input={input}
        handleChange={handleChange}
        handleSubmit={handleSubmit}
      />

      <InfiniteScroll
        dataLength={allImages.length} //This is important field to render the next data
        next={fetchImages}
        hasMore={true}
        loader={<h4>Loading...</h4>}
      >
        <div className='main--image-list mt-5 pb-5'>
          {allImages.map(el => (
            <Image
              key={el.id}
              // do need spread operator below for img's src to work in Image.js
              {...el}
              el={el}
              isLiked={isLiked(el.id)}
              favorites={favorites}
              setFavorites={setFavorites}

            />
          ))}
        </div>
      </InfiniteScroll>
    </main>
  )
}

export default Main
</code>```

for visuals

Body:
I am building an image search app using Unsplash API and trying to implement react infinite scroll (https://www.npmjs.com/package/react-infinite-scroll-component), but it is not working properly.

Now, the search form works fine and it displays 10 images(which is the default number of images using Unsplash API) when you search something,  but when I scroll down to the end of of the page, it only displays the loader (h4 'Loading') but it does not display more images.

App.js

import './App.css';
import Main from './components/Main';

function App() {
  return (

  );
}

export default App;

Main.js

import React from 'react'
import Header from './Header'
import Image from './Image'
import { useState, useEffect } from 'react'
import InfiniteScroll from 'react-infinite-scroll-component';

function Main() {
  const [input, setInput] = useState('')
  const [allImages, setAllImages] = useState([])
  const [favorites, setFavorites] = useState(() => JSON.parse(localStorage.getItem("favorites")) || [])

  useEffect(() => {
    localStorage.setItem("favorites", JSON.stringify(favorites))
    console.log(favorites)
  }, [favorites])

  function handleChange(event) {
    setInput(event.target.value)
  }

  async function fetchImages() {
    try {
      const res = await fetch(`https://api.unsplash.com/search/photos?&query=${input}&client_id=${process.env.REACT_APP_UNSPLASH_API_KEY}`)
      const data = await res.json();
      setAllImages(data.results)
    } catch(error) {
      alert("Sum ting wong");
    }
  }

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchImages()
  }
  console.log(`allImages: ${allImages.length}`);

  // use parameter 'id' to read specific one
  function isLiked(id) {
    return favorites.find(el => el.id === id) ? true : false
  }

  return (

      <InfiniteScroll
        dataLength={allImages.length} //This is important field to render the next data
        next={fetchImages}
        hasMore={true}
        loader={
Loading...
}
      >

          {allImages.map(el => (
            <Image
              key={el.id}
              // do need spread operator below for img's src to work in Image.js
              {...el}
              el={el}
              isLiked={isLiked(el.id)}
              favorites={favorites}
              setFavorites={setFavorites}

            />
          ))}

      </InfiniteScroll>

  )
}

export default Main

for visuals


问:
Fit linear model on all data after doing it just on training data in order to make predictions about future data
In linear regression (but in general on any other model) is there a need to use .fit() on all input data after using it only on training data? I'll try to explain it better with an example. I will artificially create a trivial set of input and output data:

```<code>import numpy as np
from random import uniform
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score

X = np.arange(0, 500, 5).reshape(-1, 1)
y = np.zeros(100)
for i in range(len(X)):
    y[i] = 3 * X[i] + uniform(-10, 10)

X_train = X[:80]
y_train = y[:80]

X_test = X[80:]
y_test = y[80:]

reg = LinearRegression()
</code>```

It could be seen as a time series (X contains the time periods).
Now, I train the model using the training sets:

```<code>reg.fit(X_train, y_train)
</code>```

and I make predictions using the testing set:

```<code>y_pred = reg.predict(X_test)
</code>```

Using r2_score(y_test, y_pred) I get about 0.99, so my model is able to fit the data correctly.

Now my question: I want to make a prediction about the future, i.e. about a series of data not contained in X, let's say:

```<code>X_future = np.arange(500, 525, 5).reshape(-1, 1)
</code>```

Should I proceed this way:

```<code>y_future = reg.predict(X_future)
</code>```

or in this:

```<code>reg.fit(X, y)
y_future = reg.predict(X_future)
</code>```

In other words, do I have to fit again the model found earlier on the entire (X, y) before making a prediction of the future? Are there any chances that both approaches are correct?

Thanks to anyone who will answer me.

Body:
In linear regression (but in general on any other model) is there a need to use .fit() on all input data after using it only on training data? I'll try to explain it better with an example. I will artificially create a trivial set of input and output data:

import numpy as np
from random import uniform
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score

X = np.arange(0, 500, 5).reshape(-1, 1)
y = np.zeros(100)
for i in range(len(X)):
    y[i] = 3 * X[i] + uniform(-10, 10)

X_train = X[:80]
y_train = y[:80]

X_test = X[80:]
y_test = y[80:]

reg = LinearRegression()

It could be seen as a time series (X contains the time periods).
Now, I train the model using the training sets:

reg.fit(X_train, y_train)

and I make predictions using the testing set:

y_pred = reg.predict(X_test)

Using r2_score(y_test, y_pred) I get about 0.99, so my model is able to fit the data correctly.

Now my question: I want to make a prediction about the future, i.e. about a series of data not contained in X, let's say:

X_future = np.arange(500, 525, 5).reshape(-1, 1)

Should I proceed this way:

y_future = reg.predict(X_future)

or in this:

reg.fit(X, y)
y_future = reg.predict(X_future)

In other words, do I have to fit again the model found earlier on the entire (X, y) before making a prediction of the future? Are there any chances that both approaches are correct?

Thanks to anyone who will answer me.


问:
Closing a ADODB.Recordset VBA
I have built this VBA function but I'm getting the below error (see the next screenshot) in the below portion of the code:
Set RstUserAccess.ActiveConnection = Nothing
RstUserAccess.Close

```<code>Public Sub UserLogoutDetail(UserEmail As String)
    Dim MySQL As String
    Dim RstUserAccess As New ADODB.Recordset
    Dim CmdUserAccess  As New ADODB.Command
    Dim i As Integer

    'Setup the command
    Set CmdUserAccess.ActiveConnection = fGetConn
    CmdUserAccess.CommandType = adCmdText
    MySQL = "UPDATE User_Access_TABLE SET EXIT_DATA = #" & Now & "# WHERE (((ID)=" & GetID_ToUpdate(UserEmail) & "))"
    CmdUserAccess.CommandText = MySQL
    RstUserAccess.CursorLocation = adUseClient
    RstUserAccess.CursorType = adOpenDynamic
    RstUserAccess.LockType = adLockOptimistic

    'Open the connection
    RstUserAccess.Open CmdUserAccess
    Set RstUserAccess.ActiveConnection = Nothing
    RstUserAccess.Close

    'Cleanup
    If CBool(CmdUserAccess.State And adStateOpen) = True Then
        Set CmdUserAccess = Nothing
    End If

    If CBool(fGetConn.State And adStateOpen) = True Then
        CloseConn
    End If
 End Sub
</code>```

Error message

Do you have any suggestion?
Thanks

I have tried to change my code many times

Title: Closing a ADODB.Recordset VBA

Body:
I have built this VBA function but I'm getting the below error (see the next screenshot) in the below portion of the code:
Set RstUserAccess.ActiveConnection = Nothing
RstUserAccess.Close

Public Sub UserLogoutDetail(UserEmail As String)
    Dim MySQL As String
    Dim RstUserAccess As New ADODB.Recordset
    Dim CmdUserAccess  As New ADODB.Command
    Dim i As Integer

    'Setup the command
    Set CmdUserAccess.ActiveConnection = fGetConn
    CmdUserAccess.CommandType = adCmdText
    MySQL = "UPDATE User_Access_TABLE SET EXIT_DATA = #" & Now & "# WHERE (((ID)=" & GetID_ToUpdate(UserEmail) & "))"
    CmdUserAccess.CommandText = MySQL
    RstUserAccess.CursorLocation = adUseClient
    RstUserAccess.CursorType = adOpenDynamic
    RstUserAccess.LockType = adLockOptimistic

    'Open the connection
    RstUserAccess.Open CmdUserAccess
    Set RstUserAccess.ActiveConnection = Nothing
    RstUserAccess.Close

    'Cleanup
    If CBool(CmdUserAccess.State And adStateOpen) = True Then
        Set CmdUserAccess = Nothing
    End If

    If CBool(fGetConn.State And adStateOpen) = True Then
        CloseConn
    End If
 End Sub

Error message

Do you have any suggestion?
Thanks

I have tried to change my code many times


问:
How to solve problem about [Errno 11] unable to lock file?
I want to run solo (https://doi.org/10.1016/j.cels.2020.05.010.) to detect doublets in the scRNAseq dataset, but when I run this, it jumps a BlockIOError to me, like the picture.

I googled this problem and tried upgrading h5py, numpy and ipython, but it doesn't work. I also tried modifying the ~/.bashrc, but it can't execute because my server is public and it doesn't support this. The reboot didn't seem to work either. What can I do to solve this? QAQ


问:
Spring boot create HTTPS endpoints
I have a Spring Boot application which uses SAML for authorization. The Application runs behind a reverse proxy, which terminates the SSL and redirects to the application at localhost:8080 (https://application.com -> http://localhost:808)

I use OpenSamlMetadataResolver to create the SP Metadata for the IDP.
But the generated endpoints in the resulting metadata-file will not contain the https scheme. Therefore the IDP can't validate the ACS and other endpoints.

Is there a way to force Endpoints use HTTPS scheme?

Title: Spring boot create HTTPS endpoints


问:
pyspark - Check if shuffle caused when joining 2 DFs repartitioned on same column

Spark Version: 2.4.7

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1) is set

I have two pyspark dataframes which I want to co-partition and hence avoid shuffling. I tried to
repartition them, giving same number of partitions and same column for repartitioning, and wrote as
parquet files. Now I'm trying to check if a shuffle is actually happenning or not when I subsequently
use these tables.

Stats on initial dataframes

>>> initital_df1.count(), initial_df1.select('id').distinct().count()  # distinct rows per id
(1000, 1000)
>>> initital_df2.count(), initial_df2.select('id').distinct().count()  # 300 rows per id (25 yrs of data, 1 row for each month)
(300000, 1000)
>>> initial_df1.rdd.getNumPartitions(), initial_df2.rdd.getNumPartitions()
(2, 8)
>>> initial_df1.rdd.glom().map(len).collect()
[500, 500]
>>> initial_df2.rdd.glom().map(len).collect()
[56400, 50700, 45000, 40800, 36300, 30000, 25200, 15600]
```
<p><strong>Step 1: repartition the initital dataframes with same number of partitions and same partitioner column</strong></p>
<pre class="lang-py prettyprint-override"><code>>>> initial_df1.repartition(4, 'id').write.parquet(df1_write_path)
>>> initial_df2.repartition(4, 'id').write.parquet(df2_write_path)
</code>```

Step 2: read the previously repartitioned dataframes at a later point of time to perform some computation

>>> repartitioned_df1 = spark.read.parquet(df1_write_path)
>>> repartitioned_df2 = spark.read.parquet(df2_write_path)
```
<p><strong>Stats on repartitioned dataframes</strong></p>
<pre class="lang-py prettyprint-override"><code>
>>> repartitioned_df1.rdd.getNumPartitions(), repartitioned_df2.rdd.getNumPartitions()
(4, 4)
>>> initial_df1.rdd.glom().map(len).collect()
[279, 255, 238, 228]
>>> initial_df2.rdd.glom().map(len).collect()
[83700, 76500, 71400, 68400]
</code>```

Step 3: join the repartitioned dataframes read above to perform aggregations and write the aggregated dataframe

>>> agg_df = repartitioned_df1.join(repartitioned_df2, 'id').groupBy('id').agg(F.sum(col1_df1), F.avg(col1_df2))
>>> agg_df.write.parquet(agg_df_write_path)
```

Tested two scenarios:

repartitioned_df1 and repartitioned_df2 are used in step (3)

initial_df1 and initial_df2 are used in step (3)

Observarions:

agg_df.explain() gives the same spark plan in both the cases

Shuffle read and write data in SparkUI shows the same set of values for both cases

scenario (1) is at least 2x faster than scenario (2)

Question: How do I check if a shuffle is being caused (i.e. the dataframes are hash partitioned again) or the initial repartitioning caused the two dataframes to be co-partitioned and hence there would just be movement of partitions already created during initial writing step?

Body:
Spark Version: 2.4.7

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1) is set

I have two pyspark dataframes which I want to co-partition and hence avoid shuffling. I tried to
repartition them, giving same number of partitions and same column for repartitioning, and wrote as
parquet files. Now I'm trying to check if a shuffle is actually happenning or not when I subsequently
use these tables.

Stats on initial dataframes

>>> initital_df1.count(), initial_df1.select('id').distinct().count()  # distinct rows per id
(1000, 1000)
>>> initital_df2.count(), initial_df2.select('id').distinct().count()  # 300 rows per id (25 yrs of data, 1 row for each month)
(300000, 1000)
>>> initial_df1.rdd.getNumPartitions(), initial_df2.rdd.getNumPartitions()
(2, 8)
>>> initial_df1.rdd.glom().map(len).collect()
[500, 500]
>>> initial_df2.rdd.glom().map(len).collect()
[56400, 50700, 45000, 40800, 36300, 30000, 25200, 15600]

Step 1: repartition the initital dataframes with same number of partitions and same partitioner column

>>> initial_df1.repartition(4, 'id').write.parquet(df1_write_path)
>>> initial_df2.repartition(4, 'id').write.parquet(df2_write_path)

Step 2: read the previously repartitioned dataframes at a later point of time to perform some computation

>>> repartitioned_df1 = spark.read.parquet(df1_write_path)
>>> repartitioned_df2 = spark.read.parquet(df2_write_path)

Stats on repartitioned dataframes

>>> repartitioned_df1.rdd.getNumPartitions(), repartitioned_df2.rdd.getNumPartitions()
(4, 4)
>>> initial_df1.rdd.glom().map(len).collect()
[279, 255, 238, 228]
>>> initial_df2.rdd.glom().map(len).collect()
[83700, 76500, 71400, 68400]

Step 3: join the repartitioned dataframes read above to perform aggregations and write the aggregated dataframe

>>> agg_df = repartitioned_df1.join(repartitioned_df2, 'id').groupBy('id').agg(F.sum(col1_df1), F.avg(col1_df2))
>>> agg_df.write.parquet(agg_df_write_path)

Tested two scenarios:

repartitioned_df1 and repartitioned_df2 are used in step (3)

initial_df1 and initial_df2 are used in step (3)

Observarions:

agg_df.explain() gives the same spark plan in both the cases

Shuffle read and write data in SparkUI shows the same set of values for both cases

scenario (1) is at least 2x faster than scenario (2)

Question: How do I check if a shuffle is being caused (i.e. the dataframes are hash partitioned again) or the initial repartitioning caused the two dataframes to be co-partitioned and hence there would just be movement of partitions already created during initial writing step?


问:
RTK Query polling only fixed number of times
I'm trying to implement a polling with redux toolkit RTK Query.
My need is to execute the polling only a fixed number of times (this number of times comes from a preloaded configuration).
The process for the polling itself it's pretty simple and following the documentation I see that it is sufficient to add the options pollingInterval in the hook, but I don't understand how I can achive my need to execute the polling only a fixed number of times.

Here my service

service.ts

```<code>export const landingPageApi = createApi({
    reducerPath: 'landingPageApi',
    baseQuery: dynamicBaseQuery,
    endpoints: (builder) => ({
        ...,
        deepCheck: builder.query<HttpResponse<PaymentTransactionResponse>, { paymentId: string; deepCheck: boolean }>({
            query: ({ paymentId, deepCheck }) => `some-url`,
            async onQueryStarted(queryArg, { dispatch, queryFulfilled }) {
                const { data } = await queryFulfilled
                const { payload } = data
                dispatch(updateTransactions(data.payload.transactionList ?? []))
            },
        })
    }),
})
</code>```

and in my React component I use the auto-created hook useDeepCheckQuery and I try to execute the polling in this manner

Component.tsx

```<code>export function TransactionDetail(props: Props) {
    let pollingCount = 0;
    // some code ...
    const {} = useDeepCheckQuery(
         {
             paymentId: props.paymentId,
             deepCheck: pollingCount++ === 3,
         },
         {
             skip: pollingCount++ > 3 && !['PMT_IN_PRGS', 'PAYMENT_STARTED'].includes(props.transaction.status),
             pollingInterval: 3000,
         },
     )
</code>```

but it doesn't work.

For example if the fixed number of times is 3, I need to execute the API call 3 times with the first 2 with the property deepCheck=false and the last call with the property deepCheck=true. In general I need that only the last call has the property deepCheck setted to true

Body:
I'm trying to implement a polling with redux toolkit RTK Query.
My need is to execute the polling only a fixed number of times (this number of times comes from a preloaded configuration).
The process for the polling itself it's pretty simple and following the documentation I see that it is sufficient to add the options pollingInterval in the hook, but I don't understand how I can achive my need to execute the polling only a fixed number of times.

Here my service

service.ts

export const landingPageApi = createApi({
    reducerPath: 'landingPageApi',
    baseQuery: dynamicBaseQuery,
    endpoints: (builder) => ({
        ...,
        deepCheck: builder.query<HttpResponse<PaymentTransactionResponse>, { paymentId: string; deepCheck: boolean }>({
            query: ({ paymentId, deepCheck }) => `some-url`,
            async onQueryStarted(queryArg, { dispatch, queryFulfilled }) {
                const { data } = await queryFulfilled
                const { payload } = data
                dispatch(updateTransactions(data.payload.transactionList ?? []))
            },
        })
    }),
})

and in my React component I use the auto-created hook useDeepCheckQuery and I try to execute the polling in this manner

Component.tsx

export function TransactionDetail(props: Props) {
    let pollingCount = 0;
    // some code ...
    const {} = useDeepCheckQuery(
         {
             paymentId: props.paymentId,
             deepCheck: pollingCount++ === 3,
         },
         {
             skip: pollingCount++ > 3 && !['PMT_IN_PRGS', 'PAYMENT_STARTED'].includes(props.transaction.status),
             pollingInterval: 3000,
         },
     )

but it doesn't work.

For example if the fixed number of times is 3, I need to execute the API call 3 times with the first 2 with the property deepCheck=false and the last call with the property deepCheck=true. In general I need that only the last call has the property deepCheck setted to true


问:
Bitbucket (server API) treats new files as renamed/copied old ones. Is there a way to prevent this?
The problem:

I'm using bitbucket stash (server) API in a script for my project with the {path} api method:
/rest/api/1.0/projects/{projectKey}/repos/{repositorySlug}/browse/{path:.*}

The idea was to save versions of config files in a repository (version01-versionXX for every config). But those configs have the same structure with different names and parameters,
so when I push a new config with a commit message like 'version01' without specifying any sourceCommitId, bitbucket automatically adds a parent commit from the last file with the same structure (if it exists). As a result, in this new file's history I'm getting several 'version01' commits, which is not what I was intended to have.

What I've tried:

If I do specify sourceCommitId as the initial or the last commit on the branch, I get an error message since the file doesn't exist on this commit.

I've tried to experiment with empty sourceBranch parameter, but still some parent commit appears.
The only idea I came up with is to create a new branch for every config, but this seems like overkill to me.

All attempts to find a method for editing file commit history via API also failed.

At the moment as a work around I create every config file with its name as the only line of its content and then change it to the structure I need. This works so far, but doesn't look like a good solution to me and requires 2 API requests instead of one.
Is there a better way to prevent BitBucket from treating those new files as copies of old ones?


问:
AnyLogic - How to define and redefine Agent's Parameters?
We’re generating the data that we might get from a shop floor to run, test, and validate our machine learning models. We first have here a discrete event simulation model for our manufacturing system. Each production order is seen as an agent, which then goes through different processes with a queue (waiting time) and delays (firstly production time, secondly logistics time).

enter image description here

But sometimes we have one process, for example, printing (code 5A, after the second Select5Output), with three different machines, which do not have a particular capacity. It’s time when we divide our order into parts and send them to those machines (very randomly, subjectively).
The data we take is from flowchart_process_states_log in Database.

The data we take is from flowchart_process_states_log in Database.
My questions here are:

How can we define the number of products in each order? Ex. we’re printing card, for one order it may be 10k, for another 8k or 33k. Can we define it as agent’s parameter? Then how can we vary them (stochastically, no exact number needed).

How can we split those 10k cards into three different machines? And then how to get back an complete agent with 10k? The Agent ID should remain the same as we trace and analyse them in ML model. Is it reasonable to see an order as an agent?

How can we multiply the number of our agent after a process? Ex. After cutting 10k pieces we have 20k.

We have the distribution for delay ex. triangle distribution. But we want some disturbances, when it suddenly takes 2 days for that delay instead of 3-4 hours as normal. How to do it?

Thank you in advance for your effort. Every help is highly appreciated, because we're here and learning together. Thank you !!


问:
Kubernetes cronjob doesn't use env variables
I have a Cron job in Kubernetes that does not use the urls in env variables to go to another api's find information to use in him, returning errors like will be using the urls of the appsettings/launchsettings from the console application project.

When I executed the cronjob, it returned an error ex: "Connection refused (20.210.70.20:80)"

My Cron job:

`

```<code>apiVersion: batch/v1
kind: CronJob
metadata:
  name: productintegration-cronjob
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: Never
          containers:
          - name: productintegration-cronjob
            image: reconhece.azurecr.io/ms-product-integration:9399
            command:
            - /bin/sh
            - -c
            - echo dotnet - $(which dotnet);
              echo Running Product Integration;
              /usr/bin/dotnet /app/MsProductIntegration.dll
            env:
            - name: DatabaseProducts
              value: "http://catalog-api:8097/api/Product/hash/{0}/{1}"
            - name: DatabaseCategory
              value: "http://catalog-api:8097/api/Category"
</code>```

`

My catalogApi deployment where my cron job needs to go:

`

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: catalog-api-deployment
  labels:
    app: catalog-api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: catalog-api
  template:
    metadata:
      labels:
        app: catalog-api
    spec:
      containers:
        - name: catalog-api
          image: test.azurecr.io/ms-catalog-api:6973
          ports:
            - containerPort: 80
          env:
          - name: DatabaseSettings__ConnectionString
            value: "String Connection" - I removed
          - name: DatabaseSettings__DatabaseName
            value: "DbCatalog"
</code>```

``

The minikube works fine.

How do I fix this error ?

I already changed the port from my catalogApi but without success.

I tried changing the name of the env variable but without success too.

Body:
I have a Cron job in Kubernetes that does not use the urls in env variables to go to another api's find information to use in him, returning errors like will be using the urls of the appsettings/launchsettings from the console application project.

When I executed the cronjob, it returned an error ex: "Connection refused (20.210.70.20:80)"

My Cron job:

`

apiVersion: batch/v1
kind: CronJob
metadata:
  name: productintegration-cronjob
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: Never
          containers:
          - name: productintegration-cronjob
            image: reconhece.azurecr.io/ms-product-integration:9399
            command:
            - /bin/sh
            - -c
            - echo dotnet - $(which dotnet);
              echo Running Product Integration;
              /usr/bin/dotnet /app/MsProductIntegration.dll
            env:
            - name: DatabaseProducts
              value: "http://catalog-api:8097/api/Product/hash/{0}/{1}"
            - name: DatabaseCategory
              value: "http://catalog-api:8097/api/Category"

`

My catalogApi deployment where my cron job needs to go:

`

apiVersion: apps/v1
kind: Deployment
metadata:
  name: catalog-api-deployment
  labels:
    app: catalog-api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: catalog-api
  template:
    metadata:
      labels:
        app: catalog-api
    spec:
      containers:
        - name: catalog-api
          image: test.azurecr.io/ms-catalog-api:6973
          ports:
            - containerPort: 80
          env:
          - name: DatabaseSettings__ConnectionString
            value: "String Connection" - I removed
          - name: DatabaseSettings__DatabaseName
            value: "DbCatalog"

``

The minikube works fine.

How do I fix this error ?

I already changed the port from my catalogApi but without success.

I tried changing the name of the env variable but without success too.


问:
Create object from multiple object with same value in map JS
Hello i'm in a JS map from a api response.
i have multiple object like this :

```<code>{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type3', label: 'Foodies'}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type4', label: 'Grand air & Nature'}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type3', label: 'Foodies'}
</code>```

And i need a simple object like this for build a select :

```<code>const arr = {
    type1 : 'Pieds dans l\'eau',
    type2 : 'Patrimoine & Culture',
    type3 : 'Foodies',
    type4 : 'Grand air & Nature',
};
</code>```

many thank for you help !

Body:
Hello i'm in a JS map from a api response.
i have multiple object like this :

{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type3', label: 'Foodies'}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type4', label: 'Grand air & Nature'}
{value: 'type1', label: "Pieds dans l'eau"}
{value: 'type2', label: 'Patrimoine & Culture'}
{value: 'type3', label: 'Foodies'}

And i need a simple object like this for build a select :

const arr = {
    type1 : 'Pieds dans l\'eau',
    type2 : 'Patrimoine & Culture',
    type3 : 'Foodies',
    type4 : 'Grand air & Nature',
};

many thank for you help !


问:
dynamic styles for Table rows antd
I put rowClassName,

```<code>rowClassName={({ expanded }) => (expanded ? 'blue' : 'red')}
</code>```
```<code>.blue {
  background-color: blue;
}

.red {
  background-color: red;
}
</code>```

which should check if the row is expanded (similar to icon icon). However, the style is not dynamic and is only applied once.

Here is the complete code snippet of the table:

```<code>    <Table
      columns={columns}
      rowClassName={({ expanded }) => (expanded ? 'blue' : 'red')}
      expandable={{
        expandedRowRender,
        rowExpandable: (record) => record.name !== 'Not Expandable',
        expandIcon: ({ expanded, onExpand, record }) =>
          expanded ? (
            <DownOutlined style={{ color: '#BAB3BC' }} onClick={(e) => onExpand(record, e)} />
          ) : (
            <RightOutlined style={{ color: '#BAB3BC' }} onClick={(e) => onExpand(record, e)} />
          ),
      }}
      dataSource={data}
    />

</code>```

The result:

Title: dynamic styles for Table rows antd

Body:
I put rowClassName,

rowClassName={({ expanded }) => (expanded ? 'blue' : 'red')}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

which should check if the row is expanded (similar to icon icon). However, the style is not dynamic and is only applied once.

Here is the complete code snippet of the table:

 (expanded ? 'blue' : 'red')}
      expandable={{
        expandedRowRender,
        rowExpandable: (record) => record.name !== 'Not Expandable',
        expandIcon: ({ expanded, onExpand, record }) =>
          expanded ? (
            <DownOutlined style={{ color: '#BAB3BC' }} onClick={(e) => onExpand(record, e)} />
          ) : (
            <RightOutlined style={{ color: '#BAB3BC' }} onClick={(e) => onExpand(record, e)} />
          ),
      }}
      dataSource={data}
    />

The result:


问:
Debian rockpi apt update errors
I'm using debian image from radxa web-site on my rockpi m4a. But when i try to execute sudo apt update I get:

```<code>Get:1 http://httpredir.debian.org/debian bullseye InRelease [2682 B]
Get:2 http://httpredir.debian.org/debian bullseye-updates InRelease [2682 B]
Get:3 http://httpredir.debian.org/debian bullseye-backports InRelease [2682 B]
Get:4 http://security.debian.org/debian-security bullseye-security InRelease [2682 B]
Get:5 http://apt.radxa.com/bullseye bullseye-stable InRelease [2682 B]
Err:1 http://httpredir.debian.org/debian bullseye InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:2 http://httpredir.debian.org/debian bullseye-updates InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:3 http://httpredir.debian.org/debian bullseye-backports InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:4 http://security.debian.org/debian-security bullseye-security InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:5 http://apt.radxa.com/bullseye bullseye-stable InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Reading package lists... Done
N: See apt-secure(8) manpage for repository creation and user configuration details.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
E: The repository 'http://httpredir.debian.org/debian bullseye InRelease' is no longer signed.
E: Failed to fetch http://httpredir.debian.org/debian/dists/bullseye/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
N: See apt-secure(8) manpage for repository creation and user configuration details.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
E: The repository 'http://httpredir.debian.org/debian bullseye-updates InRelease' is no longer signed.
E: Failed to fetch http://httpredir.debian.org/debian/dists/bullseye-updates/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
N: See apt-secure(8) manpage for repository creation and user configuration details.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
E: The repository 'http://httpredir.debian.org/debian bullseye-backports InRelease' is no longer signed.
E: Failed to fetch http://httpredir.debian.org/debian/dists/bullseye-backports/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
E: Failed to fetch http://security.debian.org/debian-security/dists/bullseye-security/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
E: The repository 'http://security.debian.org/debian-security bullseye-security InRelease' is no longer signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://apt.radxa.com/bullseye/dists/bullseye-stable/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
E: The repository 'http://apt.radxa.com/bullseye bullseye-stable InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
</code>```

I tried to do wget -O - apt.radxa.com/bullseye-stable/public.key | sudo apt-key add -
But it doesn't work. it gives gpg: no valid OpenPGP data found.

I tried to do sudo apt update --allow-insecure-repositories but got same errors.

What can I do? Thanks in advance.

Title: Debian rockpi apt update errors

Body:
I'm using debian image from radxa web-site on my rockpi m4a. But when i try to execute sudo apt update I get:

Get:1 http://httpredir.debian.org/debian bullseye InRelease [2682 B]
Get:2 http://httpredir.debian.org/debian bullseye-updates InRelease [2682 B]
Get:3 http://httpredir.debian.org/debian bullseye-backports InRelease [2682 B]
Get:4 http://security.debian.org/debian-security bullseye-security InRelease [2682 B]
Get:5 http://apt.radxa.com/bullseye bullseye-stable InRelease [2682 B]
Err:1 http://httpredir.debian.org/debian bullseye InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:2 http://httpredir.debian.org/debian bullseye-updates InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:3 http://httpredir.debian.org/debian bullseye-backports InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:4 http://security.debian.org/debian-security bullseye-security InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Err:5 http://apt.radxa.com/bullseye bullseye-stable InRelease
  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
Reading package lists... Done
N: See apt-secure(8) manpage for repository creation and user configuration details.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
E: The repository 'http://httpredir.debian.org/debian bullseye InRelease' is no longer signed.
E: Failed to fetch http://httpredir.debian.org/debian/dists/bullseye/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
N: See apt-secure(8) manpage for repository creation and user configuration details.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
E: The repository 'http://httpredir.debian.org/debian bullseye-updates InRelease' is no longer signed.
E: Failed to fetch http://httpredir.debian.org/debian/dists/bullseye-updates/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
N: See apt-secure(8) manpage for repository creation and user configuration details.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
E: The repository 'http://httpredir.debian.org/debian bullseye-backports InRelease' is no longer signed.
E: Failed to fetch http://httpredir.debian.org/debian/dists/bullseye-backports/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
E: Failed to fetch http://security.debian.org/debian-security/dists/bullseye-security/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
E: The repository 'http://security.debian.org/debian-security bullseye-security InRelease' is no longer signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://apt.radxa.com/bullseye/dists/bullseye-stable/InRelease  Clearsigned file isn't valid, got 'NOSPLIT' (does the network require authentication?)
E: The repository 'http://apt.radxa.com/bullseye bullseye-stable InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

I tried to do wget -O - apt.radxa.com/bullseye-stable/public.key | sudo apt-key add -
But it doesn't work. it gives gpg: no valid OpenPGP data found.

I tried to do sudo apt update --allow-insecure-repositories but got same errors.

What can I do? Thanks in advance.


问:
Multi-Script progress bar for Python
I would like to implement a status bar that gives the user feedback of the status of the script. I have build a script that will loop through a video directory and for every video that it detects it runs a process against it. While the initial code does work, the issue I am having is that when the code finishes using a trained tensorflow model, it fails to release the gpu memory reserved for the process. My solution to this is to run a separate script that has values passed through to it from the initial script. Any help would be appreciated.

Here is the code I referenced for building a multi-status bar output:
`

```<code>import multiprocessing
import random
from concurrent.futures import ProcessPoolExecutor
from time import sleep

#from rich import progress
from rich.progress import Progress

def long_running_fn(progress, task_id):
    len_of_task = random.randint(3, 20)  # take some random length of time
    for n in range(0, len_of_task):
        sleep(1)  # sleep for a bit to simulate work
        progress[task_id] = {"progress": n + 1, "total": len_of_task}

if __name__ == "__main__":
    n_workers = 8  # set this to the number of cores you have on your machine

    with Progress() as progress:
        futures = []  # keep track of the jobs
        with multiprocessing.Manager() as manager:
            # this is the key - we share some state between our
            # main process and our worker functions
            _progress = manager.dict()
            overall_progress_task = progress.add_task("[green]All jobs progress:")

            with ProcessPoolExecutor(max_workers=n_workers) as executor:
                for n in range(0, 20):  # iterate over the jobs we need to run
                    # set visible false so we don't have a lot of bars all at once:
                    task_id = progress.add_task(f"task {n}", visible=False)
                    futures.append(executor.submit(long_running_fn, _progress, task_id))

                # monitor the progress:
                while (n_finished := sum([future.done() for future in futures])) < len(
                    futures
                ):
                    progress.update(
                        overall_progress_task, completed=n_finished, total=len(futures)
                    )
                    for task_id, update_data in _progress.items():
                        latest = update_data["progress"]
                        total = update_data["total"]
                        # update the progress bar for this task:
                        progress.update(
                            task_id,
                            completed=latest,
                            total=total,
                            visible=latest < total,
                        )

                # raise any errors:
                for future in futures:
                    future.result()
</code>```

`
Which gives a result that look like this:
progress bars

In implementing this into my code, the progress bars work, but only until the gpu memory fills up than I am unable to keep the code running. If I run a two script variant without a progress bar everything works perfectly.

Here is the code that I currently have. I apologize in advance its a WIP.

`

```<code>
def detect_frames(progress, task_id, gpu, filename, xl, size):
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) #"1"

    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
      for gpu in gpus:
          try:
              tf.config.experimental.set_virtual_device_configuration(gpu,
                [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*size)]) #1024 #starts mem limit at 1Gig, 5715 is for the R720
          except RuntimeError as e:
            print(e)
model = tensorflow.keras.models.load_model('SQ-D4096-V7.h5', compile=False)

    labels = ['Corrupt','Good'] #needs to be in same order as text file
    start_time = time.time()
    f3 = 0
    T = 0 #time
    T2 = 0 #time2 for testing
    cap = cv.VideoCapture(filename)
    fps = cap.get(cv.CAP_PROP_FPS)
    totalNoFrames = cap.get(cv.CAP_PROP_FRAME_COUNT)#/30
    durationInSeconds = (totalNoFrames / fps)/fps
    good = []
    corrupt = []
    bad = []
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        count += 120
        cap.set(cv.CAP_PROP_POS_FRAMES, count)
        fnum = cap.get(cv.CAP_PROP_POS_FRAMES);
        progress[task_id] = {"progress": fnum, "total": totalNoFrames}

rest of def ....

if __name__ == "__main__":

    CWD = os.path.dirname(os.path.realpath(__file__))
    nvidia_smi.nvmlInit()

    try:
        deviceCount = nvmlDeviceGetCount()
        for i in range(deviceCount):
            #gpus = len(i)
            #print("Num GPU: ",gpus)
            handle = nvmlDeviceGetHandleByIndex(i)
            info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)
            card = nvmlDeviceGetName(handle)
            print("Device", i, ":", nvmlDeviceGetName(handle))
            print("Total memory: %sGB" %(info.total//(1.024*10**9)))
            print("Free memory: %sGB" %(info.free//(1.024*10**9)))
            print("Used memory: %sGB" %(info.used//(1.024*10**9)))
            Num = (info.free//(1.024*10**9))-1
            print("Max number of scripts at once: ",Num)
            #print("Recommended Max number of scripts at once, per GPU: ",Num-1)
    except NVMLError as error:
        print(error)

    numgpu = deviceCount

    nvidia_smi.nvmlShutdown()

    # Input area
#%%
    #Where are the videos located?
    #file = glob.glob("/Data/2_DeInter/*.avi") #for production
    file = glob.glob("/Data/2_DeInter/Untitled_5.avi") #for Testing
    #file = sys.argv[1]
    #print(file)
    #How many videos do you want to process per GPU?
    #Num = 12
    NumProc = 1
    #nvidia_smi.nvmlInit()
    if (str(card) == "b'NVIDIA GeForce GTX 1050 Ti'") and (NumProc > 2 ):
        print("Unfortunately the 1050 Ti can only process two streams per card:")
        print("Changing number of processes to 2!")
        NumProc = 2
    #if NumProc == 1:
    #    MemFree = ((Num//NumProc)-1)
    #else:
    #    MemFree = (Num//NumProc)
    print("NumProc: ",NumProc)
    MemFree = 1/((Num*1.2)/NumProc)
    print("Memory free:",MemFree)
    size = (Num/NumProc)#MemFree #2 #1.2 #size of the tensorflow model
    print('Memory size Used: ',size)
    #print(size)
    print("\n")
    n_workers = NumProc#*numgpu #2
   #%%
    gpu = 0
    x = 0
    T = 0
    nvidia_smi.nvmlInit()

    with Progress() as progress:
        futures = []  # keep track of the jobs
        # with multiprocessing.Manager() as manager:
        #     # this is the key - we share some state between our
        #     # main process and our worker functions
        #     _progress = manager.dict()
        #     overall_progress_task = progress.add_task("[green]All jobs progress:")
        with multiprocessing.Manager() as manager:
            # this is the key - we share some state between our
            # main process and our worker functions
            _progress = manager.dict()
            overall_progress_task = progress.add_task("[green]All jobs progress:")

            #for n in range(len(file)):
            with ProcessPoolExecutor(max_workers=n_workers) as executor:
                #with ProcessPoolExecutor(max_workers=n_workers) as executor:
                while True:
                #for n in range(len(file)):
                    #task_id = progress.add_task(f"task {x}", visible=False)
                    task_id = progress.add_task(f"Processing video: {Path(file[x]).name}", visible=False)

                    #print("X: %s"%x)
                    #while True:
                    #for gpu in range(deviceCount):
                        #print("GPU: ",gpu)
                    print("X:",x)
                    # if x > NumProc: #clear the tf models
                    #     tf.keras.backend.clear_session()
                    #     tf.compat.v1.reset_default_graph()
                    #     del model
                    #     load.model()
                        #print("Mem Free: ",info.free//(size*10**9)-1)
                        #with Progress() as progress:
                        #    futures = []
                    while info.free/(size*10**9) <= MemFree:
                         #print("Mem Free: ",info.free/(1.024*10**9))
                         #print("Mem Free: ",info.free/(size*10**9))
                         #print("No Free Memory!")

                         #print("Checking GPU: %s for space"%gpu)
                         #print("Update Progress Bar")
                         if (n_finished := sum([future.done() for future in futures])) < len(futures):
                             progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                             for task_id, update_data in _progress.items():
                                 latest = update_data["progress"]
                                 total = update_data["total"]
                                 # update the progress bar for this task:
                                 progress.update(task_id,completed=latest,total=total,visible=latest < total,)
                         time.sleep(1)
                         gpu = gpu+1
                         if gpu == deviceCount:
                             gpu = 0
                         handle = nvmlDeviceGetHandleByIndex(gpu)
                         info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)

                    if info.free/(size*10**9) > MemFree:
                        tf.config.experimental.set_virtual_device_configuration(gpu,

                        futures.append(executor.submit(detect_frames, _progress, task_id, gpu, file[x], x, size))

                        if (n_finished := sum([future.done() for future in futures])) < len(futures):
                            progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                            for task_id, update_data in _progress.items():
                                latest = update_data["progress"]
                                total = update_data["total"]
                                # update the progress bar for this task:
                                progress.update(task_id,completed=latest,total=total,visible=latest < total,)
                        time.sleep(5)

                    #print("Update Progress Bar")
                    if (n_finished := sum([future.done() for future in futures])) < len(futures):
                        progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                        for task_id, update_data in _progress.items():
                            latest = update_data["progress"]
                            total = update_data["total"]
                            # update the progress bar for this task:
                            progress.update(task_id,completed=latest,total=total,visible=latest < total,)

                    x = x+1
                    gpu = gpu+1
                    if gpu == deviceCount:
                        gpu = 0
                       #break
                    if x == len(file):
                        print("End of file list")
                        #print("Update Progress Bar")
                        while (n_finished := sum([future.done() for future in futures])) < len(futures):
                            progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                            for task_id, update_data in _progress.items():
                                latest = update_data["progress"]
                                total = update_data["total"]
                                # update the progress bar for this task:
                                progress.update(task_id,completed=latest,total=total,visible=latest < total,)
                        break
                    handle = nvmlDeviceGetHandleByIndex(gpu)
                    info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)

    nvidia_smi.nvmlShutdown()
</code>```

`

Title: Multi-Script progress bar for Python

Body:
I would like to implement a status bar that gives the user feedback of the status of the script. I have build a script that will loop through a video directory and for every video that it detects it runs a process against it. While the initial code does work, the issue I am having is that when the code finishes using a trained tensorflow model, it fails to release the gpu memory reserved for the process. My solution to this is to run a separate script that has values passed through to it from the initial script. Any help would be appreciated.

Here is the code I referenced for building a multi-status bar output:
`

import multiprocessing
import random
from concurrent.futures import ProcessPoolExecutor
from time import sleep

#from rich import progress
from rich.progress import Progress

def long_running_fn(progress, task_id):
    len_of_task = random.randint(3, 20)  # take some random length of time
    for n in range(0, len_of_task):
        sleep(1)  # sleep for a bit to simulate work
        progress[task_id] = {"progress": n + 1, "total": len_of_task}

if __name__ == "__main__":
    n_workers = 8  # set this to the number of cores you have on your machine

    with Progress() as progress:
        futures = []  # keep track of the jobs
        with multiprocessing.Manager() as manager:
            # this is the key - we share some state between our
            # main process and our worker functions
            _progress = manager.dict()
            overall_progress_task = progress.add_task("[green]All jobs progress:")

            with ProcessPoolExecutor(max_workers=n_workers) as executor:
                for n in range(0, 20):  # iterate over the jobs we need to run
                    # set visible false so we don't have a lot of bars all at once:
                    task_id = progress.add_task(f"task {n}", visible=False)
                    futures.append(executor.submit(long_running_fn, _progress, task_id))

                # monitor the progress:
                while (n_finished := sum([future.done() for future in futures])) < len(
                    futures
                ):
                    progress.update(
                        overall_progress_task, completed=n_finished, total=len(futures)
                    )
                    for task_id, update_data in _progress.items():
                        latest = update_data["progress"]
                        total = update_data["total"]
                        # update the progress bar for this task:
                        progress.update(
                            task_id,
                            completed=latest,
                            total=total,
                            visible=latest < total,
                        )

                # raise any errors:
                for future in futures:
                    future.result()

`
Which gives a result that look like this:
progress bars

In implementing this into my code, the progress bars work, but only until the gpu memory fills up than I am unable to keep the code running. If I run a two script variant without a progress bar everything works perfectly.

Here is the code that I currently have. I apologize in advance its a WIP.

`

def detect_frames(progress, task_id, gpu, filename, xl, size):
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) #"1"

    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
      for gpu in gpus:
          try:
              tf.config.experimental.set_virtual_device_configuration(gpu,
                [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*size)]) #1024 #starts mem limit at 1Gig, 5715 is for the R720
          except RuntimeError as e:
            print(e)
model = tensorflow.keras.models.load_model('SQ-D4096-V7.h5', compile=False)

    labels = ['Corrupt','Good'] #needs to be in same order as text file
    start_time = time.time()
    f3 = 0
    T = 0 #time
    T2 = 0 #time2 for testing
    cap = cv.VideoCapture(filename)
    fps = cap.get(cv.CAP_PROP_FPS)
    totalNoFrames = cap.get(cv.CAP_PROP_FRAME_COUNT)#/30
    durationInSeconds = (totalNoFrames / fps)/fps
    good = []
    corrupt = []
    bad = []
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        count += 120
        cap.set(cv.CAP_PROP_POS_FRAMES, count)
        fnum = cap.get(cv.CAP_PROP_POS_FRAMES);
        progress[task_id] = {"progress": fnum, "total": totalNoFrames}

rest of def ....

if __name__ == "__main__":

    CWD = os.path.dirname(os.path.realpath(__file__))
    nvidia_smi.nvmlInit()

    try:
        deviceCount = nvmlDeviceGetCount()
        for i in range(deviceCount):
            #gpus = len(i)
            #print("Num GPU: ",gpus)
            handle = nvmlDeviceGetHandleByIndex(i)
            info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)
            card = nvmlDeviceGetName(handle)
            print("Device", i, ":", nvmlDeviceGetName(handle))
            print("Total memory: %sGB" %(info.total//(1.024*10**9)))
            print("Free memory: %sGB" %(info.free//(1.024*10**9)))
            print("Used memory: %sGB" %(info.used//(1.024*10**9)))
            Num = (info.free//(1.024*10**9))-1
            print("Max number of scripts at once: ",Num)
            #print("Recommended Max number of scripts at once, per GPU: ",Num-1)
    except NVMLError as error:
        print(error)

    numgpu = deviceCount

    nvidia_smi.nvmlShutdown()

    # Input area
#%%
    #Where are the videos located?
    #file = glob.glob("/Data/2_DeInter/*.avi") #for production
    file = glob.glob("/Data/2_DeInter/Untitled_5.avi") #for Testing
    #file = sys.argv[1]
    #print(file)
    #How many videos do you want to process per GPU?
    #Num = 12
    NumProc = 1
    #nvidia_smi.nvmlInit()
    if (str(card) == "b'NVIDIA GeForce GTX 1050 Ti'") and (NumProc > 2 ):
        print("Unfortunately the 1050 Ti can only process two streams per card:")
        print("Changing number of processes to 2!")
        NumProc = 2
    #if NumProc == 1:
    #    MemFree = ((Num//NumProc)-1)
    #else:
    #    MemFree = (Num//NumProc)
    print("NumProc: ",NumProc)
    MemFree = 1/((Num*1.2)/NumProc)
    print("Memory free:",MemFree)
    size = (Num/NumProc)#MemFree #2 #1.2 #size of the tensorflow model
    print('Memory size Used: ',size)
    #print(size)
    print("\n")
    n_workers = NumProc#*numgpu #2
   #%%
    gpu = 0
    x = 0
    T = 0
    nvidia_smi.nvmlInit()

    with Progress() as progress:
        futures = []  # keep track of the jobs
        # with multiprocessing.Manager() as manager:
        #     # this is the key - we share some state between our
        #     # main process and our worker functions
        #     _progress = manager.dict()
        #     overall_progress_task = progress.add_task("[green]All jobs progress:")
        with multiprocessing.Manager() as manager:
            # this is the key - we share some state between our
            # main process and our worker functions
            _progress = manager.dict()
            overall_progress_task = progress.add_task("[green]All jobs progress:")

            #for n in range(len(file)):
            with ProcessPoolExecutor(max_workers=n_workers) as executor:
                #with ProcessPoolExecutor(max_workers=n_workers) as executor:
                while True:
                #for n in range(len(file)):
                    #task_id = progress.add_task(f"task {x}", visible=False)
                    task_id = progress.add_task(f"Processing video: {Path(file[x]).name}", visible=False)

                    #print("X: %s"%x)
                    #while True:
                    #for gpu in range(deviceCount):
                        #print("GPU: ",gpu)
                    print("X:",x)
                    # if x > NumProc: #clear the tf models
                    #     tf.keras.backend.clear_session()
                    #     tf.compat.v1.reset_default_graph()
                    #     del model
                    #     load.model()
                        #print("Mem Free: ",info.free//(size*10**9)-1)
                        #with Progress() as progress:
                        #    futures = []
                    while info.free/(size*10**9) <= MemFree:
                         #print("Mem Free: ",info.free/(1.024*10**9))
                         #print("Mem Free: ",info.free/(size*10**9))
                         #print("No Free Memory!")

                         #print("Checking GPU: %s for space"%gpu)
                         #print("Update Progress Bar")
                         if (n_finished := sum([future.done() for future in futures])) < len(futures):
                             progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                             for task_id, update_data in _progress.items():
                                 latest = update_data["progress"]
                                 total = update_data["total"]
                                 # update the progress bar for this task:
                                 progress.update(task_id,completed=latest,total=total,visible=latest < total,)
                         time.sleep(1)
                         gpu = gpu+1
                         if gpu == deviceCount:
                             gpu = 0
                         handle = nvmlDeviceGetHandleByIndex(gpu)
                         info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)

                    if info.free/(size*10**9) > MemFree:
                        tf.config.experimental.set_virtual_device_configuration(gpu,

                        futures.append(executor.submit(detect_frames, _progress, task_id, gpu, file[x], x, size))

                        if (n_finished := sum([future.done() for future in futures])) < len(futures):
                            progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                            for task_id, update_data in _progress.items():
                                latest = update_data["progress"]
                                total = update_data["total"]
                                # update the progress bar for this task:
                                progress.update(task_id,completed=latest,total=total,visible=latest < total,)
                        time.sleep(5)

                    #print("Update Progress Bar")
                    if (n_finished := sum([future.done() for future in futures])) < len(futures):
                        progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                        for task_id, update_data in _progress.items():
                            latest = update_data["progress"]
                            total = update_data["total"]
                            # update the progress bar for this task:
                            progress.update(task_id,completed=latest,total=total,visible=latest < total,)

                    x = x+1
                    gpu = gpu+1
                    if gpu == deviceCount:
                        gpu = 0
                       #break
                    if x == len(file):
                        print("End of file list")
                        #print("Update Progress Bar")
                        while (n_finished := sum([future.done() for future in futures])) < len(futures):
                            progress.update(overall_progress_task, completed=n_finished, total=len(futures))
                            for task_id, update_data in _progress.items():
                                latest = update_data["progress"]
                                total = update_data["total"]
                                # update the progress bar for this task:
                                progress.update(task_id,completed=latest,total=total,visible=latest < total,)
                        break
                    handle = nvmlDeviceGetHandleByIndex(gpu)
                    info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)

    nvidia_smi.nvmlShutdown()

`


问:
how to get the image with the auth headers in react js
I want to get the image the after the authentication. I use the axios. it return the value as a response. the response is

```<code>{
    "data": "����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0....0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u001f��",
    "status": 200,
    "statusText": "OK",
    "headers": {
        "cache-control": "public, max-age=0",
        "content-length": "13611",
        "content-type": "image/png",
        "last-modified": "Mon, 31 Oct 2022 09:52:27 GMT"
    },
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Authorization": "Bearer eyJhbGciO...nwEMs"
        },
        "method": "get",
        "url": "url"
    },
    "request": {}
}
</code>```

and the code that I use to get the response is

```<code>import axios from "axios";
import { userService } from "../services";
import { fetchWrapper } from "./fetch-wrapper";

export async function fetchImage(url) {

    if (url) {
        const user = userService.userValue;
        const result = await axios.get(url, {
            headers: { Authorization: `Bearer ${user.token}` }
        })
        console.log('result is ',result)
        if (result.status === 200) {
            const data = `data:${result.headers["content-type"]};base64,${new Buffer(result.data, "binary").toString("base64")}`;
            console.log("data is ",data)
            return data
        }
    }
}
</code>```

It return the data but the image is not showing on page. It may be the image src code is may be wrong. I don't know how to solve this problem. Kindly tell me the problem that I make in this code.

Body:
I want to get the image the after the authentication. I use the axios. it return the value as a response. the response is

{
    "data": "����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0....0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u001f��",
    "status": 200,
    "statusText": "OK",
    "headers": {
        "cache-control": "public, max-age=0",
        "content-length": "13611",
        "content-type": "image/png",
        "last-modified": "Mon, 31 Oct 2022 09:52:27 GMT"
    },
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Authorization": "Bearer eyJhbGciO...nwEMs"
        },
        "method": "get",
        "url": "url"
    },
    "request": {}
}

and the code that I use to get the response is

import axios from "axios";
import { userService } from "../services";
import { fetchWrapper } from "./fetch-wrapper";

export async function fetchImage(url) {

    if (url) {
        const user = userService.userValue;
        const result = await axios.get(url, {
            headers: { Authorization: `Bearer ${user.token}` }
        })
        console.log('result is ',result)
        if (result.status === 200) {
            const data = `data:${result.headers["content-type"]};base64,${new Buffer(result.data, "binary").toString("base64")}`;
            console.log("data is ",data)
            return data
        }
    }
}

It return the data but the image is not showing on page. It may be the image src code is may be wrong. I don't know how to solve this problem. Kindly tell me the problem that I make in this code.


问:
how to remove folder name from url using htaccess or php
I want to change the URL from:

```<code>http://example.com/folder/name-file.php
</code>```

To:

```<code>http://example.com/name-file.php
</code>```

basically i want to hide url folder

```<code><IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule ^folder(/.*|)$ $1 [L,NC]
</IfModule>
</code>```

I have tried a lot but nothing is working for me.

Body:
I want to change the URL from:

http://example.com/folder/name-file.php

To:

http://example.com/name-file.php

basically i want to hide url folder

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule ^folder(/.*|)$ $1 [L,NC]
</IfModule>

I have tried a lot but nothing is working for me.


问:
How can I set the size of the markers in plotly express sacatter_mapbox?
I am trying to plot some latitudes and longitudes in a map
I do

```<code>import plotly.express as px

fig = px.scatter_mapbox(one_line, lat="lat", lon="lon",
                            zoom=15,
                            text = 'point_idx',
                            size='size',
                            size_max=15
                        )
 fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
 fig.show()
</code>```

where one_line is the dataframe with the values (only 17 values)
For some reason this shows the map, I can see the text when I put the mouse there but the marker is not drawn

For an even strange reason in a similar script but with 3176 points I can see the markers
How can I set the marker size so that I can see them

EDIT
The data

```<code>          lat         lon
0   35.843737  139.870344
1   35.843765  139.870372
2   35.843800  139.870407
3   35.843835  139.870441
4   35.843871  139.870476
5   35.843907  139.870511
6   35.843942  139.870545
7   35.843978  139.870580
8   35.844014  139.870614
9   35.844049  139.870648
10  35.844085  139.870682
11  35.844121  139.870715
12  35.844157  139.870749
13  35.844194  139.870783
14  35.844230  139.870817
15  35.844266  139.870850
16  35.844306  139.870887
</code>```

Body:
I am trying to plot some latitudes and longitudes in a map
I do

import plotly.express as px

fig = px.scatter_mapbox(one_line, lat="lat", lon="lon",
                            zoom=15,
                            text = 'point_idx',
                            size='size',
                            size_max=15
                        )
 fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})
 fig.show()

where one_line is the dataframe with the values (only 17 values)
For some reason this shows the map, I can see the text when I put the mouse there but the marker is not drawn

For an even strange reason in a similar script but with 3176 points I can see the markers
How can I set the marker size so that I can see them

EDIT
The data

          lat         lon
0   35.843737  139.870344
1   35.843765  139.870372
2   35.843800  139.870407
3   35.843835  139.870441
4   35.843871  139.870476
5   35.843907  139.870511
6   35.843942  139.870545
7   35.843978  139.870580
8   35.844014  139.870614
9   35.844049  139.870648
10  35.844085  139.870682
11  35.844121  139.870715
12  35.844157  139.870749
13  35.844194  139.870783
14  35.844230  139.870817
15  35.844266  139.870850
16  35.844306  139.870887