问:
How to push code to 2 github repositories at the same time?
I want to push the same code from my local using git + vscode to two github repos with only one command without individually specifying each remote.

I have tried adding 2 remote repos in the config file:
Updated config file:

```<code>cat config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
[remote "origin"]
        url = git@github.com:profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
[remote "github"]
        fetch = +refs/heads/*:refs/remotes/github/*
        url = git@github.com:profile2/e-commerceAPI.git
        pushurl = git@github.com:profile2/e-commerceAPI.git
</code>```

Now when I do git push it only pushes to one repo, this one

profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git

I have tried using git push -u github main but it throws an error:

error: src refspec main does not match any,
error: failed to push some refs to 'github.com:profile2/e-comm..

I have tried with git push -u origin main.
But, I'm completely unfamiliar with the process and this is my 1st attempt. Please suggest. I could also go for a way to push it with multiple steps every time as long as my commits are preserved.

Thank You

答:
The git push command only pushes to one (1) repository, each time you run it.  You pick the (as in, one) repository that it should push to, at the time you run it, using the argument origin or github, given your two remotes:

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

or:

```<code>git push github
</code>```

The former connects to:

```<code>url = git@github.com:profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git
</code>```

and the latter connects to:

```<code>pushurl = git@github.com:profile2/e-commerceAPI.git
</code>```

It uses the pushurl setting since it has a pushurl setting; as origin lacks such a setting, it uses the url setting instead.

In either case, having made this connection, the set of commits and other objects that your git push will send, and the set of requests it will make to whoever answers at the URL, will depend on the last argument.  So if you want to send your master branch commits each time, and have the GitHub repository update its master branch each time, you would use master each time:

```<code>git push origin master
git push github master
</code>```

You should run two commands to update two remotes.  This allows you to detect which one failed, if one fails.

I want to push the same code from my local using git + vscode to two github repos with only one command without individually specifying each remote.

<s>You can't do that.</s>  It turns out that git push will do this, but it's not documented.  As such, it could potentially stop working in the future.  It's certainly safer to do something else: You can, for instance, set up an alias or script that contains the two commands, and run the alias or script, at least from the command line.  Whether, and how, you can do this from the mouse in VS, I have no idea.

To do this with Git, simply set two or more urls or pushurls under any one given remote, e.g.:

```<code>[remote "pushpair"]
    pushurl = git@github.com:profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git
    pushurl = git@github.com:profile2/e-commerceAPI.git
</code>```

Running git push pushpair master will now try to push to each of the two pushurl settings in sequence.  Either can fail; Git will still try the remaining one if one fails.  This is based on the Git source code, not the documentation.

