问:
Why Can't I push to gitlab repository?
I recently created a new gitlab repository, and have set up a repository deployment key with the ssh public key from my computer. I manage to clone the project with ssh, but when I try to push changes into the repository, I get returned with a fatal error:</p>
```<code>fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

答:
In order to be able to push all the following should be implemented first

Make sure the project has been created under your username on
GitLab.com.

your Git username and email  match your GitLab.com account for this
repository

the remote origin was set:

git remote add origin git@gitlab.com:user_name/work.git

an SSH public key was added to your GitLab.com account (if cloning
over using git or ssh).

ssh -T git@gitlab.com

Otherwise you could create a specific access token for the project you want to write to

The following guide could be useful https://blog.programster.org/gitlab-create-a-projects-access-token

Title: Why Can't I push to gitlab repository?

Body:
I recently created a new gitlab repository, and have set up a repository deployment key with the ssh public key from my computer. I manage to clone the project with ssh, but when I try to push changes into the repository, I get returned with a fatal error:

fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.


来源: stackexchange

问:
Trying to connect to Azure Cosmos DB from GoLang Application
I've created a Cosmos DB and I am trying to connect to it through my GoLang application. Here is the code:

```<code>type DB struct {
    MongoDB *mongo.Client
}

var dbConn = &DB{}

func NewMongoDB(connectionString string) (*mongo.Client, error) {
    //Create a context to use with the connection
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
    client, err := mongo.NewClient(clientOptions)
    if err != nil {
        log.Fatalf("unable to initialize new Cosmos DB client %v", err)
        return nil, err
    }

    err = client.Connect(ctx)
    if err != nil {
        log.Fatalf("unable to initialize connection %v", err)
        return nil, err
    }

    err = TestConnection(client, &ctx)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }

    return client, err
}

func ConnectNoSQL(connectionString string) (*DB, error) {
    //Create a new Mongo DB client
    db, err := NewMongoDB(connectionString)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }
    dbConn.MongoDB = db

    return dbConn, err
}

func TestConnection(client *mongo.Client, ctx *context.Context) error {
    if err := client.Ping(*ctx, nil); err != nil {
        fmt.Println("Could not PING database due to - ", err)
        return err
    }
    return nil
}

...

// 2. Connect to database
    log.Println("Connecting to database ..") //Create the URI we will use to connect to out cosmosDB
    connecturi := fmt.Sprintf(
        "mongodb://%s:%s@%s.documents.azure.com:%s/%s?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@%s@",
        *dbUser,
        *dbPassword,
        *dbHost,
        *dbPort,
        *dbName,
        *dbHost)
    db, err := driver.ConnectNoSQL(connecturi)
    if err != nil {
        log.Fatal("Cannot to databse ...")
    }
</code>```

Here is the error message:

2022/02/01 22:48:53 server selection error: context deadline exceeded,
current topology: { Type: Single, Servers: [{ Addr:
scenario-prototype-db.documents.azure.com:443, Type: Unknown, Last
error: connection() error occured during connection handshake:
connection({COSMOS-DB-NAME}.documents.azure.com:443[-22]) length
of read message too large: length of read message too large }, ] }

I am not sure what is going on. I followed tutorial from Microsoft's official documentation - https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/create-mongodb-go, but did not manage to do it.

It looks like it:

Creates a new client via mongo.NewClient

Manages to connects to it

FAILS at TestConnection when I try to PING it.

Any thoughts? Also, could this be due to the fact that my API is set to SQL api and not Mongo API (probably silly question, but I would like to understand meaning of error)

Thanks!

答: So, the problem turned out to be exactly as specified in the question and in the comments as well. Resource was created as an SQL API instead of MongoDB, even though error is a bit misleading or at least not detailed enough.</p>

ContentLicense: CC BY-SA 4.0

Body:
I've created a Cosmos DB and I am trying to connect to it through my GoLang application. Here is the code:

type DB struct {
    MongoDB *mongo.Client
}

var dbConn = &DB{}

func NewMongoDB(connectionString string) (*mongo.Client, error) {
    //Create a context to use with the connection
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
    client, err := mongo.NewClient(clientOptions)
    if err != nil {
        log.Fatalf("unable to initialize new Cosmos DB client %v", err)
        return nil, err
    }

    err = client.Connect(ctx)
    if err != nil {
        log.Fatalf("unable to initialize connection %v", err)
        return nil, err
    }

    err = TestConnection(client, &ctx)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }

    return client, err
}

func ConnectNoSQL(connectionString string) (*DB, error) {
    //Create a new Mongo DB client
    db, err := NewMongoDB(connectionString)
    if err != nil {
        log.Fatal(err)
        return nil, err
    }
    dbConn.MongoDB = db

    return dbConn, err
}

func TestConnection(client *mongo.Client, ctx *context.Context) error {
    if err := client.Ping(*ctx, nil); err != nil {
        fmt.Println("Could not PING database due to - ", err)
        return err
    }
    return nil
}

...

// 2. Connect to database
    log.Println("Connecting to database ..") //Create the URI we will use to connect to out cosmosDB
    connecturi := fmt.Sprintf(
        "mongodb://%s:%s@%s.documents.azure.com:%s/%s?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@%s@",
        *dbUser,
        *dbPassword,
        *dbHost,
        *dbPort,
        *dbName,
        *dbHost)
    db, err := driver.ConnectNoSQL(connecturi)
    if err != nil {
        log.Fatal("Cannot to databse ...")
    }

Here is the error message:

2022/02/01 22:48:53 server selection error: context deadline exceeded,
current topology: { Type: Single, Servers: [{ Addr:
scenario-prototype-db.documents.azure.com:443, Type: Unknown, Last
error: connection() error occured during connection handshake:
connection({COSMOS-DB-NAME}.documents.azure.com:443[-22]) length
of read message too large: length of read message too large }, ] }

I am not sure what is going on. I followed tutorial from Microsoft's official documentation - https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/create-mongodb-go, but did not manage to do it.

It looks like it:

Creates a new client via mongo.NewClient

Manages to connects to it

FAILS at TestConnection when I try to PING it.

Any thoughts? Also, could this be due to the fact that my API is set to SQL api and not Mongo API (probably silly question, but I would like to understand meaning of error)

Thanks!


问:
How to format React Codes in Visual Studio Code?
When auto-formatting React codes in VSCode it makes errors. I am using the Prettier extension. So what is the best code formatted for this?</p>

答:
Finally, I have found a way to do it. In the vscode settings, I have to change to default format to prettier.

As well as on the project it is needed to create a .prettierrc file with suitable configurations for the project.

```<code>{
  "trailingComma": "es5",
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true
}
</code>```

And if you do not need it, you can always enable to format the code without the .prettierrc file.

Body:
Finally, I have found a way to do it. In the vscode settings, I have to change to default format to prettier.

As well as on the project it is needed to create a .prettierrc file with suitable configurations for the project.

{
  "trailingComma": "es5",
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true
}

And if you do not need it, you can always enable to format the code without the .prettierrc file.


问:
Layout problem after integrating a slideshow html css
one page of my website is locking like that:
http://www.pflanzspass.bplaced.net/

Yesterdy I tried to integrate a slideshow:
http://www.pflanzspass.bplaced.net/indextest.php

The slideshow is working, but now there are some new layout problems:

now:

before:

I don't know why.

This is my new css-Code for the slideshow:

```<code>  * {box-sizing: border-box}
  /*body {
  font-family: Verdana, sans-serif;
  margin:0
  }*/
  .mySlides {display: none}
  img {vertical-align: middle;}
  .slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
  }
  /* Next & previous buttons */
  .prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  }
  /* Position the "next button" to the right */
  .next {
  right: 0;
  border-radius: 3px 0 0 3px;
  }
  /* On hover, add a black background color with a little bit see-through */
  .prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
  }
  /* Caption text */
  .text {
  color: #ffffff;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
  }
  /* Number text (1/3 etc) */
  .numbertext {
  color: #ffffff;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
  }
  /* The dots/bullets/indicators */
  .dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #999999;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
  }
  .active, .dot:hover {
  background-color: #111111;
  }
  /* Fading animation */
  .fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
  }
  @-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  @keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  /* On smaller screens, decrease text size */
  @media only screen and (max-width: 300px) {
  .prev, .next,.text {font-size: 11px}
  }
</code>```

This is the css-code, already online before added the slide-show css-code:

```<code>*{
    margin: 0px;
    padding: 0px;
}
body {
    font-family:Verdana;
    font-size:10px;
}
#wrapper{
    width:1000px;overflow:hidden;
    margin:0 auto 10px auto;background-image: url(./grafics/bg.gif);background-repeat:repeat-y;
}
/*-------------------------------------------------------------------*/
/*                          font-size                                */
/*-------------------------------------------------------------------*/
h1 {
   font-size: 25px;
}
h2 {
   font-size: 19px;
}
h3{
    font-size:18px;
    color:#660033;
}
h4, h5, h6 {
   font-size: 16px;
}
p{
    font-size: 14px;
    margin-right:20px;
}
h2, h3, h4, h5, p{
    margin-bottom:10px;
}
h5{

}
/*-------------------------------------------------------------------*/
/*                          links                                    */
/*-------------------------------------------------------------------*/
a:link, a:visited, a:active, a:hover{
    text-decoration:none;
    color:#634142;
    font-size:12px;
    font-weight:bold;
}
a:active, a:hover{
    text-decoration:underline;
}
/*-------------------------------------------------------------------*/
/*                          header                                   */
/*-------------------------------------------------------------------*/
#header {
    width:968px;
    height:161px;
    margin:0 13px 0 13px;
    border:3px solid #000;
    background-color: #000;
}
#header2{
    width:974px;
    height:65px;
    padding:5px 0 0 0;
    margin:0 13px 0 13px;
    background:#fff;
    clear:both;
}
#logo {
    width:222px;
    margin: 0 0 0 0;
    padding: 0 5px 0 0;
    float: left;
    overflow: hidden;
}
#header-title {
    height: 160px;
    background: transparent url(banner_2.jpg) no-repeat 0 0;
    float:left;
}

#ueberschrift {
    padding:60px 0 0 20px;
    color:#fff;
}
#ueberschrift p{
    font-size:16px;
}
#content-header{
    width:990px;height:60px;
    padding:0 0 20px 10px;
}
#like{
    width:77px;
    margin:5px 30px 0 10px;
    float:left;
}
#kaktus-banner{
    width:468px;
    margin:5px 0 0 129px;
    float:left;
}
#wobinich{
    width:964px;height:16px;
    margin:0 13px 0 13px;
    font-size:12px;
    border-bottom:1px solid #000;
    background:#fff;
    float:left;padding:0 0 0 10px;

}
h2.title{
    text-align:center;
    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title1.gif) no-repeat 0px 35px;
}
h2.title2{

    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 35px;
}
h2.gb{
    height:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 25px;
}
/*-------------------------------------------------------------------*/
/*                          content                                  */
/*-------------------------------------------------------------------*/

