问:
Change radio button colour and select first element on load
I'm trying to populate radio buttons with data from MySQL.

I'd like the selected radio button to change colour, and the first element to be selected on page load.

How can I do this?

```<code><div class="panel bg-product">
  <?php
    $stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
    $stmt->execute();
    $stmt->bind_result($prod_id, $prod_name, $prod_price);
    while($stmt->fetch()) {
      echo '<label><input type="radio" name="config-prod" value="'.$prod_id.'"> ' .$prod_name.'</label><br>';
    }
    $stmt->close();
  ?>
</div>
</code>```

CSS:

```<code>.panel input[type="radio"]:checked + label{
  font-weight: 700;
  color: red;
  transition: color 0.5s ease;
}
</code>```

This CSS does not change the colour of the radio button when selected, nor is a radio button selected on load.

答:
This is your new CSS:

```<code>.input-list {
    list-style-type: none;
    width: 100%;
    padding: 0;
    margin: 0;
}

.input-list li input:checked{
  content: "";
      -webkit-appearance: push-button;
    width: 12px;
    border-radius: 13px;
    height: 12px;
    background: red;
}

.input-list li input:checked + label {
  color: red;
}
</code>```

New JS code:

```<code>document.querySelector("#radio li input").checked = true;
</code>```

And Your new PHP:

```<code>    <ul id="radio" class="input-list">
  <?php
    $stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
    $stmt->execute();
    $stmt->bind_result($prod_id, $prod_name, $prod_price);
    while($stmt->fetch()) {
      echo '<li>
              <input id="'.$prod_id.'" name="config-prod" value="'.$prod_id.'" type="radio">
              <label class="sub-label" for="'.$prod_id.'">'.$prod_name.'</label>
            </li>';
    }
    $stmt->close();
  ?>
</ul>
</code>```

And that's how it will look:

document.querySelector("#radio li input").checked = true;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input-list {
    list-style-type: none;
    width: 100%;
    padding: 0;
    margin: 0;
}

.input-list li input:checked {
  content: "";
      -webkit-appearance: push-button;
    width: 12px;
    border-radius: 13px;
    height: 12px;
    background: red;
}

.input-list li input:checked + label {
  color: red;
}</code>```

    <input id="first" name="radio" value="first" type="radio">
    first

    <input id="second" name="radio" value="second" type="radio">
    second

```

Body:
I'm trying to populate radio buttons with data from MySQL.

I'd like the selected radio button to change colour, and the first element to be selected on page load.

How can I do this?

  <?php
    $stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
    $stmt->execute();
    $stmt->bind_result($prod_id, $prod_name, $prod_price);
    while($stmt->fetch()) {
      echo '<input type="radio" name="config-prod" value="'.$prod_id.'"> ' .$prod_name.'
';
    }
    $stmt->close();
  ?>

CSS:

.panel input[type="radio"]:checked + label{
  font-weight: 700;
  color: red;
  transition: color 0.5s ease;
}

This CSS does not change the colour of the radio button when selected, nor is a radio button selected on load.

Body:
This is your new CSS:

.input-list {
    list-style-type: none;
    width: 100%;
    padding: 0;
    margin: 0;
}

.input-list li input:checked{
  content: "";
      -webkit-appearance: push-button;
    width: 12px;
    border-radius: 13px;
    height: 12px;
    background: red;
}

.input-list li input:checked + label {
  color: red;
}

New JS code:

document.querySelector("#radio li input").checked = true;

And Your new PHP:

    <ul id="radio" class="input-list">
  <?php
    $stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
    $stmt->execute();
    $stmt->bind_result($prod_id, $prod_name, $prod_price);
    while($stmt->fetch()) {
      echo '<li>
              <input id="'.$prod_id.'" name="config-prod" value="'.$prod_id.'" type="radio">
              <label class="sub-label" for="'.$prod_id.'">'.$prod_name.'</label>
            </li>';
    }
    $stmt->close();
  ?>
</ul>

And that's how it will look:

document.querySelector("#radio li input").checked = true;

.input-list {
    list-style-type: none;
    width: 100%;
    padding: 0;
    margin: 0;
}

.input-list li input:checked {
  content: "";
      -webkit-appearance: push-button;
    width: 12px;
    border-radius: 13px;
    height: 12px;
    background: red;
}

.input-list li input:checked + label {
  color: red;
}

<ul id="radio" class="input-list">
  <li>
    <input id="first" name="radio" value="first" type="radio">
    <label class="sub-label" for="first">first</label>
  </li>
  <li>
    <input id="second" name="radio" value="second" type="radio">
    <label class="sub-label" for="second">second</label>
  </li>
</ul>


来源: stackexchange

问:
alphabetically enumerate file lists with attributes
I'm trying to enumerate in alphabetical order two lists.

Issue being one
For now I'm using zip to do as follows:

```<code>lista = ['A', 'B', 'E', 'R']
listb = ['C', 'D', 'F', 'G']

for elt, (contenta, contentb) in enumerate(zip(lista, listb)):
    print('[{}] {}'.center(79).format(str(elt), contenta.name))
    print('[{}] {}'.center(79).format(str(elt), contentb))
</code>```

Now issue is that lista has a ".name" variable and that's what I'd like to print, however listb doesn't and I'd like to print listb directly (of course lista and listb are only used as examples)

So what I'd like to get is:

```<code>                                    [0] A
                                    [1] B
                                    [1] C
                                    [2] D
                                    [3] E
                                    [4] F
                                    [5] G
                                    [6] R
</code>```

However what I get is:

```<code>                                    [0] A
                                    [0] C
                                    [1] B
                                    [1] D
                                    [2] E
                                    [2] F
                                    [3] R
                                    [3] G
</code>```

I'm not sure how I would go to fix this? Is there anyway to sort and enumerate two lists while keeping the number consistent? And at the same time order it alphabetically?

答:
Sort lista + listb and enumerate on them:

```<code>lista = ['A', 'B', 'E', 'R']
listb = ['C', 'D', 'F', 'G']

for i, x in enumerate(sorted(lista + listb)):
    print(i, x)

# 0 A
# 1 B
# 2 C
# 3 D
# 4 E
# 5 F
# 6 G
# 7 R
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to enumerate in alphabetical order two lists.

Issue being one
For now I'm using zip to do as follows:

lista = ['A', 'B', 'E', 'R']
listb = ['C', 'D', 'F', 'G']

for elt, (contenta, contentb) in enumerate(zip(lista, listb)):
    print('[{}] {}'.center(79).format(str(elt), contenta.name))
    print('[{}] {}'.center(79).format(str(elt), contentb))

Now issue is that lista has a ".name" variable and that's what I'd like to print, however listb doesn't and I'd like to print listb directly (of course lista and listb are only used as examples)

So what I'd like to get is:

                                    [0] A
                                    [1] B
                                    [1] C
                                    [2] D
                                    [3] E
                                    [4] F
                                    [5] G
                                    [6] R

However what I get is:

                                    [0] A
                                    [0] C
                                    [1] B
                                    [1] D
                                    [2] E
                                    [2] F
                                    [3] R
                                    [3] G

I'm not sure how I would go to fix this? Is there anyway to sort and enumerate two lists while keeping the number consistent? And at the same time order it alphabetically?

Body:
Sort lista + listb and enumerate on them:

lista = ['A', 'B', 'E', 'R']
listb = ['C', 'D', 'F', 'G']

for i, x in enumerate(sorted(lista + listb)):
    print(i, x)

# 0 A
# 1 B
# 2 C
# 3 D
# 4 E
# 5 F
# 6 G
# 7 R


问:
How can one declare unreachable code in Java?
I have a complex case in a switch statement that (as it happens) always abruptly terminates (with a return, or break or ...).  I'd like to put something like lint's  /*UNREACHABLE*/ declaration so as to indicate to anyone reading the code that it doesn't fall through to the next case (a common bug in Java).  I'm looking for a more formal way to indicate this, ideally something that would cause a compiler warning or error if it was not unreachable.  Any ideas?

```<code>    switch (x) {
        case 1:
           if (...) {
             switch (.) {
                ...
             }
           } else {
             ...
           }
           /*UNREACHABLE*/
        case 2:
           ...
    }
