问:
How can I modify the input of multiple EditTexts at the same time, as I only modify one?
I have multiple EditTexts and I want to change the input of all of them at the same time, as I modify only one.(all of them take decimal numbers as input)

I stored the EditTexts in an array named 'editTexts'.

Here's what I tried

```<code>//Set the listener for each element
for (int i=0; i<editTexts.length; i++) {
        final int finalI = i;
        editTexts[i].addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//if the editText which is currently edited is empty, set the input for all the rest to be '0.0'
                if (editTexts[finalI].getText().toString().trim().length() == 0) {
                    for(EditText e : editTexts) {
                        if (e == editTexts[finalI])
                            continue;
                        e.setText("0.0");
                    }
                } else {
                    float no = Float.parseFloat(s.toString() + "");
//Set the input of all the other editTexts to be the decimal number entered, multiplied by 2
                    for(EditText e : editTexts){
                        if(e == editTexts[finalI])
                            continue;
                        e.setText(no*2+"");
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        })
    }
</code>```

In this case the multiplication coefficient is just an example, it's not always gonna be 2. I used it just to test it out.

For some reason, when I change the input value, the app freezes.

Any help? Thanks!

答:
Try it like this:

```<code>// et_x1, et_x2 and et_x3 are ids of EditTexts
//set inputType for all EditTexts as numberDecimal

EditText editText1 = findViewById(R.id.et_x1);
final EditText editText2 = findViewById(R.id.et_x2);
final EditText editText3 = findViewById(R.id.et_x3);

editText1.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String value = s.toString();
        double x;
        if (!value.equals("")) {
            x = Double.parseDouble(value);
        } else {
            x = 0.0;
        }
        editText2.setText(Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 2)))));
        editText3.setText(
                Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 3)))));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
</code>```

Hope it helps you!

Body:
I have multiple EditTexts and I want to change the input of all of them at the same time, as I modify only one.(all of them take decimal numbers as input)

I stored the EditTexts in an array named 'editTexts'.

Here's what I tried

//Set the listener for each element
for (int i=0; i<editTexts.length; i++) {
        final int finalI = i;
        editTexts[i].addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//if the editText which is currently edited is empty, set the input for all the rest to be '0.0'
                if (editTexts[finalI].getText().toString().trim().length() == 0) {
                    for(EditText e : editTexts) {
                        if (e == editTexts[finalI])
                            continue;
                        e.setText("0.0");
                    }
                } else {
                    float no = Float.parseFloat(s.toString() + "");
//Set the input of all the other editTexts to be the decimal number entered, multiplied by 2
                    for(EditText e : editTexts){
                        if(e == editTexts[finalI])
                            continue;
                        e.setText(no*2+"");
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        })
    }

In this case the multiplication coefficient is just an example, it's not always gonna be 2. I used it just to test it out.

For some reason, when I change the input value, the app freezes.

Any help? Thanks!

Body:
Try it like this:

// et_x1, et_x2 and et_x3 are ids of EditTexts
//set inputType for all EditTexts as numberDecimal

EditText editText1 = findViewById(R.id.et_x1);
final EditText editText2 = findViewById(R.id.et_x2);
final EditText editText3 = findViewById(R.id.et_x3);

editText1.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String value = s.toString();
        double x;
        if (!value.equals("")) {
            x = Double.parseDouble(value);
        } else {
            x = 0.0;
        }
        editText2.setText(Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 2)))));
        editText3.setText(
                Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 3)))));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

Hope it helps you!


来源: stackexchange

问:
Weird diagonal plot with gnuplot plot with images
I am trying to plot 3 variables, where the third column defines the colour palette. The code is called by another program. The data file has scattered data points which are ":" (colon) separated.

The script file used:

```<code>reset
set title "Cluster Properties"
set datafile separator ":"
outfile = sprintf("%s%s", ARG2, "ClusterCount2.png")
set output  outfile
set term pngcairo size 1920, 1080 enhanced font 'Verdana,30'
x_tk = sprintf("%s%s%s", "Sweeps ( X ", ARG6, " )")
set xtics 1,1
set ytics 1,1 font ", 20"
set ytics add (2)
set xlabel x_tk
set ylabel "Cluster Size (Particles)"
set zlabel "Number of Clusters"
set cblabel "Number of Clusters"
set cbtics 0,1 font ", 20"
set autoscale xfix
set yrange [1:*]
set view map

set y2tics 1,1

set grid front xtics y2tics lw 1.5 lt -1 lc rgb 'white'

unset key
plot ARG1 using ($1/ARG6):2:3 with image

reset
</code>```

Gives the following output:

Problematic Plot:

While with doing the same with less data points:

Okay Plot:

Link to the data file: Drive Link to data file

Can someone help me with this, I don't know what's wrong?

答:
Your data file does not contain a line for each pixel in the implied image.
I.e. there are 11 points with x value 50000, 25 with x value 100000, 39 with x value 150000, ...  When the program tries to figure out the number of horizontal and vertical pixels in the image it sees 11 points with the same x coordinate and thinks Aha! one of the image dimensions is 11.  But then after reading the entire data file it knows there are 738 pixels total, and tries to make it an 11xSomething  rectangle.  That obviously doesn't work and it ends up drawing 11 pixels on each vertical line but staggering them to fill the full range of coordinates seen.

In short, your data file does not actually describe a full rectangular array of pixels that can be rendered as an image. You could modify the procedure used to generate the file so that the entire rectangle is filled in, or plot with points pt 5 rather than with image.

Here is the output from

```<code>gnuplot> set pointsize 4
gnuplot> plot 'clusterstat.dat' using ($1/5.e5):2:3 with point pt 5 lc palette
</code>```

Obviously you would want to further adjust the point size, axis ratio, placement of labels etc, but it shows what is there in the data.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to plot 3 variables, where the third column defines the colour palette. The code is called by another program. The data file has scattered data points which are ":" (colon) separated.

The script file used:

reset
set title "Cluster Properties"
set datafile separator ":"
outfile = sprintf("%s%s", ARG2, "ClusterCount2.png")
set output  outfile
set term pngcairo size 1920, 1080 enhanced font 'Verdana,30'
x_tk = sprintf("%s%s%s", "Sweeps ( X ", ARG6, " )")
set xtics 1,1
set ytics 1,1 font ", 20"
set ytics add (2)
set xlabel x_tk
set ylabel "Cluster Size (Particles)"
set zlabel "Number of Clusters"
set cblabel "Number of Clusters"
set cbtics 0,1 font ", 20"
set autoscale xfix
set yrange [1:*]
set view map

set y2tics 1,1

set grid front xtics y2tics lw 1.5 lt -1 lc rgb 'white'

unset key
plot ARG1 using ($1/ARG6):2:3 with image

reset

Gives the following output:

Problematic Plot:

While with doing the same with less data points:

Okay Plot:

Link to the data file: Drive Link to data file

Can someone help me with this, I don't know what's wrong?

Body:
Your data file does not contain a line for each pixel in the implied image.
I.e. there are 11 points with x value 50000, 25 with x value 100000, 39 with x value 150000, ...  When the program tries to figure out the number of horizontal and vertical pixels in the image it sees 11 points with the same x coordinate and thinks Aha! one of the image dimensions is 11.  But then after reading the entire data file it knows there are 738 pixels total, and tries to make it an 11xSomething  rectangle.  That obviously doesn't work and it ends up drawing 11 pixels on each vertical line but staggering them to fill the full range of coordinates seen.

In short, your data file does not actually describe a full rectangular array of pixels that can be rendered as an image. You could modify the procedure used to generate the file so that the entire rectangle is filled in, or plot with points pt 5 rather than with image.

Here is the output from

gnuplot> set pointsize 4
gnuplot> plot 'clusterstat.dat' using ($1/5.e5):2:3 with point pt 5 lc palette

Obviously you would want to further adjust the point size, axis ratio, placement of labels etc, but it shows what is there in the data.


问:
GC Doesn't Delete Circular References in WeakKeyDictionaries?
I have a situation in which I'd like to maintain a mapping from one object to another for as long as the first object exists. My first thought was to use a WeakKeyDictionary.

```<code>import weakref
import gc

class M:
    pass

w = weakref.WeakKeyDictionary()
m = M()
w[m] = some_other_object
del m
gc.collect()
print w.keys()
</code>```

This works fine in most cases. However, in the case where some_other_object is (or has a reference to) m, the M instance will not be garbage collected. (To see an example, replace some_other_object with m)

Of course, if I stored the mapping on the object itself, it would be garbage collected when I deleted it:

```<code>import weakref
import gc

class M:
    pass

m = M()
m.circular_reference = m
r = weakref.ref(m)
del m
gc.collect()
print r
</code>```

Can I achieve the results of the second example using the weakref module (i.e. without mutating m)?

In other words, can I use the weakref module to map an object to itself (or another object that has a strong reference to it) and only keep the object in memory as long as there are other references to it?

答:
Dealing with circular references like this is likely to do one's head in, but, undaunted, I shall try to answer your question anyway.

A python dictionary stores references to both its keys and it values. A WeakKeyDictionary stores weak references to its keys, but strong references to its values. So in your first example, if you set w[m] = m the dictionary w has a weak reference to m as a key and a strong reference to m as a value.

Python's weakref module also has a WeakValueDictionary which has strong references to its keys and weak references to its values, but this won't solve your problem.

What you really want is a dictionary that has weak references to both its keys and values. The following code explicitly makes each value in the dictionary a weak reference:

```<code>import weakref
import gc

class M():
  pass

class Other():
  pass

m = M()
w = weakref.WeakKeyDictionary()
w[m] = weakref.ref(m)
print len(w.keys()) # prints 1
del m
print len(w.keys()) # prints 0

m = M()
o = Other()
o.strong_ref = m
w[m] = weakref.ref(o)
print len(w.keys()) # prints 1
del m
print len(w.keys()) # prints 1
del o
print len(w.keys()) # prints 0
</code>```

You could make the value a weak reference automatically by sub-classing WeakKeyDictionary. Note, however, that this does not behave like a real WeakValueDictionary because it does not have a callback to notify the dictionary when a value has been deleted.

