问:
Xamarin.Froms Frame BackgroudColor change not showing
Ihave this scenario: A ListView and every Cell is a frame. When showing the list all frames backgroudcolor is white when i click on frame i want the color to change in  blie. I change the color but not refreshing. This is my code:
In xaml page

```<code>
   <pages:PopupPage.Resources>
        <local1:ChangeFrameBackgroudColor x:Key="ChangeFrameBackgroudColor" />
    </ResourceDictionary>-->
    </pages:PopupPage.Resources>
  <ListView x:Name="IzberiFirmaListView" HasUnevenRows="True"  ItemsSource="{Binding KorisnikFirmi}" SelectedItem="{Binding IzbranaFirmaId } " Header="{Binding}" ItemTapped="IzberiFirmaListView_ItemTapped">
                <ListView.ItemTemplate >
                    <DataTemplate>
                        <local:ExtendedViewCell SelectedBackgroundColor="#2188ff"  >

                            <StackLayout  Padding="20, 10"  >
                                <Frame x:Name="frameLabel" BorderColor="#2188ff" BackgroundColor="{Binding IsActive, Converter={StaticResource ChangeFrameBackgroudColor}}">
                                    <Label  FontAttributes="Bold" FontSize="18" TextColor="Black" Text="{Binding Naziv}" ></Label>
                                </Frame>
                            </StackLayout>

                        </local:ExtendedViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
                <ListView.HeaderTemplate>
                    <DataTemplate>
                        <ContentView BackgroundColor="#006BE6" >
                            <Label Margin="10" HorizontalOptions="CenterAndExpand" Text="ОДБЕРЕТЕ ФИРМА"  TextColor="White" FontSize="20" FontAttributes="Bold"/>
                        </ContentView>
                    </DataTemplate>
                </ListView.HeaderTemplate>
            </ListView>

</code>```

In xaml.cs Page:

```<code>        private void IzberiFirmaListView_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            var vm = BindingContext as OdberiFirmaPopupViewModel;
            var firm = e.Item as SysDashFirma;
            vm.ChangeColorOnItemSelected(firm);

        }
</code>```

In viewModel

```<code>    public List<SysDashFirma> KorisnikFirmi
        {
            get { return korisnikFirmi; }
            set
            {
                if (korisnikFirmi != value)
                {
                    korisnikFirmi = value;

                    SetProperty(ref korisnikFirmi, value);
                    OnPropertyChanged("KorisnikFirmi");

                }
            }
        }
  public void ChangeColorOnItemSelected(SysDashFirma firm)
        {
            if (_oldFirmSelected == firm)
            {
                //firm.BackColor = "#2188ff";
                firm.IsActive = true;
                UpdateSelectedFirmItemColor(firm);
            }
            else
            {
                if(_oldFirmSelected != null)
                {
                    //_oldFirmSelected.BackColor = "#f5f5f5";
                    _oldFirmSelected.IsActive = false;
                    UpdateSelectedFirmItemColor(_oldFirmSelected);
                }
                // firm.BackColor = "#2188ff";
                firm.IsActive = true;
                UpdateSelectedFirmItemColor(firm);
            }

            _oldFirmSelected = firm;
        }

        private void UpdateSelectedFirmItemColor(SysDashFirma firm)
        {
            var index = KorisnikFirmi.IndexOf(firm);
            KorisnikFirmi.Remove(firm);
            KorisnikFirmi.Insert(index,firm);
        }

</code>```

Changes are made in the list ,flag is changed, probably cant refresh the bidning context to converter read all from start.

答:
Use OnPropertyChanged for the IsActive property to notify the UI about its change.

