答:
Please see and run the code snippets for your desire output.

ul > li {
  color: grey;
  border-bottom: thin dashed grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li> Terms of Use </li>
  <li> Privacy Policy </li>
</ul></code>```

Updated with class mylist

ul.mylist > li {
  color: grey;
  border-bottom: thin dashed grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="mylist">
  <li> Terms of Use </li>
  <li> Privacy Policy </li>
</ul></code>```

Title: CSS unordered list with dotted full block width underline

Body:
How i can make an ordered list like the one in the screenshot?
What is important is to have a full width dotted underline per item.

Thank you
Sample ordered list

Body:
Please see and run the code snippets for your desire output.

ul > li {
  color: grey;
  border-bottom: thin dashed grey;
}

<ul>
  <li> Terms of Use </li>
  <li> Privacy Policy </li>
</ul>

Updated with class mylist

ul.mylist > li {
  color: grey;
  border-bottom: thin dashed grey;
}

<ul class="mylist">
  <li> Terms of Use </li>
  <li> Privacy Policy </li>
</ul>


来源: stackexchange

问:
Returning True or False from find command
I need to check if a given file, with specific filename, exists in a directory (including sub-directories), and then perform an action if it exists, and another if not.
Is there a way to use find command, returning True or False, as a condition for an if statement? I'm struggling to get it to work, but I don't know if it's just a problem of syntax or if there is a better way to approach the problem.

My specific problem is that I have a folder with lots of pictures in it, altogether. And I have a second folder where part of the same pictures are organized by subject on subfolders.
So I want to delete, in the first folder, all the pictures that already are in the second folder.

What I'm trying to do is:

```<code>for file in "/first/folder"/*; do
   filename=`basename $file`

   if [find /second/folder -name $filename]
   then
      rm $file
   fi
done
</code>```

答:
I don't know if it's just a problem of syntax or if there is a better way to approach the problem.

Yes there are syntax errors in your program. But there is no need to run find over and over for each file. Here is a more effective approach:

```<code>find <b>/second/folder</b> -type f -exec bash -c '
for fpath in "${@/#*\//"<b>/first/folder</b>/"}"; do
  if [[ -f $fpath ]]; then
    delete+=("$fpath")
  fi
done
echo rm -- "${delete[@]}"' _ {} +</code>```

Drop echo if its output looks good.

ContentLicense: CC BY-SA 4.0

Body:
I need to check if a given file, with specific filename, exists in a directory (including sub-directories), and then perform an action if it exists, and another if not.
Is there a way to use find command, returning True or False, as a condition for an if statement? I'm struggling to get it to work, but I don't know if it's just a problem of syntax or if there is a better way to approach the problem.

My specific problem is that I have a folder with lots of pictures in it, altogether. And I have a second folder where part of the same pictures are organized by subject on subfolders.
So I want to delete, in the first folder, all the pictures that already are in the second folder.

What I'm trying to do is:

for file in "/first/folder"/*; do
   filename=`basename $file`

   if [find /second/folder -name $filename]
   then
      rm $file
   fi
done

Body:
I don't know if it's just a problem of syntax or if there is a better way to approach the problem.

Yes there are syntax errors in your program. But there is no need to run find over and over for each file. Here is a more effective approach:

find /second/folder -type f -exec bash -c '
for fpath in "${@/#*\//"/first/folder/"}"; do
  if [[ -f $fpath ]]; then
    delete+=("$fpath")
  fi
done
echo rm -- "${delete[@]}"' _ {} +

Drop echo if its output looks good.


问:
Is it possible sccessing a subset of a WCF service operations
I have the following doubt:
Consider the following:

```<code>/* My service is formed by several subservices
   (subfunctionalities). Here is functionality 1 */
[ServiceContract]
public interface IMySubService1 {
   [OperationContract]
   int MyOp11(string opnd);
   [OperationContract]
   int MyOp12(stirng opnd);
}

/* My service is formed by several subservices
   (subfunctionalities). Here is functionality 2 */
[ServiceContract]
public interface IMySubService2 {
   [OperationContract]
   int MyOp21(string opnd);
   [OperationContract]
   int MyOp22(stirng opnd);
}

/* My service is formed by several subservices
   (subfunctionalities). Here is functionality 3 */
[ServiceContract]
public interface IMySubService3 {
   [OperationContract]
   int MyOp31(string opnd);
   [OperationContract]
   int MyOp32(stirng opnd);
}
</code>```

And the following:

```<code>/* My server will implement a complex great
   service made of the previously introduced subservices. */
[ServiceContract]
public interface IMyService : IMySubService1, IMySubService2, IMySubService3 {
}
</code>```

well, I will implement my service:

```<code>// Implementing the service
public class MyService : IMyService {
   ...
}
</code>```

OK! Up until now, nothing strange!
My service will be hosted on a server and I am happy :)
The service is hosted (as example) on a svc file, but remember the service is IMyService.

Now let's get to the point:
In my client I would like to create a client in order to get access JUST TO A SUBSET of my service. Given that my service is the usion of three subservices, I would like to access only one subservice.

For example, my client is interested in IMySubService1
Can I do the following?

```<code>ServiceEndpoint httpEndpoint = new ServiceEndpoint(
   ContractDescription.GetContract(typeof(IMySubService1)),
   new BasicHttpBinding(),
   new EndpointAddress("http://tempuri.org/MyService.svc/ServiceCall")
   );
ChannelFactory<IMySubService1> channelFactory =
   new ChannelFactory<IMySubService1>(httpEndpoint);

IMySubService1svc = channelFactory.CreateChannel();
/* Calling methods in IMySubService1 */
int i1 = svc.MyOp11("A string");
int i2 = svc.MyOp12("Another string");
int i3 = svc.MyOp11("And another string");
int i4 = svc.MyOp12("In the end a string");
int i5 = svc.MyOp11("The final string");
</code>```

Is this possible???

答:
OK!
Finally I tried it!

IT CAN BE DONE!!! Exactly in the same manner as I showed in my question.

ContentLicense: CC BY-SA 3.0

Body:
I have the following doubt:
Consider the following:

/* My service is formed by several subservices
   (subfunctionalities). Here is functionality 1 */
[ServiceContract]
public interface IMySubService1 {
   [OperationContract]
   int MyOp11(string opnd);
   [OperationContract]
   int MyOp12(stirng opnd);
}

/* My service is formed by several subservices
   (subfunctionalities). Here is functionality 2 */
[ServiceContract]
public interface IMySubService2 {
   [OperationContract]
   int MyOp21(string opnd);
   [OperationContract]
   int MyOp22(stirng opnd);
}

/* My service is formed by several subservices
   (subfunctionalities). Here is functionality 3 */
[ServiceContract]
public interface IMySubService3 {
   [OperationContract]
   int MyOp31(string opnd);
   [OperationContract]
   int MyOp32(stirng opnd);
}

And the following:

/* My server will implement a complex great
   service made of the previously introduced subservices. */
[ServiceContract]
public interface IMyService : IMySubService1, IMySubService2, IMySubService3 {
}

well, I will implement my service:

// Implementing the service
public class MyService : IMyService {
   ...
}

OK! Up until now, nothing strange!
My service will be hosted on a server and I am happy :)
The service is hosted (as example) on a svc file, but remember the service is IMyService.

Now let's get to the point:
In my client I would like to create a client in order to get access JUST TO A SUBSET of my service. Given that my service is the usion of three subservices, I would like to access only one subservice.

For example, my client is interested in IMySubService1
Can I do the following?

ServiceEndpoint httpEndpoint = new ServiceEndpoint(
   ContractDescription.GetContract(typeof(IMySubService1)),
   new BasicHttpBinding(),
   new EndpointAddress("http://tempuri.org/MyService.svc/ServiceCall")
   );
ChannelFactory<IMySubService1> channelFactory =
   new ChannelFactory<IMySubService1>(httpEndpoint);

IMySubService1svc = channelFactory.CreateChannel();
/* Calling methods in IMySubService1 */
int i1 = svc.MyOp11("A string");
int i2 = svc.MyOp12("Another string");
int i3 = svc.MyOp11("And another string");
int i4 = svc.MyOp12("In the end a string");
int i5 = svc.MyOp11("The final string");

Is this possible???


问:
splitting a string using strtok()
I have a string I would like to split into two different strings, the delimiter is $$$.
For instance: milk $$$ 45
On the left side is the product name and on the right is its quantity.
I've used strtok to split the string but I can't extract the number unfortunately.

```<code>int num;
char *token = strtok(str, DELIMITER);
printf("%s\n", token);
strcpy(component->name, token);
char *number = strtok(NULL, "       ");
num = atoi(number);
printf("%s\n", number);
</code>```

The printf calls are for debugging.

答:
You want to split the input string on a delimiter string $$$: strtok() is not a precise solution for this because it does not search for a delimiter string, but considers any sequence of characters from the delimiter string as a delimiter. Passing "$$$" is equivalent to passing just "$". since the second call uses a different set of delimiters (white space), the strtok() will return $$ as the second token, so you get 0 after conversion with atoi().

There are different ways to address this problem.

use "$" or "$ \t" as the delimiter set for the second call to strtok(). This is sloppy but will work in your case because the second field does not contain embedded spaces and atoi ignores leading white space.

```<code>int num;
char *token = strtok(str, "$");
if (token) {
    printf("%s\n", token);
    strcpy(component->name, token);
    char *number = strtok(NULL, "$");
    if (number) {
        num = atoi(number);
        printf("%s\n", number);
    }
}
</code>```

use strstr to locate the delimiter string and skip that to get the second part:

```<code>int num;
char *token = str;
char *p = strstr(str, "$$$");
if (p) {
    p = '\0';
    p += 3;
}
printf("%s\n", token);
strcpy(component->name, token);
char *number = p;
if (number) {
    num = atoi(number);
    printf("%s\n", number);
}
</code>```

write a custom function to split the string on a delimiter string, and trim white space for consistency:

```<code>#include <string.h>
#include <ctype.h>

char *trim_token(char *str) {
    if (str) {
        size_t len = strlen(str);
        while (len > 0 && isspace((unsigned char)str[-1])
            str[--len] = '\0';
        while (isspace((unsigned char)str[0])
            str++;
    }
    return str;
}

char *get_token(char *str, const char *delim, char **context) {
    if (!str)
        str = context;
    if (!str)
        return NULL;   // no more tokens
    char *p = strstr(str, delim);
    if (p) {
        *p = '\0';
        p += strlen(delim);
    }
    *context = p;
    // trimming starting and trailing white space from the token is
    //   a good idea, just return str to preserve these spaces.
    return trim_token(str);
}
</code>```

and use it this way:

```<code>int num;
char *context;
char *token = get_token(str, "$$$", &context);
if (token) {
    printf("%s\n", token);
    strcpy(component->name, token);
}
char *number = get_token(NULL, "$$$", &context);
if (number) {
    num = atoi(number);
    printf("%s\n", number);
}
</code>```

Title: splitting a string using strtok()

Body:
I have a string I would like to split into two different strings, the delimiter is $$$.
For instance: milk $$$ 45
On the left side is the product name and on the right is its quantity.
I've used strtok to split the string but I can't extract the number unfortunately.

int num;
char *token = strtok(str, DELIMITER);
printf("%s\n", token);
strcpy(component->name, token);
char *number = strtok(NULL, "       ");
num = atoi(number);
printf("%s\n", number);

The printf calls are for debugging.

Body:
You want to split the input string on a delimiter string $$$: strtok() is not a precise solution for this because it does not search for a delimiter string, but considers any sequence of characters from the delimiter string as a delimiter. Passing "$$$" is equivalent to passing just "$". since the second call uses a different set of delimiters (white space), the strtok() will return $$ as the second token, so you get 0 after conversion with atoi().

There are different ways to address this problem.

use "$" or "$ \t" as the delimiter set for the second call to strtok(). This is sloppy but will work in your case because the second field does not contain embedded spaces and atoi ignores leading white space.

int num;
char *token = strtok(str, "$");
if (token) {
    printf("%s\n", token);
    strcpy(component->name, token);
    char *number = strtok(NULL, "$");
    if (number) {
        num = atoi(number);
        printf("%s\n", number);
    }
}

use strstr to locate the delimiter string and skip that to get the second part:

int num;
char *token = str;
char *p = strstr(str, "$$$");
if (p) {
    p = '\0';
    p += 3;
}
printf("%s\n", token);
strcpy(component->name, token);
char *number = p;
if (number) {
    num = atoi(number);
    printf("%s\n", number);
}

write a custom function to split the string on a delimiter string, and trim white space for consistency:

#include <string.h>
#include <ctype.h>

char *trim_token(char *str) {
    if (str) {
        size_t len = strlen(str);
        while (len > 0 && isspace((unsigned char)str[-1])
            str[--len] = '\0';
        while (isspace((unsigned char)str[0])
            str++;
    }
    return str;
}

char *get_token(char *str, const char *delim, char **context) {
    if (!str)
        str = context;
    if (!str)
        return NULL;   // no more tokens
    char *p = strstr(str, delim);
    if (p) {
        *p = '\0';
        p += strlen(delim);
    }
    *context = p;
    // trimming starting and trailing white space from the token is
    //   a good idea, just return str to preserve these spaces.
    return trim_token(str);
}

and use it this way:

int num;
char *context;
char *token = get_token(str, "$$$", &context);
if (token) {
    printf("%s\n", token);
    strcpy(component->name, token);
}
char *number = get_token(NULL, "$$$", &context);
if (number) {
    num = atoi(number);
    printf("%s\n", number);
}


问:
Find whole word that starts at character position in R
```<code>Str <- "I love chocolate pudding"
pos <- 8
</code>```

I need to return the word that starts with the letter c at pos 8, which is chocolate. How can I do that?

答:
You can use substring to get everything after 8th character. Then remove everything after space using gsub :

```<code>gsub(" .*", "", substring(Str, pos))
</code>```

In case you need to check for the "c":

```<code>Str <- "I love dogs"

ifelse(
  substr(Str, pos, pos) == "c",
  gsub(" .*", "", substring(Str, pos)),
  ""
)
</code>```

Body:
Str <- "I love chocolate pudding"
pos <- 8

I need to return the word that starts with the letter c at pos 8, which is chocolate. How can I do that?

Body:
You can use substring to get everything after 8th character. Then remove everything after space using gsub :

gsub(" .*", "", substring(Str, pos))

In case you need to check for the "c":

Str <- "I love dogs"

ifelse(
  substr(Str, pos, pos) == "c",
  gsub(" .*", "", substring(Str, pos)),
  ""
)


问:
Division by zero exception flag not set in STM32H7 FPU
I'm digging into the FPU of a STM32H743 (Nucleo board, Keil IDE).

I've checked that the FPU is enabled in register CPACR.

I've compiled the following dumb code:

```<code>volatile double test = 0;
test = 1.0 / test;
</code>```

If I look at the assembly I've got:

```<code>VDIV.F64 d0,d1,d0
</code>```

where d1 contains the double representation for 1, d0 contains the double representation for 0.

After the instruction d0 contains 0x7F00...00 which is a representation for infinity, so it looks fine.

However the flag DZC in register FPSCR is not set, as I was expecting it would be.

Am I missing something ?

答:
The issue is in the debugger.

Reading the FPSCR from the code (with instruction VMRS) works fine. But through the debugger (System Viewer FPU tab) of Keil 5.28 the value is wrong.

I've been told there is the same issue with gdb.

EDIT: since I am back on FPU exception management, I noticed I was wrong in my previous answer. The Cortex M7 Programming Manual explicitely states that:

The FPSCR register is not memory-mapped, it can bee accessed using the
VMSR and VMRS instructions

So it is not a debugger issue.

Body:
I'm digging into the FPU of a STM32H743 (Nucleo board, Keil IDE).

I've checked that the FPU is enabled in register CPACR.

I've compiled the following dumb code:

volatile double test = 0;
test = 1.0 / test;

If I look at the assembly I've got:

VDIV.F64 d0,d1,d0

where d1 contains the double representation for 1, d0 contains the double representation for 0.

After the instruction d0 contains 0x7F00...00 which is a representation for infinity, so it looks fine.

However the flag DZC in register FPSCR is not set, as I was expecting it would be.

Am I missing something ?


问:
CSS unordered list with dotted full block width underline
How i can make an ordered list like the one in the screenshot?
What is important is to have a full width dotted underline per item.

Thank you
Sample ordered list

答:
Use a unordered list (
) in combination with border-bottom, like this:

li {
  border-bottom: 1px dashed gray
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>A</li>
  <li>B</li>
  <li>B</li>
</ul></code>```

Body:
Use a unordered list (<ul>) in combination with border-bottom, like this:

li {
  border-bottom: 1px dashed gray
}

<ul>
  <li>A</li>
  <li>B</li>
  <li>B</li>
</ul>


答:
Check this out, add dotted border.

ul li{
  border-bottom: dotted 1px #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>term of use</li>
  <li>Privecy Policy</li>
  <li>Refund Policy</li>
</ul></code>```

Body:
Check this out, add dotted border.

ul li{
  border-bottom: dotted 1px #ccc;
}

<ul>
  <li>term of use</li>
  <li>Privecy Policy</li>
  <li>Refund Policy</li>
</ul>


问:
Entering data twice
I made a php code for insert data on mysql.

```<code>if(isset($_POST['submitted'])){

$img = NULL;
if(isset($_FILES['upload'])){

    include('classes/imagens.class.php');
    $imagem = new imagem($_FILES['upload']['name'],$_FILES['upload']['tmp_name'],$_FILES['upload']['size'],$_FILES['upload']['error']);

            if($imagem->verifica_extensao($_FILES['upload']['type']) && $imagem->verifica_tamanho()){
                $erro = $imagem->upload();
                $img = $imagem->getNome();
            }

}

$trimmed = array_map('trim', $_POST); // usa a função trim() em todas as variáveis POST
$tit = $cat = $dat = $end = $des = $pr = $dono = $hor = FALSE; // atribui falso para as variaveis que poderÃ£o receber as variaveis POST

    $mysql = new mysql('eventos');

if(!empty($trimmed['nome'])){
    $tit = $mysql->escape_string($trimmed['nome']);
}

    if(!empty($trimmed['categoria'])){
    $cat = $mysql->escape_string($trimmed['categoria']);
}

    if(!empty($trimmed['data'])){
    $dat = $mysql->escape_string($trimmed['data']);
}

if($trimmed['hora'] != '--' && $trimmed['minuto'] != '--'){
            $hor = $trimmed['hora'].":".$trimmed['minuto'];
    $hor = $mysql->escape_string($hor);
}

if(!empty($trimmed['endereco'])){
    $end = $mysql->escape_string($trimmed['endereco']);
}

    if(!empty($trimmed['descricao'])){
    $des = $mysql->escape_string($trimmed['descricao']);
}

    if(!empty($trimmed['preco'])){
    $pr = $mysql->escape_string($trimmed['preco']);
}

    $dono = $_SESSION['user_id'];

   if($tit && $cat && $dat && $end && $des && $pr && $dono && $hor){

        $evento = new evento($tit, $cat, $end, $dat, $hor, $des, $pr, NULL, NULL, $img,$dono, NULL, NULL);
        $evento->cadastrar();
        echo '<h3>Evento cadastrado com sucesso!</h3>';
        echo "<a href=".BASE_URL."><h1>Clique aqui para voltar para a página inicial</h1></a>";
    exit();
   }

    }
</code>```

and my function cadastrar()

```<code>function cadastrar(){
    $this->mysql->sql("INSERT INTO eventos (nome, categoria, data, endereco, descricao,ref_imagem,preco,user_id, hora, data_registro) VALUES ('$this->Titulo','$this->Categoria','$this->Data','$this->Endereco','$this->Descricao','$this->RefImagem','$this->Preco','$this->Dono','$this->Horario',NOW())");
}
</code>```

and my function sql()

```<code>function sql($query){
            $this->connect();
            $this->query = $query;
            if(mysqli_query($this->dbc,$this->query)){
                    $linhas_afetadas = mysqli_affected_rows($this->dbc);
                    echo $query;
                    $this->result=mysqli_query($this->dbc,$this->query);
                    $this->disconnect();
                    $retorno = array($this->result,$linhas_afetadas);
                    return $retorno;
            } else {
                    die("Ocorreu um erro ao executar a Query SQL abaixo:<br>$query");
                    $this->disconnect();
            }

    }
</code>```

and... the result is 2 same columns on the table.

答:
Every time you call mysqli_query, a query is launched to the database. You are doing that twice:

```<code>if (mysqli_query(...))
{
    ....
    $this->result = mysqli_query(...);
}
</code>```

So that's why you end with duplicated data.

Title: Entering data twice

Body:
I made a php code for insert data on mysql.

if(isset($_POST['submitted'])){

$img = NULL;
if(isset($_FILES['upload'])){

    include('classes/imagens.class.php');
    $imagem = new imagem($_FILES['upload']['name'],$_FILES['upload']['tmp_name'],$_FILES['upload']['size'],$_FILES['upload']['error']);

            if($imagem->verifica_extensao($_FILES['upload']['type']) && $imagem->verifica_tamanho()){
                $erro = $imagem->upload();
                $img = $imagem->getNome();
            }

}

$trimmed = array_map('trim', $_POST); // usa a função trim() em todas as variáveis POST
$tit = $cat = $dat = $end = $des = $pr = $dono = $hor = FALSE; // atribui falso para as variaveis que poderÃ£o receber as variaveis POST

    $mysql = new mysql('eventos');

if(!empty($trimmed['nome'])){
    $tit = $mysql->escape_string($trimmed['nome']);
}

    if(!empty($trimmed['categoria'])){
    $cat = $mysql->escape_string($trimmed['categoria']);
}

    if(!empty($trimmed['data'])){
    $dat = $mysql->escape_string($trimmed['data']);
}

if($trimmed['hora'] != '--' && $trimmed['minuto'] != '--'){
            $hor = $trimmed['hora'].":".$trimmed['minuto'];
    $hor = $mysql->escape_string($hor);
}

if(!empty($trimmed['endereco'])){
    $end = $mysql->escape_string($trimmed['endereco']);
}

    if(!empty($trimmed['descricao'])){
    $des = $mysql->escape_string($trimmed['descricao']);
}

    if(!empty($trimmed['preco'])){
    $pr = $mysql->escape_string($trimmed['preco']);
}

    $dono = $_SESSION['user_id'];

   if($tit && $cat && $dat && $end && $des && $pr && $dono && $hor){

        $evento = new evento($tit, $cat, $end, $dat, $hor, $des, $pr, NULL, NULL, $img,$dono, NULL, NULL);
        $evento->cadastrar();
        echo '
Evento cadastrado com sucesso!
';
        echo "
Clique aqui para voltar para a página inicial
";
    exit();
   }

    }

and my function cadastrar()

function cadastrar(){
    $this->mysql->sql("INSERT INTO eventos (nome, categoria, data, endereco, descricao,ref_imagem,preco,user_id, hora, data_registro) VALUES ('$this->Titulo','$this->Categoria','$this->Data','$this->Endereco','$this->Descricao','$this->RefImagem','$this->Preco','$this->Dono','$this->Horario',NOW())");
}

and my function sql()

function sql($query){
            $this->connect();
            $this->query = $query;
            if(mysqli_query($this->dbc,$this->query)){
                    $linhas_afetadas = mysqli_affected_rows($this->dbc);
                    echo $query;
                    $this->result=mysqli_query($this->dbc,$this->query);
                    $this->disconnect();
                    $retorno = array($this->result,$linhas_afetadas);
                    return $retorno;
            } else {
                    die("Ocorreu um erro ao executar a Query SQL abaixo:
$query");
                    $this->disconnect();
            }

    }

and... the result is 2 same columns on the table.

Body:
Every time you call mysqli_query, a query is launched to the database. You are doing that twice:

if (mysqli_query(...))
{
    ....
    $this->result = mysqli_query(...);
}

So that's why you end with duplicated data.


问:
Get Current slide index with Glide.js
how can I get the current slide index/number when I swipe between elements with GLide.js</p>

```<code> const config = {
    type: "carousel",
    perView: 5,
    startAt: 2,
    perTouch: 1,
    focusAt: "center",
  };
  new Glide(".glide", config)
    .on("swipe.end", function (event) {
      console.log(event);
    })
    .mount();
</code>```

答:
Try using glide.index

```<code>const config = {
  type: "carousel",
  perView: 5,
  startAt: 2,
  perTouch: 1,
  focusAt: "center",
};

var glide = new Glide(".glide", config)

glide.on("swipe.end", function(event) {
  console.log('on swipe.end', glide.index)
})

glide.mount()

console.log(glide.index)
</code>```

Title: Get Current slide index with Glide.js

Body:
how can I get the current slide index/number when I swipe between elements with GLide.js

 const config = {
    type: "carousel",
    perView: 5,
    startAt: 2,
    perTouch: 1,
    focusAt: "center",
  };
  new Glide(".glide", config)
    .on("swipe.end", function (event) {
      console.log(event);
    })
    .mount();

Body:
Try using glide.index

const config = {
  type: "carousel",
  perView: 5,
  startAt: 2,
  perTouch: 1,
  focusAt: "center",
};

var glide = new Glide(".glide", config)

glide.on("swipe.end", function(event) {
  console.log('on swipe.end', glide.index)
})

glide.mount()

console.log(glide.index)


问:
How to perform a server side data fetching with React Hooks
We just start moving into React Hooks from the React life-cycle and one of the things that we noticed, is that there's no straightforward way to run something similar to ComponentWillMount for loading data before sending the rendered page to the user (since useEffect is not running on SSR).

Is there any easy way supported by React to do so?

答:
I had the same problem. I've managed to solve it with a custom hook and by rendering application twice on the server-side. The whole process looks like this:

during the first render, collect all effects to the global context,

after first render wait for all effects to resolve,

render the application for the second time with all data.

I wrote an article with examples describing this approach.
This is a direct link to the example form article on CodeSandbox.

Also, I have published an NPM package that simplifies this process - useSSE on GitHub.


问:
Spring Boot custom ErrorAttributes http status not set to response
Following Spring Boot documentation I defined my own ErrorAttributes bean (see below), I was able to make the json response to show the information I wanted, including my own error code and message by using a custom exception to wrap that information and generate the error response from it. The only issue with this is that the http status of the response is not matching the one I define in the status attribute, it is not been overridden.

```<code>@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {

            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);

            Throwable error = getError(requestAttributes);

            if (error instanceof MyException) {
                MyException myException = (MyException) error;

                errorAttributes.put("errorCode", myException.getErrorCode());
                errorAttributes.put("message", myException.getMessage());
                errorAttributes.put("status", myException.getStatus());

                HttpStatus correspondentStatus = HttpStatus.valueOf(myException.getStatus());
                errorAttributes.put("error", correspondentStatus.getReasonPhrase());
            }

            return errorAttributes;
        }
    };
}
</code>```

The response's http status is not matching the status in the json, for example:

```<code>HTTP/1.1 500
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 01 Mar 2017 18:48:22 GMT
{
   "timestamp": "2017-03-01T18:48:21.894+0000",
   "status": 403,
   "error": "Forbidden",
   "exception": "com.myapp.MyException",
   "message": "You are not authorized. This user doesn't exist in the db",
   "path": "/account",
   "errorCode": "00013"
}
</code>```

答:
The accepted answer didn't work for me in a Spring Boot 2.3.0 application, I had to subclass ErrorController to override the original status.

This is the code of BasicErrorController, applied as default:

```<code>    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        return new ResponseEntity<>(body, status);
    }