</code>```

The code is truly unreachable and the Java compiler knows it is, so I can't put any (normal) code there because it would be marked as unreachable code by the compiler.

答:
If you are open to wild hacks, you can insert unused cases between the valid ones:

```<code>switch (x) {
    case 1:
       if (...) {
         switch (.) {
            ...
         }
       } else {
         ...
       }
    case -1:
       /*UNREACHABLE*/
       throw new RuntimeException("nope");

    case 2:
       ...
}
</code>```

Personally I do not think I would use this, but it should work.

Body:
I have a complex case in a switch statement that (as it happens) always abruptly terminates (with a return, or break or ...).  I'd like to put something like lint's  /*UNREACHABLE*/ declaration so as to indicate to anyone reading the code that it doesn't fall through to the next case (a common bug in Java).  I'm looking for a more formal way to indicate this, ideally something that would cause a compiler warning or error if it was not unreachable.  Any ideas?

    switch (x) {
        case 1:
           if (...) {
             switch (.) {
                ...
             }
           } else {
             ...
           }
           /*UNREACHABLE*/
        case 2:
           ...
    }

The code is truly unreachable and the Java compiler knows it is, so I can't put any (normal) code there because it would be marked as unreachable code by the compiler.

Body:
If you are open to wild hacks, you can insert unused cases between the valid ones:

switch (x) {
    case 1:
       if (...) {
         switch (.) {
            ...
         }
       } else {
         ...
       }
    case -1:
       /*UNREACHABLE*/
       throw new RuntimeException("nope");

    case 2:
       ...
}

Personally I do not think I would use this, but it should work.


问:
SpelParseException: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
I am trying to condtionally create a component using @ConditionalOnExpression("not ${service.synchronous} && not ${service.disabled}").

I based this on Spring Boot SpEL ConditionalOnExpression check multiple properties, which provides a multi-property conditional as follows: @ConditionalOnExpression("${properties.first.property.enable:true} && ${properties.second.property.startServer:false}")

However, I keep getting:

Caused by: org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

Those properties are always set in my .properties file so I did not provide a default value with the colon notation. What am I doing wrong?

答:
You will need to provide the default values for your properties like in the example you followed, so update the expression to be:</p>

```<code>@ConditionalOnExpression("not ${service.synchronous:false} && not ${service.disabled:true}")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You will need to provide the default values for your properties like in the example you followed, so update the expression to be:

@ConditionalOnExpression("not ${service.synchronous:false} && not ${service.disabled:true}")


问:
How to change the folder name of a PrestaShop module?
I need change folder name on FTP of one of modules in PrestaShop 1.7. Where in database or any files of PrestaShop I should rewrite this change?</p>

答:
I'd recommend the following:

First, uninstall the module from the PrestaShop Admin Panel

Then, rename the module's folder via FTP

Then, make sure you also rename the main module file inside the module's folder

Lastly, edit this file, and make sure you update the module's name and class name

Re-install the module

Voilà! By proceeding this way, you don't have to make any changes in database.

I hope this helps.


答:
It's processed at same time between elements of lista and listb because you use zip.

So, I recommend that making lists to one list first and sorting alphabetically.

```<code>lista = ['A', 'B', 'E', 'R']
listb = ['C', 'D', 'F', 'G']

listc = lista + listb
listc.sort()

for elt, content in enumerate(listc):
    print('[{}] {}'.center(79).format(str(elt), content))
</code>```

The Result:

```<code>                                    [0] A
                                    [1] B
                                    [2] C
                                    [3] D
                                    [4] E
                                    [5] F
                                    [6] G
                                    [7] R
</code>```

Title: alphabetically enumerate file lists with attributes

Body:
It's processed at same time between elements of lista and listb because you use zip.

So, I recommend that making lists to one list first and sorting alphabetically.

lista = ['A', 'B', 'E', 'R']
listb = ['C', 'D', 'F', 'G']

listc = lista + listb
listc.sort()

for elt, content in enumerate(listc):
    print('[{}] {}'.center(79).format(str(elt), content))

The Result:

                                    [0] A
                                    [1] B
                                    [2] C
                                    [3] D
                                    [4] E
                                    [5] F
                                    [6] G
                                    [7] R


问:
How to get count of each item in a list
I have csv where it reads transaction like as follows

Diaper Cola Paste

Diaper Cola Pen

I would like to get the count of each transaction items as follows:

Diaper:1 Cola:1 Paste:1

Diaper:1 Cola:1 Pen:1

The code i tried is :

```<code>from collections import Counter

def M():
    list=[]
    DataCaptured= csv.reader(Datafile,delimiter=" ")
    for row in DataCaptured:
        list.append(row)
    Counter(list)
</code>```

I am getting list is unhashable error.

答:
Some issues/fixed in your code

Don't use python built-in keywords like list for your list variable, use some other name e.g li

You want to pass a file object to csv.reader, and not the name of the file

You want to append the Counter on each row in a single list via li.append(row)

Once we have this fixes, the code changes to

```<code>from collections import Counter
import csv

def M():
    li=[]
    #Open the csv file
    with open('file.txt') as fp:
        DataCaptured = csv.reader(fp,delimiter=' ')
        #Iterate throught each word in csv and add it's counter to the row
        for row in DataCaptured:
            li.append(dict(Counter(row)))
    #Return the list of counters
    return li

print(M())
</code>```

The output will be

```<code>[{'Diaper': 1, 'Cola': 1, 'Paste': 1},
{'Diaper': 1, 'Cola': 1, 'Pen': 1}]
</code>```

Title: How to get count of each item in a list

Body:
I have csv where it reads transaction like as follows

Diaper Cola Paste

Diaper Cola Pen

I would like to get the count of each transaction items as follows:

Diaper:1 Cola:1 Paste:1

Diaper:1 Cola:1 Pen:1

The code i tried is :

from collections import Counter

def M():
    list=[]
    DataCaptured= csv.reader(Datafile,delimiter=" ")
    for row in DataCaptured:
        list.append(row)
    Counter(list)

I am getting list is unhashable error.

Body:
Some issues/fixed in your code

Don't use python built-in keywords like list for your list variable, use some other name e.g li

You want to pass a file object to csv.reader, and not the name of the file

You want to append the Counter on each row in a single list via li.append(row)

Once we have this fixes, the code changes to

from collections import Counter
import csv

def M():
    li=[]
    #Open the csv file
    with open('file.txt') as fp:
        DataCaptured = csv.reader(fp,delimiter=' ')
        #Iterate throught each word in csv and add it's counter to the row
        for row in DataCaptured:
            li.append(dict(Counter(row)))
    #Return the list of counters
    return li

print(M())

The output will be

[{'Diaper': 1, 'Cola': 1, 'Paste': 1},
{'Diaper': 1, 'Cola': 1, 'Pen': 1}]


问:
How to create the file in azure storage blob using SQL Server
I am looking for an approach to create the file in the azure blob storage using SQL server Stored procedure.

I tried to use below approach

```<code>CREATE CREDENTIAL indcredential
WITH IDENTITY= 'storage account name', -- this is the name of the storage account you specified when creating a storage account
SECRET = 'key1'

BACKUP DATABASE ILS
TO URL = 'blobpath/dbbackup.bacpac'
/* URL includes the endpoint for the BLOB service, followed by the container name, and the name of the backup file*/
WITH CREDENTIAL = 'indcredential' ;
/* name of the credential you created in the previous step */
GO
</code>```

Using the above code , I am able to create the db backup file dbbackup.bacpac in azure storage.

Any idea how to create the simple text file in azure blob path ?

答:
I am looking for an approach to create the file in the azure blob storage using SQL server Stored procedure.

There's no direct way to do this.  You can read files from BLOB storage, but not write them.  Instead, you can use an Azure Function, or perhaps a Logic App to copy data from Azure SQL Database to Azure Storage.

Body:
I am looking for an approach to create the file in the azure blob storage using SQL server Stored procedure.

I tried to use below approach

CREATE CREDENTIAL indcredential
WITH IDENTITY= 'storage account name', -- this is the name of the storage account you specified when creating a storage account
SECRET = 'key1'

BACKUP DATABASE ILS
TO URL = 'blobpath/dbbackup.bacpac'
/* URL includes the endpoint for the BLOB service, followed by the container name, and the name of the backup file*/
WITH CREDENTIAL = 'indcredential' ;
/* name of the credential you created in the previous step */
GO

Using the above code , I am able to create the db backup file dbbackup.bacpac in azure storage.

Any idea how to create the simple text file in azure blob path ?


问:
enumerate in dictionary loop take long time how to improv the speed
I am using python-3.x and I would like to speed my code where in every loop, I am creating new values and I checked if they exist or not in the dictionary by using the (check if) then I will keep the index where it is found if it exists in the dictionary. I am using the enumerate but it takes a long time and it very clear way. is there any way to speed my code by using another way or in my case the enumerate is the only way I need to work with? I am not sure in my case using numpy will be better.

Here is my code:

```<code># import numpy
import numpy as np

# my first array
my_array_1 = np.random.choice ( np.linspace ( -1000 , 1000 , 2 ** 8 ) , size = ( 100 , 3 ) , replace = True )
my_array_1 = np.array(my_array_1)

# here I want to find the unique values from my_array_1
indx = np.unique(my_array_1, return_index=True, return_counts= True,axis=0)

#then saved the result to dictionary
dic_t= {"my_array_uniq":indx[0], # unique values in my_array_1
       "counts":indx[2]} # how many times this unique element appear on my_array_1

# here I want to create random array 100 times
for i in range (100):

    print (i)

    # my 2nd array
    my_array_2 = np.random.choice ( np.linspace ( -1000 , 1000 , 2 ** 8 ) , size = ( 100 , 3 ) , replace = True )
    my_array_2 = np.array(my_array_2)

#   I would like to check if the values in my_array_2 exists or not in the dictionary (my_array_uniq":indx[0])
#   if it exists then I want to hold the index number of that value in the dictionary and
#    add 1 to the dic_t["counts"], which mean this value appear agin and cunt how many.
#   if not exists, then add this value to the dic (my_array_uniq":indx[0])
#    also add 1 to the dic_t["counts"]
    for i, a in enumerate(my_array_2):

        ix = [k for k,j in enumerate(dic_t["my_array_uniq"]) if (a == j).all()]
        if ix:

            print (50*"*", i, "Yes", "at", ix[0])
            dic_t["counts"][ix[0]] +=1

        else:
#            print (50*"*", i, "No")
            dic_t["counts"] =  np.hstack((dic_t["counts"],1))
            dic_t["my_array_uniq"] = np.vstack((dic_t["my_array_uniq"], my_array_2[i]))
</code>```

explanation:

```<code>1- I will create an initial array.
2- then I want to find the unique values, index and count from an initial array by using (np.unique).
3- saved the result to the dictionary (dic_t)
4- Then I want to start the loop by creating random values 100 times.
5- I would like to check if this random values in my_array_2 exist or not in the dictionary (my_array_uniq":indx[0])
6- if one of them exists then I want to hold the index number of that value in the dictionary.
7 - add 1 to the dic_t["counts"], which mean this value appears again and count how many.
8- if not exists, then add this value to the dic as new unique value (my_array_uniq":indx[0])
9 - also add 1 to the dic_t["counts"]
</code>```

答:
So from what I can see you are

Creating 256 random numbers from a linear distribution of numbers between -1000 and 1000

Generating 100 triplets from those (it could be fewer than 100 due to unique but with overwhelming probability it will be exactly 100)

Then doing pretty much the same thing 100 times and each time checking for each of the triplets in the new list whether they exist in the old list.

You're then trying to get a count of how often each element occurs.

I'm wondering why you're trying to do this, because it doesn't make much sense to me, but I'll give a few pointers:

There's no reason to make a dictionary dic_t if you're only going to hold to objects in it, just use two variables my_array_uniq and counts

You're dealing with triplets of floating point numbers. In the given range, that should give you about 10^48 different possible triplets (I may be wrong on the exact number but it's an absurdly large number either way). The way you're generating them does reduce the total phase-space a fair bit, but nowhere near enough. The probability of finding identical ones is very very low.

If you have a set of objects (in this case number triplets) and you want to determine whether you have seen a given one before, you want to use sets. Sets can only contain immutable objects, so you want to turn your triplets into tuples. Determining whether a given triplet is already contained in your set is then an O(1) operation.

For counting the number of occurences of sth, collections.Counter is the natural datastructure to use.

Body:
I am using python-3.x and I would like to speed my code where in every loop, I am creating new values and I checked if they exist or not in the dictionary by using the (check if) then I will keep the index where it is found if it exists in the dictionary. I am using the enumerate but it takes a long time and it very clear way. is there any way to speed my code by using another way or in my case the enumerate is the only way I need to work with? I am not sure in my case using numpy will be better.

Here is my code:

# import numpy
import numpy as np

# my first array
my_array_1 = np.random.choice ( np.linspace ( -1000 , 1000 , 2 ** 8 ) , size = ( 100 , 3 ) , replace = True )
my_array_1 = np.array(my_array_1)

# here I want to find the unique values from my_array_1
indx = np.unique(my_array_1, return_index=True, return_counts= True,axis=0)

#then saved the result to dictionary
dic_t= {"my_array_uniq":indx[0], # unique values in my_array_1
       "counts":indx[2]} # how many times this unique element appear on my_array_1

# here I want to create random array 100 times
for i in range (100):

    print (i)

    # my 2nd array
    my_array_2 = np.random.choice ( np.linspace ( -1000 , 1000 , 2 ** 8 ) , size = ( 100 , 3 ) , replace = True )
    my_array_2 = np.array(my_array_2)

#   I would like to check if the values in my_array_2 exists or not in the dictionary (my_array_uniq":indx[0])
#   if it exists then I want to hold the index number of that value in the dictionary and
#    add 1 to the dic_t["counts"], which mean this value appear agin and cunt how many.
#   if not exists, then add this value to the dic (my_array_uniq":indx[0])
#    also add 1 to the dic_t["counts"]
    for i, a in enumerate(my_array_2):

        ix = [k for k,j in enumerate(dic_t["my_array_uniq"]) if (a == j).all()]
        if ix:

            print (50*"*", i, "Yes", "at", ix[0])
            dic_t["counts"][ix[0]] +=1

        else:
#            print (50*"*", i, "No")
            dic_t["counts"] =  np.hstack((dic_t["counts"],1))
            dic_t["my_array_uniq"] = np.vstack((dic_t["my_array_uniq"], my_array_2[i]))

explanation:

1- I will create an initial array.
2- then I want to find the unique values, index and count from an initial array by using (np.unique).
3- saved the result to the dictionary (dic_t)
4- Then I want to start the loop by creating random values 100 times.
5- I would like to check if this random values in my_array_2 exist or not in the dictionary (my_array_uniq":indx[0])
6- if one of them exists then I want to hold the index number of that value in the dictionary.
7 - add 1 to the dic_t["counts"], which mean this value appears again and count how many.
8- if not exists, then add this value to the dic as new unique value (my_array_uniq":indx[0])
9 - also add 1 to the dic_t["counts"]


问:
Listener keydown : backspace and field length
I'm wondering why my Backspace touch increment my countLetters variable.

I ask him to return the number of characters, without ever manually incrementing the variable. Why does the backspace key increment my variable once, before working properly?

```<code>const $textareas   = document.querySelectorAll('.js-textarea');

$textareas.forEach(function($textarea) {
  $textarea.addEventListener('keydown', function(event) {
    let max = 100;
    let countLetters = $textarea.value.length;

    let $meta = this.nextSibling.nextSibling; // = meta

    $meta.innerHTML = countLetters + ' / ' + max;

    if (countLetters >= max) {
      $textarea.value.toString().substring(0, max);
    }

    if (event.which != 46) {
      return;
    }

    // Disabled <textarea>
    if (countLetters >= max) {
      event.preventDefault();
    }
  });
});
</code>```

Demo is available on Here's Codepen!

Thanks

答: Keydown fires before letter was added or removed in case of backspace. Use keyup instead of keydown.

Body:
I'm wondering why my Backspace touch increment my countLetters variable.

I ask him to return the number of characters, without ever manually incrementing the variable. Why does the backspace key increment my variable once, before working properly?

const $textareas   = document.querySelectorAll('.js-textarea');

$textareas.forEach(function($textarea) {
  $textarea.addEventListener('keydown', function(event) {
    let max = 100;
    let countLetters = $textarea.value.length;

    let $meta = this.nextSibling.nextSibling; // = meta

    $meta.innerHTML = countLetters + ' / ' + max;

    if (countLetters >= max) {
      $textarea.value.toString().substring(0, max);
    }

    if (event.which != 46) {
      return;
    }

    // Disabled <textarea>
    if (countLetters >= max) {
      event.preventDefault();
    }
  });
});

Demo is available on Here's Codepen!

Thanks


问:
How to find the list of pairs in an array using ruby?
Input:

```<code>a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
</code>```

How to list out no of pairs in an array.

Output:

9

Description

```<code>#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs
</code>```

答:
Here is another option:

```<code>a.group_by(&:itself).transform_values{ |v| v.size / 2 }.values.sum
#=> 9
</code>```

How it works.

First group the elements by value:

```<code>a.group_by(&:itself) #=> {4=>[4, 4, 4, 4, 4], 5=>[5, 5, 5, 5, 5, 5], 6=>[6, 6, 6, 6, 6], 1=>[1, 1], 3=>[3, 3]}
</code>```

Then transforming the keys to the pair count:

```<code>a.group_by(&:itself).transform_values{ |v| v.size / 2 } #=> {4=>2, 5=>3, 6=>2, 1=>1, 3=>1}
</code>```

So, get the values of the hash:

```<code>a.group_by(&:itself).transform_values{ |v| v.size / 2 }.values #=> [2, 3, 2, 1, 1]
</code>```

Finally, sum the values, which is the first line of code posted above.

Body:
Input:

a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]

How to list out no of pairs in an array.

Output:

9

Description

#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs

Body:
Here is another option:

a.group_by(&:itself).transform_values{ |v| v.size / 2 }.values.sum
#=> 9

How it works.

First group the elements by value:

a.group_by(&:itself) #=> {4=>[4, 4, 4, 4, 4], 5=>[5, 5, 5, 5, 5, 5], 6=>[6, 6, 6, 6, 6], 1=>[1, 1], 3=>[3, 3]}

Then transforming the keys to the pair count:

a.group_by(&:itself).transform_values{ |v| v.size / 2 } #=> {4=>2, 5=>3, 6=>2, 1=>1, 3=>1}

So, get the values of the hash:

a.group_by(&:itself).transform_values{ |v| v.size / 2 }.values #=> [2, 3, 2, 1, 1]

Finally, sum the values, which is the first line of code posted above.


问:
How to get a Clickable Link inside this text string in PHP
I have tried to send an email from PHP with the next body:

```<code>$message .= 'This is a simple message';
$message .= "\n";
$message .= 'http://www.yahoo.com';
$message .= "\n";
$message .= "<a href='https://www.google.com'>Google</a>";
$message .= "\n";
</code>```

As a result I got the next output:

```<code>This is a simple message    //This line is ok
http://www.yahoo.com        //This line is ok
<a href='https://www.google.com'>Google</a> //It should appear the word Google clickable but it does not
</code>```

Instead of having the word Google with the link clickable to the Google site I get the html code, how could I fix this? Thanks

答:
I'm not sure, haven't tried it but maybe try:

```<code>$message .= '<a href="https://www.google.com">Google</a>';
</code>```

NOTE: added double quotes in href link

Body:
I have tried to send an email from PHP with the next body:

$message .= 'This is a simple message';
$message .= "\n";
$message .= 'http://www.yahoo.com';
$message .= "\n";
$message .= "Google";
$message .= "\n";

As a result I got the next output:

This is a simple message    //This line is ok
http://www.yahoo.com        //This line is ok
Google //It should appear the word Google clickable but it does not

Instead of having the word Google with the link clickable to the Google site I get the html code, how could I fix this? Thanks

Body:
I'm not sure, haven't tried it but maybe try:

$message .= '<a href="https://www.google.com">Google</a>';

NOTE: added double quotes in href link


问:
How to highlight item currently selected in a gallery?
I've come with a problem. I need to highlight the selected item within a Gallery. I've tried changing the appearance of the selected view through this method:

```<code>@Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
</code>```

The second parameter of that view is the current selected view, and I'm trying in this case, increase the size of the text. However this doesn't work, not even if I call invalidate in the selected item or in the entire Gallery.

This is the code I use to change the textview text size

```<code>TextView textview = (TextView)view;
textview.setTextSize(50, TypedValue.COMPLEX_UNIT_SP);
textview.invalidate();
</code>```

Do you know how to do this? Thanks

答:
Try StateListDrawable - looks apt for your situation.

UPDATE: You have reversed the parameters in setTextSize. It should be:

```<code>textview.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
</code>```

Body:
I've come with a problem. I need to highlight the selected item within a Gallery. I've tried changing the appearance of the selected view through this method:

@Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)