public class Firm : INotifyPropertyChanged
{
    private string name = "Unknown";

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            OnPropertyChanged();
        }
    }

    private bool isActive;

    public bool IsActive
    {
        get
        {
            return isActive;
        }
        set
        {
            isActive = value;
            OnPropertyChanged();
        }
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
```

<p>I would suggest changing the <code>IsActive</code> property alone as removing and adding the item is not necessary.</p>

<pre class="lang-cs prettyprint-override"><code><ListView
    ItemTapped="ListView_ItemTapped"
    ItemsSource="{Binding FirmCollection}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Frame
                    Padding="2"
                    BackgroundColor="{Binding IsActive, Converter={StaticResource converterTest}}">
                    <Label Text="{Binding Name}"/>
                </Frame>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

ViewModel

public class ViewModel : INotifyPropertyChanged
{

....
....

    private Firm oldSelectedFirm;

    public Firm OldSelectedFirm
    {
        get
        {
            return oldSelectedFirm;
        }
        set
        {
            oldSelectedFirm = value;
            OnPropertyChanged();
        }
    }

...
...

}

```

<p><strong>Xaml.cs</strong></p>

<pre class="lang-cs prettyprint-override"><code>void ListView_ItemTapped(System.Object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
    var tappedFirm = (e.Item as Firm);
    var vm = (BindingContext as ViewModel);
    if (vm.OldSelectedFirm != null)
        vm.OldSelectedFirm.IsActive = false;

    tappedFirm.IsActive = true;
    vm.OldSelectedFirm = tappedFirm;
}

</code>```

Body:
Ihave this scenario: A ListView and every Cell is a frame. When showing the list all frames backgroudcolor is white when i click on frame i want the color to change in  blie. I change the color but not refreshing. This is my code:
In xaml page

   <pages:PopupPage.Resources>
        <local1:ChangeFrameBackgroudColor x:Key="ChangeFrameBackgroudColor" />
    </ResourceDictionary>-->
    </pages:PopupPage.Resources>
  <ListView x:Name="IzberiFirmaListView" HasUnevenRows="True"  ItemsSource="{Binding KorisnikFirmi}" SelectedItem="{Binding IzbranaFirmaId } " Header="{Binding}" ItemTapped="IzberiFirmaListView_ItemTapped">
                <ListView.ItemTemplate >
                    <DataTemplate>
                        <local:ExtendedViewCell SelectedBackgroundColor="#2188ff"  >

                            <StackLayout  Padding="20, 10"  >
                                <Frame x:Name="frameLabel" BorderColor="#2188ff" BackgroundColor="{Binding IsActive, Converter={StaticResource ChangeFrameBackgroudColor}}">

                                </Frame>
                            </StackLayout>

                        </local:ExtendedViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
                <ListView.HeaderTemplate>
                    <DataTemplate>
                        <ContentView BackgroundColor="#006BE6" >

                        </ContentView>
                    </DataTemplate>
                </ListView.HeaderTemplate>
            </ListView>

In xaml.cs Page:

        private void IzberiFirmaListView_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            var vm = BindingContext as OdberiFirmaPopupViewModel;
            var firm = e.Item as SysDashFirma;
            vm.ChangeColorOnItemSelected(firm);

        }

In viewModel

    public List<SysDashFirma> KorisnikFirmi
        {
            get { return korisnikFirmi; }
            set
            {
                if (korisnikFirmi != value)
                {
                    korisnikFirmi = value;

                    SetProperty(ref korisnikFirmi, value);
                    OnPropertyChanged("KorisnikFirmi");

                }
            }
        }
  public void ChangeColorOnItemSelected(SysDashFirma firm)
        {
            if (_oldFirmSelected == firm)
            {
                //firm.BackColor = "#2188ff";
                firm.IsActive = true;
                UpdateSelectedFirmItemColor(firm);
            }
            else
            {
                if(_oldFirmSelected != null)
                {
                    //_oldFirmSelected.BackColor = "#f5f5f5";
                    _oldFirmSelected.IsActive = false;
                    UpdateSelectedFirmItemColor(_oldFirmSelected);
                }
                // firm.BackColor = "#2188ff";
                firm.IsActive = true;
                UpdateSelectedFirmItemColor(firm);
            }

            _oldFirmSelected = firm;
        }

        private void UpdateSelectedFirmItemColor(SysDashFirma firm)
        {
            var index = KorisnikFirmi.IndexOf(firm);
            KorisnikFirmi.Remove(firm);
            KorisnikFirmi.Insert(index,firm);
        }

Changes are made in the list ,flag is changed, probably cant refresh the bidning context to converter read all from start.

Body:
Use OnPropertyChanged for the IsActive property to notify the UI about its change.

public class Firm : INotifyPropertyChanged
{
    private string name = "Unknown";

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            OnPropertyChanged();
        }
    }

    private bool isActive;

    public bool IsActive
    {
        get
        {
            return isActive;
        }
        set
        {
            isActive = value;
            OnPropertyChanged();
        }
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

I would suggest changing the IsActive property alone as removing and adding the item is not necessary.

<ListView
    ItemTapped="ListView_ItemTapped"
    ItemsSource="{Binding FirmCollection}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Frame
                    Padding="2"
                    BackgroundColor="{Binding IsActive, Converter={StaticResource converterTest}}">
                    <Label Text="{Binding Name}"/>
                </Frame>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel

public class ViewModel : INotifyPropertyChanged
{

....
....

    private Firm oldSelectedFirm;

    public Firm OldSelectedFirm
    {
        get
        {
            return oldSelectedFirm;
        }
        set
        {
            oldSelectedFirm = value;
            OnPropertyChanged();
        }
    }

...
...

}

Xaml.cs

void ListView_ItemTapped(System.Object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
    var tappedFirm = (e.Item as Firm);
    var vm = (BindingContext as ViewModel);
    if (vm.OldSelectedFirm != null)
        vm.OldSelectedFirm.IsActive = false;

    tappedFirm.IsActive = true;
    vm.OldSelectedFirm = tappedFirm;
}


来源: stackexchange

问:
How to send operational log data from Azure IoT Edge runtime device?
We have an Edge device running Azure IoT Edge Runtime. The device is sending telemetry data from sensors to IoT Hub but all operational logging is done to logs on the device.

What is the recommended way to send operational log data, i.e. not the actual sensor data, from an edge device? Should we send them to their own topic in IoT Hub or is there some dedicated method?

答:
IoT Edge supports native retrieval of module logs and upload to Azure Blob Storage as of Version 1.0.8 as an experimental feature. To enable it, the following environment variables need to be set for the edgeAgent (make note of the double underscores):

```<code>ExperimentalFeatures__Enabled=true
ExperimentalFeatures__EnableUploadLogs=true
</code>```

Refer here for more details.

Also, there are some custom solutions like this one, that work with Log Analytics workspace, but the problem is that you do not have any guarantee for the maintenance.

And the third option would be, your own custom implementation, potentially by leveraging Azure blob storage module, and that way you can store whatever you want and have a local blob store to be synced in a secured way with the remote blob storage acc.

ContentLicense: CC BY-SA 4.0

Body:
IoT Edge supports native retrieval of module logs and upload to Azure Blob Storage as of Version 1.0.8 as an experimental feature. To enable it, the following environment variables need to be set for the edgeAgent (make note of the double underscores):

ExperimentalFeatures__Enabled=true
ExperimentalFeatures__EnableUploadLogs=true

Refer here for more details.

Also, there are some custom solutions like this one, that work with Log Analytics workspace, but the problem is that you do not have any guarantee for the maintenance.

And the third option would be, your own custom implementation, potentially by leveraging Azure blob storage module, and that way you can store whatever you want and have a local blob store to be synced in a secured way with the remote blob storage acc.


问:
Rails request with id
I want to detect the ID in which my page is called.

Example:
http://localhost:3000#technical-options

the browser jumps to the element with id technical-options but i am not able to detect the full request by ruby / rails.

this did not help
How do I get the current absolute URL in Ruby on Rails?

request.url, request.fullpath are not delivering the id after the #

many thanks

答: I don't think this is possible from chrome since chrome doesn't send the parameter after the hash in the request.</p>

Title: Rails request with id


问:
How to find multiple indexes of a letter inside a word? (Python)
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

```<code>for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.
</code>```

Full code:

```<code>#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)
</code>```

答:
Another more verbose solution might be:

```<code>str1 = "ooottat"
def find_all_indices(text, letter):
    indices_of_letter = []
    for i, ch in enumerate(text):

        if ch == letter:
            indices_of_letter.append(i)
    return indices_of_letter
print(find_all_indices(str1, 'o'))
</code>```

Side note:

Indexes is the nontechnical plural of index. the right technical plural for index is indices

Body:
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.

Full code:

#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)

Body:
Another more verbose solution might be:

str1 = "ooottat"
def find_all_indices(text, letter):
    indices_of_letter = []
    for i, ch in enumerate(text):

        if ch == letter:
            indices_of_letter.append(i)
    return indices_of_letter
print(find_all_indices(str1, 'o'))

Side note:

Indexes is the nontechnical plural of index. the right technical plural for index is indices


问:
NLTK Tagging spanish words using a corpus
I am trying to learn how to tag spanish words using NLTK.

From the nltk book, It is quite easy to tag english words using their example.  Because I am new to nltk and all language processing, I am quite confused on how to proceeed.

I have downloaded the cess_esp corpus.  Is there a way to specifiy a corpus in nltk.pos_tag. I looked at the pos_tag documentation and didn't see anything that suggested I could.  I feel like i'm missing some key concepts.  Do I have to manually tag the words in my text agains the cess_esp corpus? (by manually I mean tokenize my sentance and run it agains the corpus) Or am I off the mark entirely.  Thank you

答:
I ended up here searching for POS taggers for other languages then English. Another option for your problem is using the Spacy library. Which offers POS tagging for multiple languages such as Dutch, German, French, Portuguese, Spanish, Norwegian, Italian, Greek and Lithuanian.

From the Spacy Documentation:

```<code>import es_core_news_sm
nlp = es_core_news_sm.load()
doc = nlp("El copal se usa principalmente para sahumar en distintas ocasiones como lo son las fiestas religiosas.")
print([(w.text, w.pos_) for w in doc])
</code>```

leads to:

[('El', 'DET'), ('copal', 'NOUN'), ('se', 'PRON'), ('usa', 'VERB'),
  ('principalmente', 'ADV'), ('para', 'ADP'), ('sahumar', 'VERB'),
  ('en', 'ADP'), ('distintas', 'DET'), ('ocasiones', 'NOUN'), ('como',
  'SCONJ'), ('lo', 'PRON'), ('son', 'AUX'), ('las', 'DET'), ('fiestas',
  'NOUN'), ('religiosas', 'ADJ'), ('.', 'PUNCT')]

and to visualize in a notebook:

```<code>displacy.render(doc, style='dep', jupyter = True, options = {'distance': 120})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I ended up here searching for POS taggers for other languages then English. Another option for your problem is using the Spacy library. Which offers POS tagging for multiple languages such as Dutch, German, French, Portuguese, Spanish, Norwegian, Italian, Greek and Lithuanian.

From the Spacy Documentation:

import es_core_news_sm
nlp = es_core_news_sm.load()
doc = nlp("El copal se usa principalmente para sahumar en distintas ocasiones como lo son las fiestas religiosas.")
print([(w.text, w.pos_) for w in doc])

leads to:

[('El', 'DET'), ('copal', 'NOUN'), ('se', 'PRON'), ('usa', 'VERB'),
  ('principalmente', 'ADV'), ('para', 'ADP'), ('sahumar', 'VERB'),
  ('en', 'ADP'), ('distintas', 'DET'), ('ocasiones', 'NOUN'), ('como',
  'SCONJ'), ('lo', 'PRON'), ('son', 'AUX'), ('las', 'DET'), ('fiestas',
  'NOUN'), ('religiosas', 'ADJ'), ('.', 'PUNCT')]

and to visualize in a notebook:

displacy.render(doc, style='dep', jupyter = True, options = {'distance': 120})


问:
dotnet test doesn't recursively search folders for .csproj with wildcards
I want to run all tests in several dotnet core C# test projects.

From the root folder if I run 'dotnet test /*.test.csproj' it will only run the tests one folder down.
From the root folder if I run 'dotnet test **//*.test.csproj' it will only run the tests two folders down.

How can I get 'dotnet test' to recursively check all folders for a *.test.csproj project? i.e. run test from both projects above.

答:
Run dotnet test without any argument in the root folder. Make sure you added a .sln file that defines the path for all the projects of your solution, including the test projects. It works for my GitHub repository for an API with test files in folders:

Api.IntegrationTests\

Logic.Tests\

Subfolder\Another.Tests\

I added the third test project just on my local computer (you will not see it on the GitHub repository) to make sure it works:

Test run for ...\Subfolder\Another.Tests\bin\Debug\netcoreapp3.0\Another.Tests.dll(.NETCoreApp,Version=v3.0)

Test run for ...\Logic.Tests\bin\Debug\netcoreapp3.0\Logic.Tests.dll(.NETCoreApp,Version=v3.0)

Test run for ...\Api.IntegrationTests\bin\Debug\netcoreapp3.0\Api.IntegrationTests.dll(.NETCoreApp,Version=v3.0)


问:
Delete local folder when project is deleted in TFS?
We just started using TFS and it works great. I have one question though, if we delete a folder it's not deleted on my local workspace. We are currently reorganizing a project and I wish to not have heaps of unused folders on my local drive.

Where can I configure this?

Thanks in advance.

答: Another solution, which also checks how well your project is put together, is to cut the whole folder and move it elsewhere, then perform a get across the project.  This will allow you to check if the project will build or if there are some "magic" DLLs missing.  Anything that is missing can be retrieved from the copy of the structure and added into source control.</p>


问:
Wrong records when filtering date
I have strange problem when i filter in related models by date,
consider this code :

```<code>function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }

    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}
</code>```

if I filtering yesterday date  17/02/20;  it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

答:
remove greater than and less than sign so that you can get specific date result</p>

```<code>function applyDepositOnRangeFilter($query, $request)
{
if ($request->has('deposit_at_from')) {
    $query->whereHas('deposits', function ($query) use ($request) {
        $query->whereDate('created_at', '=', $request->input('deposit_at_from'));
    });
}

if ($request->has('deposit_at_to')) {
    $query->whereHas('deposits', function ($query) use ($request) {
        $query->whereDate('created_at', '=', $request->input('deposit_at_to'));
    });
 }
}
</code>```

Title: Wrong records when filtering date

Body:
I have strange problem when i filter in related models by date,
consider this code :

function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }

    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}

if I filtering yesterday date  17/02/20;  it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

Body:
remove greater than and less than sign so that you can get specific date result

