问:
Does AWS request signing hide the access key?
If I sign a request to the AWS API and I then forward this request to a client to have it execute the request, can the client (given the request) reverse engineer the access key that was used?

In other words, if I sign a request with my access key, can I safely have someone else execute that request for me, without them knowing the access key?

And can the client see the request contents that are being fired?

答:
The access key technically  is not a secret.

For example, it is stored as a plain text in any pre-sign s3 url that you give out to people or post on your website:

```<code>https://<bucket-name>.s3.amazonaws.com/test.txt?AWSAccessKeyId=AKIA4CHRFYIMJSLJKLHO&Signature=cD47pThlUZ%2BUmfkA0DLAEf%2BxiyU%3D&Expires=1591143311
</code>```

What's more, you access key is always in plain text when you do requests to AWS. The request has the form shown below, where access key ID is in plain text:

```<code>Authorization: algorithm Credential=access key ID/credential scope, SignedHeaders=SignedHeaders, Signature=signature
</code>```

Think about access key and secret access key as username and password. Username can be publicly know, but password not. Thus if someone gets an access key from the signed url there is no major issue, because its not secret as AWS openly stores it in plain text in the urls.

Having said that, its still recommended not to give it away for no reason. Thus instead of using your access key in plain text from your admin account in your pre-sign S3 urls or signed requests, you can create a temporary IAM user with just enough credentials to perform the actions needed. This is line with a good practice of Grant Least Privilege.

Body:
The access key technically  is not a secret.

For example, it is stored as a plain text in any pre-sign s3 url that you give out to people or post on your website:

https://<bucket-name>.s3.amazonaws.com/test.txt?AWSAccessKeyId=AKIA4CHRFYIMJSLJKLHO&Signature=cD47pThlUZ%2BUmfkA0DLAEf%2BxiyU%3D&Expires=1591143311

What's more, you access key is always in plain text when you do requests to AWS. The request has the form shown below, where access key ID is in plain text:

Authorization: algorithm Credential=access key ID/credential scope, SignedHeaders=SignedHeaders, Signature=signature

Think about access key and secret access key as username and password. Username can be publicly know, but password not. Thus if someone gets an access key from the signed url there is no major issue, because its not secret as AWS openly stores it in plain text in the urls.

Having said that, its still recommended not to give it away for no reason. Thus instead of using your access key in plain text from your admin account in your pre-sign S3 urls or signed requests, you can create a temporary IAM user with just enough credentials to perform the actions needed. This is line with a good practice of Grant Least Privilege.


来源: stackexchange

问:
Sum up the elements of a record
```<code>type MyType = {a:int; b:int};;
let test = [{a=5;b=10}; {a=10;b=100}; {a=200; b=500}; {a=100; b=2}];;
</code>```

I would like to create a function which will sum up a and b in such a way it will display

```<code>Sum of a : 315
Sum of b : 612
</code>```

I think I have to use a recursive function. Here is my attempt :

```<code>let my_func record =
  let adds = [] in
  let rec add_func = match adds with
  | [] -> record.a::adds; record.b::adds
  | _ -> s + add_func(e::r)

add_func test;;
</code>```

This function doesn't seem to work at all. Is there a right way to do such function?

答:
OK, you know exactly what you're doing, you just need one suggestion I think.

Assume your function is named sumab and returns a pair of ints. Then the key expression in your recursive function will be something like this:

```<code>| { a = ha; b = hb; } :: t ->
    let (a, b) = sumab t in (ha + a, hb + b)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sum up the elements of a record

Body:
type MyType = {a:int; b:int};;
let test = [{a=5;b=10}; {a=10;b=100}; {a=200; b=500}; {a=100; b=2}];;

I would like to create a function which will sum up a and b in such a way it will display

Sum of a : 315
Sum of b : 612

I think I have to use a recursive function. Here is my attempt :

let my_func record =
  let adds = [] in
  let rec add_func = match adds with
  | [] -> record.a::adds; record.b::adds
  | _ -> s + add_func(e::r)

add_func test;;

This function doesn't seem to work at all. Is there a right way to do such function?

Body:
OK, you know exactly what you're doing, you just need one suggestion I think.

Assume your function is named sumab and returns a pair of ints. Then the key expression in your recursive function will be something like this:

| { a = ha; b = hb; } :: t ->
    let (a, b) = sumab t in (ha + a, hb + b)


问:
Remove first line from txt file using python3
So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it?
or even better, how can i print directly to the first line?

```<code>file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)
</code>```

答:
This will output your ping to the top of a text file: </p>

```<code>import io, subprocess

ping = subprocess.Popen(["ping", "-n", "3","127.0.0.1"], stdout=subprocess.PIPE)

with open('ping.txt', 'r+') as output:
   data = output.read()
   for line in ping.stdout.readlines():
      data += str(line.decode())
   ping.stdout.close()
   output.seek(0)
   output.write(data.lstrip())
   output.truncate()
</code>```

Body:
So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it?
or even better, how can i print directly to the first line?

file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)

Body:
This will output your ping to the top of a text file:

import io, subprocess

ping = subprocess.Popen(["ping", "-n", "3","127.0.0.1"], stdout=subprocess.PIPE)

with open('ping.txt', 'r+') as output:
   data = output.read()
   for line in ping.stdout.readlines():
      data += str(line.decode())
   ping.stdout.close()
   output.seek(0)
   output.write(data.lstrip())
   output.truncate()


问:
Add a color bar in imported figure (Python)
I have a figure in a grayscale. I would like to know how to add a color bar in such imported figure, using Python. I know how to plot a 2D array and add a color bar, but I can not figure out how to do a similar task for an imported figure. I also would like to preserve the size of the original image. I import the figure with

```<code>from PIL import Image
im= Image.open("gray.png")
</code>```

Thanks in advance.

`

答:
```<code>from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt

def display_image_in_actual_size(im_path):

    dpi = 80
    im_data = plt.imread(im_path)
    height, width, depth = im_data.shape
    # What size does the figure need to be in inches to fit the image?
    figsize = width / float(dpi), height / float(dpi)

    # Create a figure of the right size with one axes that takes up the full figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([0, 0, 1, 1])

    #ax.axis('off') #  uncommenting this will result  a plot without axis !
    # configures size of colorbar
    divider = make_axes_locatable(ax)
    im=plt.imshow(im_data)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)

    ax.imshow(im_data, cmap='gray')
    ax.set(xlim=[-10, width - 0.5], ylim=[height - 0.5, -0.5], aspect=1)

    plt.savefig('last_image.png')    #saving new image
    plt.show()

display_image_in_actual_size("gray.png")
</code>```

I have adapted some portions  of answer from here

Body:
I have a figure in a grayscale. I would like to know how to add a color bar in such imported figure, using Python. I know how to plot a 2D array and add a color bar, but I can not figure out how to do a similar task for an imported figure. I also would like to preserve the size of the original image. I import the figure with

from PIL import Image
im= Image.open("gray.png")

Thanks in advance.

`

Body:
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt

def display_image_in_actual_size(im_path):

    dpi = 80
    im_data = plt.imread(im_path)
    height, width, depth = im_data.shape
    # What size does the figure need to be in inches to fit the image?
    figsize = width / float(dpi), height / float(dpi)

    # Create a figure of the right size with one axes that takes up the full figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([0, 0, 1, 1])

    #ax.axis('off') #  uncommenting this will result  a plot without axis !
    # configures size of colorbar
    divider = make_axes_locatable(ax)
    im=plt.imshow(im_data)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)

    ax.imshow(im_data, cmap='gray')
    ax.set(xlim=[-10, width - 0.5], ylim=[height - 0.5, -0.5], aspect=1)

    plt.savefig('last_image.png')    #saving new image
    plt.show()

display_image_in_actual_size("gray.png")

I have adapted some portions  of answer from here


问:
permutation calculation runtime complexity with some changes
I have a question about the runtime complexity of the standard permutation finding algorithm. Consider a list A, find (and print) all permutations of its elements.

Here's my recursive implementation, where printperm() prints every permutation:

```<code>def printperm(A, p):
    if len(A) == len(p):
        print("".join(p))
        return

    for i in range(0, len(A)):
        if A[i] != 0:
            tmp = A[i] # remember ith position
            A[i] = 0 # mark character i as used
            p.append(tmp) # select character i for this permutation
            printperm(A, p) # Solve subproblem, which is smaller because we marked a character in this subproblem as smaller
            p.pop() # done with selecting character i for this permutation
            A[i] = tmp # restore character i in preparation for selecting the next available character