The second parameter of that view is the current selected view, and I'm trying in this case, increase the size of the text. However this doesn't work, not even if I call invalidate in the selected item or in the entire Gallery.

This is the code I use to change the textview text size

TextView textview = (TextView)view;
textview.setTextSize(50, TypedValue.COMPLEX_UNIT_SP);
textview.invalidate();

Do you know how to do this? Thanks

Body:
Try StateListDrawable - looks apt for your situation.

UPDATE: You have reversed the parameters in setTextSize. It should be:

textview.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);


问:
using arrays to query with SELECT with PHP
I'm querying a table that returns id's and I'd like to use these id's within an array to perform another query.

I have the two queries working independently of each other by hard coding the id's into the second query just to be sure that it functions as expected, which it does.

```<code>$query = "SELECT item_id FROM items";

$query = "SELECT * FROM results WHERE results_item_id in (1,2,3,4)";
</code>```

I'd like the return of the second query to include data for all of the id's returned to me from the first query.

答:
Instead of sub query, you can do it by JOIN matching ON item_id = results_item_id

```<code>$query = "SELECT R.* FROM results R JOIN items I ON I.item_id = R.results_item_id";
</code>```

Body:
I'm querying a table that returns id's and I'd like to use these id's within an array to perform another query.

I have the two queries working independently of each other by hard coding the id's into the second query just to be sure that it functions as expected, which it does.

$query = "SELECT item_id FROM items";

$query = "SELECT * FROM results WHERE results_item_id in (1,2,3,4)";

I'd like the return of the second query to include data for all of the id's returned to me from the first query.

Body:
Instead of sub query, you can do it by JOIN matching ON item_id = results_item_id

$query = "SELECT R.* FROM results R JOIN items I ON I.item_id = R.results_item_id";


问:
How to install and run project in github
Im a newbie in Reactjs. I get project from github but cant run it though i npm install and npm run build it. Here is the project i try to install in my computer: https://github.com/iuliaL/diagonistician-ReactJS-Express-Mongoose-RestAPI

Thank you very much, << sorry but stackoverflow doesnt allow me post this question so i type some line >>

答:
Try to follow these steps.

Git clone... git clone https://github.com/iuliaL/diagonistician-ReactJS-Express-Mongoose-RestAPI.git

Enter into project directory... cd diagonistician-ReactJS-Express-Mongoose-RestAPI

Install npm dependancy npm install

start npm server npm run build

that's all. Now browse to localhost: on browser.


问:
SQL: extracting a number in middle of a cell from a different table
I need help extracting a number within a number from a different table.
I'll explain:
1st table has phone numbers.
example: +12125634533, +41542858585

2nd table has

country code | second column
-------------+--------------
1            | usa
41           | switzerland
```

how do I get the operator within the numbers?

example:

+12125634533 -- operator is 212 (1 is the country code, 5634533 is the phone number - always 7 numbers)

+41542858585 -- operator is 54 (41 is the country code, 2858585 is the phonen number).

答:
Assuming the phone prefixes are unique and the phone numbers always start with +, then something like this:

```<code>select t1.*,
       substring(t1.phonenumber, 2 + len(t2.countrycode),
                 len(t1.phonenumber) - 7 - len(t2.countrycode) - 1
                )
from table1 t1 left join
     table2 t2
     on t1.phonenumber like '+' + t2.countrycode + '%';