</code>```

As you can see the original status is kept on a variable gotten before the invocation of getErrorAttributes(). Thus, adding requestAttributes.setAttribute("javax.servlet.error.status_code", httpStatus, 0); in your custom getErrorAttibutes() doesn't really do anything.

In a custom extension of BasicErrorController (remember to add it as a bean) you can override error() and make sure status gets the value you want:

```<code>public class CustomBasicErrorController extends BasicErrorController {

    public CustomBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    public CustomBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        Integer status = (Integer) body.get("status");
        if (status == HttpStatus.NO_CONTENT.value()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(body, HttpStatus.valueOf(status));
    }
}
</code>```

Body:
Following Spring Boot documentation I defined my own ErrorAttributes bean (see below), I was able to make the json response to show the information I wanted, including my own error code and message by using a custom exception to wrap that information and generate the error response from it. The only issue with this is that the http status of the response is not matching the one I define in the status attribute, it is not been overridden.

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {

            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);

            Throwable error = getError(requestAttributes);

            if (error instanceof MyException) {
                MyException myException = (MyException) error;

                errorAttributes.put("errorCode", myException.getErrorCode());
                errorAttributes.put("message", myException.getMessage());
                errorAttributes.put("status", myException.getStatus());

                HttpStatus correspondentStatus = HttpStatus.valueOf(myException.getStatus());
                errorAttributes.put("error", correspondentStatus.getReasonPhrase());
            }

            return errorAttributes;
        }
    };
}

The response's http status is not matching the status in the json, for example:

HTTP/1.1 500
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 01 Mar 2017 18:48:22 GMT
{
   "timestamp": "2017-03-01T18:48:21.894+0000",
   "status": 403,
   "error": "Forbidden",
   "exception": "com.myapp.MyException",
   "message": "You are not authorized. This user doesn't exist in the db",
   "path": "/account",
   "errorCode": "00013"
}

Body:
The accepted answer didn't work for me in a Spring Boot 2.3.0 application, I had to subclass ErrorController to override the original status.

This is the code of BasicErrorController, applied as default:

    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        return new ResponseEntity<>(body, status);
    }

As you can see the original status is kept on a variable gotten before the invocation of getErrorAttributes(). Thus, adding requestAttributes.setAttribute("javax.servlet.error.status_code", httpStatus, 0); in your custom getErrorAttibutes() doesn't really do anything.

In a custom extension of BasicErrorController (remember to add it as a bean) you can override error() and make sure status gets the value you want:

public class CustomBasicErrorController extends BasicErrorController {

    public CustomBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    public CustomBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        Integer status = (Integer) body.get("status");
        if (status == HttpStatus.NO_CONTENT.value()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(body, HttpStatus.valueOf(status));
    }
}


问:
Should GC.SuppressFinalize be called on objects that do not have a finalizer?
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not. </p>

<p>Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined? </p>

答:
It looks like FxCop simply inspects the Dispose() and doesn't check for the presence of a destructor.

It should be safe to ignore.

ContentLicense: CC BY-SA 2.5

Body:
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not.

Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined?

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: Henk Holterman


问:
Turn this inefficient code appending columns to multiple dfs into a for loop?
I have the below code which appends a year column to each of my respective dataframes. I assume this would use a for loop, but since the year is different each year, I'm unsure how to do it.

```<code>hic_dfs = [hic15,hic16,hic17,hic18,hic19]