```<code>class MyWeakKeyValueDictionary(weakref.WeakKeyDictionary):
    def __init__(self):
        weakref.WeakKeyDictionary.__init__(self)

    def __setitem__(self, key, value):
        weakref.WeakKeyDictionary.__setitem__(self, key, weakref.ref(value))

w2 = MyWeakKeyValueDictionary()
m = M()
w2[m] = m
print len(w2.keys()) # prints 1
del m
print len(w2.keys()) # prints 0

m = M()
o = Other()
o.strong_ref = m
w2[m] = o
print len(w2.keys()) # prints 1
del m
print len(w2.keys()) # prints 1
del o
print len(w2.keys()) # prints 0
</code>```

In the end, however, I fear trying to deal with circular references like this may cause more problems than it's worth.

ContentLicense: CC BY-SA 3.0

Body:
I have a situation in which I'd like to maintain a mapping from one object to another for as long as the first object exists. My first thought was to use a WeakKeyDictionary.

import weakref
import gc

class M:
    pass

w = weakref.WeakKeyDictionary()
m = M()
w[m] = some_other_object
del m
gc.collect()
print w.keys()

This works fine in most cases. However, in the case where some_other_object is (or has a reference to) m, the M instance will not be garbage collected. (To see an example, replace some_other_object with m)

Of course, if I stored the mapping on the object itself, it would be garbage collected when I deleted it:

import weakref
import gc

class M:
    pass

m = M()
m.circular_reference = m
r = weakref.ref(m)
del m
gc.collect()
print r

Can I achieve the results of the second example using the weakref module (i.e. without mutating m)?

In other words, can I use the weakref module to map an object to itself (or another object that has a strong reference to it) and only keep the object in memory as long as there are other references to it?

Body:
Dealing with circular references like this is likely to do one's head in, but, undaunted, I shall try to answer your question anyway.

A python dictionary stores references to both its keys and it values. A WeakKeyDictionary stores weak references to its keys, but strong references to its values. So in your first example, if you set w[m] = m the dictionary w has a weak reference to m as a key and a strong reference to m as a value.

Python's weakref module also has a WeakValueDictionary which has strong references to its keys and weak references to its values, but this won't solve your problem.

What you really want is a dictionary that has weak references to both its keys and values. The following code explicitly makes each value in the dictionary a weak reference:

import weakref
import gc

class M():
  pass

class Other():
  pass

m = M()
w = weakref.WeakKeyDictionary()
w[m] = weakref.ref(m)
print len(w.keys()) # prints 1
del m
print len(w.keys()) # prints 0

m = M()
o = Other()
o.strong_ref = m
w[m] = weakref.ref(o)
print len(w.keys()) # prints 1
del m
print len(w.keys()) # prints 1
del o
print len(w.keys()) # prints 0

You could make the value a weak reference automatically by sub-classing WeakKeyDictionary. Note, however, that this does not behave like a real WeakValueDictionary because it does not have a callback to notify the dictionary when a value has been deleted.

class MyWeakKeyValueDictionary(weakref.WeakKeyDictionary):
    def __init__(self):
        weakref.WeakKeyDictionary.__init__(self)

    def __setitem__(self, key, value):
        weakref.WeakKeyDictionary.__setitem__(self, key, weakref.ref(value))

w2 = MyWeakKeyValueDictionary()
m = M()
w2[m] = m
print len(w2.keys()) # prints 1
del m
print len(w2.keys()) # prints 0

m = M()
o = Other()
o.strong_ref = m
w2[m] = o
print len(w2.keys()) # prints 1
del m
print len(w2.keys()) # prints 1
del o
print len(w2.keys()) # prints 0

In the end, however, I fear trying to deal with circular references like this may cause more problems than it's worth.


问:
Django custom 404 page not recognized
I've placed a custom 404.html page in my root templates directory, but whenever an invalid URL is requested, the default error page is given. Strangely in production, "Internal Server Error" is displayed, while "Not Found.
The requested resource was not found on this server." is displayed on localhost.

Debug is set to false in both cases.

app/templates/app/404.html:

```<code>{% extends "app/base.html" %}

{% block page_header %}
    <h1>404</h1>
    <h2>The page you requested is not available.</h2>
    <i class="far fa-meh"></i>
{% endblock page_header %}
</code>```

答: I had to create a new templates folder in the root (not in an app folder) without any sub-folders. The file is located now in root/templates/404.html

Title: Django custom 404 page not recognized

Body:
I've placed a custom 404.html page in my root templates directory, but whenever an invalid URL is requested, the default error page is given. Strangely in production, "Internal Server Error" is displayed, while "Not Found.
The requested resource was not found on this server." is displayed on localhost.

Debug is set to false in both cases.

app/templates/app/404.html:

{% extends "app/base.html" %}

{% block page_header %}

404

The page you requested is not available.

{% endblock page_header %}


问:
how to forward request to https backend
I have a website running at https://myexample.com:32437. Now I want to access it with URL https://myexample.com.

I used Nginx as a reverse proxy and tried to configure upstream like

```<code>upstream cluster{
    server myexample.com:32437;
}

server{
    listen      80;
    server_name myexample.com;

    access_log  /var/log/nginx/nginx.access.log;
    error_log   /var/log/nginx/nginx.error.log;

    proxy_buffers 16 64k;
    proxy_buffer_size 128k;

    location / {
        proxy_pass  https://cluster;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;

        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
    }

}
</code>```

but this is not working. I am getting "ERR_CONNECTION_REFUSED" error in the browser.
Can anyone please help me with configuration.

答:
I think the problem is that you did not set HTTPS listener and valid certificate, because you are trying to establish secure connection to https://myexample.com.

And also please note, if you want to proxy pass HTTPS traffic, then an upstream should be configured to accept HTTPS connections.
And since you accept HTTPS connections and then proxying to HTTPS, it’s enough to specify the certificate settings once in the server section.

Add https listener and certificate settings to your config in server section.

```<code>listen 443 ssl;
ssl_certificate     /path_to_cert/server.crt;
ssl_certificate_key /path_to_key/server.key;
</code>```

Remove those unneeded lines from your config:

```<code>proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
</code>```

Here is the link which can explain such behavior in more details.

Title: how to forward request to https backend

Body:
I have a website running at https://myexample.com:32437. Now I want to access it with URL https://myexample.com.

I used Nginx as a reverse proxy and tried to configure upstream like

upstream cluster{
    server myexample.com:32437;
}

server{
    listen      80;
    server_name myexample.com;

    access_log  /var/log/nginx/nginx.access.log;
    error_log   /var/log/nginx/nginx.error.log;

    proxy_buffers 16 64k;
    proxy_buffer_size 128k;

    location / {
        proxy_pass  https://cluster;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;

        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
    }

}

but this is not working. I am getting "ERR_CONNECTION_REFUSED" error in the browser.
Can anyone please help me with configuration.

Body:
I think the problem is that you did not set HTTPS listener and valid certificate, because you are trying to establish secure connection to https://myexample.com.

And also please note, if you want to proxy pass HTTPS traffic, then an upstream should be configured to accept HTTPS connections.
And since you accept HTTPS connections and then proxying to HTTPS, it’s enough to specify the certificate settings once in the server section.

Add https listener and certificate settings to your config in server section.

listen 443 ssl;
ssl_certificate     /path_to_cert/server.crt;
ssl_certificate_key /path_to_key/server.key;

Remove those unneeded lines from your config:

proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;

Here is the link which can explain such behavior in more details.


问:
Providing un-intrusive messages on an iPhone
This is kind of a silly question, but I cannot find the answer as I don't know the terms with which to search for it.

I am looking for a simple way of giving a 'status' message like 'Data updated' to the user without necessarily interrupting what he/she is doing (but have a option I guess in some instances to tab it an perform an action).

For example; some Apps give a rounded square semi-transparent with 'Lock screen/rotation' when an iPhone is rotated, I am look for something similar (or like the square box 'Build Complete in Xcode 4').

Is there an easy way of doing this?
Thanks a million in advance!

答:
As @kubi has pointed out, MTStatusBarOverlay is a good one, and I've passed Apple reviewer inspection with it.  However I just found something that looks fraking awesome...

Tweetbot-Like Alert Panels (Blog), and the repository is MKInfoPanelDemo at Github.

ContentLicense: CC BY-SA 2.5


问:
why list of users are not shown in the django template?
my goal is to show user list on the template in django. but it's not rendering the users.

accounts/models.py:

```<code>class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)
    name = models.CharField(max_length=200, blank=True)
</code>```

accounts/admin.py:

```<code>class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username', 'age', 'is_staff', ]
admin.site.register(CustomUser, CustomUserAdmin)
</code>```

accounts/form.py:

```<code>class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('age',)
class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields
</code>```

accounts/views.py:

```<code>class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
class UsersView(TemplateView):
    template_name='homepage.html'
    def get_context_data(self,**kwargs):
        context = super(UsersView,self).get_context_data(**kwargs)
        context['object_list'] = CustomUser.objects.all()
        return context
</code>```

and blogapp/urls.py:

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/',include('accounts.urls')),
    path('accounts/',include('django.contrib.auth.urls')),
    path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'),
]
</code>```

templates/homepage.html:

```<code>{% block content %}
<h1>Online users</h1>
<ul>
    {% for user in object_list %}
        <li class="user">{{ user }}</li>
    {% endfor %}
</ul>
{% endblock content %}
</code>```

when i execute python manage.py runserver it is just showing the head line Online users but there is no list of users. i have created three users in admin but it is not showing anything in the template and there is no error.

will you please help me on this please?

答:
i found the solution.

in blogapp/urls.py, i have to change this:

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('accounts.urls')), #here is the change...delete accounts/
    path('accounts/',include('django.contrib.auth.urls')),
    path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'),
]
</code>```

after than i have to change some settings like LOGIN_REDIRECT_URL and LOGIN_REDIRECT_URL because they were redirecting the pages after login and logout. it took couple of full projects delete. i dun know why it is occurring but did my job. if someone knows, please mention.

thanx everyone

Body:
my goal is to show user list on the template in django. but it's not rendering the users.

accounts/models.py:

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)
    name = models.CharField(max_length=200, blank=True)

accounts/admin.py:

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username', 'age', 'is_staff', ]
admin.site.register(CustomUser, CustomUserAdmin)