function applyDepositOnRangeFilter($query, $request)
{
if ($request->has('deposit_at_from')) {
    $query->whereHas('deposits', function ($query) use ($request) {
        $query->whereDate('created_at', '=', $request->input('deposit_at_from'));
    });
}

if ($request->has('deposit_at_to')) {
    $query->whereHas('deposits', function ($query) use ($request) {
        $query->whereDate('created_at', '=', $request->input('deposit_at_to'));
    });
 }
}


问:
Why/How image dataet dimensions get changed after it converts into tensorflow 2.0 dataset
I am using CIFAR10 dataset.which has original size: (60000,32,32,3)
,after converting it into tensorflow dataset it gets converted into tf.Tensor : shape(64,24,24,3).
What I understand from above is, per batch there are 64 images of 24 x 24 in 3 channels.(Lemme know if I am wrong)
Here's my code snippet.

```<code>(x_train,y_train),(x_test,y_test)=tf.keras.datasets.cifar10.load_data()
train_dataset=tf.data.Dataset.from_tensor_slices((x_train,y_train)).batch(64).shuffle(10000)
train_dataset=train_dataset.map(lambda x,y:(tf.cast(x,tf.float32)/255.0,y))
train_dataset=train_dataset.map(lambda x,y:(tf.image.central_crop(x,0.75),y))
train_dataset=train_dataset.map(lambda x,y:(tf.image.random_flip_left_right(x),y))
train_dataset=train_dataset.repeat()
</code>```

as per my understanding, it's because It's been centrally cropped by 75%. If it's right then how exactly?

答:
Your understanding is correct. The central_crop crops the central region of the image by removing its outer parts. Therefore with central_fraction=0.75, the new dimensions of image would be 32*0.75 = 24. Here's the documentation of the method:

```<code>central_crop(image, central_fraction)
    Crop the central region of the image(s).

    Remove the outer parts of an image but retain the central region of the image
    along each dimension. If we specify central_fraction = 0.5, this function
    returns the region marked with "X" in the below diagram.

         --------
        |        |
        |  XXXX  |
        |  XXXX  |
        |        |   where "X" is the central 50% of the image.
         --------

    This function works on either a single image (`image` is a 3-D Tensor), or a
    batch of images (`image` is a 4-D Tensor).

    Args:
      image: Either a 3-D float Tensor of shape [height, width, depth], or a 4-D
        Tensor of shape [batch_size, height, width, depth].
      central_fraction: float (0, 1], fraction of size to crop
    Usage Example: ```python >> import tensorflow as tf >> x =
      tf.random.normal(shape=(256, 256, 3)) >> tf.image.central_crop(x, 0.5) ```

    Raises:
      ValueError: if central_crop_fraction is not within (0, 1].

    Returns:
      3-D / 4-D float Tensor, as per the input.
</code>```

Body:
I am using CIFAR10 dataset.which has original size: (60000,32,32,3)
,after converting it into tensorflow dataset it gets converted into tf.Tensor : shape(64,24,24,3).
What I understand from above is, per batch there are 64 images of 24 x 24 in 3 channels.(Lemme know if I am wrong)
Here's my code snippet.

(x_train,y_train),(x_test,y_test)=tf.keras.datasets.cifar10.load_data()
train_dataset=tf.data.Dataset.from_tensor_slices((x_train,y_train)).batch(64).shuffle(10000)
train_dataset=train_dataset.map(lambda x,y:(tf.cast(x,tf.float32)/255.0,y))
train_dataset=train_dataset.map(lambda x,y:(tf.image.central_crop(x,0.75),y))
train_dataset=train_dataset.map(lambda x,y:(tf.image.random_flip_left_right(x),y))
train_dataset=train_dataset.repeat()

as per my understanding, it's because It's been centrally cropped by 75%. If it's right then how exactly?

Body:
Your understanding is correct. The central_crop crops the central region of the image by removing its outer parts. Therefore with central_fraction=0.75, the new dimensions of image would be 32*0.75 = 24. Here's the documentation of the method:

central_crop(image, central_fraction)
    Crop the central region of the image(s).

    Remove the outer parts of an image but retain the central region of the image
    along each dimension. If we specify central_fraction = 0.5, this function
    returns the region marked with "X" in the below diagram.

         --------
        |        |
        |  XXXX  |
        |  XXXX  |
        |        |   where "X" is the central 50% of the image.
         --------

    This function works on either a single image (`image` is a 3-D Tensor), or a
    batch of images (`image` is a 4-D Tensor).

    Args:
      image: Either a 3-D float Tensor of shape [height, width, depth], or a 4-D
        Tensor of shape [batch_size, height, width, depth].
      central_fraction: float (0, 1], fraction of size to crop
    Usage Example: ```python >> import tensorflow as tf >> x =
      tf.random.normal(shape=(256, 256, 3)) >> tf.image.central_crop(x, 0.5) ```

    Raises:
      ValueError: if central_crop_fraction is not within (0, 1].

    Returns:
      3-D / 4-D float Tensor, as per the input.


问:
How to send Plain text body in email in laravel 5.1?
My email is sending properly with subject name, now I dont know how to send email body with simple text. The thing just now I am doing is sending blank email with just a subject name on it.
Can anyone help me?</p>

```<code>$data = array('title' => 'Forget Password - App', 'content' => 'This is the content of mail body');
           Mail::send(['text' => 'view'],$data, function ($message) {
                $message->from('fromemail@gmail.com', 'Social Team');
                $message->to('randomemail@gmail.com');
                $message->subject('App - Forget Password');
            });
</code>```

答:
You can also use send method and setBody with plain text or html.</p>

```<code>Mail::send([], [], function ($message) {
  $message->to(..)
    ->subject(..)
    // here comes what you want
    ->setBody('Hi, welcome user!'); // assuming text/plain
    // or:
    ->setBody('<h1>Hi, welcome user!</h1><br> hello world', 'text/html'); // for HTML rich messages.
});
</code>```

Body:
My email is sending properly with subject name, now I dont know how to send email body with simple text. The thing just now I am doing is sending blank email with just a subject name on it.
Can anyone help me?

$data = array('title' => 'Forget Password - App', 'content' => 'This is the content of mail body');
           Mail::send(['text' => 'view'],$data, function ($message) {
                $message->from('fromemail@gmail.com', 'Social Team');
                $message->to('randomemail@gmail.com');
                $message->subject('App - Forget Password');
            });

Body:
You can also use send method and setBody with plain text or html.

Mail::send([], [], function ($message) {
  $message->to(..)
    ->subject(..)
    // here comes what you want
    ->setBody('Hi, welcome user!'); // assuming text/plain
    // or:
    ->setBody('<h1>Hi, welcome user!</h1><br> hello world', 'text/html'); // for HTML rich messages.
});


问:
Is there a way to create test summary from the existing test suites - in Microsoft TFS?
I am struggling to find an efficient way to:
create TEST SUMMARY from the existing test suites, that can be put under task in TFS.

Currently, we export that somehow into Excel.

Looking for a way to create a TEST SUMMARY from the existing test suites, so that it can be stored in TFS.

答:
You could check Offline Test Execution extension. With this extension, you can export the entire test plan, or a filtered selection, to an Excel file:

https://marketplace.visualstudio.com/items?itemName=ms-devlabs.OfflineTestExecution

Or you can use Test Suites - Get Test Cases REST API to get all test cases in a suite:

https://learn.microsoft.com/en-us/rest/api/azure/devops/test/test%20%20suites/get%20test%20cases?view=azure-devops-server-rest-5.0


问:
why my CSS transition not working in react
My css transition not working correctly

when I click the button, the div disappears immediately...

I had tried animation too.

But when the animation finishes, the width becomes 0 immediately.

react

```<code>const NaviDrawer = ({ naviData, show }) => {
    return (
        <div className={`navi container${show ? " show" : " hide"}`}>
            {naviData.map((item, index) => {
                return item.initIdentity === permissionTypes.ADMIN ? (
                    <AdminNaviItem key={item.id} id={item.id} path={item.path} />
                ) : (
                    <UserNaviItem key={item.id} id={item.id} path={item.path} />
                );
            })}
        </div>
    );
};
</code>```

css

```<code>.navi.container {
    position: fixed;
    background-color: rgba(0, 0, 0, 0.8);
    height: calc(100% - 70px);
    overflow: hidden;
    width: 300px;
    -webkit-transition: width 2s linear;
    -moz-transition: width 2s linear;
    transition: width 2s linear;
}

.navi.container.hide {
    width: 0px;
    -webkit-transition: width 2s linear;
    -moz-transition: width 2s linear;
    transition: width 2s linear;
}
</code>```

答: It is sufficient to have the transition parameter in the css rule for the initial state, so just erase transition: width 2s linear; and similar (prefixed versions) from  .navi.container.hide

Body:
My css transition not working correctly

when I click the button, the div disappears immediately...

I had tried animation too.

But when the animation finishes, the width becomes 0 immediately.

react

const NaviDrawer = ({ naviData, show }) => {
    return (
        <div className={`navi container${show ? " show" : " hide"}`}>
            {naviData.map((item, index) => {
                return item.initIdentity === permissionTypes.ADMIN ? (
                    <AdminNaviItem key={item.id} id={item.id} path={item.path} />
                ) : (
                    <UserNaviItem key={item.id} id={item.id} path={item.path} />
                );
            })}

    );
};

css

