问:
How to group by one column and divide the numbers in second column depending from the third
I have frequency (column 1) for SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING (column 3) mutations for a list of genes in the second column.

I need to calculate dN/dS ratio (NON_SYNONYMOUS_CODING / SYNONYMOUS_CODING) for each gene.

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency

```<code>0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING
</code>```

Expected result is smth like this:

```<code>187.95 A1BG
0.3353 A1CF
13.926 A2M
1.565 A2ML1
</code>```

答:
Hypothesis:

You file is ordered via the genes names.

if it is not the case, run sort -k2 genes | awk -f dNdSCompute.awk

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency => In this case, they will just be ignored as it is impossible to compute dN/dS ratio.

Code:

```<code>$ cat dNdSCompute.awk
{
    #assign the first column value to syn or nonSyn depending on the third column value
    if ($3 == "NON_SYNONYMOUS_CODING")
        nonSyn = $1
    else syn = $1
    #if the current gene is the same as the previous one
    #print the result and reset the frequencie
    if ( $2 == gene){
        print (nonSyn/syn), $2
        syn = nonSyn = 0
    }
    #current gene name is saved in gene variable and will be used at next line
    gene = $2
}
</code>```

Input:

(with genes that do not have both frequencies)

```<code>$ cat genes
0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.111161 A2CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
1.76174 A3R NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING
</code>```

Output:

```<code>$ awk -f dNdSCompute.awk genes
187.954 A1BG
0.33534 A1CF
13.9263 A2M
1.56543 A2ML1
</code>```

Body:
I have frequency (column 1) for SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING (column 3) mutations for a list of genes in the second column.

I need to calculate dN/dS ratio (NON_SYNONYMOUS_CODING / SYNONYMOUS_CODING) for each gene.

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency

0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING

Expected result is smth like this:

187.95 A1BG
0.3353 A1CF
13.926 A2M
1.565 A2ML1

Body:
Hypothesis:

You file is ordered via the genes names.

if it is not the case, run sort -k2 genes | awk -f dNdSCompute.awk

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency => In this case, they will just be ignored as it is impossible to compute dN/dS ratio.

Code:

$ cat dNdSCompute.awk
{
    #assign the first column value to syn or nonSyn depending on the third column value
    if ($3 == "NON_SYNONYMOUS_CODING")
        nonSyn = $1
    else syn = $1
    #if the current gene is the same as the previous one
    #print the result and reset the frequencie
    if ( $2 == gene){
        print (nonSyn/syn), $2
        syn = nonSyn = 0
    }
    #current gene name is saved in gene variable and will be used at next line
    gene = $2
}

Input:

(with genes that do not have both frequencies)

$ cat genes
0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.111161 A2CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
1.76174 A3R NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING

Output:

$ awk -f dNdSCompute.awk genes
187.954 A1BG
0.33534 A1CF
13.9263 A2M
1.56543 A2ML1


来源: stackexchange

问:
Is the MS Ribbon/Office UI License worth worrying about?
Imagine I want to create an application which is very similar to MS Word 2007, using C++ in VS2008 and the MFC Feature Pack. For the ribbon, there are 3 options available to me:

Use the ribbon from MFC Feature Pack without acquiring a license.

Probably dodgy in the long run. You're all right until your product becomes a global success, at which point MS Legal send the heavies round. But could they really do anything about it?

Use the ribbon from MFC Feature Pack, but try to acquire a license.

I believe that if I should try to register an Office UI License, the chances are that I would be turned down because it is a competing product:

The license is available for applications on any platform, except for applications that compete directly with the five Office applications that currently have the new UI (Microsoft Word, Excel, PowerPoint, Outlook, and Access).

Use a 3rd party ribbon control.

If I were to buy a license of the BCGControlBar Library for about £500 from BCGSoft -- whose ribbon bar is used by MS in the MFC Feature Pack -- then I could use the ribbon in my app with no problem.

I don't want to spend any money unless absolutely necessary. How about if I use option #1 until I get hassled about it, at which point I could ditch it and go for #3? Would it be too late?

Of course all the above is hypothetical... ;)

Note: I don't care about any patents or copyrights relating to the similarity between my product and Word, that's just an example. This question is only concerned with the ribbon licensing aspect.

答:
I realize you say that you don't care about the patents issue, but that's really the only issue.  Even if you were to aquire a 3rd party ribbon control, Microsoft has the patents on it and can come after you for violating them.  They've explicitly come out and said that people can use it for non-competing products.

The Office UI license restrictions are for the concept of the ribbon, not just MFC's specific implementation of it.  See this page for more information.

OwnerDisplayName: demoncodemonkey

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Josh


问:
How to detect if Windows 10 is in tablet mode with Delphi?
How would someone detect when a user enters tablet mode on a Windows 10 device with Delphi code?

Can someone show a code example for this?

I don't want to detect if the user has a tablet or not. I simply want to see whether they're in tablet mode or not. What would be the best way to do this?

答:
You can use UIViewSettings.UserInteractionMode API. Please refer to @Raymond blog: "How can I detect whether my PC is in tablet mode?", there are UWP and desktop ways in C++ you can refer to.

More detailed information you can check this thread.

But you need find out how to do in Delphi. There are some related issues hope they are helpful for you:

delphi - call external WinAPI function

Can we call Native Windows API from Delphi?

ContentLicense: CC BY-SA 4.0


问:
How to make ASP.NET website and ASP.NET Core website work on a same server
There is a domain name www.xxx.com. This is a ASP.NET web site, and it is working well. There is a second level domain name which is yyy.xxx.com. This is an ASP.NET Core 2.0 website. This yyy.xxx.com is what I am developing.

I try to publish and upload ASP.NET Core web application to yyy.xxx.com. Then both websites are on same server. I know I have to install some software to make ASP.NET Core web application work on the server.

So my question is can both ASP.NET website and ASP.NET Core website be visited at same time? I am afraid once I install some software which make ASP.NET Core website can work, the ASP.NET website will work well.

I try use ASP.NET Core 2.0 to develop my website again. Before the new website can work perfect I want the current website to work. That is why there are 2 websites on a same server, one is ASP.NET, the other is ASP.NET Core.

答:
Yes, you can. Just install the asp.net core hosting runtime from here

Follow this link to understand how to deploy your asp.net site to IIS. Basically, it will be a separate IIS App Pool for .net core site and another one for the asp.net framework site. You can then change the binding to set the host header for each site.


问:
When finding the prime factors of a number some numbers work but others dont
When testing numbers some work for example 48, but others don't. I'm not sure what the best way to approach finding all the factors of a number.

Prime Factorization

```<code>def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while n % i == 0:
            next_n = n / i
            factors.append(i)
            n = next_n
            if n % i != 0:
                i += 1
                continue
            elif i == n:
                break
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
</code>```

I am expecting to get a list of all the factors of a number.

答:
I changed your code and now it works for all natural numbers:</p>

```<code>def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while i * i <= n:
            while n % i == 0:
                factors.append(i)
                n = n // i
            i += 1
    if n > 1:
        factors.append(n)
    if len(factors) == 1:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
</code>```

Body:
When testing numbers some work for example 48, but others don't. I'm not sure what the best way to approach finding all the factors of a number.

Prime Factorization

def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while n % i == 0:
            next_n = n / i
            factors.append(i)
            n = next_n
            if n % i != 0:
                i += 1
                continue
            elif i == n:
                break
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))

I am expecting to get a list of all the factors of a number.

Body:
I changed your code and now it works for all natural numbers:

def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while i * i <= n:
            while n % i == 0:
                factors.append(i)
                n = n // i
            i += 1
    if n > 1:
        factors.append(n)
    if len(factors) == 1:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))


问:
Access a struct i unmanaged C code
I have a pile of C code (.exe) which is unmanaged (not compiled with /clr). I would like to access/manipulate a C struct in the C code from a managed wrapper in C++/CLI prefarably as a dll. I am new to C++/CLI, what do I have to do to make this happen?</p>

答:
Unless you know the address of that struct, it's not going to happen.

And knowing the adderss depends heavily if it is defined as a global variable, a local variable in a function or allocated dynamically?

ContentLicense: CC BY-SA 3.0

Title: Access a struct i unmanaged C code


问:
How can i remove the horizontal line in my Table?
Any idea, How can i remove the line horizontal from the table?

css, html

```<code><table border="1" style="width:100%; border-collapse: collapse">

            <tr>
                <th>Prepared By:</th>
                <th>Released By:</th>
                <th>Trucker's Acknowledgement</th>
            </tr>
            <tr>
                <td><font size="1">/*auto populated*/</font></td>
                <td><font size="1">/*auto populated*/</font></td>
                <td><font size="1">Driver : ______________                Helper: ______________ </font></td>
            </tr>
            <tr>
                <td> </td>
                <td><font size="1">Signature/Date</font></td>
                <td><font size="1">Signature/Date</font></td>
            </tr>
            <tr>
                <td> </td>
                <td> </td>
                <td><font size="1">Contact Nos. : ______________</font></td>
            </tr>
        </table>
</code>```

i want to remove only the horizontal line table

答: 1.) @Hassan Siddiqui here master.

Body:
Any idea, How can i remove the line horizontal from the table?

css, html

                Prepared By:
                Released By:
                Trucker's Acknowledgement

                /*auto populated*/
                /*auto populated*/
                Driver : ______________                Helper: ______________

                Signature/Date
                Signature/Date

                Contact Nos. : ______________

i want to remove only the horizontal line table

Body: 1.) @Hassan Siddiqui here master.


问:
Calculate percentage share of values against a value which is a row observation in the data frame
I want to calculate the percentage share and create new columns using mutate. I have the following data:

```<code>country, metric, segment, value1990, value2000, value2010
canada, abc, rural, 10, 15, 16
canada, abc, urban, 12, 12, 18
canada, abc, total, 22, 27, 34
canada, xyz, rural, 6, 9, 10
canada, xyc, urban, 7, 8, 8
canada, xyc, total, 13, 17, 18
canada, population, rural, 80, 86, 95
canada, population, urban, 102, 110, 121
canada, population, total, 182, 196, 216
</code>```

The data frame consists data from several countries and across several years. I want to create a new column with the following values

```<code>country, metric, segment, value, percent1990, percent2000, percent2010

canada, abc, rural, 10, 15, 16, 12.5%, 17.4%, 16.8%
canada, abc, urban, 12, 12, 18, 11.7%, 10.9%, 14.8%
canada, abc, total, 22, 27, 34, 12.1%, 13.7%, 15.7%
canada, xyz, rural, 6, 9, 10, 7.5%, 10.4%, 10.5%
canada, xyc, urban, 7, 8, 8, 6.8%, 7.2%, 6.6%
canada, xyc, total, 13, 17, 18, 7.22%, 8.6%, 8.3%
canada, population, rural, 80, 86, 95, 100%, 100%, 100%
canada, population, urban, 102, 110, 121, 100%, 100%, 100%
canada, population, total, 182, 196, 216, 100%, 100%, 100%
</code>```

Essentially, I want to calculate the value variable's percentage share of the population depending on whether it is rural/urban/total, across multiple years.

E.g.
(row 1) percent_share = (10/80)*100 = 12.5%

(row 2) percent_share = (10/102)*100 = 11.76%

(row 3) percent_share = (10/182)*100 = 12.09%

I'm unable to go beyond the group_by chaining to ascertain how to input the necessary function

```<code>df = df %>%
     group_by (country, metric) %>%
     mutate(...)
</code>```

答:
You can also just group by segment and divide by max(value), since the population value should be the largest:

```<code>df %>%
  group_by(country, segment) %>%
  mutate(percent_share = value / max(value))

# A tibble: 9 x 5
# Groups:   segment [3]
  country metric     segment value percent_share
  <chr>   <chr>      <chr>   <dbl>         <dbl>
1 canada  abc        rural      10        0.125
2 canada  abc        urban      12        0.118
3 canada  abc        total      22        0.121
4 canada  xyz        rural       6        0.075
5 canada  xyc        urban       7        0.0686
6 canada  xyc        total      13        0.0714
7 canada  population rural      80        1
8 canada  population urban     102        1
9 canada  population total     182        1
</code>```

Body:
I want to calculate the percentage share and create new columns using mutate. I have the following data:

country, metric, segment, value1990, value2000, value2010
canada, abc, rural, 10, 15, 16
canada, abc, urban, 12, 12, 18
canada, abc, total, 22, 27, 34
canada, xyz, rural, 6, 9, 10
canada, xyc, urban, 7, 8, 8
canada, xyc, total, 13, 17, 18
canada, population, rural, 80, 86, 95
canada, population, urban, 102, 110, 121
canada, population, total, 182, 196, 216

The data frame consists data from several countries and across several years. I want to create a new column with the following values

country, metric, segment, value, percent1990, percent2000, percent2010

canada, abc, rural, 10, 15, 16, 12.5%, 17.4%, 16.8%
canada, abc, urban, 12, 12, 18, 11.7%, 10.9%, 14.8%
canada, abc, total, 22, 27, 34, 12.1%, 13.7%, 15.7%
canada, xyz, rural, 6, 9, 10, 7.5%, 10.4%, 10.5%
canada, xyc, urban, 7, 8, 8, 6.8%, 7.2%, 6.6%
canada, xyc, total, 13, 17, 18, 7.22%, 8.6%, 8.3%
canada, population, rural, 80, 86, 95, 100%, 100%, 100%
canada, population, urban, 102, 110, 121, 100%, 100%, 100%
canada, population, total, 182, 196, 216, 100%, 100%, 100%

Essentially, I want to calculate the value variable's percentage share of the population depending on whether it is rural/urban/total, across multiple years.

E.g.
(row 1) percent_share = (10/80)*100 = 12.5%

(row 2) percent_share = (10/102)*100 = 11.76%

(row 3) percent_share = (10/182)*100 = 12.09%

I'm unable to go beyond the group_by chaining to ascertain how to input the necessary function

df = df %>%
     group_by (country, metric) %>%
     mutate(...)

Body:
You can also just group by segment and divide by max(value), since the population value should be the largest:

df %>%
  group_by(country, segment) %>%
  mutate(percent_share = value / max(value))

# A tibble: 9 x 5
# Groups:   segment [3]
  country metric     segment value percent_share
  <chr>   <chr>      <chr>   <dbl>         <dbl>
1 canada  abc        rural      10        0.125
2 canada  abc        urban      12        0.118
3 canada  abc        total      22        0.121
4 canada  xyz        rural       6        0.075
5 canada  xyc        urban       7        0.0686
6 canada  xyc        total      13        0.0714
7 canada  population rural      80        1
8 canada  population urban     102        1
9 canada  population total     182        1


问:
Add Dynamic Content Disposition for file names(amazon S3) in python
I have a Django model that saves filename as "uuid4().pdf". Where uuid4 generates a random uuid for each instance created. This file name is also stored on the amazon s3 server with the same name.

I am trying to add a custom disposition for filename that i upload to amazon s3, this is because i want to see a custom name whenever i download the file not the uuid one. At the same time, i want the files to stored on s3 with the uuid filename.

So, I am using django-storages with python 2.7. I have tried adding content_disposition in settings like this:

```<code>AWS_CONTENT_DISPOSITION = 'core.utils.s3.get_file_name'
</code>```

where get_file_name() returns the filename.

I have also tried adding this to the settings:

```<code>AWS_HEADERS = {
'Content-Disposition': 'attachments; filename="%s"'% get_file_name(),

 }
</code>```

no luck!

Do anyone of you know to implement this.

答:
Current version of S3Boto3Storage from django-storages supports AWS_S3_OBJECT_PARAMETERS global settings variable, which allows modify ContentDisposition too. But the problem is that it is applied as is to all objects that are uploaded to s3 and, moreover, affects all models working with the storage, which may turn to be not the expected result.

The following hack worked for me.

```<code>from storages.backends.s3boto3 import S3Boto3Storage

class DownloadableS3Boto3Storage(S3Boto3Storage):

    def _save_content(self, obj, content, parameters):
        """
        The method is called by the storage for every file being uploaded to S3.
        Below we take care of setting proper ContentDisposition header for
        the file.
        """
        filename = obj.key.split('/')[-1]
        parameters.update({'ContentDisposition': f'attachment; filename="{filename}"'})
        return super()._save_content(obj, content, parameters)
</code>```

Here we override native save method of the storage object and make sure proper content disposition is set on each file.
Of course, you need to feed this storage to the field you working on:

```<code>my_file_filed = models.FileField(upload_to='mypath', storage=DownloadableS3Boto3Storage())
</code>```

Body:
I have a Django model that saves filename as "uuid4().pdf". Where uuid4 generates a random uuid for each instance created. This file name is also stored on the amazon s3 server with the same name.

I am trying to add a custom disposition for filename that i upload to amazon s3, this is because i want to see a custom name whenever i download the file not the uuid one. At the same time, i want the files to stored on s3 with the uuid filename.

So, I am using django-storages with python 2.7. I have tried adding content_disposition in settings like this:

AWS_CONTENT_DISPOSITION = 'core.utils.s3.get_file_name'

where get_file_name() returns the filename.

I have also tried adding this to the settings:

AWS_HEADERS = {
'Content-Disposition': 'attachments; filename="%s"'% get_file_name(),

 }

no luck!

Do anyone of you know to implement this.

Body:
Current version of S3Boto3Storage from django-storages supports AWS_S3_OBJECT_PARAMETERS global settings variable, which allows modify ContentDisposition too. But the problem is that it is applied as is to all objects that are uploaded to s3 and, moreover, affects all models working with the storage, which may turn to be not the expected result.

The following hack worked for me.

from storages.backends.s3boto3 import S3Boto3Storage

class DownloadableS3Boto3Storage(S3Boto3Storage):

    def _save_content(self, obj, content, parameters):
        """
        The method is called by the storage for every file being uploaded to S3.
        Below we take care of setting proper ContentDisposition header for
        the file.
        """
        filename = obj.key.split('/')[-1]
        parameters.update({'ContentDisposition': f'attachment; filename="{filename}"'})
        return super()._save_content(obj, content, parameters)

Here we override native save method of the storage object and make sure proper content disposition is set on each file.
Of course, you need to feed this storage to the field you working on:

my_file_filed = models.FileField(upload_to='mypath', storage=DownloadableS3Boto3Storage())


问:
Error running playbook with encrypted group_vars
I am trying to run a playbook with a file that has been encrypted using ansible-vault. However, I get the following error:

```<code>ERROR! Syntax Error while loading YAML.
  could not find expected ':'

The error appears to have been in 'inventories/group_vars/main_server': line 41, column 1, but may
be elsewhere in the file depending on the exact syntax problem.
</code>```

Content of vault file:

```<code>me@server:ansible$ cat inventories/group_vars/main_server
$ANSIBLE_VAULT;1.1;AES256
...
</code>```

Command I'm running:

```<code>ansible-playbook -i inventories/group_vars/main_server --extra-vars "target=my_target" playbook.yml --ask-become-pass --ask-pass --vault-password-file vault_pwd.txt
</code>```