accounts/form.py:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('age',)
class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields

accounts/views.py:

class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'
class UsersView(TemplateView):
    template_name='homepage.html'
    def get_context_data(self,**kwargs):
        context = super(UsersView,self).get_context_data(**kwargs)
        context['object_list'] = CustomUser.objects.all()
        return context

and blogapp/urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/',include('accounts.urls')),
    path('accounts/',include('django.contrib.auth.urls')),
    path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'),
]

templates/homepage.html:

{% block content %}

Online users

    {% for user in object_list %}

{{ user }}

    {% endfor %}

{% endblock content %}

when i execute python manage.py runserver it is just showing the head line Online users but there is no list of users. i have created three users in admin but it is not showing anything in the template and there is no error.

will you please help me on this please?

Body:
i found the solution.

in blogapp/urls.py, i have to change this:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('accounts.urls')), #here is the change...delete accounts/
    path('accounts/',include('django.contrib.auth.urls')),
    path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'),
]

after than i have to change some settings like LOGIN_REDIRECT_URL and LOGIN_REDIRECT_URL because they were redirecting the pages after login and logout. it took couple of full projects delete. i dun know why it is occurring but did my job. if someone knows, please mention.

thanx everyone


问:
Center a button in a Linear layout
I am using a linear layout to display a pretty light initial screen.  It has 1 button that is supposed to centre in the screen both horizontally and vertically.  However no matter what I try to do the button will top align centre.  I have included the XML below, can some one point me in the right direction?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageButton android:id="@+id/btnFindMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:background="@drawable/findme"></ImageButton>

</LinearLayout>
</code>```

答:
This is working for me.</p>

```<code>android:layout_alignParentEnd="true"
</code>```

Title: Center a button in a Linear layout

Body:
I am using a linear layout to display a pretty light initial screen.  It has 1 button that is supposed to centre in the screen both horizontally and vertically.  However no matter what I try to do the button will top align centre.  I have included the XML below, can some one point me in the right direction?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageButton android:id="@+id/btnFindMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:background="@drawable/findme"></ImageButton>

</LinearLayout>

Body:
This is working for me.

android:layout_alignParentEnd="true"


问:
Problem with adding two elements in MATLAB
I'm trying to write a function for blurring images. (I'm aware of imfilter command. Just trying to implement it in my own way). I've the following function which takes a uint8 matrix as argument img.

```<code>function output=bl(img,w)
row=size(img,1);
col=size(img,2);
g_size=(2*w+1)^2;
output=uint8(zeros(row,col));
for ii=1:row
    for jj=1:col
        s=0;
        corner=[ii jj]-w;
        for r=corner(1):(corner(1)+(2*w))
            for c=corner(2):(corner(2)+(2*w))
                if((r>0 && r<=row) && (c>0 && c<=col))
                    s=s+img(r,c); %PROBLEMATIC LINE
                    fprintf('The value of s is %d\n',s);
                end
            end
        end
        m=s/g_size;
        output(ii,jj)=fix(m);
        s=0;
    end
end
end
</code>```

I'm having trouble with the line marked as "PROBLEMATIC LINE". The line of code was supposed to add previous value of s with img(c,r). But surprisingly each time the line runs, the previous value of s becomes 0. What am I doing wrong here? How can I solve this?

答:
The problem is that your problematic line casts the result to a uint8. If you add more and more integers, you will eventually exceed the limit value of 255 (more cannot be represented with 8 bit). See:

```<code>s = 0 % s = 0; class double
s = s + uint8(200) % s = 200; class uint8
s = s + uint8(200) % s = 255; class uint8
</code>```

The reason for this is that MATLAB cannot add different types, so it implicitly cast its default type double to a unit8. You will see that this fails if you would initialize s as a certain type other than double

```<code>s = uint16(0);
s = s + uint8(200) % this will produce an error
</code>```

Error using  +

  Integers can only be combined with integers of the
  same class, or scalar doubles.

You will get around this by casting the image manually:

```<code>s = uint16(0) % s = 0; class uint16
img = uint8(200); % img = 200; class uint8
s = s + uint16( img ) % s = 200; class uint16
s = s + uint16( img ) % s = 400; class uint16
</code>```

uint16 should suite your needs as you can represent numbers up to 2^16-1 = 65535 with it.

Body:
I'm trying to write a function for blurring images. (I'm aware of imfilter command. Just trying to implement it in my own way). I've the following function which takes a uint8 matrix as argument img.

function output=bl(img,w)
row=size(img,1);
col=size(img,2);
g_size=(2*w+1)^2;
output=uint8(zeros(row,col));
for ii=1:row
    for jj=1:col
        s=0;
        corner=[ii jj]-w;
        for r=corner(1):(corner(1)+(2*w))
            for c=corner(2):(corner(2)+(2*w))
                if((r>0 && r<=row) && (c>0 && c<=col))
                    s=s+img(r,c); %PROBLEMATIC LINE
                    fprintf('The value of s is %d\n',s);
                end
            end
        end
        m=s/g_size;
        output(ii,jj)=fix(m);
        s=0;
    end
end
end

I'm having trouble with the line marked as "PROBLEMATIC LINE". The line of code was supposed to add previous value of s with img(c,r). But surprisingly each time the line runs, the previous value of s becomes 0. What am I doing wrong here? How can I solve this?

Body:
The problem is that your problematic line casts the result to a uint8. If you add more and more integers, you will eventually exceed the limit value of 255 (more cannot be represented with 8 bit). See:

s = 0 % s = 0; class double
s = s + uint8(200) % s = 200; class uint8
s = s + uint8(200) % s = 255; class uint8

The reason for this is that MATLAB cannot add different types, so it implicitly cast its default type double to a unit8. You will see that this fails if you would initialize s as a certain type other than double

s = uint16(0);
s = s + uint8(200) % this will produce an error

Error using  +

  Integers can only be combined with integers of the
  same class, or scalar doubles.

You will get around this by casting the image manually:

s = uint16(0) % s = 0; class uint16
img = uint8(200); % img = 200; class uint8
s = s + uint16( img ) % s = 200; class uint16
s = s + uint16( img ) % s = 400; class uint16

uint16 should suite your needs as you can represent numbers up to 2^16-1 = 65535 with it.


问:
How can I extract text and lists with BeautifulSoup

Start with BeautifulSoup I was using using SCRAPY to extract the OER data but I have 3 problems with:

1. The amount of: visits, times saved .. because xpath used something like "/dl[2]/dd[2]/"

with scrapy

cant_visitas = response.xpath ("//// i [@ class = 'fa fa-eye'] / following-sibling :: span [1] / text ()"). extract_first ()

with BeautifulSoup I can't extract the value (someone knows if it is possible to use a tag with spaces)

cant_guardados = soup.find ('li', {'id': 'Number of saves'}) #. find ('span'). get_text ()

2. And the lists as is the case of the degrees .getall() (with JSON TYPE return) in BeautifulSoup it seems that it is find_all only that I don't know how to do it because using xpath "everything is nested dl [2] / dd [3 ] "

with scrapy

degrees = response.xpath ('normalize-space (// div [@ class = "material-details"] / dl [2] / dd [3] / text ())'). getall ()

with BeautifulSoup

degrees = soup.find ('div', 'material-details'). select ('dl: nth-of-type (2)> dd: nth-of-type (3)')

3. How could I extract the average value of the valuation, since it is found as an attribute of the div

amount_stars = soup.find('div', 'item-rating').find('div', 'stars').find_all('i', 'active-star') #div data-rating-value
amount_stars = len(amount_stars)
```

This brings the number of active stars not their actual rating

PS: I think the closest thing to xpath in BeautifulSoup is the select but the safest thing is that I'm wrong

答:
This script will get all information from the webpage using CSS selectors:

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://www.oercommons.org/courses/randomized-synthesis-project'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

number_of_visits = soup.select_one('[title="Number of visits"]').get_text(strip=True)
number_of_saves  = soup.select_one('[title="Number of saves"]').get_text(strip=True)
material_type = soup.select_one('dt:contains("Material Type:") + dd').get_text(strip=True)
data_rating = soup.select_one('[data-rating-value]')['data-rating-value']

