问:
Django Development: Chrome warns "Change Password"
im new at django and for learning i create a fantasy project. By testing my website i was been warned from my Chrome browser that i should change my password. The exact message is

Due to a data breach on a website or in an app your password was disclosed. Chrome recommends changing your password to 127.0.0.1:8000.

is there anything in my code that makes this data breach?

Thanks for helping!

forms.py

```<code>class RegisterForm(forms.Form):

username = forms.CharField(
    label='Benutzername',
    max_length=150,
    required=True,
    widget=forms.TextInput(
        attrs={
            'placeholder': 'Username',
        }
    )
)

email = forms.EmailField(
    label='E-Mail Adresse',
    max_length=254,
    required=True,
    widget=forms.EmailInput(
        attrs={
            'placeholder': 'email@exapmle.com',
        }
    )
)

password = forms.CharField(
    label='Passwort',
    max_length=254,
    required=True,
    widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Password',
        }
    )
)

repeatPassword = forms.CharField(
    label='Passwort wiederholen',
    max_length=254, required=True,
    widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Password',
        }
    )
)

name = forms.CharField(
    label='Nachname',
    max_length=150,
    required=False,
    widget=forms.TextInput(
        attrs={
            'placeholder': 'Last Name',
        }
    )
)

firstName = forms.CharField(
    label='Vorname',
    max_length=150,
    required=False,
    widget=forms.TextInput(
        attrs={
            'placeholder': 'First name',
        }
    )
)

def clean(self):
    cleaned_data = super(RegisterForm, self).clean()
    username = cleaned_data.get('username')
    email = cleaned_data.get('email')
    password = cleaned_data.get('password')
    repeatPassword = cleaned_data.get('repeatPassword')
    name = cleaned_data.get('name')
    firstName = cleaned_data.get('firstName')

    if not username:
        raise forms.ValidationError('Enter Username')

    if User.objects.filter(username=username).exists():
        raise forms.ValidationError("Username is taken by another one")

    if not email:
        raise forms.ValidationError('Enter E-Mail')

    if User.objects.filter(email=email).exists():
        raise forms.ValidationError("E-Mail is taken by another one")

    if not password:
        raise forms.ValidationError('Enter password')

    if not repeatPassword:
        raise forms.ValidationError('Repeat password')

    if password != repeatPassword:
        raise forms.ValidationError('Passwords are not equal')
</code>```

views.py

```<code>def register_view(request):
if request.method == 'POST':
    form = RegisterForm(request.POST)
    if form.is_valid():
        user = User.objects.create_user(username=request.POST['username'], email=request.POST['email'],
                                        password=request.POST['password'], first_name=request.POST['firstName'],
                                        last_name=request.POST['name'])

        user.save()

        # Get Created User from DB
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
        if user:
            # LogIn (create Session etc...)
            login(request, user)

            # open user.html
            return render(request, 'web/user.html')
    return render(request, 'web/register.html', {'form': form})
else:
    form = RegisterForm()
    return render(request, 'web/register.html', {'form': form})
</code>```

答: Your code is fine, Chrome does show such warning when you use a weak password.No need to worry about it.</p>

Body:
im new at django and for learning i create a fantasy project. By testing my website i was been warned from my Chrome browser that i should change my password. The exact message is

Due to a data breach on a website or in an app your password was disclosed. Chrome recommends changing your password to 127.0.0.1:8000.

is there anything in my code that makes this data breach?

Thanks for helping!

forms.py

class RegisterForm(forms.Form):

username = forms.CharField(
    label='Benutzername',
    max_length=150,
    required=True,
    widget=forms.TextInput(
        attrs={
            'placeholder': 'Username',
        }
    )
)

email = forms.EmailField(
    label='E-Mail Adresse',
    max_length=254,
    required=True,
    widget=forms.EmailInput(
        attrs={
            'placeholder': 'email@exapmle.com',
        }
    )
)

password = forms.CharField(
    label='Passwort',
    max_length=254,
    required=True,
    widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Password',
        }
    )
)

repeatPassword = forms.CharField(
    label='Passwort wiederholen',
    max_length=254, required=True,
    widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Password',
        }
    )
)

name = forms.CharField(
    label='Nachname',
    max_length=150,
    required=False,
    widget=forms.TextInput(
        attrs={
            'placeholder': 'Last Name',
        }
    )
)

firstName = forms.CharField(
    label='Vorname',
    max_length=150,
    required=False,
    widget=forms.TextInput(
        attrs={
            'placeholder': 'First name',
        }
    )
)

def clean(self):
    cleaned_data = super(RegisterForm, self).clean()
    username = cleaned_data.get('username')
    email = cleaned_data.get('email')
    password = cleaned_data.get('password')
    repeatPassword = cleaned_data.get('repeatPassword')
    name = cleaned_data.get('name')
    firstName = cleaned_data.get('firstName')

    if not username:
        raise forms.ValidationError('Enter Username')

    if User.objects.filter(username=username).exists():
        raise forms.ValidationError("Username is taken by another one")

    if not email:
        raise forms.ValidationError('Enter E-Mail')

    if User.objects.filter(email=email).exists():
        raise forms.ValidationError("E-Mail is taken by another one")

    if not password:
        raise forms.ValidationError('Enter password')

    if not repeatPassword:
        raise forms.ValidationError('Repeat password')

    if password != repeatPassword:
        raise forms.ValidationError('Passwords are not equal')

views.py

def register_view(request):
if request.method == 'POST':
    form = RegisterForm(request.POST)
    if form.is_valid():
        user = User.objects.create_user(username=request.POST['username'], email=request.POST['email'],
                                        password=request.POST['password'], first_name=request.POST['firstName'],
                                        last_name=request.POST['name'])

        user.save()

        # Get Created User from DB
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
        if user:
            # LogIn (create Session etc...)
            login(request, user)

            # open user.html
            return render(request, 'web/user.html')
    return render(request, 'web/register.html', {'form': form})
else:
    form = RegisterForm()
    return render(request, 'web/register.html', {'form': form})


来源: stackexchange

问:
Why can't Bundler locate this gem?
Why can't bundler locate the Mechanize gem?

The following is in my Rails project's Gemfile:

```<code>gem 'mechanize', :git => 'git://github.com/tenderlove/mechanize.git'
</code>```

Running bundle install throws the following error:

```<code>Updating git://github.com/tenderlove/mechanize.git
Fetching source index for http://rubygems.org/
Could not find gem 'mechanize (>= 0)' in git://github.com/tenderlove/mechanize.git (at master).
Source does not contain any versions of 'mechanize (>= 0)'
</code>```

I arrived at this problem after forking the project to make some small changes, but was not able to get bundler to use the github location nor a local path. Why is it that it cannot locate the gem?

If I remove all instructions and simply do gem 'mechanize' then it works flawlessly.

Versions: Bundler 1.0.14 + Rails 3.1 Release Canditate + Ruby 1.8.7 (via RVM) + Debian 5

答:
It looks as though the project is missing a gemspec and one won't be getting added.

You should be able to clone the project into your vendor/gems directory. You will need to create a mechanize.gemspec file, too.
You would then require it in your Gemfile using something like.