vault_pwd.txt is populated with the required password. I have been encrypting/decrypting as I develop my playbook. For instance, the shell script with the encrypting command:

```<code>ansible-vault encrypt inventories/group_vars/main_server --vault-password-file vault_pwd.txt
</code>```

Edit #1

Version of Ansible:

```<code>me@server:ansible$ ansible --version
ansible 2.7.5
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/me/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609]
</code>```

答:
The error you're seeing...

ERROR! Syntax Error while loading YAML.
    could not find expected ':'

The error appears to have been in 'inventories/group_vars/main_server': line 41, column 1, but may
  be elsewhere in the file depending on the exact syntax problem.

...is a YAML syntax error. Ansible is probably complaining about an actual syntax error in the unencrypted content (and if you're lucky, the line referenced in the error message is in fact the one with the error).

Body:
I am trying to run a playbook with a file that has been encrypted using ansible-vault. However, I get the following error:

ERROR! Syntax Error while loading YAML.
  could not find expected ':'

The error appears to have been in 'inventories/group_vars/main_server': line 41, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

Content of vault file:

me@server:ansible$ cat inventories/group_vars/main_server
$ANSIBLE_VAULT;1.1;AES256
...

Command I'm running:

ansible-playbook -i inventories/group_vars/main_server --extra-vars "target=my_target" playbook.yml --ask-become-pass --ask-pass --vault-password-file vault_pwd.txt

vault_pwd.txt is populated with the required password. I have been encrypting/decrypting as I develop my playbook. For instance, the shell script with the encrypting command:

ansible-vault encrypt inventories/group_vars/main_server --vault-password-file vault_pwd.txt

Edit #1

Version of Ansible:

me@server:ansible$ ansible --version
ansible 2.7.5
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/me/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609]


问:
Using $in clause for insensitive search in mongo db driver c#
I am wondering how to use the case insensitive for $in expressions.

According to the official MongoDB manual you can do this:

```<code>{ name: { $in: [ /^acme/i, /^ack/ ] } }
</code>```

I tested out this on Compass and it's working fine, search is insensitive.

I need to this using the Mongo Driver in C#.

I am doing this:

```<code>  var array = new BsonArray(companyNames);

  var filter = new BsonDocument { { "Name", new BsonDocument { { "$in", new BsonArray(array) }} } };
  var result = _collection.Find(filter).ToList();
</code>```

companyNames is a string[]

However this retrieves me only exact matches. It's kind of obvious because I am not including the "regex" expression. But I don't know how I am able to include the regex in a string.

The workaround is to create an $or expresion with regex for every company name.

Does anyone knows how to do this?

Thanks

答:
With mongo-csharp-driver, you can utilise MongoDB.Bson.BsonRegularExpression. You can either perform:

```<code>var arrayIn = new BsonArray().Add(
                      new BsonRegularExpression("^acme", "i")
                  ).Add(
                      new BsonRegularExpression("^ack"));
var filter = new BsonDocument { { "name", new BsonDocument { { "$in", arrayIn }} } };
var cursor = collection.Find(filter).ToList();
</code>```

Or alternatively, instead of string use Regex and RegexOptions:

```<code>var arrayIn = new BsonArray().Add(
                      new BsonRegularExpression(
                          new Regex(
                              "^acme", RegexOptions.IgnoreCase))
                  ).Add(new BsonRegularExpression(
                              "^ack"));
</code>```

Body:
I am wondering how to use the case insensitive for $in expressions.

According to the official MongoDB manual you can do this:

{ name: { $in: [ /^acme/i, /^ack/ ] } }

I tested out this on Compass and it's working fine, search is insensitive.

I need to this using the Mongo Driver in C#.

I am doing this:

  var array = new BsonArray(companyNames);

  var filter = new BsonDocument { { "Name", new BsonDocument { { "$in", new BsonArray(array) }} } };
  var result = _collection.Find(filter).ToList();

companyNames is a string[]

However this retrieves me only exact matches. It's kind of obvious because I am not including the "regex" expression. But I don't know how I am able to include the regex in a string.

The workaround is to create an $or expresion with regex for every company name.

Does anyone knows how to do this?

Thanks

Body:
With mongo-csharp-driver, you can utilise MongoDB.Bson.BsonRegularExpression. You can either perform:

var arrayIn = new BsonArray().Add(
                      new BsonRegularExpression("^acme", "i")
                  ).Add(
                      new BsonRegularExpression("^ack"));
var filter = new BsonDocument { { "name", new BsonDocument { { "$in", arrayIn }} } };
var cursor = collection.Find(filter).ToList();

Or alternatively, instead of string use Regex and RegexOptions:

var arrayIn = new BsonArray().Add(
                      new BsonRegularExpression(
                          new Regex(
                              "^acme", RegexOptions.IgnoreCase))
                  ).Add(new BsonRegularExpression(
                              "^ack"));


问:
UITextView (editing) - detecting that next line event occured
I have a UITextView which is editable. Now I have a requirement which requires me to find (as and when I keep typing) as to when the next line has begun (maybe due to me hitting the return key, or an auto wordwrap linebreak). Is there any notification which can be obtained to figure out when the next line has started while typing?

I tried searching for solutions to find out cursor positions within a textview but using selectedRange and the location properties to find it out does not help me. There is no correlation at all between the location value and a new line. The location value just keeps increasing on typing. Any ideas?

Thanks!

答:
Sourav Gupta's solution partially worked for me however it had a few pitfalls, namely that it didn't correctly call the target code if the editing happened in the middle of the text body (for example: writing a bunch of text, moving the cursor to the middle and then hitting return three times) as well as handling insertion events like pasting and text correction. As a result, I did some testing on my own and found a few more conditions in which we can assume that editing has moved to the next line.

note: this approach has a few false positives but I found that to be more tolerable as I use this for relaying out the code and so laying out unnecessarily is far better than not responding

Swift 5

```<code>private var previousRect:CGRect = CGRect.zero
private func checkIfReturnOrLineWrap(textView:UITextView) {
    let currentRect = textView.caretRect(for:textView.endOfDocument)
    if (currentRect.origin.y != previousRect.origin.y && (previousRect.origin.y != CGFloat.infinity || currentRect.origin.y > 0) ||
        currentRect.origin.y == CGFloat.infinity) {
        //React to the line change!
    }
    previousRect = currentRect
}

//MARK: UITextViewDelegate methods (be sure to hook up your textviews!)
func textViewDidChange(_ textView: UITextView) {
    checkIfReturnOrLineWrap(textView: textView)
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    checkIfReturnOrLineWrap(textView: textView)
    return true
}
</code>```

Body:
Sourav Gupta's solution partially worked for me however it had a few pitfalls, namely that it didn't correctly call the target code if the editing happened in the middle of the text body (for example: writing a bunch of text, moving the cursor to the middle and then hitting return three times) as well as handling insertion events like pasting and text correction. As a result, I did some testing on my own and found a few more conditions in which we can assume that editing has moved to the next line.

note: this approach has a few false positives but I found that to be more tolerable as I use this for relaying out the code and so laying out unnecessarily is far better than not responding

Swift 5

private var previousRect:CGRect = CGRect.zero
private func checkIfReturnOrLineWrap(textView:UITextView) {
    let currentRect = textView.caretRect(for:textView.endOfDocument)
    if (currentRect.origin.y != previousRect.origin.y && (previousRect.origin.y != CGFloat.infinity || currentRect.origin.y > 0) ||
        currentRect.origin.y == CGFloat.infinity) {
        //React to the line change!
    }
    previousRect = currentRect
}

//MARK: UITextViewDelegate methods (be sure to hook up your textviews!)
func textViewDidChange(_ textView: UITextView) {
    checkIfReturnOrLineWrap(textView: textView)
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    checkIfReturnOrLineWrap(textView: textView)
    return true
}


问:
Pure GWT, events converting
So, I have a ‘FlexTable’ in GWT and I need to drop down list of actions on right click on some cell. On left mouse click to retrieve ‘rowIndex’ of my cell I simply use ClickEvent method ‘getCellForEvent(event).getRowIndex()’. But there is no right click handler in pure GWT. So I decided to use ContextMenuHandler which requires ContextMenuEvent. And, of course, I can’t put ContextMenuEvent into ClickEvent method ‘getCellForEvent’. Is there any solution to this case? Or maybe someone knows easier way to drop down list on rightClick on ‘FlexTable’.</p>

答:
I have done this for a CellTable or DataGrid widget, but not FlexTable.  With the former I applied one handler object to the entire grid widget and used the event to work out the row or cell that the event happened in.  I can't see how that can be done with FlexTable.

With FlexTable, a hack would be to create a handler object for each cell, and tell it the cell/row at the time of creation.  Something like this:

```<code>    cell.addDomHandler(new ContextMenuHandler() {
        @Override
        public void onContextMenu(ContextMenuEvent event)
        {
            // stop the browser from opening the context menu
            event.preventDefault();
            event.stopPropagation();

            NativeEvent nativeClickEvent = event.getNativeEvent();

            displayPopupMenuForCell(cell, nativeClickEvent);
        }
    }, ContextMenuEvent.getType());
</code>```

In the above, cell needs to be a Widget.  So you would need to get the  Element in the HTMLTable (FlexTable exends HTMLTable which is a normal HTML table element) and wrap it as a Widget.  I am not sure how to do that, but it would be possible.

One other thing, you need to prevent the browser from popping up its own context menu.  I added this to the html file in the body tag:

```<code>  <body oncontextmenu="return false" >
</code>```

Title: Pure GWT, events converting

Body:
I have done this for a CellTable or DataGrid widget, but not FlexTable.  With the former I applied one handler object to the entire grid widget and used the event to work out the row or cell that the event happened in.  I can't see how that can be done with FlexTable.