print('Number of visits: {}'.format(number_of_visits))
print('Number of saves : {}'.format(number_of_saves))
print('Material type   : {}'.format(material_type))
print('Data rating     : {}'.format(data_rating))
</code>```

Prints:

```<code>Number of visits: 62
Number of saves : 3
Material type   : Activity/Lab,Lesson
Data rating     : 0.0
</code>```

More about CSS selectors here.

EDIT: This should be compatible with BeautifulSoup 4.6.0:

```<code>number_of_visits = soup.select_one('[title="Number of visits"]').get_text(strip=True)
number_of_saves  = soup.select_one('[title="Number of saves"]').get_text(strip=True)
material_type = soup.find(lambda tag: tag.name=='dt' and 'Material Type:' in tag.text).find_next('dd').get_text(strip=True)
data_rating = soup.select_one('[data-rating-value]')['data-rating-value']
</code>```

Body:
Start with BeautifulSoup I was using using SCRAPY to extract the OER data but I have 3 problems with:

1. The amount of: visits, times saved .. because xpath used something like "/dl[2]/dd[2]/"

with scrapy

cant_visitas = response.xpath ("//// i [@ class = 'fa fa-eye'] / following-sibling :: span [1] / text ()"). extract_first ()

with BeautifulSoup I can't extract the value (someone knows if it is possible to use a tag with spaces)

cant_guardados = soup.find ('li', {'id': 'Number of saves'}) #. find ('span'). get_text ()

2. And the lists as is the case of the degrees .getall() (with JSON TYPE return) in BeautifulSoup it seems that it is find_all only that I don't know how to do it because using xpath "everything is nested dl [2] / dd [3 ] "

with scrapy

degrees = response.xpath ('normalize-space (// div [@ class = "material-details"] / dl [2] / dd [3] / text ())'). getall ()

with BeautifulSoup

degrees = soup.find ('div', 'material-details'). select ('dl: nth-of-type (2)> dd: nth-of-type (3)')

3. How could I extract the average value of the valuation, since it is found as an attribute of the div

amount_stars = soup.find('div', 'item-rating').find('div', 'stars').find_all('i', 'active-star') #div data-rating-value
amount_stars = len(amount_stars)

This brings the number of active stars not their actual rating

PS: I think the closest thing to xpath in BeautifulSoup is the select but the safest thing is that I'm wrong

Body:
This script will get all information from the webpage using CSS selectors:

import requests
from bs4 import BeautifulSoup

url = 'https://www.oercommons.org/courses/randomized-synthesis-project'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

number_of_visits = soup.select_one('[title="Number of visits"]').get_text(strip=True)
number_of_saves  = soup.select_one('[title="Number of saves"]').get_text(strip=True)
material_type = soup.select_one('dt:contains("Material Type:") + dd').get_text(strip=True)
data_rating = soup.select_one('[data-rating-value]')['data-rating-value']

print('Number of visits: {}'.format(number_of_visits))
print('Number of saves : {}'.format(number_of_saves))
print('Material type   : {}'.format(material_type))
print('Data rating     : {}'.format(data_rating))

Prints:

Number of visits: 62
Number of saves : 3
Material type   : Activity/Lab,Lesson
Data rating     : 0.0

More about CSS selectors here.

EDIT: This should be compatible with BeautifulSoup 4.6.0:

number_of_visits = soup.select_one('[title="Number of visits"]').get_text(strip=True)
number_of_saves  = soup.select_one('[title="Number of saves"]').get_text(strip=True)
material_type = soup.find(lambda tag: tag.name=='dt' and 'Material Type:' in tag.text).find_next('dd').get_text(strip=True)
data_rating = soup.select_one('[data-rating-value]')['data-rating-value']


问:
Pushing File into Android Device
I have developed an application which read text file. In Emulator I have push the file in
\Data\Data\PackageName\File.txt and its working fine. But when I try to push file in Device its generate the error Read Only File System. I have try to remount directory as writable but the same error. Please help me how can I push file into device.

答: In practice, we can push such file in assets folder. Assets folder is there for you to put such raw files to be used inside the application.</p>

Title: Pushing File into Android Device


问:
Load dataset from amazon S3 to jupyter notebook on EC2
I want to try image segmentation with deep learning using AWS. I have my data stored on Amazon S3 and I'd like to access it from a Jupyter Notebook which is running on an Amazon EC2 instance.

I'm planning on using Tensorflow for segmentation, therefore it seemed appropriate to me to use options provided by Tensorflow themselves (https://www.tensorflow.org/deploy/s3) as it feels that in the end I want my data to be represented in the format of tf.Dataset. However, it didn't quite work out for me. I've tried the following:

```<code>filenames = ["s3://path_to_first_image.png", "s3://path_to_second_image.png"]
dataset = tf.data.TFRecordDataset(filenames)

iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
for i in range(2):
    print(sess.run(next_element))
</code>```

I get the following error:

```<code>OutOfRangeError: End of sequence
 [[Node: IteratorGetNext_6 = IteratorGetNext[output_shapes=[[]], output_types=[DT_STRING], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator_6)]]
</code>```

I'm quite new to tensorflow and have just recently started trying out some stuff with AWS, so I hope that my mistake is gonna be obvious to someone with more experience. I would greatly appreciate any help or advice! Maybe it's even the wrong way and I'm better off with something like boto3 (also stumbled upon it, but thought that tf would be more appropriate in my case) or something else?

P.S. Tensorflow also recommends to test a setup with the following piece:

```<code>from tensorflow.python.lib.io import file_io
print (file_io.stat('s3://path_to_image.png'))
</code>```

For me this leads to Object doesn't exist error, though the object certainly exists and it's being listed among others if I use

```<code>for obj in s3.Bucket(name=MY_BUCKET_NAME).objects.all():
print(os.path.join(obj.bucket_name, obj.key))
</code>```

I also have my credentials filled in /.aws/credentials. What might be the problem here?

答:
Not a direct answer to your question but still something I noticed as to why you can't load data using Tensorflow.

The files in your filenames are .png and not in the .tfrecord file format which is a binary storage format. So, tf.data.TFRecordDataset(filenames) shouldn't work.

I think the following will work. Note: this is for TF2, not sure if it is the same for TF1. A similar example can be found here at TensorFlow's web site tensorflow example

Step 1

Load your files into a TensorFlow dataset with tf.data.Dataset.list_files.

import tensorflow as tf

list_ds = tf.data.Dataset.list_files(filenames)

Step 2

Make a function that will be applied to each element in the dataset by using map; this will use the function on every element in the TF dataset.

```<code>def process_path(file_path):
    '''reads the path and returns an image.'''
    # load the raw data from the file as a string
    byteString = tf.io.read_file(file_path)
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_png(byteString, channels=3)
    return img
</code>```

dataset = list_ds.map(preprocess_path)

Step 3

Check out the image.

import matplotlib.pyplot as plt

for image in dataset.take(1): plt.imshow(image)

Body:
I want to try image segmentation with deep learning using AWS. I have my data stored on Amazon S3 and I'd like to access it from a Jupyter Notebook which is running on an Amazon EC2 instance.

I'm planning on using Tensorflow for segmentation, therefore it seemed appropriate to me to use options provided by Tensorflow themselves (https://www.tensorflow.org/deploy/s3) as it feels that in the end I want my data to be represented in the format of tf.Dataset. However, it didn't quite work out for me. I've tried the following:

filenames = ["s3://path_to_first_image.png", "s3://path_to_second_image.png"]
dataset = tf.data.TFRecordDataset(filenames)

iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
for i in range(2):
    print(sess.run(next_element))

I get the following error:

OutOfRangeError: End of sequence
 [[Node: IteratorGetNext_6 = IteratorGetNext[output_shapes=[[]], output_types=[DT_STRING], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator_6)]]

I'm quite new to tensorflow and have just recently started trying out some stuff with AWS, so I hope that my mistake is gonna be obvious to someone with more experience. I would greatly appreciate any help or advice! Maybe it's even the wrong way and I'm better off with something like boto3 (also stumbled upon it, but thought that tf would be more appropriate in my case) or something else?

P.S. Tensorflow also recommends to test a setup with the following piece:

from tensorflow.python.lib.io import file_io
print (file_io.stat('s3://path_to_image.png'))

For me this leads to Object doesn't exist error, though the object certainly exists and it's being listed among others if I use

for obj in s3.Bucket(name=MY_BUCKET_NAME).objects.all():
print(os.path.join(obj.bucket_name, obj.key))

I also have my credentials filled in /.aws/credentials. What might be the problem here?

Body:
Not a direct answer to your question but still something I noticed as to why you can't load data using Tensorflow.

The files in your filenames are .png and not in the .tfrecord file format which is a binary storage format. So, tf.data.TFRecordDataset(filenames) shouldn't work.

I think the following will work. Note: this is for TF2, not sure if it is the same for TF1. A similar example can be found here at TensorFlow's web site tensorflow example

Step 1

Load your files into a TensorFlow dataset with tf.data.Dataset.list_files.

import tensorflow as tf

list_ds = tf.data.Dataset.list_files(filenames)

Step 2

Make a function that will be applied to each element in the dataset by using map; this will use the function on every element in the TF dataset.

def process_path(file_path):
    '''reads the path and returns an image.'''
    # load the raw data from the file as a string
    byteString = tf.io.read_file(file_path)
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_png(byteString, channels=3)
    return img

dataset = list_ds.map(preprocess_path)

Step 3

Check out the image.

import matplotlib.pyplot as plt

for image in dataset.take(1): plt.imshow(image)


问:
Add custom columns to select
I am trying to add custom row and column to all results. I am getting below error,

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.png as badge, 3.5 as rating from instructors as i inner join use' at line 1 (SQL: selecti.id,u.name,i.about,i.price_per_hour,u.profile_picture,https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.pngasbadge,3.5asratingfrominstructorsasiinner joinusersasuonu.id=i.user_idwhere 0 = 1 andgenderin (male) order byi.id` desc limit 10 offset 0)

The associated code:

```<code>public function findInstructors($instrutors, $gender, $offet, $fetch) {

    return DB::table('instructors as i')
        ->select(
            'i.id',
            'u.name',
            'i.about',
            'i.price_per_hour',
            'u.profile_picture',
            'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge',
            '3.5 as rating'
        )
        ->join('users as u', 'u.id', 'i.user_id')
        ->whereIn('i.id', $instrutors)
        ->whereIn('gender', $gender)
        ->offset($offet)
        ->limit($fetch)
        ->orderBy('i.id', 'desc')->get();
}
</code>```

答:
I would suggest to stick with Laravel Collection map() function when it comes to adding additional data to a collection.</p>

```<code>return DB::table('instructors as i')
->select(
    'i.id',
    'u.name',
    'i.about',
    'i.price_per_hour',
    'u.profile_picture', // Notice* column removed from here
    '3.5 as rating'
)
->join('users as u', 'u.id', 'i.user_id')
->whereIn('i.id', $instrutors)
->whereIn('gender', $gender)
->offset($offet)
->limit($fetch)
->orderBy('i.id', 'desc')
->get()
->map(function($row) {
    // Here you can add like this. Keep in mind, this will be common for all the rows.
    $row['badge'] = 'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png';
    return $row;
});
</code>```

Title: Add custom columns to select

Body:
I am trying to add custom row and column to all results. I am getting below error,

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.png as badge, 3.5 as rating from instructors as i inner join use' at line 1 (SQL: selecti.id,u.name,i.about,i.price_per_hour,u.profile_picture,https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.pngasbadge,3.5asratingfrominstructorsasiinner joinusersasuonu.id=i.user_idwhere 0 = 1 andgenderin (male) order byi.id` desc limit 10 offset 0)

The associated code:

public function findInstructors($instrutors, $gender, $offet, $fetch) {

    return DB::table('instructors as i')
        ->select(
            'i.id',
            'u.name',
            'i.about',
            'i.price_per_hour',
            'u.profile_picture',
            'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png as badge',
            '3.5 as rating'
        )
        ->join('users as u', 'u.id', 'i.user_id')
        ->whereIn('i.id', $instrutors)
        ->whereIn('gender', $gender)
        ->offset($offet)
        ->limit($fetch)
        ->orderBy('i.id', 'desc')->get();
}