#content {
    width:974px;
    margin:0 13px 0 13px;
    background:#fff;
    float:left;
}
#content p{
    line-height:24px;
}
#links{
    width:185px;
    margin:0 0 0 0;
    float:left;
}
#mitte{
    width:609px; /*609px*/
    padding:10px 10px 0 10px;
    float:left;
}
#mitte_a-z{
    width:873px;
    padding:10px 0 0 20px;
}
#mitte1{
    width:767px;
    padding:10px 10px 0 10px;
    float:left;
}
#rechts{
    width:160px;
    margin:0 0px 10px 0;
    float:right;
}
#film{
    margin:10px 0 10px 182px;
}

#footer{
    width:974px;height:30px;

    font-size:12px;
    line-height: 27px;
    text-align:center;
    color:#000;
    border-top:1px solid #000;background:#fff;border-bottom:1px solid #000;background:#fff;
    float:left;
}
#footer a{
    font-weight:normal;
    color:#000;
}
/*-------------------------------------------------------------------*/
/*                          navigation                               */
/*-------------------------------------------------------------------*/
.navtitle{
    margin:0px;
    background:#7fb37f;
    text-align:center;
}
#navigationsleiste{
    margin:0 16px 20px 0;padding:0 0 10px 0;
    width:185px;background:#a5e8a5;
}
#navigationsleiste a{
    display: block;
    height: 20px;
    padding:8px 0 0 19px;

    color: #000;
    text-decoration: none;
}
#navigationsleiste a:hover{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
#navigationsleiste a.aktiv{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
.link{
    /*margin:0 16px -2000px 0;padding-bottom:2000px;*/
    width: 185px;background:#a5e8a5;
}
.link a{
    display: block;
    height: 20px;
    margin:2px;
    padding:10px 0 10px 9px;
    font-size:12px;
}
.link-re{
    /*margin:0 0px -2500px 0;padding:0 0 2500px 0;*/
    width: 160px;background:#a5e8a5;
}
.link-re a{
    display: block;
    height: 20px;
    margin:0px;
    padding:2px 0 0 20px;
    font-size:12px;
    font-weight:bold;

}
#zapp{
    width:964px;height:20px;
    margin:0 13px 0 13px;
    font-size:12px;
    background:#fff;
    border-bottom:1px solid #000;
    padding:10px 0 0 10px;
    float:left;

}
.up{
    margin:10px 0 10px 0px;
    text-align:right;

}
.up a{
    font-weight:bold;
}
.back{
    margin:0 60px 0 0;
    float:left
}
.zurueck{
    float:left;
}
.ist{
    float:left;
    color:#a5a5a5;
    margin-left:30px;
}
.vor{
    margin:0 0 0 30px;
    float:left;
}
/*-------------------------------------------------------------------*/
/*                          listenelemente                           */
/*-------------------------------------------------------------------*/
ul{
    list-style-type:none;
}
li{

}
#mitte ul{
    list-style-type:disc;
    margin-left:15px;
}
#mitte li a{

}
ol{
    font-size:14px;
    margin:0 0 0 20px;
    line-height:24px;
}
.cb{
    clear:both;
}
img{

}
#table{
}
p.hn {
  color: #870B0B;
}

p.se {
  color:#057C11;
}

p.nanl {
  color:#64057C;
}

p.bild {
    float:left;
    }
</code>```

答:
```<code>* {

    box-sizing: border-box;
}

.link a {
        display: block;
        height: auto;
        margin: 2px;
        padding: 10px 0 10px 9px;
        font-size: 12px;
    }

</code>```

Body:
one page of my website is locking like that:
http://www.pflanzspass.bplaced.net/

Yesterdy I tried to integrate a slideshow:
http://www.pflanzspass.bplaced.net/indextest.php

The slideshow is working, but now there are some new layout problems:

now:

before:

I don't know why.

This is my new css-Code for the slideshow:

  * {box-sizing: border-box}
  /*body {
  font-family: Verdana, sans-serif;
  margin:0
  }*/
  .mySlides {display: none}
  img {vertical-align: middle;}
  .slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
  }
  /* Next & previous buttons */
  .prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  }
  /* Position the "next button" to the right */
  .next {
  right: 0;
  border-radius: 3px 0 0 3px;
  }
  /* On hover, add a black background color with a little bit see-through */
  .prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
  }
  /* Caption text */
  .text {
  color: #ffffff;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
  }
  /* Number text (1/3 etc) */
  .numbertext {
  color: #ffffff;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
  }
  /* The dots/bullets/indicators */
  .dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #999999;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
  }
  .active, .dot:hover {
  background-color: #111111;
  }
  /* Fading animation */
  .fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
  }
  @-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  @keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  /* On smaller screens, decrease text size */
  @media only screen and (max-width: 300px) {
  .prev, .next,.text {font-size: 11px}
  }

This is the css-code, already online before added the slide-show css-code:

*{
    margin: 0px;
    padding: 0px;
}
body {
    font-family:Verdana;
    font-size:10px;
}
#wrapper{
    width:1000px;overflow:hidden;
    margin:0 auto 10px auto;background-image: url(./grafics/bg.gif);background-repeat:repeat-y;
}
/*-------------------------------------------------------------------*/
/*                          font-size                                */
/*-------------------------------------------------------------------*/
h1 {
   font-size: 25px;
}
h2 {
   font-size: 19px;
}
h3{
    font-size:18px;
    color:#660033;
}
h4, h5, h6 {
   font-size: 16px;
}
p{
    font-size: 14px;
    margin-right:20px;
}
h2, h3, h4, h5, p{
    margin-bottom:10px;
}
h5{

}
/*-------------------------------------------------------------------*/
/*                          links                                    */
/*-------------------------------------------------------------------*/
a:link, a:visited, a:active, a:hover{
    text-decoration:none;
    color:#634142;
    font-size:12px;
    font-weight:bold;
}
a:active, a:hover{
    text-decoration:underline;
}
/*-------------------------------------------------------------------*/
/*                          header                                   */
/*-------------------------------------------------------------------*/
#header {
    width:968px;
    height:161px;
    margin:0 13px 0 13px;
    border:3px solid #000;
    background-color: #000;
}
#header2{
    width:974px;
    height:65px;
    padding:5px 0 0 0;
    margin:0 13px 0 13px;
    background:#fff;
    clear:both;
}
#logo {
    width:222px;
    margin: 0 0 0 0;
    padding: 0 5px 0 0;
    float: left;
    overflow: hidden;
}
#header-title {
    height: 160px;
    background: transparent url(banner_2.jpg) no-repeat 0 0;
    float:left;
}

#ueberschrift {
    padding:60px 0 0 20px;
    color:#fff;
}
#ueberschrift p{
    font-size:16px;
}
#content-header{
    width:990px;height:60px;
    padding:0 0 20px 10px;
}
#like{
    width:77px;
    margin:5px 30px 0 10px;
    float:left;
}
#kaktus-banner{
    width:468px;
    margin:5px 0 0 129px;
    float:left;
}
#wobinich{
    width:964px;height:16px;
    margin:0 13px 0 13px;
    font-size:12px;
    border-bottom:1px solid #000;
    background:#fff;
    float:left;padding:0 0 0 10px;

}
h2.title{
    text-align:center;
    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title1.gif) no-repeat 0px 35px;
}
h2.title2{

    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 35px;
}
h2.gb{
    height:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 25px;
}
/*-------------------------------------------------------------------*/
/*                          content                                  */
/*-------------------------------------------------------------------*/

#content {
    width:974px;
    margin:0 13px 0 13px;
    background:#fff;
    float:left;
}
#content p{
    line-height:24px;
}
#links{
    width:185px;
    margin:0 0 0 0;
    float:left;
}
#mitte{
    width:609px; /*609px*/
    padding:10px 10px 0 10px;
    float:left;
}
#mitte_a-z{
    width:873px;
    padding:10px 0 0 20px;
}
#mitte1{
    width:767px;
    padding:10px 10px 0 10px;
    float:left;
}
#rechts{
    width:160px;
    margin:0 0px 10px 0;
    float:right;
}
#film{
    margin:10px 0 10px 182px;
}

#footer{
    width:974px;height:30px;

    font-size:12px;
    line-height: 27px;
    text-align:center;
    color:#000;
    border-top:1px solid #000;background:#fff;border-bottom:1px solid #000;background:#fff;
    float:left;
}
#footer a{
    font-weight:normal;
    color:#000;
}
/*-------------------------------------------------------------------*/
/*                          navigation                               */
/*-------------------------------------------------------------------*/
.navtitle{
    margin:0px;
    background:#7fb37f;
    text-align:center;
}
#navigationsleiste{
    margin:0 16px 20px 0;padding:0 0 10px 0;
    width:185px;background:#a5e8a5;
}
#navigationsleiste a{
    display: block;
    height: 20px;
    padding:8px 0 0 19px;

    color: #000;
    text-decoration: none;
}
#navigationsleiste a:hover{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
#navigationsleiste a.aktiv{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
.link{
    /*margin:0 16px -2000px 0;padding-bottom:2000px;*/
    width: 185px;background:#a5e8a5;
}
.link a{
    display: block;
    height: 20px;
    margin:2px;
    padding:10px 0 10px 9px;
    font-size:12px;
}
.link-re{
    /*margin:0 0px -2500px 0;padding:0 0 2500px 0;*/
    width: 160px;background:#a5e8a5;
}
.link-re a{
    display: block;
    height: 20px;
    margin:0px;
    padding:2px 0 0 20px;
    font-size:12px;
    font-weight:bold;

}
#zapp{
    width:964px;height:20px;
    margin:0 13px 0 13px;
    font-size:12px;
    background:#fff;
    border-bottom:1px solid #000;
    padding:10px 0 0 10px;
    float:left;

}
.up{
    margin:10px 0 10px 0px;
    text-align:right;

}
.up a{
    font-weight:bold;
}
.back{
    margin:0 60px 0 0;
    float:left
}
.zurueck{
    float:left;
}
.ist{
    float:left;
    color:#a5a5a5;
    margin-left:30px;
}
.vor{
    margin:0 0 0 30px;
    float:left;
}
/*-------------------------------------------------------------------*/
/*                          listenelemente                           */
/*-------------------------------------------------------------------*/
ul{
    list-style-type:none;
}
li{

}
#mitte ul{
    list-style-type:disc;
    margin-left:15px;
}
#mitte li a{

}
ol{
    font-size:14px;
    margin:0 0 0 20px;
    line-height:24px;
}
.cb{
    clear:both;
}
img{

}
#table{
}
p.hn {
  color: #870B0B;
}

p.se {
  color:#057C11;
}

p.nanl {
  color:#64057C;
}

p.bild {
    float:left;
    }


问:
How can I create a new array and append it to the source array using map + arrow function?
So I would like to map a resulting value to each row within a range of values, populate the results into a new array and paste the created array to enrich the source data.

So the callback function in the map method should check if the amount is < > 0 and return revenue expense respectively. I'm struggling in defining the map method and callback function. How can I "access" the amount column? And do I need one or two parameters for the arrow function?

```<code>function example_function() {

  // Get active Sheet
  sheet = SpreadsheetApp.getActiveSheet()

  // Get the range
  range = sheet.getDataRange()

  // Get its values
  values = range.getValues()

  // Create new array by mapping the desired results
  resulting_array = values.map((a, b) => {

    // "if value in current row and column b is > 0 then return "revenue", else "expense"
    // what would be the app script language equivalent to this condition?

  });

  // Paste the created array
  sheet.getRange(2, 3).setValues(resulting_array);
}
</code>```

Source

Item
Amount
P&L

Shopify
-30

Paypal
40

Desired Outcome

Item
Amount
P&L

Shopify
-30
Expense

Paypal
40
Revenue

答:
It can be done many ways. I'd try this:</p>
```<code>function example_function() {

    // Get active Sheet
    sheet = SpreadsheetApp.getActiveSheet()

    // Get the range
    range = sheet.getDataRange()

    // Get its values
    values = range.getValues()

    // Create new array by mapping the desired results
    resulting_array = values.map(row => row[1] > 0 ? ['Revenue'] : ['Expense']);

    // Paste the created array
    sheet.getRange(1,3,resulting_array.length,1).setValues(resulting_array);
}
</code>```

Body:
So I would like to map a resulting value to each row within a range of values, populate the results into a new array and paste the created array to enrich the source data.

So the callback function in the map method should check if the amount is < > 0 and return revenue expense respectively. I'm struggling in defining the map method and callback function. How can I "access" the amount column? And do I need one or two parameters for the arrow function?

function example_function() {

  // Get active Sheet
  sheet = SpreadsheetApp.getActiveSheet()

  // Get the range
  range = sheet.getDataRange()

  // Get its values
  values = range.getValues()

  // Create new array by mapping the desired results
  resulting_array = values.map((a, b) => {

    // "if value in current row and column b is > 0 then return "revenue", else "expense"
    // what would be the app script language equivalent to this condition?

  });

  // Paste the created array
  sheet.getRange(2, 3).setValues(resulting_array);
}

Source

Item
Amount
P&L

Shopify
-30

Paypal
40

Desired Outcome

Item
Amount
P&L

Shopify
-30
Expense

Paypal
40
Revenue

Body:
It can be done many ways. I'd try this:

function example_function() {

    // Get active Sheet
    sheet = SpreadsheetApp.getActiveSheet()

    // Get the range
    range = sheet.getDataRange()

    // Get its values
    values = range.getValues()

    // Create new array by mapping the desired results
    resulting_array = values.map(row => row[1] > 0 ? ['Revenue'] : ['Expense']);

    // Paste the created array
    sheet.getRange(1,3,resulting_array.length,1).setValues(resulting_array);
}


问:
Change php variable based on javascript value
how can i change/assign a value to php variable depending on a javascript variable?
here is my code.

```<code><select id="reOutcome" name="reOutcome" onchange="OnChange(this.form.reOutcome);">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>