With FlexTable, a hack would be to create a handler object for each cell, and tell it the cell/row at the time of creation.  Something like this:

    cell.addDomHandler(new ContextMenuHandler() {
        @Override
        public void onContextMenu(ContextMenuEvent event)
        {
            // stop the browser from opening the context menu
            event.preventDefault();
            event.stopPropagation();

            NativeEvent nativeClickEvent = event.getNativeEvent();

            displayPopupMenuForCell(cell, nativeClickEvent);
        }
    }, ContextMenuEvent.getType());

In the above, cell needs to be a Widget.  So you would need to get the  Element in the HTMLTable (FlexTable exends HTMLTable which is a normal HTML table element) and wrap it as a Widget.  I am not sure how to do that, but it would be possible.

One other thing, you need to prevent the browser from popping up its own context menu.  I added this to the html file in the body tag:

  <body oncontextmenu="return false" >


问:
How to use pick_asset from the photos module?
I use the App Python Offline.

I tried to use photos module.

```<code>import photos
assets = photos.pick_asset(title='Pick some assets', multi=True)
print(assets)
</code>```

I got this error: AttributeError: 'module' object has no attribute 'pick_asset'

https://itunes.apple.com/fr/app/python-offline/id1351388468?mt=8

http://omz-software.com/pythonista/docs/ios/photos.html

答:
AttributeError for pythonista means the attribute does not exist. As this is not a PC platform I am not sure if you can debug it in pythonista in itself. As I see in the docs it the attribute photos.pick_asset is present.

You can try uninstalling the app and reinstalling it again. Similar case happened with me in case of matplotlib, I reinstalled and it worked again.

Body:
I use the App Python Offline.

I tried to use photos module.

import photos
assets = photos.pick_asset(title='Pick some assets', multi=True)
print(assets)

I got this error: AttributeError: 'module' object has no attribute 'pick_asset'

https://itunes.apple.com/fr/app/python-offline/id1351388468?mt=8

http://omz-software.com/pythonista/docs/ios/photos.html


问:
Recycler's content doubles every time the fragment is added to the fragment manager even though it should be cleared
I have an fragment with photos recycler (user profile with a gallery).

I populate the recycler in onViewCreated, and my function calls adapter.clear() before listening to the data. I try to clear twice actually.
I add the fragment to the supportFragmentManager, and when the back button is clicked I pop the back stack.

The problem is, that even though I pop the stack (which as to my understanding, should remove the fragment and completely destroy it), when I re-add the fragment and go to the profile of the same user, the gallery now has double the photos. If I do it again, it will be triple.

This is my function:

```<code>private fun listenToImagesFromRoll() {

    galleryRollAdapter.clear()

    val ref = FirebaseDatabase.getInstance().getReference("/users/${userProfile.uid}/images")

    ref.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(p0: DataSnapshot) {

            for (imagePath in p0.children){

                val imageObjectPath =
                    FirebaseDatabase.getInstance().getReference("/images/${imagePath.key}/body")

                imageObjectPath.addListenerForSingleValueEvent(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {

                    }

                    override fun onDataChange(p0: DataSnapshot) {
                        val imageObject = p0.getValue(Images::class.java)
                        if (imageObject != null) {

                            imageList.add(FeedImage(imageObject, 1))
                            galleryRollAdapter.clear()
                            galleryRollAdapter.addAll(imageList.reversed())
                        }
                    }
                })

            }

        }

        override fun onCancelled(p0: DatabaseError) {
        }
    })
}
</code>```

I call this inside in the in create method, inside an Observer that holds the user which profile I open.

This is how I add the fragment:

```<code>activity.subFm.beginTransaction()
.add(R.id.feed_subcontents_frame_container, activity.profileSecondRandomUserFragment, "profileSecondRandomUserFragment").addToBackStack("profileSecondRandomUserFragment")
.commit()
</code>```

And this is how I pop it:

```<code>subFm.popBackStack("profileSecondRandomUserFragment", FragmentManager.POP_BACK_STACK_INCLUSIVE)
</code>```

Can't understand why it keeps re adding the photos.

答:
You need to clear your list before every time you want to load fresh new content.

or it will just append a new set of data at the end of your list.

```<code>           imageObjectPath.addListenerForSingleValueEvent(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {

                }

                override fun onDataChange(p0: DataSnapshot) {
                    val imageObject = p0.getValue(Images::class.java)
                    if (imageObject != null) {
---- The point is to clear the collection
---- before you tell your adapter to update the list, like this
                      ++imageList.clear()
                        imageList.add(FeedImage(imageObject, 1))
                      +-galleryRollAdapter.clear()// may not need, try it
                      +-galleryRollAdapter.notifyDataSetChanged()
                    }
                }
            })
</code>```

Body:
I have an fragment with photos recycler (user profile with a gallery).

I populate the recycler in onViewCreated, and my function calls adapter.clear() before listening to the data. I try to clear twice actually.
I add the fragment to the supportFragmentManager, and when the back button is clicked I pop the back stack.

The problem is, that even though I pop the stack (which as to my understanding, should remove the fragment and completely destroy it), when I re-add the fragment and go to the profile of the same user, the gallery now has double the photos. If I do it again, it will be triple.

This is my function:

private fun listenToImagesFromRoll() {

    galleryRollAdapter.clear()

    val ref = FirebaseDatabase.getInstance().getReference("/users/${userProfile.uid}/images")

    ref.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(p0: DataSnapshot) {

            for (imagePath in p0.children){

                val imageObjectPath =
                    FirebaseDatabase.getInstance().getReference("/images/${imagePath.key}/body")

                imageObjectPath.addListenerForSingleValueEvent(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {

                    }

                    override fun onDataChange(p0: DataSnapshot) {
                        val imageObject = p0.getValue(Images::class.java)
                        if (imageObject != null) {

                            imageList.add(FeedImage(imageObject, 1))
                            galleryRollAdapter.clear()
                            galleryRollAdapter.addAll(imageList.reversed())
                        }
                    }
                })

            }

        }

        override fun onCancelled(p0: DatabaseError) {
        }
    })
}

I call this inside in the in create method, inside an Observer that holds the user which profile I open.

This is how I add the fragment:

activity.subFm.beginTransaction()
.add(R.id.feed_subcontents_frame_container, activity.profileSecondRandomUserFragment, "profileSecondRandomUserFragment").addToBackStack("profileSecondRandomUserFragment")
.commit()

And this is how I pop it:

subFm.popBackStack("profileSecondRandomUserFragment", FragmentManager.POP_BACK_STACK_INCLUSIVE)

Can't understand why it keeps re adding the photos.

Body:
You need to clear your list before every time you want to load fresh new content.

or it will just append a new set of data at the end of your list.

           imageObjectPath.addListenerForSingleValueEvent(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {

                }

                override fun onDataChange(p0: DataSnapshot) {
                    val imageObject = p0.getValue(Images::class.java)
                    if (imageObject != null) {
---- The point is to clear the collection
---- before you tell your adapter to update the list, like this
                      ++imageList.clear()
                        imageList.add(FeedImage(imageObject, 1))
                      +-galleryRollAdapter.clear()// may not need, try it
                      +-galleryRollAdapter.notifyDataSetChanged()
                    }
                }
            })


问:
How to parameterise a Python dictionary in papermill?
I want to pass on all the parameters in one variable. To make this happen, I am passing a dictionary in my Python client for Papermill using:

```<code>params = {"aviral":"srivastava"}
pm.execute_notebook( 'path/to/input.ipynb', 'path/to/output.ipynb', parameters = params )
</code>```

Now, I want to do run the corresponding command from bash. In the document it states:

```<code>papermill local/input.ipynb s3://bkt/output.ipynb -p alpha 0.6 -p l1_ratio 0.1
</code>```

But nowhere is given how to pass on a dictionary.

I tried many permutations and combinations like:

papermill test_params.ipynb params_output.ipynb -p params {"aviral":"srivastava"}

papermill test_params.ipynb params_output.ipynb -p params '{"aviral":"srivastava"}'

I also read to pass a dict in the format: '{"aviral":"srivastava"}' and then json.loads would do the work. But I am not having the liberty for converting the input. It has to be used right away in the script.

Just a minimal script to actually check the type of the variable passed:

```<code>params = {} # I tag this with `parameter`
print(type(params))
print(params)
</code>```

Yes, I see the params variable got changed when running with papermill but the value passed is a complete string.

答: Since, in your case, you can not modify the template notebook directly to parse the string input, how about having a python script that you call which then executes papermill? That allows you to parse the string into a python dictionary and then pass that to the papermill execution. You could also pass through the notebook names in the same way. </p>

Body:
I want to pass on all the parameters in one variable. To make this happen, I am passing a dictionary in my Python client for Papermill using:

params = {"aviral":"srivastava"}
pm.execute_notebook( 'path/to/input.ipynb', 'path/to/output.ipynb', parameters = params )

Now, I want to do run the corresponding command from bash. In the document it states:

papermill local/input.ipynb s3://bkt/output.ipynb -p alpha 0.6 -p l1_ratio 0.1

But nowhere is given how to pass on a dictionary.

I tried many permutations and combinations like:

papermill test_params.ipynb params_output.ipynb -p params {"aviral":"srivastava"}

papermill test_params.ipynb params_output.ipynb -p params '{"aviral":"srivastava"}'

I also read to pass a dict in the format: '{"aviral":"srivastava"}' and then json.loads would do the work. But I am not having the liberty for converting the input. It has to be used right away in the script.

Just a minimal script to actually check the type of the variable passed:

params = {} # I tag this with `parameter`
print(type(params))
print(params)