.navi.container {
    position: fixed;
    background-color: rgba(0, 0, 0, 0.8);
    height: calc(100% - 70px);
    overflow: hidden;
    width: 300px;
    -webkit-transition: width 2s linear;
    -moz-transition: width 2s linear;
    transition: width 2s linear;
}

.navi.container.hide {
    width: 0px;
    -webkit-transition: width 2s linear;
    -moz-transition: width 2s linear;
    transition: width 2s linear;
}


问:
How to replace blank lines to word?
I have list

```<code>apple
oranges

banana
</code>```

How to replace blank lines to word "empty"?

```<code>apple
oranges
empty
banana
</code>```

答: On replace dialog (Crtl+H) select "Extended". In "Find what" enter \r\n\r\n. In "Replace with" enter \r\nempty\r\n. And press "Replace", "Replace all" or whatever you need

Title: How to replace blank lines to word?

Body:
I have list

apple
oranges

banana

How to replace blank lines to word "empty"?

apple
oranges
empty
banana


问:
Laravel 5.4 Class 'form' not found
I'm facing problem 'Class 'form' not found'  I'm currently using laravel 5.4. I already have tried maximum efforts to solve.

Thanks

Error is : Whoops, looks like something went wrong.

1/1

FatalErrorException in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23:
  Class 'Form' not found
  in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23

Here is my Comp

```<code>{
    "require": {
       "php": ">=5.6.4",
       "laravel/framework": "5.4.*",
       "laravel/tinker": "~1.0",
       "laravelcollective/html": "^5.4"
    },
}
</code>```

I run the composer update command.

Here is my app.php

```<code>'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Notifications\NotificationServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    'Collective\Html\HtmlServiceProvider',

    /*
     * Package Service Providers...
     */
    Laravel\Tinker\TinkerServiceProvider::class,

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    // App\Providers\BroadcastServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    'Auth' => Illuminate\Support\Facades\Auth::class,
    'Blade' => Illuminate\Support\Facades\Blade::class,
    'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
    'Bus' => Illuminate\Support\Facades\Bus::class,
    'Cache' => Illuminate\Support\Facades\Cache::class,
    'Config' => Illuminate\Support\Facades\Config::class,
    'Cookie' => Illuminate\Support\Facades\Cookie::class,
    'Crypt' => Illuminate\Support\Facades\Crypt::class,
    'DB' => Illuminate\Support\Facades\DB::class,
    'Eloquent' => Illuminate\Database\Eloquent\Model::class,
    'Event' => Illuminate\Support\Facades\Event::class,
    'File' => Illuminate\Support\Facades\File::class,
    'Gate' => Illuminate\Support\Facades\Gate::class,
    'Hash' => Illuminate\Support\Facades\Hash::class,
    'Lang' => Illuminate\Support\Facades\Lang::class,
    'Log' => Illuminate\Support\Facades\Log::class,
    'Mail' => Illuminate\Support\Facades\Mail::class,
    'Notification' => Illuminate\Support\Facades\Notification::class,
    'Password' => Illuminate\Support\Facades\Password::class,
    'Queue' => Illuminate\Support\Facades\Queue::class,
    'Redirect' => Illuminate\Support\Facades\Redirect::class,
    'Redis' => Illuminate\Support\Facades\Redis::class,
    'Request' => Illuminate\Support\Facades\Request::class,
    'Response' => Illuminate\Support\Facades\Response::class,
    'Route' => Illuminate\Support\Facades\Route::class,
    'Schema' => Illuminate\Support\Facades\Schema::class,
    'Session' => Illuminate\Support\Facades\Session::class,
    'Storage' => Illuminate\Support\Facades\Storage::class,
    'URL' => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,
    'FORM' => 'Collective\Html\FormFacade',
    'HTML' => 'Collective\Html\HtmlFacade',
],

];
</code>```

using form in formupload.blade.php

```<code>@if(isset($success))
    <div class="alert alert-success"> {{$success}} </div>
@endif
    {!! Form::open(['action'=>'ImageController@store', 'files'=>true]) !!}

    <div class="form-group">
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title', null, ['class'=>'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::label('description', 'Description:') !!}
        {!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>5] ) !!}
    </div>

    <div class="form-group">
        {!! Form::label('image', 'Choose an image') !!}
        {!! Form::file('image') !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
    </div>

    {!! Form::close() !!}
    <div class="alert-warning">
        @foreach( $errors->all() as $error )
           <br> {{ $error }}
        @endforeach
    </div>

</div>
</code>```

答:
class aliases in the config/app.php

```<code>'Form' => 'Collective\Html\FormFacade',
</code>```

this is working for me

Title: Laravel 5.4 Class 'form' not found

Body:
I'm facing problem 'Class 'form' not found'  I'm currently using laravel 5.4. I already have tried maximum efforts to solve.

Thanks

Error is : Whoops, looks like something went wrong.

1/1

FatalErrorException in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23:
  Class 'Form' not found
  in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23

Here is my Comp

{
    "require": {
       "php": ">=5.6.4",
       "laravel/framework": "5.4.*",
       "laravel/tinker": "~1.0",
       "laravelcollective/html": "^5.4"
    },
}

I run the composer update command.

Here is my app.php

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Auth\AuthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Notifications\NotificationServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    'Collective\Html\HtmlServiceProvider',

    /*
     * Package Service Providers...
     */
    Laravel\Tinker\TinkerServiceProvider::class,

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    // App\Providers\BroadcastServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    'Auth' => Illuminate\Support\Facades\Auth::class,
    'Blade' => Illuminate\Support\Facades\Blade::class,
    'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
    'Bus' => Illuminate\Support\Facades\Bus::class,
    'Cache' => Illuminate\Support\Facades\Cache::class,
    'Config' => Illuminate\Support\Facades\Config::class,
    'Cookie' => Illuminate\Support\Facades\Cookie::class,
    'Crypt' => Illuminate\Support\Facades\Crypt::class,
    'DB' => Illuminate\Support\Facades\DB::class,
    'Eloquent' => Illuminate\Database\Eloquent\Model::class,
    'Event' => Illuminate\Support\Facades\Event::class,
    'File' => Illuminate\Support\Facades\File::class,
    'Gate' => Illuminate\Support\Facades\Gate::class,
    'Hash' => Illuminate\Support\Facades\Hash::class,
    'Lang' => Illuminate\Support\Facades\Lang::class,
    'Log' => Illuminate\Support\Facades\Log::class,
    'Mail' => Illuminate\Support\Facades\Mail::class,
    'Notification' => Illuminate\Support\Facades\Notification::class,
    'Password' => Illuminate\Support\Facades\Password::class,
    'Queue' => Illuminate\Support\Facades\Queue::class,
    'Redirect' => Illuminate\Support\Facades\Redirect::class,
    'Redis' => Illuminate\Support\Facades\Redis::class,
    'Request' => Illuminate\Support\Facades\Request::class,
    'Response' => Illuminate\Support\Facades\Response::class,
    'Route' => Illuminate\Support\Facades\Route::class,
    'Schema' => Illuminate\Support\Facades\Schema::class,
    'Session' => Illuminate\Support\Facades\Session::class,
    'Storage' => Illuminate\Support\Facades\Storage::class,
    'URL' => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,
    'FORM' => 'Collective\Html\FormFacade',
    'HTML' => 'Collective\Html\HtmlFacade',
],

];

using form in formupload.blade.php

@if(isset($success))

 {{$success}}

@endif
    {!! Form::open(['action'=>'ImageController@store', 'files'=>true]) !!}

        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title', null, ['class'=>'form-control']) !!}

        {!! Form::label('description', 'Description:') !!}
        {!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>5] ) !!}

        {!! Form::label('image', 'Choose an image') !!}
        {!! Form::file('image') !!}

        {!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}

    {!! Form::close() !!}

        @foreach( $errors->all() as $error )

 {{ $error }}
        @endforeach

Body:
class aliases in the config/app.php

'Form' => 'Collective\Html\FormFacade',

this is working for me


问:
How to focus Textbox with Alt + letter
I need to quick focus the text box using Alt+Letter combination. In my form for each textbox is a label. For this label I can specify name as '&My Label' and M letter will be underlined when I press the Alt button. But how I can focus the textbox (in winforms)?

P.S. As I remember WPF has possibility to bind label with textbox. And if label get focus textbox will get focus automatically.

答:
You need to set the Tab Index. It will automatically handled. You can view/set the Tab index by

View > Tab Order menu

Title: How to focus Textbox with Alt + letter


问:
How to post image to instagram Feed Directly in Swift?
is there any way to share image to instagram feed directly. I can Only Share image using default share functionality i m using swift 5 and xcode 11</p>

答: it is not possible to post images/video to the Instagram app directly. Instead you can pass the image/video to the app and follow the process of manually posting to Instagram normally, there is another catch as well you cannot pass the title (caption) either you would have to copy the text to clipboard and on the final process of posting you can paste that text from clipboard.</p>


问:
Internal Server Error(500) while running load test in JMETER

I am unable to get response from server so how will correlate dynamic values too

答:
As per HTTP Status Code 500 description:

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.

This error response is a generic "catch-all" response. Usually, this indicates the server cannot find a better 5xx error code to response. Sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future.