Body:
I would suggest to stick with Laravel Collection map() function when it comes to adding additional data to a collection.

return DB::table('instructors as i')
->select(
    'i.id',
    'u.name',
    'i.about',
    'i.price_per_hour',
    'u.profile_picture', // Notice* column removed from here
    '3.5 as rating'
)
->join('users as u', 'u.id', 'i.user_id')
->whereIn('i.id', $instrutors)
->whereIn('gender', $gender)
->offset($offet)
->limit($fetch)
->orderBy('i.id', 'desc')
->get()
->map(function($row) {
    // Here you can add like this. Keep in mind, this will be common for all the rows.
    $row['badge'] = 'https://www.pngitem.com/pimgs/m/575-5754595_why-bali-best-driver-driver-icons-hd-png.png';
    return $row;
});


问:
ajax xmlhttprequests in nodejs express
I am a newbie to xmlhttprequests.I am not understanding how the xml api works with nodejs.I can understand express properly about the servers and routes. I would suggest someone explain me the setup of xhr api with nodejs with an example .Just a basic example of how all works is fine.
Thank you!</p>

答:
Here's a basic example using the fetch() API from the browser:

```<code>// server
const app = require('express')();
app.get("/getrandom", (req, res) => {
    let random = Math.random();           // generate random number
    res.json({random});                   // wrap random number in an object and send it
});
app.listen(80);
</code>```

And, browser Javascript code:

```<code>fetch("http://yourhost/getrandom").then(res => res.json()).then(result => {
    console.log(result);     // {random: 0.7594837274}
}).catch(err => {
    console.log(err);
});
</code>```

This particular example uses the more modern fetch() API from the browser.  The server code would not be any different whether you were using the fetch() API or the XMLHttpRequest() API.  In both cases, they just generate an http request which your server has a route for and sends a response to.

Since the server here is sending back JSON, res.json() is used as part of the fetch() call to read the body of the response and parse the JSON into a Javascript object.

Title: ajax xmlhttprequests in nodejs express

Body:
Here's a basic example using the fetch() API from the browser:

// server
const app = require('express')();
app.get("/getrandom", (req, res) => {
    let random = Math.random();           // generate random number
    res.json({random});                   // wrap random number in an object and send it
});
app.listen(80);

And, browser Javascript code:

fetch("http://yourhost/getrandom").then(res => res.json()).then(result => {
    console.log(result);     // {random: 0.7594837274}
}).catch(err => {
    console.log(err);
});

This particular example uses the more modern fetch() API from the browser.  The server code would not be any different whether you were using the fetch() API or the XMLHttpRequest() API.  In both cases, they just generate an http request which your server has a route for and sends a response to.

Since the server here is sending back JSON, res.json() is used as part of the fetch() call to read the body of the response and parse the JSON into a Javascript object.


问:
Obtain a specific data from my model - Django
I'm trying to understand how to obtain some data from my models.

I have a model like this,

```<code>class Device(models.Model):
    dev_id= models.CharField(max_length=16, primary_key=True, unique=True)
    dev_name = models.CharField(max_length=20, unique=True)

    fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE)

def __str__(self):
    return self.dev_eui
</code>```

If for example one of my devices has the dev_id like "lop7576", I want to obtain two data, its dev_name and its fleet_id.

If I do the following I obtain all the info from this device,

```<code>jq1 = Device.objects.filter(dev_id="lop7576")
</code>```

But how can I obtain only this two values in string/int format directly?

Thank you very much.

答:
You can use the <code>.values()</code> function like this: </p>

```<code>jq1 = Device.objects.filter(dev_id="lop7576").values('dev_name', 'fleet_id')
</code>```

Body:
I'm trying to understand how to obtain some data from my models.

I have a model like this,

class Device(models.Model):
    dev_id= models.CharField(max_length=16, primary_key=True, unique=True)
    dev_name = models.CharField(max_length=20, unique=True)

    fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE)

def __str__(self):
    return self.dev_eui

If for example one of my devices has the dev_id like "lop7576", I want to obtain two data, its dev_name and its fleet_id.

If I do the following I obtain all the info from this device,

jq1 = Device.objects.filter(dev_id="lop7576")

But how can I obtain only this two values in string/int format directly?

Thank you very much.

Body:
You can use the .values() function like this:

jq1 = Device.objects.filter(dev_id="lop7576").values('dev_name', 'fleet_id')


问:
Weird Behaviour of Merge Sort Algorithm in C++
I have implemented a merge sort algorithm, but it has a very weird bug which is hard to explain so please look at the code and output.

CODE:-

```<code>#include <bits/stdc++.h>

using namespace std;

int merge(int *ar, int l, int r) {
    int aux[r - l + 1], s1 = 0, s2 = (r - l) / 2 + 1;

    for (int i = 0; i < r - l + 1; i++)
        aux[i] = ar[l + i];
    for (int k = 0; k < r - l + 1; k++) {
        if (s1 > ((r - l) / 2))
            ar[l + k] = aux[s2++];
        else
        if (s2 > r)
            ar[l + k] = aux[s1++];
        else
        if (aux[s1] <= aux[s2])
            ar[l + k] = aux[s1++];
        else
            ar[l + k] = aux[s2++];
    }
    //for (int i = 0; i < 17; i++) cout << ar[i] << " ";
    //cout << endl;
    return 0;
}

void  mergesort(int *ar, int l, int r) {
    if (l >= r)
        return;
    int mid = (l + r) / 2;
    mergesort(ar, l, mid);
    mergesort(ar, mid + 1, r);
    merge(ar, l, r);
}

int main() {
    int ar[] ={ 34, 54, 56, 42, 32, 46, 99, 85, 5, 45, 34, 54, 6, 56, 54, 64, 5 },
        l = 0, r = sizeof(ar) / sizeof(int) - 1;
    mergesort(ar, l, r);
    for (int i = 0; i < r + 1; i++)
        cout << ar[i] << " ";
    return 0;
}
</code>```

OUTPUT:-

```<code>5 5 6 16 16 16 32 16 34 34 16 46 54 54 16 56 99
</code>```

I don't know where are these 16 are coming from, this does not happen for array of single digit numbers of any length and small arrays of 2 digit numbers. Also, if I cout anything in the merge function (like spaces, tabs, new lines or any number) I get the correct output i.e,

```<code>        5 5 6 32 34 34 42 45 46 54 54 54 56 56 56 64 99
</code>```

[I have printed spaces here.]

I tried changing function parameters but it does not help.
Please help I cannot figure this out on my own.

答:
In the merge function, the test if (s2 > r) is incorrect. It should be if (s2 > r - l).

It is very confusing to pass r as the index of the last element. In C and C++, it is more idiomatic to pass the index of the element after the last one, so r - l be the length of the array. With this approach, there are no error-prone +1/-1 adjustments.

Here is a modified version:

#include <iostream>

using namespace std;

void merge(int *ar, int l, int r) {
    int len = r - l;
    int mid = len / 2;
    int s1 = 0, s2 = mid;
    int aux[len];

    for (int i = 0; i < len; i++)
        aux[i] = ar[l + i];
    for (int k = l; k < r; k++) {
        if (s1 >= mid)
            ar[k] = aux[s2++];
        else
        if (s2 >= len)
            ar[k] = aux[s1++];
        else
        if (aux[s1] <= aux[s2])
            ar[k] = aux[s1++];
        else
            ar[k] = aux[s2++];
    }
}

void mergesort(int *ar, int l, int r) {
    if (r - l >= 2)
        return;
    int mid = l + (r - l) / 2;
    mergesort(ar, l, mid);
    mergesort(ar, mid, r);
    merge(ar, l, r);
}

int main() {
    int ar[] = { 34, 54, 56, 42, 32, 46, 99, 85, 5, 45, 34, 54, 6, 56, 54, 64, 5 };
    int len = sizeof(ar) / sizeof(ar[0]);
    mergesort(ar, 0, len);
    for (int i = 0; i < len; i++)
        cout << ar[i] << " ";
    cout << endl;
    return 0;
}
```

Body:
I have implemented a merge sort algorithm, but it has a very weird bug which is hard to explain so please look at the code and output.

CODE:-

#include <bits/stdc++.h>

using namespace std;

int merge(int *ar, int l, int r) {
    int aux[r - l + 1], s1 = 0, s2 = (r - l) / 2 + 1;

    for (int i = 0; i < r - l + 1; i++)
        aux[i] = ar[l + i];
    for (int k = 0; k < r - l + 1; k++) {
        if (s1 > ((r - l) / 2))
            ar[l + k] = aux[s2++];
        else
        if (s2 > r)
            ar[l + k] = aux[s1++];
        else
        if (aux[s1] <= aux[s2])
            ar[l + k] = aux[s1++];
        else
            ar[l + k] = aux[s2++];
    }
    //for (int i = 0; i < 17; i++) cout << ar[i] << " ";
    //cout << endl;
    return 0;
}

void  mergesort(int *ar, int l, int r) {
    if (l >= r)
        return;
    int mid = (l + r) / 2;
    mergesort(ar, l, mid);
    mergesort(ar, mid + 1, r);
    merge(ar, l, r);
}

int main() {
    int ar[] ={ 34, 54, 56, 42, 32, 46, 99, 85, 5, 45, 34, 54, 6, 56, 54, 64, 5 },
        l = 0, r = sizeof(ar) / sizeof(int) - 1;
    mergesort(ar, l, r);
    for (int i = 0; i < r + 1; i++)
        cout << ar[i] << " ";
    return 0;
}

OUTPUT:-

5 5 6 16 16 16 32 16 34 34 16 46 54 54 16 56 99

I don't know where are these 16 are coming from, this does not happen for array of single digit numbers of any length and small arrays of 2 digit numbers. Also, if I cout anything in the merge function (like spaces, tabs, new lines or any number) I get the correct output i.e,

        5 5 6 32 34 34 42 45 46 54 54 54 56 56 56 64 99

[I have printed spaces here.]

I tried changing function parameters but it does not help.
Please help I cannot figure this out on my own.


问:
How to write where condition in postgres-flask for dynamic values
I am looking for a solution to dynamically pass values into the where clause of my postgres query in a flask app.

client is the value that changes dynamically which i want to pass on to 'clientid'. the above method doesn't throw any error, but it is not filtering. the no of rows i expect is 3 but this query fetches everything from payments table

client = 'ms0001'
cur.execute("SELECT * FROM payments WHERE clientid = clientid", client)
value = cur.fetchall()
for a in value:
    print(a[0])
```