Yes, I see the params variable got changed when running with papermill but the value passed is a complete string.


问:
TextField reloads FutureBuilder when pressed/left in Flutter
The user can either enter the answer with InputChips or manually type it in the TextField. When I try with InputChips, the correct answer is not detected. When I try to manually type it, the FutureBuilder reloads when I enter and leave the TextField. What is the reason?
The Future function should only be called once because it fetches a random document from Firestore, splits the String and scrambles the different pieces. It is some form of quiz.

class _buildPhrases extends State<PhrasesSession>{
  TextEditingController _c;
  String _text = "initial";

  @override
  void initState(){
    _c = new TextEditingController();
    super.initState();
  }

  @override
  void dispose(){
    _c?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    final Arguments args = ModalRoute.of(context).settings.arguments;
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;

    // TODO: implement build
    return Scaffold(
      body: Column(
        children: <Widget>[
          Flexible(flex: 2, child: _buildRest(context),),
          Flexible(flex: 5,
            child: FutureBuilder(
              future: getEverything(args.colName),
              builder: (context, snapshot){
                if(!snapshot.hasData){
                  return Center(child: CircularProgressIndicator(),);
                }else{

                  return Column(
                    children: <Widget>[
                      Flexible(flex: 1, child: Text(snapshot.data[1]),),
                      Divider(),
                      Flexible(flex: 2, child: Container(
                        child: TextField(
                        onChanged: (t){
                            _text += "$t ";
                            if(_c.text == snapshot.data[0]){
                              return print("CORRECT ANSWER");
                            }
                        },
                        controller: _c,
                        textAlign: TextAlign.center,
                          enabled: true,

                      ),
                      ),),
                      Flexible(flex: 3,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: snapshot.data.length - 2,
                          itemBuilder: (context, index){
                            if(index>snapshot.data.length - 2){
                              return null;
                            }else{
                              return Padding(
                                padding: const EdgeInsets.all(4.0),
                                child: InputChip(
                                  label: Text(snapshot.data[index + 2]),
                                  onPressed: (){
                                    _c.text += "${snapshot.data[index  + 2]} ";
                                  },
                                ),
                              );
                            }
                          },
                        ))
                    ],
                  );
                }
              },
            ),)
        ],
      )
    );
  }
}
```

答:
Let's solve this in parts.

When I try to manually type it the FutureBuilder reloads when I enter and leave the TextField. What is the reason?

This is hapenning because when the keyboard is showing or hidding the flutter framework calls build method of your widget and this default behavior is the reason why your FutureBuilder is realoading. You should avoid call network methods inside build method and I advise you to use BLoC pattern to handle state of your widget.

My Future needs the String that is passed from another route, though. See the Arguments args = .... Any idea how I get it in the initState?

Well if you need context instance to get this String you can't access current context inside initState method because your widget isn't full initialized yet. A simple way to solve this in your case but not the best is verify if the data was already fetched from network or not.

```<code>Future _myNetworkFuture; // declare this as member of your stateWidgetClass

Widget build(BuildContext context){
   final Arguments args = ModalRoute.of(context).settings.arguments;
   var height = MediaQuery.of(context).size.height;
   var width = MediaQuery.of(context).size.width;

   // this line says if(_myNetworkFuture == null) do the thing.
   _myNetworkFuture ??= getEverything(args.colName);

   return ...
   Flexible(flex: 5,
        child: FutureBuilder(
          future: _myNetworkFuture,
          builder: (context, snapshot){
           // ...
          }
}
</code>```

With this approach when flutter framework calls build method if you already fetched the data you don't download the data again. But I really advise you to use BLoC pattern in this kind of situation.

Body:
Let's solve this in parts.

When I try to manually type it the FutureBuilder reloads when I enter and leave the TextField. What is the reason?

This is hapenning because when the keyboard is showing or hidding the flutter framework calls build method of your widget and this default behavior is the reason why your FutureBuilder is realoading. You should avoid call network methods inside build method and I advise you to use BLoC pattern to handle state of your widget.

My Future needs the String that is passed from another route, though. See the Arguments args = .... Any idea how I get it in the initState?

Well if you need context instance to get this String you can't access current context inside initState method because your widget isn't full initialized yet. A simple way to solve this in your case but not the best is verify if the data was already fetched from network or not.

Future _myNetworkFuture; // declare this as member of your stateWidgetClass

Widget build(BuildContext context){
   final Arguments args = ModalRoute.of(context).settings.arguments;
   var height = MediaQuery.of(context).size.height;
   var width = MediaQuery.of(context).size.width;

   // this line says if(_myNetworkFuture == null) do the thing.
   _myNetworkFuture ??= getEverything(args.colName);

   return ...
   Flexible(flex: 5,
        child: FutureBuilder(
          future: _myNetworkFuture,
          builder: (context, snapshot){
           // ...
          }
}

With this approach when flutter framework calls build method if you already fetched the data you don't download the data again. But I really advise you to use BLoC pattern in this kind of situation.


答:
I would use a left join here:

```<code>SELECT
    po.position_id,
    po.position_name,
    COALESCE(pe.people_name, 'EMPTY') AS STATUS
FROM position po
LEFT JOIN people pe
    ON po.position_id = pe.people_position_id;
</code>```

By the way, the reason your current right join attempt is failing is that you have placed the people table on the right side of the join.  This means that non matching position records would be discarded.  Here is my answer above, rewritten using a right join:

```<code>SELECT
    po.position_id,
    po.position_name,
    COALESCE(pe.people_name, 'EMPTY') AS STATUS
FROM people pe
RIGHT JOIN position po
    ON po.position_id = pe.people_position_id;
</code>```

Note carefully that the table order has switched.  Most of the time, you will see people using left joins rather than right joins.

Title: Return all wows, mached and unmatched in MySQL Query

Body:
I have two tables and i'm like to query 2 tables to obtain a report.

POSITION
+-------------+---------------+
| position_id | position_name |
+-------------+---------------+
|     1       |     E1P1      |
|     2       |     E1P2      |
|     3       |     E3P3      |
|     4       |     E4P4      |
+-------------+---------------+

PEOPLE
+------------+-------------+--------------------+
| people_id  | people_name | people_position_id |
+------------+-------------+--------------------+
|     1      |    JOHN     |         2          |
|     2      |    MARK     |         4          |
+------------+-------------+--------------------+

QUERY

SELECT position_id, position_name, people_name FROM position
RIGHT JOIN people ON people_position_id = position_id

When I use simple query I get only matched rows, ho to obtain all?

I'm like to obtain this result

+----+----------+--------+
| ID | POSITION | STATUS |
+----+----------+--------+
| 1  |   E1P1   | Empty  |
| 2  |   E1P2   | JOHN   |
| 3  |   E3P3   | Empty  |
| 4  |   E4P4   | MARK   |
+----+----------+--------+

Body:
I would use a left join here:

SELECT
    po.position_id,
    po.position_name,
    COALESCE(pe.people_name, 'EMPTY') AS STATUS
FROM position po
LEFT JOIN people pe
    ON po.position_id = pe.people_position_id;

By the way, the reason your current right join attempt is failing is that you have placed the people table on the right side of the join.  This means that non matching position records would be discarded.  Here is my answer above, rewritten using a right join:

SELECT
    po.position_id,
    po.position_name,
    COALESCE(pe.people_name, 'EMPTY') AS STATUS
FROM people pe
RIGHT JOIN position po
    ON po.position_id = pe.people_position_id;

Note carefully that the table order has switched.  Most of the time, you will see people using left joins rather than right joins.


问:
Using map function instead of for loop
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

```<code>def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)
</code>```

答:
In Python 3, map is an iterator: (akin: itertools.imap)

```<code>class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
</code>```

While in Python 2:

```<code>map(...)
    map(function, sequence[, sequence, ...]) -> list
</code>```

It returns a list by default.

So in your case, you need to do:

numwords = list(map(wordcount, lines))

There are other problems also with your code, but others have pointed that out well enough.

Title: Using map function instead of for loop

Body:
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23":
Number of words =

What am I doing wrong here?

def wordcount(l):
    global numwords
    words = l.split()
    numwords += len(words)

f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)

numwords=0

numwords = map(wordcount, lines)
print ('Number of words =', numwords)

Body:
In Python 3, map is an iterator: (akin: itertools.imap)

class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

While in Python 2:

map(...)
    map(function, sequence[, sequence, ...]) -> list

It returns a list by default.

So in your case, you need to do:

numwords = list(map(wordcount, lines))

There are other problems also with your code, but others have pointed that out well enough.


问:
Asp Core Api Route that Accepts All Paths
Trying to find somewhere that explains how to create a route that accepts all requests starting with a particular name. As well as retrieving information of that request. So an example of that would be creating a route of test that accepts all incoming get requests of that route.

Ideally, something that supports

```<code>[Route("test")]
[ApiController]
public class TestController : ControllerBase
{
    // so that all request that start with 'test' go through this method
    public IActionRequest Process() {

    }
}
</code>```

答:
Approach 1:

```<code>[Route("test/{*any}")]
[ApiController]
public class TestController : Controller
{

    // so that all request that start with 'test' go through this method
    public IActionResult Process()
    {
        return new JsonResult(new{
            a = 1,
        });
    }

}
</code>```

Approach 2:

register a catch-all route :

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        name:"routeAny",
        template:"test/{*any}",
        defaults: new{
            Controller = "Test",
            Action = "Process",
        }
    );
});
</code>```

And remove the [ApiController] attribute because it requires a [Route()]:

```
<strike>[ApiController]</strike>
public class TestController : Controller
{

    // so that all request that start with 'test' go through this method
    public IActionResult Process()
    {
        return new JsonResult(new{
            a = 1,
        });
    }

}
```

Body:
Trying to find somewhere that explains how to create a route that accepts all requests starting with a particular name. As well as retrieving information of that request. So an example of that would be creating a route of test that accepts all incoming get requests of that route.

Ideally, something that supports

[Route("test")]
[ApiController]
public class TestController : ControllerBase
{
    // so that all request that start with 'test' go through this method
    public IActionRequest Process() {

    }
}

Body:
Approach 1:

[Route("test/{*any}")]
[ApiController]
public class TestController : Controller
{

    // so that all request that start with 'test' go through this method
    public IActionResult Process()
    {
        return new JsonResult(new{
            a = 1,
        });
    }

}

Approach 2:

register a catch-all route :

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        name:"routeAny",
        template:"test/{*any}",
        defaults: new{
            Controller = "Test",
            Action = "Process",
        }
    );
});