hic15['year']=2015
hic16['year']=2016
hic17['year']=2017
hic18['year']=2018
hic19['year']=2019
</code>```

Thanks in advance!

答:
Try this:</p>

```<code>ye = 2015
for idx, elem in enumerate(hic_dfs):
    elem["year"] = ye + idx
</code>```

Body:
I have the below code which appends a year column to each of my respective dataframes. I assume this would use a for loop, but since the year is different each year, I'm unsure how to do it.

hic_dfs = [hic15,hic16,hic17,hic18,hic19]

hic15['year']=2015
hic16['year']=2016
hic17['year']=2017
hic18['year']=2018
hic19['year']=2019

Thanks in advance!

Body:
Try this:

ye = 2015
for idx, elem in enumerate(hic_dfs):
    elem["year"] = ye + idx


问:
view tab bar controller from storyboard swift 5
I am working on swift 5 and xcode 11.5

I am trying to move user from main storyboard to tab bar controller if he is logged in,

in my appDelegate I tried this

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    if let api_token = helper.getApiToken() {
        print("api_token: \(api_token)")

        let tab = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "maintab")
        window?.rootViewController = tab
    }
    return true
}
```

here I want to check if there is a user api_token, if yes move to the tab bar
if no show the main storyboard
but it always goes to main.storyboard even if there is a token!