printperm(['a', 'b', 'c', 'd'], [])
</code>```

The runtime complexity appears to be O(n!) where n is the size of A. This is because at each recursion level, the amount of work decreases by 1. So, the top recursion level is n amount of work, the next level is n-1, and the next level is n-2, and so on. So the total complexity is n*(n-1)*(n-2)...=n!

Now the problem is the print("".join(p)) statement. Every time this line runs, it iterates through the list, which iterates through the entire list, which is complexity n. There are n! number of permutations of a list of size n. So that means the amount of work done by the print("".join(p)) statement is n!*n.

Does the presence of the print("".join(p)) statement then increases the runtime complexity to O(n * n!)?? But this doesn't seem right, because I'm not running the print statement on every recursion call. Where does my logic for getting O(n * n!) break down?

答:
Permutations can be generated from combinations using divide and conquer technique to achieve better time complexity. However, generated output is not in order.

Suppose we want to generate permutations for n=8 {0,1,2,3,4,5,6,7}.
Below are instances of permutations
       01234567
       01234576
       03215654
       30126754
Note first 4 items in each arrangement are of same set {0,1,2,3} and last 4 items are of same set {4,5,6,7}
This means given set A={0,1,2,3} B={4,5,6,7} permutations from A are 4! and from B are 4!.

It follows that taking one instance of permutations from A and one instance of permutations from B we get a correct permutation instance from universal set {0,1,2,3,4,5,6,7}.

Total permutations given sets A and B such that A union B and A equals universal set and B intersection is null set gives universal set are 2*A!*B!  (By swapping A and B order
In this case we get 2*4!*4! = 1156.

So to generate all permutations when n=8, we simply need to generate possible combinations of sets A and B that satisfy conditions explained earlier.
Generating combinations of 8 elements taking 4 at time in lexicographical order is pretty fast. We need to generate the first half combinations each assign to respective set A and set B is found using set operation.
For each pair A and B we apply divide and conquer algorithm.

A and B doesn't need to be of equal sizes and the trick can be applied recursive for higher values of n.

In stead of using 8!  = 40320 steps
We can use 8!/(2*4!4!)(4!+4!+1) = 1750 steps with this method. I ignore the cross product operation when joining set A and set B permutations because its straight forward operation.

In real implementation this method runs approximately 20 times faster than some naive algorithm and can take advantage of parallelism. For example different pairs of set A and B can be grouped and process on different threads.

Body:
I have a question about the runtime complexity of the standard permutation finding algorithm. Consider a list A, find (and print) all permutations of its elements.

Here's my recursive implementation, where printperm() prints every permutation:

def printperm(A, p):
    if len(A) == len(p):
        print("".join(p))
        return

    for i in range(0, len(A)):
        if A[i] != 0:
            tmp = A[i] # remember ith position
            A[i] = 0 # mark character i as used
            p.append(tmp) # select character i for this permutation
            printperm(A, p) # Solve subproblem, which is smaller because we marked a character in this subproblem as smaller
            p.pop() # done with selecting character i for this permutation
            A[i] = tmp # restore character i in preparation for selecting the next available character

printperm(['a', 'b', 'c', 'd'], [])

The runtime complexity appears to be O(n!) where n is the size of A. This is because at each recursion level, the amount of work decreases by 1. So, the top recursion level is n amount of work, the next level is n-1, and the next level is n-2, and so on. So the total complexity is n*(n-1)*(n-2)...=n!

Now the problem is the print("".join(p)) statement. Every time this line runs, it iterates through the list, which iterates through the entire list, which is complexity n. There are n! number of permutations of a list of size n. So that means the amount of work done by the print("".join(p)) statement is n!*n.

Does the presence of the print("".join(p)) statement then increases the runtime complexity to O(n * n!)?? But this doesn't seem right, because I'm not running the print statement on every recursion call. Where does my logic for getting O(n * n!) break down?


问:
Java for( x : y) execution
I have the following for loop:

```<code>for(String s : someString.split("\\s+")){
   //do something
}
</code>```

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?

答:
It only does it once, and uses that array and interates through it.

Edit: from Mat This is the reference

ContentLicense: CC BY-SA 3.0

Title: Java for( x : y) execution

Body:
I have the following for loop:

for(String s : someString.split("\\s+")){
   //do something
}

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?


问:
Xamarin Forms Listview - Using custom view cell for each item in items source
I am not sure if this is possible or if there are any recommended ways to achieve this. Essentially, I'm trying to have a list view with "jagged" or differing view cells foreach cell in the list view. As a super simple example, I am trying to dynamically display a button, label, and entry each in their own row of the list view. Here is my code:

XAML

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Chaser.Views.Admin_Detail_MasterDetail_View">
    <ContentPage.Content>
        <StackLayout Orientation="Vertical"
                     Spacing="15"
                     Margin="10">
            <Label Text="{Binding ViewTitle, Mode=OneWay}"
                   FontSize="Large"
                   TextColor="Red"
                   FontAttributes="Bold" />
            <ListView ItemsSource="{Binding ItemViews, Mode=OneWay}"
                      SelectionMode="None"
                      PropertyChanged="ListView_PropertyChanged">
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
</code>```

Codebehind

```<code>public Admin_Detail_MasterDetail_View()
    {
        InitializeComponent();
        DetailViewContext = new Models.Detail_MasterDetail_Model();
        DetailViewContext.ViewTitle = "Info";

        DetailViewContext.ItemViews = new List<ViewCell>
        {
            new ViewCell
            {
                View = new Button
                {
                    Text = "TestButton"
                },
            },

            new ViewCell
            {
                View = new Label
                {
                    Text = "TestLabel"
                }
            },

            new ViewCell
            {
                View = new Entry
                {
                    Placeholder = "TestEntry"
                }
            }
        };

        BindingContext = DetailViewContext;
    }
</code>```

Note: This was also tried with adding stack layouts to the views then adding the individual items to the stack layouts, either way I get the following:

If possible, I would like to have command bindings on a per cellview basis as one type of cell may have differing context menu actions than another.

In the end the view cells will be much more complicated than a simple button or label, but this is for conceptual purposes to see if something like this is possible/recommended.

After some brief research I see there is a data template selector we can create, however, I am not sure if it would apply in this scenario. At the very least, I am not sure if it would allow for custom context menu actions on a per cell basis.

Thank you for any input on this!

答:
After a so much Research i created below code Listview with Test data.

just copy and paste the code and check the result.

```<code>        <ListView HasUnevenRows="true"
                  RowHeight="200">
            <ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>Item One</x:String>
                    <x:String>Item Two</x:String>
                    <x:String>Item Three</x:String>
                    <x:String>Item Four</x:String>
                    <x:String>Item Five</x:String>
                </x:Array>
            </ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame BorderColor="Red" Padding="0">
                            <Grid Margin="10">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="90" />
                                    <RowDefinition Height="90"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>

                                <BoxView Grid.Row="0"
                                         Grid.Column="0"
                                         Color="Yellow" />
                                <BoxView Grid.Row="0"
                                         Grid.Column="1"
                                         Color="Black" />
                                <BoxView Grid.Row="1"
                                         Grid.Column="0"
                                         Color="Green" />
                                <BoxView Grid.Row="1"
                                         Grid.Column="1"
                                         Color="Blue" />
                                <Label Text="{Binding}"
                                       FontAttributes="Bold"
                                       TextColor="Red"
                                       HorizontalOptions="CenterAndExpand"
                                       VerticalOptions="CenterAndExpand"/>
                            </Grid>
                        </Frame>
                </ViewCell>
              </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

Body:
I am not sure if this is possible or if there are any recommended ways to achieve this. Essentially, I'm trying to have a list view with "jagged" or differing view cells foreach cell in the list view. As a super simple example, I am trying to dynamically display a button, label, and entry each in their own row of the list view. Here is my code:

XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Chaser.Views.Admin_Detail_MasterDetail_View">
    <ContentPage.Content>
        <StackLayout Orientation="Vertical"
                     Spacing="15"
                     Margin="10">

            <ListView ItemsSource="{Binding ItemViews, Mode=OneWay}"
                      SelectionMode="None"
                      PropertyChanged="ListView_PropertyChanged">
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Codebehind

public Admin_Detail_MasterDetail_View()
    {
        InitializeComponent();
        DetailViewContext = new Models.Detail_MasterDetail_Model();
        DetailViewContext.ViewTitle = "Info";

        DetailViewContext.ItemViews = new List<ViewCell>
        {
            new ViewCell
            {
                View = new Button
                {
                    Text = "TestButton"
                },
            },

            new ViewCell
            {
                View = new Label
                {
                    Text = "TestLabel"
                }
            },

            new ViewCell
            {
                View = new Entry
                {
                    Placeholder = "TestEntry"
                }
            }
        };

        BindingContext = DetailViewContext;
    }

Note: This was also tried with adding stack layouts to the views then adding the individual items to the stack layouts, either way I get the following:

If possible, I would like to have command bindings on a per cellview basis as one type of cell may have differing context menu actions than another.

In the end the view cells will be much more complicated than a simple button or label, but this is for conceptual purposes to see if something like this is possible/recommended.

After some brief research I see there is a data template selector we can create, however, I am not sure if it would apply in this scenario. At the very least, I am not sure if it would allow for custom context menu actions on a per cell basis.

Thank you for any input on this!

Body:
After a so much Research i created below code Listview with Test data.

just copy and paste the code and check the result.

        <ListView HasUnevenRows="true"
                  RowHeight="200">
            <ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>Item One</x:String>
                    <x:String>Item Two</x:String>
                    <x:String>Item Three</x:String>
                    <x:String>Item Four</x:String>
                    <x:String>Item Five</x:String>
                </x:Array>
            </ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame BorderColor="Red" Padding="0">
                            <Grid Margin="10">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="90" />
                                    <RowDefinition Height="90"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>

                                <BoxView Grid.Row="0"
                                         Grid.Column="0"
                                         Color="Yellow" />
                                <BoxView Grid.Row="0"
                                         Grid.Column="1"
                                         Color="Black" />
                                <BoxView Grid.Row="1"
                                         Grid.Column="0"
                                         Color="Green" />
                                <BoxView Grid.Row="1"
                                         Grid.Column="1"
                                         Color="Blue" />
                                <Label Text="{Binding}"
                                       FontAttributes="Bold"
                                       TextColor="Red"
                                       HorizontalOptions="CenterAndExpand"
                                       VerticalOptions="CenterAndExpand"/>
                            </Grid>
                        </Frame>
                </ViewCell>
              </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>


问:
Set two different python versions with pyenv with different names?
Is it possible to set two different python versions for different names using pyenv? E.g. I want the python3 refer to version 3.7.4 but python refer to version 2 of python defined by system which is 2.7.12 so there will not be any conflicts and issues.

Currently I just can set version globally using pyenv global 3.7.4 which cause both python and python3 be version 3.7.4.

答:
Pyenv allows you to use different versions of Python at once using "advanced" mode

Example from documentation:

```<code>$ pyenv local 2.7.6 3.3.3
$ pyenv versions
  system