```<code>gem 'mechanize',            :path => 'vendor/gems/mechanize'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why can't Bundler locate this gem?

Body:
Why can't bundler locate the Mechanize gem?

The following is in my Rails project's Gemfile:

gem 'mechanize', :git => 'git://github.com/tenderlove/mechanize.git'

Running bundle install throws the following error:

Updating git://github.com/tenderlove/mechanize.git
Fetching source index for http://rubygems.org/
Could not find gem 'mechanize (>= 0)' in git://github.com/tenderlove/mechanize.git (at master).
Source does not contain any versions of 'mechanize (>= 0)'

I arrived at this problem after forking the project to make some small changes, but was not able to get bundler to use the github location nor a local path. Why is it that it cannot locate the gem?

If I remove all instructions and simply do gem 'mechanize' then it works flawlessly.

Versions: Bundler 1.0.14 + Rails 3.1 Release Canditate + Ruby 1.8.7 (via RVM) + Debian 5

Body:
It looks as though the project is missing a gemspec and one won't be getting added.

You should be able to clone the project into your vendor/gems directory. You will need to create a mechanize.gemspec file, too.
You would then require it in your Gemfile using something like.

gem 'mechanize',            :path => 'vendor/gems/mechanize'


问:
Regular expression to handle two different file extensions
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

```<code>if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
</code>```

This handles only the .txt. How can I handle ".txt.gz"
Thanks

答:
I think what you want (following from the direction you were going) is this:

```<code>[\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.[a-zA-Z]{3}(?:$|\\.[a-zA-Z]{2}$)
</code>```

At the end, I have a conditional statement.  It has to either match the end of the string ($) OR it has to match a literal dot followed by 2 letters (\\.[a-zA-Z]{2}).  Remember to escape the ., because in regex . means "match any character".

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}

This handles only the .txt. How can I handle ".txt.gz"
Thanks

Body:
I think what you want (following from the direction you were going) is this:

[\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.[a-zA-Z]{3}(?:$|\\.[a-zA-Z]{2}$)

At the end, I have a conditional statement.  It has to either match the end of the string ($) OR it has to match a literal dot followed by 2 letters (\\.[a-zA-Z]{2}).  Remember to escape the ., because in regex . means "match any character".


问:
Why do I repeatedly get EADDRINUSE errors
I may know the answer to this question but I am looking for confirmation in case I am missing something.

I am in a development mode on a full stack Node/React project. My server is running on port 5000. My client is running on port 3000. I am proxying my frontend routes to node for the actual IO. All of that seems to be running just fine.

I am working from my home office so when I quit work each evening I simply walk away from my work. Sometime later that night my machine logs me out. That is probably NOT a best practice.

The next working day I sit down to work, I login, I execute npm run dev (I'm running concurrently). Typically the front end comes up No Problem. However (even though the app executes properly) my console displays ERRADDRINUSE :::5000.

It looks like everything is going ok but I suppose something may be lying in wait for me. And, it also indicates that it isn't completely benign.

Here is my thought. I do get automatically logged out each evening but apparently that is not necessarily closing the ports down (at least not port 5000). I am thinking that I should probably be performing and actual shut down or restart every evening.

Am I right? And, when you confirm, would you mind including the "why"? I am still learning as I go. Thanks.

答:
ERRADDRINUSE appears when there is already a process listening on port 5000. Check to see if the process is running before you start the node process again.

```<code>ps -A | grep node
</code>```

If the process needs to be restarted for whatever reason you probably want to kill that process first and then try to start it again.

Body:
ERRADDRINUSE appears when there is already a process listening on port 5000. Check to see if the process is running before you start the node process again.

ps -A | grep node

If the process needs to be restarted for whatever reason you probably want to kill that process first and then try to start it again.


问:
How to convert image to pdf using flutter?
I have implemented a app to capture images using camera and display captured image in new page as a Image but I want to display the captured Image(ex:document) as Pdf file(editable).

So how can I convert my image(ex:document) as a pdf file ?

```<code>class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;
  const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Display the Picture')),
      body: Image.file(File(imagePath)),
    );
  }
}
</code>```

答: This flutter printing library talks about To load an image from an ImageProvider: perhaps this might do what you ask, you might be able to extract the PDF after its processed the image

Body:
I have implemented a app to capture images using camera and display captured image in new page as a Image but I want to display the captured Image(ex:document) as Pdf file(editable).

So how can I convert my image(ex:document) as a pdf file ?

class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;
  const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Display the Picture')),
      body: Image.file(File(imagePath)),
    );
  }
}


问:
Search for a key in a list of dictionaries
"trip" is a list of dictionaries.  In this instance, the key "trip_block" only appears in the 6th dictionary.  Why doesn't this work:

```<code>trip[:]['trip_block']
TypeError: list indices must be integers or slices, not str
</code>```

But this does work and returns the value:

```<code>trip[5]['trip_block']
</code>```

Since that key appears in different indexes, I would really like to search for it by using trip[:].  I'm trying to use this in an if statement:

```<code>if trip[:]['trip_block']:
</code>```

答:
trip[:] means you get just a copy of the whole list

You need to iterate over the list...

and because it appears in different indexes you need to store it again in an list.

You can use list comprehension like

```<code>trip_block_items = [item["trip_block"] for item in trip if "trip_block" in item]
</code>```

or a simply a for loop

```<code>trip_block_items = []

for item in trip:
    if "trip_block" in item:
        trip_block_items.append(item["trip_block"])
</code>```

Body:
"trip" is a list of dictionaries.  In this instance, the key "trip_block" only appears in the 6th dictionary.  Why doesn't this work:

trip[:]['trip_block']
TypeError: list indices must be integers or slices, not str

But this does work and returns the value:

trip[5]['trip_block']

Since that key appears in different indexes, I would really like to search for it by using trip[:].  I'm trying to use this in an if statement:

if trip[:]['trip_block']:

Body:
trip[:] means you get just a copy of the whole list

You need to iterate over the list...

and because it appears in different indexes you need to store it again in an list.

You can use list comprehension like

trip_block_items = [item["trip_block"] for item in trip if "trip_block" in item]

or a simply a for loop

trip_block_items = []

for item in trip:
    if "trip_block" in item:
        trip_block_items.append(item["trip_block"])


问:
Rails Ajax pagination/infinite scroll - keeping it fast and efficient?
I have a pretty classic case of ajax pagination, where I paginate my records (using Kaminari) and when the user hits a "load more" button the next page/set of records should be loaded and inserted via ajax.

The problem is that most examples I see are very simplistic, with an index action that looks like this:

```<code>def index
  users = User.page(params[:page]).per(10)
end
</code>```

And the pagination (or load more) button just keeps calling that index action, with the next page param.

The problem is, my index action has a LOT more to it than that, and I don't want to run all that code when all I want is the next page of user records - it's slow and needless.

In terms of convention, what's the cleanest way to handle this? My thought was to have another method in addition to index like so:

```<code>def load_more_users
  users = User.page(params[:page]).per(10)
end
</code>```

And the pagination calls that one instead of index. However, is there a tidy way to do a conditional in the index action, for example check for the existence of params[:page] and if request.xhr??

What's the best way to do this?

答:
You may be able to use a respond_to block for this

respond_to do |format|
  format.html {
     # Existing index controller code
     # Will render the existing template
  }
  format.js {
     users = User.page(params[:page]).per(10)
     render json: users # Or render a partial
  }
end
```

Ajax will hit the format.js block, the initial page load will hit the format.html block.

Body:
I have a pretty classic case of ajax pagination, where I paginate my records (using Kaminari) and when the user hits a "load more" button the next page/set of records should be loaded and inserted via ajax.

The problem is that most examples I see are very simplistic, with an index action that looks like this:

def index
  users = User.page(params[:page]).per(10)
end

And the pagination (or load more) button just keeps calling that index action, with the next page param.

The problem is, my index action has a LOT more to it than that, and I don't want to run all that code when all I want is the next page of user records - it's slow and needless.

In terms of convention, what's the cleanest way to handle this? My thought was to have another method in addition to index like so:

def load_more_users
  users = User.page(params[:page]).per(10)
end

And the pagination calls that one instead of index. However, is there a tidy way to do a conditional in the index action, for example check for the existence of params[:page] and if request.xhr??

What's the best way to do this?

Body:
You may be able to use a respond_to block for this

respond_to do |format|
  format.html {
     # Existing index controller code
     # Will render the existing template
  }
  format.js {
     users = User.page(params[:page]).per(10)
     render json: users # Or render a partial
  }
end

Ajax will hit the format.js block, the initial page load will hit the format.html block.


问:
converting a pine script strategy to study
I want to convert a TradingView pine script "Price Channel Strategy" to a study. can someone please help?

The code is as given below:

```<code>//@version=4
strategy("ChannelBreakOutStrategy", overlay=true)

length = input(title="Length", type=input.integer, minval=1, maxval=1000, defval=5)

upBound = highest(high, length)
downBound = lowest(low, length)

if (not na(close[length]))
    strategy.entry("ChBrkLE", strategy.long, stop=upBound + syminfo.mintick, comment="ChBrkLE")
    strategy.entry("ChBrkSE", strategy.short, stop=downBound - syminfo.mintick, comment="ChBrkSE")
strategy.exit("long_tsl", "ChBrkLE", trail_points = 4000, trail_offset = 1500)
strategy.exit("short_tsl", "ChBrkSE", trail_points = 4000, trail_offset = 1500)
</code>```

答:
Mainly, you have to change the word strategy to study at the top of your code.
You'll also have to remove the strategy.entry/exit calls since those aren't allowed in a study.
See here for some more information: https://marketscripters.com/pine-script-strategy-vs-study/

Body:
I want to convert a TradingView pine script "Price Channel Strategy" to a study. can someone please help?

The code is as given below:

//@version=4
strategy("ChannelBreakOutStrategy", overlay=true)

length = input(title="Length", type=input.integer, minval=1, maxval=1000, defval=5)

upBound = highest(high, length)
downBound = lowest(low, length)

if (not na(close[length]))
    strategy.entry("ChBrkLE", strategy.long, stop=upBound + syminfo.mintick, comment="ChBrkLE")
    strategy.entry("ChBrkSE", strategy.short, stop=downBound - syminfo.mintick, comment="ChBrkSE")
strategy.exit("long_tsl", "ChBrkLE", trail_points = 4000, trail_offset = 1500)
strategy.exit("short_tsl", "ChBrkSE", trail_points = 4000, trail_offset = 1500)


问:
BubbleSort CSV by specific column
I've got a csv-file containing multiple rows and colums.
I want to use python and bubblesort to sort the file by a specific column.
For example:

Input csv-file:

```<code>Daniel,New York,23456,Gaming
Melinda,Washington,45678,Sports
Dave,Chicago,12345,Hiking
Ross,Boston,34567,Chess
</code>```

Output:

```<code>Dave,Chicago,12345,Hiking
Daniel,New York,23456,Gaming
Ross,Boston,34567,Chess
Melinda,Washington,45678,Sports
</code>```

In this example the rows should be sorted by the third column.

Until now i'm only able to sort the third column but the other columns stay in place.

答:
Here is an implementation using the python built-in csv module. This solution assumes that the input csv file is in test.csv, and you want the output in output.csv.

```<code>import csv
file = csv.reader(open('test.csv', 'r'))
rows = [row for row in file]

# Python program for implementation of Bubble Sort
# from: https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# modified to sort by the third element in the row per SO question
def bubble_sort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n - 1):
        # range(n) also work but outer loop will repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j][2] > arr[j + 1][2]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr

sorted_rows = [', '.join(row)+'\n' for row in bubble_sort(rows)]
with open('output.csv', 'w+') as f:
    f.writelines(sorted_rows)
</code>```

Note: you could also use pandas to read in the csv file, and sort using a faster built-in algorithm in pandas!

Title: BubbleSort CSV by specific column

Body:
I've got a csv-file containing multiple rows and colums.
I want to use python and bubblesort to sort the file by a specific column.
For example:

Input csv-file:

Daniel,New York,23456,Gaming
Melinda,Washington,45678,Sports
Dave,Chicago,12345,Hiking
Ross,Boston,34567,Chess

Output:

Dave,Chicago,12345,Hiking
Daniel,New York,23456,Gaming
Ross,Boston,34567,Chess
Melinda,Washington,45678,Sports