答:
Try this code</p>

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    if let api_token = helper.getApiToken() {
        print("api_token: \(api_token)")

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tab = storyboard.instantiateViewController(withIdentifier: "maintab")
        window?.rootViewController = tab
    }

    return true
}

</code>```

Body:
I am working on swift 5 and xcode 11.5

I am trying to move user from main storyboard to tab bar controller if he is logged in,

in my appDelegate I tried this

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    if let api_token = helper.getApiToken() {
        print("api_token: \(api_token)")

        let tab = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "maintab")
        window?.rootViewController = tab
    }
    return true
}

here I want to check if there is a user api_token, if yes move to the tab bar
if no show the main storyboard
but it always goes to main.storyboard even if there is a token!

Body:
Try this code

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    if let api_token = helper.getApiToken() {
        print("api_token: \(api_token)")

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tab = storyboard.instantiateViewController(withIdentifier: "maintab")
        window?.rootViewController = tab
    }

    return true
}


问:
Updating Html content through loop not reflecting the final value
html

```<code><div class="content"></div>
</code>```

array of objects:

```<code>var obj = [
  {
    title : "burger",
    price : 5
  },
  {
    title : "salad",
    price : 10
  }
]
</code>```

functions:

```<code>function addItems() {
  $(".content").html('<div id="title"></div><div id="price"></div>');
};

function addContent() {
  $("#title").text(obj[i].title);
  $("#price").text(obj[i].price);
};
</code>```

Then I am looping through to change the html and the content:

```<code>for(i = 0; i < obj.length; i++){
  addItems();
  addContent();
}
</code>```

The actual result is the text string from obj[2].title

salad

My expected result :

burger 5 salad 10

Thanks for the help

答:
there are multiple problems with your code.

1) you addItem function in not adding a item but replacing it. html() is replacing the actual html content with the new one. Try append() instead of html().

2) Your addCOntent is always adding to the same item because you have only one id and that's "title". If you add another item with addItem() you will have two div with the same id, what is forbidden. So you have to add an identifier to your id.

e.G.

```<code>function addItems(id) {
     $(".content").append('<div id="title_'+id+'"></div><div id="price_'+id+'"></div>');
}

function addContent(id) {
   $("#title_"+id).text(obj[id].title);
   $("#price_"+id).text(obj[id].price);
};

for(let id = 0; id < obj.length; id++) {
   addItems(id);
   addContent(id);
}
</code>```

Body:
html

array of objects:

var obj = [
  {
    title : "burger",
    price : 5
  },
  {
    title : "salad",
    price : 10
  }
]

functions:

function addItems() {
  $(".content").html('

');
};

function addContent() {
  $("#title").text(obj[i].title);
  $("#price").text(obj[i].price);
};

Then I am looping through to change the html and the content:

for(i = 0; i < obj.length; i++){
  addItems();
  addContent();
}

The actual result is the text string from obj[2].title

salad

My expected result :

burger 5 salad 10

Thanks for the help

Body:
there are multiple problems with your code.

1) you addItem function in not adding a item but replacing it. html() is replacing the actual html content with the new one. Try append() instead of html().

2) Your addCOntent is always adding to the same item because you have only one id and that's "title". If you add another item with addItem() you will have two div with the same id, what is forbidden. So you have to add an identifier to your id.

e.G.

function addItems(id) {
     $(".content").append('<div id="title_'+id+'"></div><div id="price_'+id+'"></div>');
}

function addContent(id) {
   $("#title_"+id).text(obj[id].title);
   $("#price_"+id).text(obj[id].price);
};

for(let id = 0; id < obj.length; id++) {
   addItems(id);
   addContent(id);
}


问:
Action icon not appear in toolbar
Good Day

I'm working on app that use navigation component I setup my toolbar icons but it's didn't appear
 so I tried to follow these guide here hereto fix the issue but still not appearing

here is my fragment code

```<code>public class myFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_community_timeline, container, false);

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    NavController navController = Navigation.findNavController(view);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
    Toolbar toolbar = view.findViewById(R.id.timeline_toolbar);
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);

}
</code>```

Xml file

```<code>    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".User.Community.CommunityTimelineFragment">

<androidx.appcompat.widget.Toolbar
        android:id="@+id/timeline_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:menu="@menu/user_menu"
        app:title="@string/timeline" />

</FrameLayout>
</code>```

my menu

```<code>    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/add_company"
        android:icon="@drawable/ic_company"
        android:title="@string/add_company"
        android:visible="true"
        app:showAsAction="always" />
    <item
        android:id="@+id/fiter_bodcast"
        android:icon="@drawable/ic_bodcast"
        android:title="@string/filter_setting"
        android:visible="true"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/add_question"
        android:icon="@drawable/ic_question"
        android:title="@string/add_question"
        android:visible="true"
        app:showAsAction="ifRoom" />
</menu>
</code>```

please anyone know why this issue is happend

答:
Try to create all the views in your onCreateView method.

Instead of this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_community_timeline, container, false);

}
</code>```