答:
Try this :

```<code>cursor.execute("SELECT * FROM payments WHERE clientid = %s", ('client',))
</code>```

Let me know if that works for you :D

Body:
Try this :

cursor.execute("SELECT * FROM payments WHERE clientid = %s", ('client',))

Let me know if that works for you :D


问:
check if number is in given range?
Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

```<code>is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False
</code>```

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

```<code>is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False
</code>```

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))
```

答:
Rather than looping, you can directly check whether:

if n>=r['min'] and n<=r['max']:
    return True
else:
    return False
```

Title: check if number is in given range?

Body:
Given a number and a dictionary with min and max properties, return True if the number lies within the given range (inclusive).

Examples

is_in_range(4, { "min": 0, "max": 5 }) ➞ True
is_in_range(1, { "min": 4, "max": 5 }) ➞ False

The below code is working for the int values of a number to be searched and dictionary values, but not for float values.

Examples

is_in_range(1.8, { "min": 1.25, "max": 1.75 }) ➞ False

So far what I tried:

def is_in_range(n, r):
    for i in range(r['min'],r['max']+1):
        if i<=n:
            return True
        else:
            return False

    print(is_in_range(4, { "min": 6, "max": 10 }))


问:
What's a good way to store a lot of small texts with metadata with reactNative?
I am developing an app that will displays a series of small texts everyday and I have been wondering what's the best way to store them. I intend to change them only when I update it to new versions so.</p>

答:
Since you need to update those small texts only when you update your APP to a new version, I think the best way is to store them in a local storage such as AsyncStorage.

AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app.

You can refer the docs of AsyncStorage here


问:
Typescript: Creating a method on a class with args that are part of the class
I created a class and want to extract repeated logic into a method on the class to be re-used by other properties of the class.

```<code>class Card {
  protected readonly data: Data;
  protected readonly user: User;
  nameVal: string;
  addressVal: string[];

  constructor(raw_data: Data, user: User) {
    this.data = raw_data;
    this.user = user;
  }

  get name(): string {
    if (!this.nameVal) {
      this.nameVal = name_getter(this.data, this.user); // same parameters
    }
    return this.nameVal;
  }

  get address(): string[] {
    if (!this.addressVal) {
      this.addressVal = address_getter(this.data, this.user); // same parameters
    }
    return this.addressVal;
  }

  // I want to refactor the above logic and have it handled in a function like below
  // maybe getter type would be something like this:
  // type FieldValueGetter = (data: Data, user: User) => any;
  getFieldValue(getter: FieldValueGetter, field: ?) { // Is there a way to define field type?
    if(!field) {
      this.field = getter(this.data, this.user);
    }
    return this.field;
  }
}
</code>```

I'm not sure how I can define the type for the field parameter for getFieldValue method as the value of the field would differ by field, but the common factor is that the field would be part of the class.

答:
I believe this is what you are looking for.

keyof

```<code>function getter(data:Data, user:User, field: string){
// your logic here.
}
class Card {
    protected readonly data: Data;
    protected readonly user: User;

    field: string = '';
    field2: number = 0;

    constructor(raw_data: Data, user: User) {
        this.data = raw_data;
        this.user = user;
    }

    getFieldValue<T>(getter: FieldValueGetter, field: keyof this): T {
        if (!field) {
            this[field] = getter(this.data, this.user, field);
        }
        return this[field] as any as  T;
    }
}

const card = new Card({}, {});
card.getFieldValue<string>(getter, 'field');
card.getFieldValue<number>(getter, 'field2');
</code>```

Body:
I created a class and want to extract repeated logic into a method on the class to be re-used by other properties of the class.

class Card {
  protected readonly data: Data;
  protected readonly user: User;
  nameVal: string;
  addressVal: string[];

  constructor(raw_data: Data, user: User) {
    this.data = raw_data;
    this.user = user;
  }

  get name(): string {
    if (!this.nameVal) {
      this.nameVal = name_getter(this.data, this.user); // same parameters
    }
    return this.nameVal;
  }

  get address(): string[] {
    if (!this.addressVal) {
      this.addressVal = address_getter(this.data, this.user); // same parameters
    }
    return this.addressVal;
  }

  // I want to refactor the above logic and have it handled in a function like below
  // maybe getter type would be something like this:
  // type FieldValueGetter = (data: Data, user: User) => any;
  getFieldValue(getter: FieldValueGetter, field: ?) { // Is there a way to define field type?
    if(!field) {
      this.field = getter(this.data, this.user);
    }
    return this.field;
  }
}

I'm not sure how I can define the type for the field parameter for getFieldValue method as the value of the field would differ by field, but the common factor is that the field would be part of the class.

Body:
I believe this is what you are looking for.

keyof

function getter(data:Data, user:User, field: string){
// your logic here.
}
class Card {
    protected readonly data: Data;
    protected readonly user: User;

    field: string = '';
    field2: number = 0;

    constructor(raw_data: Data, user: User) {
        this.data = raw_data;
        this.user = user;
    }

    getFieldValue<T>(getter: FieldValueGetter, field: keyof this): T {
        if (!field) {
            this[field] = getter(this.data, this.user, field);
        }
        return this[field] as any as  T;
    }
}

const card = new Card({}, {});
card.getFieldValue<string>(getter, 'field');
card.getFieldValue<number>(getter, 'field2');


问:
RazorPages anchor tag helper with multiple parameters
Here's the RazorPages page I'm trying to make a link to:

```<code>@page "{ReportId:int}/{SicCode:alpha?}"
</code>```

This works

```<code><a asp-page="/ReportSics" asp-route-ReportId="3">rs1</a>
</code>```

it produces

```<code><a href="/Reports/ReportSics/3">rs1</a>
</code>```

But this produces a blank href.

```<code><a asp-page="/ReportSics" asp-route-ReportId="3" asp-route-SicCode="10">rss2</a>
</code>```

That is: the tag helper works with one parameter but not with two.
Why?
Is it possible to make it work?

(I have another page with the same @page but with the second parameter not optional and it appears to be impossible to create a link to it.)

Furthermore, requesting Page/2/M works, but Page/2/12 returns 404. Why? (The second parameter is a string that can sometimes be a number, but it always treated as a string.)

答:
This works

Yes it works because it produces a route that is similar to this baseUrl/reportsics/?reportId=5
And the other produces a URL that is similar to this baseUrl/reportsics/?reportId=5&sicCode=678 and then it doesn't match your route definition. I think you should try this.

Experimental

```<code>asp-page="/reportSics/@myId/@sicCode
</code>```

Though this would not be the right way to do what you're thinking. If you really want to change your URL structure, why not do url-rewrite?

Edit.
Form your recent comments, seems you want to pass many parameters in your action method and not targeting URL structure. Then I recommend you just

```<code>public IActionResult(string ReportId, string sicCode)
{
  //......
}

//And the your URL target
<a asp-page="ReportSics" asp-route-ReportId="55" asp-route-sicCode="566" ></a>
</code>```

And then it will match the route. I think you should remove that helper you placed after your @page definition and try it out if this is what you have already done and the problem persists.

Body:
Here's the RazorPages page I'm trying to make a link to:

@page "{ReportId:int}/{SicCode:alpha?}"

This works

rs1

it produces

rs1

But this produces a blank href.

rss2

That is: the tag helper works with one parameter but not with two.
Why?
Is it possible to make it work?

(I have another page with the same @page but with the second parameter not optional and it appears to be impossible to create a link to it.)

Furthermore, requesting Page/2/M works, but Page/2/12 returns 404. Why? (The second parameter is a string that can sometimes be a number, but it always treated as a string.)

Body:
This works

Yes it works because it produces a route that is similar to this baseUrl/reportsics/?reportId=5
And the other produces a URL that is similar to this baseUrl/reportsics/?reportId=5&sicCode=678 and then it doesn't match your route definition. I think you should try this.

Experimental

asp-page="/reportSics/@myId/@sicCode

Though this would not be the right way to do what you're thinking. If you really want to change your URL structure, why not do url-rewrite?

Edit.
Form your recent comments, seems you want to pass many parameters in your action method and not targeting URL structure. Then I recommend you just

public IActionResult(string ReportId, string sicCode)
{
  //......
}

//And the your URL target
<a asp-page="ReportSics" asp-route-ReportId="55" asp-route-sicCode="566" ></a>

And then it will match the route. I think you should remove that helper you placed after your @page definition and try it out if this is what you have already done and the problem persists.


问:
How to design a simple login system in C?
I am new to C. I try to develop a simple login system as part of another program. And if the user writes a wrong password 3 times, the program exits. when I write the right password at the first time, it goes well. But when I write a wrong one then tries to write the right one at the second or third one, it still considers it a wrong one.</p>

```<code>void login ()
{
  int i;
  char password[12] = "mohammed3336";
  char trypassword[50];
  for (i = 0; i<3; i++)
  {
    scanf ("%s", &trypassword);
    if (strcmp (trypassword, password) == 0)
    {
      printf ("login is successful!\n\n");
      break;
    }
    else
    {
      if (i == 2)
      {
          exit (0);
      }
      printf ("password is wrong, try again (trial %d of 3)\n", i+1);
      }
  }
}
</code>```

答:
Try this:</p>

```<code>#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    char username[15];
    char password[12];

    printf("Enter your username:\n");
    scanf("%s",&username);

    printf("Enter your password:\n");
    scanf("%s",&password);

    if(strcmp(username,"chaitu")==0){
        if(strcmp(password,"123")==0){

        printf("\nWelcome.Login Success!");

        }else{
    printf("\nwrong password");
}
    }else{
    printf("\nUser doesn't exist");
}

    return 0;

}
</code>```