</code>```

Here is a db<>fiddle.

Body:
I need help extracting a number within a number from a different table.
I'll explain:
1st table has phone numbers.
example: +12125634533, +41542858585

2nd table has

country code | second column
-------------+--------------
1            | usa
41           | switzerland

how do I get the operator within the numbers?

example:

+12125634533 -- operator is 212 (1 is the country code, 5634533 is the phone number - always 7 numbers)

+41542858585 -- operator is 54 (41 is the country code, 2858585 is the phonen number).

Body:
Assuming the phone prefixes are unique and the phone numbers always start with +, then something like this:

select t1.*,
       substring(t1.phonenumber, 2 + len(t2.countrycode),
                 len(t1.phonenumber) - 7 - len(t2.countrycode) - 1
                )
from table1 t1 left join
     table2 t2
     on t1.phonenumber like '+' + t2.countrycode + '%';

Here is a db<>fiddle.


问:
How to generically format a boolean to a Yes/No string?
I would like to display Yes/No in different languages according to some boolean variable.

Is there a generic way to format it according to the locale passed to it?

If there isn't, what is the standard way to format a boolean besides boolVar ? Resources.Yes : Resources.No.

I'm guessing that boolVar.ToString(IFormatProvider) is involved.

Is my assumption correct?

答:
The framework itself does not provide this for you (as far as I know). Translating true/false into yes/no does not strike me as more common than other potential translations (such as on/off, checked/unchecked, read-only/read-write or whatever).

I imagine that the easiest way to encapsulate the behavior is to make an extension method that wraps the construct that you suggest yourself in your question:

```<code>public static class BooleanExtensions
{
    public static string ToYesNoString(this bool value)
    {
        return value ? Resources.Yes : Resources.No;
    }
}
</code>```

Usage:

```<code>bool someValue = GetSomeValue();
Console.WriteLine(someValue.ToYesNoString());
</code>```

Body:
The framework itself does not provide this for you (as far as I know). Translating true/false into yes/no does not strike me as more common than other potential translations (such as on/off, checked/unchecked, read-only/read-write or whatever).

I imagine that the easiest way to encapsulate the behavior is to make an extension method that wraps the construct that you suggest yourself in your question:

public static class BooleanExtensions
{
    public static string ToYesNoString(this bool value)
    {
        return value ? Resources.Yes : Resources.No;
    }
}

Usage:

bool someValue = GetSomeValue();
Console.WriteLine(someValue.ToYesNoString());


问:
How to specify second argument in Jest v24.6 toMatchSnapshot(propertyMatchers?, hint?)?
I'm updating Jest snapshot tests after upgrading from Jest v22 to Jest v24. The toMatchSnapshot() function changed to taking 2 parameters instead of 1, as seen here -

v22 - https://jestjs.io/docs/en/22.x/expect#tomatchsnapshotoptionalstring

v24 - https://jestjs.io/docs/en/expect#tomatchsnapshotpropertymatchers-hint

I still want to use the hint (string) parameter but I don't want to use the propertyMatchers (object) parameter. Unfortunately, if I just pass in an empty object literal (ex. toMatchSnapshot({}, 'test')), it causes the generated snapshot output to be an object of ~100000+ lines rather than the XML output as before.

Any ideas on how I might be able to do this? Has anyone run into a similar problem with generated snapshot output?

A sample implementation would look like this:

```<code>test('Test', () => {
    files.forEach((file) => {
        expect(file.data).toMatchSnapshot({}, file.path);
    });
)};
</code>```

答:
If you pass a string in as the first argument instead of an object, Jest will treat it as the hint ('optional snapshot name' in v22 terminology):</p>

```<code>test('Test', () => {
    files.forEach((file) => {
        expect(file.data).toMatchSnapshot(file.path);
    });
)};
</code>```

Body:
I'm updating Jest snapshot tests after upgrading from Jest v22 to Jest v24. The toMatchSnapshot() function changed to taking 2 parameters instead of 1, as seen here -

v22 - https://jestjs.io/docs/en/22.x/expect#tomatchsnapshotoptionalstring

v24 - https://jestjs.io/docs/en/expect#tomatchsnapshotpropertymatchers-hint

I still want to use the hint (string) parameter but I don't want to use the propertyMatchers (object) parameter. Unfortunately, if I just pass in an empty object literal (ex. toMatchSnapshot({}, 'test')), it causes the generated snapshot output to be an object of ~100000+ lines rather than the XML output as before.

Any ideas on how I might be able to do this? Has anyone run into a similar problem with generated snapshot output?

A sample implementation would look like this:

test('Test', () => {
    files.forEach((file) => {
        expect(file.data).toMatchSnapshot({}, file.path);
    });
)};

Body:
If you pass a string in as the first argument instead of an object, Jest will treat it as the hint ('optional snapshot name' in v22 terminology):

test('Test', () => {
    files.forEach((file) => {
        expect(file.data).toMatchSnapshot(file.path);
    });
)};


问:
RegEx for capturing a word in between = and ;
I want to select word2 from the following :

```<code>word2;word3
</code>```

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line
like word2 from

```<code>word1=word2;word3
</code>```

I have tried using this regex

```<code>(?<=\=|^).*?(?=;)
</code>```

which select the word2 from

```<code>word2;word3
</code>```

but also the whole word1=word2 from

```<code>word1=word2;word3
</code>```

答:
Instead of using regular expresions you can solve the problem with String class methods.

```<code>string[] words = str.Split(';');
string word2 = words[0].Substring(words[0].IndexOf('=') + 1);
</code>```

First line splits the line from ';'. Assuming you just have a single ';' this statement splits your line into two strings. And second line returns a substring of first part (words[0]) starting from the first occurence of '=' (words[0].IndexOf('=')) character's next characher (+1) to the end. If your line doesn't have any '=' characters it just starts from the beginning because IndexOf returns -1.

Related documentation:

https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof?view=netframework-4.8

Body:
I want to select word2 from the following :

word2;word3

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line
like word2 from

word1=word2;word3

I have tried using this regex

(?<=\=|^).*?(?=;)

which select the word2 from

word2;word3

but also the whole word1=word2 from

word1=word2;word3

Body:
Instead of using regular expresions you can solve the problem with String class methods.

string[] words = str.Split(';');
string word2 = words[0].Substring(words[0].IndexOf('=') + 1);

First line splits the line from ';'. Assuming you just have a single ';' this statement splits your line into two strings. And second line returns a substring of first part (words[0]) starting from the first occurence of '=' (words[0].IndexOf('=')) character's next characher (+1) to the end. If your line doesn't have any '=' characters it just starts from the beginning because IndexOf returns -1.

Related documentation:

https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof?view=netframework-4.8


问:
DocuSign API - Creating a document - How do you enable links for HTML content in the document?
I am trying to add a document to my DocuSign envelope using the REST API.

This document is being added by converting an HTML document to a base64 string and setting this string as the value for the DocumentBase64 property of the document (See https://developers.docusign.com/esign-rest-api/reference/Envelopes/Envelopes/create/#envelopeDefinition).

My concern is that the HTML document has some links, but those links are not clickable in the DocuSign signing session. Is there any way to allow for links to be clickable/navigatable?

答:
Due to security concerns, links in documents sent to DocuSign are disabled.
This applies to all document source types including links in HTML, PDF, Word, and other document source types.

If you want to provide optional documents to the signers or other recipients for them to potentially look at while they're signing a document, there are several options:

Use Supplemental documents. These are separate documents that are included in the envelope for the recipient to (optionally) refer to.

Use Smart Sections. This enables you to mark sections of a document as optional. They're then only shown if the recipient clicks on them.


问:
Generic cleanup attribute for malloced memory
There is GCC-specific attribute cleanup. It might be used like this:

```<code>#define SCOPED_FILE __attribute__((cleanup(cleanup_file)))

void
cleanup_file(FILE **file) {
    if (*file != NULL) { fclose(*file); }
}
…
FILE *SCOPED_FILE file = fopen(…); // file will be closed at the end of scope.
</code>```

I thought it would be handy to have cleanup function for any malloced memory. Having to circumvent casting issues, I came up with the following implementation:

```<code>#define SCOPED_MEM __attribute__((cleanup(cleanup_mem)))

static inline void
cleanup_mem(void *pmem) {
    void *mem = *(void **)pmem;
    free(mem);
}

int main(void) {
    char *SCOPED_MEM str = malloc(20);
    strcpy(str, "pineapple");
    printf("hi, %s\n", str);
    // str will be free'd at the end of scope
}
</code>```

It does work, but smells funny, because I don't directly specify void ** as parameter type, but rather cast to it.
I wonder, if there are some problems with it that I don't see right now.

答:
but smells funny, because I don't directly specify void ** as parameter type, but rather cast to it.

Casts in C are often code smells, so you should ask yourself: why is the cast necessary?

One's first approach probably would be:

```<code>static inline void
cleanup_mem(void **pmem) {
    free(*mem);
}
</code>```

But the compiler won't let you implicitly convert T** to void** because, strictly speaking, it's not necessarily safe.

Making cleanup_mem take a void* and internally cast to void** doesn't make that conversion any safer.

Body:
There is GCC-specific attribute cleanup. It might be used like this:

#define SCOPED_FILE __attribute__((cleanup(cleanup_file)))

void
cleanup_file(FILE **file) {
    if (*file != NULL) { fclose(*file); }
}
…
FILE *SCOPED_FILE file = fopen(…); // file will be closed at the end of scope.

I thought it would be handy to have cleanup function for any malloced memory. Having to circumvent casting issues, I came up with the following implementation:

#define SCOPED_MEM __attribute__((cleanup(cleanup_mem)))

static inline void
cleanup_mem(void *pmem) {
    void *mem = *(void **)pmem;
    free(mem);
}

int main(void) {
    char *SCOPED_MEM str = malloc(20);
    strcpy(str, "pineapple");
    printf("hi, %s\n", str);
    // str will be free'd at the end of scope
}

It does work, but smells funny, because I don't directly specify void ** as parameter type, but rather cast to it.
I wonder, if there are some problems with it that I don't see right now.

Body:
but smells funny, because I don't directly specify void ** as parameter type, but rather cast to it.

Casts in C are often code smells, so you should ask yourself: why is the cast necessary?

One's first approach probably would be:

static inline void
cleanup_mem(void **pmem) {
    free(*mem);
}

But the compiler won't let you implicitly convert T** to void** because, strictly speaking, it's not necessarily safe.

Making cleanup_mem take a void* and internally cast to void** doesn't make that conversion any safer.


问:
My page is scrolling to right. Why is it happening?
I'm building a web page and working in the layout for small screens (max-width: 600px). When the screen gets narrow, the page gets a bit of horizontal scroll, as you can see in the code snippet, but it is unexpected for me. I am not finding anything wider than the viewport's width in my code. Why is there that scroll?

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    width: 100vw;
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">
    </head>
    <body>
        <header>
            <img src="Images/icons8-fund-accounting-80.png">
            <h1>Finances</h1>
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Contact us</li>
                    <li>Register</li>
                    <li>Login</li>
                </ul>
                <img src="Images/icons8-menu-50.png" id="menu">
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    Get started
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    Create an account
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html></code>```