In this example the rows should be sorted by the third column.

Until now i'm only able to sort the third column but the other columns stay in place.

Body:
Here is an implementation using the python built-in csv module. This solution assumes that the input csv file is in test.csv, and you want the output in output.csv.

import csv
file = csv.reader(open('test.csv', 'r'))
rows = [row for row in file]

# Python program for implementation of Bubble Sort
# from: https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# modified to sort by the third element in the row per SO question
def bubble_sort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n - 1):
        # range(n) also work but outer loop will repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j][2] > arr[j + 1][2]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr

sorted_rows = [', '.join(row)+'\n' for row in bubble_sort(rows)]
with open('output.csv', 'w+') as f:
    f.writelines(sorted_rows)

Note: you could also use pandas to read in the csv file, and sort using a faster built-in algorithm in pandas!


问:
R - Find if characters of a vector are in another vector
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

```<code>commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")
</code>```

I tried the code in the topic cited before, but I had an error:

```<code>> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used
</code>```

What am I doing wrong? I would thank any help.

答:
You can do something like this too:

```<code>clients.first <- gsub(" ..", "", clients)
clients.first %in% commercial_names
</code>```

This returns:

```<code>[1] FALSE FALSE  TRUE FALSE
</code>```

You might need to change the regular expression for gsub if your clients data is more heterogeneous though.

Body:
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")

I tried the code in the topic cited before, but I had an error:

> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used

What am I doing wrong? I would thank any help.

Body:
You can do something like this too:

clients.first <- gsub(" ..", "", clients)
clients.first %in% commercial_names

This returns:

[1] FALSE FALSE  TRUE FALSE

You might need to change the regular expression for gsub if your clients data is more heterogeneous though.


问:
Accessing Nuxt plugin function in vuex getter
I am getting started with nuxtjs and vuex. I just encountered an issue accessing a combined injected plugin function from a getter. E.g.:

nuxt.config.js

```<code>...
plugins: [
  '~/plugins/myplugin.js'
  ],
...
</code>```

~/plugins/myplugin.js

```<code>function doSomething(string) {
        console.log("done something: " + string)
    }

export default ({ app }, inject) => {
    inject('doSomething', (string) => doSomething(string))
  }
</code>```

~/store/index.js

```<code>export const actions = {
    someAction({commit}) {
        this.$doSomething("Called from Action") // works
    }
}

export const getters = {
    someGetter: state => {
        this.$doSomething("Called from Getter") // throws error
    }
}
</code>```

The code works for the action someAction but the call in getter someGetter will result in a error suggesting this is undefined.

The nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter? Any help appreciated.

答:
You shouldn't try to do_something in a getter. Getters are for deriving state from your store's state only. The point being that you don't have to separately store and keep up-to-date the derived state. For example you have a list of tasks and you have a getter for completed tasks instead of a separate list of done tasks: completedTasks: state => state.tasks.filter(task => task.completed).

Mutations should only be used for mutating your store's state.

Finally, in actions you can interact with whatever you need, like a webserver API somewhere or this.$do_something and then fire off mutations to update the state based on the results.

So I'd say it makes sense what Nuxt is doing here, to inject in the actions but not to the getters.

Body:
I am getting started with nuxtjs and vuex. I just encountered an issue accessing a combined injected plugin function from a getter. E.g.:

nuxt.config.js

...
plugins: [
  '~/plugins/myplugin.js'
  ],
...

~/plugins/myplugin.js

function doSomething(string) {
        console.log("done something: " + string)
    }

export default ({ app }, inject) => {
    inject('doSomething', (string) => doSomething(string))
  }

~/store/index.js

export const actions = {
    someAction({commit}) {
        this.$doSomething("Called from Action") // works
    }
}

export const getters = {
    someGetter: state => {
        this.$doSomething("Called from Getter") // throws error
    }
}

The code works for the action someAction but the call in getter someGetter will result in a error suggesting this is undefined.

The nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter? Any help appreciated.


问:
How to assign default value to column variable if column value is coming as null
Hi I want to assign default value to column variable if value from select query for that variable is coming as null.

```<code>    @Entity
    @Table(name = "CDP_ALERTS")
    public class Country {

       @Column(name = "alert_reported_time")
    private String alertReportedTime;

    @Column(name = "unique_id")
    private String uniqueTrxId;

    @Column(name = "status_data")
    private String status;

public String getAlertReportedTime() {
        return alertReportedTime;
    }

    public void setAlertReportedTime(String alertReportedTime) {
        this.alertReportedTime = alertReportedTime;
    }
public String getUniqueTrxId() {
        return uniqueTrxId;
    }

    public void setUniqueTrxId(String uniqueTrxId) {
        this.uniqueTrxId = uniqueTrxId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    }
</code>```

Here status_data column value is coming as null sometime.
below is the select query.

```<code>@Query( "SELECT a FROM Country a WHERE to_char(alert_reported_time,'DD-MM-YY')=to_char(current_date,'DD-MM-YY') order by alert_reported_time desc")
    List<Country> findCountryByDate();
</code>```

Below is the output where in one object I am getting value as closed for status but in one object I am getting value as null.