If your test works fine with 1-2 users and you're seeing this HTTP 500 error only when your application is under the load, most probably your application gets overloaded hence fails to provide valid response.

You can already report it as the bug, or if you want you can investigate it a little bit further, to wit:

Use Active Threads Over Time and Response Codes per Second to see when these errors start occurring (i.e. application works fine till 200 concurrent users and after 201 it starts throwing HTTP 500 errors)

Inspect your application logs

Make sure that the application has enough headroom to operate in terms of CPU, RAM, Network, Disk, etc, you can use JMeter PerfMon Plugin for this

Inspect your application middleware configuration and logs (load balancer, application server, database, etc.)

Consider collecting APM and/or profiler tools output during the load test execution, this way you will be able to precisely identify the root cause of the problem


问:
How can i zoom ionic page that contain HTML content?
I am trying load HTML string in ion-content but i am not able to zoom page like mobile safari.

```<code>url: string = "";
    <ion-content padding>
      <div  [innerHTML]="url"></div>
    </ion-content>

url: string = "HTML String";
</code>```

It loads html contant but i am not able to make pinch zoom on text

答:
Please try to add scrollX = "true" to ion-content.

https://ionicframework.com/docs/api/content

Body:
I am trying load HTML string in ion-content but i am not able to zoom page like mobile safari.

url: string = "";
    <ion-content padding>

    </ion-content>

url: string = "HTML String";

It loads html contant but i am not able to make pinch zoom on text


答:
You can use row_number()

```<code>SELECT SUM(price*quantity) + SUM(CASE WHEN rn = 1 THEN fee END) AS RESULT
FROM   (SELECT *,ROW_NUMBER() OVER ( partition BY id_test) rn
        FROM   test) m
</code>```

CHECK DEMO HERE

OUTPUT

```<code>Result
2146.67
</code>```

Title: SQL Query SUM with conditions

Body:
I'm having some difficulties finding the good query I need, looking for help.
After multiple JOIN and a lot of WHERE, I have this columns and values :

+---------+----------+--------+-------+
| id_test | quantity | price  |  fee  |
+---------+----------+--------+-------+
| "1-3"   |        1 | 33.52  | 29.00 |
| "1-5"   |        1 | 33.52  | 29.00 |
| "1-6"   |        1 | 33.52  | 29.00 |
| "1-8"   |        1 | 86.49  | 29.00 |
| "19-1"  |        1 | 176.54 | 29.00 |
| "19-4"  |        1 | 176.54 | 29.00 |
| "19-5"  |        4 | 176.54 | 29.00 |
| "19-6"  |        1 | 199.47 | 29.00 |
| "19-6"  |        1 | 176.54 | 29.00 |
| "20-10" |        2 | 72.67  | 29.00 |
| "20-11" |        2 | 18.95  | 29.00 |
| "20-9"  |        1 | 22.13  | 29.00 |
+---------+----------+--------+-------+

Each id_test object as a quantity, a price and a fee. I would like to SUM everything so to have a global price : (quantity*price)+fee
The thing is, and that's where I'm stuck, the fee has to be added only once by id_test. Yet, I have here two id_test "19-6".

If I SUM everything I have 1827.67 (price*quantity) + 348 (fee).

Since I have two "19-6", I need 1827.67 (price*quantity) + 319 (fee).

How would you do in SQL ?

Thanks

Body:
You can use row_number()

SELECT SUM(price*quantity) + SUM(CASE WHEN rn = 1 THEN fee END) AS RESULT
FROM   (SELECT *,ROW_NUMBER() OVER ( partition BY id_test) rn
        FROM   test) m

CHECK DEMO HERE

OUTPUT

Result
2146.67


问:
Autocad 2018 NETLOAD not showing my command method
I'm trying to make a plug in for Autocad 2018 with Visual Studio 2019 using .Net
Firstly, I am getting a warning in VS when the debug is "Any CPU" the bug goes off when I switch to x64.
After building the project and having the .dll file and I go to Autocad and load it using NETLOAD command, when I try to load my method or "CommandMethod" it doesn't show up.

I tried changing the .Net Framework to whatever version I have from 4.7.2 to 4.5

Tried different codes from other sources and still no results
Should I use a higher version of AutoCad? or should I use a lower version of VS like 2017?
What could be the problem?
Here's the code:

```<code>using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices.Core;

[assembly: CommandClass(typeof(Testing.Class1))]
   namespace Testing
{
    public class Class1
    {
        [CommandMethod("MyFirstCommand")]
        public void my()
        {

        Document doc=Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor edt = doc.Editor;

        using (Transaction trans=db.TransactionManager.StartTransaction())
        {
            try
            {

                BlockTable bt;
                bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr;
                btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                // send message to the user
                edt.WriteMessage("\nDrawing a line objet");

                Point3d pt1 = new Point3d(0, 0, 0);
                Point3d pt2 = new Point3d(100, 0, 0);

                Line ln = new Line(pt1, pt2);
                ln.ColorIndex = 1;
                btr.AppendEntity(ln);
                trans.AddNewlyCreatedDBObject(ln, true);
                trans.Commit();
            }
            catch (System.Exception e)
            {
                edt.WriteMessage("Error Encountered" + e.Message);
                trans.Abort();
            }
        }
        edt.WriteMessage("Script loaded");

    }

}
</code>```

}

答: class where You define [CommandMethod("Command_Name")] must be public

Body:
I'm trying to make a plug in for Autocad 2018 with Visual Studio 2019 using .Net
Firstly, I am getting a warning in VS when the debug is "Any CPU" the bug goes off when I switch to x64.
After building the project and having the .dll file and I go to Autocad and load it using NETLOAD command, when I try to load my method or "CommandMethod" it doesn't show up.

I tried changing the .Net Framework to whatever version I have from 4.7.2 to 4.5

Tried different codes from other sources and still no results
Should I use a higher version of AutoCad? or should I use a lower version of VS like 2017?
What could be the problem?
Here's the code:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices.Core;

[assembly: CommandClass(typeof(Testing.Class1))]
   namespace Testing
{
    public class Class1
    {
        [CommandMethod("MyFirstCommand")]
        public void my()
        {

        Document doc=Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor edt = doc.Editor;

        using (Transaction trans=db.TransactionManager.StartTransaction())
        {
            try
            {

                BlockTable bt;
                bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr;
                btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                // send message to the user
                edt.WriteMessage("\nDrawing a line objet");

                Point3d pt1 = new Point3d(0, 0, 0);
                Point3d pt2 = new Point3d(100, 0, 0);

                Line ln = new Line(pt1, pt2);
                ln.ColorIndex = 1;
                btr.AppendEntity(ln);
                trans.AddNewlyCreatedDBObject(ln, true);
                trans.Commit();
            }
            catch (System.Exception e)
            {
                edt.WriteMessage("Error Encountered" + e.Message);
                trans.Abort();
            }
        }
        edt.WriteMessage("Script loaded");

    }

}

}


问:
Compare line by line within a linux file
I have a file (test1.txt) like this:

```<code>100 100
200 200
300 HR
400 IT
500 500
600 600
</code>```

And I want to desired output like this:

```<code>100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0
</code>```

I already try to run this command:

```<code>#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi
</code>```

but the result is not as I expected.

答:
Awk is quite good but i wonder if sed can do it? So here it is a variant with sed.

```<code>sed 's/\(^.*\) \1/& 0/;t;s/$/ 1/' file
</code>```

Explanation, first command s/\(^.*\) \1/& 0/

\(^.*\) - define 1st column

\1 - add copy of the 1st column

So we've got a 1st column and a copy of it in a pattern and if patern matched we change it to itself(&) + ' 0' then t will run next s command if firs didn't match. Second command s/$/ 1/ simple add ' 1' to the end of the line.

Body:
I have a file (test1.txt) like this:

100 100
200 200
300 HR
400 IT
500 500
600 600

And I want to desired output like this:

100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0

I already try to run this command:

#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi

but the result is not as I expected.

Body:
Awk is quite good but i wonder if sed can do it? So here it is a variant with sed.

sed 's/\(^.*\) \1/& 0/;t;s/$/ 1/' file

Explanation, first command s/\(^.*\) \1/& 0/

\(^.*\) - define 1st column

\1 - add copy of the 1st column

So we've got a 1st column and a copy of it in a pattern and if patern matched we change it to itself(&) + ' 0' then t will run next s command if firs didn't match. Second command s/$/ 1/ simple add ' 1' to the end of the line.


问:
Extracting a specific substring from a column in sql
i wanted to extract month from a column named implemented_date which specifies the date/time as 2018-02-14 15:00:23. I just want 02 from this data and want to view months of all the rows similarly. How can i do it in mysql

答:
You could use DATE_FORMAT here with the mask %m, which would also pad the month number to two digits:

```<code>SELECT DATE_FORMAT('2018-02-14 15:00:23', '%m');
</code>```

This prints 02 as the result set.

Body:
You could use DATE_FORMAT here with the mask %m, which would also pad the month number to two digits:

SELECT DATE_FORMAT('2018-02-14 15:00:23', '%m');

This prints 02 as the result set.


问:
Update AppStore connect build version
Our app was uploaded to our AppStore connect account with incorrect version. Supposedly the app should have a version 1001.200211, but we incorrectly entered 1010.200211 which is too large.