* 2.7.6 (set by /Users/yyuu/path/to/project/.python-version)
* 3.3.3 (set by /Users/yyuu/path/to/project/.python-version)
$ python --version
Python 2.7.6
$ python2.7 --version
Python 2.7.6
$ python3.3 --version
Python 3.3.3
</code>```

For more information, please look at:
https://github.com/pyenv/pyenv/blob/master/COMMANDS.md#pyenv-local-advanced

Body:
Pyenv allows you to use different versions of Python at once using "advanced" mode

Example from documentation:

$ pyenv local 2.7.6 3.3.3
$ pyenv versions
  system
* 2.7.6 (set by /Users/yyuu/path/to/project/.python-version)
* 3.3.3 (set by /Users/yyuu/path/to/project/.python-version)
$ python --version
Python 2.7.6
$ python2.7 --version
Python 2.7.6
$ python3.3 --version
Python 3.3.3

For more information, please look at:
https://github.com/pyenv/pyenv/blob/master/COMMANDS.md#pyenv-local-advanced


问:
How to initialize Directwrite IDWriteTextLayout properly in a Direct2D window
I'm trying to write text to my ID2D1HwndRenderTarget* renderTarget-window using Directwrite. That works good and text appears where it should. But i have the feeling i'm doing something wrong in Graphics::DrawMyText. I think I should create my IDWriteTextLayout* textLayout also in the Graphics::Initialisation but if I do that, i cannot alter the text const wchar_t* wszText anymore. At least, I did not find any helper function in IDWriteTextLayout interface

So is it correct to create and release my IDWriteTextLayout all the time, or is there a way I only have to create it once like the other interfaces?

#include<dwrite.h>

class Graphics
{
    IDWriteFactory* writeFactory;
    IDWriteTextLayout* textLayout;
    IDWriteTextFormat* textFormat;
}

Graphics() // constructor
{
    writeFactory = NULL;
    textLayout = NULL;
    textFormat = NULL;
}

Graphics::~Graphics() // destructor
{
    if (writeFactory) writeFactory->Release();
    if (textLayout) textLayout->Release();
    if (textFormat) textFormat->Release();
}

bool Graphics::Initialise(HWND windowsHandle)
{
    res = writeFactory->CreateTextFormat(
    L"Lucida Console",
    NULL,
    DWRITE_FONT_WEIGHT_REGULAR,
    DWRITE_FONT_STYLE_NORMAL,
    DWRITE_FONT_STRETCH_NORMAL,
    10.0f,
    L"en-us",
    &textFormat
    );
    if (res != S_OK) return false;

    return true;
}

void Graphics::DrawMyText(const wchar_t* wszText, float x, float y, float boxWidth,
                          float boxHeight, float r, float g, float b, float a)
{
    writeFactory->CreateTextLayout(wszText, (UINT32)wcslen(wszText), textFormat,
                                   boxWidth, boxHeight, &textLayout);
    brush->SetColor(D2D1::ColorF(r, g, b, a));
    renderTarget->DrawTextLayout(D2D1::Point2F(x, y), textLayout, brush);
    textLayout->Release(); // don't forget this one to prevent memory leaks
}
```

答: The text of a DWrite layout is indeed fixed, your choices are either to create (and release) layout objects or go the much harder route of using IDWriteTextAnalyzer (along with IDWriteTextAnalysisSource/IDWriteTextAnalysisSink). It would have been nice if the text of a layout were mutable but MS simply didn't make that choice.</p>


问:
Keeping track of refreshes in Crystal Reports 2008
I am curious to know if there is a way to tell if a report has been printed or ran. For example, the user enters in a inspectionnumber and hits apply and then clicks print and then prints the report. Can i know if the report has been printed? is there a way to use local variables to track that, some sort of loop?</p>

答:
I've never tested this, but here's a theory you can try.

In your Database Expert, go to your Current Connections and Add Command.  Use this to write up a SQL query to save the usage data to a table in your data source  (If your data source is read only, just add a delimited text file as an additional data source and output your usage data to that instead.)

The best example I have of this is @ http://www.scribd.com/doc/2190438/20-Secrets-of-Crystal-Reports. On page 39, you'll see a method for creating a table of contents that more or less uses this method.


问:
MATLAB named colormap with custom number of elements
If I call colormap('jet'), I will get a 256-by-3 matrix with the colors of jet. If I do jet(1000), I can get a much more densely sampled equivalent. I happen to need the more densely sampled colormaps, but for arbitrary named colormaps. How can I get a colormap with a variable number of elements by name.

I have considered something like eval(sprintf('%s(%d)', name, num)), where e.g. name = 'parula' and num = 1000, but that carries all the problems inherent with eval, and I would like to avoid using it, as I am sure there is a way to access colormap functions by name.

To avoid an X-Y problem, here is my background info:

I am trying to apply gamma-correction to an indexed image. I can not map ranges outside [0, 1] using imadjust. Also, I would like to display a colorbar with the image that maps to correct values. To that end, I am adjusting the colormap by resampling a higher-density version of it to the desired range with the inverted gamma function:

```<code>function imdisp(img, cmap, gamma)

density = 1000;  % not really a good name, but w/e

x = linspace(0, 1, 10 * density);
y = x.^(1 / gamma);
z = linspace(0, 1, density);
ind = round(interp1(y, x, z, 'nearest', 'extrap') * (10 * density - 1)  + 1);

% this is the problem line
colors = eval(sprintf('%s(%d)', cmap, 10 * density));

colors = colors(ind);
imshow(img, []);
colormap(colors);
colorbar();

end
</code>```

If there is a better way to do this entirely, please feel free to post that instead of a direct answer.

答:
This is what feval is for:

```<code>colors = feval(cmap, 10 * density);
</code>```

feval is not as dangerous as eval, because it doesn't execute arbitrary code, but it can execute an arbitrary function and therefore should still be used carefully. It also doesn't allow the JIT to know ahead of time what function will be called, so there's an additional overhead. On the other hand, you don't need to create a string for the arguments that then has to be parsed again.

Consider instead accepting a function handle into your function: call it as imdisp(img, @jet, gamma). Now your cmap variable is a function that you can call: cmap(10 * density).

Body:
If I call colormap('jet'), I will get a 256-by-3 matrix with the colors of jet. If I do jet(1000), I can get a much more densely sampled equivalent. I happen to need the more densely sampled colormaps, but for arbitrary named colormaps. How can I get a colormap with a variable number of elements by name.

I have considered something like eval(sprintf('%s(%d)', name, num)), where e.g. name = 'parula' and num = 1000, but that carries all the problems inherent with eval, and I would like to avoid using it, as I am sure there is a way to access colormap functions by name.

To avoid an X-Y problem, here is my background info:

I am trying to apply gamma-correction to an indexed image. I can not map ranges outside [0, 1] using imadjust. Also, I would like to display a colorbar with the image that maps to correct values. To that end, I am adjusting the colormap by resampling a higher-density version of it to the desired range with the inverted gamma function:

function imdisp(img, cmap, gamma)

density = 1000;  % not really a good name, but w/e

x = linspace(0, 1, 10 * density);
y = x.^(1 / gamma);
z = linspace(0, 1, density);
ind = round(interp1(y, x, z, 'nearest', 'extrap') * (10 * density - 1)  + 1);

% this is the problem line
colors = eval(sprintf('%s(%d)', cmap, 10 * density));

colors = colors(ind);
imshow(img, []);
colormap(colors);
colorbar();

end

If there is a better way to do this entirely, please feel free to post that instead of a direct answer.

Body:
This is what feval is for:

colors = feval(cmap, 10 * density);

feval is not as dangerous as eval, because it doesn't execute arbitrary code, but it can execute an arbitrary function and therefore should still be used carefully. It also doesn't allow the JIT to know ahead of time what function will be called, so there's an additional overhead. On the other hand, you don't need to create a string for the arguments that then has to be parsed again.

Consider instead accepting a function handle into your function: call it as imdisp(img, @jet, gamma). Now your cmap variable is a function that you can call: cmap(10 * density).


问:
How to sort tuple with python by using specific rules
I have this tuple:

```<code>[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]
</code>```

I would like to classify it in this order:

```<code>site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02
</code>```