Body:
I am new to C. I try to develop a simple login system as part of another program. And if the user writes a wrong password 3 times, the program exits. when I write the right password at the first time, it goes well. But when I write a wrong one then tries to write the right one at the second or third one, it still considers it a wrong one.

void login ()
{
  int i;
  char password[12] = "mohammed3336";
  char trypassword[50];
  for (i = 0; i<3; i++)
  {
    scanf ("%s", &trypassword);
    if (strcmp (trypassword, password) == 0)
    {
      printf ("login is successful!\n\n");
      break;
    }
    else
    {
      if (i == 2)
      {
          exit (0);
      }
      printf ("password is wrong, try again (trial %d of 3)\n", i+1);
      }
  }
}

Body:
Try this:

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    char username[15];
    char password[12];

    printf("Enter your username:\n");
    scanf("%s",&username);

    printf("Enter your password:\n");
    scanf("%s",&password);

    if(strcmp(username,"chaitu")==0){
        if(strcmp(password,"123")==0){

        printf("\nWelcome.Login Success!");

        }else{
    printf("\nwrong password");
}
    }else{
    printf("\nUser doesn't exist");
}

    return 0;

}


问:
Add columns dynamically to ag-grid from http request
I am trying to add dynamically columns to an ag-grid epending on the response of an http request.

the fixed columns are

```<code> rowData: Task[];
 gridOptions: GridOptions;
 domLayout = "autoHeight";

 columnDefs = [
   { headerName: 'Titre', field: 'name', sortable: true, filter: true, width: 120 },
   { headerName: 'Collaborateur', field: 'collaborator', sortable: true, width: 250 },
   { headerName: 'Statut', field: 'status', sortable: true, width: 100 },
   { headerName: 'Lot', field: 'lot', sortable: true, width: 100 },
 ]
</code>```

And then depending on the http response I would like to ad new columns like this

```<code>{
  headerName: 'IC S1', valueGetter: function (params) { return params.data.charge[0] },
  editable: true, sortable: true, width: 60
},
</code>```

I know I am doing something wrong but I don't knowwhat exactly.
Here is what I am trying:

```<code>colDef = [];
newColumns() {
 this.rowData.forEach(task => {
  task.charge.forEach(initCharge => {

    let i = 0;
    this.colDef.push({ headerName: 'IC S' + (i + 1), field: 'initCharge', })
    });
  this.gridOptions.api.setColumnDefs(this.colDef);
  });
}
</code>```

And I am calling all of this in the ngOnInit

```<code> ngOnInit() {
   this.subscription = this.route.params.subscribe(params => {
      this.id = +params['id'];
   });

   this.getProjectTasks();
   this.newColumns();
   this.getDates();
 }
</code>```

答:
Here is how I fixed the problem even though not sure if it's the best thing to do.</p>

```<code> getProjectTasks() {
this.managerService.getTasksByProject(this.id).subscribe((resp) => {
  this.rowData = resp;
  let maxCharge = 0;
  this.rowData.forEach(task => {
    if (task.charge.length > maxCharge) {
      maxCharge = task.charge.length
    }
  });

  for (let i = 1; i < maxCharge; i++) {
    let j = i + 1;
    this.columnDefs.push({
      headerName: 'IC S' + j, valueGetter: function (params) { return params.data.charge[i] }, valueSetter: function (params) {
        if (params.data.charge[i] === params.newValue) {
          return false
        } else { params.data.charge[i] = params.newValue; return true }
      }, editable: true, sortable: true, maxWidth: 200
    })
  }

  this.gridOptions.api.setColumnDefs(this.columnDefs);
  this.gridOptions.api.sizeColumnsToFit();
},
  (err) => {
    console.log(err);
    }
  );
}
</code>```

Body:
I am trying to add dynamically columns to an ag-grid epending on the response of an http request.

the fixed columns are

 rowData: Task[];
 gridOptions: GridOptions;
 domLayout = "autoHeight";

 columnDefs = [
   { headerName: 'Titre', field: 'name', sortable: true, filter: true, width: 120 },
   { headerName: 'Collaborateur', field: 'collaborator', sortable: true, width: 250 },
   { headerName: 'Statut', field: 'status', sortable: true, width: 100 },
   { headerName: 'Lot', field: 'lot', sortable: true, width: 100 },
 ]

And then depending on the http response I would like to ad new columns like this

{
  headerName: 'IC S1', valueGetter: function (params) { return params.data.charge[0] },
  editable: true, sortable: true, width: 60
},

I know I am doing something wrong but I don't knowwhat exactly.
Here is what I am trying:

colDef = [];
newColumns() {
 this.rowData.forEach(task => {
  task.charge.forEach(initCharge => {

    let i = 0;
    this.colDef.push({ headerName: 'IC S' + (i + 1), field: 'initCharge', })
    });
  this.gridOptions.api.setColumnDefs(this.colDef);
  });
}

And I am calling all of this in the ngOnInit

 ngOnInit() {
   this.subscription = this.route.params.subscribe(params => {
      this.id = +params['id'];
   });

   this.getProjectTasks();
   this.newColumns();
   this.getDates();
 }

Body:
Here is how I fixed the problem even though not sure if it's the best thing to do.

 getProjectTasks() {
this.managerService.getTasksByProject(this.id).subscribe((resp) => {
  this.rowData = resp;
  let maxCharge = 0;
  this.rowData.forEach(task => {
    if (task.charge.length > maxCharge) {
      maxCharge = task.charge.length
    }
  });

  for (let i = 1; i < maxCharge; i++) {
    let j = i + 1;
    this.columnDefs.push({
      headerName: 'IC S' + j, valueGetter: function (params) { return params.data.charge[i] }, valueSetter: function (params) {
        if (params.data.charge[i] === params.newValue) {
          return false
        } else { params.data.charge[i] = params.newValue; return true }
      }, editable: true, sortable: true, maxWidth: 200
    })
  }

  this.gridOptions.api.setColumnDefs(this.columnDefs);
  this.gridOptions.api.sizeColumnsToFit();
},
  (err) => {
    console.log(err);
    }
  );
}


问:
Count content inside quotes as one argument
I'm making a discord bot with node.js's discord.js module, I have a basic arguments detection system that uses the whitespace as the separator and puts the different arguments in an array, here's the important part of my code. (I'm using separate command modules using module.exports).

const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.alias && cmd.alias.includes(commandName));
```

So for example when someone writes !give foo 50 bar. the args array is ['foo','50','bar']

I want the args to not divide quoted parts of the command in the command, meaning if somenoe writes !give "foo1 bar1" 50 "foo2 bar2". I want the args to return an array like this ['foo1 bar1', '50','foo2 bar2'] instead of ['foo1','bar1','50','foo2','bar1',]

答:
This may not be the most efficient way to do it, but I think it's comprehensible: we can scan every character and we keep track of whether we're inside or outside a couple of quotes and, if so, we ignore the spaces.

function parseQuotes(str = '') {
  let current = '',
    arr = [],
    inQuotes = false

  for (let char of str.trim()) {
    if (char == '"') {
      // Switch the value of inQuotes
      inQuotes = !inQuotes
    } else if (char == ' ' && !inQuotes) {
      // If there's a space and where're not between quotes, push a new word
      arr.push(current)
      current = ''
    } else {
      // Add the character to the current word
      current += char
    }
  }

  // Push the last word
  arr.push(current)

  return arr
}

// EXAMPLES
// Run the snippet to see the results in the console

// !give "foo1 bar1" 50 "foo2 bar2"
let args1 = parseQuotes('!give "foo1 bar1" 50 "foo2 bar2"')
console.log(`Test 1: !give "foo1 bar1" 50 "foo2 bar2"\n-> [ "${args1.join('", "')}" ]`)

// !cmd foo bar baz
let args2 = parseQuotes('!cmd foo bar baz')
console.log(`Test 2: !cmd foo bar baz\n-> [ "${args2.join('", "')}" ]`)

// !cmd foo1 weir"d quot"es "not closed
let args3 = parseQuotes('!cmd foo1 weir"d quot"es "not closed')
console.log(`Test 3: !cmd foo1 weir"d quot"es "not closed\n-> [ "${args3.join('", "')}" ]`)```

Body:
I'm making a discord bot with node.js's discord.js module, I have a basic arguments detection system that uses the whitespace as the separator and puts the different arguments in an array, here's the important part of my code. (I'm using separate command modules using module.exports).

const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.alias && cmd.alias.includes(commandName));

So for example when someone writes !give foo 50 bar. the args array is ['foo','50','bar']

I want the args to not divide quoted parts of the command in the command, meaning if somenoe writes !give "foo1 bar1" 50 "foo2 bar2". I want the args to return an array like this ['foo1 bar1', '50','foo2 bar2'] instead of ['foo1','bar1','50','foo2','bar1',]


问:
Setting locale in moment.js not working despite using the locale file
There is a setLocale method in a dependency of a project, and I call this method from the project on locale change. However, the locale doesn't seem to change.

```<code>import moment from 'moment';
import 'moment/locale/de';

export const setLocale = locale => {
    console.log(`Locale to be set: ${locale}`)
    moment.locale(locale);
    console.log(moment.locale())
};
</code>```

Output in console

I'm using moment-js v2.26.0in the dependency and 2.24.0 in the main project.

Same happens if I set locale explicitly.

However, changing the locale works in the main project works just fine.

答:
I fixed this issue by importing momentjs and locales in the following way:

```<code>import moment from 'moment/min/moment-with-locales';
</code>```

From momentjs documentation

To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.

This of course doesn't explain why importing just one file fails.

Body:
There is a setLocale method in a dependency of a project, and I call this method from the project on locale change. However, the locale doesn't seem to change.

import moment from 'moment';
import 'moment/locale/de';

export const setLocale = locale => {
    console.log(`Locale to be set: ${locale}`)
    moment.locale(locale);
    console.log(moment.locale())
};

Output in console

I'm using moment-js v2.26.0in the dependency and 2.24.0 in the main project.

Same happens if I set locale explicitly.

However, changing the locale works in the main project works just fine.

Body:
I fixed this issue by importing momentjs and locales in the following way:

import moment from 'moment/min/moment-with-locales';

From momentjs documentation

To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.

This of course doesn't explain why importing just one file fails.