The first number in our version 1001 indicates the iteration number the release happen, the expected next version would be 1002 or 1003 but since we already entered 1010.200211 the next release versions no longer valid and will not be accepted!

Is there a way to update the build version after it has been uploaded in our AppStore connect account?

答: There is currently no way to change the build version of an app. You may be able to contact Apple Support to help you with this by deleting that binary but there's no way to do this yourself.</p>

Title: Update AppStore connect build version


问:
File Not Found Error for displaying images using Tkinter
So I have a list of files and a random file is selected then the image should be displayed.

The code I has thus far is as follows:

```<code>    def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(question))
        img.place(x=100, y=100)
</code>```

I have checked each section individually whilst implementing it and all the correct files are put into a list as I want them to also a random file is selected when I want it to be but the issue is that I get an error message everytime I run it saying:

```<code> File "C:\Users\cj_he\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2809, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Particle Q3.png'
</code>```

which I don't understand because I can go into my files and I can see the file is there and I can open it but for some reason python can't find the file. I am using the PyCharm IDE. Any suggestions on what the issue is?

答:
While listing you are giving a path. But while reading the file you are passing just file name. You need to append path before file name during opening file.

Try this :

```<code>import os

def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(os.path.join(examQ_dir, question)))

</code>```

Body:
So I have a list of files and a random file is selected then the image should be displayed.

The code I has thus far is as follows:

    def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(question))
        img.place(x=100, y=100)

I have checked each section individually whilst implementing it and all the correct files are put into a list as I want them to also a random file is selected when I want it to be but the issue is that I get an error message everytime I run it saying:

 File "C:\Users\cj_he\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2809, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Particle Q3.png'

which I don't understand because I can go into my files and I can see the file is there and I can open it but for some reason python can't find the file. I am using the PyCharm IDE. Any suggestions on what the issue is?

Body:
While listing you are giving a path. But while reading the file you are passing just file name. You need to append path before file name during opening file.

Try this :

import os

def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(os.path.join(examQ_dir, question)))


问:
Android 8: Cleartext HTTP traffic not permitted
I had reports from users with Android 8 that my app (that uses back-end feed) does not show content. After investigation I found following Exception happening on Android 8:

```<code>08-29 12:03:11.246 11285-11285/ E/: [12:03:11.245, main]: Exception: IOException java.io.IOException: Cleartext HTTP traffic to * not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.doConnection(AbstractHttpAsyncTask.java:207)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.extendedDoInBackground(AbstractHttpAsyncTask.java:102)
at com.deiw.android.generic.tasks.AbstractAsyncTask.doInBackground(AbstractAsyncTask.java:88)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
</code>```