答:
The 100vw width of the body span the whole viewport width. If a vertical scrollbar appears (which is almost always the case), this scrollbar covers / cuts off a small part of those 100vw, so the body actually has to become narrower than 100vw to be fully visible - like "100vw minus the width of the vertical scrollbar". Otherwise a * horizontal*  scrollbar will appear (like in your example).

To avoid this, you can simply erase width: 100vw from body, which will set the width to the default auto and will work as expected:

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">
    </head>
    <body>
        <header>
            <img src="Images/icons8-fund-accounting-80.png">
            <h1>Finances</h1>
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Contact us</li>
                    <li>Register</li>
                    <li>Login</li>
                </ul>
                <img src="Images/icons8-menu-50.png" id="menu">
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    Get started
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    Create an account
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html></code>```

Body:
I'm building a web page and working in the layout for small screens (max-width: 600px). When the screen gets narrow, the page gets a bit of horizontal scroll, as you can see in the code snippet, but it is unexpected for me. I am not finding anything wider than the viewport's width in my code. Why is there that scroll?

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    width: 100vw;
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}

<!DOCTYPE html>

        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">

Finances

Home

About

Contact us

Register

Login

Manage your money easily, anywhere, anytime.

                    Get started

Concrete data

Simple but concrete data that are the answer to all the quesions about your current money, spending and.

Easy interface

An interface easy to use, made to you who want to manage your money faster and with no problems.

Fast access

No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.

Register now and enjoy
the best of Finances.

                    Create an account

A work of Bruno Sdoukos.

Body:
The 100vw width of the body span the whole viewport width. If a vertical scrollbar appears (which is almost always the case), this scrollbar covers / cuts off a small part of those 100vw, so the body actually has to become narrower than 100vw to be fully visible - like "100vw minus the width of the vertical scrollbar". Otherwise a * horizontal*  scrollbar will appear (like in your example).

To avoid this, you can simply erase width: 100vw from body, which will set the width to the default auto and will work as expected:

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}

<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">
    </head>
    <body>
        <header>
            <a href="index.html"><img src="Images/icons8-fund-accounting-80.png"></a>
            <a href="index.html"><h1>Finances</h1></a>
            <nav>
                <ul>
                    <li><a href="index.html">Home</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Contact us</a></li>
                    <li><a href="#">Register</a></li>
                    <li><a href="#">Login</a></li>
                </ul>
                <a href="#"><img src="Images/icons8-menu-50.png" id="menu"></a>
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    <a href="#">Get started</a>
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    <a href="#">Create an account</a>
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html>


问:
How to move all elements that are zero to the end of an array?
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

```<code>function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}
</code>```

input:

```<code>[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
</code>```

Expected:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Actual:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Result is coming as correct but I need to do it without array.push() or array.splice()

答:
Use a for loop, iterate through the array, and use a simple conditional to check zeroes.</p>

```<code>var arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14];
var prev_zero_index = 0;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] != 0 && arr[i - 1] == 0) {
    prev_zero_index++;
    arr[prev_zero_index] = arr[i];
    arr[i] = 0;
  }
}
</code>```

Body:
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

input:

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

Expected:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Actual:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Result is coming as correct but I need to do it without array.push() or array.splice()

Body:
Use a for loop, iterate through the array, and use a simple conditional to check zeroes.

var arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14];
var prev_zero_index = 0;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] != 0 && arr[i - 1] == 0) {
    prev_zero_index++;
    arr[prev_zero_index] = arr[i];
    arr[i] = 0;
  }
}


问:
Swift: What is the difference between casting using as / as? / as! keywords and a C-style cast?
I've noticed that I can cast a closure that has regular arguments to a closure that has its arguments wrapped in a tuple. But only if I use a particular method of casting!

```<code>let myClosure = { (a: Int, b: Float) -> Void in
    print(a, b)
}

// I want to convert the closure to be of this type.
var myClosureWithTupleArgVar: (((Int, Float)) -> Void)? = nil

// Cast A is possible.
myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)
myClosureWithTupleArgVar?((1, 2))

// Cast B will always fail and return nil (as warned by the compiler).
myClosureWithTupleArgVar = myClosure as? (((Int, Float)) -> Void)
myClosureWithTupleArgVar?((3, 4))
</code>```

Outputs:

```<code>1 2.0
</code>```

Why is it possible to cast using cast A but not cast B? What is the difference between using an as Swift-style cast and the C-style function call cast?

(I am not interested in the difference between as, as?, and as!)

答:
Short answer :

The C-Style cast basically means the Swift compiler will just force your closure to be called as if it takes a (Int, Float) tuple as parameter whereas the as / as? / as! cast will first do some sanity checks on your cast to ensure that the types are compatible and so on.

Since the compiler believes (in certains versions, as seen on the comments on the other answer) that (Int, Float) -> () and ((Int, Float)) -> () are too far apart to be compatible, the sanity check will just return nil, therefore blocking your call.

What makes it work is that a function / closure taking a (Int, Float) tuple behaves exactly the same (in the current version of Swift) as a function / closure taking an Int and a Float parameter.

Long answer :

I compiled a snippet of code into assembly which I will be referencing from now on. That snippet can be found here : https://swift.godbolt.org/z/CaOb0s

For readability purposes, I used functions instead of actual closures here.

I've created two functions corresponding to the two cases we have :

func twoParamFunc(a: Int, b: Float)-> Void {
    print(a, b)
}

func singleParamFunc(tuple: (a: Int, b: Float))-> Void {
    print(tuple.a, tuple.b)
}
```

<p>I then tried to cast those using your two different methods : </p>

<pre class="lang-swift prettyprint-override"><code>    let cCastFunction = ((((Int, Float)) -> Void)?(twoParamFunc))!
    let asCastFunction = (twoParamFunc as? (((Int, Float)) -> Void))!
</code>```

And when looking at the assembly code compiled by swift, we can see a lot of differences between the two.

When looking at the C-style cast, we can see that most of the code is basically just calling alloc/retain/release and moving pointers and values around. The only call to external code is through a failure case (the ! dereferencing a null reference), calling $ss18_fatalErrorMessage__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtF

Whereas in the swift-style cast, there are a lot of additional calls (the sanity checks I was talking about earlier).
We have for exemple

```<code>call    (type metadata accessor for (Swift.Int, Swift.Float) -> ())
...
call    (type metadata accessor for ((Swift.Int, Swift.Float)) -> ())
...
call    swift_dynamicCast@PLT
</code>```

which clearly shows that the Swift compiler is doing some checks to the compatibility of the types being cast, and are nowhere to be found in the c-style cast.

So now that the C-style cast / Swift-style cast difference has been found, we can try to understand why the call to the C-style casted function works.

When looking at the assembly code generated by the two simple calls to the functions I made in the sample :

    twoParamFunc(a: a.0,b: a.1)
    singleParamFunc(tuple: a)
```

<p>We can see that those functions are actually compiled to be called identically :</p>

<p><code>singleParamFunc</code> :</p>

```        mov     rdi, qword ptr [rip + (output.a : (Swift.Int, Swift.Float))]
        movss   xmm0, dword ptr [rip + (output.a : (Swift.Int, Swift.Float))+8]
        call    (output.singleParamFunc(tuple: (a: Swift.Int, b: Swift.Float)) -> ())
```

<p>Here we see that the value corresponding to the first value of the tuple is put into register <code>rdi</code>, and the second one is put into <code>xmm0</code>, and then the function is called</p>

<p><code>twoParamFunc</code> :</p>

```        mov     rax, qword ptr [rip + (output.a : (Swift.Int, Swift.Float))]
        movss   xmm0, dword ptr [rip + (output.a : (Swift.Int, Swift.Float))+8]
...
        mov     rdi, rax
...
        call    (output.twoParamFunc(a: Swift.Int, b: Swift.Float) -> ())
```

<p>In this function, it is not as straightforward, but now value 1 goes in <code>rax</code> register which itself is copied into <code>rdi</code> register, and value 2 still goes in <code>xmm0</code>, and the function is called.</p>

<p>But in this sample since we are doing other things, the assembly code is a bit messier, I've made another sample to test this cleanly : https://swift.godbolt.org/z/vDCZZV</p>