You should do this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_community_timeline, container, false);

    NavController navController = Navigation.findNavController(view);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
    Toolbar toolbar = view.findViewById(R.id.timeline_toolbar);
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);

    return view;
}
</code>```

Hope this helps

Title: Action icon not appear in toolbar

Body:
Good Day

I'm working on app that use navigation component I setup my toolbar icons but it's didn't appear
 so I tried to follow these guide here hereto fix the issue but still not appearing

here is my fragment code

public class myFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_community_timeline, container, false);

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    NavController navController = Navigation.findNavController(view);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
    Toolbar toolbar = view.findViewById(R.id.timeline_toolbar);
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);

}

Xml file

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".User.Community.CommunityTimelineFragment">

<androidx.appcompat.widget.Toolbar
        android:id="@+id/timeline_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:menu="@menu/user_menu"
        app:title="@string/timeline" />

</FrameLayout>

my menu

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/add_company"
        android:icon="@drawable/ic_company"
        android:title="@string/add_company"
        android:visible="true"
        app:showAsAction="always" />
    <item
        android:id="@+id/fiter_bodcast"
        android:icon="@drawable/ic_bodcast"
        android:title="@string/filter_setting"
        android:visible="true"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/add_question"
        android:icon="@drawable/ic_question"
        android:title="@string/add_question"
        android:visible="true"
        app:showAsAction="ifRoom" />
</menu>

please anyone know why this issue is happend

Body:
Try to create all the views in your onCreateView method.

Instead of this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_community_timeline, container, false);

}

You should do this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_community_timeline, container, false);

    NavController navController = Navigation.findNavController(view);
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
    Toolbar toolbar = view.findViewById(R.id.timeline_toolbar);
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);

    return view;
}

Hope this helps


问:
How do I grab an index from an array in a HashMap?
I've got a HashMap<Object, String[]> I just want to grab the 0 index position from the String[]. How do I do that?

Can I just do this? mMap.get(position)[0]?

答:
HashMap doesn't have a 0index and it doesn't have a String[]

You cannot do what you ask because it doesn't make sense.

Can I just do this? mMap.get(position)[0]?

You can. Have you tried this to see if it works?  Note: it will fail if map.get() returns null


问:
Github Simple Commit Issue
I made modifications to my github repo on the actual website rather than the terminal. Now, I can't commit anything locally from my computer to my terminal because it says the files stored locally are not in sync with the github repo. How can I fix this so I can push my changes in terminal? Can I undo my previous commits that I did on the website?</p>

答:
(Optional) If you've some modifications locally, stash them first:

```<code>$  git stash
</code>```

Because you've made some modifications at remote repo, you need to pull them down before pushing new commits (fix conflicts one by one if you got in this step):

```<code>$ git pull origin your_branch
</code>```

Now your local branch & remote branch are in same stage, get back previously stashed modifications back (if you did step #1 before):

```<code>$ git stash pop
$ git add .
$ git commit -m "commit msg here"
</code>```

It's OK to push local modifications to remote then:

```<code>$ git push origin your_branch
</code>```

Btw, if you did modification at remote repo BY MISTAKE, and just want to use local repo as latest, you can push local repo to overwrite remote one (make sure remote repo's branch is not protected by server):

```<code>// !!! Use it wisely & carefully, cause it will overwrite the whole branch at remote side.
//
$ git push -f origin your_branch
</code>```

Title: Github Simple Commit Issue

Body:
(Optional) If you've some modifications locally, stash them first:

$  git stash

Because you've made some modifications at remote repo, you need to pull them down before pushing new commits (fix conflicts one by one if you got in this step):

$ git pull origin your_branch

Now your local branch & remote branch are in same stage, get back previously stashed modifications back (if you did step #1 before):

$ git stash pop
$ git add .
$ git commit -m "commit msg here"

It's OK to push local modifications to remote then:

$ git push origin your_branch

Btw, if you did modification at remote repo BY MISTAKE, and just want to use local repo as latest, you can push local repo to overwrite remote one (make sure remote repo's branch is not protected by server):

// !!! Use it wisely & carefully, cause it will overwrite the whole branch at remote side.
//
$ git push -f origin your_branch


问:
How to use github nuget packages on Visual Studio 2019
I try to learn Github action and packages. So, I create a sample nuget package and successfully created. However I could not use it.

I follow this step;

Options > Nuget Package Manager > Package Sources

Click add button write organization name and add package source address like that:

After that Visual Studio doesn't ask me any credential for this address.

If there is no credential, I will expect to an error. And I got it.

[github] Failed to retrieve metadata from source 'https://nuget.pkg.github.com/[OrganizationName]/query?q=&skip=0&take=26&prerelease=false&semVerLevel=2.0.0'.
  Response status code does not indicate success: 401 (Unauthorized).

Then, I decide to some credential like explained in github documentation.

My nuget.config file:

However still I get Unauthorized error. And also when I click the error link gettin a message like that:

{"errors":[{"code":"Your token has not been granted the required
  scopes to execute this query. The 'id' field requires one of the
  following scopes","message":" ['read:packages'], but your token has
  only been granted the: [''] scopes. Please modify your token's scopes
  at: https://github.com/settings/tokens."}]}

but I already have a token with read/write package credential.

All that fails and I try to another way. I add credential information to Windows Credential Manager. Eveything still same.

So, how I add and use my private nuget packages?

答:
How to use github nuget packages on Visual Studio 2019

First, make sure that your credential info is correct on the nuget.config file.

I found your document suggest you should put a new nuget.config file to your solution. This nuget.config file is a local action file, it will act on any projects in the current subdirectory and below the current level. You can refer to this document.

In this way, you should restart VS Instance to enable this new nuget.config file.

-------Global nuget.config--------

However, from your description and first picture, you used the global nuget.config file. And UI's info stores under global nuget.config file.

If you want to config this gihub package source for all the projects on your PC, you should config it on the global nuget.config file.

And the first picture which you provided indicates that you used in the global file(C:\Users\xxx(current user)\AppData\Roaming\NuGet\NuGet.Config).

This function also needs restart VS to enable the new nuget.config file.

Suggestion

please add your content of the file into C:\Users\xxx(current user)\AppData\Roaming\NuGet\NuGet.Config.

restart VS Instance or restart PC to enable this new nuget.config file. It is designed by that.


问:
Default value on insert PHP and SQL
I want to make that when someone inserts a post into my database that if they don't supply their name it defaults to anonymous. How would I do this?
My code here

$query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";

$stmt = $conn->prepare($query);
$stmt->bindValue(1, $post_data['name']);
$stmt->bindValue(2, $post_data['post']);

$stmt->execute();
```

<p>I have tried doing a default in the create tables for the db but when the user triggers the insert it overides it as a blank field.</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE CinemaPost(
  id INT AUTO_INCREMENT NOT NULL,
  name varchar(255) NOT NULL DEFAULT 'anonymous',
  text varchar(100) NOT NULL,
  post_date timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  likes INT NOT NULL,
  reply_to INT,
  Primary KEY (id)
);
</code>```

答:
Using DEFAULT on the SQL side is absolutely correct. However, you need to ensure that value is actually used.

The default value is only used if you pass NULL as the parameter from PHP. An empty string ("") is not NULL.

```<code>$stmt->bindValue(1, empty($post_data['name']) ? NULL : $post_data['name']);
</code>```

Title: Default value on insert PHP and SQL

Body:
I want to make that when someone inserts a post into my database that if they don't supply their name it defaults to anonymous. How would I do this?
My code here

$query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";

$stmt = $conn->prepare($query);
$stmt->bindValue(1, $post_data['name']);
$stmt->bindValue(2, $post_data['post']);

$stmt->execute();

I have tried doing a default in the create tables for the db but when the user triggers the insert it overides it as a blank field.

CREATE TABLE CinemaPost(
  id INT AUTO_INCREMENT NOT NULL,
  name varchar(255) NOT NULL DEFAULT 'anonymous',
  text varchar(100) NOT NULL,
  post_date timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  likes INT NOT NULL,
  reply_to INT,
  Primary KEY (id)
);

Body:
Using DEFAULT on the SQL side is absolutely correct. However, you need to ensure that value is actually used.

The default value is only used if you pass NULL as the parameter from PHP. An empty string ("") is not NULL.

$stmt->bindValue(1, empty($post_data['name']) ? NULL : $post_data['name']);


答:
```<code>with cte as
(select FkLocationId, FkProductId, SortValue,
ROW_NUMBER() over(partition by FkLocationId order by sortvalue,FkProductId desc) new_sort_value
from productLocation where FkLocationId =1  --and SortValue =0
)

update pl SET
pl.SortValue = c.new_sort_value
from productLocation pl inner join cte c
on pl.FkLocationId = c.FkLocationId and pl.FkProductId = c.FkProductId