<script type="text/javascript">

function OnChange(dropdown)
{
    var myindex  = dropdown.selectedIndex
    var SelValue = dropdown.options[myindex].value
    if(SelValue==2){
     <?php
    $sCOMPFields .= "|"."SreComments";
    $sCOMPFields .= "|"."rePrID";
     ?>
    }
    return true;
}
</script>
</code>```

The onchange function is working fine. I just don't know how to change the php variable. I searched online a lot. All im getting is how to assign php variable to javascript. That is not what im looking for.
Thanks for your help.

答: PHP variables are set at run time. You can't do it directly within the javascript. Off the top of my head the best way I can think of to do it would be to set the php variables as session variables. Then use your javascript to call a php file via ajax/jquery that can update the session variables.</p>

ContentLicense: CC BY-SA 3.0

Body:
how can i change/assign a value to php variable depending on a javascript variable?
here is my code.

<select id="reOutcome" name="reOutcome" onchange="OnChange(this.form.reOutcome);">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>

The onchange function is working fine. I just don't know how to change the php variable. I searched online a lot. All im getting is how to assign php variable to javascript. That is not what im looking for.
Thanks for your help.


问:
Room database not created
I'm trying to develop an app with Room. The project is in java. This is my first time using Room.

I've followed the documentation and created class with @Database, @Dao & @Entity. However when I run the app, it throws the following exception.

Can someone please help me figure out what am I doing wrong here? I've spent a day on it but still couldn't figure out.

```<code>2021-02-07 20:29:16.151 13959-13959/com.hello.testapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hello.testapp, PID: 13959
    java.lang.RuntimeException: cannot find implementation for com.hello.testapp.persistance.MyDatabase. MyDatabase_Impl does not exist   <----- ERROR
        at androidx.room.Room.getGeneratedImplementation(Room.java:94)
        at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:952)
        at com.hello.testapp.persistance.MyDatabase.getInstance(MyDatabase.java:33)
        at com.hello.testapp.repositories.MyClientRepo.<init>(MyClientRepo.java:30)
        at com.hello.testapp.SplashActivity$1.run(SplashActivity.java:45)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

Following are the classes:

Category.java:

```<code>@Entity(tableName = "category")
public class Category {

    @PrimaryKey
    @SerializedName("category_name")
    @Expose
    private String categoryName;
    @SerializedName("type")
    @Expose
    private int type;

    public Category() {}

    public Category(String categoryName, int type) {
        this.categoryName = categoryName;
        this.type = type;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}
</code>```

MyDao.java:

```<code>@Dao
public interface MyDao {

    @Query("SELECT * FROM category LIMIT (:pageNum * 10)")
    LiveData<List<Category>> getCategories(int pageNum);
}
</code>```

MyDatabase.java:

```<code>@Database(entities = {Category.class}, version = 1)
@TypeConverters({ListConverter.class})
public abstract class MyDatabase extends RoomDatabase {

    private static final String DATABASE_NAME = "my_db";
    private static MyDatabase db;

    public static MyDatabase getInstance(Context context) {
        if(db == null) {
            System.out.println("creating instance");
            db = Room.databaseBuilder(
                    context.getApplicationContext(),
                    MyDatabase.class,
                    DATABASE_NAME
            ).build();
        }

        return db;
    }
    public abstract MyDao getDao();
}
</code>```

ListConverter.java:

```<code>public class ListConverter {

    @TypeConverter
    public static List<String> fromString(String value) {
        Type listType = new TypeToken<List<String>>(){}.getType();
        return new Gson().fromJson(value, listType);
    }

    @TypeConverter
    public static String fromList(List<String> list) {
        return new Gson().toJson(list);
    }
}
</code>```

Build.gradle

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

dependencies {
    ..other dependencies

    def room_version = "2.2.6"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    def hilt_version = '2.31.2-alpha'
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
}
</code>```

Please help me understand where am I making a mistake.

答:
I was facing the same error. change your dependencies like this:

dependencies {
    def roomVersion = "2.4.1"
    implementation("androidx.room:room-runtime:$roomVersion")
    kapt("androidx.room:room-compiler:$roomVersion")
    implementation("androidx.room:room-ktx:$roomVersion")
}
```

Title: Room database not created

Body:
I'm trying to develop an app with Room. The project is in java. This is my first time using Room.

I've followed the documentation and created class with @Database, @Dao & @Entity. However when I run the app, it throws the following exception.

Can someone please help me figure out what am I doing wrong here? I've spent a day on it but still couldn't figure out.

2021-02-07 20:29:16.151 13959-13959/com.hello.testapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hello.testapp, PID: 13959
    java.lang.RuntimeException: cannot find implementation for com.hello.testapp.persistance.MyDatabase. MyDatabase_Impl does not exist   <----- ERROR
        at androidx.room.Room.getGeneratedImplementation(Room.java:94)
        at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:952)
        at com.hello.testapp.persistance.MyDatabase.getInstance(MyDatabase.java:33)
        at com.hello.testapp.repositories.MyClientRepo.<init>(MyClientRepo.java:30)
        at com.hello.testapp.SplashActivity$1.run(SplashActivity.java:45)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Following are the classes:

Category.java:

@Entity(tableName = "category")
public class Category {

    @PrimaryKey
    @SerializedName("category_name")
    @Expose
    private String categoryName;
    @SerializedName("type")
    @Expose
    private int type;

    public Category() {}

    public Category(String categoryName, int type) {
        this.categoryName = categoryName;
        this.type = type;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}

MyDao.java:

@Dao
public interface MyDao {

    @Query("SELECT * FROM category LIMIT (:pageNum * 10)")
    LiveData<List<Category>> getCategories(int pageNum);
}

MyDatabase.java:

@Database(entities = {Category.class}, version = 1)
@TypeConverters({ListConverter.class})
public abstract class MyDatabase extends RoomDatabase {

    private static final String DATABASE_NAME = "my_db";
    private static MyDatabase db;

    public static MyDatabase getInstance(Context context) {
        if(db == null) {
            System.out.println("creating instance");
            db = Room.databaseBuilder(
                    context.getApplicationContext(),
                    MyDatabase.class,
                    DATABASE_NAME
            ).build();
        }

        return db;
    }
    public abstract MyDao getDao();
}

ListConverter.java:

public class ListConverter {

    @TypeConverter
    public static List<String> fromString(String value) {
        Type listType = new TypeToken<List<String>>(){}.getType();
        return new Gson().fromJson(value, listType);
    }