And remove the [ApiController] attribute because it requires a [Route()]:

[ApiController]
public class TestController : Controller
{

    // so that all request that start with 'test' go through this method
    public IActionResult Process()
    {
        return new JsonResult(new{
            a = 1,
        });
    }

}


问:
What is the difference between .NET Core and .NET Standard Class Library project types?
In Visual Studio, there are at least three different types of class libraries you can create:

Class Library (.NET Framework)

Class Library (.NET Standard)

Class Library (.NET Core)

While the first is what we've been using for years, a major point of confusion I've been having is when to use the .NET Standard and .NET Core class library types. I've been bitten by this recently when attempting to multi-target different framework versions, and creating a unit test project.

So, what is the difference between Class Library (.NET Standard) and Class Library (.NET Core), why do both exist, and when should we use one over the other?

答:
The previous answers may describe the best understanding about the difference between .NET Core, .NET Standard and .NET Framework, so I just want to share my experience when choosing this over that.

In the project that you need to mix between .NET Framework, .NET Core and .NET Standard. For example, at the time we build the system with .NET Core 1.0, there is no support for Window Services hosting with .NET Core.

The next reason is we were using Active Report which doesn't support .NET Core.

So we want to build an infrastructure library that can be used for both .NET Core (ASP.NET Core) and Windows Service and Reporting (.NET Framework) -> That's why we chose .NET Standard for this kind of library.
Choosing .NET standard means you need to carefully consider every class in the library should be simple and cross .NET (Core, Framework, and Standard).

Conclusion:

.NET Standard for the infrastructure library and shared common. This library can be referenced by .NET Framework and .NET Core.

.NET Framework for unsupported technologies like Active Report, Window Services (now with .NET 3.0 it supports).

.NET Core for ASP.NET Core of course.

Microsoft just announced .NET 5: Introducing .NET 5


问:
php rename() Device or resource busy
I have code that gives the following error:

Warning:

[function.rename]: Device or resource busy in

```<code>if ($handle = opendir($temp_images)) {

        /* This is the correct way to loop over the directory. */
        while (false !== ($file = readdir($handle))) {
             if ($file == $file) {
             }
             $path = '';
             $dir_handle = opendir($path);
             chdir($path);
             $oldfile = $path.$file ;
             $newfile = $path.preg_replace('/[\\&\\%\\$\\ ]+/', '-', $file); // replace &%$ with a -

             if(FALSE == rename($oldfile, $newfile))
             {

             }

        }

       closedir($handle);
}
</code>```

What's the problem and how do I fix it?

答:
Try to exclude '.' and '..'.

```<code>if($file == '.' || $file == '..') {
    continue;
}
</code>```

It works for me. Hopefully, it will work for you. Thanks

Title: php rename() Device or resource busy

Body:
I have code that gives the following error:

Warning:

[function.rename]: Device or resource busy in

if ($handle = opendir($temp_images)) {

        /* This is the correct way to loop over the directory. */
        while (false !== ($file = readdir($handle))) {
             if ($file == $file) {
             }
             $path = '';
             $dir_handle = opendir($path);
             chdir($path);
             $oldfile = $path.$file ;
             $newfile = $path.preg_replace('/[\\&\\%\\$\\ ]+/', '-', $file); // replace &%$ with a -

             if(FALSE == rename($oldfile, $newfile))
             {

             }

        }

       closedir($handle);
}

What's the problem and how do I fix it?

Body:
Try to exclude '.' and '..'.

if($file == '.' || $file == '..') {
    continue;
}

It works for me. Hopefully, it will work for you. Thanks


问:
React - How to sync front-end with back-end requests without using setTimeout?
When I'm trying to do a validation in react JS I normally have to create a set time out function to sync the fetch api calls with front end as the fetch api calls take a bit of time. Is there are any other way to do this? Something that's under best practices and not recurring codes?

I have been using set time out with 4000-5000, it works, but i feel as if that's not the best way to do so.

edit-
Below is the code snippet of what i did before using timeout, but for some reason when the function runs, 'existingTrains' disappears from state.

```<code>async getExistingReservations(date, trackNo, direction, noTickets) {

        let self = this;
        var trains;
        var ticketRange = 100 - noTickets;

        var data = {
            "date": date,
            "trackNo": trackNo,
            "direction": direction
        }

        console.log(data);

        //get Existing Reservation Details
        await fetch('http://localhost:5000/resRecords/getSeats', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {'Content-Type': 'application/json'}
        })
            .then(response => {
                return response.json()
            })
            .then(json => {
                console.log(json)
                trains = json.find(function (tickets) {
                    return tickets.noTickets < ticketRange

                })
                self.setState({
                        existingTrains: trains
                    }
                )
            });

    }
</code>```

答:
The best way to resolve this is by using async -> await.

```<code>const getNetworkRequest = async (): string => {
  const r = await makeNetworkRequest();
  console.log(r);

  if(r.data){ return 'got it!' }
  return 'no data :(';
}
</code>```

Body:
When I'm trying to do a validation in react JS I normally have to create a set time out function to sync the fetch api calls with front end as the fetch api calls take a bit of time. Is there are any other way to do this? Something that's under best practices and not recurring codes?

I have been using set time out with 4000-5000, it works, but i feel as if that's not the best way to do so.

edit-
Below is the code snippet of what i did before using timeout, but for some reason when the function runs, 'existingTrains' disappears from state.

async getExistingReservations(date, trackNo, direction, noTickets) {

        let self = this;
        var trains;
        var ticketRange = 100 - noTickets;

        var data = {
            "date": date,
            "trackNo": trackNo,
            "direction": direction
        }

        console.log(data);

        //get Existing Reservation Details
        await fetch('http://localhost:5000/resRecords/getSeats', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {'Content-Type': 'application/json'}
        })
            .then(response => {
                return response.json()
            })
            .then(json => {
                console.log(json)
                trains = json.find(function (tickets) {
                    return tickets.noTickets < ticketRange

                })
                self.setState({
                        existingTrains: trains
                    }
                )
            });

    }

Body:
The best way to resolve this is by using async -> await.

const getNetworkRequest = async (): string => {
  const r = await makeNetworkRequest();
  console.log(r);

  if(r.data){ return 'got it!' }
  return 'no data :(';
}


问:
How to clean up v-bind directives from html code in Vue?
Ok, I've got some Vue code and HTML.