Select * from productLocation where FkLocationId =1 order by FkProductId
</code>```

The core of the approach taken by me is based row_number window function, which partitions data over fkproductid sorted by sortvalue and fkproductid in descending manner.

There are 2 queries involved, although could have been done is single, but for simplicity's sake i have used common table expression (cte)

CTE derived from query one is used as joining table in second update query.

I have left much to self exploration, remember its imperative to think in term of sets.

Title: How to increment column by one group wise

Body:
I have a table called productLocation, and its data structure as follows,  SQLFiddle

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 0         |
+--------------+-------------+-----------+
| 1            | 101         | 0         |
+--------------+-------------+-----------+
| 1            | 102         | 0         |
+--------------+-------------+-----------+
| 1            | 103         | 2         |
+--------------+-------------+-----------+
| 1            | 104         | 1         |
+--------------+-------------+-----------+
| 1            | 105         | 3         |
+--------------+-------------+-----------+
| 2            | 100         | 0         |
+--------------+-------------+-----------+
| 2            | 101         | 0         |
+--------------+-------------+-----------+
| 2            | 102         | 0         |
+--------------+-------------+-----------+
| 2            | 103         | 1         |
+--------------+-------------+-----------+
| 2            | 104         | 3         |
+--------------+-------------+-----------+
| 2            | 105         | 2         |
+--------------+-------------+-----------+
| 3            | 100         | 0         |
+--------------+-------------+-----------+
| 3            | 101         | 0         |
+--------------+-------------+-----------+
| 3            | 102         | 0         |
+--------------+-------------+-----------+
| 3            | 103         | 1         |
+--------------+-------------+-----------+
| 3            | 104         | 2         |
+--------------+-------------+-----------+

For each location have its own sorting order for products. But some of the products have 0 as the SortValue
Now I need to write a query to update SortValue as,

If I consider one location, FkLocationId  = 1

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 0         |
+--------------+-------------+-----------+
| 1            | 101         | 0         |
+--------------+-------------+-----------+
| 1            | 102         | 0         |
+--------------+-------------+-----------+
| 1            | 103         | 2         |
+--------------+-------------+-----------+
| 1            | 104         | 1         |
+--------------+-------------+-----------+
| 1            | 105         | 3         |
+--------------+-------------+-----------+

In the above data table, you can see, FkProductId  = 100,101,102 have 0 as the SortValue. I need to update its sortValue as order by FkProductId descending order. I need to update its like

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 3         |
+--------------+-------------+-----------+
| 1            | 101         | 2         |
+--------------+-------------+-----------+
| 1            | 102         | 1         |
+--------------+-------------+-----------+

And also update the previous SortValue by one by one.

Then the complete output should be,

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 3         |
+--------------+-------------+-----------+
| 1            | 101         | 2         |
+--------------+-------------+-----------+
| 1            | 102         | 1         |
+--------------+-------------+-----------+
| 1            | 103         | 5         |
+--------------+-------------+-----------+
| 1            | 104         | 4         |
+--------------+-------------+-----------+
| 1            | 105         | 6         |
+--------------+-------------+-----------+

Is this possible to do? I'm really confused about this, please help me to solve this. Thank you

Updated:

Suppose I have another table as product. And its data structure as follows,

+-----------+-----------+
| ProdcutId | SortValue |
+-----------+-----------+
| 100       | 0         |
+-----------+-----------+
| 101       | 0         |
+-----------+-----------+
| 107       | 0         |
+-----------+-----------+
| 108       | 1         |
+-----------+-----------+
| 109       | 2         |
+-----------+-----------+
| 110       | 6         |
+-----------+-----------+
| 111       | 5         |
+-----------+-----------+
| 112       | 4         |
+-----------+-----------+
| 113       | 3         |
+-----------+-----------+

I also need to do same thing for this table as well, How can I do it

Expected Output:

+-----------+-----------+
| ProdcutId | SortValue |
+-----------+-----------+
| 100       | 3         |
+-----------+-----------+
| 101       | 2         |
+-----------+-----------+
| 107       | 1         |
+-----------+-----------+
| 108       | 4         |
+-----------+-----------+
| 109       | 5         |
+-----------+-----------+
| 110       | 9         |
+-----------+-----------+
| 111       | 8         |
+-----------+-----------+
| 112       | 7         |
+-----------+-----------+
| 113       | 6         |
+-----------+-----------+

Body:
with cte as
(select FkLocationId, FkProductId, SortValue,
ROW_NUMBER() over(partition by FkLocationId order by sortvalue,FkProductId desc) new_sort_value
from productLocation where FkLocationId =1  --and SortValue =0
)

update pl SET
pl.SortValue = c.new_sort_value
from productLocation pl inner join cte c
on pl.FkLocationId = c.FkLocationId and pl.FkProductId = c.FkProductId

Select * from productLocation where FkLocationId =1 order by FkProductId

The core of the approach taken by me is based row_number window function, which partitions data over fkproductid sorted by sortvalue and fkproductid in descending manner.

There are 2 queries involved, although could have been done is single, but for simplicity's sake i have used common table expression (cte)

CTE derived from query one is used as joining table in second update query.

I have left much to self exploration, remember its imperative to think in term of sets.


问:
windows phone app how to intergrate video player using only c# code
in my application i want to navigate from a page which is extending Canvas to the video player
for video player page i hav created one class and i m doing this there

```<code> MediaElement videoPlayer = new MediaElement();
 videoPlayer.Source = (new Uri("some video url", UriKind.Absolute));
 videoPlayer.AutoPlay = true;
 videoPlayer.Play();
</code>```

but when i m going to that page nothing is happning
can some body tell me what i m missing.
i am new to windows development.
thanks is advance

答:
You need to insert the MediaElement into your VisualTree. For example, if your canvas' name is LayoutRoot (the default), you could to this:

```<code>LayoutRoot.Children.Add(videoPlayer);
</code>```

Body:
in my application i want to navigate from a page which is extending Canvas to the video player
for video player page i hav created one class and i m doing this there

 MediaElement videoPlayer = new MediaElement();
 videoPlayer.Source = (new Uri("some video url", UriKind.Absolute));
 videoPlayer.AutoPlay = true;
 videoPlayer.Play();

but when i m going to that page nothing is happning
can some body tell me what i m missing.
i am new to windows development.
thanks is advance

Body:
You need to insert the MediaElement into your VisualTree. For example, if your canvas' name is LayoutRoot (the default), you could to this:

LayoutRoot.Children.Add(videoPlayer);


问:
Chart.js not showing all labels on pie chart
I recently updated Chart.js and got the following bug afterwards.

Some of the labels under my pie chart are not showing anymore, until I click on one of the visible ones. Then everything shows as it should.

Here you can see how it looks before clicking on something:
before clicking

and here you can see the chart after clicking on a visible label: after clicking

Here you can see the options section of my chart code:

```<code>options: {
                    maintainAspectRatio : false,
                    animation: {
                        duration: 0
                    },
                    elements: {
                        center: center
                    },
                    legend: {
                        position: 'bottom',
                        //fullWidth: 'true',
                        labels: {
                            generateLabels: (chart) => {
                                chart.legend.afterFit = function () {
                                    var width = this.width;

                                    this.lineWidths = this.lineWidths.map( () => this.width - 12 );

                                    this.options.labels.padding = 30;
                                    this.options.labels.boxWidth = 15;
                                };

                                var data = chart.data;
                                if (data.labels.length && data.datasets.length) {
                                    return data.labels.map((label, i) => {
                                        var meta = chart.getDatasetMeta(0);
                                        var ds = data.datasets[0];
                                        var arc = meta.data[i];
                                        var custom = arc && arc.custom || {};
                                        var getValueAtIndexOrDefault = this.getValueAtIndexOrDefault;
                                        var arcOpts = chart.options.elements.arc;
                                        var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
                                        var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
                                        var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);

                                        return {
                                            text: label,
                                            fillStyle: fill,
                                            strokeStyle: stroke,
                                            lineWidth: bw,
                                            hidden: isNaN(ds.data[i]) || meta.data[i].hidden,

                                            // Extra data used for toggling the correct item
                                            index: i
                                        };
                                    });
                                }
                                return [];
                            }
                        },
                    },
                    cutoutPercentage: 85,
                    plugins: {
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            display: function(context) {
                                var index = context.dataIndex;
                                var value = context.dataset.data[index];
                                return value > 0; // display labels with a value greater than 0
                            },
                            font: {
                                weight: 'bold',
                                size: 16,
                            },
                        }
                    }
                }
</code>```

答:
```<code>chart.legend.afterFit = function () {
    if (keys.length > 4) {
        this.options.labels.padding = 15;
        this.height = this.height + 25;
    }
    else {
        this.options.labels.padding = 20;
        this.height = this.height + 18;
    }
    var width = this.width; // guess you can play with this value to achieve needed layout
    this.lineWidths = this.lineWidths.map(function () { return width; });
};
</code>```

I changed the part at afterFit to this, so it is formatting right, the problem is, the padding settings are set back when i click on a label.

Body:
I recently updated Chart.js and got the following bug afterwards.

Some of the labels under my pie chart are not showing anymore, until I click on one of the visible ones. Then everything shows as it should.

Here you can see how it looks before clicking on something:
before clicking

and here you can see the chart after clicking on a visible label: after clicking

Here you can see the options section of my chart code:

options: {
                    maintainAspectRatio : false,
                    animation: {
                        duration: 0
                    },
                    elements: {
                        center: center
                    },
                    legend: {
                        position: 'bottom',
                        //fullWidth: 'true',
                        labels: {
                            generateLabels: (chart) => {
                                chart.legend.afterFit = function () {
                                    var width = this.width;

                                    this.lineWidths = this.lineWidths.map( () => this.width - 12 );

                                    this.options.labels.padding = 30;
                                    this.options.labels.boxWidth = 15;
                                };

                                var data = chart.data;
                                if (data.labels.length && data.datasets.length) {
                                    return data.labels.map((label, i) => {
                                        var meta = chart.getDatasetMeta(0);
                                        var ds = data.datasets[0];
                                        var arc = meta.data[i];
                                        var custom = arc && arc.custom || {};
                                        var getValueAtIndexOrDefault = this.getValueAtIndexOrDefault;
                                        var arcOpts = chart.options.elements.arc;
                                        var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
                                        var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
                                        var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);

                                        return {
                                            text: label,
                                            fillStyle: fill,
                                            strokeStyle: stroke,
                                            lineWidth: bw,
                                            hidden: isNaN(ds.data[i]) || meta.data[i].hidden,

                                            // Extra data used for toggling the correct item
                                            index: i
                                        };
                                    });
                                }
                                return [];
                            }
                        },
                    },
                    cutoutPercentage: 85,
                    plugins: {
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            display: function(context) {
                                var index = context.dataIndex;
                                var value = context.dataset.data[index];
                                return value > 0; // display labels with a value greater than 0
                            },
                            font: {
                                weight: 'bold',
                                size: 16,
                            },
                        }
                    }
                }

Body:
chart.legend.afterFit = function () {
    if (keys.length > 4) {
        this.options.labels.padding = 15;
        this.height = this.height + 25;
    }
    else {
        this.options.labels.padding = 20;
        this.height = this.height + 18;
    }
    var width = this.width; // guess you can play with this value to achieve needed layout
    this.lineWidths = this.lineWidths.map(function () { return width; });
};

I changed the part at afterFit to this, so it is formatting right, the problem is, the padding settings are set back when i click on a label.


问:
Ruby: combining methods into 1 line
I have an array of objects, and I want to take one of the methods to return it into 1 single line.

here is my array

```<code>def set
        @seconds = Counter.new('Seconds')
        @minutes = Counter.new('Minutes')
        @hours = Counter.new('Hours')

        @time = [@seconds, @minutes, @hours]
    end