{

```<code>[
        "alertSubject": "CWDigital Alert in MS onlinepayment with StatusCode 400",
        "alertReportedTime": "2020-05-29 15:16:03",
        "uniqueTrxId": "1018",
        "status": null,
        "reason": null,
        "conversationId": "ecd6184d-b2f1-4545-c5f2-1ac6d1df48fc",
        "clusterName": "patlacw01",
        "statusCode": "400\n",
        "nameSpace": "com-att-cwdigital-shop-prod"
    },
    {
        "alertSubject": "CWPOS Alert-500 in mS OrderManagement from pbhmacw01 and m26845@prod.shop.cwdigital.att.com",
        "alertReportedTime": "2020-05-29 15:15:41",
        "uniqueTrxId": "1017",
        "status": "CLOSED",
        "reason": null,
        "conversationId": "ee66359e-f87d-4eff-ce50-02ff6e18879a",
        "clusterName": "pbhmacw01",
        "statusCode": "500\n",
        "nameSpace": "com-att-cwpos-prod"
    }]
</code>```

答:
You could change your getter method for the property.

```<code>public String getStatus(){
   if(status != null) return status;
   return "Whatever you want";
}
</code>```

Also, if you want to persist default value in db. you could set a default value in property.

```<code>@Column
private String status = "My default value";
</code>```

Body:
Hi I want to assign default value to column variable if value from select query for that variable is coming as null.

    @Entity
    @Table(name = "CDP_ALERTS")
    public class Country {

       @Column(name = "alert_reported_time")
    private String alertReportedTime;

    @Column(name = "unique_id")
    private String uniqueTrxId;

    @Column(name = "status_data")
    private String status;

public String getAlertReportedTime() {
        return alertReportedTime;
    }

    public void setAlertReportedTime(String alertReportedTime) {
        this.alertReportedTime = alertReportedTime;
    }
public String getUniqueTrxId() {
        return uniqueTrxId;
    }

    public void setUniqueTrxId(String uniqueTrxId) {
        this.uniqueTrxId = uniqueTrxId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    }

Here status_data column value is coming as null sometime.
below is the select query.

@Query( "SELECT a FROM Country a WHERE to_char(alert_reported_time,'DD-MM-YY')=to_char(current_date,'DD-MM-YY') order by alert_reported_time desc")
    List<Country> findCountryByDate();

Below is the output where in one object I am getting value as closed for status but in one object I am getting value as null.

{

[
        "alertSubject": "CWDigital Alert in MS onlinepayment with StatusCode 400",
        "alertReportedTime": "2020-05-29 15:16:03",
        "uniqueTrxId": "1018",
        "status": null,
        "reason": null,
        "conversationId": "ecd6184d-b2f1-4545-c5f2-1ac6d1df48fc",
        "clusterName": "patlacw01",
        "statusCode": "400\n",
        "nameSpace": "com-att-cwdigital-shop-prod"
    },
    {
        "alertSubject": "CWPOS Alert-500 in mS OrderManagement from pbhmacw01 and m26845@prod.shop.cwdigital.att.com",
        "alertReportedTime": "2020-05-29 15:15:41",
        "uniqueTrxId": "1017",
        "status": "CLOSED",
        "reason": null,
        "conversationId": "ee66359e-f87d-4eff-ce50-02ff6e18879a",
        "clusterName": "pbhmacw01",
        "statusCode": "500\n",
        "nameSpace": "com-att-cwpos-prod"
    }]

Body:
You could change your getter method for the property.

public String getStatus(){
   if(status != null) return status;
   return "Whatever you want";
}

Also, if you want to persist default value in db. you could set a default value in property.

@Column
private String status = "My default value";


问:
Hibernate Envers 'forEntitiesAtRevision' generates redundant subquery
I am using Hibernate Envers to audit entity changes. Entities and audit tables are stored in MySQL database. The solution works fine in most cases but I found a quite strange problem with that.

Let's say I have an entity state at a certain revision and I want to get the previous change for that entity. For that purpose, I have written the following method:

```<code>    public <T> T getLastChange(@Nonnull Object id, @Nonnull Class<T> type, long beforeRev) {
        List<Number> revisions = AuditReaderFactory.get(entityManager).getRevisions(type, id);

        return revisions.stream()
                .map(Number::longValue)
                .filter(rev -> rev < beforeRev)
                .max(Comparator.comparingLong(rev -> rev))
                .map(rev -> AuditReaderFactory.get(entityManager).find(type, type.getName(), id, rev, true))
                .orElse(null);
    }
</code>```

It works fine except the fact that find generates "too safe" query:

```<code>select *
from persons_AUD person_aud0_
where person_aud0_.REV=(select max(person_aud1_.REV) from persons_AUD person_aud1_ where person_aud1_.REV<=462864 and person_aud0_.id=person_aud1_.id)
  and person_aud0_.id=56591;
</code>```

I already know the exact revision! How to avoid this subquery?? I just want

```<code>select *
from persons_AUD person_aud0_
where person_aud0_.REV=462864
  and person_aud0_.id=56591;
</code>```

Currently, it causes hard performance issues on big tables.

Would appreciate any advice on how I can persuade Envers to use passed revision as an exact match.

答:
I found the solution to my problem.
AuditReader.find method uses forEntitiesAtRevision which always produce that subquery.
But after some experiments, I've noticed that another method forRevisionsOfEntity can do exactly what I want.
So I rewrote my query as follows

```<code>    public <T> T getPreviousChange(@Nonnull Object id, @Nonnull Class<T> type, int beforeRev) {

        List resultList = getEntityManager().createQuery()
                .forRevisionsOfEntity(type, type.getName(), true, true)
                .add(AuditEntity.id().eq(id))
                .add(AuditEntity.revisionNumber().lt(beforeRev))
                .addOrder(AuditEntity.revisionNumber().desc())
                .setMaxResults(1).getResultList();

        return resultList.isEmpty() ? null : (T) resultList.get(0);
    }
</code>```

And now, instead of 2 queries, I get one:

```<code>select *
from persons_AUD person_aud0_
where person_aud0_.id=? and person_aud0_.REV<?
order by person_aud0_.REV desc limit ?
</code>```

which performs quite nicely even on a large table.

P.S.
The AuditQuery constructor is actually quite rich and powerful!
It is easy to modify the query in the required way.
Thanks.

Body:
I am using Hibernate Envers to audit entity changes. Entities and audit tables are stored in MySQL database. The solution works fine in most cases but I found a quite strange problem with that.

Let's say I have an entity state at a certain revision and I want to get the previous change for that entity. For that purpose, I have written the following method:

    public <T> T getLastChange(@Nonnull Object id, @Nonnull Class<T> type, long beforeRev) {
        List<Number> revisions = AuditReaderFactory.get(entityManager).getRevisions(type, id);

        return revisions.stream()
                .map(Number::longValue)
                .filter(rev -> rev < beforeRev)
                .max(Comparator.comparingLong(rev -> rev))
                .map(rev -> AuditReaderFactory.get(entityManager).find(type, type.getName(), id, rev, true))
                .orElse(null);
    }

It works fine except the fact that find generates "too safe" query:

select *
from persons_AUD person_aud0_
where person_aud0_.REV=(select max(person_aud1_.REV) from persons_AUD person_aud1_ where person_aud1_.REV<=462864 and person_aud0_.id=person_aud1_.id)
  and person_aud0_.id=56591;

I already know the exact revision! How to avoid this subquery?? I just want

select *
from persons_AUD person_aud0_
where person_aud0_.REV=462864
  and person_aud0_.id=56591;

Currently, it causes hard performance issues on big tables.

Would appreciate any advice on how I can persuade Envers to use passed revision as an exact match.

Body:
I found the solution to my problem.
AuditReader.find method uses forEntitiesAtRevision which always produce that subquery.
But after some experiments, I've noticed that another method forRevisionsOfEntity can do exactly what I want.
So I rewrote my query as follows

    public <T> T getPreviousChange(@Nonnull Object id, @Nonnull Class<T> type, int beforeRev) {

        List resultList = getEntityManager().createQuery()
                .forRevisionsOfEntity(type, type.getName(), true, true)
                .add(AuditEntity.id().eq(id))
                .add(AuditEntity.revisionNumber().lt(beforeRev))
                .addOrder(AuditEntity.revisionNumber().desc())
                .setMaxResults(1).getResultList();

        return resultList.isEmpty() ? null : (T) resultList.get(0);
    }

And now, instead of 2 queries, I get one:

select *
from persons_AUD person_aud0_
where person_aud0_.id=? and person_aud0_.REV<?
order by person_aud0_.REV desc limit ?

which performs quite nicely even on a large table.

P.S.
The AuditQuery constructor is actually quite rich and powerful!
It is easy to modify the query in the required way.
Thanks.


问:
Trigger multiple files from one PHP file
The requirement is to run multiple PHP files from one single PHP File without any timeouts, having searched stack overflow the only solution seems to be using EXEC however this is not allowed on my host.

If I run all.php from CLI then it should run 1.php , 2.php and 3.php.

Now normally this would be straight forward and I would just require or include them into all.php however the function names in 1.php , 2.php and 3.php match and I am looking for a solution which runs the file and then forgets about functions, variables or anything else within the file.

Essentially I want 1.php , 2.php , 3.php to run separately and All.php is only needs to trigger these files.

One possible solution in my mind was using curl in all.php to trigger them files, however this would introduce webserver limits and timeouts which I am not looking to deal with.

Thanks for the help guys.
Apologies if the question is not very clear.

答:
You can use CURL to run them sequentially or CURL_MULTI if you want them to run in parallel.
PHP CURL documentation

A very simplified example:

```<code><?php

$ch = curl_init("http://localhost/1.php");
curl_exec($ch);
curl_close($ch);

$ch = curl_init("http://localhost/2.php");
curl_exec($ch);
curl_close($ch);

$ch = curl_init("http://localhost/3.php");
curl_exec($ch);
curl_close($ch);
</code>```

Body:
You can use CURL to run them sequentially or CURL_MULTI if you want them to run in parallel.
PHP CURL documentation

A very simplified example:

<?php

$ch = curl_init("http://localhost/1.php");
curl_exec($ch);
curl_close($ch);

$ch = curl_init("http://localhost/2.php");
curl_exec($ch);
curl_close($ch);

$ch = curl_init("http://localhost/3.php");
curl_exec($ch);
curl_close($ch);


答:
Why not just use endsWith instead complex regex

```<code>if(fileName.endsWith(".txt") || fileName.endsWith(".txt.gz")){
 Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
</code>```

Title: Regular expression to handle two different file extensions

Body:
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}

This handles only the .txt. How can I handle ".txt.gz"
Thanks

Body:
Why not just use endsWith instead complex regex

if(fileName.endsWith(".txt") || fileName.endsWith(".txt.gz")){
 Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}


问:
raw folder is not recognized even though it has been created in the "res" folder

If I hover over the raw folder it says

"raw cannot be resolved or is not a field"

答:
I had the same issue today.
Restarting android studio work for me.</p>


问:
Submitting a HTML form in and onload function
I want send a form as soon as the page is loaded. All variables in the form are written dynamically and there is no button for submitting.

Does following JS script work in all browsers ?

```<code><script type='text/javascript'> window.onload = function(){ window.document.forms[0].submit(); }; </script>
</code>```

I doubt window.onload will work in all without any problems.

Thanks in advance...

答:
Don't use the window.onload (I mean, you can, but is easier/ more logical to do it differently). What you should do is print the form in a hidden div tag, assign an id to the submit button and then use javascript to 'click' it. Here is an example:

```<code><div style="display: hidden;">
    <form action="page/site" method="get/post">
        <input type="hidden" name="name" value="value" />
        <input type="submit" id="formButton" />
    </form>
    <script language="javascript">
        document.getElementById("formButton").click();
    </script>
</div>
</code>```

I hope that helps.

Body:
I want send a form as soon as the page is loaded. All variables in the form are written dynamically and there is no button for submitting.

Does following JS script work in all browsers ?

I doubt window.onload will work in all without any problems.

Thanks in advance...

Body:
Don't use the window.onload (I mean, you can, but is easier/ more logical to do it differently). What you should do is print the form in a hidden div tag, assign an id to the submit button and then use javascript to 'click' it. Here is an example:

<div style="display: hidden;">
    <form action="page/site" method="get/post">
        <input type="hidden" name="name" value="value" />
        <input type="submit" id="formButton" />
    </form>
    <script language="javascript">
        document.getElementById("formButton").click();
    </script>
</div>

I hope that helps.


问:
How to set an image vertical align but align left horizontally?
I need to set a welcome section like the following:

I have set an absolute position just for the image, but I cannot make the image keeps horizontally align with the other column. Any ideas?

My code:

```<code>.img-welcome{
    position: absolute;
    top:10%;
    right: 0;
    bottom: 0;
    margin: auto;
    align-items: center;
    display: flex;
    height: max-content;
}

.container-relative{
    position: relative;
    height: 100%;
    padding-bottom: 50px;

}

<div className='welcome-container d-flex align-items-center'>
        <div className='container'>
         <div className='pt-5 text-left pb-5 container-relative'>
            <div class="col-6 pt-5  mb-5">
                <h1 class="mb-3 row h1-text-style">Combine all your credit cards in one place</h1>
                <h3 class="mb-5 row h3-text-style">We alow you to connect diferent bank cards, in one system, in which you will have the opportunity to manage to financial data and track the statistics of your costs.</h3>
                <a class="button-gradient" href="#">Get Started</a>
            </div>

        </div>
        </div>
         <div class="img-welcome">
             <img className='w-100' src={require('./img/img2.png')}></img>
         </div>
    </div>
</code>```

答:
You can use flexbox to easily achieve this.

You just need a container and the two sides:

body {
  background-image: linear-gradient(to right, #00b795 , #0092a2);
  height: 100vh;
  margin: 0;
  padding: 0;
}

.container {
  height: 100%;
  display: flex;
  align-items: center;
}

.container > div {
  flex: 50%;
}

.left {
  padding: 20px;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  display: flex;
  flex-direction: column;
}

.right img {
  height: 80vh;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left">
    <strong>Combine all your credit cards in one place</strong>
    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum architecto repellendus deserunt ex quo impedit in blanditiis facere, nisi quos, excepturi doloribus fuga expedita amet.</p>
  </div>
  <div class="right">
    <img src="https://startbootstrap.com/assets/img/screenshots/themes/sb-admin-2.png">
  </div>
</div></code>```

Body:
I need to set a welcome section like the following:

I have set an absolute position just for the image, but I cannot make the image keeps horizontally align with the other column. Any ideas?

My code:

.img-welcome{
    position: absolute;
    top:10%;
    right: 0;
    bottom: 0;
    margin: auto;
    align-items: center;
    display: flex;
    height: max-content;
}

.container-relative{
    position: relative;
    height: 100%;
    padding-bottom: 50px;

}

Combine all your credit cards in one place

We alow you to connect diferent bank cards, in one system, in which you will have the opportunity to manage to financial data and track the statistics of your costs.

                Get Started

Body:
You can use flexbox to easily achieve this.

You just need a container and the two sides:

body {
  background-image: linear-gradient(to right, #00b795 , #0092a2);
  height: 100vh;
  margin: 0;
  padding: 0;
}

.container {
  height: 100%;
  display: flex;
  align-items: center;
}

.container > div {
  flex: 50%;
}

.left {
  padding: 20px;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  display: flex;
  flex-direction: column;
}

.right img {
  height: 80vh;
  width: 100%;
}

<div class="container">
  <div class="left">
    <strong>Combine all your credit cards in one place</strong>
    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum architecto repellendus deserunt ex quo impedit in blanditiis facere, nisi quos, excepturi doloribus fuga expedita amet.</p>
  </div>
  <div class="right">
    <img src="https://startbootstrap.com/assets/img/screenshots/themes/sb-admin-2.png">
  </div>
</div>


Body:
You can replace .[a-zA-Z]{3} with .txt(\.gz)

if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}).txt(\.gz)?")){
   Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}


问:
Is there a way to update all values in a PostgreSQL table that are null with 0
I have a large table that doesn't follow the best data organization practices so I can't do a simple

```<code>update table set (...cols) = 0 where (...cols) is null
</code>```

because the columns names are the months of the year dash a year up to 5 years. i.e Jan-20, Jan-21, Jan-22, etc.

I'm wondering if there's a command out there that would essentially do

update table set all data = 0 where data is null

I understand this goes against SQL principles but my hope is that there's something out there that's does what I would expect that command to do.

答:
There is no pure-SQL way to do that (aside from listing all the columns manually).

You can use pl/pgsql:

```<code>DO
$$
    DECLARE
        schema_ TEXT := 'public';
        table_ TEXT := 't';
        column_list TEXT;
        coalesced_list TEXT;
    BEGIN
        -- Build up 2 strings containing
        --   (col1, col2, col3, ....)
        --   (COALESCE(col1, 0), COALESCE(col2, 0), ...)
        SELECT
            '(' || string_agg(quote_ident(column_name), ', ') || ')',
            '(' || string_agg('COALESCE(' || quote_ident(column_name) || ', 0)', ',') || ')'
        FROM information_schema.columns
        WHERE table_name = table_
          AND table_schema = schema_
        INTO column_list, coalesced_list
        ;
        -- Update the table, settings columns (c1, c2, ...) to (COALESCE(c1, 0), COALESCE(c2, 0), ...)
        -- changing all null values to zeroes
        EXECUTE format($query$
            UPDATE %I.%I
            SET %s = %s
        $query$, schema_, table_, column_list, coalesced_list);
    END
$$;
</code>```

Body:
I have a large table that doesn't follow the best data organization practices so I can't do a simple

update table set (...cols) = 0 where (...cols) is null

because the columns names are the months of the year dash a year up to 5 years. i.e Jan-20, Jan-21, Jan-22, etc.

I'm wondering if there's a command out there that would essentially do

update table set all data = 0 where data is null

I understand this goes against SQL principles but my hope is that there's something out there that's does what I would expect that command to do.

Body:
There is no pure-SQL way to do that (aside from listing all the columns manually).

You can use pl/pgsql:

DO
$$
    DECLARE
        schema_ TEXT := 'public';
        table_ TEXT := 't';
        column_list TEXT;
        coalesced_list TEXT;
    BEGIN
        -- Build up 2 strings containing
        --   (col1, col2, col3, ....)
        --   (COALESCE(col1, 0), COALESCE(col2, 0), ...)
        SELECT
            '(' || string_agg(quote_ident(column_name), ', ') || ')',
            '(' || string_agg('COALESCE(' || quote_ident(column_name) || ', 0)', ',') || ')'
        FROM information_schema.columns
        WHERE table_name = table_
          AND table_schema = schema_
        INTO column_list, coalesced_list
        ;
        -- Update the table, settings columns (c1, c2, ...) to (COALESCE(c1, 0), COALESCE(c2, 0), ...)
        -- changing all null values to zeroes
        EXECUTE format($query$
            UPDATE %I.%I
            SET %s = %s
        $query$, schema_, table_, column_list, coalesced_list);
    END
$$;


问:
Implementing Selectable user controls inside a ListBox
I have widgets that display data of an entity. I have made user controls to display data for each entity.

```<code> <UserControl x:Class="Widget"
    <Border BorderBrush="#FF000000" CornerRadius="10" Width="220" Height="180">
        <Border.Style>
            <Style TargetType="{x:Type Border}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsSelected}" Value="True">
                        <Setter Property="BorderThickness" Value="5"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsSelected}" Value="False">
                        <Setter Property="BorderThickness" Value="1"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <StackPanel Orientation="Vertical">
          <Label>Name</Label>
        </StackPanel>
    </Border>
</UserControl>
</code>```

and the code behind

```<code>public partial class Widget: UserControl
    {
        /// <summary>
        /// Is Selected Dependency property
        /// </summary>
        public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(StationStatus), new PropertyMetadata(false));

        public bool IsSelected
        {
            get
            {
                return (bool)GetValue(IsSelectedProperty);
            }
            set
            {
                SetValue(IsSelectedProperty, value);
            }
        }

        public Widget()
        {
            InitializeComponent();
        }
    }
</code>```

The user control is rendered in ListBox

```<code>      <ListBox ItemsSource="{Binding WidgetData}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Single">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel IsItemsHost="True" Grid.Row="0" ItemHeight="200" ItemWidth="230" Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>

                        <ListBox.ItemTemplate>
                            <DataTemplate>
  <view:StationStatus IsSelected="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected}">
                            </view:StationStatus>
                                </view:Widget>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
</code>```

I was expecting the IsSelected of the ListBoxItem would be bound to the user control and the border thickness would change when the Listbox item is selected but is not working as expected.

答:
I don't have enough reputation to comment so I'll put it in the answer.

I had a similar problem in the past where I was mistakenly capturing ListBox events and thinking that it should apply to my controls inside ListBox. Well, it doesn't. In your case, the Widget itself doesn't really get selected, and you're binding the border to the Widget's property, so nothing happens. Or at least that's what it looks like to me.

Body:
I have widgets that display data of an entity. I have made user controls to display data for each entity.

 <UserControl x:Class="Widget"
    <Border BorderBrush="#FF000000" CornerRadius="10" Width="220" Height="180">
        <Border.Style>

            </Style>
        </Border.Style>
        <StackPanel Orientation="Vertical">
          Name
        </StackPanel>
    </Border>
</UserControl>

and the code behind

public partial class Widget: UserControl
    {
        ///
        /// Is Selected Dependency property
        ///
        public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(StationStatus), new PropertyMetadata(false));

        public bool IsSelected
        {
            get
            {
                return (bool)GetValue(IsSelectedProperty);
            }
            set
            {
                SetValue(IsSelectedProperty, value);
            }
        }

        public Widget()
        {
            InitializeComponent();
        }
    }

The user control is rendered in ListBox

      <ListBox ItemsSource="{Binding WidgetData}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Single">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel IsItemsHost="True" Grid.Row="0" ItemHeight="200" ItemWidth="230" Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>

                        <ListBox.ItemTemplate>
                            <DataTemplate>
  <view:StationStatus IsSelected="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected}">
                            </view:StationStatus>
                                </view:Widget>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

I was expecting the IsSelected of the ListBoxItem would be bound to the user control and the border thickness would change when the Listbox item is selected but is not working as expected.


问:
Sorting a vector with pointer at object C++
If anyone can help I would be very grateful.
How do i sort this vector:

vector<Person*>person

by this criterium:

Surname

I have already tried it using set but it removes object if there is more than 2 objects with same Surname

there are lot of string variables, and I need to sort it by

Surname

and then if surnames are the same, then I need to sort them by

Name

and also it sorts by hexadecimal value of that pointer...
EDIT:
More code as you ask:

```<code>for (pChild = pRoot->FirstChildElement("Member"); pChild != NULL; pChild = pChild->NextSiblingElement())
    {
        string Surname = pChild->Attribute("surname");
        string Name = pChild->Attribute("name");
        string DateOfBirth = pChild->Attribute("dateofbirth");
        person.push_back(new Person(Surname, Name, DateOfBirth));
    }
</code>```

答:
I had a bit of fun doing it with std::set. There are a couple of examples of comparators. One function and one "functor."

```<code>#include <iostream>
#include <set>
#include <string>

struct Person {
  uint64_t id;
  std::string name;
  std::string family_name;

  bool operator<(const Person &other) const {
    if (family_name == other.family_name) {
      if (name == other.name) {
        return id < other.id;
      } else {
        return name < other.name;
      }
    } else {
      return family_name < other.family_name;
    }
  }
};

std::ostream &operator<<(std::ostream &os, const Person &x) {
  return os << '{' << x.id << ", " << x.name << ", " << x.family_name << '}';
}

bool person_ptr_less(const Person *a, const Person *b) { return *a < *b; }

class PersonPtrComparator {
public:
  bool operator()(const Person *a, const Person *b) const { return *a < *b; }
};

int main() {
  std::set<Person *, bool (*)(const Person *, const Person *)> people(
      person_ptr_less);
  people.emplace(new Person{1, "Joe", "Smith"});
  people.emplace(new Person{2, "Joe", "Blow"});
  people.emplace(new Person{3, "Joa", "Smith"});
  people.emplace(new Person{4, "Joe", "Smith"});

  std::set<Person *, PersonPtrComparator> people_2(people.begin(),
                                                   people.end());

  for (const auto &x : people) {
    std::cout << *x << '\n';
  }
  std::cout << "---\n";
  for (const auto &x : people_2) {
    std::cout << *x << '\n';
  }
  return 0;
}
</code>```

Body:
If anyone can help I would be very grateful.
How do i sort this vector:

vector<Person*>person

by this criterium:

Surname

I have already tried it using set but it removes object if there is more than 2 objects with same Surname

there are lot of string variables, and I need to sort it by

Surname

and then if surnames are the same, then I need to sort them by

Name

and also it sorts by hexadecimal value of that pointer...
EDIT:
More code as you ask:

for (pChild = pRoot->FirstChildElement("Member"); pChild != NULL; pChild = pChild->NextSiblingElement())
    {
        string Surname = pChild->Attribute("surname");
        string Name = pChild->Attribute("name");
        string DateOfBirth = pChild->Attribute("dateofbirth");
        person.push_back(new Person(Surname, Name, DateOfBirth));
    }

Body:
I had a bit of fun doing it with std::set. There are a couple of examples of comparators. One function and one "functor."

#include <iostream>
#include <set>
#include <string>

struct Person {
  uint64_t id;
  std::string name;
  std::string family_name;

  bool operator<(const Person &other) const {
    if (family_name == other.family_name) {
      if (name == other.name) {
        return id < other.id;
      } else {
        return name < other.name;
      }
    } else {
      return family_name < other.family_name;
    }
  }
};

std::ostream &operator<<(std::ostream &os, const Person &x) {
  return os << '{' << x.id << ", " << x.name << ", " << x.family_name << '}';
}

bool person_ptr_less(const Person *a, const Person *b) { return *a < *b; }

class PersonPtrComparator {
public:
  bool operator()(const Person *a, const Person *b) const { return *a < *b; }
};

int main() {
  std::set<Person *, bool (*)(const Person *, const Person *)> people(
      person_ptr_less);
  people.emplace(new Person{1, "Joe", "Smith"});
  people.emplace(new Person{2, "Joe", "Blow"});
  people.emplace(new Person{3, "Joa", "Smith"});
  people.emplace(new Person{4, "Joe", "Smith"});

  std::set<Person *, PersonPtrComparator> people_2(people.begin(),
                                                   people.end());

  for (const auto &x : people) {
    std::cout << *x << '\n';
  }
  std::cout << "---\n";
  for (const auto &x : people_2) {
    std::cout << *x << '\n';
  }
  return 0;
}


问:
Associations of Hierarchical Objects, belongs_to, has_many of Own Class
I'm trying to make objects belong to other objects of the same class by adding a parent_id attribute to the object so active record can associate them with each other in a hierarchical manner.

I know I can just write an instance method to do a find and get them, but I want to know if there is a more rails appropriate way to accomplish this, so can I set this up with active record associations, if so how?

答:
There are a lot of ways of nesting data in databases. The one to choose manly depends on how you are going to access this data, and how often you are going to change the tree.

Here is a list of current nesting plugins for rails: http://www.ruby-toolbox.com/categories/activerecord_nesting.html Be sure to reed each of the gems documentation in order to choose the most appropriate one for your situation.


答:
Your code is correct but for a typo:

```<code>grepl(paste0(commercial_names, collapse = "|"), clients) # typo: collape
[1] FALSE FALSE  TRUE FALSE
</code>```

Given the typo, the commercial_names are not collapsed.

Title: R - Find if characters of a vector are in another vector

Body:
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")

I tried the code in the topic cited before, but I had an error:

> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used

What am I doing wrong? I would thank any help.

Body:
Your code is correct but for a typo:

grepl(paste0(commercial_names, collapse = "|"), clients) # typo: collape
[1] FALSE FALSE  TRUE FALSE

Given the typo, the commercial_names are not collapsed.


问:
How to iterate over all values of an Enum including any nested Enums?
Imagine one has two classes derived from Enum, e.g.

```<code>class Color(Enum):
    blue = 'blue'
    red = 'red'

class Properties(Enum):
    height = 'h'
    weight = 'w'
    colors = Color

</code>```

What is the best way to (probably recursively) iterate over all Enum-labels of a nested Enum like Properties, including the ones of Enum-members like Properties.colors in the example above (i.e. including  Color.blue and Color.red)? Checking for the type of the value?

答:
Doing it recursively is probably the best way. This example is slightly cleaner than using a try except block

```<code>import inspect

def iter_enum(e):
  for member in e:
    if inspect.isclass(member.value) and issubclass(member.value, enum.Enum):
        iter_enum(member.value)
    else:
        print(member)

iter_enum(Properties)

</code>```

Output

```<code>Properties.height
Properties.weight
Color.blue
Color.red

</code>```

Body:
Imagine one has two classes derived from Enum, e.g.

class Color(Enum):
    blue = 'blue'
    red = 'red'

class Properties(Enum):
    height = 'h'
    weight = 'w'
    colors = Color

What is the best way to (probably recursively) iterate over all Enum-labels of a nested Enum like Properties, including the ones of Enum-members like Properties.colors in the example above (i.e. including  Color.blue and Color.red)? Checking for the type of the value?

Body:
Doing it recursively is probably the best way. This example is slightly cleaner than using a try except block

import inspect

def iter_enum(e):
  for member in e:
    if inspect.isclass(member.value) and issubclass(member.value, enum.Enum):
        iter_enum(member.value)
    else:
        print(member)

iter_enum(Properties)

Output

Properties.height
Properties.weight
Color.blue
Color.red


问:
For loop crashes program while trying to read array c++
Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.

Lets say s = 4 and  A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)

My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?

```<code>#include <iomanip>

using namespace std;

int ordering(int s, int n, int A[]);

int main()
{
    int n, A[n];
    int s;
    cout << "Vlera e s: ";
    cin >> s;

    if (s <= 0)
    {
        return 1;
    }

    cout << "\nN: ";
    cin >> n;

    if (n <= 0)
    {
        return 1;
    }

    cout << "\nVector:";
    for (int i = 0; i < n; i++)
    {
        A[i] = i + 1;
        cout << " " << A[i] << " ";
    }

    if (s > n)
    {
        cout << "\nNo change\n";
        return 0;
    }
    else
    {
        ordering(s, n, A);
    }

    cout << "\nNew vector:";
    for (int i = 0; i < n; i++)
    {
        cout << " " << A[i] << " ";
    }

    return 0;
}

int ordering(int s, int n, int A[])
{
    int counter = 0;
    for (int i = 0, divider = n / s; i < divider; i++)
    {
        int decrease = 0;
        for (int j = counter, a = counter + s; j < a; j++)
        {
            A[j] = a - decrease;
            decrease++;
        }
        counter += s;
    }
    return 0;
}
</code>```

答:
Variable length arrays is not a standard C++ feature.

```<code>int n, A[n];
</code>```

Moreover in the above declaration the variable n was not initialized. So in any case the program has undefined behavior.

Instead of an array you could use the standard class template std::vector.

The program can look simpler and more safer is to use standard algorithms such as, for example, std::reverse.

Here is a demonstrative program.

```<code>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>

void reorder( std::vector<int> &v, size_t s )
{
    if ( not ( s < 2 ) )
    {
        for ( auto last = std::end( v );
              not (std::distance( std::begin( v ), last ) < s );  )
        {
            auto first = std::prev( last, s );
            std::reverse( first, last );
            last = first;
        }
    }
}

int main()
{
    std::cout << "Vlera e s: ";

    size_t s = 0;
    std::cin >> s;

    std::cout << "N: ";

    size_t n = 0;
    std::cin >> n;

    std::vector<int> v( n );

    std::iota( std::begin( v ), std::end( v ), 1 );

    putchar( '\n' );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    reorder( v, s );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    return 0;
}
</code>```

The program output might look like

```<code>Vlera e s: 4
N: 10

1 2 3 4 5 6 7 8 9 10
1 2 6 5 4 3 10 9 8 7
</code>```

But it seems you need write the corresponding code yourself using loops. In this case the program can look like

```<code>#include <iostream>
#include <vector>

void reorder( std::vector<int> &v, size_t s )
{
    if ( not ( s < 2 ) )
    {
        for ( auto n = v.size(); !( n < s ); n -= s )
        {
            for ( size_t i = 0; i < s / 2; i++ )
            {
                int value = v[n - s + i];
                v[n - s + i] = v[n - i - 1];
                v[n - i - 1] = value;
            }
        }
    }
}

int main()
{
    std::cout << "Vlera e s: ";

    size_t s = 0;
    std::cin >> s;

    std::cout << "N: ";

    size_t n = 0;
    std::cin >> n;

    std::vector<int> v( n );

    int value = 1;

    for ( auto &item : v ) item = value++;

    putchar( '\n' );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    reorder( v, s );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    return 0;
}
</code>```

The program output might look as already shown above

```<code>Vlera e s: 4
N: 10

1 2 3 4 5 6 7 8 9 10
1 2 6 5 4 3 10 9 8 7
</code>```

Body:
Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.

Lets say s = 4 and  A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)

My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?

#include <iomanip>

using namespace std;

int ordering(int s, int n, int A[]);

int main()
{
    int n, A[n];
    int s;
    cout << "Vlera e s: ";
    cin >> s;

    if (s <= 0)
    {
        return 1;
    }

    cout << "\nN: ";
    cin >> n;

    if (n <= 0)
    {
        return 1;
    }

    cout << "\nVector:";
    for (int i = 0; i < n; i++)
    {
        A[i] = i + 1;
        cout << " " << A[i] << " ";
    }

    if (s > n)
    {
        cout << "\nNo change\n";
        return 0;
    }
    else
    {
        ordering(s, n, A);
    }

    cout << "\nNew vector:";
    for (int i = 0; i < n; i++)
    {
        cout << " " << A[i] << " ";
    }

    return 0;
}

int ordering(int s, int n, int A[])
{
    int counter = 0;
    for (int i = 0, divider = n / s; i < divider; i++)
    {
        int decrease = 0;
        for (int j = counter, a = counter + s; j < a; j++)
        {
            A[j] = a - decrease;
            decrease++;
        }
        counter += s;
    }
    return 0;
}

Body:
Variable length arrays is not a standard C++ feature.

int n, A[n];

Moreover in the above declaration the variable n was not initialized. So in any case the program has undefined behavior.

Instead of an array you could use the standard class template std::vector.

The program can look simpler and more safer is to use standard algorithms such as, for example, std::reverse.

Here is a demonstrative program.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>

void reorder( std::vector<int> &v, size_t s )
{
    if ( not ( s < 2 ) )
    {
        for ( auto last = std::end( v );
              not (std::distance( std::begin( v ), last ) < s );  )
        {
            auto first = std::prev( last, s );
            std::reverse( first, last );
            last = first;
        }
    }
}

int main()
{
    std::cout << "Vlera e s: ";

    size_t s = 0;
    std::cin >> s;

    std::cout << "N: ";

    size_t n = 0;
    std::cin >> n;

    std::vector<int> v( n );

    std::iota( std::begin( v ), std::end( v ), 1 );

    putchar( '\n' );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    reorder( v, s );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    return 0;
}

The program output might look like

Vlera e s: 4
N: 10

1 2 3 4 5 6 7 8 9 10
1 2 6 5 4 3 10 9 8 7

But it seems you need write the corresponding code yourself using loops. In this case the program can look like

#include <iostream>
#include <vector>

void reorder( std::vector<int> &v, size_t s )
{
    if ( not ( s < 2 ) )
    {
        for ( auto n = v.size(); !( n < s ); n -= s )
        {
            for ( size_t i = 0; i < s / 2; i++ )
            {
                int value = v[n - s + i];
                v[n - s + i] = v[n - i - 1];
                v[n - i - 1] = value;
            }
        }
    }
}

int main()
{
    std::cout << "Vlera e s: ";

    size_t s = 0;
    std::cin >> s;

    std::cout << "N: ";

    size_t n = 0;
    std::cin >> n;

    std::vector<int> v( n );

    int value = 1;

    for ( auto &item : v ) item = value++;

    putchar( '\n' );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    reorder( v, s );

    for ( const auto &item : v )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    return 0;
}

The program output might look as already shown above

Vlera e s: 4
N: 10

1 2 3 4 5 6 7 8 9 10
1 2 6 5 4 3 10 9 8 7


问:
Sequelize.js : What's the difference between sequelize.define and model.init?
The documentation doesn't explain the difference between sequelize.define and Model.init. All it says is Internally, sequelize.define calls Model.init

What things do I need to consider when choosing which one to use? What are the main differences between the two and what are the consequences for choosing one over the other? It seems like sequelize.init is the preferred method in the documentation - why is that?

答:
I was recently wondering the same thing when I came across this question. I did some further investigation and found some additional details explained in the documentation that may be useful here.

TL:DR

Overall, the differences are strictly related to syntax, and using sequelize.define or Model.init comes down to personal preference. I do not believe one is preferred over the other, especially since the Sequelize CLI tool generates model definitions using the sequelize.define method, and it is not explicitly stated anywhere.

Models can be defined in two equivalent ways in Sequelize:

Calling sequelize.define(modelName, attributes, options) API documentation on define

Extending Model and calling init(attributes, options) API documentation on init

After a model is defined, it is available within sequelize.models by its model name.

As you mentioned and as stated in the documentation:

Internally, sequelize.define calls Model.init, so both approaches are essentially equivalent.


问:
How can I merge the outputs from a For_Each loop in an Azure Logic App to a single flat array?
I have a For_Each loop in an Azure Logic App that calls another, nested, Logic App. The result from each iteration of the nested Logic Apps is a JSON object that contains an array of strings, like this:

```<code>{
 "Results": ["string a", "string b"]
}
</code>```

So the output from my For_Each loop in the parent Logic App looks like this:

```<code>[
 {"Results": ["string a", "string b"]},
 {"Results": ["string c", "string d"]}
]
</code>```

I want to put all these strings into a single flat list that I can pass to another action.

How can I do this? Is it possible using the workflow definition language and built-in functions, or do I need to use an external function (in a service, or an Azure Function)?

答:
This technique works pretty well, and only uses run-of-the-mill Logic App actions:

1. start with declaring an empty array variable (action Variable: Initialise variable)

2. iterate through your items (action Control: For each), e.g. the resultset from a previous action

in each iteration, first compose the JSON fragment you need (action Data Operations: Compose)

then append the output of your Compose action to the array (action: Variable: Append to array variable)

3. then, outside the loop, join the elements of the array (action Data Operations: Join)

4. do what you need with the output of the Join action, e.g. send as response payload (action Request: Response)

This is what it looks like in the end:

Body:
I have a For_Each loop in an Azure Logic App that calls another, nested, Logic App. The result from each iteration of the nested Logic Apps is a JSON object that contains an array of strings, like this:

{
 "Results": ["string a", "string b"]
}

So the output from my For_Each loop in the parent Logic App looks like this:

[
 {"Results": ["string a", "string b"]},
 {"Results": ["string c", "string d"]}
]

I want to put all these strings into a single flat list that I can pass to another action.

How can I do this? Is it possible using the workflow definition language and built-in functions, or do I need to use an external function (in a service, or an Azure Function)?


问:
Regular expression to handle two different file extensions
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

```<code>if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
</code>```

This handles only the .txt. How can I handle ".txt.gz"
Thanks

Body:
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}

This handles only the .txt. How can I handle ".txt.gz"
Thanks

Body:
? will work for your required | . Try adding

(.[a-zA-Z]{2})?

to your original regex

([\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3}(.[a-zA-Z]{2})?)


问:
Javascript Canvas: Drawing over picture
I have been having a problem with a drawing on a canvas. I want the user to be able to change the background on the canvas and I will eventually want to be able to type something in an input box and it will appear on the canvas in boxes. I have been trying to get more on the screen after they have choosen a background (which works fine), but when I try to add just a simple box I can't. I have been trying to do it in different parts of the code but doesn't work for me, and haven't been able to find a solution. </p>

<p>So what I am asking, is there a specific way you have to do it in order to have
a image (choosen with a select tag, which I already have working), and be able to draw a box ontop of the image choosen. Hope someone can explain to me how I will be able to do so! </p>

```<code>function load(){
  draw()
}

//Canvas change background
function draw(){
  changeBackground("assets/images/1.jpg");
}

function changeBackground(imagePath){
  var c=document.getElementById("myCanvas");
  var ctx=c.getContext("2d");
  var img=new Image();
  img.onload = function(){
        ctx.drawImage(img,0,0,954,507);
  };
  img.src=imagePath;
}

function background(){
  var imageN = document.getElementById("imageselector").value;
  console.log("Image picked as a Background: " + imageN)
  changeBackground("assets/images/" + imageN + ".jpg");
}
</code>```

答:
Let this be a good foundation for your app!

Happy coding!

const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const imageInput = document.querySelector("#imageInput");
const textInput = document.querySelector("#textInput");
const imageUrl = 'https://i.picsum.photos/id/944/600/600.jpg';

imageInput.value = imageUrl;
const state = {
  image: null,
  text: ''
}

const width = window.innerWidth;
const height = window.innerHeight;;
canvas.width = width;
canvas.height = height;

textInput.addEventListener("keydown", ({key}) => {
  const value = textInput.value;

  if(key === "Backspace") {
    state.text = value.substring(0, value.length - 1);
  }
  else {
    state.text = value + key;
  }

  render();
})

imageInput.addEventListener("input", () => {
  getImage(imageInput.value)
    .then(image => {
      state.image = image;
      render();
    })
})

const render = () => {
  clear();
  drawBackground(state.image);
  drawText(state.text);
}

const drawText = (text) => {
  context.font = "40px Comic Sans";
  context.fillStyle = "white";
  const textMeasure = context.measureText(text);
  context.fillText(text, width / 2 - textMeasure.width / 2, height / 5);
}

const clear = () => {
  context.fillStyle = "white";
  context.fillRect(0, 0, width, height);
}

const getImage = (imagePath) => new Promise((resolve, reject) => {
  const image = new Image();

  image.onload = function() {
    resolve(image);
  };

  image.src = imagePath;
})

const drawBackground = (image) => {
  context.drawImage(image, 0, 0, width, height);
}

getImage(imageInput.value)
  .then(image => {
    state.image = image;
    render();
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  margin: 0;
  height: 100%;
  box-sizing: border-box;
}

#box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

#wrapper {
  background: white;
}

#textInput, #imageInput {
  width: 300px;
  padding: 1rem;
  background: transparent;
  border: none;
}

#canvas {
  position: absolute;
  z-Index: -1;
}</code>```

<canvas id="canvas"></canvas>

    <input id="imageInput" type="text" placeholder="Enter src or dataUri of an image...">

      <input id="textInput" type="text" placeholder="Enter text to show up...">

```

Title: Javascript Canvas: Drawing over picture

Body:
I have been having a problem with a drawing on a canvas. I want the user to be able to change the background on the canvas and I will eventually want to be able to type something in an input box and it will appear on the canvas in boxes. I have been trying to get more on the screen after they have choosen a background (which works fine), but when I try to add just a simple box I can't. I have been trying to do it in different parts of the code but doesn't work for me, and haven't been able to find a solution.

So what I am asking, is there a specific way you have to do it in order to have
a image (choosen with a select tag, which I already have working), and be able to draw a box ontop of the image choosen. Hope someone can explain to me how I will be able to do so!

function load(){
  draw()
}

//Canvas change background
function draw(){
  changeBackground("assets/images/1.jpg");
}

function changeBackground(imagePath){
  var c=document.getElementById("myCanvas");
  var ctx=c.getContext("2d");
  var img=new Image();
  img.onload = function(){
        ctx.drawImage(img,0,0,954,507);
  };
  img.src=imagePath;
}

function background(){
  var imageN = document.getElementById("imageselector").value;
  console.log("Image picked as a Background: " + imageN)
  changeBackground("assets/images/" + imageN + ".jpg");
}

Body:
Let this be a good foundation for your app!

Happy coding!

const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const imageInput = document.querySelector("#imageInput");
const textInput = document.querySelector("#textInput");
const imageUrl = 'https://i.picsum.photos/id/944/600/600.jpg';

imageInput.value = imageUrl;
const state = {
  image: null,
  text: ''
}

const width = window.innerWidth;
const height = window.innerHeight;;
canvas.width = width;
canvas.height = height;

textInput.addEventListener("keydown", ({key}) => {
  const value = textInput.value;

  if(key === "Backspace") {
    state.text = value.substring(0, value.length - 1);
  }
  else {
    state.text = value + key;
  }

  render();
})

imageInput.addEventListener("input", () => {
  getImage(imageInput.value)
    .then(image => {
      state.image = image;
      render();
    })
})

const render = () => {
  clear();
  drawBackground(state.image);
  drawText(state.text);
}

const drawText = (text) => {
  context.font = "40px Comic Sans";
  context.fillStyle = "white";
  const textMeasure = context.measureText(text);
  context.fillText(text, width / 2 - textMeasure.width / 2, height / 5);
}

const clear = () => {
  context.fillStyle = "white";
  context.fillRect(0, 0, width, height);
}

const getImage = (imagePath) => new Promise((resolve, reject) => {
  const image = new Image();

  image.onload = function() {
    resolve(image);
  };

  image.src = imagePath;
})

const drawBackground = (image) => {
  context.drawImage(image, 0, 0, width, height);
}

getImage(imageInput.value)
  .then(image => {
    state.image = image;
    render();
  })

html, body {
  margin: 0;
  height: 100%;
  box-sizing: border-box;
}

#box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

#wrapper {
  background: white;
}

#textInput, #imageInput {
  width: 300px;
  padding: 1rem;
  background: transparent;
  border: none;
}

#canvas {
  position: absolute;
  z-Index: -1;
}

<canvas id="canvas"></canvas>
<div id="box">
  <div id="wrapper">
    <input id="imageInput" type="text" placeholder="Enter src or dataUri of an image...">
    <div>
      <input id="textInput" type="text" placeholder="Enter text to show up...">
    </div>
  </div>
</div>


问:
Angular 7: Using a mat-select: Getting the options for mat-option dynamically creates a never ending loop
The goal is to change the options for my dropdown depending on some conditions in my angular component.
The html looks like this:

```<code>                <mat-label>{{jobStatus}}</mat-label>
                <mat-select [formControl]="jobStatusModificationControl" panelClass="mcCoyDropDown">
                  <mat-option *ngFor="let option of getJobStatusModificationOptions()" [value]="option.value"
                    (onSelectionChange)="changeJobStatus($event)">
                    {{option.option}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
</code>```

The component looks like this:

```<code>getJobStatusModificationOptions() {
    let jobStatusModificationOptions = [
      { option: "Close Job", value: JobStatusEnum.Closed },
      { option: "Activate Job", value: JobStatusEnum.Active }
    ];

    if (this.jobStatus == JobStatusEnum.Closed) {
      jobStatusModificationOptions = [
        { option: "Open Job", value: JobStatusEnum.Closed },
        { option: "Activate Job", value: JobStatusEnum.Active }
      ];
    }
    else if (this.jobStatus == JobStatusEnum.Active) {
      jobStatusModificationOptions = [
        { option: "Close Job", value: JobStatusEnum.Closed },
        { option: "Open Job", value: JobStatusEnum.Opened }
      ];
    }
    return jobStatusModificationOptions;
</code>```

So depending on the conditions, the jobStatusModificationOptions will change.  I only call this function in the html and not in the ngOnInit().
The result is a never ending look.  I can put a break point at the line return jobStatusModificationOptions and hit it all day long.

Is there a way to set these mat-options dynamically or do I need to set up 3 drop downs and use ngFor with the conditions.  I did not want to do it that way because it is so messy.

答:
The problem here is that every time getJobStatusModificationOptions() is called it returns a new pointer despite internal data is the same.

try to keep pointer of the returned value between calls the same if data is the same.

For example like that:

private readonly statuses = {
    [JobStatusEnum.Closed]: [
        {option: "Open Job", value: JobStatusEnum.Closed},
        {option: "Activate Job", value: JobStatusEnum.Active},
    ],
    [JobStatusEnum.Active]: [
        {option: "Close Job", value: JobStatusEnum.Closed},
        {option: "Open Job", value: JobStatusEnum.Opened},
    ],
    [JobStatusEnum.Opened]: [
        {option: "Close Job", value: JobStatusEnum.Closed},
        {option: "Activate Job", value: JobStatusEnum.Active},
    ]
};

getJobStatusModificationOptions() {
    if (this.jobStatus == JobStatusEnum.Closed) {
        return this.statuses[JobStatusEnum.Closed];
    }
    if (this.jobStatus == JobStatusEnum.Active) {
        return this.statuses[JobStatusEnum.Active];
    }
    return return this.statuses[JobStatusEnum.Opened];
}
```

Now angular can detect that the returned value hasn't been changed and skip rerender.

Body:
The goal is to change the options for my dropdown depending on some conditions in my angular component.
The html looks like this:

                <mat-label>{{jobStatus}}</mat-label>
                <mat-select [formControl]="jobStatusModificationControl" panelClass="mcCoyDropDown">
                  <mat-option *ngFor="let option of getJobStatusModificationOptions()" [value]="option.value"
                    (onSelectionChange)="changeJobStatus($event)">
                    {{option.option}}
                  </mat-option>
                </mat-select>
              </mat-form-field>

The component looks like this:

getJobStatusModificationOptions() {
    let jobStatusModificationOptions = [
      { option: "Close Job", value: JobStatusEnum.Closed },
      { option: "Activate Job", value: JobStatusEnum.Active }
    ];

    if (this.jobStatus == JobStatusEnum.Closed) {
      jobStatusModificationOptions = [
        { option: "Open Job", value: JobStatusEnum.Closed },
        { option: "Activate Job", value: JobStatusEnum.Active }
      ];
    }
    else if (this.jobStatus == JobStatusEnum.Active) {
      jobStatusModificationOptions = [
        { option: "Close Job", value: JobStatusEnum.Closed },
        { option: "Open Job", value: JobStatusEnum.Opened }
      ];
    }
    return jobStatusModificationOptions;

So depending on the conditions, the jobStatusModificationOptions will change.  I only call this function in the html and not in the ngOnInit().
The result is a never ending look.  I can put a break point at the line return jobStatusModificationOptions and hit it all day long.

Is there a way to set these mat-options dynamically or do I need to set up 3 drop downs and use ngFor with the conditions.  I did not want to do it that way because it is so messy.

Body:
The problem here is that every time getJobStatusModificationOptions() is called it returns a new pointer despite internal data is the same.

try to keep pointer of the returned value between calls the same if data is the same.

For example like that:

private readonly statuses = {
    [JobStatusEnum.Closed]: [
        {option: "Open Job", value: JobStatusEnum.Closed},
        {option: "Activate Job", value: JobStatusEnum.Active},
    ],
    [JobStatusEnum.Active]: [
        {option: "Close Job", value: JobStatusEnum.Closed},
        {option: "Open Job", value: JobStatusEnum.Opened},
    ],
    [JobStatusEnum.Opened]: [
        {option: "Close Job", value: JobStatusEnum.Closed},
        {option: "Activate Job", value: JobStatusEnum.Active},
    ]
};

getJobStatusModificationOptions() {
    if (this.jobStatus == JobStatusEnum.Closed) {
        return this.statuses[JobStatusEnum.Closed];
    }
    if (this.jobStatus == JobStatusEnum.Active) {
        return this.statuses[JobStatusEnum.Active];
    }
    return return this.statuses[JobStatusEnum.Opened];
}

Now angular can detect that the returned value hasn't been changed and skip rerender.


问:
Multiple process to catch uncaught exception?
I am developing a module that will be installed on multiple app. On of our client expressed concern about the potential of our module crashing making his app crash. I want to find a way to catch all uncaught exceptions that my module can throw. The module is composed of a service and 2-3 activities who have very little communication with the main app.

To catch those exceptions thrown by a handful of classes, and only those classes, what whould be the best option ? I have considered using Thread.UncaughtExceptionHandler which catch all exception thrown by a thread and putting all thoses classes in a separate process (with the android:process attribute), but I was told that using multiple processes can impact performance and battery usage. Is it possible to start a service and multiple activities in a separate thread without having to rewrite them all ?

答:
You can implement an uncaught exception handler from your library. It will handle the uncaught exceptions that got triggered from threads started from your library.
Don't forget to pass it to the DefaultUncaughtExceptionHandler.
If the app implemented its own UncaughtExceptionHandler it will handle it as well.