For example:

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});
</code>```

And in my page:

```<code><div is="area-selectors-box" v-bind:selects="selects"></div>
</code>```

It all works, but if I read the page source, I see the v-bind:selects="selects" portion, which is not standard compliant, I guess.

Similarly, other components have other object properties like:

```<code>Vue.component('area-option', {
  template: `<option :area="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});
</code>```

which on the page source evaluates to something like:

```<code><option area="[object Object]" value="82">Europa</option>
</code>```

which is obviously not desirable.

How do I bind these properties without them appearing in the DOM as attributes?

答:
By default, when v-bind encounters a binding name that isn't associated to a property on the target, the value is converted to a string and assigned as an attribute. Since <option> has no property named area, the object is assigned as a string attribute, which you observed in the DOM.

You can use v-bind's .prop modifier to always assign it as a property:

<option :area.prop="area" ...>
```
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('area-selectors-box', {
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `<div>
    <select v-model="selection">
      <area-option
         v-for="option in select.options"
         :key="option.id"
         :area="option.area" />
    </select>
    ```{{selection}}```
</div>`,
  props: ['select'],
  data() {
    return {
      selection: null,
    }
  }
})

Vue.component('area-option', {
  template: `<option :area.prop="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

new Vue({
  el: '#app',
  data: () => ({
    selects: [
      { id: 1, options: [
                { id: 10, area: { term_id: 100, name: 'Europe' } },
                { id: 11, area: { term_id: 101, name: 'Asia' } },
              ]
      },
      { id: 2, options: [
                { id: 20, area: { term_id: 200, name: 'North America' } },
                { id: 21, area: { term_id: 201, name: 'South America' } },
              ]
      },
    ]
  }),
})</code>```

  <area-selectors-box :selects="selects"></area-selectors-box>

```

Body:
Ok, I've got some Vue code and HTML.

For example:

Vue.component('area-selectors-box', {
  template: `

      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>

  `,
  props:['selects']
});

And in my page:

It all works, but if I read the page source, I see the v-bind:selects="selects" portion, which is not standard compliant, I guess.

Similarly, other components have other object properties like:

Vue.component('area-option', {
  template: `<option :area="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

which on the page source evaluates to something like:

<option area="[object Object]" value="82">Europa</option>

which is obviously not desirable.

How do I bind these properties without them appearing in the DOM as attributes?

Body:
By default, when v-bind encounters a binding name that isn't associated to a property on the target, the value is converted to a string and assigned as an attribute. Since <option> has no property named area, the object is assigned as a string attribute, which you observed in the DOM.

You can use v-bind's .prop modifier to always assign it as a property:

<option :area.prop="area" ...>

Vue.component('area-selectors-box', {
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `<div>
    <select v-model="selection">
      <area-option
         v-for="option in select.options"
         :key="option.id"
         :area="option.area" />
    </select>
    <pre>{{selection}}</pre>
</div>`,
  props: ['select'],
  data() {
    return {
      selection: null,
    }
  }
})

Vue.component('area-option', {
  template: `<option :area.prop="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

new Vue({
  el: '#app',
  data: () => ({
    selects: [
      { id: 1, options: [
                { id: 10, area: { term_id: 100, name: 'Europe' } },
                { id: 11, area: { term_id: 101, name: 'Asia' } },
              ]
      },
      { id: 2, options: [
                { id: 20, area: { term_id: 200, name: 'North America' } },
                { id: 21, area: { term_id: 201, name: 'South America' } },
              ]
      },
    ]
  }),
})

<script src="https://unpkg.com/vue@2.6.10"></script>

<div id="app">
  <area-selectors-box :selects="selects"></area-selectors-box>
</div>


问:
How to call an external method from within an MVEL expression?
I have a JAVA class that has two methods. The first one is the main method and the second one is method1().

Let's say the following is the class:

```<code>public class SomeClass() {
  public static void main(String[] args){
    MVEL.eval("System.out.println(\"I am inside main method\");method1();");
  }
  public static void method1(){
    System.out.println("I am inside method 1");
  }
}
</code>```

Now when I run the program, I get the following output:-

I am inside main method

```<code>Exception in thread "main" [Error: no such method or function: method1]
[Near : ... main method"); method1(); ..}]
                                    ^
[Line: 1, Column: 184]
at org.mvel2.PropertyAccessor.getMethod(PropertyAccessor.java:898)
at org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:182)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:146)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:126)
at org.mvel2.ast.ASTNode.getReducedValue(ASTNode.java:187)
at org.mvel2.MVELInterpretedRuntime.parseAndExecuteInterpreted(MVELInterpretedRuntime.java:106)
at org.mvel2.MVELInterpretedRuntime.parse(MVELInterpretedRuntime.java:49)
at org.mvel2.MVEL.eval(MVEL.java:136)
at mypackage.SomeClass.main(SomeClass.java:15)
</code>```

As you can see, it prints the first sop, but when it comes to calling method1, it throws exception.

Is there a way to fix this issue?

答:
There are two ways to call your own method in MVEL. First way like @Ankur Singhal's answer. And another way is use ParserContext.

Here is the Class

```<code>public class CalcHelper {
    public static int add(int a, int b){
        return a + b;
    }
}
</code>```

Use ParserContext to import the Class to MVEL.

```<code>ParserContext parserContext = new ParserContext();
parserContext.addImport(CalcHelper.class.getSimpleName(), CalcHelper.class);
</code>```

Then you can call static method of the Class in your expression.

```<code>Serializable s = MVEL.compileExpression("CalcHelper.add(1,2)", parserContext);
MVEL.executeExpression(s, parserContext);
</code>```

Body:
I have a JAVA class that has two methods. The first one is the main method and the second one is method1().

Let's say the following is the class:

public class SomeClass() {
  public static void main(String[] args){
    MVEL.eval("System.out.println(\"I am inside main method\");method1();");
  }
  public static void method1(){
    System.out.println("I am inside method 1");
  }
}

Now when I run the program, I get the following output:-

I am inside main method

Exception in thread "main" [Error: no such method or function: method1]
[Near : ... main method"); method1(); ..}]
                                    ^
[Line: 1, Column: 184]
at org.mvel2.PropertyAccessor.getMethod(PropertyAccessor.java:898)
at org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:182)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:146)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:126)
at org.mvel2.ast.ASTNode.getReducedValue(ASTNode.java:187)
at org.mvel2.MVELInterpretedRuntime.parseAndExecuteInterpreted(MVELInterpretedRuntime.java:106)
at org.mvel2.MVELInterpretedRuntime.parse(MVELInterpretedRuntime.java:49)
at org.mvel2.MVEL.eval(MVEL.java:136)
at mypackage.SomeClass.main(SomeClass.java:15)

As you can see, it prints the first sop, but when it comes to calling method1, it throws exception.

Is there a way to fix this issue?

Body:
There are two ways to call your own method in MVEL. First way like @Ankur Singhal's answer. And another way is use ParserContext.

Here is the Class

public class CalcHelper {
    public static int add(int a, int b){
        return a + b;
    }
}

Use ParserContext to import the Class to MVEL.

ParserContext parserContext = new ParserContext();
parserContext.addImport(CalcHelper.class.getSimpleName(), CalcHelper.class);

Then you can call static method of the Class in your expression.

Serializable s = MVEL.compileExpression("CalcHelper.add(1,2)", parserContext);
MVEL.executeExpression(s, parserContext);


问:
Cognito accounts created with admin_create_user can't log in. Is there a known fix?
I'm creating a backend tool to create some accounts in an AWS Cognito User Pool using Python and boto3. Creating accounts with CognitoIdentityProvider's admin_create_user seems to work fine, but when I attempt to log into our app with the new account I receive a 400 response with:

{"__type":"UserNotFoundException","message":"User does not exist."}

I have made sure that the user has in-fact been added to the cognito user pool and that the user is enabled.

I have also specified that the email address be verified automatically upon account creation.

Here is my account creation function:

import boto3

idp_client = boto3.client('cognito-idp')

# Redacted for stackoverflow example
user_pool_id = 'XXXXXXXXXXX'

response = idp_client.admin_create_user(
            UserPoolId=user_pool_id,
            Username=email,
            UserAttributes=[
                {
                    'Name': 'email',
                    'Value': email
                },{
                    'Name': 'email_verified',
                    'Value': 'true'
                }
            ],
            TemporaryPassword=generateSecureRandomString()
        )
```

I'd expect that as the account is successfully created in the Cognito user pool and that the account seems to be enabled and verified that this should result in an account that can sign-in.

Any light that can be shed on the problem would be greatly appreciated!

答:
That code is perfectly fine. So it must be a problem with either the pool settings or the login flow.

In the pool settings, make sure it's set to log in with "email address or phone number" - not username.

In the login flow, are you using the hosted ui? It might be worth giving that a shot, because it will weed out any issues with your login code. Note that your user will be set as status "FORCE_CHANGE_PASSWORD". I'm not sure what error cognito returns if you try to log someone in with your own code, but they have that set.

Body:
I'm creating a backend tool to create some accounts in an AWS Cognito User Pool using Python and boto3. Creating accounts with CognitoIdentityProvider's admin_create_user seems to work fine, but when I attempt to log into our app with the new account I receive a 400 response with:

{"__type":"UserNotFoundException","message":"User does not exist."}

I have made sure that the user has in-fact been added to the cognito user pool and that the user is enabled.

I have also specified that the email address be verified automatically upon account creation.

Here is my account creation function:

import boto3

idp_client = boto3.client('cognito-idp')

# Redacted for stackoverflow example
user_pool_id = 'XXXXXXXXXXX'

response = idp_client.admin_create_user(
            UserPoolId=user_pool_id,
            Username=email,
            UserAttributes=[
                {
                    'Name': 'email',
                    'Value': email
                },{
                    'Name': 'email_verified',
                    'Value': 'true'
                }
            ],
            TemporaryPassword=generateSecureRandomString()
        )

I'd expect that as the account is successfully created in the Cognito user pool and that the account seems to be enabled and verified that this should result in an account that can sign-in.

Any light that can be shed on the problem would be greatly appreciated!


问:
CORS request error (react native / laravel passport)
I created a mobile app which consumes a back-end API.I am using fetch api on JS end to make my requests. However, I am getting a CORS error

```<code>Error message: Access to fetch at 'mydomain.com' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

I have tried the following:

A/ In my .htaccess

```<code> RewriteEngine On
 RewriteCond %{HTTPS} off
 RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]]
 <FilesMatch ".(ttf|otf|eot|woff)$">
 <IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin "*"
 Header set Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
 Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, token"
 Header set Access-Control-Allow-Credentials "true"
 </IfModule>
</code>```

This had the effect of at least letting my GET request to pass.

B/ in my index.php

```<code>header("Access-Control-Allow-Origin: *")
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
</code>```

Same effect as .htaccess, only GET request passes, with OPTIONS . I also saw the my Access-Control-Allow-Origin would be "*, null" and i would get an error stating that only one is allowed.

C. https://github.com/barryvdh/laravel-cors
In AuthServiceProvider, i tried both these. Only one at a time, not at the same time.

```<code>        Route::group([ 'middleware' => 'cors'], function() {
            Passport::routes();
        });

    Passport::routes(null, ['middleware' => [ \Barryvdh\Cors\HandleCors::class ]]);
</code>```

D. Created a custom middle with this code

```<code>    public function handle($request, Closure $next)
    {
                return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

</code>```

I dumped my $_SERVER and could not find the HTTP_ORIGIN, HTTP_REFERER. I did get my HTTP_REMOTE_ADDR

What is even more frustrating was that my app was working correctly, and I just suddenly started having the issue (back-end hosted on bluehost)

Edit: Sample request

```<code>var data = new FormData();

        data.append('grant_type', 'password');
        data.append('client_id', '2');
        data.append('client_secret', 'secret_token');
        data.append('scope', '*');

        data.append('username', 'mail');
        data.append('password', 'pwd');

        var link = (mydomain in https) + '/oauth/token';
        fetch(link, config)
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);

            })
            .catch(err => {
                console.log(err);
            })
</code>```

答:
Very weird but the issue I was having was with the config of my fetch

The initial one:

```<code>    const config = {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data;',
          'Authorization': 'Bearer ' + global.token,
        },
        body: data,
       }
</code>```

The corrected one

```<code>    const config = {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Content-Type': 'multipart/form-data;',
          'Authorization': 'Bearer ' + global.token,
        },
        body: data,
       }
</code>```

I just removed the 'Content-Type': 'multipart/form-data;',

Body:
I created a mobile app which consumes a back-end API.I am using fetch api on JS end to make my requests. However, I am getting a CORS error

Error message: Access to fetch at 'mydomain.com' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried the following:

A/ In my .htaccess

 RewriteEngine On
 RewriteCond %{HTTPS} off
 RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]]
 <FilesMatch ".(ttf|otf|eot|woff)$">
 <IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin "*"
 Header set Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
 Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, token"
 Header set Access-Control-Allow-Credentials "true"
 </IfModule>