(I've removed package name, URL and other possible identifiers)

On Android 7 and lower everything works, I do not set android:usesCleartextTraffic in Manifest (and setting it to true does not help, that is the default value anyway), neither do I use Network Security Information. If I call NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(), it returns false for Android 8, true for older version, using the same apk file.
I tried to find some mention of this on Google info about Android O, but without success.

答:
```<code> cleartext support is disabled by default.Android in 9 and above

 Try This one I hope It will work fine

1 Step:->  add inside android build gradle (Module:App)
            useLibrary 'org.apache.http.legacy'

  android {
               compileSdkVersion 28
              useLibrary 'org.apache.http.legacy'

          }
</code>```

Then 2 Step:-> manifest
   add inside manifest   application tag

```<code><application
    android:networkSecurityConfig="@xml/network_security_config">//add drawable goto Step 4

   // Step --->3  add to top this line
     <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />

</application>
</code>```

//Step 4-->> Create Drawable>>Xml file>>name as>> network_security_config.xml

```<code>   <?xml version="1.0" encoding="utf-8"?>
   <network-security-config>
      <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
           <certificates src="system" />
        </trust-anchors>
      </base-config>
    </network-security-config>
</code>```

Body:
I had reports from users with Android 8 that my app (that uses back-end feed) does not show content. After investigation I found following Exception happening on Android 8:

08-29 12:03:11.246 11285-11285/ E/: [12:03:11.245, main]: Exception: IOException java.io.IOException: Cleartext HTTP traffic to * not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.doConnection(AbstractHttpAsyncTask.java:207)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.extendedDoInBackground(AbstractHttpAsyncTask.java:102)
at com.deiw.android.generic.tasks.AbstractAsyncTask.doInBackground(AbstractAsyncTask.java:88)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

(I've removed package name, URL and other possible identifiers)

On Android 7 and lower everything works, I do not set android:usesCleartextTraffic in Manifest (and setting it to true does not help, that is the default value anyway), neither do I use Network Security Information. If I call NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(), it returns false for Android 8, true for older version, using the same apk file.
I tried to find some mention of this on Google info about Android O, but without success.

Body:
 cleartext support is disabled by default.Android in 9 and above

 Try This one I hope It will work fine

1 Step:->  add inside android build gradle (Module:App)
            useLibrary 'org.apache.http.legacy'

  android {
               compileSdkVersion 28
              useLibrary 'org.apache.http.legacy'

          }

Then 2 Step:-> manifest
   add inside manifest   application tag

<application
    android:networkSecurityConfig="@xml/network_security_config">//add drawable goto Step 4

   // Step --->3  add to top this line
     <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />

</application>

//Step 4-->> Create Drawable>>Xml file>>name as>> network_security_config.xml

   <?xml version="1.0" encoding="utf-8"?>
   <network-security-config>
      <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
           <certificates src="system" />
        </trust-anchors>
      </base-config>
    </network-security-config>


问:
Preloading images with JavaScript
Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

```<code>function preloadImage(url)
{
    var img=new Image();
    img.src=url;
}
</code>```

I have an array of image URLs that I loop over and call the preloadImage function for each URL.

答:
```<code>const preloadImage = src =>
  new Promise((resolve, reject) => {
    const image = new Image()
    image.onload = resolve
    image.onerror = reject
    image.src = src
  })

// Preload an image
await preloadImage('https://picsum.photos/100/100')

// Preload a bunch of images in parallel
await Promise.all(images.map(x => preloadImage(x.src)))
</code>```

Title: Preloading images with JavaScript

Body:
Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

function preloadImage(url)
{
    var img=new Image();
    img.src=url;
}

I have an array of image URLs that I loop over and call the preloadImage function for each URL.


问:
CDC Function not displaying information from past day
I'm using SQL Server 2014 (SP2).

I have enabled CDC on a table.  I then want to view all that has happened in the past 24 hours so I'm using the below:

```<code>DECLARE @begin_time DATETIME, @end_time DATETIME, @begin_lsn BINARY(10), @end_lsn BINARY(10);
SELECT @begin_time = GETDATE()-1, @end_time = GETDATE();
SELECT @begin_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than', @begin_time);
SELECT @end_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time);
SELECT *
FROM [MyDatabase].cdc.fn_cdc_get_all_changes_dbo_MyTable(@begin_lsn,@end_lsn,'all')
GO
</code>```

But I keep receiving the below error:

```<code>An insufficient number of arguments were supplied for the procedure or function cdc.fn_cdc_get_all_changes_ ... .
</code>```

However ,the above function is system generated when I enabled CDC and only contains 3 parameters:

```<code>ALTER function [cdc].[fn_cdc_get_all_changes_dbo_MyTable]
(   @from_lsn binary(10),
    @to_lsn binary(10),
    @row_filter_option nvarchar(30)
)
</code>```

Why is the function not working?

答:
If the specified LSN range does not fall within the change tracking
  timeline for the capture instance, the function returns error 208 ("An
  insufficient number of arguments were supplied for the procedure or
  function cdc.fn_cdc_get_all_changes.").

According to this explanation, you might need to determine@begin_time and @end_time
Such as you can specify the begin time and end time according to __$start_lsn of the CDC table. If you execute the following query you will not experience an error.

```<code>DECLARE @begin_time DATETIME, @end_time DATETIME, @begin_lsn BINARY(10), @end_lsn BINARY(10);
--SELECT @begin_time = GETDATE()-1, @end_time = GETDATE();
SELECT @begin_time=sys.fn_cdc_map_lsn_to_time(MIN(__$start_lsn))  FROM AdventureWorks2017.cdc.dbo_MyTable_CT
SELECT @end_time = sys.fn_cdc_map_lsn_to_time(MAX(__$start_lsn)) FROM AdventureWorks2017.cdc.dbo_MyTable_CT
SELECT @begin_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than', @begin_time);
SELECT @end_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time);
SELECT *
FROM AdventureWorks2017.cdc.fn_cdc_get_all_changes_dbo_MyTable(@begin_lsn, @end_lsn, N'all')

+------------------------+------------------------+--------------+----------------+----+----------+------------+-------------------------+
|      __$start_lsn      |       __$seqval        | __$operation | __$update_mask | Id | SomeText | ModifiedBy |      ModifiedDate       |
+------------------------+------------------------+--------------+----------------+----+----------+------------+-------------------------+
| 0x0000002E000070F80004 | 0x0000002E000070F80003 |            2 | 0x0F           |  2 | SomeText | Matt       | 2020-02-18 14:38:00.120 |
+------------------------+------------------------+--------------+----------------+----+----------+------------+-------------------------+
</code>```

Body:
I'm using SQL Server 2014 (SP2).

I have enabled CDC on a table.  I then want to view all that has happened in the past 24 hours so I'm using the below:

DECLARE @begin_time DATETIME, @end_time DATETIME, @begin_lsn BINARY(10), @end_lsn BINARY(10);
SELECT @begin_time = GETDATE()-1, @end_time = GETDATE();
SELECT @begin_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than', @begin_time);
SELECT @end_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time);
SELECT *
FROM [MyDatabase].cdc.fn_cdc_get_all_changes_dbo_MyTable(@begin_lsn,@end_lsn,'all')
GO

But I keep receiving the below error:

An insufficient number of arguments were supplied for the procedure or function cdc.fn_cdc_get_all_changes_ ... .

However ,the above function is system generated when I enabled CDC and only contains 3 parameters:

ALTER function [cdc].[fn_cdc_get_all_changes_dbo_MyTable]
(   @from_lsn binary(10),
    @to_lsn binary(10),
    @row_filter_option nvarchar(30)
)

Why is the function not working?

Body:
If the specified LSN range does not fall within the change tracking
  timeline for the capture instance, the function returns error 208 ("An
  insufficient number of arguments were supplied for the procedure or
  function cdc.fn_cdc_get_all_changes.").

According to this explanation, you might need to determine@begin_time and @end_time
Such as you can specify the begin time and end time according to __$start_lsn of the CDC table. If you execute the following query you will not experience an error.

DECLARE @begin_time DATETIME, @end_time DATETIME, @begin_lsn BINARY(10), @end_lsn BINARY(10);
--SELECT @begin_time = GETDATE()-1, @end_time = GETDATE();
SELECT @begin_time=sys.fn_cdc_map_lsn_to_time(MIN(__$start_lsn))  FROM AdventureWorks2017.cdc.dbo_MyTable_CT
SELECT @end_time = sys.fn_cdc_map_lsn_to_time(MAX(__$start_lsn)) FROM AdventureWorks2017.cdc.dbo_MyTable_CT
SELECT @begin_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than', @begin_time);
SELECT @end_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time);
SELECT *
FROM AdventureWorks2017.cdc.fn_cdc_get_all_changes_dbo_MyTable(@begin_lsn, @end_lsn, N'all')

+------------------------+------------------------+--------------+----------------+----+----------+------------+-------------------------+
|      __$start_lsn      |       __$seqval        | __$operation | __$update_mask | Id | SomeText | ModifiedBy |      ModifiedDate       |
+------------------------+------------------------+--------------+----------------+----+----------+------------+-------------------------+
| 0x0000002E000070F80004 | 0x0000002E000070F80003 |            2 | 0x0F           |  2 | SomeText | Matt       | 2020-02-18 14:38:00.120 |
+------------------------+------------------------+--------------+----------------+----+----------+------------+-------------------------+


问:
Lambda expression for table row & column
I am trying to create constraints for my matrix elements, which should validate themselves with lambda functions before simply changing.

This is an example of what I have at the moment (This function should deliver a coordinate [x,y] that is based on another [x,y]:

```<code>Constraints.append(lambda row,col: [row-1,col+1] )
</code>```

However, executing this results in the following message:

```<code>TypeError: unsupported operand type(s) for -: 'str' and 'int'
</code>```

Also I tried casting, but then I got the following exception:

```<code>Constraints.append(lambda row,col: [(int(row)-1),(int(col)+1)] )
ValueError: invalid literal for int() with base 10: 'N'
</code>```

Does anyone know how to rewrite the lambda function so that it accepts arithmetic to produce a new [x,y] coordinate?

答:
Followed the trace as mkrieger1 suggested. Seemed that the issue was not in the lambda function, but implementing it:

```<code>File "C:/Users/Algorithm.py", line 78, in CheckConsistency
var = _constraint(int(Assignment[0]),int(Assignment[1]))
</code>```

ValueError: invalid literal for int() with base 10: 'N'

```<code>var = _constraint(Assignment[0],Assignment[1])
</code>```

It seems my parameters for Assignment[0] & Assignment[1] were not integers as I expected.

Body:
I am trying to create constraints for my matrix elements, which should validate themselves with lambda functions before simply changing.

This is an example of what I have at the moment (This function should deliver a coordinate [x,y] that is based on another [x,y]:

Constraints.append(lambda row,col: [row-1,col+1] )

However, executing this results in the following message:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

Also I tried casting, but then I got the following exception:

Constraints.append(lambda row,col: [(int(row)-1),(int(col)+1)] )
ValueError: invalid literal for int() with base 10: 'N'

Does anyone know how to rewrite the lambda function so that it accepts arithmetic to produce a new [x,y] coordinate?

Body:
Followed the trace as mkrieger1 suggested. Seemed that the issue was not in the lambda function, but implementing it:

File "C:/Users/Algorithm.py", line 78, in CheckConsistency
var = _constraint(int(Assignment[0]),int(Assignment[1]))

ValueError: invalid literal for int() with base 10: 'N'

var = _constraint(Assignment[0],Assignment[1])

It seems my parameters for Assignment[0] & Assignment[1] were not integers as I expected.


问:
How to find multiple indexes of a letter inside a word? (Python)
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

```<code>for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.
</code>```

Full code:

```<code>#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)
</code>```

答:
Yes, if you instantiate a new_variable to be the secret_word variable before the for loop, the in the line current_word_index = secret_word.find(letter) change secret_word.find(letter) to new_variable .find(letter) then below the if statement write new_variable = new_variable [1:] which will remove the letter just found.

so your code would look something like:

```<code>new_variable  =  secret_word

for i in secret_word
     if user_guess == letter:
            current_word_index = new_variable.find(letter)
               #I would do print(current_word_index) this will show the index
               #Or current_word_index = current_word_index + ',' + new_variable.find(letter)
     new_variable=  new_variable[1:] #this will take away your letter.
</code>```

Body:
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.

Full code:

#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)

Body:
Yes, if you instantiate a new_variable to be the secret_word variable before the for loop, the in the line current_word_index = secret_word.find(letter) change secret_word.find(letter) to new_variable .find(letter) then below the if statement write new_variable = new_variable [1:] which will remove the letter just found.

so your code would look something like:

new_variable  =  secret_word

for i in secret_word
     if user_guess == letter:
            current_word_index = new_variable.find(letter)
               #I would do print(current_word_index) this will show the index
               #Or current_word_index = current_word_index + ',' + new_variable.find(letter)
     new_variable=  new_variable[1:] #this will take away your letter.


问:
Python: Retain a child process after killing the parent process
I am working on a simple flask Application and I have an endpoint which creates a bash session on request. I want the process to be retained even if I kill flask.

The process is started using subprocess.Popen() and I want it to persist even after performing killall python from the terminal.

I tried setting the preexec_fn=os.setsid and preexec_fn=setpgrp argument on Popen but running killall is still killing the bash-shell that I created within my Flask application.

Relevant code:

```<code>def run_command(command):
        Process.proc = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            preexec_fn=os.setsid,
        )

run_command(['bash', '-c', 'for((i=0;i<1000;i++)); do echo $i; sleep 1; done; echo EOF'])
</code>```

I'd appreciate any pointers. Thank you.

答:
Instead of using Popen directly you may want to use subprocess.run() which is recommended in the docs (17.5.1).

```<code># Python3.5 or above:
from subprocess import PIPE, run

def run_command(cmd:str):
    run(cmd, universal_newlines=True)

def run_piped_command(cmd:str):
    result = run(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    return result.stdout, result.stderr
</code>```

If you dont pipe the output as stated by @metatoaster, process will continue executing, and if you run the killall python command it will output a nice python: no process found message.

Body:
I am working on a simple flask Application and I have an endpoint which creates a bash session on request. I want the process to be retained even if I kill flask.

The process is started using subprocess.Popen() and I want it to persist even after performing killall python from the terminal.

I tried setting the preexec_fn=os.setsid and preexec_fn=setpgrp argument on Popen but running killall is still killing the bash-shell that I created within my Flask application.

Relevant code:

def run_command(command):
        Process.proc = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            preexec_fn=os.setsid,
        )

run_command(['bash', '-c', 'for((i=0;i<1000;i++)); do echo $i; sleep 1; done; echo EOF'])

I'd appreciate any pointers. Thank you.

Body:
Instead of using Popen directly you may want to use subprocess.run() which is recommended in the docs (17.5.1).

# Python3.5 or above:
from subprocess import PIPE, run

def run_command(cmd:str):
    run(cmd, universal_newlines=True)

def run_piped_command(cmd:str):
    result = run(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    return result.stdout, result.stderr

If you dont pipe the output as stated by @metatoaster, process will continue executing, and if you run the killall python command it will output a nice python: no process found message.


问:
unable to perform time based rolling operations window pandas? Always gives window must be an integer
My data is of the form

```<code>{'transaction': {'merchant': 'merchantA', 'amount': 20, 'time': '2019-02-13T10:00:00.000Z'}}
{'transaction': {'merchant': 'merchantA', 'amount': 90, 'time': '2019-02-13T11:00:00.000Z'}}
.
.
.
</code>```

and I want to perform some rolling operations based upon time. eg the number of transactions that happened in the past 'X' minutes etc.

I have tried multiple ways but can't figure out.
Initially, I gave len(df.index) as index. (don't know if it is efficient to do it like that)

Later I also tried giving data['transaction']['time'] as the index. still, doesn't work.

It always gives the error window must be an integer.

```<code>df = pd.DataFrame()
    df2 = pd.DataFrame()
    for line in sys.stdin:
        data = json.loads(line)
        # df1 = pd.DataFrame(data["transaction"], index=[len(df.index)])
        df1 = pd.DataFrame(data["transaction"], index=[data['transaction']['time']])
        # df1 = pd.DataFrame.from_dict(data, orient='index')
        df = df.append(df1)
        ro = df.rolling('2min', on='time').count()
        # ro = pd.get_dummies(df).rolling('2M').count()
        print(ro)
        # df2 = df.merge(ro)

    # print(df2)
    print(df)
</code>```

What am I missing here?

Thanks

答:
I think you can create list of dictionaries first and pass to DataFrame constructor, convert column time to datetimes and then use rolling:

```<code>out = [json.loads(line)["transaction"] for line in sys.stdin]
df = pd.DataFrame(out)
df['time'] = pd.to_datetime(df['time'])
</code>```

And then:

```<code>df['new'] = df.rolling('2min', on='time')['amount'].count()
print (df)
    merchant  amount                      time  new
0  merchantA      90 2019-02-13 11:00:00+00:00  1.0
1  merchantA      90 2019-02-13 11:00:00+00:00  2.0
</code>```

EDIT:

Your solution should be changed:

```<code>out = []
for line in sys.stdin:
    data = json.loads(line)
    out.append(data["transaction"])

df = pd.DataFrame(out)
df['time'] = pd.to_datetime(df['time'])

df['new'] = df.rolling('2min', on='time')['amount'].count()
</code>```

Body:
My data is of the form

{'transaction': {'merchant': 'merchantA', 'amount': 20, 'time': '2019-02-13T10:00:00.000Z'}}
{'transaction': {'merchant': 'merchantA', 'amount': 90, 'time': '2019-02-13T11:00:00.000Z'}}
.
.
.

and I want to perform some rolling operations based upon time. eg the number of transactions that happened in the past 'X' minutes etc.

I have tried multiple ways but can't figure out.
Initially, I gave len(df.index) as index. (don't know if it is efficient to do it like that)

Later I also tried giving data['transaction']['time'] as the index. still, doesn't work.

It always gives the error window must be an integer.

df = pd.DataFrame()
    df2 = pd.DataFrame()
    for line in sys.stdin:
        data = json.loads(line)
        # df1 = pd.DataFrame(data["transaction"], index=[len(df.index)])
        df1 = pd.DataFrame(data["transaction"], index=[data['transaction']['time']])
        # df1 = pd.DataFrame.from_dict(data, orient='index')
        df = df.append(df1)
        ro = df.rolling('2min', on='time').count()
        # ro = pd.get_dummies(df).rolling('2M').count()
        print(ro)
        # df2 = df.merge(ro)

    # print(df2)
    print(df)

What am I missing here?

Thanks

Body:
I think you can create list of dictionaries first and pass to DataFrame constructor, convert column time to datetimes and then use rolling:

out = [json.loads(line)["transaction"] for line in sys.stdin]
df = pd.DataFrame(out)
df['time'] = pd.to_datetime(df['time'])

And then:

df['new'] = df.rolling('2min', on='time')['amount'].count()
print (df)
    merchant  amount                      time  new
0  merchantA      90 2019-02-13 11:00:00+00:00  1.0
1  merchantA      90 2019-02-13 11:00:00+00:00  2.0

EDIT:

Your solution should be changed:

out = []
for line in sys.stdin:
    data = json.loads(line)
    out.append(data["transaction"])

df = pd.DataFrame(out)
df['time'] = pd.to_datetime(df['time'])

df['new'] = df.rolling('2min', on='time')['amount'].count()


问:
How to categorize a data set without the use of `case when`
Please have a look at my picture in which I have tried to explain what I want to achieve: each column should be the sum of values within the country and category.
How will you suggest I solve this problem? There must be a standard approach by SQL user that I have overlooked.

I know I can work my way around it by something like

case when category = 'CatA' then sum(value) as 'CatA' and then a group by

but when my categories are too many this solution will be messy I will avoid it.

I am using Oracle SQL and Toad

EDIT:
I have two answers but I think I have mis communicated what I whish. Basically what I wish to achieve is to avoid type in the categories manually.

答:
You want conditional aggregation.  The case is the argument to the sum():

```<code>sum(case when category = 'CatA' then value end) as CatA
</code>```

Also, don't use single quotes for column names -- this can leave to unexpected syntax errors and hard-to-debug run-time errors.  Only use single quotes for string and date constants.

Body:
You want conditional aggregation.  The case is the argument to the sum():

sum(case when category = 'CatA' then value end) as CatA

Also, don't use single quotes for column names -- this can leave to unexpected syntax errors and hard-to-debug run-time errors.  Only use single quotes for string and date constants.


问:
Canvas JS chart not displaying when pulling from MySQL
Can anyone see a reason why the below will not display the doughnut chart as it should? Depending on where I close the while it will display the chart but only with the final entry from the database while it prints the other two entries which should be pulled in text as { label: "Ireland",  y: 2 }. I think if have closed the while  in the right place now but nothing displays. ( i know i should be using prepared statements - apologies for inexperience)

```<code> <%

                            Statement stat = null;
                            ResultSet res = null;
                            stat = conn.createStatement();
                            String data = "SELECT COUNT(user_id) AS count_user, user_country FROM user GROUP BY user_country;";

                            res = stat.executeQuery(data);

                            while(res.next()){
                        %>

                        <tr>
                            <td><%= res.getInt("count_user")%></td>
                            <td><%= res.getString("user_country")%></td>
                           </tr>
                        <%
                            }
                         %>
                    </tbody>
                </table>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">

window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer", {
        title:{
            text: "Alumni by country"
                        },

        data:
                      [

                        {
                            // Change type to "doughnut", "line", "splineArea", etc.
                                type: "doughnut",

                                dataPoints:

                                <%  res = stat.executeQuery(data);

                                 while(res.next()){
                                %>

                                [

                { label: "<%= res.getString("user_country")%>",  y: <%= res.getString("count_user")%> }

                                ]

                                                <%}%>
                        }
        ]
    });
    chart.render();
};
}
</script>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</code>```

答: It seems there is a missing comma after every {label ... } block (except the last of course) </p>

Body:
Can anyone see a reason why the below will not display the doughnut chart as it should? Depending on where I close the while it will display the chart but only with the final entry from the database while it prints the other two entries which should be pulled in text as { label: "Ireland",  y: 2 }. I think if have closed the while  in the right place now but nothing displays. ( i know i should be using prepared statements - apologies for inexperience)

 <%

                            Statement stat = null;
                            ResultSet res = null;
                            stat = conn.createStatement();
                            String data = "SELECT COUNT(user_id) AS count_user, user_country FROM user GROUP BY user_country;";

                            res = stat.executeQuery(data);

                            while(res.next()){
                        %>

                            <%= res.getInt("count_user")%>
                            <%= res.getString("user_country")%>

                        <%
                            }
                         %>


问:
How To Return The Right of An Either
I have a value of this type:

List[Either[Error, Files]]
```

<p>and I have a function which checks if there are any errors like this:</p>

<pre class="lang-scala prettyprint-override"><code>  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }
</code>```

Is this the best way to return the List of files if there are no errors in result?

答:
Here is a solution that uses partition:

```<code>private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] =
  result.partition(_.isLeft) match {
    case (Left(error)::_, _) =>
      Left(error)
    case (_, r) =>
      Right(r.collect{ case Right(r) => r })
  }
</code>```

This recursive version is more efficient but perhaps less clear:

```<code>private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
  @annotation.tailrec
  def loop(rem: List[Either[Error, Files]], res: List[Files]): Either[Error, List[Files]] =
    rem match {
      case Left(error) :: _ =>
        Left(error)
      case Right(file) :: tail =>
        loop(tail, file +: res)
      case _ =>
        Right(res.reverse)
    }

  loop(result, Nil)
}
</code>```

Title: How To Return The Right of An Either

Body:
I have a value of this type:

List[Either[Error, Files]]

and I have a function which checks if there are any errors like this:

  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }

Is this the best way to return the List of files if there are no errors in result?

Body:
Here is a solution that uses partition:

private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] =
  result.partition(_.isLeft) match {
    case (Left(error)::_, _) =>
      Left(error)
    case (_, r) =>
      Right(r.collect{ case Right(r) => r })
  }

This recursive version is more efficient but perhaps less clear:

private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
  @annotation.tailrec
  def loop(rem: List[Either[Error, Files]], res: List[Files]): Either[Error, List[Files]] =
    rem match {
      case Left(error) :: _ =>
        Left(error)
      case Right(file) :: tail =>
        loop(tail, file +: res)
      case _ =>
        Right(res.reverse)
    }

  loop(result, Nil)
}


问:
How to create add new contacts in iOS like whatsapp
I want to show an add new contact screen exactly the same as Whatsapp. I tried the default ios contact view controller CNContactViewController. But it is not the same as Whatsapp. Please give me a solution for this.

答:
You could use the Contacts Framework to create the new contact in code, thus allowing you to build your own ViewController from scratch:

https://developer.apple.com/documentation/contacts