(Note that if you use one pushurl, any url settings are ignored, so both must be a pushurl.  If you use url without pushurl, and set multiple URLs, all will be used.  However, it's not clear how git fetch will behave here.)

Body:
I want to push the same code from my local using git + vscode to two github repos with only one command without individually specifying each remote.

I have tried adding 2 remote repos in the config file:
Updated config file:

cat config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
[remote "origin"]
        url = git@github.com:profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
[remote "github"]
        fetch = +refs/heads/*:refs/remotes/github/*
        url = git@github.com:profile2/e-commerceAPI.git
        pushurl = git@github.com:profile2/e-commerceAPI.git

Now when I do git push it only pushes to one repo, this one

profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git

I have tried using git push -u github main but it throws an error:

error: src refspec main does not match any,
error: failed to push some refs to 'github.com:profile2/e-comm..

I have tried with git push -u origin main.
But, I'm completely unfamiliar with the process and this is my 1st attempt. Please suggest. I could also go for a way to push it with multiple steps every time as long as my commits are preserved.

Thank You

Body:
The git push command only pushes to one (1) repository, each time you run it.  You pick the (as in, one) repository that it should push to, at the time you run it, using the argument origin or github, given your two remotes:

git push origin

or:

git push github

The former connects to:

url = git@github.com:profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git

and the latter connects to:

pushurl = git@github.com:profile2/e-commerceAPI.git

It uses the pushurl setting since it has a pushurl setting; as origin lacks such a setting, it uses the url setting instead.

In either case, having made this connection, the set of commits and other objects that your git push will send, and the set of requests it will make to whoever answers at the URL, will depend on the last argument.  So if you want to send your master branch commits each time, and have the GitHub repository update its master branch each time, you would use master each time:

git push origin master
git push github master

You should run two commands to update two remotes.  This allows you to detect which one failed, if one fails.

I want to push the same code from my local using git + vscode to two github repos with only one command without individually specifying each remote.

<s>You can't do that.</s>  It turns out that git push will do this, but it's not documented.  As such, it could potentially stop working in the future.  It's certainly safer to do something else: You can, for instance, set up an alias or script that contains the two commands, and run the alias or script, at least from the command line.  Whether, and how, you can do this from the mouse in VS, I have no idea.

To do this with Git, simply set two or more urls or pushurls under any one given remote, e.g.:

[remote "pushpair"]
    pushurl = git@github.com:profile1/-MS_E-commerce_Grus_Tep_Online_Full-time_2021_1.git
    pushurl = git@github.com:profile2/e-commerceAPI.git

Running git push pushpair master will now try to push to each of the two pushurl settings in sequence.  Either can fail; Git will still try the remaining one if one fails.  This is based on the Git source code, not the documentation.

(Note that if you use one pushurl, any url settings are ignored, so both must be a pushurl.  If you use url without pushurl, and set multiple URLs, all will be used.  However, it's not clear how git fetch will behave here.)


来源: stackexchange

问:
How to add a close button to ValidationSummary in Silverlight
In Silverlight 3 I am working with a MVVM and also the validation principle that the setters cause an exception if a validation error occurs.  I using the Binding Syntax on the fields using TwoWay i.e.:

```<code><TextBox x:Name="TextBoxClientName" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=true}"  Grid.Column="1" Grid.Row="0" Margin="5 5 5 5" />
</code>```

I validate this property in the ViewModel using the Annotations:

```<code>[Required(ErrorMessage = "Name is required")]
public string Name
{
    get
    {
        return _client.Name;
    }
    set
    {
        Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name", DisplayName="Client Name" });
        _client.Name = value;
    }
}
</code>```

I have the Validation summary and all work well BUT lol, the functionality I am looking for is the following:

You have the Data Form and I want the validation summary to appear over the top ONLY when I click save, and further more I want to implement a close button on that ValidationSummary so the user can continue on with entering and correcting.

I am not sure how to control the visibility or toggle of with the validationsummary, I have tried the Visibility.  The following is code that I tried, WHICH does collect the errors on submit, but I cannot apply them to the validationsummary:

```<code>    public void Save()
    {
        List<ValidationError> errors = new List<ValidationError>();

        foreach (UIElement ui in LayoutRoot.Children)
        {
            FrameworkElement fe = ui as FrameworkElement;

            if (fe != null)
            {
                foreach (ValidationError ve in Validation.GetErrors(fe))
                {
                    errors.Add(ve);
                }
            }
        }

        if (errors.Count > 0)
        {

            Validation1.DataContext = errors;
            Validation1.Filter = ValidationSummaryFilters.All;
        }
        else
        {
            if (Saved != null)
                Saved(this, EventArgs.Empty);
        }

    }
</code>```

Cheers,

Andrew

答:
I guess that by now you're using SIlverlight 4 in your apps. So this answer is for Silverlight 4.

With Silverlight 4 a new interface was added INotifyDataError with 3 methods:

```<code>public interface INotifyDataErrorInfo
{
    // Returns True if the object has at least one property-level or top-level error.
    bool HasErrors { get; }

    // Returns the current set of property-level errors for the provided property name, or
    // the current top-level errors if the argument is null or empty.
    IEnumerable GetErrors(string propertyName);

    // Raised when the set of errors for a particular property has changed, or when the
    // top-level errors have changed.
    event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
}
</code>```

There is vast documentation around the web about that interface and how to use it.

You don't have to use DataAnotations if you don't want to. But if you do, you still will be able to get the validation errors using the Validator class from the System.ComponentModel.DataAnnotations namespace.

If you make your ViewModel implement INotifyDataError and have also a property (in the ViewModel) bool IsValidating or something like that. Then every time the property changes fire the ErrorsChanged event for all the properties that you want to validate (you could get the property names using reflection). And thats it.

Now you just have to make IsValidating = false and then when Save is requested show the errors with IsValidating = true.

Other thing that you could do (and this would work on Silverlight 3) is bind the Visibility of the ValidationSummary to the IsValidating property (using a IValueConverter), and then control this from the ViewModel.

ContentLicense: CC BY-SA 2.5

Body:
In Silverlight 3 I am working with a MVVM and also the validation principle that the setters cause an exception if a validation error occurs.  I using the Binding Syntax on the fields using TwoWay i.e.:

<TextBox x:Name="TextBoxClientName" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=true}"  Grid.Column="1" Grid.Row="0" Margin="5 5 5 5" />

I validate this property in the ViewModel using the Annotations:

[Required(ErrorMessage = "Name is required")]
public string Name
{
    get
    {
        return _client.Name;
    }
    set
    {
        Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name", DisplayName="Client Name" });
        _client.Name = value;
    }
}

I have the Validation summary and all work well BUT lol, the functionality I am looking for is the following:

You have the Data Form and I want the validation summary to appear over the top ONLY when I click save, and further more I want to implement a close button on that ValidationSummary so the user can continue on with entering and correcting.

I am not sure how to control the visibility or toggle of with the validationsummary, I have tried the Visibility.  The following is code that I tried, WHICH does collect the errors on submit, but I cannot apply them to the validationsummary:

    public void Save()
    {
        List<ValidationError> errors = new List<ValidationError>();

        foreach (UIElement ui in LayoutRoot.Children)
        {
            FrameworkElement fe = ui as FrameworkElement;

            if (fe != null)
            {
                foreach (ValidationError ve in Validation.GetErrors(fe))
                {
                    errors.Add(ve);
                }
            }
        }

        if (errors.Count > 0)
        {

            Validation1.DataContext = errors;
            Validation1.Filter = ValidationSummaryFilters.All;
        }
        else
        {
            if (Saved != null)
                Saved(this, EventArgs.Empty);
        }

    }

Cheers,

Andrew

Body:
I guess that by now you're using SIlverlight 4 in your apps. So this answer is for Silverlight 4.

With Silverlight 4 a new interface was added INotifyDataError with 3 methods:

public interface INotifyDataErrorInfo
{
    // Returns True if the object has at least one property-level or top-level error.
    bool HasErrors { get; }

    // Returns the current set of property-level errors for the provided property name, or
    // the current top-level errors if the argument is null or empty.
    IEnumerable GetErrors(string propertyName);

    // Raised when the set of errors for a particular property has changed, or when the
    // top-level errors have changed.
    event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
}

There is vast documentation around the web about that interface and how to use it.

You don't have to use DataAnotations if you don't want to. But if you do, you still will be able to get the validation errors using the Validator class from the System.ComponentModel.DataAnnotations namespace.

If you make your ViewModel implement INotifyDataError and have also a property (in the ViewModel) bool IsValidating or something like that. Then every time the property changes fire the ErrorsChanged event for all the properties that you want to validate (you could get the property names using reflection). And thats it.

Now you just have to make IsValidating = false and then when Save is requested show the errors with IsValidating = true.

Other thing that you could do (and this would work on Silverlight 3) is bind the Visibility of the ValidationSummary to the IsValidating property (using a IValueConverter), and then control this from the ViewModel.

ContentLicense: CC BY-SA 3.0


问:
Interpret bytes in a string as RGB in Python
I was wondering if this was possible.
I'm currently drafting a simple project that would transform my text files into images by using the values of the characters to determine the RGB values of the outputted image.

I know it sounds counterintuitive and no, I don't want to print a string into an image file, I want the text itself to determine the RGB values of each pixel. This is just a rough idea and is far from refined.

I just want a simple program that will work as a proof of concept.

Code so far:

#first contact
from ctypes import sizeof
from PIL import Image
import math as m

def test():
    f='qran.txt'
    file = open(f)
    text = file.read()
    file.close()            # this is dumb, should just read from file instead of dumping it into a
    text = list(text)       #rudimentary fix, turn text into list so we can manage the characters
    size = m.floor(m.sqrt(len(text)//3))     #round the value for a square image
    print(size)
    # for elem in text:
    #     print(ord(elem))

    img =  Image.new('RGB', (size,size))
    pixels = img.load() # create the pixel map
    c = 0
    for i in range(img.size[0]):    # for every col:
        for j in range(img.size[1]):    # For every row
            pixels[i,j] = (ord(text[c]), ord(text[c+1]), ord(text[c+2])) # set the colour accordingly
            c+=1
        c+=1
    img.show()
    img.save('qran.png')

test()
```

As you can see right now my idea is working as a rough concept. You can copy the quran in plaintext and paste it in the same folder as this simple py program to see this output

The image comes out as dull, since characters are converted into integers and their values are too high, and so most colors come off as light-dark gray.

Are there some libraries that could help with exaggerating the values so that they would come off as more representative? I've thought of multiplying by 10 and truncating the result of inverting the values then applying some filters.

I know its pretty much trial and error by this point (as well as polishing the actual code to provide usable functions that allow tweaking images without editing the function over and over again) but I'd like some outside input from people that have dwelved into image processing and such in python.

I apologize in advance if this post was too wordy or contained some unnecessary tidbits, it's my first post in this community.

答:
Just implementing Christoph's idea in the comments:

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

from PIL import Image
import math as m
import pathlib
import numpy as np

# Load document as bytes
qran = pathlib.Path('qran.txt').read_bytes()
size = m.floor(m.sqrt(len(qran)))     #round the value for a square image

# Make palette image from bytes
img = Image.frombuffer('P', (size,size), qran, "raw", 'P', 0, 1)

# Add random palette of 256 RGB triplets to image
palette = np.random.randint(0,256, 768, np.uint8)
img.putpalette(palette)

img.save('qran.png')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was wondering if this was possible.
I'm currently drafting a simple project that would transform my text files into images by using the values of the characters to determine the RGB values of the outputted image.

I know it sounds counterintuitive and no, I don't want to print a string into an image file, I want the text itself to determine the RGB values of each pixel. This is just a rough idea and is far from refined.

I just want a simple program that will work as a proof of concept.

Code so far:

#first contact
from ctypes import sizeof
from PIL import Image
import math as m

def test():
    f='qran.txt'
    file = open(f)
    text = file.read()
    file.close()            # this is dumb, should just read from file instead of dumping it into a
    text = list(text)       #rudimentary fix, turn text into list so we can manage the characters
    size = m.floor(m.sqrt(len(text)//3))     #round the value for a square image
    print(size)
    # for elem in text:
    #     print(ord(elem))

    img =  Image.new('RGB', (size,size))
    pixels = img.load() # create the pixel map
    c = 0
    for i in range(img.size[0]):    # for every col:
        for j in range(img.size[1]):    # For every row
            pixels[i,j] = (ord(text[c]), ord(text[c+1]), ord(text[c+2])) # set the colour accordingly
            c+=1
        c+=1
    img.show()
    img.save('qran.png')

test()

As you can see right now my idea is working as a rough concept. You can copy the quran in plaintext and paste it in the same folder as this simple py program to see this output

The image comes out as dull, since characters are converted into integers and their values are too high, and so most colors come off as light-dark gray.

Are there some libraries that could help with exaggerating the values so that they would come off as more representative? I've thought of multiplying by 10 and truncating the result of inverting the values then applying some filters.

I know its pretty much trial and error by this point (as well as polishing the actual code to provide usable functions that allow tweaking images without editing the function over and over again) but I'd like some outside input from people that have dwelved into image processing and such in python.

I apologize in advance if this post was too wordy or contained some unnecessary tidbits, it's my first post in this community.

Body:
Just implementing Christoph's idea in the comments:

#!/usr/bin/env python3

from PIL import Image
import math as m
import pathlib
import numpy as np

# Load document as bytes
qran = pathlib.Path('qran.txt').read_bytes()
size = m.floor(m.sqrt(len(qran)))     #round the value for a square image

# Make palette image from bytes
img = Image.frombuffer('P', (size,size), qran, "raw", 'P', 0, 1)

# Add random palette of 256 RGB triplets to image
palette = np.random.randint(0,256, 768, np.uint8)
img.putpalette(palette)

img.save('qran.png')


问:
Can't display the values from my data base with Laravel Livewire
I'm using a Livewire component, this is my code:

Search.php :

```<code><?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}
</code>```

search.blade.php :

```<code><div class="searchcomponent">
    <h1>Search</h1>
    <input wire:model="query" type="text" placeholder="Rechercher...">

    @if(!empty($query))
        <ul>
            @if(!empty($vegetables))
                <div class="vegetables">

                    @foreach($vegetables as $vegetable)
                        <li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
                    @endforeach

                </div>
            @else
                <li>No result</li>
            @endif
       </ul>
    @endif
</div>
</code>```

My vegetable Model:

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

    public function getName($id) {
        return $this->name;
    }
}
</code>```

My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?

答:
Defining public $vegetables; will prevent you from passing it to the view.
Remove that. Also remove your mounting logic.

Thus you should have:

```<code>class Search extends Component
{
    public $query = '';

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}
</code>```

Also make sure you are calling @livewireScripts and  @livewireStyles or their alternative syntaxes <livewire:styles /> <livewire:scripts /> from your main view which uses <livewire:search />.

Edit:

Alternatively, you could also use a public properly and write to it using $this->vegetables like so:

```<code>class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function render()
    {
            $this->vegetables = Vegetable::where('name', 'like', '%' . $this->query . '%')->get()->toArray();
            return view('livewire.search');
    }
}
</code>```

Body:
I'm using a Livewire component, this is my code:

Search.php :

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}

search.blade.php :

Search

    <input wire:model="query" type="text" placeholder="Rechercher...">

    @if(!empty($query))

            @if(!empty($vegetables))

                    @foreach($vegetables as $vegetable)

lunch_dining{{ $vegetable['name'] }}

                    @endforeach

            @else

No result

            @endif

    @endif

My vegetable Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

    public function getName($id) {
        return $this->name;
    }
}

My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?

Body:
Defining public $vegetables; will prevent you from passing it to the view.
Remove that. Also remove your mounting logic.

Thus you should have:

class Search extends Component
{
    public $query = '';

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}

Also make sure you are calling @livewireScripts and  @livewireStyles or their alternative syntaxes <livewire:styles /> <livewire:scripts /> from your main view which uses <livewire:search />.

Edit:

Alternatively, you could also use a public properly and write to it using $this->vegetables like so:

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function render()
    {
            $this->vegetables = Vegetable::where('name', 'like', '%' . $this->query . '%')->get()->toArray();
            return view('livewire.search');
    }
}


问:
How do you determine the version of OCaml or Jane Street Core library at runtime
I am migrating to a recent version of OCaml (and Jane Street's Core modules), but would like my code to continue to compile with older versions. To do so, I would like to create a module with portable functions that map to either the old or new interfaces depending on the version. Querying both the version of OCaml and the version of Jane Street Core would work.

How can we look up the version of the compiler or of Jane Street Core at runtime? I know that I could pass the output of ocamlopt --version via my build system, but ideally I should not have to invoke my programs in a special way.

答:
Sorry to answer a slightly different question, but that might be a XY problem: if you want to build a compatibility package, determining the version of packages at runtime doesn't really help because something like

```<code>let f = if Sys.ocaml_version > ... then new_function else compat_function
</code>```

requires new_function to exist independently of the runtime value of Sys.ocaml_version.

A common solution for compatibility package is to detect version earlier at build time with cppo for instance or using some code generation, see for instance https://github.com/janestreet/result or https://github.com/ocaml/stdlib-shims.

Body:
Sorry to answer a slightly different question, but that might be a XY problem: if you want to build a compatibility package, determining the version of packages at runtime doesn't really help because something like

let f = if Sys.ocaml_version > ... then new_function else compat_function

requires new_function to exist independently of the runtime value of Sys.ocaml_version.

A common solution for compatibility package is to detect version earlier at build time with cppo for instance or using some code generation, see for instance https://github.com/janestreet/result or https://github.com/ocaml/stdlib-shims.


问:
How to tell if an app is a Winforms app or WPF app by looking at project properties
When I look at the project properties in Visual Studio for my particular project, there is a field called Output Type which says Windows Application. Does that automatically tell me that it's a WinForms application? I'm trying to find a way to determine right away if the project is a Winforms application. Yes, I can look at the files and determine that by looking at the forms. But I'm wondering if there is a more obvious way to determine that by simply looking at a project's properties.

The other reason I'm asking is because when I look at the project properties of a WPF application, the Output Type is also Windows Application. The way to determine that it's a WPF app is by looking for XAML files. So is there a simpler technique to determine what type of app it is by looking at project properties?

答:
I do it by using .NET Reflector (it has a 14 Day trial) there i look at the exe and open Refrences and there i can see if it says System.Windows.Forms or not.

Update:
Don't use .NET Reflector. Use JetBrains DotPeek its Free and has no trial.


问:
How can i make transection using .where
Since transaction only accepts DocumentReference so I couldn't handle the .where().

```<code> DocumentReference test1=  FirebaseFirestore.instance.collection("users").doc(currentUser.uid);

Query<Map<String, dynamic>> test2=   FirebaseFirestore.instance.collection("users").where('test',isEqualTo: 'mytest').limit(1);

    return FirebaseFirestore.instance.runTransaction((transaction) async {

      //no problem with this DocumentSnapshot
      DocumentSnapshot _value = await transaction.get(test1);

      //BUT
      //here in test2 will never accept Query<Map<String, dynamic>>
      //since the transaction is only accept DocumentReference
      DocumentSnapshot _value2 = await transaction.get(test2);

      if (_value.exists) {
     //action
      }

    })
</code>```

How can I get the .whereReference into the transaction?

答:
Cloud Firestore doesn't provide a solution in which you can use transactions on documents that are obtained through queries. Please also note that a Transaction object cannot perform a query. The single option that you have is to use transactions on a single individual document.

According to your last comment, since you are using a .limit(1) it means that you need to update a single document, a case in which you can create a reference that points exactly to that document and perform the transaction:

```<code>DocumentReference uidRef =  FirebaseFirestore.instance.collection("users").doc(currentUser.uid);
uidRef.runTransaction(/* ... /*);
</code>```

If you don't know the UID of the user on which you need to perform the transaction, then you should perform the necessary query outside the transaction, get the ID of the document, and perform the transaction right after that. But as you can see, there is no way you can do these two operations in a single go.

Please also remember, that a transaction makes sense to be used only if you need to read some data from a document in order to make a decision before you update it. I'm not 100% sure, but in your particular case, I don't think you do that. You are not using the value of _value in a way you decide what to do with it.  If this is your scenario, a batch write will definitely do the job.

Title: How can i make transection using .where

Body:
Since transaction only accepts DocumentReference so I couldn't handle the .where().

 DocumentReference test1=  FirebaseFirestore.instance.collection("users").doc(currentUser.uid);

Query<Map<String, dynamic>> test2=   FirebaseFirestore.instance.collection("users").where('test',isEqualTo: 'mytest').limit(1);

    return FirebaseFirestore.instance.runTransaction((transaction) async {

      //no problem with this DocumentSnapshot
      DocumentSnapshot _value = await transaction.get(test1);

      //BUT
      //here in test2 will never accept Query<Map<String, dynamic>>
      //since the transaction is only accept DocumentReference
      DocumentSnapshot _value2 = await transaction.get(test2);

      if (_value.exists) {
     //action
      }

    })

How can I get the .whereReference into the transaction?

Body:
Cloud Firestore doesn't provide a solution in which you can use transactions on documents that are obtained through queries. Please also note that a Transaction object cannot perform a query. The single option that you have is to use transactions on a single individual document.

According to your last comment, since you are using a .limit(1) it means that you need to update a single document, a case in which you can create a reference that points exactly to that document and perform the transaction:

DocumentReference uidRef =  FirebaseFirestore.instance.collection("users").doc(currentUser.uid);
uidRef.runTransaction(/* ... /*);

If you don't know the UID of the user on which you need to perform the transaction, then you should perform the necessary query outside the transaction, get the ID of the document, and perform the transaction right after that. But as you can see, there is no way you can do these two operations in a single go.

Please also remember, that a transaction makes sense to be used only if you need to read some data from a document in order to make a decision before you update it. I'm not 100% sure, but in your particular case, I don't think you do that. You are not using the value of _value in a way you decide what to do with it.  If this is your scenario, a batch write will definitely do the job.


问:
CMake error while running flutter desktop application
When I am trying to launch flutter desktop application, this error occurred to me:

"CMake Error at CMakeLists.txt:2 (project):

Generator

Visual Studio 16 2019

could not find any instance of Visual Studio.

Building Windows application...

Exception: Unable to generate build files"

What I did...

1- Installed Visual Studio 2022 with (Desktop development with C++ and Universal Windows Platform development)

2- Run these commands:

flutter config --enable-windows-desktop

flutter create .

flutter run -d windows

Also I tried to use dev channel:

flutter channel dev

flutter upgrade

flutter config--enable-windows-uwp-desktop

And these what I have when I run flutter devices and flutter doctor

flutter devices

4 connected devices:
Windows (desktop)       • windows • windows-x64     • Microsoft
Windows [Version 10.0.22000.318] Windows (UWP) (desktop) • winuwp  •
windows-uwp-x64 • Chrome (web)            • chrome  • web-javascript
• Google Chrome 94.0.4606.81 Edge (web)              • edge    •
web-javascript  • Microsoft Edge 95.0.1020.44

flutter doctor

[√] Flutter (Channel dev, 2.6.0-11.0.pre, on Microsoft Windows
[Version 10.0.22000.318], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK
version 31.0.0)

[√] Chrome - develop for the web

[√] Visual Studio - develop for Windows (Visual Studio Community 2022
17.0.0)

[√] Android Studio (version 2020.3)

[√] VS Code (version 1.61.1)

[√] Connected device (4 available)

• No issues found!

答:
Download Visual Studio 17 2022

Delete CMakeLists.txt from project (path: your_prject_name/windows/CMakeLists.txt)

Run in terminal flutter clean

Then run flutter create .


问:
Is there currently any way to install mypy for python 3.7 and use with PyDev?
I tried to install mypy with "phyton -m pip install mypy" but it fails with an error about typed_ast that says it needs Visual C++ compiler but after installing that the error remains. I found several similar reports and notes that it can't be fixed due to the typed_ast thing, I don't know any details about that.

Is there a way to install mypy manually? Just copy a bunch of files somewhere?

I use Windows 10, Python 3.7, I updated to the latest pip.

Any help or hint is welcome

Thanks a lot

Martin

答:
I found an answer myself.
I have python 3.7-32 installed and there is no appropriate wheel for typed -ast for this. This video
https://www.youtube.com/watch?v=XZrThBBpFlo
explains the problem and also gives a solution. I installed a 32-bit wheel from the link given and then installed mypy again and it finished successfully.
Now I will try mypy.
Good luck</p>


问:
How do I return single orderid having same rank?
I have the following output:

Orderid
Time
State
Order_rank

1
10.15
mfr
1

1
10.15
delivered
1

2
12.10
picked
1

2
12.10
mfr
1

Here I have ranked the order ids wrt to the latest time and put the condition in where clause "where order_rank = 1", but I want to return a single entry for one orderjobid, i.e. for orderid 1 I want to return the delivered state entry and for orderid 2 I want mfr state entry etc.

This is just a sample data, I have more than 1000s of orderids, how do I return single entry for the same rank?

答:
you could try
row_number() over (partition by Orderid order by State)
and select the first one


问:
Windows Batch File: How to dynamically pick up input filenames and also use as the output filename?
I am trying to create a batch file on Windows to run this psiblast application.
An example of the command is as follows:

```<code>psiblast -db swissprot -query ./seq/C3W5S7.FASTA -out ./out/C3W5S7.FASTA
</code>```

The input is the '-query' option and output is the '-out' option.

I have a folder 'seq' that contains all the input data files to query the application. The input files are all named with their unique IDs (e.g. in this case, C3W5S7). How can I pick up this filename dynamically and similarly use it as the filename in the output?

Any help on this will be very much appreciated.

答:
```<code>@ECHO OFF
SETLOCAL
rem The following settings for the source directory, destination directory are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"

FOR %%b IN ("%sourcedir%\*.fasta") DO IF NOT EXIST "%destdir%\%%~nxb" ECHO psiblast -db swissprot -query "%%b" -out "%destdir%\%%~nxb"
GOTO :EOF
</code>```

Note that if you use fixed absolute source and destination names, you can run this batch regardless of your current directory. If you change those names to ".\seq" ".\out" then the directories will be relative to your current directory.

The if not exist statement will NOT run the conversion if the destination filename already exists. This is obviously optional.

Note that the psiblast command is merely Echoed for testing purposes. Remove that echo keyword to run psiblast as listed.

If psiblast is a batch file, replace ECHO with CALL to execute it.

Body:
I am trying to create a batch file on Windows to run this psiblast application.
An example of the command is as follows:

psiblast -db swissprot -query ./seq/C3W5S7.FASTA -out ./out/C3W5S7.FASTA

The input is the '-query' option and output is the '-out' option.

I have a folder 'seq' that contains all the input data files to query the application. The input files are all named with their unique IDs (e.g. in this case, C3W5S7). How can I pick up this filename dynamically and similarly use it as the filename in the output?

Any help on this will be very much appreciated.

Body:
@ECHO OFF
SETLOCAL
rem The following settings for the source directory, destination directory are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"

FOR %%b IN ("%sourcedir%\*.fasta") DO IF NOT EXIST "%destdir%\%%~nxb" ECHO psiblast -db swissprot -query "%%b" -out "%destdir%\%%~nxb"
GOTO :EOF

Note that if you use fixed absolute source and destination names, you can run this batch regardless of your current directory. If you change those names to ".\seq" ".\out" then the directories will be relative to your current directory.

The if not exist statement will NOT run the conversion if the destination filename already exists. This is obviously optional.

Note that the psiblast command is merely Echoed for testing purposes. Remove that echo keyword to run psiblast as listed.

If psiblast is a batch file, replace ECHO with CALL to execute it.


问:
Flink Metrics Web UI don't show double value
How can I see double value in flink web ui on dashboard? Maybe, it's possible with something configuration?

When I tried see metrics, like Meter, on dashboard view only the integer part of number. In log I can see double value:

image with dasboard

image with log

Function with metrics: https://github.com/dedkot01/busting-grain/blob/master/grain-generator/src/main/scala/org/dedkot/CounterProcessFunction.scala

File with Flink config: https://github.com/dedkot01/busting-grain/blob/master/local.conf

Full Cloudflow Sbt Project: https://github.com/dedkot01/busting-grain

If u want run project, just use command in project directory sbt pipeline/runLocal

If it's not possible in Flink Web UI, where it's possible? (maybe in Grafana?)

答:
I'm not found answer how this fix in Flink Web UI.

It's good works in Prometheus and Grafana.

Screenshot from Grafana, value 0.2 is displayed correctly.


问:
How to get a Jupyter Notebook to run with docker run when it already works with docker compose?
I am unable to open Jupyter Notebooks in the web browser when I use a Docker image using the docker run command. I get the following error:

```<code>This site can’t be reached. The webpage at http://127.0.0.1:8888/?token=8543b16468608a7d26b8183256a97ebc3df41bf8838a3729 might be temporarily down or it may have moved permanently to a new web address. ERR_SOCKET_NOT_CONNECTED
</code>```

So far, I noticed it doesn't work for me from Jupyter and Tensorflow docker images. However, if I use the same image tags in a Dockerfile and use the docker-compose command everything works fine.
I also tried building the image and then running the image but that didn't work either.
I build from the Dockerfile:

```<code>docker build -t notebook .
</code>```

and then do

```<code>docker run --rm -p 8888:8888 -v $(pwd):/home/jovyan/work notebook
</code>```

It seems that only using docker-compose works for me when trying to use Jupyter Notebook.  Anybody know why that is?

OS: Ubuntu 20.04 LTS

Computer model HP ZBook

Docker run command and output (doesn't work)

```<code>docker run --rm -p 8888:8888 -v $(pwd):/home/jovyan/work jupyter/minimal-notebook:notebook-6.4.3
</code>```

The output from the terminal

```<code>WARN: Jupyter Notebook deprecation notice https://github.com/jupyter/docker-stacks#jupyter-notebook-deprecation-notice.
Executing the command: jupyter notebook
[I 14:17:21.359 NotebookApp] Writing notebook server cookie secret to /home/jovyan/.local/share/jupyter/runtime/notebook_cookie_secret
[W 2021-08-31 14:17:21.823 LabApp] 'ip' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-08-31 14:17:21.823 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-08-31 14:17:21.823 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-08-31 14:17:21.823 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[I 2021-08-31 14:17:21.830 LabApp] JupyterLab extension loaded from /opt/conda/lib/python3.9/site-packages/jupyterlab
[I 2021-08-31 14:17:21.831 LabApp] JupyterLab application directory is /opt/conda/share/jupyter/lab
[I 14:17:21.835 NotebookApp] Serving notebooks from local directory: /home/jovyan
[I 14:17:21.835 NotebookApp] Jupyter Notebook 6.4.3 is running at:
[I 14:17:21.835 NotebookApp] http://7f3100bc5b0b:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
[I 14:17:21.835 NotebookApp]  or http://127.0.0.1:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
[I 14:17:21.835 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 14:17:21.838 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///home/jovyan/.local/share/jupyter/runtime/nbserver-8-open.html
    Or copy and paste one of these URLs:
        http://7f3100bc5b0b:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
     or http://127.0.0.1:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
</code>```

When I open the browser with the link I get

```<code>This site can’t be reached The webpage at http://127.0.0.1:8888/?token=8543b16468608a7d26b8183256a97ebc3df41bf8838a3729 might be temporarily down or it may have moved permanently to a new web address.
    ERR_SOCKET_NOT_CONNECTED
</code>```

Docker compose command and output (works)

I have a docker-compose.yml file with

version: "3.2"

services:
  jupyter:  # you can change this "jupyter" service to whatever you want.
    build:
      context: ./docker-folder  # this is where the build directory is aka. Dockerfile.
    image: compose-test
    volumes:
      - "./:/home/jovyan"
    ports:
     - "8888:8888"
```
<p>A Dockerfile with the following contents in a folder called docker-folder</p>
```FROM jupyter/minimal-notebook:notebook-6.4.3
```
<p>In the terminal, I use the following commands</p>
```docker-compose build && docker-compose up
```
<p>The jupyter notebook opens in the web browser with no problems. The output in the terminal is the following</p>
```Creating network "desktop_default" with the default driver
Creating desktop_jupyter_1 ... done
Attaching to desktop_jupyter_1
jupyter_1  | WARN: Jupyter Notebook deprecation notice https://github.com/jupyter/docker-stacks#jupyter-notebook-deprecation-notice.
jupyter_1  | Executing the command: jupyter notebook
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'ip' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [I 2021-08-31 14:25:26.654 LabApp] JupyterLab extension loaded from /opt/conda/lib/python3.9/site-packages/jupyterlab
jupyter_1  | [I 2021-08-31 14:25:26.654 LabApp] JupyterLab application directory is /opt/conda/share/jupyter/lab
jupyter_1  | [I 14:25:26.659 NotebookApp] Serving notebooks from local directory: /home/jovyan
jupyter_1  | [I 14:25:26.659 NotebookApp] Jupyter Notebook 6.4.3 is running at:
jupyter_1  | [I 14:25:26.659 NotebookApp] http://bf12dc888bfb:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  | [I 14:25:26.659 NotebookApp]  or http://127.0.0.1:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  | [I 14:25:26.659 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
jupyter_1  | [C 14:25:26.663 NotebookApp]
jupyter_1  |
jupyter_1  |     To access the notebook, open this file in a browser:
jupyter_1  |         file:///home/jovyan/.local/share/jupyter/runtime/nbserver-7-open.html
jupyter_1  |     Or copy and paste one of these URLs:
jupyter_1  |         http://bf12dc888bfb:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  |      or http://127.0.0.1:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  | [I 14:25:28.996 NotebookApp] 302 GET /?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581 (172.23.0.1) 0.960000ms
jupyter_1  | /opt/conda/lib/python3.9/json/encoder.py:257: UserWarning: date_default is deprecated since jupyter_client 7.0.0. Use jupyter_client.jsonutil.json_default.
jupyter_1  |   return _iterencode(o, 0)
```

Then I close it all down with

docker-compose down -v

答:
ANSWER: Apparently, this problem is caused by my VPN (I use Express VPN but not sure if also applies to other VPNs). Everything works fine if I turn my computer on and do docker run .... If I turn my VPN on, the error will occur. Even if I turn my VPN off, the error will continue to occur. However, if I restart my computer and do the docker run command again, everything works completely fine.

I'm not sure why but I never get errors when I use my docker-compose file, it always works.

Body:
I am unable to open Jupyter Notebooks in the web browser when I use a Docker image using the docker run command. I get the following error:

This site can’t be reached. The webpage at http://127.0.0.1:8888/?token=8543b16468608a7d26b8183256a97ebc3df41bf8838a3729 might be temporarily down or it may have moved permanently to a new web address. ERR_SOCKET_NOT_CONNECTED

So far, I noticed it doesn't work for me from Jupyter and Tensorflow docker images. However, if I use the same image tags in a Dockerfile and use the docker-compose command everything works fine.
I also tried building the image and then running the image but that didn't work either.
I build from the Dockerfile:

docker build -t notebook .

and then do

docker run --rm -p 8888:8888 -v $(pwd):/home/jovyan/work notebook

It seems that only using docker-compose works for me when trying to use Jupyter Notebook.  Anybody know why that is?

OS: Ubuntu 20.04 LTS

Computer model HP ZBook

Docker run command and output (doesn't work)

docker run --rm -p 8888:8888 -v $(pwd):/home/jovyan/work jupyter/minimal-notebook:notebook-6.4.3

The output from the terminal

WARN: Jupyter Notebook deprecation notice https://github.com/jupyter/docker-stacks#jupyter-notebook-deprecation-notice.
Executing the command: jupyter notebook
[I 14:17:21.359 NotebookApp] Writing notebook server cookie secret to /home/jovyan/.local/share/jupyter/runtime/notebook_cookie_secret
[W 2021-08-31 14:17:21.823 LabApp] 'ip' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-08-31 14:17:21.823 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-08-31 14:17:21.823 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[W 2021-08-31 14:17:21.823 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
[I 2021-08-31 14:17:21.830 LabApp] JupyterLab extension loaded from /opt/conda/lib/python3.9/site-packages/jupyterlab
[I 2021-08-31 14:17:21.831 LabApp] JupyterLab application directory is /opt/conda/share/jupyter/lab
[I 14:17:21.835 NotebookApp] Serving notebooks from local directory: /home/jovyan
[I 14:17:21.835 NotebookApp] Jupyter Notebook 6.4.3 is running at:
[I 14:17:21.835 NotebookApp] http://7f3100bc5b0b:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
[I 14:17:21.835 NotebookApp]  or http://127.0.0.1:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
[I 14:17:21.835 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 14:17:21.838 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///home/jovyan/.local/share/jupyter/runtime/nbserver-8-open.html
    Or copy and paste one of these URLs:
        http://7f3100bc5b0b:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122
     or http://127.0.0.1:8888/?token=1eee2aee8a3fcda212f056af931a14b7dd5490846627c122

When I open the browser with the link I get

This site can’t be reached The webpage at http://127.0.0.1:8888/?token=8543b16468608a7d26b8183256a97ebc3df41bf8838a3729 might be temporarily down or it may have moved permanently to a new web address.
    ERR_SOCKET_NOT_CONNECTED

Docker compose command and output (works)

I have a docker-compose.yml file with

version: "3.2"

services:
  jupyter:  # you can change this "jupyter" service to whatever you want.
    build:
      context: ./docker-folder  # this is where the build directory is aka. Dockerfile.
    image: compose-test
    volumes:
      - "./:/home/jovyan"
    ports:
     - "8888:8888"

A Dockerfile with the following contents in a folder called docker-folder

FROM jupyter/minimal-notebook:notebook-6.4.3

In the terminal, I use the following commands

docker-compose build && docker-compose up

The jupyter notebook opens in the web browser with no problems. The output in the terminal is the following

Creating network "desktop_default" with the default driver
Creating desktop_jupyter_1 ... done
Attaching to desktop_jupyter_1
jupyter_1  | WARN: Jupyter Notebook deprecation notice https://github.com/jupyter/docker-stacks#jupyter-notebook-deprecation-notice.
jupyter_1  | Executing the command: jupyter notebook
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'ip' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [W 2021-08-31 14:25:26.648 LabApp] 'port' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release.
jupyter_1  | [I 2021-08-31 14:25:26.654 LabApp] JupyterLab extension loaded from /opt/conda/lib/python3.9/site-packages/jupyterlab
jupyter_1  | [I 2021-08-31 14:25:26.654 LabApp] JupyterLab application directory is /opt/conda/share/jupyter/lab
jupyter_1  | [I 14:25:26.659 NotebookApp] Serving notebooks from local directory: /home/jovyan
jupyter_1  | [I 14:25:26.659 NotebookApp] Jupyter Notebook 6.4.3 is running at:
jupyter_1  | [I 14:25:26.659 NotebookApp] http://bf12dc888bfb:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  | [I 14:25:26.659 NotebookApp]  or http://127.0.0.1:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  | [I 14:25:26.659 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
jupyter_1  | [C 14:25:26.663 NotebookApp]
jupyter_1  |
jupyter_1  |     To access the notebook, open this file in a browser:
jupyter_1  |         file:///home/jovyan/.local/share/jupyter/runtime/nbserver-7-open.html
jupyter_1  |     Or copy and paste one of these URLs:
jupyter_1  |         http://bf12dc888bfb:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  |      or http://127.0.0.1:8888/?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581
jupyter_1  | [I 14:25:28.996 NotebookApp] 302 GET /?token=8376064cc9487deacb8182d280bb07dba6740a69cf890581 (172.23.0.1) 0.960000ms
jupyter_1  | /opt/conda/lib/python3.9/json/encoder.py:257: UserWarning: date_default is deprecated since jupyter_client 7.0.0. Use jupyter_client.jsonutil.json_default.
jupyter_1  |   return _iterencode(o, 0)

Then I close it all down with

docker-compose down -v


问:
How to run any interactive program before sign in to windows or before login?
Basically I want to send Windows Credentials at windows login screen and make it to send password in Password Box and click on login button automatically.
Am making a Project where I need to implement auto login system, when I send Password to windows a program should be there at windows logon screen to receive inputs and send to password entry and click on login button.</p>

答:
Windows Security DONOT allow any problem running before winlogon

You may be needed to write a driver as a HID device,and type password in time.

Check out it in learn.microsoft.com


问:
rake db:migrate doesn't detect new migration?
Experienced with Rails / ActiveRecord 2.1.1

You create a first version with (for example) ruby script\generate scaffold product title:string description:text image_url:string

This create (for example) a migration file called 20080910122415_create_products.rb

You apply the migration with rake db:migrate

Now, you add a field to the product table with ruby script\generate migration add_price_to_product price:decimal

This create a migration file called 20080910125745_add_price_to_product.rb

If you try to run rake db:migrate, it will actually revert the first migration, not apply the next one! So your product table will get destroyed!

But if you ran rake alone, it would have told you that one migration was pending

Pls note that applying rake db:migrate (once the table has been destroyed) will apply all migrations in order.

The only workaround I found is to specify the version of the new migration as in:

```<code>rake db:migrate version=20080910125745
</code>```

So I'm wondering: is this an expected new behavior?

答:
I respectfully disagree Tom! this is a bug !! V3.5.0f is not a valid version for rake migrations. Rake should not use it to migrate:down just because ruby chose to consider that "V3.5.0f".to_i is 0 ...

Rake should loudly complain that VERSION is not valid so that users know what is up
(between you and me, checking that the version is a YYYYMMDD formated timestamp by converting to integer is a bit light)

[Damn IE6 that won't allow me to comment ! and no I can't change browser thanks corporate]

Body:
Experienced with Rails / ActiveRecord 2.1.1

You create a first version with (for example) ruby script\generate scaffold product title:string description:text image_url:string

This create (for example) a migration file called 20080910122415_create_products.rb

You apply the migration with rake db:migrate

Now, you add a field to the product table with ruby script\generate migration add_price_to_product price:decimal

This create a migration file called 20080910125745_add_price_to_product.rb

If you try to run rake db:migrate, it will actually revert the first migration, not apply the next one! So your product table will get destroyed!

But if you ran rake alone, it would have told you that one migration was pending

Pls note that applying rake db:migrate (once the table has been destroyed) will apply all migrations in order.

The only workaround I found is to specify the version of the new migration as in:

rake db:migrate version=20080910125745

So I'm wondering: is this an expected new behavior?

OwnerDisplayName: Jean


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
Make a UI.

Then throw that away, and make another after you tried to use the first one. Then simplify as much as you can. Any time you can programmatically determine what the user wants from inputs, instead of multiple explicit choices, do so. Too many buttons induces paralysis.

OwnerDisplayName: Fedyashev Nikita

LastEditorDisplayName: Gortok

OwnerDisplayName: Kalium


问:
MySQL Not unique table/alias
I looked at the answers of others having the same problem, but I can't figure out how to fix the "Not unique table/alias".

```<code>SELECT m.*, u.*
  FROM ".TABLE_PREFIX."users_medals u
  LEFT JOIN ".TABLE_PREFIX."medals m ON u.medal_id = m.medal_id
  WHERE u.user_id IN (".$post['uid'].")
  AND m.medal_level = (
    SELECT MAX(".TABLE_PREFIX."medals.medal_level) FROM ".TABLE_PREFIX."medals
    LEFT JOIN ".TABLE_PREFIX."medals ON ".TABLE_PREFIX."users_medals.medal_id = ".TABLE_PREFIX."medals.medal_id
    WHERE ".TABLE_PREFIX."users_medals.user_id = u.user_id
    AND ".TABLE_PREFIX."medals.medal_type = m.medal_type
  )
</code>```

TABLE_PREFIX is what my script uses to define the database table prefix.

答:
In the subquery you have two medals tables without aliases. I think the FROM ".TABLE_PREFIX."medals should be FROM ".TABLE_PREFIX."users_medals:

```<code>SELECT m.*, u.*
  FROM ".TABLE_PREFIX."users_medals u
  LEFT JOIN ".TABLE_PREFIX."medals m ON u.medal_id = m.medal_id
  WHERE u.user_id IN (".$post['uid'].")
  AND m.medal_level = (
    SELECT MAX(".TABLE_PREFIX."medals.medal_level) FROM ".TABLE_PREFIX."users_medals
    LEFT JOIN ".TABLE_PREFIX."medals ON ".TABLE_PREFIX."users_medals.medal_id = ".TABLE_PREFIX."medals.medal_id
    WHERE ".TABLE_PREFIX."users_medals.user_id = u.user_id
    AND ".TABLE_PREFIX."medals.medal_type = m.medal_type
  )
</code>```

Title: MySQL Not unique table/alias

Body:
I looked at the answers of others having the same problem, but I can't figure out how to fix the "Not unique table/alias".

SELECT m.*, u.*
  FROM ".TABLE_PREFIX."users_medals u
  LEFT JOIN ".TABLE_PREFIX."medals m ON u.medal_id = m.medal_id
  WHERE u.user_id IN (".$post['uid'].")
  AND m.medal_level = (
    SELECT MAX(".TABLE_PREFIX."medals.medal_level) FROM ".TABLE_PREFIX."medals
    LEFT JOIN ".TABLE_PREFIX."medals ON ".TABLE_PREFIX."users_medals.medal_id = ".TABLE_PREFIX."medals.medal_id
    WHERE ".TABLE_PREFIX."users_medals.user_id = u.user_id
    AND ".TABLE_PREFIX."medals.medal_type = m.medal_type
  )

TABLE_PREFIX is what my script uses to define the database table prefix.

Body:
In the subquery you have two medals tables without aliases. I think the FROM ".TABLE_PREFIX."medals should be FROM ".TABLE_PREFIX."users_medals:

SELECT m.*, u.*
  FROM ".TABLE_PREFIX."users_medals u
  LEFT JOIN ".TABLE_PREFIX."medals m ON u.medal_id = m.medal_id
  WHERE u.user_id IN (".$post['uid'].")
  AND m.medal_level = (
    SELECT MAX(".TABLE_PREFIX."medals.medal_level) FROM ".TABLE_PREFIX."users_medals
    LEFT JOIN ".TABLE_PREFIX."medals ON ".TABLE_PREFIX."users_medals.medal_id = ".TABLE_PREFIX."medals.medal_id
    WHERE ".TABLE_PREFIX."users_medals.user_id = u.user_id
    AND ".TABLE_PREFIX."medals.medal_type = m.medal_type
  )


问:
NoClassDefFoundError: java/time/LocalDateTime
I'm new with Java language. I have developed an example of a maven project and I have added the package LocalDateTime.

The problem is that when I run the program it appears me this error:
NoClassDefFoundError: java/time/LocalDateTime

I have added this line to import the package:

```<code>import java.time.LocalDateTime;
</code>```

I haven't added anything in the pom.xml file because with other packages imports I didn't add anything and it works properly.

Do I need to add some plugin or dependency in pom.xml file regarding to LocalDateTime?

Thanks for your help!

答:
It is a new api in Java.

Please try with java 8.

Body:
I'm new with Java language. I have developed an example of a maven project and I have added the package LocalDateTime.

The problem is that when I run the program it appears me this error:
NoClassDefFoundError: java/time/LocalDateTime

I have added this line to import the package:

import java.time.LocalDateTime;

I haven't added anything in the pom.xml file because with other packages imports I didn't add anything and it works properly.

Do I need to add some plugin or dependency in pom.xml file regarding to LocalDateTime?

Thanks for your help!


问:
Can we add a const to an inherited virtual member function
I am learning inheritance in C++. So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below:

```<code>struct Base
{
  virtual void func(int a)
  {
      std::cout<<"base version called"<<std::endl;
  }
};
struct Derived: Base
{
  void func(int a) const  //note the const here: Is this a new function or this function overrides the old virtual from base
  {
     std::cout<<"derived version called"<<std::endl;
  }
};
</code>```

Note that i have added const for the func member function inside struct Derived. My question is that: is this member function func inside Derive a new(separate from func inside Base) function or does this func in Derived overrides the old virtual func from Base?

PS: My question is not about the meaning of const here since i know that in this context it means a const member function which means that that the object to which this pointer points is treated as const object. My question is whether func inside Derived a different function that the one inside Base.

答:
The member function func inside Derived is a separate/different non-virtual member function from the virtual func inside Base, as explained below.

Explanation

You can confirm this:

by adding the specifier override after const of func in Derived as shown here you will see the error saying

```<code>marked override, but does not override
</code>```

This confirm that the func in Derived does not override the virtual from func from Base.

```<code>struct Derived: Base
{
  void func(int a) const override //added keyword override. This gives error now
  {
     std::cout<<"derived version called"<<std::endl;
  }
};
</code>```

moreover, by adding the specifier final after the const of func in Derived as shown here you will see the error saying

```<code>marked final, but is not virtual
</code>```

This confirm that the func in Derived is a non-virtual member function.

```<code>struct Derived: Base
{
  void func(int a) const final //added keyword final. This gives error now
  {
     std::cout<<"derived version called"<<std::endl;
  }
};
</code>```

Combining these two points, we come to the conclusion that func inside Derived is a non-virtual member function that is separate from the virtual member function func inside Base.

We say that func that belongs to Derived hides the virtual func in Base. So effectively, Derived has two functions named func. One that it inherits from Base which is implicitly virtual and second that it defines which is a nonvirtual.

Also note that there is another way of confirming that the func inside Derived is a nonvirtual member function by just declaring it and not defining it as shown here because we must define a virtual member function. On the other hand if the member function is nonvirtual we can have its declaration without having its definition as long as we do not call that member function.

```<code>struct Derived: Base
{
  void func(int a) const; //note this is a declaration and not a definition. This works as long as you do not call this function. You cannot do this with a virtual member function

};
</code>```

Body:
I am learning inheritance in C++. So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below:

struct Base
{
  virtual void func(int a)
  {
      std::cout<<"base version called"<<std::endl;
  }
};
struct Derived: Base
{
  void func(int a) const  //note the const here: Is this a new function or this function overrides the old virtual from base
  {
     std::cout<<"derived version called"<<std::endl;
  }
};

Note that i have added const for the func member function inside struct Derived. My question is that: is this member function func inside Derive a new(separate from func inside Base) function or does this func in Derived overrides the old virtual func from Base?

PS: My question is not about the meaning of const here since i know that in this context it means a const member function which means that that the object to which this pointer points is treated as const object. My question is whether func inside Derived a different function that the one inside Base.

Body:
The member function func inside Derived is a separate/different non-virtual member function from the virtual func inside Base, as explained below.

Explanation

You can confirm this:

by adding the specifier override after const of func in Derived as shown here you will see the error saying

marked override, but does not override

This confirm that the func in Derived does not override the virtual from func from Base.

struct Derived: Base
{
  void func(int a) const override //added keyword override. This gives error now
  {
     std::cout<<"derived version called"<<std::endl;
  }
};

moreover, by adding the specifier final after the const of func in Derived as shown here you will see the error saying

marked final, but is not virtual

This confirm that the func in Derived is a non-virtual member function.

struct Derived: Base
{
  void func(int a) const final //added keyword final. This gives error now
  {
     std::cout<<"derived version called"<<std::endl;
  }
};

Combining these two points, we come to the conclusion that func inside Derived is a non-virtual member function that is separate from the virtual member function func inside Base.

We say that func that belongs to Derived hides the virtual func in Base. So effectively, Derived has two functions named func. One that it inherits from Base which is implicitly virtual and second that it defines which is a nonvirtual.

Also note that there is another way of confirming that the func inside Derived is a nonvirtual member function by just declaring it and not defining it as shown here because we must define a virtual member function. On the other hand if the member function is nonvirtual we can have its declaration without having its definition as long as we do not call that member function.

struct Derived: Base
{
  void func(int a) const; //note this is a declaration and not a definition. This works as long as you do not call this function. You cannot do this with a virtual member function

};


问:
How to find the process id of a running Java process on Windows? And how to kill the process alone?
I want to kill the particular Java process in Windows, like in Linux (ps -aux to get processid and then kill processid to kill the process).

答:
In windows, we can use the PowerShell to list the java running process. Then using the process id we can kill the process. Please find the below commands that needs to be executed in the PowerShell.

To list the Java Process.

```<code>ps | Where-Object -Property ProcessName -EQ -Value 'Java'
</code>```

To kill the java process with specific id.

```<code>Stop-Process <PID>
</code>```

The above approach worked for me.

Body:
In windows, we can use the PowerShell to list the java running process. Then using the process id we can kill the process. Please find the below commands that needs to be executed in the PowerShell.

To list the Java Process.

ps | Where-Object -Property ProcessName -EQ -Value 'Java'

To kill the java process with specific id.

Stop-Process <PID>

The above approach worked for me.


问:
Invalid hooks call - React Native
I'm new to react native and implementing a flat list. Inside render item of flat list I'm rendering a functional component and I want to use state to change an image if the user selects or deselects it.

The issue I'm facing is that is throws invalid hooks call. I'm tried all the tutorials but it shows the exact same way for describing the state.

```<code>const NewsItem = (props, item, onFavouriteSelect, index) => {

const[isFavourite,setFavourite] = useState(false);

return<Text>Random text for stackoverflow</Text>

}
</code>```

Flat List Code:

```<code>render() {
return (
  <View style={styles.container}>
    {this.state.newsList.length > 0 ? (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={this.state.newsList}
        renderItem={({item, index}) =>
          NewsItem(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.state.isFavourite,
          )
        }
      />
    ) : (
      <LoadingScreen />
    )}
  </View>
);
}
</code>```

Versions of react, react dom and react native are mentioned below:

```<code>"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.67.2",
</code>```

Error it throws is:

```<code>Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
</code>```

Thank you.

Updated Code:

```<code>class HomeScreen extends Component {
state = {
newsList: [],
IdsList: [],
isFavourite: false,
};

isFavouriteItem(index) {
if (this.state.IdsList.indexOf(index) === -1) {
  return false;
} else {
  return true;
}
}

render(){
return(){

 <FlatList
   showsVerticalScrollIndicator={false}
   data={this.state.newsList}
   renderItem={({item, index}) =>
          NewsCell(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.isFavouriteItem(index),
            this.state.isFavourite,
          )
        }
      />

      }}
</code>```

The updated code I've added now works. But is this a good approach?

答:
Use this way</p>
```<code>import NewsItem from './NewsItem';

renderItem={({item, index}) =>
          <NewsItem
            props={this.props}
            item={item}
            onFavouriteSelect={this.onFavouriteSelect}
            index={index}
            isFavourite={this.state.isFavourite},
          )
        }

const NewsItem = ({props, item, onFavouriteSelect, index}) => {

  const[isFavourite,setFavourite] = useState(false);

  return<Text>Random text for stackoverflow</Text>

}
export default NewsItem;
</code>```

Title: Invalid hooks call - React Native

Body:
I'm new to react native and implementing a flat list. Inside render item of flat list I'm rendering a functional component and I want to use state to change an image if the user selects or deselects it.

The issue I'm facing is that is throws invalid hooks call. I'm tried all the tutorials but it shows the exact same way for describing the state.

const NewsItem = (props, item, onFavouriteSelect, index) => {

const[isFavourite,setFavourite] = useState(false);

return<Text>Random text for stackoverflow</Text>

}

Flat List Code:

render() {
return (
  <View style={styles.container}>
    {this.state.newsList.length > 0 ? (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={this.state.newsList}
        renderItem={({item, index}) =>
          NewsItem(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.state.isFavourite,
          )
        }
      />
    ) : (
      <LoadingScreen />
    )}
  </View>
);
}

Versions of react, react dom and react native are mentioned below:

"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.67.2",

Error it throws is:

Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Thank you.

Updated Code:

class HomeScreen extends Component {
state = {
newsList: [],
IdsList: [],
isFavourite: false,
};

isFavouriteItem(index) {
if (this.state.IdsList.indexOf(index) === -1) {
  return false;
} else {
  return true;
}
}

render(){
return(){

 <FlatList
   showsVerticalScrollIndicator={false}
   data={this.state.newsList}
   renderItem={({item, index}) =>
          NewsCell(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.isFavouriteItem(index),
            this.state.isFavourite,
          )
        }
      />

      }}

The updated code I've added now works. But is this a good approach?

Body:
Use this way

import NewsItem from './NewsItem';

renderItem={({item, index}) =>
          <NewsItem
            props={this.props}
            item={item}
            onFavouriteSelect={this.onFavouriteSelect}
            index={index}
            isFavourite={this.state.isFavourite},
          )
        }

const NewsItem = ({props, item, onFavouriteSelect, index}) => {

  const[isFavourite,setFavourite] = useState(false);

  return<Text>Random text for stackoverflow</Text>

}
export default NewsItem;


问:
Chaining the map state with choice state in AWS Step Function
In AWS Step Functions, we have a use case where depending on the value of each item in the ItemsPath, we would like to trigger a different choice of task.

Consider the scenario where ItemsPath has the following:

```<code>[
 {"type":"A", "index":"0"},
 {"type":"B", "index":"1"}
]
</code>```

For type "A" I would want to trigger a lambda of arn "lambda-A", and for type "B" we want to trigger a lambda of arn "lambda-B".

答:
For your case, you can have a map state with a choice state inside which splits the work for A and B as follows:</p>
```<code>{
    "Type": "Choice",
    "Choices": [
        {
            "Variable": "$.type",
            "StringEquals": "A",
            "Next": "Go_to_LambdaA_state"
        }
    ],
    "Default": "Go_to_LambdaB_state"
}
</code>```

Body:
In AWS Step Functions, we have a use case where depending on the value of each item in the ItemsPath, we would like to trigger a different choice of task.

Consider the scenario where ItemsPath has the following:

[
 {"type":"A", "index":"0"},
 {"type":"B", "index":"1"}
]

For type "A" I would want to trigger a lambda of arn "lambda-A", and for type "B" we want to trigger a lambda of arn "lambda-B".

Body:
For your case, you can have a map state with a choice state inside which splits the work for A and B as follows:

{
    "Type": "Choice",
    "Choices": [
        {
            "Variable": "$.type",
            "StringEquals": "A",
            "Next": "Go_to_LambdaA_state"
        }
    ],
    "Default": "Go_to_LambdaB_state"
}


问:
Call specific method on object depending on selected enum value
Let's assume we have an enum, that represents searchable fields:

enum SearchableFields {
    ALL,
    FIELD1,
    FIELD2,
    FIELD3;
}
```
<p>This enum is displayed via a (combobox) selection inside a GUI. At runtime, I want to evaluate the selection of this combobox and search accordingly.</p>
<p>Depending on the selection, I need to retrieve the fields to search from a POJO (example below) via a getter.</p>
<pre class="lang-java prettyprint-override"><code>class FieldPojo {
    private String field1;
    private String field2;
    private String field3;
    ...
    public String getField1() {
        return field1;
    }
    ...
}
</code>```

I currently use a switch statement to evaluate the selection of SelectableFields and to then retrieve the correct field(s) to search:

private String retrieveField(FieldPojo f) {
    switch (selectedField) {
    case ALL:
        return retrieveAll(); // method that retrieves all available fields
    case FIELD1:
        return f.getField1();
    ...
}
```

This does work, however I feel like it's clunky.

Question:

Is there a more concise way to do this without evaluating the enum via a switch? (Java 8)

答:
Given that you can modify all parts of the code, you have several options:

Put the retrieveField into the class FieldPojo and modify it's parameter so it takes the enum SearchableFields as parameter.

Put the fields of FieldPojo as values into a map with a key of type SearchableFields. You can then decide whether you want to have "ALL" as an extra entry of the map or handle it as special case in a method similar to retrieveField. You could use this to have a "default" handling if you want to update the enum but not the FieldPojo class.

You put retrieveField into the class FieldPojo together with the SearchableFields enum - since only FieldPojo knows, which fields it actually provides as searchable fields.

You use introspection to gather the list of possible searchable fields and also access their contents.

Depending on your real requirements (you only showed a very abstract and specific version of them) one or the other method might be "the right one" for you. I would actually prefer the "everything into FieldPojo" as the most robust one, but on the other hand if you are not able to change FieldPojo and have to handle many different classes like it, the introspection variant might be the right one. (Be aware that it is fragile in terms of security and also probably very slow.)

Body:
Let's assume we have an enum, that represents searchable fields:

enum SearchableFields {
    ALL,
    FIELD1,
    FIELD2,
    FIELD3;
}

This enum is displayed via a (combobox) selection inside a GUI. At runtime, I want to evaluate the selection of this combobox and search accordingly.

Depending on the selection, I need to retrieve the fields to search from a POJO (example below) via a getter.

class FieldPojo {
    private String field1;
    private String field2;
    private String field3;
    ...
    public String getField1() {
        return field1;
    }
    ...
}

I currently use a switch statement to evaluate the selection of SelectableFields and to then retrieve the correct field(s) to search:

private String retrieveField(FieldPojo f) {
    switch (selectedField) {
    case ALL:
        return retrieveAll(); // method that retrieves all available fields
    case FIELD1:
        return f.getField1();
    ...
}

This does work, however I feel like it's clunky.

Question:

Is there a more concise way to do this without evaluating the enum via a switch? (Java 8)


问:
How do I configure my Kubernetes cluster to work with Gitlab CI?
I'm learning how to use Kubernetes and Gitlab CI/CD so I installed a Gitlab agent into my Kubernetes cluster by following the documentation. I wrote a simple hello world pipeline to see if it works

```<code>image: "docker.io/ubuntu"

stages:
  - build

build-contabo:
  stage: build
  script:
    - echo "hello world"
</code>```

But the pipeline won't run and complains about missing configuration:

```<code>Running with gitlab-runner 14.6.0 (5316d4ac)
  on vmi769777 NWjdRisx
Preparing the "kubernetes" executor 00:09
WARNING: Namespace is empty, therefore assuming 'default'.
Using Kubernetes namespace: default
ERROR: Preparation failed: getting Kubernetes config: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable
</code>```

I read on how to configure an agent, but could not find anything addressed this error.
I also deployed a hello world kubernetes deployment to check if my cluster does not work, but it ran successfully.

How can I provide configurations so that my pipeline runs?
And is this a problem with the Kubernetes Cluster or the Gitlab configuration?

答:
I found the problem.

So kubectl works because when running it I am in the root user.
This user has a kubernetes config in its home /home/root/.kube.

The gitlab runner runs in a different user, in my case gitlab-runner.
This user doesn't have a kubernetes config dir.

Copying it from root solves the issue: cp -r /home/root/.kube /home/gitlab-runner/.kube

Body:
I'm learning how to use Kubernetes and Gitlab CI/CD so I installed a Gitlab agent into my Kubernetes cluster by following the documentation. I wrote a simple hello world pipeline to see if it works

image: "docker.io/ubuntu"

stages:
  - build

build-contabo:
  stage: build
  script:
    - echo "hello world"

But the pipeline won't run and complains about missing configuration:

Running with gitlab-runner 14.6.0 (5316d4ac)
  on vmi769777 NWjdRisx
Preparing the "kubernetes" executor 00:09
WARNING: Namespace is empty, therefore assuming 'default'.
Using Kubernetes namespace: default
ERROR: Preparation failed: getting Kubernetes config: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable

I read on how to configure an agent, but could not find anything addressed this error.
I also deployed a hello world kubernetes deployment to check if my cluster does not work, but it ran successfully.

How can I provide configurations so that my pipeline runs?
And is this a problem with the Kubernetes Cluster or the Gitlab configuration?


问:
Extract info inside parenthesis in R
I have some rows, some have parenthesis and some don't. Like ABC(DEF) and ABC. I want to extract info from parenthesis:

ABC(DEF) -> DEF

ABC -> NA

I wrote

```<code>gsub(".*\\((.*)\\).*", "\\1",X).
</code>```

It works good for ABC(DEF), but output "ABC" when there is not parenthesis.

答:
Using string_extract() will work.

```<code>library(stringr)

df$`new column` <- str_extract(df$`existing column`,  "(?<=\\().+?(?=\\))")

</code>```

This creates a new column of any text inside parentheses of an existing column. If there is no parentheses in the column, it will fill in NA.

The inspiration for my answer comes from this answer on the original question about this topic

Title: Extract info inside parenthesis in R

Body:
I have some rows, some have parenthesis and some don't. Like ABC(DEF) and ABC. I want to extract info from parenthesis:

ABC(DEF) -> DEF

ABC -> NA

I wrote

gsub(".*\\((.*)\\).*", "\\1",X).

It works good for ABC(DEF), but output "ABC" when there is not parenthesis.

Body:
Using string_extract() will work.

library(stringr)

df$`new column` <- str_extract(df$`existing column`,  "(?<=\\().+?(?=\\))")

This creates a new column of any text inside parentheses of an existing column. If there is no parentheses in the column, it will fill in NA.

The inspiration for my answer comes from this answer on the original question about this topic


问:
running a batch file from C#
UPDATE
** STILL LOOKING FOR A CORRECT ANSWER **
I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }

        }
    }
</code>```

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here.
thanks

答:
It looks like it's running the batch script when the service is first run and then it quits (p.WaitForExit();) before the other functions get the ability to be called. Is that the intended behavior? That would explain why you can see it do the folder operations and not see the script being run.

Try this code to bring up the console window. It should give you an idea of when the batch script is running.

```<code>protected override void OnStart(string[] args)
{
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;

        /*
        This is commented out so we can see what the script is doing
        inside the cmd console.
        */
        //p.StartInfo.RedirectStandardOutput = true;

        p.StartInfo.FileName = "C:\\myFile.bat";
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // p.WaitForExit();
        // Read the output stream first and then wait.

        /*
        Since we aren't redirecting the output, we have to comment out
        this line or we get an error
        */
        //string output = p.StandardOutput.ReadToEnd();

        p.WaitForExit();
}
</code>```

Title: running a batch file from C#

Body:
UPDATE
** STILL LOOKING FOR A CORRECT ANSWER **
I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }

        }
    }

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here.
thanks

Body:
It looks like it's running the batch script when the service is first run and then it quits (p.WaitForExit();) before the other functions get the ability to be called. Is that the intended behavior? That would explain why you can see it do the folder operations and not see the script being run.

Try this code to bring up the console window. It should give you an idea of when the batch script is running.

protected override void OnStart(string[] args)
{
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;

        /*
        This is commented out so we can see what the script is doing
        inside the cmd console.
        */
        //p.StartInfo.RedirectStandardOutput = true;

        p.StartInfo.FileName = "C:\\myFile.bat";
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // p.WaitForExit();
        // Read the output stream first and then wait.

        /*
        Since we aren't redirecting the output, we have to comment out
        this line or we get an error
        */
        //string output = p.StandardOutput.ReadToEnd();

        p.WaitForExit();
}


问:
What are elements in no namespace in CSS?
This is an exemple in CSS Namespaces:

Given the namespace declarations:

@namespace toto "http://toto.example.org";
@namespace "http://example.com/foo";
```