This had the effect of at least letting my GET request to pass.

B/ in my index.php

header("Access-Control-Allow-Origin: *")
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

Same effect as .htaccess, only GET request passes, with OPTIONS . I also saw the my Access-Control-Allow-Origin would be "*, null" and i would get an error stating that only one is allowed.

C. https://github.com/barryvdh/laravel-cors
In AuthServiceProvider, i tried both these. Only one at a time, not at the same time.

        Route::group([ 'middleware' => 'cors'], function() {
            Passport::routes();
        });

    Passport::routes(null, ['middleware' => [ \Barryvdh\Cors\HandleCors::class ]]);

D. Created a custom middle with this code

    public function handle($request, Closure $next)
    {
                return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

I dumped my $_SERVER and could not find the HTTP_ORIGIN, HTTP_REFERER. I did get my HTTP_REMOTE_ADDR

What is even more frustrating was that my app was working correctly, and I just suddenly started having the issue (back-end hosted on bluehost)

Edit: Sample request

var data = new FormData();

        data.append('grant_type', 'password');
        data.append('client_id', '2');
        data.append('client_secret', 'secret_token');
        data.append('scope', '*');

        data.append('username', 'mail');
        data.append('password', 'pwd');

        var link = (mydomain in https) + '/oauth/token';
        fetch(link, config)
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);

            })
            .catch(err => {
                console.log(err);
            })

Body:
Very weird but the issue I was having was with the config of my fetch

The initial one:

    const config = {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data;',
          'Authorization': 'Bearer ' + global.token,
        },
        body: data,
       }

The corrected one

    const config = {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Content-Type': 'multipart/form-data;',
          'Authorization': 'Bearer ' + global.token,
        },
        body: data,
       }

I just removed the 'Content-Type': 'multipart/form-data;',


问:
F# XUnit test does not print output
I have the following XUnit test in a project created with dotnet new xunit:

```<code>type Scenarios(output : ITestOutputHelper) =

  [<Fact>]
  member __.``Output shows up`` () =
    output.WriteLine("I'm here")
</code>```

This approach seems to have worked before, but running the tests doesn't show any output, regardless of whether I use dotnet test or dotnet xunit:

```<code>> dotnet test
Build started, please wait...
Build completed.

Test run for C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll(.NETCoreApp,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 15.6.0-preview-20180109-01
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:00.4295013]   Discovering: StreamstoneFs.Tests
[xUnit.net 00:00:00.4750480]   Discovered:  StreamstoneFs.Tests
[xUnit.net 00:00:00.4792986]   Starting:    StreamstoneFs.Tests
[xUnit.net 00:00:00.5964013]   Finished:    StreamstoneFs.Tests

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.1835 Seconds

> dotnet xunit
Detecting target frameworks in StreamstoneFs.Tests.fsproj...
Building for framework netcoreapp2.0...
  StreamstoneFs -> C:\Work\OSS\Streamstone.fs\src\StreamstoneFs\bin\Debug\netstandard2.0\StreamstoneFs.dll
  StreamstoneFs.Tests -> C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll
Running .NET Core 2.0.0 tests for framework netcoreapp2.0...
xUnit.net Console Runner (64-bit .NET Core 4.6.00001.0)
  Discovering: StreamstoneFs.Tests
  Discovered:  StreamstoneFs.Tests
  Starting:    StreamstoneFs.Tests
  Finished:    StreamstoneFs.Tests
=== TEST EXECUTION SUMMARY ===
   StreamstoneFs.Tests  Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.109s
</code>```

What am I doing wrong here?

答:
I got output to appear without a failing test by using Console.SetOut

```<code>module StackOverflowTests

open System.IO
open System
open Xunit
open Xunit.Abstractions

type Converter(output: ITestOutputHelper) =
    inherit TextWriter()
    override __.Encoding = stdout.Encoding
    override __.WriteLine message =
        output.WriteLine message
    override __.Write message =
        output.WriteLine message

type StackOverflow(output : ITestOutputHelper) =
    do new Converter(output) |> Console.SetOut

    [<Fact>]
    member __.``Output shows up, for real`` () =
        output.WriteLine "ITestOutputHelper"
        printfn "printfn"
        printf "printf"
        Console.WriteLine("Console.WriteLine")
</code>```

Here's it working in Rider; it also works in Visual Studio 2019. I haven't tested it in VSCode/Ionide.

My answer combines this and this. I didn't have to do anything to xunit.diagnosticMessages.

Title: F# XUnit test does not print output

Body:
I have the following XUnit test in a project created with dotnet new xunit:

type Scenarios(output : ITestOutputHelper) =

  [<Fact>]
  member __.``Output shows up`` () =
    output.WriteLine("I'm here")

This approach seems to have worked before, but running the tests doesn't show any output, regardless of whether I use dotnet test or dotnet xunit:

> dotnet test
Build started, please wait...
Build completed.

Test run for C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll(.NETCoreApp,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 15.6.0-preview-20180109-01
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:00.4295013]   Discovering: StreamstoneFs.Tests
[xUnit.net 00:00:00.4750480]   Discovered:  StreamstoneFs.Tests
[xUnit.net 00:00:00.4792986]   Starting:    StreamstoneFs.Tests
[xUnit.net 00:00:00.5964013]   Finished:    StreamstoneFs.Tests

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.1835 Seconds

> dotnet xunit
Detecting target frameworks in StreamstoneFs.Tests.fsproj...
Building for framework netcoreapp2.0...
  StreamstoneFs -> C:\Work\OSS\Streamstone.fs\src\StreamstoneFs\bin\Debug\netstandard2.0\StreamstoneFs.dll
  StreamstoneFs.Tests -> C:\Work\OSS\Streamstone.fs\tests\StreamstoneFs.Tests\bin\Debug\netcoreapp2.0\StreamstoneFs.Tests.dll
Running .NET Core 2.0.0 tests for framework netcoreapp2.0...
xUnit.net Console Runner (64-bit .NET Core 4.6.00001.0)
  Discovering: StreamstoneFs.Tests
  Discovered:  StreamstoneFs.Tests
  Starting:    StreamstoneFs.Tests
  Finished:    StreamstoneFs.Tests
=== TEST EXECUTION SUMMARY ===
   StreamstoneFs.Tests  Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.109s

What am I doing wrong here?

Body:
I got output to appear without a failing test by using Console.SetOut

module StackOverflowTests

open System.IO
open System
open Xunit
open Xunit.Abstractions

type Converter(output: ITestOutputHelper) =
    inherit TextWriter()
    override __.Encoding = stdout.Encoding
    override __.WriteLine message =
        output.WriteLine message
    override __.Write message =
        output.WriteLine message

type StackOverflow(output : ITestOutputHelper) =
    do new Converter(output) |> Console.SetOut

    [<Fact>]
    member __.``Output shows up, for real`` () =
        output.WriteLine "ITestOutputHelper"
        printfn "printfn"
        printf "printf"
        Console.WriteLine("Console.WriteLine")

Here's it working in Rider; it also works in Visual Studio 2019. I haven't tested it in VSCode/Ionide.

My answer combines this and this. I didn't have to do anything to xunit.diagnosticMessages.


问:
How to change name of file in javascript from input=File
I need to change the filename (not the file, just the metadata of the name) when uploading to a sharepoint site.

I figured that it would be easy enough to change the html attribute in javascript rather than playing with Sharepoint backend. So that when I upload a file it changes the name of the file (not the data)

something like this:

```<code>function PreSaveAction(){
   var file = document.GetElementById('fileupload1');
   file.files[0].name='ChangedName.tmp'

return true;
}
</code>```

Is this impossible due to the nature of the locked input='file' attributes?

答:
A simpler and more memory efficient approach - change the file's 'name' property to writeable:

```<code>Object.defineProperty(fileToAmend, 'name', {
  writable: true,
  value: updatedFileName
});
</code>```

Where fileToAmend is the File and updatedFileName is the new filename.

Method from
Cannot assign to read only property 'name' of object '[object Object]'

Body:
I need to change the filename (not the file, just the metadata of the name) when uploading to a sharepoint site.

I figured that it would be easy enough to change the html attribute in javascript rather than playing with Sharepoint backend. So that when I upload a file it changes the name of the file (not the data)

something like this:

function PreSaveAction(){
   var file = document.GetElementById('fileupload1');
   file.files[0].name='ChangedName.tmp'

return true;
}

Is this impossible due to the nature of the locked input='file' attributes?

Body:
A simpler and more memory efficient approach - change the file's 'name' property to writeable:

Object.defineProperty(fileToAmend, 'name', {
  writable: true,
  value: updatedFileName
});

Where fileToAmend is the File and updatedFileName is the new filename.

Method from
Cannot assign to read only property 'name' of object '[object Object]'