To have: [('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]

574 idea is to first classify the NFV part in ascending order ,after that, we classify the SWSTO in increasing order too but by putting the SWSTO which ends with 'V' first

How can I do that?

答:
I found it way clearer to make a standalone keying function:

```<code>#!/usr/bin/env python

lst = [
    ("site-nfv01-swsto01",),
    ("site-nfv01-swsto01V",),
    ("site-nfv01-swsto02",),
    ("site-nfv02-swsto02",),
    ("site-nfv02-swsto01",),
    ("site-nfv02-swsto01V",),
]

def my_key(item):
    """Return a tuple that can be used for ordering the item."""

    first, middle, last = item[0].split("-")

    # For the middle part, what we really care about is the int after the "nfv" string.
    middle_int = int(middle[3:])

    # For the last part, we mostly care about the int after the "swsto" string...
    last_value = last[5:]

    # ...but not quite. Let's make sure that items with a trailing "V" sort lower than ones without
    # a "V".
    if last_value.endswith("V"):
        last_tuple = int(last_value[:-1]), "V"
    else:
        last_tuple = int(last_value), "z"

    # Python sorts tuples one component at a time, so return a tuple that can be compared against
    # the tuples generated for other values.
    return first, middle_int, last_tuple

# For demonstration purposes, show the sorting key generated for each item in the list.
for item in lst:
    print(item, my_key(item))

# Use that sorting key to actually sort the list.
print(sorted(lst, key=my_key))
</code>```

This lets you be super explicit about how the sorting key is generated, as is vastly easier to test.

Body:
I have this tuple:

[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]

I would like to classify it in this order:

site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02

To have: [('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]

574 idea is to first classify the NFV part in ascending order ,after that, we classify the SWSTO in increasing order too but by putting the SWSTO which ends with 'V' first

How can I do that?

Body:
I found it way clearer to make a standalone keying function:

#!/usr/bin/env python

lst = [
    ("site-nfv01-swsto01",),
    ("site-nfv01-swsto01V",),
    ("site-nfv01-swsto02",),
    ("site-nfv02-swsto02",),
    ("site-nfv02-swsto01",),
    ("site-nfv02-swsto01V",),
]

def my_key(item):
    """Return a tuple that can be used for ordering the item."""

    first, middle, last = item[0].split("-")

    # For the middle part, what we really care about is the int after the "nfv" string.
    middle_int = int(middle[3:])

    # For the last part, we mostly care about the int after the "swsto" string...
    last_value = last[5:]

    # ...but not quite. Let's make sure that items with a trailing "V" sort lower than ones without
    # a "V".
    if last_value.endswith("V"):
        last_tuple = int(last_value[:-1]), "V"
    else:
        last_tuple = int(last_value), "z"

    # Python sorts tuples one component at a time, so return a tuple that can be compared against
    # the tuples generated for other values.
    return first, middle_int, last_tuple

# For demonstration purposes, show the sorting key generated for each item in the list.
for item in lst:
    print(item, my_key(item))

# Use that sorting key to actually sort the list.
print(sorted(lst, key=my_key))

This lets you be super explicit about how the sorting key is generated, as is vastly easier to test.


问:
Using SQLDF to select specific values from a column
SQLDF newbie here.

I have a data frame which has about 15,000 rows and 1 column.
The data looks like:

```<code>cars
autocar
carsinfo
whatisthat
donnadrive
car
telephone
...
</code>```

I wanted to use the package sqldf to loop through the column and
pick all values which contain "car" anywhere in their value.
However, the following code generates an error.

```<code>> sqldf("SELECT Keyword FROM dat WHERE Keyword="car")
Error: unexpected symbol in "sqldf("SELECT Keyword FROM dat WHERE Keyword="car"
</code>```

There is no unexpected symbol, so I'm not sure whats wrong.

so first, I want to know all the values which contain 'car'.
then I want to know only those values which contain just 'car' by itself.

Can anyone help.

EDIT:

allright, there was an unexpected symbol, but it only gives me just car and not every
row which contains 'car'.

```<code>> sqldf("SELECT Keyword FROM dat WHERE Keyword='car'")
  Keyword
1     car
</code>```

答:
Using = will only return exact matches.

You should probably use the like operator combined with the wildcards % or _.  The % wildcard will match multiple characters, while _ matches a single character.

Something like the following will find all instances of car, e.g. "cars", "motorcar", etc:

```<code>sqldf("SELECT Keyword FROM dat WHERE Keyword like '%car%'")
</code>```

And the following will match "car" or "cars":

```<code>sqldf("SELECT Keyword FROM dat WHERE Keyword like 'car_'")
</code>```

Body:
SQLDF newbie here.

I have a data frame which has about 15,000 rows and 1 column.
The data looks like:

cars
autocar
carsinfo
whatisthat
donnadrive
car
telephone
...

I wanted to use the package sqldf to loop through the column and
pick all values which contain "car" anywhere in their value.
However, the following code generates an error.

> sqldf("SELECT Keyword FROM dat WHERE Keyword="car")
Error: unexpected symbol in "sqldf("SELECT Keyword FROM dat WHERE Keyword="car"

There is no unexpected symbol, so I'm not sure whats wrong.

so first, I want to know all the values which contain 'car'.
then I want to know only those values which contain just 'car' by itself.

Can anyone help.

EDIT:

allright, there was an unexpected symbol, but it only gives me just car and not every
row which contains 'car'.

> sqldf("SELECT Keyword FROM dat WHERE Keyword='car'")
  Keyword
1     car

Body:
Using = will only return exact matches.

You should probably use the like operator combined with the wildcards % or _.  The % wildcard will match multiple characters, while _ matches a single character.

Something like the following will find all instances of car, e.g. "cars", "motorcar", etc:

sqldf("SELECT Keyword FROM dat WHERE Keyword like '%car%'")

And the following will match "car" or "cars":

sqldf("SELECT Keyword FROM dat WHERE Keyword like 'car_'")


问:
string representation of dictionary without quotes in values
I am trying to create a string that can be evaluated to a dictionary such as:

```<code>'{"key1": val1, "key2": val2}'
</code>```

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})
```

This mostly works except instead of val1 I get 'val1'. I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.

答:
You could use eval() if this is what you are after:

val1 = "one"
val2 = "two"
test = '{"key1": val1, "key2": val2}'
test_dict = eval(test)
print(test_dict)
# {'key1': 'one', 'key2': 'two'}
```

Body:
I am trying to create a string that can be evaluated to a dictionary such as:

'{"key1": val1, "key2": val2}'

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})

This mostly works except instead of val1 I get 'val1'. I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.


问:
Ansible with_sequence output format 01 instead of 1
I have the following Ansible code:

- set_fact:
    newvms: "{{ (newvms | default([])) + [ item ] }}"
  with_sequence: "start=1 count=3 format=%d"
```

What I get with the above code: 1, 2 ,3

What I want to get: 01, 02, 03

Is this possible?
Appreciate the input!

J

答:
Use Python printf-style formatting

    %02d
```

Body:
I have the following Ansible code:

- set_fact:
    newvms: "{{ (newvms | default([])) + [ item ] }}"
  with_sequence: "start=1 count=3 format=%d"

What I get with the above code: 1, 2 ,3

What I want to get: 01, 02, 03

Is this possible?
Appreciate the input!

J

Body:
Use Python printf-style formatting

    %02d


问:
How do I host CoreNLP server with caseless models?
I'm trying to host a CoreNLP server but with the caseless models but I don't think I was successful and the official site doesn't have example hosting such model.

I'm currently hosting with:

```<code>java -mx4g \
           -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
           -port 9000 \
           -timeout 15000
</code>```

but this is the default way of hosting which doesn't use the caseless models. I checked the app log and it was loading the standard models instead of caseless models:

```<code>[pool-1-thread-1] INFO edu.stanford.nlp.ie.AbstractSequenceClassifier - Loading classifier from edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz ... done [0.9 sec].
[pool-1-thread-1] INFO edu.stanford.nlp.ie.AbstractSequenceClassifier - Loading classifier from edu/stanford/nlp/models/ner/english.muc.7class.distsim.crf.ser.gz ... done [0.5 sec].
[pool-1-thread-1] INFO edu.stanford.nlp.ie.AbstractSequenceClassifier - Loading classifier from edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz ... done [0.5 sec].
</code>```

According to https://stanfordnlp.github.io/CoreNLP/caseless.html, I have downloaded the english models jar file and put it under the corenlp module folder, but I don't know exactly how to specify and use those for server hosting.

In the client side, I'm doing the following:

```<code>import requests

r = requests.post('http://[::]:9000/?properties={"annotators":"tokenize,ssplit,truecase,pos,ner","outputFormat":"json"}',
                  data="show me hotels in toronto for next weekend")
print(r.text)
</code>```

The truecase is working, but I don't see the caseless models being used.

Any help would be appreciated.

答:
You need to pass the property "ner.model": "edu/stanford/nlp/models/ner/english.all.3class.caseless.distsim.crf.ser.gz,edu/stanford/nlp/models/ner/english.muc.7class.caseless.distsim.crf.ser.gz,edu/stanford/nlp/models/ner/english.conll.4class.caseless.distsim.crf.ser.gz"

Also you may want to use Stanza for accessing the Stanford CoreNLP server.

Details here: https://stanfordnlp.github.io/stanza/corenlp_client.html#overview

Body:
I'm trying to host a CoreNLP server but with the caseless models but I don't think I was successful and the official site doesn't have example hosting such model.

I'm currently hosting with:

java -mx4g \
           -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
           -port 9000 \
           -timeout 15000

but this is the default way of hosting which doesn't use the caseless models. I checked the app log and it was loading the standard models instead of caseless models:

[pool-1-thread-1] INFO edu.stanford.nlp.ie.AbstractSequenceClassifier - Loading classifier from edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz ... done [0.9 sec].
[pool-1-thread-1] INFO edu.stanford.nlp.ie.AbstractSequenceClassifier - Loading classifier from edu/stanford/nlp/models/ner/english.muc.7class.distsim.crf.ser.gz ... done [0.5 sec].
[pool-1-thread-1] INFO edu.stanford.nlp.ie.AbstractSequenceClassifier - Loading classifier from edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz ... done [0.5 sec].

According to https://stanfordnlp.github.io/CoreNLP/caseless.html, I have downloaded the english models jar file and put it under the corenlp module folder, but I don't know exactly how to specify and use those for server hosting.

In the client side, I'm doing the following:

import requests

r = requests.post('http://[::]:9000/?properties={"annotators":"tokenize,ssplit,truecase,pos,ner","outputFormat":"json"}',
                  data="show me hotels in toronto for next weekend")
print(r.text)

The truecase is working, but I don't see the caseless models being used.

Any help would be appreciated.


问:
How can I update vue cli version?
I want to create a project on Vue Project Manager. When I try, I see that error message;

"vue create is a Vue CLI 3 only command and you are using Vue CLI 2.9.6."

This is my vue --version output: @vue/cli 4.0.5.

How can I fix this?

My system configuration is as follow:

Ubuntu 18.04
  Npm 6.13.0
  Node 10.16.3

答:
It worked on my work approach, uninstall the vue and reinstall using the steps in the documentation. enter link description here

1 - remove vue: sudo npm uninstall -g vue-cli
2 - install using: sudo npm install -g @vue/clisudo npm uninstall -g vue-cli

Title: How can I update vue cli version?


问:
maximum recursion depth exceeded in django
**i have occured error when  i logout then occure this error maximum recursion depth exceeded........................................................................................................... **</p>

```<code>    template.html
    RecursionError at /logout/
    maximum recursion depth exceeded
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/logout/
    Django Version: 3.0.6
    Exception Type: RecursionError
    Exception Value:
    maximum recursion depth exceeded
    Exception Location: C:\Users\Aqib\Desktop\Python Djnago\vscode projects\thumbsap\account\views.py in logout, line 213
    Python Executable:  C:\Users\Aqib\AppData\Local\Programs\Python\Python38\python.exe
    Python Version: 3.8.3
    Python Path:
    ['C:\\Users\\Aqib\\Desktop\\Python Djnago\\vscode projects\\thumbsap',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38',
     'C:\\Users\\Aqib\\AppData\\Roaming\\Python\\Python38\\site-packages',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin']
    Server time:    Wed, 3 Jun 2020 04:35:00 +0530
    Traceback Switch to copy-and-paste view
    C:\Users\Aqib\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py in inner
                response = get_response(request) …
   projects\thumbsap\account\views.py in logout
            logout(request) …

views.py

def logout(request):
        logout(request)
        messages.SUCCESS(request,"your successfully logged out")
        return render(request,'home/login.html')
        return HttpResponse("Logged Out Successfully")
</code>```

答:
look at the first line of your logout function ...

```<code>def logout(request):
    logout(request)
    .....
</code>```

All this is doing is calling itself with no way of stopping.

I assume that the call to logout was intended to call django.contrib.auth.logout, and thereofre you have something like this at the top of your module :

```<code>from django.contrib.auth import logout
</code>```

But the problem is when you do

```<code>def logout(request)
    ....
</code>```

That defines a new logout names, and it replaces what you imported.

You have two solutions :

rename your logout(request)  function, but that will mean changing your url.py, so the new function is invoked

Change the import to something else (using an alias) so that logout name that is imported isn't overriten

If you opt for option 2, your code will become:

```<code>from django.contrib.auth import logout as dca_logout
     ....

def logout(request):
   dca_logout(request)
     ....
</code>```

Using a different name for the django.contrib.auth.login will ensure that your logout function doesn't makes the name you import.

Body:
**i have occured error when  i logout then occure this error maximum recursion depth exceeded........................................................................................................... **

    template.html
    RecursionError at /logout/
    maximum recursion depth exceeded
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/logout/
    Django Version: 3.0.6
    Exception Type: RecursionError
    Exception Value:
    maximum recursion depth exceeded
    Exception Location: C:\Users\Aqib\Desktop\Python Djnago\vscode projects\thumbsap\account\views.py in logout, line 213
    Python Executable:  C:\Users\Aqib\AppData\Local\Programs\Python\Python38\python.exe
    Python Version: 3.8.3
    Python Path:
    ['C:\\Users\\Aqib\\Desktop\\Python Djnago\\vscode projects\\thumbsap',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38',
     'C:\\Users\\Aqib\\AppData\\Roaming\\Python\\Python38\\site-packages',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib',
     'C:\\Users\\Aqib\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin']
    Server time:    Wed, 3 Jun 2020 04:35:00 +0530
    Traceback Switch to copy-and-paste view
    C:\Users\Aqib\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py in inner
                response = get_response(request) …
   projects\thumbsap\account\views.py in logout
            logout(request) …

views.py

def logout(request):
        logout(request)
        messages.SUCCESS(request,"your successfully logged out")
        return render(request,'home/login.html')
        return HttpResponse("Logged Out Successfully")

Body:
look at the first line of your logout function ...

def logout(request):
    logout(request)
    .....

All this is doing is calling itself with no way of stopping.

I assume that the call to logout was intended to call django.contrib.auth.logout, and thereofre you have something like this at the top of your module :

from django.contrib.auth import logout

But the problem is when you do

def logout(request)
    ....

That defines a new logout names, and it replaces what you imported.

You have two solutions :

rename your logout(request)  function, but that will mean changing your url.py, so the new function is invoked

Change the import to something else (using an alias) so that logout name that is imported isn't overriten

If you opt for option 2, your code will become:

from django.contrib.auth import logout as dca_logout
     ....

def logout(request):
   dca_logout(request)
     ....

Using a different name for the django.contrib.auth.login will ensure that your logout function doesn't makes the name you import.


问:
How can I exponentially scale the Y axis with matplotlib
I'm trying to create a matplotlib plot with an exponential(?) Y axis like the fake one I've mocked up below. For my data I want to spread the values out as they approach the max Y value. And I'd like to compress the values as Y gets close to zero.

All the normal 'log' examples do the opposite: they compress values as they get away from zero. Which is what 'log' does of course. How can I create an exponential(?) scaling instead?

答:
Add this to your code:

```<code>plt.yscale('symlog')
</code>```

Source: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.yscale.html

Body:
Add this to your code:

plt.yscale('symlog')

Source: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.yscale.html


问:
What is difference b/w org.owasp.esapi.Encoder.encodeForHTML and org.owasp.esapi.Encoder.encodeForJavaScript methods
I Know, we can use encodeForHTML for HTMl and encodeForJavascript for javaScript.
There is a Cross-Site Scripting: "Reflected fortify scan problem" in my code

```<code>String errorDesc = HttpServletRequest.getParameter("error_description");
</code>```

I have to validate this using Encoder but I am confused to use which one should i use between them. As we do not know the return type of HttpServletRequest.getParameter.

```<code>1.  org.owasp.esapi.Encoder.encodeForHTML
2.  org.owasp.esapi.Encoder.encodeForJavaScript
</code>```

答:
What we have here dear asker is a rather common misunderstanding about the differences between output encoding--which is what you're working with when you look at the Encoder calls, and input validation, which is a completely separate operation that has little to do with the Encoder class.

The Encoder methods you're dealing with here are to be used only when you're presenting data to a user, and only for the correct context.  For example, if the application is a "Single Page Application" (SPA) then very likely you're just going to want to ensure that the output is encoded for JavaScript as the client-facing framework will almost certainly be JavaScript.

If you were using an older style of application, then you would encode for HTML anytime you were going to place data between <some_tag> data </some_tag>.

XSS requires you to understand one thing for every variable in your application:  Its data flow, from when the value is generated (Server, User, DB, etc.) and understand all of the transformations it might undergo as it traverses to the user and back to the system.  If the value starts in the browser, it will enter into some kind of Controller on the backend, and before you process the value you'll whitelist validate it--ESAPI has a validator class--and then if it passes validation you'll ensure that the database will only treat it as data (PreparedStatement, or through use of an ORM framework's utilities.)  Best practice is to

Canonicalize the data

Validate against the canonicalized value

If valid, discard the canonicalized value and store the original data

If used properly, the Validator class is defaulted to help you do this.

The methods you're asking about in this question are for instances where user input is being sent back to the browser, either from the database or from a previous request in your session that hasn't yet been persisted.

Body:
I Know, we can use encodeForHTML for HTMl and encodeForJavascript for javaScript.
There is a Cross-Site Scripting: "Reflected fortify scan problem" in my code

String errorDesc = HttpServletRequest.getParameter("error_description");

I have to validate this using Encoder but I am confused to use which one should i use between them. As we do not know the return type of HttpServletRequest.getParameter.

1.  org.owasp.esapi.Encoder.encodeForHTML
2.  org.owasp.esapi.Encoder.encodeForJavaScript


问:
Why is UIBarButtonItem image always fuzzy/blurry/pixelated
Here is my current code:

```<code>var reply = UIBarButtonItem(image: UIImage(named: "reply"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("reply:"))
self.navigationItem.rightBarButtonItem = reply
</code>```

The button in the top right corner is always fuzzy. This is a screenshot from an iPhone4s device so it is not a retina-related issue.

I have tried different image sizes ranging from 30x30 to 512x512 and adding the image using customView. These methods have not fixed the issue.

Thanks in advance.

答:
Try this:</p>

```<code>func createBarButton(image: String, size: CGSize, offset: (x: CGFloat, y: CGFloat) = (0,0), hightlightable: Bool = true, action: Selector) -> UIBarButtonItem {
    let btn = UIButton(type: .custom)
    let img = UIImage(named: image)

    btn.setBackgroundImage(img, for: .normal)
    btn.addTarget(self, action: action, for: .touchUpInside)
    btn.frame = CGRect(x: offset.x, y: offset.y, width: size.width, height: size.height)
    btn.adjustsImageWhenHighlighted = hightlightable
    let view = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
//        view.bounds = view.bounds.offsetBy(dx: offset.x, dy: offset.y)
    view.addSubview(btn)
    let barButton = UIBarButtonItem(customView: view)

    return barButton
}

self.navigationItem.rightBarButtonItem = createBarButton(image: "YOUR_IMAGE",
     size: CGSize(width: 35, height: 35),
     offset: (x: -10, y: 0),
     action: #selector(showXY))
</code>```

Body:
Here is my current code:

var reply = UIBarButtonItem(image: UIImage(named: "reply"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("reply:"))
self.navigationItem.rightBarButtonItem = reply

The button in the top right corner is always fuzzy. This is a screenshot from an iPhone4s device so it is not a retina-related issue.

I have tried different image sizes ranging from 30x30 to 512x512 and adding the image using customView. These methods have not fixed the issue.

Thanks in advance.

Body:
Try this:

func createBarButton(image: String, size: CGSize, offset: (x: CGFloat, y: CGFloat) = (0,0), hightlightable: Bool = true, action: Selector) -> UIBarButtonItem {
    let btn = UIButton(type: .custom)
    let img = UIImage(named: image)

    btn.setBackgroundImage(img, for: .normal)
    btn.addTarget(self, action: action, for: .touchUpInside)
    btn.frame = CGRect(x: offset.x, y: offset.y, width: size.width, height: size.height)
    btn.adjustsImageWhenHighlighted = hightlightable
    let view = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
//        view.bounds = view.bounds.offsetBy(dx: offset.x, dy: offset.y)
    view.addSubview(btn)
    let barButton = UIBarButtonItem(customView: view)

    return barButton
}

self.navigationItem.rightBarButtonItem = createBarButton(image: "YOUR_IMAGE",
     size: CGSize(width: 35, height: 35),
     offset: (x: -10, y: 0),
     action: #selector(showXY))


问:
Reasons not to build your own bug tracking system
Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.

The arguments I've heard in favous are usually along the lines of :

Wanting to 'eat our own dog food' in terms of some internally built web framework

Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way

Believing that it isn't difficult to build a bug tracking system

What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?

答: I would just say it's a matter of money - buying a finished product you know is good for you (and sometimes not even buying if it's free) is better than having to go and develop one on your own. It's a simple game of pay now vs. pay later.

OwnerDisplayName: Matt Sheppard

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Constantin

OwnerDisplayName: Omer van Kloeten


问:
Is there an edit control for Delphi that allows path editing?
I have various hierarchical structures and would like to allow navigation around then using an editor like the Microsoft one found in the explorer address bar below. Is there such a Delphi component? (Paid for or free)?

答:
I have spent the morning writing such a control. Actually, I wrote a very generic, completely virtual base control, from which I later derived a directory browser control:

The source code is published here

Here are some images:

Style := bbsClassic

Style := bbsFlat

Style := bbsHeader

Style := bbsThemed

Style := bbsCommand


问:
Wrong use of GROUP BY
i'm having a real problem with a query. The database entity are:

```<code>Paziente (Codice_Fiscale, Nome_Paziente, Cognome_Paziente, Data_Nascita, Luogo_Nascita)
Appuntamento (Codice_Appuntamento, Data_Appuntamento, Ora_Appuntamento, Codice_Fiscale)
Intervento (Codice_Intervento, Tipo_Intervento, Sala_Intervento, Data_Intervento, Ora_Intervento, Codice_Fiscale_Paziente, ID_Dentista)
Dentista (ID_Dentista, Nome_Dentista, Cognome_Dentista)
</code>```

I need to do a query that shows a list of appointment grouped by type of intervention.
It should be something like:

```<code>Tipo_Intervento       COUNT(*)
Chirurgia dentale      1
Cura carie             2
Estrazione dentale     1
Pulizia dentale        3
</code>```

I can do this correctly when i use this query:

```<code>SELECT intervento.Tipo_Intervento, COUNT(*)
FROM intervento
GROUP BY intervento.Tipo_Intervento
</code>```

But i need to link the database "intervento" to "appuntamento" ('cause it's an exercise) and when i use this:

```<code>SELECT COUNT(DISTINCT appuntamento.Codice_Appuntamento) AS Numero_Appuntamenti, intervento.Tipo_Intervento AS Tipologia_intervento
FROM appuntamento, intervento
WHERE appuntamento.Codice_Fiscale = intervento.Codice_Fiscale_Paziente
GROUP BY intervento.Tipo_Intervento
</code>```

I obtain the wrong value:

```<code>Numero_Appuntamenti      Tipologia_intervento
2                        Chirurgia dentale
4                        Cura carie
2                        Estrazione dentale
3                        Pulizia dentale
</code>```

The problem is in the GROUP BY intervento.Tipo_Intervento, that increase the number of appointments, in fact if i use GROUP BY appuntamento.Codice_Appuntamento i obtain:

```<code>Numero_Appuntamenti  Tipologia_intervento
1                    Pulizia dentale
1                    Estrazione dentale
1                    Pulizia dentale
1                    Cura carie
1                    Cura carie
1                    Pulizia dentale
1                    Estrazione dentale
</code>```

That is right, but i need it to be grouped.

Does someone can help me? (forgive my bad english, as you can see it's not my language)

EDIT: This is the table "appuntamento":

```<code>Codice_Appuntamento Data_Appuntamento   Ora_Appuntamento    Codice_Fiscale
        001           2020-05-05    16:00:00.000000     RSSMRA80A01H501U
        002           2020-07-03    16:30:00.000000     VRDGPP85E02F205P
        003          2020-06-05     16:00:00.000000     RSSMRA80A01H501U
        004          2020-08-14     17:15:00.000000     BNCGNN83D03L219B
        005           2020-08-27    17:45:00.000000     BNCGNN83D03L219B
        006          2020-07-05     16:00:00.000000     RSSMRA80A01H501U
        007          2020-09-13     17:20:00.000000     VRDGPP85E02F205P
</code>```

And this the table "intervento"

```<code>Codice_Intervento Tipo_Intervento   Sala_Intervento    Data_Intervento   Ora_Intervento   Codice_Fiscale_Paziente   ID_Dentista
    A_001          Pulizia dentale        1             2020-05-05       16:00:00.000000    RSSMRA80A01H501U            D_001
    A_002          Estrazione dentale     2             2020-07-03        16:30:00.000000   VRDGPP85E02F205P            D_003
    A_003          Pulizia dentale        1             2020-06-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_004          Cura carie             3             2020-08-14        17:15:00.000000   BNCGNN83D03L219B            D_001
    A_005          Chirurgia dentale      5             2020-08-27        17:45:00.000000   BNCGNN83D03L219B            D_002
    A_006          Pulizia dentale        1             2020-07-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_007          Cura carie             3             2020-09-13         17:20:00.000000  VRDGPP85E02F205P            D_002
</code>```

"Codice fiscale" and "ID_Dentista" are the foreing key, thery are the primary key of "paziente" and "dentista"

答:
This will work on mysql 5.6,  not on higher versions :

https://www.db-fiddle.com/f/sDXoDdMWsPVkTheoaWkx1i/0

```<code>SELECT  i.Tipo_Intervento,tmp.Numero_Appuntamenti,a.*
FROM intervento i
LEFT JOIN  appuntamento a ON a.Codice_Fiscale = i.Codice_Fiscale_Paziente
LEFT JOIN
(SELECT COUNT(*) AS Numero_Appuntamenti,Tipo_Intervento
           from intervento
           GROUP BY Tipo_Intervento)  AS tmp ON i.Tipo_Intervento=tmp.Tipo_Intervento
GROUP BY i.Tipo_Intervento
</code>```

Title: Wrong use of GROUP BY

Body:
i'm having a real problem with a query. The database entity are:

Paziente (Codice_Fiscale, Nome_Paziente, Cognome_Paziente, Data_Nascita, Luogo_Nascita)
Appuntamento (Codice_Appuntamento, Data_Appuntamento, Ora_Appuntamento, Codice_Fiscale)
Intervento (Codice_Intervento, Tipo_Intervento, Sala_Intervento, Data_Intervento, Ora_Intervento, Codice_Fiscale_Paziente, ID_Dentista)
Dentista (ID_Dentista, Nome_Dentista, Cognome_Dentista)

I need to do a query that shows a list of appointment grouped by type of intervention.
It should be something like:

Tipo_Intervento       COUNT(*)
Chirurgia dentale      1
Cura carie             2
Estrazione dentale     1
Pulizia dentale        3

I can do this correctly when i use this query:

SELECT intervento.Tipo_Intervento, COUNT(*)
FROM intervento
GROUP BY intervento.Tipo_Intervento

But i need to link the database "intervento" to "appuntamento" ('cause it's an exercise) and when i use this:

SELECT COUNT(DISTINCT appuntamento.Codice_Appuntamento) AS Numero_Appuntamenti, intervento.Tipo_Intervento AS Tipologia_intervento
FROM appuntamento, intervento
WHERE appuntamento.Codice_Fiscale = intervento.Codice_Fiscale_Paziente
GROUP BY intervento.Tipo_Intervento

I obtain the wrong value:

Numero_Appuntamenti      Tipologia_intervento
2                        Chirurgia dentale
4                        Cura carie
2                        Estrazione dentale
3                        Pulizia dentale

The problem is in the GROUP BY intervento.Tipo_Intervento, that increase the number of appointments, in fact if i use GROUP BY appuntamento.Codice_Appuntamento i obtain:

Numero_Appuntamenti  Tipologia_intervento
1                    Pulizia dentale
1                    Estrazione dentale
1                    Pulizia dentale
1                    Cura carie
1                    Cura carie
1                    Pulizia dentale
1                    Estrazione dentale

That is right, but i need it to be grouped.

Does someone can help me? (forgive my bad english, as you can see it's not my language)

EDIT: This is the table "appuntamento":

Codice_Appuntamento Data_Appuntamento   Ora_Appuntamento    Codice_Fiscale
        001           2020-05-05    16:00:00.000000     RSSMRA80A01H501U
        002           2020-07-03    16:30:00.000000     VRDGPP85E02F205P
        003          2020-06-05     16:00:00.000000     RSSMRA80A01H501U
        004          2020-08-14     17:15:00.000000     BNCGNN83D03L219B
        005           2020-08-27    17:45:00.000000     BNCGNN83D03L219B
        006          2020-07-05     16:00:00.000000     RSSMRA80A01H501U
        007          2020-09-13     17:20:00.000000     VRDGPP85E02F205P

And this the table "intervento"

Codice_Intervento Tipo_Intervento   Sala_Intervento    Data_Intervento   Ora_Intervento   Codice_Fiscale_Paziente   ID_Dentista
    A_001          Pulizia dentale        1             2020-05-05       16:00:00.000000    RSSMRA80A01H501U            D_001
    A_002          Estrazione dentale     2             2020-07-03        16:30:00.000000   VRDGPP85E02F205P            D_003
    A_003          Pulizia dentale        1             2020-06-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_004          Cura carie             3             2020-08-14        17:15:00.000000   BNCGNN83D03L219B            D_001
    A_005          Chirurgia dentale      5             2020-08-27        17:45:00.000000   BNCGNN83D03L219B            D_002
    A_006          Pulizia dentale        1             2020-07-05        16:00:00.000000   RSSMRA80A01H501U            D_001
    A_007          Cura carie             3             2020-09-13         17:20:00.000000  VRDGPP85E02F205P            D_002

"Codice fiscale" and "ID_Dentista" are the foreing key, thery are the primary key of "paziente" and "dentista"

Body:
This will work on mysql 5.6,  not on higher versions :

https://www.db-fiddle.com/f/sDXoDdMWsPVkTheoaWkx1i/0

SELECT  i.Tipo_Intervento,tmp.Numero_Appuntamenti,a.*
FROM intervento i
LEFT JOIN  appuntamento a ON a.Codice_Fiscale = i.Codice_Fiscale_Paziente
LEFT JOIN
(SELECT COUNT(*) AS Numero_Appuntamenti,Tipo_Intervento
           from intervento
           GROUP BY Tipo_Intervento)  AS tmp ON i.Tipo_Intervento=tmp.Tipo_Intervento
GROUP BY i.Tipo_Intervento


问:
Join table on multiple conditions with LINQ, always show all results of primary key and coalesce nulls
Essentially I'm trying to replicate this query, which works beautifully as a direct SQL query:

```<code>SELECT *
FROM Products p
LEFT OUTER
  JOIN EventProducts ep ON ep.Product_index = p.[index]
  AND COALESCE(ep.Event_index,'3') = '3'
</code>```

I have two relevant tables:

Products: has index and other information

EventProducts: has index, Product.index, and Event.index and other information including sold, allocated, etc.

In my application view, the Event is already selected and its index will have a constant value. I want to select ALL products, and join the EventProduct data if it has an entry in the database then populate that information into a data grid.

If a Product has no associated EventProduct, it should return an object like:

```<code>{
    index = 1,
    name = productName,
    sold = 0,
    allocated = 0
    ...
}
</code>```

but if there is an associated EventProduct entry, return the object

```<code>{
    index = 2,
    name = product2Name
    sold = 10
    allocated = 15
    ...
}
</code>```

This is my LINQ query right now:

```<code>    var eventProducts = dbContext.Products
        .Join(dbContext.EventProducts,
            product => new { productIndex = product.index, eventIndex = currentEvent.index },
            eventProduct => new { productIndex = eventProduct.Product.index, eventIndex = eventProduct.Event.index },
            (product, eventProduct) => new
            {
                Product = product,
                EventProduct = eventProduct
            });
</code>```

This query always returns 0 objects, where it should return 8 (for each of my products) even though my EventProducts table is currently empty.

答:
Join performs inner join, to perform left join you can either switch to query syntax looking something like this:

```<code> var query = from product in dbContext.Products
     join eventProduct in dbContext.EventProducts.Where(ep => ep.Event_index == currentEvent.index)
          on product.index equals eventProduct.Product_index into gj
     from sub in gj.DefaultIfEmpty()
     select new { Product,  EventProduct = sub };
</code>```

Or use GroupJoin as in this answer.

Or, if Product entity has correctly set up navigation you can try to use Include with Where clause looking like this(not sure it will work though, can't check ATM):

```<code> var productWithEventProducts = dbContext.Products
    .Include(p => p.EventProducts)
    .Where(p => p.EventProducts.Any(ep => ep.Event_index == currentEvent.index)
         || !p.EventProducts.Any())
    .ToList()
</code>```

Body:
Essentially I'm trying to replicate this query, which works beautifully as a direct SQL query:

SELECT *
FROM Products p
LEFT OUTER
  JOIN EventProducts ep ON ep.Product_index = p.[index]
  AND COALESCE(ep.Event_index,'3') = '3'

I have two relevant tables:

Products: has index and other information

EventProducts: has index, Product.index, and Event.index and other information including sold, allocated, etc.

In my application view, the Event is already selected and its index will have a constant value. I want to select ALL products, and join the EventProduct data if it has an entry in the database then populate that information into a data grid.

If a Product has no associated EventProduct, it should return an object like:

{
    index = 1,
    name = productName,
    sold = 0,
    allocated = 0
    ...
}

but if there is an associated EventProduct entry, return the object

{
    index = 2,
    name = product2Name
    sold = 10
    allocated = 15
    ...
}

This is my LINQ query right now:

    var eventProducts = dbContext.Products
        .Join(dbContext.EventProducts,
            product => new { productIndex = product.index, eventIndex = currentEvent.index },
            eventProduct => new { productIndex = eventProduct.Product.index, eventIndex = eventProduct.Event.index },
            (product, eventProduct) => new
            {
                Product = product,
                EventProduct = eventProduct
            });

This query always returns 0 objects, where it should return 8 (for each of my products) even though my EventProducts table is currently empty.

Body:
Join performs inner join, to perform left join you can either switch to query syntax looking something like this:

 var query = from product in dbContext.Products
     join eventProduct in dbContext.EventProducts.Where(ep => ep.Event_index == currentEvent.index)
          on product.index equals eventProduct.Product_index into gj
     from sub in gj.DefaultIfEmpty()
     select new { Product,  EventProduct = sub };

Or use GroupJoin as in this answer.

Or, if Product entity has correctly set up navigation you can try to use Include with Where clause looking like this(not sure it will work though, can't check ATM):

 var productWithEventProducts = dbContext.Products
    .Include(p => p.EventProducts)
    .Where(p => p.EventProducts.Any(ep => ep.Event_index == currentEvent.index)
         || !p.EventProducts.Any())
    .ToList()


问:
Is there any C socket function, which can look for datagrams from a specific UDP client?
The server I am building uses the UDP transport layer protocol. I have a scenario where multiple clients can send datagrams to my server. But each client may send the data across multiple datagrams, and before starting to process the data, I need to have the entire data at the server. From the man page of recvfrom(), it sounds like it reads the datagrams from any UDP client. Are there any recv*() family functions that enable us to read from a specific UDP client?

```<code>#include <netinet/in.h>
#include <sys/socket.h>

int append_data(void* buf, int size);

int main()
{
    /* Create a UDP socket and bind to a port */
    int sockfd;
    char rd_buf[100];

    struct sockaddr_in cliaddr;

    for ( ; ; ) {
        /* Recvfrom any client */

        int addr_len = sizeof(cliaddr);
        int rd_status = recvfrom(sockfd, rd_buf, sizeof(rd_buf), 0, (struct sockaddr*) &cliaddr, &addr_len);

        if (append_data(rd_buf, rd_status) == DATA_COMPLETE)
            continue;

        /* Recvfrom a particular client */

        for ( ; ; ) {
            /* Any function similar to recvfromcli() ? */

            int rd_status = recvfromcli(sockfd, rd_buf, sizeof(rd_buf), 0, (struct sockaddr*) &cliaddr, addr_len);

            if (append_data(rd_buf, rd_status) == DATA_COMPLETE)
                 break;
        }
    }
}
</code>```

If not what are my other alternatives?

答: You can create a separate UDP socket that is bind()'ed to the local IP/Port and connect()'ed to a specific client IP/Port, then you can recv() using that socket, and it will give you datagrams from only that client.

Body:
The server I am building uses the UDP transport layer protocol. I have a scenario where multiple clients can send datagrams to my server. But each client may send the data across multiple datagrams, and before starting to process the data, I need to have the entire data at the server. From the man page of recvfrom(), it sounds like it reads the datagrams from any UDP client. Are there any recv*() family functions that enable us to read from a specific UDP client?

#include <netinet/in.h>
#include <sys/socket.h>

int append_data(void* buf, int size);

int main()
{
    /* Create a UDP socket and bind to a port */
    int sockfd;
    char rd_buf[100];

    struct sockaddr_in cliaddr;

    for ( ; ; ) {
        /* Recvfrom any client */

        int addr_len = sizeof(cliaddr);
        int rd_status = recvfrom(sockfd, rd_buf, sizeof(rd_buf), 0, (struct sockaddr*) &cliaddr, &addr_len);

        if (append_data(rd_buf, rd_status) == DATA_COMPLETE)
            continue;

        /* Recvfrom a particular client */

        for ( ; ; ) {
            /* Any function similar to recvfromcli() ? */

            int rd_status = recvfromcli(sockfd, rd_buf, sizeof(rd_buf), 0, (struct sockaddr*) &cliaddr, addr_len);

            if (append_data(rd_buf, rd_status) == DATA_COMPLETE)
                 break;
        }
    }
}

If not what are my other alternatives?


问:
how to render form and accept values in the same function python flask
Is there any way in flask where I can render the form and at the click of the submit button fetch values.
The error I am getting is 404 not found and I don't know why. Is there any better way to do this.</p>

```<code>@application.route('/cargohandled',methods=['POST'])
def cargohandled():
    if request.method == 'post':
        postman = request.form['postman']
        postype = request.form['postype']
        return {'postman' : postman, 'postype': postype}
    else:
        cursor = connection.cursor()
        cursor.execute("SELECT DISTINCT `PortName` From trarep")
        portname = cursor.fetchall()
        cursor.execute("SELECT DISTINCT `PortType` From trarep")
        porttype = cursor.fetchall()
        return render_template('cargo_handled.htm.j2',title = 'Cargo Handled',portname = portname,porttype= porttype)
    return "CG"
</code>```

答:
You need to allow both GET and POST.

And you should capitalise "post" in your if clause.

You can do away with the else: clause since the rest of the function will execute if the request.method != 'POST'.

The final return would never get executed so you can leave that out too.

```<code>@application.route('/cargohandled',methods=['GET','POST'])
def cargohandled():
    if request.method == 'POST':
        postman = request.form['postman']
        postype = request.form['postype']
        return {'postman' : postman, 'postype': postype}
    cursor = connection.cursor()
    cursor.execute("SELECT DISTINCT `PortName` From trarep")
    portname = cursor.fetchall()
    cursor.execute("SELECT DISTINCT `PortType` From trarep")
    porttype = cursor.fetchall()
    return render_template('cargo_handled.htm.j2',title = 'Cargo Handled',
                           portname = portname,porttype= porttype)
</code>```

Body:
Is there any way in flask where I can render the form and at the click of the submit button fetch values.
The error I am getting is 404 not found and I don't know why. Is there any better way to do this.

@application.route('/cargohandled',methods=['POST'])
def cargohandled():
    if request.method == 'post':
        postman = request.form['postman']
        postype = request.form['postype']
        return {'postman' : postman, 'postype': postype}
    else:
        cursor = connection.cursor()
        cursor.execute("SELECT DISTINCT `PortName` From trarep")
        portname = cursor.fetchall()
        cursor.execute("SELECT DISTINCT `PortType` From trarep")
        porttype = cursor.fetchall()
        return render_template('cargo_handled.htm.j2',title = 'Cargo Handled',portname = portname,porttype= porttype)
    return "CG"

Body:
You need to allow both GET and POST.

And you should capitalise "post" in your if clause.

You can do away with the else: clause since the rest of the function will execute if the request.method != 'POST'.

The final return would never get executed so you can leave that out too.

@application.route('/cargohandled',methods=['GET','POST'])
def cargohandled():
    if request.method == 'POST':
        postman = request.form['postman']
        postype = request.form['postype']
        return {'postman' : postman, 'postype': postype}
    cursor = connection.cursor()
    cursor.execute("SELECT DISTINCT `PortName` From trarep")
    portname = cursor.fetchall()
    cursor.execute("SELECT DISTINCT `PortType` From trarep")
    porttype = cursor.fetchall()
    return render_template('cargo_handled.htm.j2',title = 'Cargo Handled',
                           portname = portname,porttype= porttype)


问:
How do I create a page-transition where the old page can't be reached via the back-button in Flutter?
I have an app with three pages: A, B and C. A is the startpage and has a button to open B via a Navigator.push(). Then B open C via Navigator.push(). Can I configure it in a way that pressing the back button in C brings me back to A and not C?

答:
You can use pushReplacement method, for example:

```<code>Navigator.of(context).pushReplacement(
  MaterialPageRoute(
    builder: (context) => PageC(),
  ),
);
</code>```

This method:

replace the current route (of the navigator by pushing the given route)

and

disposing the previous route

Body:
You can use pushReplacement method, for example:

Navigator.of(context).pushReplacement(
  MaterialPageRoute(
    builder: (context) => PageC(),
  ),
);

This method:

replace the current route (of the navigator by pushing the given route)

and

disposing the previous route


问:
Why DOjo Date Pickers ar not coming
```<code><html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" djConfig="parseOnLoad: true"/>
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css" />
    <script type="text/javascript">
        dojo.require("dijit.form.DateTextBox");
    </script>
</head>
<body>
    <label for="fromDate">Fromfd:</label>
    <input id="fromDate" type="text" name="fromDate" dojoType="dijit.form.DateTextBox" required="true" onChange="dijit.byId('toDate').constraints.min = arguments[0];"/>
</body>
</html>
</code>```

答:
You have to properly close the script tag. Correct usage:

```<code><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
    djConfig="parseOnLoad: true">
</script>
</code>```

The script tag doesn't work when closed using normal XHTML empty tag style. Why? Check here:

Why don't self-closing script tags work?

Title: Why DOjo Date Pickers ar not coming

Body:
    Fromfd:
    <input id="fromDate" type="text" name="fromDate" dojoType="dijit.form.DateTextBox" required="true" onChange="dijit.byId('toDate').constraints.min = arguments[0];"/>

Body:
You have to properly close the script tag. Correct usage:

<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
    djConfig="parseOnLoad: true">
</script>

The script tag doesn't work when closed using normal XHTML empty tag style. Why? Check here:

Why don't self-closing script tags work?


问:
Plot 2 pandas dataframes with same columns
I have 2 pandas dataframes that are the same length with the same column names.  I'd like to loop through and plot the columns against one another - column1 in df1 against col1 in df2. I'd like bar graphs

df1:

```<code>   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1
</code>```

df2:

```<code>   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1
</code>```

答:
Maybe something like below, not very sure what you mean by a bar plot with one against the other, I plotted side by side for every now

```<code>df1=pd.DataFrame({'A':[0,5,2],'B':[4,6,5],'C':[8,9,1]})
df2=pd.DataFrame({'A':[9,1,5],'B':[4,4,5],'C':[5,2,1]})

fig,ax = plt.subplots(1,3,figsize=(8,5))
x1 = [i-0.1 for i in range(len(df1))]
x2 = [i+0.1 for i in range(len(df2))]
for i,col in enumerate(df1.columns):
    ax[i].bar(x=x1,height=df1[col],width=0.2,label="df1")
    ax[i].bar(x=x2,height=df2[col],width=0.2,label="df2")
    ax[i].legend()
</code>```

Body:
I have 2 pandas dataframes that are the same length with the same column names.  I'd like to loop through and plot the columns against one another - column1 in df1 against col1 in df2. I'd like bar graphs

df1:

   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1

df2:

   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1

Body:
Maybe something like below, not very sure what you mean by a bar plot with one against the other, I plotted side by side for every now

df1=pd.DataFrame({'A':[0,5,2],'B':[4,6,5],'C':[8,9,1]})
df2=pd.DataFrame({'A':[9,1,5],'B':[4,4,5],'C':[5,2,1]})

fig,ax = plt.subplots(1,3,figsize=(8,5))
x1 = [i-0.1 for i in range(len(df1))]
x2 = [i+0.1 for i in range(len(df2))]
for i,col in enumerate(df1.columns):
    ax[i].bar(x=x1,height=df1[col],width=0.2,label="df1")
    ax[i].bar(x=x2,height=df2[col],width=0.2,label="df2")
    ax[i].legend()


问:
Solving Binary Gap using Recursion
I am trying to solve binary gap problem using recursion. It can be easily solved without recursion. But I want to solve this with recursion.The below program takes an integer as input and finds the binary gap.

Example:

```<code>input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2
</code>```

It finds the maximum number of zeros that occur between two 1's in the binary representation.

I want to solve this in O(logn). Right now, the below program simply counts the total number of zeros and gives output 3 instead of 2. How do I correct this to get the right output?

```<code>class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;

        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}
</code>```

答:
This is also an extremely simple solution. This problem can also be solved by keeping track of the index where the 1 occurred(in binary). The solution does not use any array and any complex method. It is simple if else logic.

```<code>    public int solution(int N) {
    int saveN = 0;
    int digit =0;
    int value =0;
    int savedi =0;
    int resultVal =0;
    saveN = N;
    bool firstHit = true;

    //First calculate the total digits
    while(N != 0)
    {
        digit++;
        N = N / 2;
    }

    N = saveN;

    for(int i =0; i<digit;i++)
    {
        // If 1 is found at the ith place
        if((N & (0x01 << i)) == (0x01 << i))
        {
            if(firstHit)
            {
                savedi = i;// save i value
                firstHit = false;
            }
            else
            {
                value = i - savedi;
                if(resultVal < value)
                    resultVal = value;
                firstHit = true;
                // 1 found again so go 1 iteration back and save the 1's position
                i--;
            }
        }
    }

    // sub 1 as it gives 1 more than true result
    resultVal = resultVal - 1;

    //handle if a single 1 is found
    if(resultVal < 0)
        return 0;
    else
        return resultVal;
}
</code>```

Title: Solving Binary Gap using Recursion

Body:
I am trying to solve binary gap problem using recursion. It can be easily solved without recursion. But I want to solve this with recursion.The below program takes an integer as input and finds the binary gap.

Example:

input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2

It finds the maximum number of zeros that occur between two 1's in the binary representation.

I want to solve this in O(logn). Right now, the below program simply counts the total number of zeros and gives output 3 instead of 2. How do I correct this to get the right output?

class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;

        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}

Body:
This is also an extremely simple solution. This problem can also be solved by keeping track of the index where the 1 occurred(in binary). The solution does not use any array and any complex method. It is simple if else logic.

    public int solution(int N) {
    int saveN = 0;
    int digit =0;
    int value =0;
    int savedi =0;
    int resultVal =0;
    saveN = N;
    bool firstHit = true;

    //First calculate the total digits
    while(N != 0)
    {
        digit++;
        N = N / 2;
    }

    N = saveN;

    for(int i =0; i<digit;i++)
    {
        // If 1 is found at the ith place
        if((N & (0x01 << i)) == (0x01 << i))
        {
            if(firstHit)
            {
                savedi = i;// save i value
                firstHit = false;
            }
            else
            {
                value = i - savedi;
                if(resultVal < value)
                    resultVal = value;
                firstHit = true;
                // 1 found again so go 1 iteration back and save the 1's position
                i--;
            }
        }
    }

    // sub 1 as it gives 1 more than true result
    resultVal = resultVal - 1;

    //handle if a single 1 is found
    if(resultVal < 0)
        return 0;
    else
        return resultVal;
}


问:
Calculating shape of conv1d layer in Pytorch
How we can calculate the shape of conv1d layer in PyTorch. IS there any command to calculate size and shape of these layers in PyTorch.</p>

```<code>            nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=2, stride=stride_size),
            nn.Dropout(0.25)```
</code>```

答:
The output size can be calculated as shown in the documentation nn.Conv1d - Shape:

The batch size remains unchanged and you already know the number of channels, since you specified them when creating the convolution (depth_2 in this example).

Only the length needs to be calculated and you can do that with a simple function analogous to the formula above:

def calculate_output_length(length_in, kernel_size, stride=1, padding=0, dilation=1):
    return (length_in + 2 * padding - dilation * (kernel_size - 1) - 1) // stride + 1
```

The default values specified are also the default values of nn.Conv1d, therefore you only need to specify what you also specify to create the convolution. It uses an integer division //, because the numerator might be not be divisible by stride, in which case it just gets rounded down (indicated by the brackets that are only closed at towards the bottom).

The same formula also applies to nn.MaxPool1d, but keep in mind that it automatically sets stride = kernel_size if stride is not specified.

Body:
How we can calculate the shape of conv1d layer in PyTorch. IS there any command to calculate size and shape of these layers in PyTorch.

            nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=2, stride=stride_size),
            nn.Dropout(0.25)```

Body:
The output size can be calculated as shown in the documentation nn.Conv1d - Shape:

The batch size remains unchanged and you already know the number of channels, since you specified them when creating the convolution (depth_2 in this example).

Only the length needs to be calculated and you can do that with a simple function analogous to the formula above:

def calculate_output_length(length_in, kernel_size, stride=1, padding=0, dilation=1):
    return (length_in + 2 * padding - dilation * (kernel_size - 1) - 1) // stride + 1

The default values specified are also the default values of nn.Conv1d, therefore you only need to specify what you also specify to create the convolution. It uses an integer division //, because the numerator might be not be divisible by stride, in which case it just gets rounded down (indicated by the brackets that are only closed at towards the bottom).

The same formula also applies to nn.MaxPool1d, but keep in mind that it automatically sets stride = kernel_size if stride is not specified.


问:
SSL: CERTIFICATE_VERIFY_FAILED error with python3 on macOS 10.15
/usr/bin/python3 from Xcode/CLT on macOS 10.15 (DB6/PB5 at the moment, with Xcode 11 beta 6) fails with SSL: CERTIFICATE_VERIFY_FAILED for all HTTPS requests originating from PSL, e.g. from urllib.request:

$ /usr/bin/python3 -c 'import urllib.request; urllib.request.urlopen("https://www.apple.com/")'
...
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)>
```

How to solve this problem?

(I know the answer, will post shortly; just sharing it in case other people run into it.)

答:
i had an issue with 'abort 6' when importing 'requests' package after updating to catalina. while searching for a solution, i was lead to this page. unfortunately none of the above worked for me, however...

updating to python 3.8 manually from python.org seemed to solve this issue very easily for me. i had to reinstall all my packages (w/ pip3) as i came across errors, but that wasn't so bad.

i don't see any of my projects having an issue with python3.8 so far (been using 3.7 for a while)

hope this helps someone!
thanks for all the additional suggestions and efforts!

Body:
/usr/bin/python3 from Xcode/CLT on macOS 10.15 (DB6/PB5 at the moment, with Xcode 11 beta 6) fails with SSL: CERTIFICATE_VERIFY_FAILED for all HTTPS requests originating from PSL, e.g. from urllib.request:

$ /usr/bin/python3 -c 'import urllib.request; urllib.request.urlopen("https://www.apple.com/")'
...
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)>

How to solve this problem?

(I know the answer, will post shortly; just sharing it in case other people run into it.)