<p>In this sample (on which I've added another test with a struct) we can see that the assembly code created to called the 3 functions are exactly the same : </p>

```        mov     rdi, qword ptr [rip + (output.structValue : output.struct_test)]
        movss   xmm0, dword ptr [rip + (output.structValue : output.struct_test)+8]
        call    (output.test(value: output.struct_test) -> ())
```

```        mov     rdi, qword ptr [rip + (output.tupleValue : (Swift.Int, Swift.Float))]
        movss   xmm0, dword ptr [rip + (output.tupleValue : (Swift.Int, Swift.Float))+8]
        call    (output.test2(tuple: (Swift.Int, Swift.Float)) -> ())
```

```        mov     ecx, 1
        mov     edi, ecx
        movss   xmm0, dword ptr [rip + .LCPI0_0]
        call    (output.test3(a: Swift.Int, b: Swift.Float) -> ())
```

To resume, in the current version of swift, any of these three functions could be c-casted into any other and still work.

This ended up being a lot longer than initially planned, but I thought this problem deserved it.

Body:
I've noticed that I can cast a closure that has regular arguments to a closure that has its arguments wrapped in a tuple. But only if I use a particular method of casting!

let myClosure = { (a: Int, b: Float) -> Void in
    print(a, b)
}

// I want to convert the closure to be of this type.
var myClosureWithTupleArgVar: (((Int, Float)) -> Void)? = nil

// Cast A is possible.
myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)
myClosureWithTupleArgVar?((1, 2))

// Cast B will always fail and return nil (as warned by the compiler).
myClosureWithTupleArgVar = myClosure as? (((Int, Float)) -> Void)
myClosureWithTupleArgVar?((3, 4))

Outputs:

1 2.0

Why is it possible to cast using cast A but not cast B? What is the difference between using an as Swift-style cast and the C-style function call cast?

(I am not interested in the difference between as, as?, and as!)

Body:
Short answer :

The C-Style cast basically means the Swift compiler will just force your closure to be called as if it takes a (Int, Float) tuple as parameter whereas the as / as? / as! cast will first do some sanity checks on your cast to ensure that the types are compatible and so on.

Since the compiler believes (in certains versions, as seen on the comments on the other answer) that (Int, Float) -> () and ((Int, Float)) -> () are too far apart to be compatible, the sanity check will just return nil, therefore blocking your call.

What makes it work is that a function / closure taking a (Int, Float) tuple behaves exactly the same (in the current version of Swift) as a function / closure taking an Int and a Float parameter.

Long answer :

I compiled a snippet of code into assembly which I will be referencing from now on. That snippet can be found here : https://swift.godbolt.org/z/CaOb0s

For readability purposes, I used functions instead of actual closures here.

I've created two functions corresponding to the two cases we have :

func twoParamFunc(a: Int, b: Float)-> Void {
    print(a, b)
}

func singleParamFunc(tuple: (a: Int, b: Float))-> Void {
    print(tuple.a, tuple.b)
}

I then tried to cast those using your two different methods :

    let cCastFunction = ((((Int, Float)) -> Void)?(twoParamFunc))!
    let asCastFunction = (twoParamFunc as? (((Int, Float)) -> Void))!

And when looking at the assembly code compiled by swift, we can see a lot of differences between the two.

When looking at the C-style cast, we can see that most of the code is basically just calling alloc/retain/release and moving pointers and values around. The only call to external code is through a failure case (the ! dereferencing a null reference), calling $ss18_fatalErrorMessage__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtF

Whereas in the swift-style cast, there are a lot of additional calls (the sanity checks I was talking about earlier).
We have for exemple

call    (type metadata accessor for (Swift.Int, Swift.Float) -> ())
...
call    (type metadata accessor for ((Swift.Int, Swift.Float)) -> ())
...
call    swift_dynamicCast@PLT

which clearly shows that the Swift compiler is doing some checks to the compatibility of the types being cast, and are nowhere to be found in the c-style cast.

So now that the C-style cast / Swift-style cast difference has been found, we can try to understand why the call to the C-style casted function works.

When looking at the assembly code generated by the two simple calls to the functions I made in the sample :

    twoParamFunc(a: a.0,b: a.1)
    singleParamFunc(tuple: a)

We can see that those functions are actually compiled to be called identically :

singleParamFunc :

        mov     rdi, qword ptr [rip + (output.a : (Swift.Int, Swift.Float))]
        movss   xmm0, dword ptr [rip + (output.a : (Swift.Int, Swift.Float))+8]
        call    (output.singleParamFunc(tuple: (a: Swift.Int, b: Swift.Float)) -> ())

Here we see that the value corresponding to the first value of the tuple is put into register rdi, and the second one is put into xmm0, and then the function is called

twoParamFunc :

        mov     rax, qword ptr [rip + (output.a : (Swift.Int, Swift.Float))]
        movss   xmm0, dword ptr [rip + (output.a : (Swift.Int, Swift.Float))+8]
...
        mov     rdi, rax
...
        call    (output.twoParamFunc(a: Swift.Int, b: Swift.Float) -> ())

In this function, it is not as straightforward, but now value 1 goes in rax register which itself is copied into rdi register, and value 2 still goes in xmm0, and the function is called.

But in this sample since we are doing other things, the assembly code is a bit messier, I've made another sample to test this cleanly : https://swift.godbolt.org/z/vDCZZV

In this sample (on which I've added another test with a struct) we can see that the assembly code created to called the 3 functions are exactly the same :

        mov     rdi, qword ptr [rip + (output.structValue : output.struct_test)]
        movss   xmm0, dword ptr [rip + (output.structValue : output.struct_test)+8]
        call    (output.test(value: output.struct_test) -> ())

        mov     rdi, qword ptr [rip + (output.tupleValue : (Swift.Int, Swift.Float))]
        movss   xmm0, dword ptr [rip + (output.tupleValue : (Swift.Int, Swift.Float))+8]
        call    (output.test2(tuple: (Swift.Int, Swift.Float)) -> ())

        mov     ecx, 1
        mov     edi, ecx
        movss   xmm0, dword ptr [rip + .LCPI0_0]
        call    (output.test3(a: Swift.Int, b: Swift.Float) -> ())

To resume, in the current version of swift, any of these three functions could be c-casted into any other and still work.

This ended up being a lot longer than initially planned, but I thought this problem deserved it.


问:
SQL query MAX() function
```<code>select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)
</code>```

What is wrong in this query?

I had tried 'having' in place of 'where' tag.

```<code>select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)
</code>```

it must produce result with max unit price,

```<code>ProductID   ProductName     QuantityPerUnit
38          Côte de Blaye   12 - 75 cl bottles
</code>```

答:
What is wrong with your query is that you are mixing aggregation value with raw values in the query.

If you want only one row, I would recommend a different approach:

```<code>select ProductID, ProductName, QuantityPerUnit
from Products
order by UnitPrice desc
fetch first 1 row only;
</code>```

Although fetch first is standard SQL, not all databases support it, so you may need the appropriate syntax for your database.

Title: SQL query MAX() function

Body:
select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)

What is wrong in this query?

I had tried 'having' in place of 'where' tag.

select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)

it must produce result with max unit price,

ProductID   ProductName     QuantityPerUnit
38          Côte de Blaye   12 - 75 cl bottles

Body:
What is wrong with your query is that you are mixing aggregation value with raw values in the query.

If you want only one row, I would recommend a different approach:

select ProductID, ProductName, QuantityPerUnit
from Products
order by UnitPrice desc
fetch first 1 row only;

Although fetch first is standard SQL, not all databases support it, so you may need the appropriate syntax for your database.


问:
Multithreading with map and pool
I'm trying to follow a multithread example and adapt it to my code. This is the simplest explanation about multithreading I've read and it's easy to implement when you have a list:

```<code>from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)
</code>```

Which is the multithreaded version of:

```<code>results = []
for item in my_array:
    results.append(my_function(item))
</code>```

The problem, is that for my example I've a dictionary and I'm stuck at the first lines of code as I have to create a function but I don't see how I can do that, because I need to work with both the keys and values of the dict inside the function.

For example, for this single thread version:

```<code>thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for key in thisdict:
    print(key, thisdict[key])
</code>```

How can I adapt it to use map and pool?

Thank you,

答:
If you want to use Pool.map(), it's an example:

```<code>from multiprocessing.dummy import Pool as ThreadPool

def my_function(d):
    return d ** 2

my_array = [*range(20)]

pool = ThreadPool(4)
results = pool.map(my_function, my_array)
print(results)
</code>```

Output:

```<code>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
</code>```

Upd.
Version for dict:

```<code>def my_function(item):
    key, value = item
    return {"recieved_key": key, "recieved_value": value}

thisdict =  {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

pool = ThreadPool(3)
results = pool.map(my_function, thisdict.items())
print(results)
</code>```

Title: Multithreading with map and pool

Body:
I'm trying to follow a multithread example and adapt it to my code. This is the simplest explanation about multithreading I've read and it's easy to implement when you have a list:

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)

Which is the multithreaded version of:

results = []
for item in my_array:
    results.append(my_function(item))

The problem, is that for my example I've a dictionary and I'm stuck at the first lines of code as I have to create a function but I don't see how I can do that, because I need to work with both the keys and values of the dict inside the function.