    @TypeConverter
    public static String fromList(List<String> list) {
        return new Gson().toJson(list);
    }
}

Build.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

dependencies {
    ..other dependencies

    def room_version = "2.2.6"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    def hilt_version = '2.31.2-alpha'
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
}

Please help me understand where am I making a mistake.


问:
Converting pandas dataframe to dictionary with same keys over multiple rows
I'm trying to create a dictionary from a pandas data frame with key from a column and values from rest of columns. But the problem is I will have same keys in multiple rows and I've read through many other similar SO posts but couldn't find the answer. This is what I have:

df1:

```<code>pid  feature_id  feature_value
78          20            1.0
78        1130            3.0
...
91        1148            1.0
92        1153            4.0
92        1154            1.0
...
115       1162            1.0
115       1175            5.0
......
</code>```

This is what I tried:

```<code>df2 = df1.set_index('pid').agg(tuple, 1).to_dict()
</code>```

But problem is this seems to not take into account the same keys from multiple rows.

What I want is something like this:

```<code>{78: [(20, 1.0), (1130, 3.0)]..., 115: [(1162, 1.0), (1175, 5.0)], ...}
</code>```

Please advise.

答:
Take the example dataframe:

```<code>df = pd.DataFrame({'col0':[1,2,3,1,2],'col1':[10,20,30,40,50],'col2':[7,8,9,8,7]})
</code>```

You can do:

```<code>df = df.assign(pairs = df.apply(lambda row: [row['col1'],row['col2']],axis=1))
res = df.groupby('col0')['pairs'].apply(list).to_dict()
</code>```

Original df:

```<code>   col0  col1  col2
0     1    10     7
1     2    20     8
2     3    30     9
3     1    40     8
4     2    50     7
</code>```

res:

```<code>{1: [[10, 7], [40, 8]], 2: [[20, 8], [50, 7]], 3: [[30, 9]]}
</code>```

Same is applicable to your df, just replace col0, col1 and col2 by pid,  feature_id and feature_value respectively.

Body:
I'm trying to create a dictionary from a pandas data frame with key from a column and values from rest of columns. But the problem is I will have same keys in multiple rows and I've read through many other similar SO posts but couldn't find the answer. This is what I have:

df1:

pid  feature_id  feature_value
78          20            1.0
78        1130            3.0
...
91        1148            1.0
92        1153            4.0
92        1154            1.0
...
115       1162            1.0
115       1175            5.0
......

This is what I tried:

df2 = df1.set_index('pid').agg(tuple, 1).to_dict()

But problem is this seems to not take into account the same keys from multiple rows.

What I want is something like this:

{78: [(20, 1.0), (1130, 3.0)]..., 115: [(1162, 1.0), (1175, 5.0)], ...}

Please advise.

Body:
Take the example dataframe:

df = pd.DataFrame({'col0':[1,2,3,1,2],'col1':[10,20,30,40,50],'col2':[7,8,9,8,7]})

You can do:

df = df.assign(pairs = df.apply(lambda row: [row['col1'],row['col2']],axis=1))
res = df.groupby('col0')['pairs'].apply(list).to_dict()

Original df:

   col0  col1  col2
0     1    10     7
1     2    20     8
2     3    30     9
3     1    40     8
4     2    50     7

res:

{1: [[10, 7], [40, 8]], 2: [[20, 8], [50, 7]], 3: [[30, 9]]}

Same is applicable to your df, just replace col0, col1 and col2 by pid,  feature_id and feature_value respectively.


问:
A very big sum - Hacker Rank
I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

```<code>function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}
</code>```

Second Solution

```<code>function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}
</code>```

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

答:
sample input [1000000001 ,1000000002 ,1000000003, 1000000004, 1000000005]

function aVeryBigSum(ar) {
  let score = 0;

  for(let i =0; i< ar.length;i++) {
    score += parseInt(ar[i].toString().substring(0));
  }

  return score;
}
```

Title: A very big sum - Hacker Rank

Body:
I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}

Second Solution

function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure


问:
why i cant return 2 value in a user defined function and display it in the main functionn? can someone help me
this countGender function need to receive what gender and return 2 value which is female or male

```<code>    int countGender(string gender)
    {
        int numGender[2] = {0};

        if(gender == "F")
        numGender[1]++;
        else if(gender == "M")
        numGender[2]++;

        return numGender[2];
    }
</code>```

display the 2 value in the main function

```<code>    int main()
    {
        string gender;
        int numGender[2];
        int n;

        cout<<"Enter number of respondents:";
        cin>>n;

        for(int i=0; i<n; i++)
        {
        cout<<"\nEnter Gender (F-Female, M-Male):";
        cin>>gender;
        numGender=countGender(gender);
        }
        cout<<"\nFemale - "<<numGender[1];
        cout<<"\nMale - "<<numGender[2];
        return 0;
    }
</code>```

答:
You're mismatching effect of function and object you want to store results. THe countGender function looks like a mess resulting of shotgun debugging.

You can't return an array in a function. More of, to actually perform counting, you have to pass existing value on each iteration. One of logical things to do is to pass the array by reference. Also, array in C++ have zero-based indexes.

```<code>void countGender(int (&numGender)[2], string gender)
{
    if(gender == "F")
        numGender[0]++;
    else if(gender == "M")
        numGender[1]++;
}

int main()
{
    string gender;
    int numGender[2] = {};
    int n;

    cout<<"Enter number of respondents:";
    cin>>n;

    for(int i=0; i<n; i++)
    {
        cout<<"\nEnter Gender (F-Female, M-Male):";
        cin>>gender;
        countGender(numGender,gender);
    }
    cout<<"\nFemale - "<<numGender[0];
    cout<<"\nMale - "<<numGender[1];
    return 0;
}
</code>```

Body:
this countGender function need to receive what gender and return 2 value which is female or male

    int countGender(string gender)
    {
        int numGender[2] = {0};

        if(gender == "F")
        numGender[1]++;
        else if(gender == "M")
        numGender[2]++;

        return numGender[2];
    }

display the 2 value in the main function

    int main()
    {
        string gender;
        int numGender[2];
        int n;

        cout<<"Enter number of respondents:";
        cin>>n;

        for(int i=0; i<n; i++)
        {
        cout<<"\nEnter Gender (F-Female, M-Male):";
        cin>>gender;
        numGender=countGender(gender);
        }
        cout<<"\nFemale - "<<numGender[1];
        cout<<"\nMale - "<<numGender[2];
        return 0;
    }

Body:
You're mismatching effect of function and object you want to store results. THe countGender function looks like a mess resulting of shotgun debugging.

You can't return an array in a function. More of, to actually perform counting, you have to pass existing value on each iteration. One of logical things to do is to pass the array by reference. Also, array in C++ have zero-based indexes.

void countGender(int (&numGender)[2], string gender)
{
    if(gender == "F")
        numGender[0]++;
    else if(gender == "M")
        numGender[1]++;
}

int main()
{
    string gender;
    int numGender[2] = {};
    int n;

    cout<<"Enter number of respondents:";
    cin>>n;

    for(int i=0; i<n; i++)
    {
        cout<<"\nEnter Gender (F-Female, M-Male):";
        cin>>gender;
        countGender(numGender,gender);
    }
    cout<<"\nFemale - "<<numGender[0];
    cout<<"\nMale - "<<numGender[1];
    return 0;
}


问:
How to remove Kubernetes 'shutdown' pods
I recently noticed a big accumulation of pods with status 'Shutdown'. We have been using Kubernetes since October, 2020.

Production and staging is running on the same nodes except that staging uses preemtible nodes to cut the cost. The containers are also stable in staging. (Failures occur rarely as they are caught in testing before).

Service provider Google Cloud Kubernetes.

I familiarized myself with the docs and tried searching however neither I recognize neither google helps with this particular status. There are no errors in the logs.

I have no problem pods being stopped. Ideally I'd like K8s to automatically delete these shutdown pods. If I run kubectl delete po redis-7b86cdccf9-zl6k9, it goes away in a blink.

kubectl get pods | grep Shutdown | awk '{print $1}' | xargs kubectl delete pod is manual temporary workaround.

PS. k is an alias to kubectl in my environment.

Final example: it happens across all namespaces // different containers.

I stumbled upon few related issues explaining the status
https://github.com/kubernetes/website/pull/28235
https://github.com/kubernetes/kubernetes/issues/102820

"When pods were evicted during the graceful node shutdown, they are marked as failed. Running kubectl get pods shows the status of the the evicted pods as Shutdown."

答:
My take on this problem looks something like this (inspiration from other solutions here):</p>
```<code># Delete all shutdown pods. This is common problem on kubernetes using preemptible nodes on gke
# why awk, not failed pods: https://github.com/kubernetes/kubernetes/issues/54525#issuecomment-340035375
# due fact failed will delete evicted pods, that will complicate pod troubleshooting

---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: del-shutdown-pods
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
spec:
  schedule: "*/1 * * * *"
  successfulJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        metadata:
          labels:
            app: shutdown-pod-cleaner
        spec:
          volumes:
          - name: scripts
            configMap:
              name: shutdown-pods-scripts
              defaultMode: 0777
          serviceAccountName: shutdown-pod-sa
          containers:
          - name: zombie-killer
            image: bitnami/kubectl
            imagePullPolicy: IfNotPresent
            command:
              - "/bin/sh"
            args:
              - "-c"
              - "/scripts/podCleaner.sh"
            volumeMounts:
              - name: scripts
                mountPath: "/scripts"
                readOnly: true
          restartPolicy: OnFailure
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: shutdown-pod-cleaner
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["delete", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: shutdown-pod-cleaner-cluster
  namespace: kube-system
subjects:
- kind: ServiceAccount
  name: shutdown-pod-sa
  namespace: kube-system
roleRef:
  kind: ClusterRole
  name: shutdown-pod-cleaner
  apiGroup: ""
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: shutdown-pod-sa
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: shutdown-pods-scripts
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
data:
  podCleaner.sh: |
    #!/bin/sh
    if [ $(kubectl get pods --all-namespaces --ignore-not-found=true | grep Shutdown | wc -l) -ge 1 ]
    then
    kubectl get pods -A | grep Shutdown | awk '{print $1,$2}' | xargs -n2 sh -c 'kubectl delete pod -n $0 $1 --ignore-not-found=true'
    else
    echo "no shutdown pods to clean"
    fi
</code>```

Body:
My take on this problem looks something like this (inspiration from other solutions here):

# Delete all shutdown pods. This is common problem on kubernetes using preemptible nodes on gke
# why awk, not failed pods: https://github.com/kubernetes/kubernetes/issues/54525#issuecomment-340035375
# due fact failed will delete evicted pods, that will complicate pod troubleshooting

---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: del-shutdown-pods
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
spec:
  schedule: "*/1 * * * *"
  successfulJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        metadata:
          labels:
            app: shutdown-pod-cleaner
        spec:
          volumes:
          - name: scripts
            configMap:
              name: shutdown-pods-scripts
              defaultMode: 0777
          serviceAccountName: shutdown-pod-sa
          containers:
          - name: zombie-killer
            image: bitnami/kubectl
            imagePullPolicy: IfNotPresent
            command:
              - "/bin/sh"
            args:
              - "-c"
              - "/scripts/podCleaner.sh"
            volumeMounts:
              - name: scripts
                mountPath: "/scripts"
                readOnly: true
          restartPolicy: OnFailure
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: shutdown-pod-cleaner
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["delete", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: shutdown-pod-cleaner-cluster
  namespace: kube-system
subjects:
- kind: ServiceAccount
  name: shutdown-pod-sa
  namespace: kube-system
roleRef:
  kind: ClusterRole
  name: shutdown-pod-cleaner
  apiGroup: ""
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: shutdown-pod-sa
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: shutdown-pods-scripts
  namespace: kube-system
  labels:
    app: shutdown-pod-cleaner
data:
  podCleaner.sh: |
    #!/bin/sh
    if [ $(kubectl get pods --all-namespaces --ignore-not-found=true | grep Shutdown | wc -l) -ge 1 ]
    then
    kubectl get pods -A | grep Shutdown | awk '{print $1,$2}' | xargs -n2 sh -c 'kubectl delete pod -n $0 $1 --ignore-not-found=true'
    else
    echo "no shutdown pods to clean"
    fi


问:
Add my own class file in ASP.NET MVC, and it couldn't be referenced?
I am currently stuck trying to add my own class file into ASP.NET MVC project, so it could
be referenced by my controller. But Visual studio 2010 always complain about "The type or name 'Products' could not be found (are your missing a using directive or assembly reference?)

I am not sure where to put my class file and tried add the class to Models or Controllers directory, and it wouldn't work either. My the class is under the right namespace, and I did reference the Models namespace in my Controller. It could be something obvious, but I couldn't get it working:(

答: Ensure the namespace of your class is correct.</p>


问:
Ansible where set ansible_user and ansible_ssh_pass in role
I am creating my first role in ansible to install packages through apt as it is a task I usually do on a daily basis.

```<code>apt
├── apt_install_package.yaml
├── server.yaml
├── tasks
│   └── main.yaml
└── vars
    └── main.yaml

# file: apt_install_package.yaml

- name: apt role
  hosts: server
  gather_facts: no
  become: yes
  roles:
  - apt

# tasks
- name: install package
  apt:
   name: "{{ package }}"
   state: present
   update_cache:  True
  with_items: "{{ package }}"

#vars
---
package:
  - nginx
  - supervisor

#inventory
---
server:
  hosts:
    new-server:
      ansible_host: 10.54.x.x

</code>```

In order to install the packages I must indicate a user of ssh but I do not know where to indicate it.

My idea is to indicate parameters with variables, something similar to this

```<code>  ansible_user: "{{ myuser }}"
  ansible_ssh_pass: "{{ mypass }}"
  ansible_become_pass: "{{ mypass }}"
</code>```

Any sugestions??

Regards,

答:
As per the latest documentation from Ansible regarding inventory sources, an SSH password can be configured using the ansible_password keyword while an SSH user is specified by ansible_user keyword, for any given host or host group entry.

It is worth mentioning that in order to implement SSH password login for hosts with Ansible, the sshpass program is required on the controller. Any plays will otherwise fail due to an error injecting the password while initializing connections.

Define these keywords within your existing inventory in the following manner:

```<code>#inventory
---
server:
  hosts:
    new-server:
      ansible_host: 10.54.x.x
      ansible_user: <username>
      ansible_password: <password>
      ansible_become_password; <password>

</code>```

The YAML plugin will parse your host configuration parameters from the inventory source and they will be appended host/group variables used for establishing an SSH connection.

The major disadvantage in this scenario is the fact that your authentication secrets will be stored in plain text, and usually Ansible is IaC committed to source control repositories. Unacceptable in production environments.

Consider using a lookup plugin such as env or file to render password secrets dynamically from the controller and prevent leakage.

```<code>#inventory
---
server:
  hosts:
    new-server:
      ansible_host: 10.54.x.x
      ansible_user: "{{ lookup('env', 'MY_SECRET_ANSIBLE_USER') }}"
      ansible_password: "{{ lookup('file', '/path/to/password') }}"
      ansible_become_password; "{{ lookup('env', 'MY_SECRET_BECOME_PASSWORD') }}"

</code>```

Other lookup plugins may also be of use to you depending on your use-case, and can be further researched here.

Alternatively, you could designate a default remote connection user, connection user password, and become password separately within your Ansible configuration file, usually located at /etc/ansible/ansible.cfg.

Read more about available configuration options in Ansible here.

All three mentioned configuration options can be specified under the [defaults] INI section as:

remote_user: default connection username

connection_password_file: default connection password file

become_password_file: default become password file

NOTE: connection_password_file  and become_password_file must be a filesystem path containing the password with which Ansible should use to login or escalate privileges. Storing a default password as plain-text string within the configuration file is not supported.

Another option involves environment variables being present at the time of playbook execution. Either export or pass them explicitly via the command line at the time of playbook execution.

ANSIBLE_REMOTE_USER: default connection username

ANSIBLE_CONNECTION_PASSWORD_FILE: default connection password file

ANSIBLE_BECOME_PASSWORD_FILE: default become password file

Such as the following:

ANSIBLE_BECOME_PASSWORD_FILE="/path/to/become_password" ansible-playbook ...

This approach is considerably less efficient unless you update the shell profile of the Ansible run user on the controller to set these variables upon login automatically. Generally not recommended for sensitive data such as passwords.

In regards to security, SSH key-pair authentication is preferred whenever possible. However, the second best approach would be to vault the sensitive passwords using ansible-vault.

Vault allows you to encrypt data at rest, and reference it within inventory/plays without risk of compromise.

Review this link to gain understanding of available procedures and get started.

Body:
I am creating my first role in ansible to install packages through apt as it is a task I usually do on a daily basis.

apt
├── apt_install_package.yaml
├── server.yaml
├── tasks
│   └── main.yaml
└── vars
    └── main.yaml

# file: apt_install_package.yaml

- name: apt role
  hosts: server
  gather_facts: no
  become: yes
  roles:
  - apt

# tasks
- name: install package
  apt:
   name: "{{ package }}"
   state: present
   update_cache:  True
  with_items: "{{ package }}"

#vars
---
package:
  - nginx
  - supervisor

#inventory
---
server:
  hosts:
    new-server:
      ansible_host: 10.54.x.x

In order to install the packages I must indicate a user of ssh but I do not know where to indicate it.

My idea is to indicate parameters with variables, something similar to this

  ansible_user: "{{ myuser }}"
  ansible_ssh_pass: "{{ mypass }}"
  ansible_become_pass: "{{ mypass }}"

Any sugestions??

Regards,

Body:
As per the latest documentation from Ansible regarding inventory sources, an SSH password can be configured using the ansible_password keyword while an SSH user is specified by ansible_user keyword, for any given host or host group entry.

It is worth mentioning that in order to implement SSH password login for hosts with Ansible, the sshpass program is required on the controller. Any plays will otherwise fail due to an error injecting the password while initializing connections.

Define these keywords within your existing inventory in the following manner:

#inventory
---
server:
  hosts:
    new-server:
      ansible_host: 10.54.x.x
      ansible_user: <username>
      ansible_password: <password>
      ansible_become_password; <password>

The YAML plugin will parse your host configuration parameters from the inventory source and they will be appended host/group variables used for establishing an SSH connection.

The major disadvantage in this scenario is the fact that your authentication secrets will be stored in plain text, and usually Ansible is IaC committed to source control repositories. Unacceptable in production environments.

Consider using a lookup plugin such as env or file to render password secrets dynamically from the controller and prevent leakage.

#inventory
---
server:
  hosts:
    new-server:
      ansible_host: 10.54.x.x
      ansible_user: "{{ lookup('env', 'MY_SECRET_ANSIBLE_USER') }}"
      ansible_password: "{{ lookup('file', '/path/to/password') }}"
      ansible_become_password; "{{ lookup('env', 'MY_SECRET_BECOME_PASSWORD') }}"

Other lookup plugins may also be of use to you depending on your use-case, and can be further researched here.

Alternatively, you could designate a default remote connection user, connection user password, and become password separately within your Ansible configuration file, usually located at /etc/ansible/ansible.cfg.

Read more about available configuration options in Ansible here.

All three mentioned configuration options can be specified under the [defaults] INI section as:

remote_user: default connection username

connection_password_file: default connection password file

become_password_file: default become password file

NOTE: connection_password_file  and become_password_file must be a filesystem path containing the password with which Ansible should use to login or escalate privileges. Storing a default password as plain-text string within the configuration file is not supported.

Another option involves environment variables being present at the time of playbook execution. Either export or pass them explicitly via the command line at the time of playbook execution.

ANSIBLE_REMOTE_USER: default connection username

ANSIBLE_CONNECTION_PASSWORD_FILE: default connection password file

ANSIBLE_BECOME_PASSWORD_FILE: default become password file

Such as the following:

ANSIBLE_BECOME_PASSWORD_FILE="/path/to/become_password" ansible-playbook ...

This approach is considerably less efficient unless you update the shell profile of the Ansible run user on the controller to set these variables upon login automatically. Generally not recommended for sensitive data such as passwords.

In regards to security, SSH key-pair authentication is preferred whenever possible. However, the second best approach would be to vault the sensitive passwords using ansible-vault.

Vault allows you to encrypt data at rest, and reference it within inventory/plays without risk of compromise.

Review this link to gain understanding of available procedures and get started.


问:
Read write an image with the GL_ARB_fragment_shader_interlock extension
I am testing whether the GL_ARB_fragment_shader_interlock extension can execute the critical section code of the same pixel position in the order of instance rendering. I used instanced rendering to draw five translucent planes (instances in order from farthest to nearer) and the result is the same as the fixed pipeline blending result (the blending result is random without this extension). But one problem is that there will be an extra line in the middle of each plane (not when using fixed pipeline blending). I found that the adjacent sides of the triangle generating the fragments twice. But rasterization should ensure that adjacent triangles do not have overlapping pixels. How to solve this please? I don't know where I went wrong, here is the code and result, please enlighten me!

The GLSL code:

```<code>#version 450 core
#extension GL_ARB_fragment_shader_interlock : require

//out vec4 Color_;

in vec4 v2f_Color;

layout(binding = 0, rgba16f) uniform image2D uColorTex;

void main()
{
    beginInvocationInterlockARB();

    vec4 color = imageLoad(uColorTex, ivec2(gl_FragCoord.xy));
    color = (1 - v2f_Color.a) * color + v2f_Color * v2f_Color.a;
    imageStore(uColorTex, ivec2(gl_FragCoord.xy), color);

    endInvocationInterlockARB();

    //Color_ = v2f_Color;
}
</code>```

Tthe result using extension to read write an image manually:

The result using fixed pipeline blending:

答:
I am a bit suspicious of the ivec2(gl_FragCoord.xy). This is doing a conversion from floating-point to an integer, and it could be the case that it gets rounded in different directions between the different triangles. This might explain not only the overlap, but why there's a missing top-left pixel in one of the squares.

Judging by the spec, ivec2(gl_FragCoord.xy) should be equivalent to ivec2(trunc(gl_FragCoord.xy)), which really ought to be consistent, but maybe the implementation is bad...

You might want to try:

ivec2(round(gl_FragCoord.xy))

ivec2(round(gl_FragCoord.xy + 0.5))

Body:
I am testing whether the GL_ARB_fragment_shader_interlock extension can execute the critical section code of the same pixel position in the order of instance rendering. I used instanced rendering to draw five translucent planes (instances in order from farthest to nearer) and the result is the same as the fixed pipeline blending result (the blending result is random without this extension). But one problem is that there will be an extra line in the middle of each plane (not when using fixed pipeline blending). I found that the adjacent sides of the triangle generating the fragments twice. But rasterization should ensure that adjacent triangles do not have overlapping pixels. How to solve this please? I don't know where I went wrong, here is the code and result, please enlighten me!

The GLSL code:

#version 450 core
#extension GL_ARB_fragment_shader_interlock : require

//out vec4 Color_;

in vec4 v2f_Color;

layout(binding = 0, rgba16f) uniform image2D uColorTex;

void main()
{
    beginInvocationInterlockARB();

    vec4 color = imageLoad(uColorTex, ivec2(gl_FragCoord.xy));
    color = (1 - v2f_Color.a) * color + v2f_Color * v2f_Color.a;
    imageStore(uColorTex, ivec2(gl_FragCoord.xy), color);

    endInvocationInterlockARB();

    //Color_ = v2f_Color;
}

Tthe result using extension to read write an image manually:

The result using fixed pipeline blending:


问:
Kotlinx.Serialization deserializing dates
I'm having a hard time finding documentation on how to deserialize date fields.
How do i achieve this? Most solutions i found on SO don't work or they use classes that are no longer available

```<code>@Serializable
data class Dashboard(
    val someNumber: Int,
    val someDate: Date? // Custom Deserialization from unix timestamp
)
</code>```

EDIT: Most solution i found use PrimitiveSerialDescriptor which seems to be not available

答:
Do not use Date, but use Instant or LocalDateTime instead, you need to add this in build.gradle file

implementation "org.jetbrains.kotlinx:kotlinx-datetime:0.3.2"
```

read more about it in this link:
https://github.com/Kotlin/kotlinx-datetime

This will automatically Serializable and also work in KMM

Body:
I'm having a hard time finding documentation on how to deserialize date fields.
How do i achieve this? Most solutions i found on SO don't work or they use classes that are no longer available

@Serializable
data class Dashboard(
    val someNumber: Int,
    val someDate: Date? // Custom Deserialization from unix timestamp
)

EDIT: Most solution i found use PrimitiveSerialDescriptor which seems to be not available

Body:
Do not use Date, but use Instant or LocalDateTime instead, you need to add this in build.gradle file

implementation "org.jetbrains.kotlinx:kotlinx-datetime:0.3.2"

read more about it in this link:
https://github.com/Kotlin/kotlinx-datetime

This will automatically Serializable and also work in KMM


问:
How to verify the HMAC in this Python cryptography code?
I am studying cryptography in Python and here is a Python 3 practice problem which is supposed to return "yes" as the input and output should match. Please tell me the right way of the second person (Hardy) to verify the message while using HMAC? I tried compare_digest() and base64decode but it doesn't work.

Question-
Laurel and Hardy are exchanging messages. However, Hardy is unsure about whether he is getting messages from Laurel. The following code is a simulation of HMAC even though the message and the key are the same, the HMAC is different. Modify the code so that Hardy knows with a guarantee that he has received the message from Laurel.

Code-

```<code>import hashlib
import base64

# Laurel and Hardy share a secret key
key = "apple".encode()

# Laurel sends Hardy a message---->
def laurel_to_hardy():
    message = input()
    msg = message.encode()
    #Laurel sends...
    #Laurel also sends hmac...

    sha256 = hashlib.sha256()
    sha256.update(msg)
    sha256.update(key)
    hmac = sha256.digest()

    return msg, hmac

#Verification by Hardy---------->
def hardy_verification(msg, hmac):
    #Hardy receives the message...
    #Hardy starts verification...

    # 000 PLEASE SUGGEST HERE#

    sha256 = hashlib.sha256()
    sha256.update(key)
    sha256.update(msg)
    hmac_hardy = sha256.digest()

    #Hardy receives
    if hmac_hardy == hmac:
        return "yes"
    else:
        return "no"
# Print ------>

msg_rec, hmac_rec = laurel_to_hardy()
print(hardy_verification(msg_rec, hmac_rec))

</code>```

Thank you!

答:
not an expert here but have a look at what this code outputs:</p>
```<code>import hashlib

import copy

a = 'ABC'

a = a.encode()

h1 = hashlib.sha256(a)

b = copy.copy(a)

h2 = hashlib.sha256(b)

print(h1)

print(h2)

print(h1.digest())

print(h2.digest())

print(h1 == h2)

print(h1.digest() == h2.digest())

a = 'DDD'

c ='ooo'

a = a.encode()

c = c.encode()

h1 = hashlib.sha256(a)

h1.update(c)

b = copy.copy(a)

d = copy.copy(c)

h2 = hashlib.sha256(b)

h2.update(d)

print(h1)

print(h2)

print(h1.digest())

print(h2.digest())

print(h1 == h2)

print(h1.digest() == h2.digest())

</code>```

Body:
I am studying cryptography in Python and here is a Python 3 practice problem which is supposed to return "yes" as the input and output should match. Please tell me the right way of the second person (Hardy) to verify the message while using HMAC? I tried compare_digest() and base64decode but it doesn't work.

Question-
Laurel and Hardy are exchanging messages. However, Hardy is unsure about whether he is getting messages from Laurel. The following code is a simulation of HMAC even though the message and the key are the same, the HMAC is different. Modify the code so that Hardy knows with a guarantee that he has received the message from Laurel.

Code-

import hashlib
import base64

# Laurel and Hardy share a secret key
key = "apple".encode()

# Laurel sends Hardy a message---->
def laurel_to_hardy():
    message = input()
    msg = message.encode()
    #Laurel sends...
    #Laurel also sends hmac...

    sha256 = hashlib.sha256()
    sha256.update(msg)
    sha256.update(key)
    hmac = sha256.digest()

    return msg, hmac

#Verification by Hardy---------->
def hardy_verification(msg, hmac):
    #Hardy receives the message...
    #Hardy starts verification...

    # 000 PLEASE SUGGEST HERE#

    sha256 = hashlib.sha256()
    sha256.update(key)
    sha256.update(msg)
    hmac_hardy = sha256.digest()

    #Hardy receives
    if hmac_hardy == hmac:
        return "yes"
    else:
        return "no"
# Print ------>

msg_rec, hmac_rec = laurel_to_hardy()
print(hardy_verification(msg_rec, hmac_rec))

Thank you!

Body:
not an expert here but have a look at what this code outputs:

import hashlib

import copy

a = 'ABC'

a = a.encode()

h1 = hashlib.sha256(a)

b = copy.copy(a)

h2 = hashlib.sha256(b)

print(h1)

print(h2)

print(h1.digest())

print(h2.digest())

print(h1 == h2)

print(h1.digest() == h2.digest())

a = 'DDD'

c ='ooo'

a = a.encode()

c = c.encode()

h1 = hashlib.sha256(a)

h1.update(c)

b = copy.copy(a)

d = copy.copy(c)

h2 = hashlib.sha256(b)

h2.update(d)

print(h1)

print(h2)

print(h1.digest())

print(h2.digest())

print(h1 == h2)

print(h1.digest() == h2.digest())


问:
Discrepancy in Javascript Intl.DateTimeFormat() Outputs for the Islamic (Hijri) Calendar between 'islamic' and 'ar-SA'
The 3rd March 2022 is the end of this Hijri Month (month of Rajab for this year 1443 AH); i.e. 30 Rajab 1443 AH.

The month of Rajab for the year 1443 AH is 30 days in accordance with the Islamic (Hijri) Calendar in accordance with all websites, applications, MS Office, and Windows calendars.

When using the javascript Intl.DateTimeFormat() to display the Islamic (Hijri) date for the 3 March 2022 using the islamic calendar option, it will give the Islamic Hijri Date of (1 Shaʻban 1443 AH). This result is one day after the month of Rajab (i.e. the 1st of the following month) and it calculated the month Rajab to be 29 days rather than 30 days.

However, if the option passed to the Intl.DateTimeFormat() is ar-SA (i.e. arabic-Saudi Arabia), it will give the correct result. This is strange because the ar-SA locale uses the Islamic (Hijri) calendar by default.

Is this an error/bug or is it the correct internal workings of javascript?

Is there a more robust method to get the Islamic Date in Javascript other than using the 'ar-SA' locale (but not using external libraries)?

See the code example below:

I have tested this in node and chrome and it gives the same resulting discrepancy.

let date = new Date("2022-03-03");
let options = {year:'numeric', month:'long',day:'numeric'};

let format = new Intl.DateTimeFormat('ar-SA-u-nu-latn', options);
console.log("3 March 2022 with 'ar-SA'         :"+format.format(date)+ " ==> means: 30 Rajab 1443 AH");

format = new Intl.DateTimeFormat('en-u-ca-islamic-nu-latn', options);
console.log("3 March 2022 with Islamic Calendar: "+format.format(date));```

答:
Following from the excellent information and data provided below by Justin Grant, I made a comparison of the output of the five (5) Islamic calendars:

islamic

islamic-umalqura

islamic-tbla

islamic-civil

islamic-rgsa

The comparison of the output was made over a period of 50 years (from 1 Jan 1980 to 31 Dec 2030).

The resulting output is as follows:

```<code>============================================================
islamic diff from islamic-tbla           :6369  days (34.19%)
islamic diff from islamic-rgsa           :0     days ( 0.00%)
islamic diff from islamic-umalqura       :11425 days (61.33%)
islamic diff from islamic-civil          :15919 days (85.46%)
------------------------------------------------------------
islamic-tbla diff from islamic-rgsa      :6369  days (34.19%)
islamic-tbla diff from islamic-umalqura  :10777 days (57.85%)
islamic-tbla diff from islamic-civil     :18628 days (100.00%)
-------------------------------------------------------------
islamic-rgsa diff from islamic-umalqura  :11425 days (61.33%)
islamic-rgsa diff from islamic-civil     :15919 days (85.46%)
-------------------------------------------------------------
islamic-umalqura diff from islamic-civil :9049  days (48.58%)
=============================================================
</code>```

The result gives the following general information:

The dates under the default islamic calendar always agree with the islamic-rgsa. Not sure if the default islamic uses the same code as the islamic rgsa or it selects the other types based on the region.

The dates under the islamic-civil calendar are the most different from all other calendar formats (between 85% to 100%).

The dates under the new islamic-umalqura calendar are in variance with the other calendars by around 50% to 62%.

From observations on some islamic sites and applications, the new islamic-umalqura calendar is the most commonly used Islamic calendar. It is also preferred in Europe and North America.

Because the locale ar-SA uses the islamic-umalqura calendar by default, the date outputs (and months length) of the ar-SA will differ from that of the islamic calendar in over 61% of the time.

The test code I have used is provided below, but please note that it needs about 25 seconds to give the output; please wait for it.

console.log("Comparing 50 years results under the 5 islamic calendar formats (from year 1980 to 2030)");
console.log("=".repeat(60));

let startDate = new Date("1980-01-01");  // date to start test from
let options   = {year: 'numeric', month: 'long', day: 'numeric'};
let d         = startDate;
let diff      = [0,0,0,0,0,0,0,0,0,0];  // array to hold the diff results
let totalDays = 18628;                  // total days approx 50 Gregorian years
for (let i=0; i<totalDays; i++) {
let dateIslamic     = new Intl.DateTimeFormat('en-u-ca-islamic'         ,options).format(d),
    dateIslamicTBLA = new Intl.DateTimeFormat('en-u-ca-islamic-tbla'    ,options).format(d),
    dateIslamicRGSA = new Intl.DateTimeFormat('en-u-ca-islamic-rgsa'    ,options).format(d),
    dateIslamicUMQ  = new Intl.DateTimeFormat('en-u-ca-islamic-umalqura',options).format(d),
    dateIslamicCIVL = new Intl.DateTimeFormat('en-u-ca-islamic-civil'   ,options).format(d);

if (dateIslamic != dateIslamicTBLA) diff[0]++;
if (dateIslamic != dateIslamicRGSA) diff[1]++;
if (dateIslamic != dateIslamicUMQ)  diff[2]++;
if (dateIslamic != dateIslamicCIVL) diff[3]++;

if (dateIslamicTBLA != dateIslamicRGSA) diff[4]++;
if (dateIslamicTBLA != dateIslamicUMQ)  diff[5]++;
if (dateIslamicTBLA != dateIslamicCIVL) diff[6]++;

if (dateIslamicRGSA != dateIslamicUMQ)  diff[7]++;
if (dateIslamicRGSA != dateIslamicCIVL) diff[8]++;

if (dateIslamicUMQ != dateIslamicCIVL)  diff[9]++;

d    = new Date(d.setDate(d.getDate() + 1)); // next day
}

console.log("islamic diff from islamic-tbla           :"+perc(0));
console.log("islamic diff from islamic-rgsa           :"+perc(1));
console.log("islamic diff from islamic-umalqura       :"+perc(2));
console.log("islamic diff from islamic-civil          :"+perc(3));
console.log("-".repeat(50));
console.log("islamic-tbla diff from islamic-rgsa      :"+perc(4));
console.log("islamic-tbla diff from islamic-umalqura  :"+perc(5));
console.log("islamic-tbla diff from islamic-civil     :"+perc(6));
console.log("-".repeat(50));
console.log("islamic-rgsa diff from islamic-umalqura  :"+perc(7));
console.log("islamic-rgsa diff from islamic-civil     :"+perc(8));
console.log("-".repeat(50));
console.log("islamic-umalqura diff from islamic-civil :"+perc(9));

function perc(n) {return + diff[n]+" days (" +((diff[n]/totalDays)*100).toFixed(2)+"%)";}```

Body:
Following from the excellent information and data provided below by Justin Grant, I made a comparison of the output of the five (5) Islamic calendars:

islamic

islamic-umalqura

islamic-tbla

islamic-civil

islamic-rgsa

The comparison of the output was made over a period of 50 years (from 1 Jan 1980 to 31 Dec 2030).

The resulting output is as follows:

============================================================
islamic diff from islamic-tbla           :6369  days (34.19%)
islamic diff from islamic-rgsa           :0     days ( 0.00%)
islamic diff from islamic-umalqura       :11425 days (61.33%)
islamic diff from islamic-civil          :15919 days (85.46%)
------------------------------------------------------------
islamic-tbla diff from islamic-rgsa      :6369  days (34.19%)
islamic-tbla diff from islamic-umalqura  :10777 days (57.85%)
islamic-tbla diff from islamic-civil     :18628 days (100.00%)
-------------------------------------------------------------
islamic-rgsa diff from islamic-umalqura  :11425 days (61.33%)
islamic-rgsa diff from islamic-civil     :15919 days (85.46%)
-------------------------------------------------------------
islamic-umalqura diff from islamic-civil :9049  days (48.58%)
=============================================================

The result gives the following general information:

The dates under the default islamic calendar always agree with the islamic-rgsa. Not sure if the default islamic uses the same code as the islamic rgsa or it selects the other types based on the region.

The dates under the islamic-civil calendar are the most different from all other calendar formats (between 85% to 100%).

The dates under the new islamic-umalqura calendar are in variance with the other calendars by around 50% to 62%.

From observations on some islamic sites and applications, the new islamic-umalqura calendar is the most commonly used Islamic calendar. It is also preferred in Europe and North America.

Because the locale ar-SA uses the islamic-umalqura calendar by default, the date outputs (and months length) of the ar-SA will differ from that of the islamic calendar in over 61% of the time.

The test code I have used is provided below, but please note that it needs about 25 seconds to give the output; please wait for it.

console.log("Comparing 50 years results under the 5 islamic calendar formats (from year 1980 to 2030)");
console.log("=".repeat(60));

let startDate = new Date("1980-01-01");  // date to start test from
let options   = {year: 'numeric', month: 'long', day: 'numeric'};
let d         = startDate;
let diff      = [0,0,0,0,0,0,0,0,0,0];  // array to hold the diff results
let totalDays = 18628;                  // total days approx 50 Gregorian years
for (let i=0; i<totalDays; i++) {
let dateIslamic     = new Intl.DateTimeFormat('en-u-ca-islamic'         ,options).format(d),
    dateIslamicTBLA = new Intl.DateTimeFormat('en-u-ca-islamic-tbla'    ,options).format(d),
    dateIslamicRGSA = new Intl.DateTimeFormat('en-u-ca-islamic-rgsa'    ,options).format(d),
    dateIslamicUMQ  = new Intl.DateTimeFormat('en-u-ca-islamic-umalqura',options).format(d),
    dateIslamicCIVL = new Intl.DateTimeFormat('en-u-ca-islamic-civil'   ,options).format(d);

if (dateIslamic != dateIslamicTBLA) diff[0]++;
if (dateIslamic != dateIslamicRGSA) diff[1]++;
if (dateIslamic != dateIslamicUMQ)  diff[2]++;
if (dateIslamic != dateIslamicCIVL) diff[3]++;

if (dateIslamicTBLA != dateIslamicRGSA) diff[4]++;
if (dateIslamicTBLA != dateIslamicUMQ)  diff[5]++;
if (dateIslamicTBLA != dateIslamicCIVL) diff[6]++;

if (dateIslamicRGSA != dateIslamicUMQ)  diff[7]++;
if (dateIslamicRGSA != dateIslamicCIVL) diff[8]++;

if (dateIslamicUMQ != dateIslamicCIVL)  diff[9]++;

d    = new Date(d.setDate(d.getDate() + 1)); // next day
}

console.log("islamic diff from islamic-tbla           :"+perc(0));
console.log("islamic diff from islamic-rgsa           :"+perc(1));
console.log("islamic diff from islamic-umalqura       :"+perc(2));
console.log("islamic diff from islamic-civil          :"+perc(3));
console.log("-".repeat(50));
console.log("islamic-tbla diff from islamic-rgsa      :"+perc(4));
console.log("islamic-tbla diff from islamic-umalqura  :"+perc(5));
console.log("islamic-tbla diff from islamic-civil     :"+perc(6));
console.log("-".repeat(50));
console.log("islamic-rgsa diff from islamic-umalqura  :"+perc(7));
console.log("islamic-rgsa diff from islamic-civil     :"+perc(8));
console.log("-".repeat(50));
console.log("islamic-umalqura diff from islamic-civil :"+perc(9));

function perc(n) {return + diff[n]+" days (" +((diff[n]/totalDays)*100).toFixed(2)+"%)";}


问:
Find the possible routes using Recursion in Python. Note [ I need this to be done without any module]
```<code>locations = ["loc1", "loc2", "loc3", "loc4", "loc5"]
</code>```

Suppose this is the list of some given locations now I want to make all the possible arrangements but make sure that all arrangements should be with the loc1 at the fixed place.
e. g

```<code>["loc1", "loc3", "loc2", "loc4", "loc5"]
["loc1", "loc3", "loc4", "loc2", "loc5"]
</code>```

and so on..
can you please tell me how the algorithm looks like for this specific problem using recursive function.

答:
You can do it with itertools.permutations:

```<code>from itertools import permutations
locations = ["loc1", "loc2", "loc3", "loc4", "loc5"]

permutated_locations = [[locations[0]] + list(i) for i in permutations(locations[1:])]

for l in permutated_locations:
    print(l)
</code>```

Output:

```<code>['loc1', 'loc2', 'loc5', 'loc4', 'loc3']
['loc1', 'loc3', 'loc2', 'loc4', 'loc5']
['loc1', 'loc3', 'loc2', 'loc5', 'loc4']
['loc1', 'loc3', 'loc4', 'loc2', 'loc5']
['loc1', 'loc3', 'loc4', 'loc5', 'loc2']
['loc1', 'loc3', 'loc5', 'loc2', 'loc4']
['loc1', 'loc3', 'loc5', 'loc4', 'loc2']
['loc1', 'loc4', 'loc2', 'loc3', 'loc5']
['loc1', 'loc4', 'loc2', 'loc5', 'loc3']
['loc1', 'loc4', 'loc3', 'loc2', 'loc5']
['loc1', 'loc4', 'loc3', 'loc5', 'loc2']
['loc1', 'loc4', 'loc5', 'loc2', 'loc3']
['loc1', 'loc4', 'loc5', 'loc3', 'loc2']
['loc1', 'loc5', 'loc2', 'loc3', 'loc4']
['loc1', 'loc5', 'loc2', 'loc4', 'loc3']
['loc1', 'loc5', 'loc3', 'loc2', 'loc4']
['loc1', 'loc5', 'loc3', 'loc4', 'loc2']
['loc1', 'loc5', 'loc4', 'loc2', 'loc3']
['loc1', 'loc5', 'loc4', 'loc3', 'loc2']
</code>```

Body:
locations = ["loc1", "loc2", "loc3", "loc4", "loc5"]

Suppose this is the list of some given locations now I want to make all the possible arrangements but make sure that all arrangements should be with the loc1 at the fixed place.
e. g

["loc1", "loc3", "loc2", "loc4", "loc5"]
["loc1", "loc3", "loc4", "loc2", "loc5"]

and so on..
can you please tell me how the algorithm looks like for this specific problem using recursive function.

Body:
You can do it with itertools.permutations:

from itertools import permutations
locations = ["loc1", "loc2", "loc3", "loc4", "loc5"]

permutated_locations = [[locations[0]] + list(i) for i in permutations(locations[1:])]

for l in permutated_locations:
    print(l)

Output:

['loc1', 'loc2', 'loc5', 'loc4', 'loc3']
['loc1', 'loc3', 'loc2', 'loc4', 'loc5']
['loc1', 'loc3', 'loc2', 'loc5', 'loc4']
['loc1', 'loc3', 'loc4', 'loc2', 'loc5']
['loc1', 'loc3', 'loc4', 'loc5', 'loc2']
['loc1', 'loc3', 'loc5', 'loc2', 'loc4']
['loc1', 'loc3', 'loc5', 'loc4', 'loc2']
['loc1', 'loc4', 'loc2', 'loc3', 'loc5']
['loc1', 'loc4', 'loc2', 'loc5', 'loc3']
['loc1', 'loc4', 'loc3', 'loc2', 'loc5']
['loc1', 'loc4', 'loc3', 'loc5', 'loc2']
['loc1', 'loc4', 'loc5', 'loc2', 'loc3']
['loc1', 'loc4', 'loc5', 'loc3', 'loc2']
['loc1', 'loc5', 'loc2', 'loc3', 'loc4']
['loc1', 'loc5', 'loc2', 'loc4', 'loc3']
['loc1', 'loc5', 'loc3', 'loc2', 'loc4']
['loc1', 'loc5', 'loc3', 'loc4', 'loc2']
['loc1', 'loc5', 'loc4', 'loc2', 'loc3']
['loc1', 'loc5', 'loc4', 'loc3', 'loc2']


问:
loading foreign key data in drop down select name too slow
I'm trying to show foreign key data as a drop down list, but we have a big data, the problem is it takes too long to load page that has the drop down field with the foreign key, is there a way to load it part by part?
here is my models.py

```<code>class Vistor(models.Model):
admin = models.ForeignKey(User,on_delete=models.PROTECT,default=1)
full_name = models.CharField(max_length=150,verbose_name=_('full name'))
dob = models.DateField(max_length=14,verbose_name=_('dob'))
city = models.ForeignKey(City,on_delete=models.CASCADE,verbose_name=_('city'))

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information')
    ]

def __str__(self):
    return f'{self.full_name} - {self.city} - {self.dob}'
</code>```

and here is my views.py

```<code>def add_new_post(request):
    ...
    context = {
        'form':form,
        'room_number':room_number,
        'cities':City.objects.all(),
        'all_guests':Vistor.objects.all().order_by('-pk'), #the problem is here, has a big data
        }

    return render(request,'booking/add_booking.html',context)
</code>```

and here is my templates

            {% trans "full information" %}
            <select name="guestinfo-0" id="guestinfo-0" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white">
                <option value="-----">------</option>
                {% for c in all_guests %}
                <option value="{{ c.full_name }} - {{c.city}} - {{c.dob | date:'Y-m-d'}}">{{ c.full_name }} - {{c.city}} - {{c.dob | date:'Y-m-d'}}</option>
                {% endfor %}
            </select>

            {% trans "reason" %}
            <input type="text" name="reason-0" id="reason-0" value="" required class="w-full pr-2 pb-1  pt-6 bg-transparent focus:outline-none text-white">

        <button type='button' class="col-span-1 flex items-center justify-center groupinput relative bglightpurple mt-2 rounded-xl" onclick="remove_form(this,${form_no})"></button>

  ```

is there a way to load it part by part please ?
thank you so much for your helps ..

答:
You can use django-autocomplete-light along with leveraging Django forms to display that element.

This gives a searchable as well as scrollable dropdown that loads your data with a pagination type of concept.

Body:
I'm trying to show foreign key data as a drop down list, but we have a big data, the problem is it takes too long to load page that has the drop down field with the foreign key, is there a way to load it part by part?
here is my models.py

class Vistor(models.Model):
admin = models.ForeignKey(User,on_delete=models.PROTECT,default=1)
full_name = models.CharField(max_length=150,verbose_name=_('full name'))
dob = models.DateField(max_length=14,verbose_name=_('dob'))
city = models.ForeignKey(City,on_delete=models.CASCADE,verbose_name=_('city'))

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information')
    ]

def __str__(self):
    return f'{self.full_name} - {self.city} - {self.dob}'

and here is my views.py

def add_new_post(request):
    ...
    context = {
        'form':form,
        'room_number':room_number,
        'cities':City.objects.all(),
        'all_guests':Vistor.objects.all().order_by('-pk'), #the problem is here, has a big data
        }

    return render(request,'booking/add_booking.html',context)

and here is my templates

            {% trans "full information" %}
            <select name="guestinfo-0" id="guestinfo-0" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white">
                <option value="-----">------</option>
                {% for c in all_guests %}
                <option value="{{ c.full_name }} - {{c.city}} - {{c.dob | date:'Y-m-d'}}">{{ c.full_name }} - {{c.city}} - {{c.dob | date:'Y-m-d'}}</option>
                {% endfor %}
            </select>

            {% trans "reason" %}
            <input type="text" name="reason-0" id="reason-0" value="" required class="w-full pr-2 pb-1  pt-6 bg-transparent focus:outline-none text-white">

        <button type='button' class="col-span-1 flex items-center justify-center groupinput relative bglightpurple mt-2 rounded-xl" onclick="remove_form(this,${form_no})"></button>

is there a way to load it part by part please ?
thank you so much for your helps ..


问:
Popover AngularJs still shows even after setting its trigger to none
The 'Thanks' pop-over when clicking the thumbs up for the first time appears, but it is still appearing the second time the thumbs up is clicked even after setting its trigger to 'none'

Steps to reproduce:

Click any thumbs up, 'Thanks' pop-over will appear

Click anywhere outside such as white area to dismiss the 'Thanks' pop-over

Click again that thumbs up and the 'Thanks' pop-over is still appearing

In the code, I set my own custom directive to conditionally set the popover-trigger such that when thumbs up is clicked once, it will set the popover-trigger to 'none':
Inspected in Element tab that popover-trigger is really set to none.

Code in html:

```<code><span ng-click="sendFeedback(false, result.id)"
      uib-popover="Thanks"
      popover-trigger="'outsideClick'"
      ...
      my-directive
      shown="this.shown[result.id]">
</span>
</code>```

Code in controller:

```<code>feedbackApp.directive('myDirective', function () {
  return {
    restrict: 'A',
    scope: {
      shown: '=',
    },
    link: function(scope, element, attrs) {
      scope.$watch('shown', function(shown) {
          if (shown)
              attrs.$set('popover-trigger', "none");
          }
      });
    }
  };
});
</code>```

Bottom line is if the user intends to undo the thumbs up, the 'Thanks' pop-over should not appear

Here is my full code in public repo

答:
You try to change the DOM via injection attrs.$set('popover-trigger', "none") and this is not recognized by the compiled AngularUI template. You could recompile the template but this is not needed. Your approach is to complex for such simple requirement. Simply us the popover-enable option and you will be fine. You don't need to handle this inside a directive. Also $watch is not needed.

angular.module('demoApp', ['ui.bootstrap'])
    .controller('DemoCtrl', function ($scope, $compile) {

    $scope.popoverState = true;

    $scope.clicked = function () {
        $scope.popoverState = false;
    };

});
/* EOF */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap-tpls.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-calendar/1.0.0/calendar.js"></script>

<div ng-app="demoApp">
  <div ng-controller="DemoCtrl">
     <br />
     <br />
     <br />
     <button popover-placement="top"
        ng-click="clicked()"
        uib-popover="On the top"
        type="button"
        popover-enable="popoverState"
        class="btn btn-default ng-binding"
        my-directive>Popover top</button>
  </div>
</div></code>```

Body:
The 'Thanks' pop-over when clicking the thumbs up for the first time appears, but it is still appearing the second time the thumbs up is clicked even after setting its trigger to 'none'

Steps to reproduce:

Click any thumbs up, 'Thanks' pop-over will appear

Click anywhere outside such as white area to dismiss the 'Thanks' pop-over

Click again that thumbs up and the 'Thanks' pop-over is still appearing

In the code, I set my own custom directive to conditionally set the popover-trigger such that when thumbs up is clicked once, it will set the popover-trigger to 'none':
Inspected in Element tab that popover-trigger is really set to none.

Code in html:

Code in controller:

feedbackApp.directive('myDirective', function () {
  return {
    restrict: 'A',
    scope: {
      shown: '=',
    },
    link: function(scope, element, attrs) {
      scope.$watch('shown', function(shown) {
          if (shown)
              attrs.$set('popover-trigger', "none");
          }
      });
    }
  };
});

Bottom line is if the user intends to undo the thumbs up, the 'Thanks' pop-over should not appear

Here is my full code in public repo

Body:
You try to change the DOM via injection attrs.$set('popover-trigger', "none") and this is not recognized by the compiled AngularUI template. You could recompile the template but this is not needed. Your approach is to complex for such simple requirement. Simply us the popover-enable option and you will be fine. You don't need to handle this inside a directive. Also $watch is not needed.

angular.module('demoApp', ['ui.bootstrap'])
    .controller('DemoCtrl', function ($scope, $compile) {

    $scope.popoverState = true;

    $scope.clicked = function () {
        $scope.popoverState = false;
    };

});
/* EOF */

<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap-tpls.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-calendar/1.0.0/calendar.js"></script>

<div ng-app="demoApp">
  <div ng-controller="DemoCtrl">
     <br />
     <br />
     <br />
     <button popover-placement="top"
        ng-click="clicked()"
        uib-popover="On the top"
        type="button"
        popover-enable="popoverState"
        class="btn btn-default ng-binding"
        my-directive>Popover top</button>
  </div>
</div>