In a context where the default namespace applies

toto|A: represents the name A in the http://toto.example.org namespace.

|B: represents the name B that belongs to no namespace.

*|C: represents the name C in any namespace, including no namespace.

D: represents the name D in the http://example.com/foo namespace.

What is an exemple of B in a HTML document? What is an exemple of |B as a CSS selector?

I tried with a custom element, but it seems declared in the (default) XHTML namespace.

答:
You can't have case B in a pure, valid HTML document. You can in an XML document.

We can add an element in no namespace using createElementNS() in script. (Doing so means the document is no longer valid HTML).

|B {
  color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><B>foo</B>
<script>
  const b = document.body.appendChild(document.createElementNS('', 'B'));
  b.appendChild(document.createTextNode('bar'));
</script></code>```

Body:
This is an exemple in CSS Namespaces:

Given the namespace declarations:

@namespace toto "http://toto.example.org";
@namespace "http://example.com/foo";

In a context where the default namespace applies

toto|A: represents the name A in the http://toto.example.org namespace.

|B: represents the name B that belongs to no namespace.

*|C: represents the name C in any namespace, including no namespace.

D: represents the name D in the http://example.com/foo namespace.

What is an exemple of B in a HTML document? What is an exemple of |B as a CSS selector?

I tried with a custom element, but it seems declared in the (default) XHTML namespace.

Body:
You can't have case B in a pure, valid HTML document. You can in an XML document.

We can add an element in no namespace using createElementNS() in script. (Doing so means the document is no longer valid HTML).

|B {
  color:red;
}

<B>foo</B>
<script>
  const b = document.body.appendChild(document.createElementNS('', 'B'));
  b.appendChild(document.createTextNode('bar'));
</script>