</code>```

and here is the method I'm trying to print in the Counter class

```<code>    def count
        @counts
    end
</code>```

Here's my attempt

```<code>    def read
        reverse = @time.reverse
        @time.each do |t|
            return '%02d' %t.count.to_s.join(":")
        end
    end
</code>```

(I also want them to be in 00, 01 formats, hence the '%02d')

.join doesn't seem to work (I'm guessing it works with arrays but not methods of an array?

any help will be appreciated!

答:
Given this Counter class and some instances:

```<code>class Counter
  attr_accessor :count

  def initialize(name, count: 0)
    @name = name
    @count = count
  end
end

@seconds = Counter.new('Seconds', count: 52)
@minutes = Counter.new('Minutes', count: 30)
@hours = Counter.new('Hours', count: 11)

@time = [@seconds, @minutes, @hours]
</code>```

You can extract the count values in hour / minute / second order via:

```<code>@time.reverse.map(&:count)
#=> [11, 30, 52]
</code>```

This array can be passed (in its entirety) to String#% to produce a HH:MM:SS string:

```<code>'%02d:%02d:%02d' % @time.reverse.map(&:count)
#=> "11:30:52"
</code>```

Some improvements

You can get rid of reverse by changing the order of your @time array:

```<code>@time = [@hours, @minutes, @seconds]

'%02d:%02d:%02d' % @time.map(&:count)
#=> "11:30:52"
</code>```

This can be simplified further by providing a to_i method:

```<code>class Counter
  # ...

  def to_i
    @count
  end
end

# ...

@time = [@hours, @minutes, @seconds]

'%02d:%02d:%02d' % @time
#=> "11:30:52"
</code>```

The above works because % tries to call to_i when specifying an integer format.

Title: Ruby: combining methods into 1 line

Body:
I have an array of objects, and I want to take one of the methods to return it into 1 single line.

here is my array

def set
        @seconds = Counter.new('Seconds')
        @minutes = Counter.new('Minutes')
        @hours = Counter.new('Hours')

        @time = [@seconds, @minutes, @hours]
    end

and here is the method I'm trying to print in the Counter class

    def count
        @counts
    end

Here's my attempt

    def read
        reverse = @time.reverse
        @time.each do |t|
            return '%02d' %t.count.to_s.join(":")
        end
    end

(I also want them to be in 00, 01 formats, hence the '%02d')

.join doesn't seem to work (I'm guessing it works with arrays but not methods of an array?

any help will be appreciated!

Body:
Given this Counter class and some instances:

class Counter
  attr_accessor :count

  def initialize(name, count: 0)
    @name = name
    @count = count
  end
end

@seconds = Counter.new('Seconds', count: 52)
@minutes = Counter.new('Minutes', count: 30)
@hours = Counter.new('Hours', count: 11)

@time = [@seconds, @minutes, @hours]

You can extract the count values in hour / minute / second order via:

@time.reverse.map(&:count)
#=> [11, 30, 52]

This array can be passed (in its entirety) to String#% to produce a HH:MM:SS string:

'%02d:%02d:%02d' % @time.reverse.map(&:count)
#=> "11:30:52"

Some improvements

You can get rid of reverse by changing the order of your @time array:

@time = [@hours, @minutes, @seconds]

'%02d:%02d:%02d' % @time.map(&:count)
#=> "11:30:52"

This can be simplified further by providing a to_i method:

class Counter
  # ...

  def to_i
    @count
  end
end

# ...

@time = [@hours, @minutes, @seconds]

'%02d:%02d:%02d' % @time
#=> "11:30:52"

The above works because % tries to call to_i when specifying an integer format.


问:
locale_t is undefined in modelicastring.c
I got an error while compiling to use dymola model in opal-rt.

```<code>./ModelicaStrings.c(300): error: identifier "locale_t" is undefined
              locale_t loc = newlocale(LC_NUMERIC, "C", NULL);
              ^
</code>```

Can anyone help me to resolve this error?

答: Try to compile with NO_LOCALE defined. This should avoid the compilation error on OpalRT.

Body:
I got an error while compiling to use dymola model in opal-rt.

./ModelicaStrings.c(300): error: identifier "locale_t" is undefined
              locale_t loc = newlocale(LC_NUMERIC, "C", NULL);
              ^

Can anyone help me to resolve this error?


问:
how i just extract the link for class = main-bullet using web craweling
i used this and using this i will extract all the in the web page but i want specific link which are in the main-bullet class.

```<code>import requests
import bs4
res = requests.get('http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF')
print(res)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
h = soup.select('title')
print(h)
    #got all link of the website
all_links = soup.find_all("a")
for link in all_links:
    link.get("href")
    print(link.get("href"))
</code>```

I used this give all the links...

答:
you know xpath？XPath</p>

```<code>//*[@class="xxx"]
</code>```

Body:
i used this and using this i will extract all the in the web page but i want specific link which are in the main-bullet class.

import requests
import bs4
res = requests.get('http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF')
print(res)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
h = soup.select('title')
print(h)
    #got all link of the website
all_links = soup.find_all("a")
for link in all_links:
    link.get("href")
    print(link.get("href"))

I used this give all the links...

Body:
you know xpath？XPath

//*[@class="xxx"]


问:
Find whole word that starts at character position in R
```<code>Str <- "I love chocolate pudding"
pos <- 8
</code>```

I need to return the word that starts with the letter c at pos 8, which is chocolate. How can I do that?

答:
```<code>library(stringr)
str_extract(Str, "(?<=[\\w\\s]{7})\\bc\\w+\\b")
[1] "chocolate"
</code>```

This solution uses str_extract and positive lookbehind (?<=[\\w\\s]{7}), which can be glossed along these lines: "if you see seven characters consisting of alphanumeric characters (\\w) or white space (\\s) to the left, match the immediately next 'word' identified by its boundaries to either side (\\b) as well as the letter c occurring as the first letter of the word.

Alternatively, use sub and backreference:

```<code>sub(".{7}(\\bc\\w+\\b).*", "\\1", Str)
[1] "chocolate"
</code>```

Body:
Str <- "I love chocolate pudding"
pos <- 8

I need to return the word that starts with the letter c at pos 8, which is chocolate. How can I do that?

Body:
library(stringr)
str_extract(Str, "(?<=[\\w\\s]{7})\\bc\\w+\\b")
[1] "chocolate"

This solution uses str_extract and positive lookbehind (?<=[\\w\\s]{7}), which can be glossed along these lines: "if you see seven characters consisting of alphanumeric characters (\\w) or white space (\\s) to the left, match the immediately next 'word' identified by its boundaries to either side (\\b) as well as the letter c occurring as the first letter of the word.

Alternatively, use sub and backreference:

sub(".{7}(\\bc\\w+\\b).*", "\\1", Str)
[1] "chocolate"


问:
UIPickerView realtime update on TextField
As soon as I scroll the PickerView (or) UIDatePicker, I need the value to get displayed on a TextField :

While Scrolling. Even when the picker is moving the text field should update itself. Is it possible ?

On the event that the Picker stops moving and comes to rest. Is there an event for the PickerView to come to rest so that I could update the textField (as soon as the pickerView comes to rest).

```<code>  // I do not wish to use the TextFieldDidEndEditing
 // I want the textField to update itself when the picker view comes to rest.
</code>```

It would be helpful if anyone could solve 1) and 2)

答:
(1) might not be possible. For (2), you can use the delegate method pickerView:didSelectRow:inComponent. Let me know if you need any help with this.

For UIPickerView

(1) Implement pickerView:titleForRow:forComponent,

```<code>- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    // Every time the picker view is rotated, this method will be called to fetch the title.
    NSInteger selectedRow = [pickerView selectedRowInComponent:0];
    // Get selected row like above and process data and update text field.

    [..] // Process the title
    return the title.
}
</code>```

(2) This is more obvious.

```<code>- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
   // You have the selected row, update the text field.
}
</code>```

Body:
As soon as I scroll the PickerView (or) UIDatePicker, I need the value to get displayed on a TextField :

While Scrolling. Even when the picker is moving the text field should update itself. Is it possible ?

On the event that the Picker stops moving and comes to rest. Is there an event for the PickerView to come to rest so that I could update the textField (as soon as the pickerView comes to rest).

  // I do not wish to use the TextFieldDidEndEditing
 // I want the textField to update itself when the picker view comes to rest.

It would be helpful if anyone could solve 1) and 2)

Body:
(1) might not be possible. For (2), you can use the delegate method pickerView:didSelectRow:inComponent. Let me know if you need any help with this.

For UIPickerView

(1) Implement pickerView:titleForRow:forComponent,

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    // Every time the picker view is rotated, this method will be called to fetch the title.
    NSInteger selectedRow = [pickerView selectedRowInComponent:0];
    // Get selected row like above and process data and update text field.

    [..] // Process the title
    return the title.
}

(2) This is more obvious.

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
   // You have the selected row, update the text field.
}


问:
Why spring Data JPA does select before update & delete
I am using Spring data JPA now every-time I perform update or delete Spring data JPA does select before running actual query.

```<code>@Modifying
@Query("update Device d set d.latestDevice = ?1 where d.senderId = ?2")
@Transactional(readOnly = false)
int updateLatestDevice(Device newDevice, Integer senderId);