问:
Is there any way to Convert byte array to String in modelAttribute?
I have a model class called "Post" which has an attribute "postContent" as a byteArray.

```<code>public class Post{
byte[] postContnet;

//getters
//setters
...
}
</code>```

So, I am using spring boot and spring form tag for getting the user's input using modelAttribute. The reason I am using byte array is I am using Ckeditor to get the WYSIWYG content.

```<code>    <form:form ...... modelAttribute="post">
   ...
    <form:textarea path="postContect" id="editor1">
....
    </form:form>
</code>```

While inserting the post to DB, I did not convert anything and it is inserted in MySQL DB where the postContent column is Blob type. However, when I am retrieving the content back for the edit purpose, I am getting byte array rather it should be a String. In a controller, I am getting and sending the data to JSP as below:

```<code>....
Post post = postService.findByPostId(postId);
        if (post != null) {
            mv.addObject("title", "Edit Post");
            mv.addObject("post", post);
 ...
</code>```

So, when I use JSTL in JSP, it prints the postContect as an array. I could get many references where converting the String to byte array and wise versa but here since I am using spring form and modelAttribute I am not sure where should I edit. How could I get back String in between?

Thanks.

答:
I have found out the answer and it works for me. I am adding the comment here because someone who has a similar issue will get an idea.

I created Spring converter for a string to byte array

@Component
public class StringBase64ToByteArray implements Converter {

```<code>@Override
public byte[] convert(String source) {
    byte[] byteSource = null;
    System.out.println("StringBase64ToByteArray is called");
    try {
        byteSource = Base64.getEncoder().encode(source.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return byteSource;
}
</code>```

}

Then I created another converter to byte array to string

@Component
public class ByteArrayToStringBase64 implements Converter{

```<code>@Override
public String convert(byte[] source) {
    byte[] decodedString = Base64.getDecoder().decode(source);
    return new String(decodedString);
}
</code>```

}

I have registered both converters to spring boot configuration
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{

```<code>@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new StringBase64ToByteArray());
    registry.addConverter(new ByteArrayToStringBase64());
}
</code>```

}

Body:
I have a model class called "Post" which has an attribute "postContent" as a byteArray.

public class Post{
byte[] postContnet;

//getters
//setters
...
}

So, I am using spring boot and spring form tag for getting the user's input using modelAttribute. The reason I am using byte array is I am using Ckeditor to get the WYSIWYG content.

    <form:form ...... modelAttribute="post">
   ...
    <form:textarea path="postContect" id="editor1">
....
    </form:form>

While inserting the post to DB, I did not convert anything and it is inserted in MySQL DB where the postContent column is Blob type. However, when I am retrieving the content back for the edit purpose, I am getting byte array rather it should be a String. In a controller, I am getting and sending the data to JSP as below:

....
Post post = postService.findByPostId(postId);
        if (post != null) {
            mv.addObject("title", "Edit Post");
            mv.addObject("post", post);
 ...

So, when I use JSTL in JSP, it prints the postContect as an array. I could get many references where converting the String to byte array and wise versa but here since I am using spring form and modelAttribute I am not sure where should I edit. How could I get back String in between?

Thanks.

Body:
I have found out the answer and it works for me. I am adding the comment here because someone who has a similar issue will get an idea.

I created Spring converter for a string to byte array

@Component
public class StringBase64ToByteArray implements Converter {

@Override
public byte[] convert(String source) {
    byte[] byteSource = null;
    System.out.println("StringBase64ToByteArray is called");
    try {
        byteSource = Base64.getEncoder().encode(source.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return byteSource;
}

}

Then I created another converter to byte array to string

@Component
public class ByteArrayToStringBase64 implements Converter{

@Override
public String convert(byte[] source) {
    byte[] decodedString = Base64.getDecoder().decode(source);
    return new String(decodedString);
}

}

I have registered both converters to spring boot configuration
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new StringBase64ToByteArray());
    registry.addConverter(new ByteArrayToStringBase64());
}

}


问:
trouble using variable inside getElementById
I want to convert these codes:

```<code>if(slidedLcount == 0){
        document.getElementById("incredable__offers__examples__item_1").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_2").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_3").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_4").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_5").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_6").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_7").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_8").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_9").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_10").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__arrow__r").classList.remove("grayedout");
    }
</code>```

to these so it would make it a lot easier, cause will use it mutiple times:

```<code>if(slidedLcount == 0){
        var x = "0";
        var y = "incredable__offers__examples__item_"
        while(x<10){
            var z = y+x;
            document.getElementById(z).style.cssText = "animation-name: SlideL_first;";
            x = (x*1)+1;
        }
        document.getElementById("incredable__offers__examples__arrow__r").classList.remove("grayedout");
    }
</code>```

but getting this error

mainscript.js:67 Uncaught TypeError: Cannot read property 'style' of
  null

答: Thanks for the comments, x should start from 1 not 0, stupid mistake from my side!</p>

Body:
I want to convert these codes:

if(slidedLcount == 0){
        document.getElementById("incredable__offers__examples__item_1").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_2").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_3").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_4").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_5").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_6").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_7").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_8").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_9").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__item_10").style.cssText = "animation-name: SlideL_first;";
        document.getElementById("incredable__offers__examples__arrow__r").classList.remove("grayedout");
    }

to these so it would make it a lot easier, cause will use it mutiple times:

if(slidedLcount == 0){
        var x = "0";
        var y = "incredable__offers__examples__item_"
        while(x<10){
            var z = y+x;
            document.getElementById(z).style.cssText = "animation-name: SlideL_first;";
            x = (x*1)+1;
        }
        document.getElementById("incredable__offers__examples__arrow__r").classList.remove("grayedout");
    }

but getting this error

mainscript.js:67 Uncaught TypeError: Cannot read property 'style' of
  null


问:
Difference between Frames and Packets in FFmpeg
I am trying to decode an MPEG video file using LibAV. There are two terms which I am not able to grok properly, Frames and Packets.

As per my present understanding, Frames are uncompressed video frames and packets are the compressed frames.

Questions :

Packet has multiple frames, right?

Can a frame be only part of one Packet? I refer to the case where a half of the frame information is in packet1 and another half in packet2? Is it possible?

How will we know how many frames are in a packet in LibAV?

答:
To answer your first and third questions:

according to the doc for the AVPacket class: "For video, it should typically contain one compressed frame. For audio it may contain several compressed frames.

the decode video example gives this code that reads all frames within a packet; you can also use it to count the frames:

static void decode(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt,
                   const char *filename)
{
    char buf[1024];
    int ret;
    ret = avcodec_send_packet(dec_ctx, pkt);
    if (ret < 0) {
        fprintf(stderr, "Error sending a packet for decoding\n");
        exit(1);
    }
    while (ret >= 0) {
        ret = avcodec_receive_frame(dec_ctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error during decoding\n");
            exit(1);
        }
        printf("saving frame %3d\n", dec_ctx->frame_number);
        fflush(stdout);
        /* the picture is allocated by the decoder. no need to
           free it */
        snprintf(buf, sizeof(buf), filename, dec_ctx->frame_number);
        pgm_save(frame->data[0], frame->linesize[0],
                 frame->width, frame->height, buf);
    }
}
```


问:
Objects are not valid as a React child (object with keys) React native
Trying to display Api data with Fetch, wanted to know how can i only bring only 'brand' in the return.Getting Error 'Objects are not valid as a React child: object with keys {all}. If you mean to render a collection of children use an array instead'. </p>

```<code> export default App = () => {
    const [isLoading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    useEffect(() => {
  fetch('https://', {
        method: 'POST',
        timeout: 10000,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },

        })
    })
        .then((response) => response.json())
     // .then((responseData) => { console.log(responseData); })
       .then((responseData)=> setData(responseData))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false)); [fetch, data];
    }, []);

    return (

<ScrollView>
         <View style= {styles.container}>
            <Text> {data.data}  </Text>
         </View>
         </ScrollView>
</code>```

<p>My Sample api return value </p>

```<code>Object {
  "data": Object {
    "all": Array [
      Object {
        "brand": "A1",
      },
      Object {
        "brand": "B1",
      },
      Object {
        "brand": "C1",
</code>```

答:
```<code>export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://', {
    method: 'POST',
    timeout: 10000,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    },

    })
})
    .then((response) => response.json())
 // .then((responseData) => { console.log(responseData); })
   .then((responseData)=> setData(responseData.data))
    .catch((error) => console.error(error))
    .finally(() => setLoading(false)); [fetch, data];
}, []);

return (

    <ScrollView>
     <View style= {styles.container}>
        {data.map((value,index)=>(<Text key={index}>{value.brand}</Text>)}
     </View>
     </ScrollView>
   )
  }
</code>```

You should use a map to access an array of objects.

You should add proper keys in response to avoid side effects.

Body:
Trying to display Api data with Fetch, wanted to know how can i only bring only 'brand' in the return.Getting Error 'Objects are not valid as a React child: object with keys {all}. If you mean to render a collection of children use an array instead'.

 export default App = () => {
    const [isLoading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    useEffect(() => {
  fetch('https://', {
        method: 'POST',
        timeout: 10000,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },

        })
    })
        .then((response) => response.json())
     // .then((responseData) => { console.log(responseData); })
       .then((responseData)=> setData(responseData))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false)); [fetch, data];
    }, []);

    return (

<ScrollView>
         <View style= {styles.container}>
            <Text> {data.data}  </Text>
         </View>
         </ScrollView>

My Sample api return value

Object {
  "data": Object {
    "all": Array [
      Object {
        "brand": "A1",
      },
      Object {
        "brand": "B1",
      },
      Object {
        "brand": "C1",

Body:
export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://', {
    method: 'POST',
    timeout: 10000,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    },

    })
})
    .then((response) => response.json())
 // .then((responseData) => { console.log(responseData); })
   .then((responseData)=> setData(responseData.data))
    .catch((error) => console.error(error))
    .finally(() => setLoading(false)); [fetch, data];
}, []);

return (

    <ScrollView>
     <View style= {styles.container}>
        {data.map((value,index)=>(<Text key={index}>{value.brand}</Text>)}
     </View>
     </ScrollView>
   )
  }

You should use a map to access an array of objects.

You should add proper keys in response to avoid side effects.