For example, for this single thread version:

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for key in thisdict:
    print(key, thisdict[key])

How can I adapt it to use map and pool?

Thank you,

Body:
If you want to use Pool.map(), it's an example:

from multiprocessing.dummy import Pool as ThreadPool

def my_function(d):
    return d ** 2

my_array = [*range(20)]

pool = ThreadPool(4)
results = pool.map(my_function, my_array)
print(results)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

Upd.
Version for dict:

def my_function(item):
    key, value = item
    return {"recieved_key": key, "recieved_value": value}

thisdict =  {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

pool = ThreadPool(3)
results = pool.map(my_function, thisdict.items())
print(results)


问:
MongoDB ODBC DSN Configuration
I want to setup this DSN, i had installed the odbc mongodb driver.
enter image description here

where i put the data, this is freeze, and not responding.
I am trying with differents data but is the same.
I need this configuration cause i wanna connect powerbi with my mongodb database.
ALso i wanna know what is the correct ip cause i have one ip for each cluster but i have a url like a main server information.

答:
Have a look at Mongo's guide on setting up the DSN: https://docs.mongodb.com/bi-connector/master/tutorial/create-system-dsn/, and more generally, the quick start guide: https://docs.mongodb.com/bi-connector/master/local-quickstart/

Some potential fixes:

make sure you have the mongosqld process running

make sure you enter a database in the database field

make sure your port is correct: you can get it from the mongosqld process logs. Note: this is not the port where mongodb itself is running.

Mongo provides two drivers: ANSI and UNICODE. Although ANSI supposedly has better performance, try the UNICODE one and see if that fixes your issue.

Title: MongoDB ODBC DSN Configuration


问:
Getting a ColorPicker value
I have a problem. I am using the

Chiralcode ColorPicker for Android

This is a nuget package that I have installed to create a ColorPicker. Now I have done that and I want to get the selected color. To do that I need to do this:

```<code>SelectedColor = ColorPickerDialog.GetColor();
</code>```

This returns me an integer with a value something like this: -61145. But how can I use this value to create a rgb string or a hexadecimal?

答:
Colors sometimes represented as Int. You need to decode the raw number. Try using that:</p>

```<code>var color = ColorPickerDialog.GetColor();
int A = (color >> 24) & 0xff; // or color >>> 24
int R = (color >> 16) & 0xff;
int G = (color >>  8) & 0xff;
int B = (color      ) & 0xff;
</code>```

Title: Getting a ColorPicker value

Body:
I have a problem. I am using the

Chiralcode ColorPicker for Android

This is a nuget package that I have installed to create a ColorPicker. Now I have done that and I want to get the selected color. To do that I need to do this:

SelectedColor = ColorPickerDialog.GetColor();

This returns me an integer with a value something like this: -61145. But how can I use this value to create a rgb string or a hexadecimal?

Body:
Colors sometimes represented as Int. You need to decode the raw number. Try using that:

var color = ColorPickerDialog.GetColor();
int A = (color >> 24) & 0xff; // or color >>> 24
int R = (color >> 16) & 0xff;
int G = (color >>  8) & 0xff;
int B = (color      ) & 0xff;


问:
How to get a Clickable Link inside this text string in PHP
I have tried to send an email from PHP with the next body:

```<code>$message .= 'This is a simple message';
$message .= "\n";
$message .= 'http://www.yahoo.com';
$message .= "\n";
$message .= "<a href='https://www.google.com'>Google</a>";
$message .= "\n";
</code>```

As a result I got the next output:

```<code>This is a simple message    //This line is ok
http://www.yahoo.com        //This line is ok
<a href='https://www.google.com'>Google</a> //It should appear the word Google clickable but it does not
</code>```

Instead of having the word Google with the link clickable to the Google site I get the html code, how could I fix this? Thanks

答:
You need to be sure you're sending mail as HTML and not as text/plain that is probably in your case so you get HTML as source code and not as it should look like.

```<code>// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
</code>```

more read here:

Body:
I have tried to send an email from PHP with the next body:

$message .= 'This is a simple message';
$message .= "\n";
$message .= 'http://www.yahoo.com';
$message .= "\n";
$message .= "Google";
$message .= "\n";

As a result I got the next output:

This is a simple message    //This line is ok
http://www.yahoo.com        //This line is ok
Google //It should appear the word Google clickable but it does not

Instead of having the word Google with the link clickable to the Google site I get the html code, how could I fix this? Thanks

Body:
You need to be sure you're sending mail as HTML and not as text/plain that is probably in your case so you get HTML as source code and not as it should look like.

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

more read here:


问:
Android - how to find multiple views with common attribute
I have a layout with multiple ImageViews, some of those images need to have the same onClickListener.
I would like my code to be flexible and to be able to get a collection of those Views, iterate and add the listeners at run-time.

Is there a method like findViewById that will return a collection of Views rather than just a single one?

答:
I will share my functional-style method with a filter, can be used with StreamSupport library.

```<code>@NonNull
public static <T> Function<View, Stream<T>> subViews(
    @NonNull final Function<View, Optional<T>> filter
) {
    return view -> RefStreams.concat(
        // If current view comply target condition adds it to the result (ViewGroup too)
        filter.apply(view).map(RefStreams::of).orElse(RefStreams.empty()),

        // Process children if current view is a ViewGroup
        ofNullable(view).filter(__ -> __ instanceof ViewGroup).map(__ -> (ViewGroup) __)
                .map(viewGroup -> IntStreams.range(0, viewGroup.getChildCount())
                        .mapToObj(viewGroup::getChildAt)
                        .flatMap(subViews(filter)))
                .orElse(RefStreams.empty()));
}

@NonNull
public static <T> Function<View, Optional<T>> hasType(@NonNull final Class<T> type) {
    return view -> Optional.ofNullable(view).filter(type::isInstance).map(type::cast);
}

@NonNull
public static Function<View, Optional<View>> hasTag(@NonNull final String tag) {
    return view -> Optional.ofNullable(view).filter(v -> Objects.equals(v.getTag(), tag));
}
</code>```

Usage example:

```<code>Optional.ofNullable(navigationViewWithSubViews)
            .map(subViews(hasType(NavigationView.class)))
            .orElse(RefStreams.empty())
            .forEach(__ -> __.setNavigationItemSelectedListener(this));
</code>```

Body:
I will share my functional-style method with a filter, can be used with StreamSupport library.

@NonNull
public static <T> Function<View, Stream<T>> subViews(
    @NonNull final Function<View, Optional<T>> filter
) {
    return view -> RefStreams.concat(
        // If current view comply target condition adds it to the result (ViewGroup too)
        filter.apply(view).map(RefStreams::of).orElse(RefStreams.empty()),

        // Process children if current view is a ViewGroup
        ofNullable(view).filter(__ -> __ instanceof ViewGroup).map(__ -> (ViewGroup) __)
                .map(viewGroup -> IntStreams.range(0, viewGroup.getChildCount())
                        .mapToObj(viewGroup::getChildAt)
                        .flatMap(subViews(filter)))
                .orElse(RefStreams.empty()));
}

@NonNull
public static <T> Function<View, Optional<T>> hasType(@NonNull final Class<T> type) {
    return view -> Optional.ofNullable(view).filter(type::isInstance).map(type::cast);
}

@NonNull
public static Function<View, Optional<View>> hasTag(@NonNull final String tag) {
    return view -> Optional.ofNullable(view).filter(v -> Objects.equals(v.getTag(), tag));
}

Usage example:

Optional.ofNullable(navigationViewWithSubViews)
            .map(subViews(hasType(NavigationView.class)))
            .orElse(RefStreams.empty())
            .forEach(__ -> __.setNavigationItemSelectedListener(this));


问:
querying the graph api with curl
I want to check how to handle the access_token. So, I use curl to perform the following queries:

```<code>curl -X POST https://graph.facebook.com/oauth/access_token -d "client_id=<appId>&client_secret=<secret>&grant_type=client_credentials&redirect_uri="
</code>```

It returns a value for access_token.

Then, I'd like to get the list of my friends:

```<code>curl -X POST https://graph.facebook.com/me/friends -d "access_token=<token>"
</code>```

It returns this error:

```<code>{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
</code>```

Any hints ?

答: You should enclose the "https://...." , with double quote after curl -X POST.</p>

Title: querying the graph api with curl

Body:
I want to check how to handle the access_token. So, I use curl to perform the following queries:

curl -X POST https://graph.facebook.com/oauth/access_token -d "client_id=<appId>&client_secret=<secret>&grant_type=client_credentials&redirect_uri="

It returns a value for access_token.

Then, I'd like to get the list of my friends:

curl -X POST https://graph.facebook.com/me/friends -d "access_token=<token>"

It returns this error:

{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}

Any hints ?