@Modifying
@Transactional(readOnly = false)
int deleteById(Integer deviceId);
</code>```

I can not find an exact answer to this situation.

答:
I'm not sure about the update, I'm actually surprised that it triggers a select.

The delete though triggers events which have the deleted entity as a payload so they need to get loaded.

Body:
I am using Spring data JPA now every-time I perform update or delete Spring data JPA does select before running actual query.

@Modifying
@Query("update Device d set d.latestDevice = ?1 where d.senderId = ?2")
@Transactional(readOnly = false)
int updateLatestDevice(Device newDevice, Integer senderId);

@Modifying
@Transactional(readOnly = false)
int deleteById(Integer deviceId);

I can not find an exact answer to this situation.


问:
Preview an image before it is uploaded
I want to be able to preview a file (image) before it is uploaded.  The preview action should be executed all in the browser without using Ajax to upload the image.

How can I do this?

答:
Try This

To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.

It needs an "onChange" event to load the image.

function preview() {
    frame.src=URL.createObjectURL(event.target.files[0]);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="file" onchange="preview()">
  <img id="frame" src="" width="100px" height="100px"/>
</form></code>```

To preview multiple image click here

Title: Preview an image before it is uploaded

Body:
Try This

To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.

It needs an "onChange" event to load the image.

function preview() {
    frame.src=URL.createObjectURL(event.target.files[0]);
}

<form>
  <input type="file" onchange="preview()">
  <img id="frame" src="" width="100px" height="100px"/>
</form>

To preview multiple image click here


问:
How to serialize specific string property from list of structures using Join function?
I have a list of custom structures and I would like to serialize one specific property into one string, but I don't know how to use Join function properly in such a case?

```<code> Structure structPerson
        Dim Name As String
        Dim Age As Integer
 End Structure

 Sub Main()

        Dim p1 As structPerson = New structPerson() With {.Name = "John", .Age = 20}
        Dim p2 As structPerson = New structPerson() With {.Name = "Samantha", .Age = 12}
        Dim persons As List(Of structPerson) = New List(Of structPerson) From {p1, p2}

        Dim strNames As String = persons.Join(", ", Function(p) p.Name)  'HOW TO JOIN NAMES OF ALL PERSONS IN LIST INTO ONE STRING?

        Debug.WriteLine(strNames)

 End Sub
</code>```

I would like to get string "John, Samantha" as a result using Join function.

Thank you for your suggestions.

#JK

答:
Dim strNames As String = String.Join(", ", persons.Select(Function(p) p.Name))
```

It's the shared String.Join method that you use to join numtiple Strings together with a separator between pairs. It will join any enumerable list of Strings or objects that will be converted to Strings. In the this case you use the LINQ function Select to get a list of Name values from your list of objects.

Body:
I have a list of custom structures and I would like to serialize one specific property into one string, but I don't know how to use Join function properly in such a case?

 Structure structPerson
        Dim Name As String
        Dim Age As Integer
 End Structure

 Sub Main()

        Dim p1 As structPerson = New structPerson() With {.Name = "John", .Age = 20}
        Dim p2 As structPerson = New structPerson() With {.Name = "Samantha", .Age = 12}
        Dim persons As List(Of structPerson) = New List(Of structPerson) From {p1, p2}

        Dim strNames As String = persons.Join(", ", Function(p) p.Name)  'HOW TO JOIN NAMES OF ALL PERSONS IN LIST INTO ONE STRING?

        Debug.WriteLine(strNames)

 End Sub

I would like to get string "John, Samantha" as a result using Join function.

Thank you for your suggestions.

#JK

Body:
Dim strNames As String = String.Join(", ", persons.Select(Function(p) p.Name))

It's the shared String.Join method that you use to join numtiple Strings together with a separator between pairs. It will join any enumerable list of Strings or objects that will be converted to Strings. In the this case you use the LINQ function Select to get a list of Name values from your list of objects.


问:
Can we increase lambda /tmp folder size ?, i Is there any method to append a file to S3
I have a lambda function that does some functions and generates a file. I have some append operation in this file so I write the file /tmp folder . after the process I upload to s3 . some times file size will bigger than 512mb so function fails. So is there any method I can write the file directly to s3. S3 does not support appending .I used python language in lambda

#

after so many searches, There is a python package smart_open that allow you to write directly to the s3

smart_open

答:
As described here, the storage of the /tmp folder cannot exceeds 512 MB. It will be better to remove your logic from  lambdas and at the end of your process, you just need to upload file to S3 by using boto3.
But if you are using image file, you can use Pillow to reduce file size before.


问:
Feature Policy Safari - Iframes - Youtube - ReactJS
I am working on my website and noticed an error that I cant figure out that deals with Feature Policy.

In Google Chrome, I do not receive the error but in Safari I do.
"Feature policy 'Fullscreen' check failed for iframe with origin 'https://www.youtube.com' and allow attribute ''."

I went and added "allow="autoplay; fullscreen"" to all of my youtube iframes but this has not solved the issue. Can anyone point me in the right direction?

I have also used allowFullScreen and allowFullScreen='allowFullScreen'

答:
Enable "Develop menu" in Safari settings

From the menu bar open "Develop" > "Experimental Features" > "Reset All to Defaults" (scroll to the bottom to see it)

Quit Safari (command + Q) and open it again and check if you error is fixed.

You may receive a prompt related to fullscreen permission, grant it.


问:
In Angular how can I pass the response of my post request as one of the parameters to go into another post request?
I have a form with two sections, that dispatch two post request actions, the second request needs parameters from the first one to be successfully sent. But I'm not sure how :( I have the request and response of the first action working fine but I'm just not sure how or where to implement the logic - should it be in the service? a reducer? I tried forkjoin then realised I had no idea what I was doing. Thanks in advance for any help!

My component :

```<code>
    const newArtist = this.store.dispatch(new CreateArtist({
      ...generalDetails,
      hometown,
    }))

    const newArtistExtraInfo = this.store.dispatch(new CreateDiscography({
      ...songCatalogue
    }
    ));

    forkJoin([newArtist, newArtistExtraInfo]).subscribe(result => {
      console.log(`the results are in : ${result}`)
    })
</code>```

答:
for that you need to extend the effect that handles CreateArtist to dispatch an another action.

ofType(actions.CreateArtist),
switchMap(action => this.http.get('url1')),
// this action goes to effects again to its own handler.
map(response => new CreateDiscography(someParams)),
```

Body:
I have a form with two sections, that dispatch two post request actions, the second request needs parameters from the first one to be successfully sent. But I'm not sure how :( I have the request and response of the first action working fine but I'm just not sure how or where to implement the logic - should it be in the service? a reducer? I tried forkjoin then realised I had no idea what I was doing. Thanks in advance for any help!

My component :

    const newArtist = this.store.dispatch(new CreateArtist({
      ...generalDetails,
      hometown,
    }))

    const newArtistExtraInfo = this.store.dispatch(new CreateDiscography({
      ...songCatalogue
    }
    ));

    forkJoin([newArtist, newArtistExtraInfo]).subscribe(result => {
      console.log(`the results are in : ${result}`)
    })


问:
How to update slice of struct in recursive fashion
For following code, I'm expecting output of {"NewName" [{"NewName" []}]} but it's not updating child structs. How can we make sure it updates every struct in hierarchy.

```<code>package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []red
}

func (r *red) setName(nameString string){
    r.Name = nameString
    for _, child := range r.Child{
        child.setName(nameString)
    }
}

func main() {
    obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("NewName")
    //Expectation {"NewName" [{"NewName" []}]}
    fmt.Print(obj)
}
</code>```

答:
Actually the problem is here

```<code>for _, ch := range r.Child{
        ch.setName(s)
}
</code>```

You are updating using ch which is not updating you r.Child slice actually. Your code is equivalent like this

```<code>var ch red
for i, _:= range r.Child{
    ch = r.Child[i]
    ch.setName(s)
}
</code>```

To solve this you can update the slice this way.

```<code>for i, _ := range r.Child {
    r.Child[i].setName(s) // access the slice eliment by index and update
}
</code>```

And it's a good pattern to use []*red for child.

Body:
For following code, I'm expecting output of {"NewName" [{"NewName" []}]} but it's not updating child structs. How can we make sure it updates every struct in hierarchy.

package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []red
}

func (r *red) setName(nameString string){
    r.Name = nameString
    for _, child := range r.Child{
        child.setName(nameString)
    }
}

func main() {
    obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("NewName")
    //Expectation {"NewName" [{"NewName" []}]}
    fmt.Print(obj)
}

Body:
Actually the problem is here

for _, ch := range r.Child{
        ch.setName(s)
}

You are updating using ch which is not updating you r.Child slice actually. Your code is equivalent like this

var ch red
for i, _:= range r.Child{
    ch = r.Child[i]
    ch.setName(s)
}

To solve this you can update the slice this way.

for i, _ := range r.Child {
    r.Child[i].setName(s) // access the slice eliment by index and update
}

And it's a good pattern to use []*red for child.


问:
Tabular Format not visible in Jupiter notebook
[The current Image of the csv file when I use panda to read it]

I was compelled to delete a few files from the Anaconda folder in my laptop and now when I used anaconda Jupyter notebook to work on a ML problem and used panda to display and read the csv file I see this(as per the image.  :::  https://i.stack.imgur.com/XUJxh.png) type of a view, instead of the fine looking tabular format .  Can someone please suggest me an idea to fix this.

答: just write data.head() instead of print data.head()