问:
JS code with table header fixed TH width must be equal to TD width
Header fixed on scroll works fine. But what I want,

Header TH should be equal to Body TD.

you can see both have different widths right now.
If the question is unclear please let me know. I don't want to use any other JS LIB or plugin.

(function ($) {
    $.fn.headerFixed = function (topOffSetVal,fTableID,topPosition) {
    var tableWidth = $('#'+fTableID).width();
        $(window).scroll(function(){
            if($(this).scrollTop() > topOffSetVal){
                $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
            }else{
                $("#"+fTableID+' > thead').removeAttr('style')
            }
        });
        $( window ).resize(function() {
                  tableWidth = $('#'+fTableID).width();
              $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
        });
    };
})(jQuery);

$(document).ready(function(){
 $('#myID').headerFixed(400,'myID',0);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table tr, .table td{
 border:0.1px solid #ddd;
}
.table thead{
 background:#C00; color:#FFF;
}</code>```

                Sr#
                MAP
                YARD ID
                NAME
                REGION
                YARD PORT
                ADDRESS
                ACCESS INFO
                CAPACITY
                TIMING
                Web
                Auction

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                Sr#
                MAP
                YARD ID
                NAME
                REGION
                YARD PORT
                ADDRESS
                ACCESS INFO
                CAPACITY
                TIMING
                Show on Web
                Auction

```

Thanks regards Zaid Bin Khalid

答:
You are passing a fixed width of 1233px that's the reason the header.th  != body.td

Update your jquery function code with this

```<code>(function ($) {
    $.fn.headerFixed = function (topOffSetVal,fTableID,topPosition) {
    var tableWidth = $('#'+fTableID).width();
        $(window).scroll(function(){
            if($(this).scrollTop() > topOffSetVal){
                $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
            }else{
                $("#"+fTableID+' > thead').removeAttr('style')
            }
        });
        $( window ).resize(function() {
                  tableWidth = $('#'+fTableID).width();
              $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
        });
    };
})(jQuery);

$(document).ready(function(){
    $('#myID').headerFixed(400,'myID',0);
});
</code>```

Body:
Header fixed on scroll works fine. But what I want,

Header TH should be equal to Body TD.

you can see both have different widths right now.
If the question is unclear please let me know. I don't want to use any other JS LIB or plugin.

(function ($) {
    $.fn.headerFixed = function (topOffSetVal,fTableID,topPosition) {
    var tableWidth = $('#'+fTableID).width();
        $(window).scroll(function(){
            if($(this).scrollTop() > topOffSetVal){
                $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
            }else{
                $("#"+fTableID+' > thead').removeAttr('style')
            }
        });
        $( window ).resize(function() {
                  tableWidth = $('#'+fTableID).width();
              $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
        });
    };
})(jQuery);

$(document).ready(function(){
 $('#myID').headerFixed(400,'myID',0);
});

.table tr, .table td{
 border:0.1px solid #ddd;
}
.table thead{
 background:#C00; color:#FFF;
}

                Sr#
                MAP
                YARD ID
                NAME
                REGION
                YARD PORT
                ADDRESS
                ACCESS INFO
                CAPACITY
                TIMING
                Web
                Auction

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                1

                3453
                test name
                kanagawa
                Ktoyo
                Test address here, address address address address
                Access info goes here Access info goes here
                5600
                80:50 PM
                Yes

                    Delete
                    Edit Image
                    Time Edit
                    Edit Rec.

                Sr#
                MAP
                YARD ID
                NAME
                REGION
                YARD PORT
                ADDRESS
                ACCESS INFO
                CAPACITY
                TIMING
                Show on Web
                Auction

Thanks regards Zaid Bin Khalid

Body:
You are passing a fixed width of 1233px that's the reason the header.th  != body.td

Update your jquery function code with this

(function ($) {
    $.fn.headerFixed = function (topOffSetVal,fTableID,topPosition) {
    var tableWidth = $('#'+fTableID).width();
        $(window).scroll(function(){
            if($(this).scrollTop() > topOffSetVal){
                $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
            }else{
                $("#"+fTableID+' > thead').removeAttr('style')
            }
        });
        $( window ).resize(function() {
                  tableWidth = $('#'+fTableID).width();
              $("#"+fTableID+' > thead').css({'position':'fixed','top':topPosition+'px','margin-left':'0px','width':tableWidth+'px'});
        });
    };
})(jQuery);

$(document).ready(function(){
    $('#myID').headerFixed(400,'myID',0);
});


来源: stackexchange

问:
Availability Group replica failover connection issue
I uploaded a video explaining what happens: https://www.youtube.com/watch?v=eDuRxJAdsLw&feature=youtu.be

When I first try to connect to the failover replica SQL02 under the availability group connection in SQL server management studio, SQL server management studio is unable to connect to SQL02, I have to press options in the connection dialog in order for it to pick the correct port, in my case 1433. So, what port is it trying to connect to? Why does this happen and I have to press options to fix this?

SQL server 2016 with CU2 installed.
Windows server 2016 as well.
SQL server management studio 17.1.

I understand very well that this can be achieved under the failover console, but I am wondering why the management studio is behaving this way. Suppose the default port for this replica server was 1434, what would I do then?

答:
, I have to press options in the connection dialog in order for it to pick the correct port, in my case 1433

I assume you are trying to connect to one of the instances under an availabilty group,but it connects only when you provide port number..

I believe this issue seems to be with SQLBrowser service.SQL Browser service runs and monitor incoming connections and redirects them to appropriate instances.First check whether this service is on..

Normally you don't need SQLBrowser service,unless you have one or more instances running on the same box..

Try check if sql server browser service status

ContentLicense: CC BY-SA 3.0


问:
Android - Toolbar and TabLayout scroll if drag them up/down
How to avoid scrolling of Toolbar and TabLayout by dragging them ? In my example I have such main.xml

```<code> <android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="?attr/colorPrimary"
            android:elevation="1dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
        </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code>```

ViewPager contains fragment with recycleview. The problem is that I can scroll Toolbar and TabLayout by dragging them up and down even if recycleview is not instantiated. I want that Toolbar and TabLayout scroll only when I scroll recycleview. Do you have any ideas how to achieve it ?

答:
In your activity class, you can put:

```<code>tabLayout.setClickable(false);
</code>```

or

```<code>tabLayout.setEnabled(false);
</code>```

And only enable again in the condition that you want.

Body:
How to avoid scrolling of Toolbar and TabLayout by dragging them ? In my example I have such main.xml

 <android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="?attr/colorPrimary"
            android:elevation="1dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
        </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

ViewPager contains fragment with recycleview. The problem is that I can scroll Toolbar and TabLayout by dragging them up and down even if recycleview is not instantiated. I want that Toolbar and TabLayout scroll only when I scroll recycleview. Do you have any ideas how to achieve it ?

Body:
In your activity class, you can put:

tabLayout.setClickable(false);

or

tabLayout.setEnabled(false);

And only enable again in the condition that you want.


问:
How to provide a plugin with data capabilities?
I have an application in which i want to provide the people who write plugins to it (plugins are made by implementing a basic interface, then i load the .dll). I want to give them the possibility to create settings and save data in my existing database. I would like to do this without having to create a table for each plugin - but if its required im willing to do it. I have come up with two basic scenarios:

Give the plugin an interface, where it can get a Dictionary  and serialize it to xml and save it in my database.

The plugin must be contained within a .zip file with a manifest file (my own invention) where it has a create sql script and a drop script for tables.

The first has limitations towards complex data types. The second has a larger complexity in the plugin, since it needs to be within a .zip file and unpacked etc...

Please advice on either of these approaces, or alternatives.

Cheers

答: 1st aproach seems fine. If application wants to save complex configuration, it can either save it as multiple keys or serialize some complex configuration object into string.</p>

ContentLicense: CC BY-SA 2.5


问:
Prospect matching query does not exist
i am new in django and i am stuck with this form problem. I have no idea what the error means.

Prospect matching query does not exist.

it says the error occurs here: if form.is_valid():

here's my files:

forms.py

```<code>class ProspectForm(forms.ModelForm):
    full_name = forms.CharField(
        label="Full Name",
        max_length=120,
        required=False,
    )

    email = forms.EmailField(
        label="E-mail",
        max_length=120,
        required=False,
    )

    contact_number = forms.CharField(
        label="Contact Number",
        max_length=14,
        required=False,
    )

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            Prospect.objects.get(email=email)
            raise forms.ValidationError('This email is taken')
        except VendicsUser.DoesNotExist:
            return email

    def clean_number(self):
        number = self.cleaned_data.get('number')
        validate_integer(number)
        try:
            Prospect.objects.get(contact_number=number)
            raise forms.ValidationError('This number is taken')
        except VendicsUser.DoesNotExist:
            if len(number) < 11:
                return number
            else:
                raise forms.ValidationError('Number is too short')

    def __init__(self, *args):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_class = 'contact_form'
        self.helper.form_action = ''
        self.helper.layout = Layout(
            Field('full_name', css_class='form_fields'),
            Field('email', css_class='form_fields'),
            Field('contact_number', css_class='form_fields'),
            Hidden('sub_domain', ''),
            FormActions(
                Submit('submit', 'SUBMIT', css_class='form_button'),
            )
        )
        super(ProspectForm, self).__init__(*args)

    class Meta:
        model = Prospect
        exclude = ['user']
</code>```

views.py

```<code>def landingpage(request, subdomain=None):
    form = ProspectForm(request.POST or None)
    if form.is_valid():
        form.save(commit=False)
        # for future changes
        form.save()
        return redirect('' + subdomain + '/')

    context = {
        'subdomain': subdomain,
        'form': form,
    }
    user = get_object_or_404(WebDetail, domain=subdomain)
    return render(request, "landingpage/landingpage.html", context)
</code>```

答:
You're getting the error because you're attempting to get an object that doesn't exist in the database. You didn't post the backtrace but I think this is the problem:

```<code>try:
    Prospect.objects.get(email=email)
    raise forms.ValidationError('This email is taken')
except VendicsUser.DoesNotExist:
    return email
</code>```

The get() raises a Prospect.DoesNotExist exception, not VendicsUser.DoesNotExist. The raised exception goes right past your except block. Update all code to reflect the exception you're trying to catch and you're good to go.

Title: Prospect matching query does not exist

Body:
i am new in django and i am stuck with this form problem. I have no idea what the error means.

Prospect matching query does not exist.

it says the error occurs here: if form.is_valid():

here's my files:

forms.py

class ProspectForm(forms.ModelForm):
    full_name = forms.CharField(
        label="Full Name",
        max_length=120,
        required=False,
    )

    email = forms.EmailField(
        label="E-mail",
        max_length=120,
        required=False,
    )

    contact_number = forms.CharField(
        label="Contact Number",
        max_length=14,
        required=False,
    )

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            Prospect.objects.get(email=email)
            raise forms.ValidationError('This email is taken')
        except VendicsUser.DoesNotExist:
            return email

    def clean_number(self):
        number = self.cleaned_data.get('number')
        validate_integer(number)
        try:
            Prospect.objects.get(contact_number=number)
            raise forms.ValidationError('This number is taken')
        except VendicsUser.DoesNotExist:
            if len(number) < 11:
                return number
            else:
                raise forms.ValidationError('Number is too short')

    def __init__(self, *args):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_class = 'contact_form'
        self.helper.form_action = ''
        self.helper.layout = Layout(
            Field('full_name', css_class='form_fields'),
            Field('email', css_class='form_fields'),
            Field('contact_number', css_class='form_fields'),
            Hidden('sub_domain', ''),
            FormActions(
                Submit('submit', 'SUBMIT', css_class='form_button'),
            )
        )
        super(ProspectForm, self).__init__(*args)

    class Meta:
        model = Prospect
        exclude = ['user']

views.py

def landingpage(request, subdomain=None):
    form = ProspectForm(request.POST or None)
    if form.is_valid():
        form.save(commit=False)
        # for future changes
        form.save()
        return redirect('' + subdomain + '/')

    context = {
        'subdomain': subdomain,
        'form': form,
    }
    user = get_object_or_404(WebDetail, domain=subdomain)
    return render(request, "landingpage/landingpage.html", context)

Body:
You're getting the error because you're attempting to get an object that doesn't exist in the database. You didn't post the backtrace but I think this is the problem:

try:
    Prospect.objects.get(email=email)
    raise forms.ValidationError('This email is taken')
except VendicsUser.DoesNotExist:
    return email

The get() raises a Prospect.DoesNotExist exception, not VendicsUser.DoesNotExist. The raised exception goes right past your except block. Update all code to reflect the exception you're trying to catch and you're good to go.


问:
Query runs in less than a millisecond in SQL, but times out in Entity Framework
The following linq-to-entities query throws

Entity Framework Timeout expired. The timeout period elapsed prior to
  completion of the operation or the server is not responding.

after ToList()ing it.

```<code> var q = (from contact
          in cDB.Contacts.Where(x => x.Templategroepen.Any(z => z.Autonummer == templategroep.Autonummer)
                                && !x.Uitschrijvings.Any(t => t.Templategroep.Autonummer == templategroep.Autonummer))
          select contact.Taal).Distinct();
</code>```

((System.Data.Objects.ObjectQuery)q).ToTraceString() gives me:

```<code>SELECT
[Distinct1].[Taal] AS [Taal]
FROM ( SELECT DISTINCT
[Extent1].[Taal] AS [Taal]
FROM [dbo].[ContactSet] AS [Extent1]
WHERE ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[TemplategroepContact] AS [Extent2]
WHERE ([Extent1].[Autonummer] = [Extent2].[Contacts_Autonummer]) AND ([Extent2].[Templategroepen_Autonummer] = @p__linq__0)
)) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[UitschrijvingenSet] AS [Extent3]
WHERE ([Extent1].[Autonummer] = [Extent3].[Contact_Autonummer]) AND ([Extent3].[Templategroep_Autonummer] = @p__linq__1)
))
)  AS [Distinct1]
</code>```

the query from tracestring runs in under 1 seconds in sql management studio, but times out when actually to-listing it? how is that possible again?

*Update: added SQL PROFILER output for query *  this runs as slow as the EF ToList() (>30seconds)

```<code>exec sp_executesql N'SELECT
[Distinct1].[Taal] AS [Taal]
FROM ( SELECT DISTINCT
    [Extent1].[Taal] AS [Taal]
    FROM [dbo].[ContactSet] AS [Extent1]
    WHERE ( EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[TemplategroepContact] AS [Extent2]
        WHERE ([Extent1].[Autonummer] = [Extent2].[Contacts_Autonummer]) AND ([Extent2].[Templategroepen_Autonummer] = @p__linq__0)
    )) AND ( NOT EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[UitschrijvingenSet] AS [Extent3]
        WHERE ([Extent1].[Autonummer] = [Extent3].[Contact_Autonummer]) AND ([Extent3].[Templategroep_Autonummer] = @p__linq__1)
    ))
)  AS [Distinct1]',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=1,@p__linq__1=1
</code>```

答: You need to Add one column serves as uniqueId or key to be able to work in EF</p>

Body:
The following linq-to-entities query throws

Entity Framework Timeout expired. The timeout period elapsed prior to
  completion of the operation or the server is not responding.

after ToList()ing it.

 var q = (from contact
          in cDB.Contacts.Where(x => x.Templategroepen.Any(z => z.Autonummer == templategroep.Autonummer)
                                && !x.Uitschrijvings.Any(t => t.Templategroep.Autonummer == templategroep.Autonummer))
          select contact.Taal).Distinct();

((System.Data.Objects.ObjectQuery)q).ToTraceString() gives me:

SELECT
[Distinct1].[Taal] AS [Taal]
FROM ( SELECT DISTINCT
[Extent1].[Taal] AS [Taal]
FROM [dbo].[ContactSet] AS [Extent1]
WHERE ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[TemplategroepContact] AS [Extent2]
WHERE ([Extent1].[Autonummer] = [Extent2].[Contacts_Autonummer]) AND ([Extent2].[Templategroepen_Autonummer] = @p__linq__0)
)) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[UitschrijvingenSet] AS [Extent3]
WHERE ([Extent1].[Autonummer] = [Extent3].[Contact_Autonummer]) AND ([Extent3].[Templategroep_Autonummer] = @p__linq__1)
))
)  AS [Distinct1]

the query from tracestring runs in under 1 seconds in sql management studio, but times out when actually to-listing it? how is that possible again?

*Update: added SQL PROFILER output for query *  this runs as slow as the EF ToList() (>30seconds)

exec sp_executesql N'SELECT
[Distinct1].[Taal] AS [Taal]
FROM ( SELECT DISTINCT
    [Extent1].[Taal] AS [Taal]
    FROM [dbo].[ContactSet] AS [Extent1]
    WHERE ( EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[TemplategroepContact] AS [Extent2]
        WHERE ([Extent1].[Autonummer] = [Extent2].[Contacts_Autonummer]) AND ([Extent2].[Templategroepen_Autonummer] = @p__linq__0)
    )) AND ( NOT EXISTS (SELECT
        1 AS [C1]
        FROM [dbo].[UitschrijvingenSet] AS [Extent3]
        WHERE ([Extent1].[Autonummer] = [Extent3].[Contact_Autonummer]) AND ([Extent3].[Templategroep_Autonummer] = @p__linq__1)
    ))
)  AS [Distinct1]',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=1,@p__linq__1=1


问:
How to subscribe to CloudMQTT using MqttDotNet or any other dot net client
I have created new MQTT instance using https://www.cloudmqtt.com/ below are the details

And below is my code I am using MqttDotNet as given on CloudMQTT website ( https://www.cloudmqtt.com/docs-dotnet.html ). Which gives error "Unable to connect to the broker"
        I am not sure how to connect to MQTT what should be the connection string how to use it with username and password.

```<code>  using System;
using MqttLib;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting MqttDotNet sample program.");
            Console.WriteLine("Press any key to stop\n");
            Program prog = new Program(Guid.NewGuid().ToString());
            prog.Start();

            Console.ReadKey();
            prog.Stop();
        }

        IMqtt _client;
        Program(string clientId)
        {
            // string connectionString = "mqtt://m13.cloudmqtt.com:12644";
            string connectionString = "mqtt://moraasdrxf:_WaY_f_sLt8Efd@m13.cloudmqtt.com:12644";
            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId, "dhiraj", "dhiraj");
            // Setup some useful client delegate callbacks
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
        }

        void Start()
        {
            // Connect to broker in 'CleanStart' mode
            Console.WriteLine("Client connecting\n");
            _client.Connect(true);
        }

        void Stop()
        {
            if (_client.IsConnected)
            {
                Console.WriteLine("Client disconnecting\n");
                _client.Disconnect();
                Console.WriteLine("Client disconnected\n");
            }
        }

        void client_Connected(object sender, EventArgs e)
        {
            Console.WriteLine("Client connected\n");
            RegisterOurSubscriptions();
            PublishSomething();
        }

        void _client_ConnectionLost(object sender, EventArgs e)
        {
            Console.WriteLine("Client connection lost\n");
        }

        void RegisterOurSubscriptions()
        {
            Console.WriteLine("Subscribing to mqttdotnet/subtest/#\n");
            //_client.Subscribe("mqttdotnet/subtest/#", QoS.BestEfforts);
            _client.Subscribe("dhiraj/test", QoS.BestEfforts);

        }

        void PublishSomething()
        {
            Console.WriteLine("Publishing on mqttdotnet/pubtest\n");
            _client.Publish("dhiraj/test", "Hello MQTT World", QoS.BestEfforts, false);
        }

        bool client_PublishArrived(object sender, PublishArrivedArgs e)
        {
            Console.WriteLine("Received Message");
            Console.WriteLine("Topic: " + e.Topic);
            Console.WriteLine("Payload: " + e.Payload);
            Console.WriteLine();
            return true;
        }
    }
}
</code>```

Can anybody please help me with this ??

答:
This is resolved. MQTT dot net implementation use tcp protocol to make connection to brocker
connection string should be
string connectionString = "tcp://m13.cloudmqtt.com:12644"</p>

Body:
I have created new MQTT instance using https://www.cloudmqtt.com/ below are the details

And below is my code I am using MqttDotNet as given on CloudMQTT website ( https://www.cloudmqtt.com/docs-dotnet.html ). Which gives error "Unable to connect to the broker"
        I am not sure how to connect to MQTT what should be the connection string how to use it with username and password.

  using System;
using MqttLib;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting MqttDotNet sample program.");
            Console.WriteLine("Press any key to stop\n");
            Program prog = new Program(Guid.NewGuid().ToString());
            prog.Start();

            Console.ReadKey();
            prog.Stop();
        }

        IMqtt _client;
        Program(string clientId)
        {
            // string connectionString = "mqtt://m13.cloudmqtt.com:12644";
            string connectionString = "mqtt://moraasdrxf:_WaY_f_sLt8Efd@m13.cloudmqtt.com:12644";
            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId, "dhiraj", "dhiraj");
            // Setup some useful client delegate callbacks
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
        }

        void Start()
        {
            // Connect to broker in 'CleanStart' mode
            Console.WriteLine("Client connecting\n");
            _client.Connect(true);
        }

        void Stop()
        {
            if (_client.IsConnected)
            {
                Console.WriteLine("Client disconnecting\n");
                _client.Disconnect();
                Console.WriteLine("Client disconnected\n");
            }
        }

        void client_Connected(object sender, EventArgs e)
        {
            Console.WriteLine("Client connected\n");
            RegisterOurSubscriptions();
            PublishSomething();
        }

        void _client_ConnectionLost(object sender, EventArgs e)
        {
            Console.WriteLine("Client connection lost\n");
        }

        void RegisterOurSubscriptions()
        {
            Console.WriteLine("Subscribing to mqttdotnet/subtest/#\n");
            //_client.Subscribe("mqttdotnet/subtest/#", QoS.BestEfforts);
            _client.Subscribe("dhiraj/test", QoS.BestEfforts);

        }

        void PublishSomething()
        {
            Console.WriteLine("Publishing on mqttdotnet/pubtest\n");
            _client.Publish("dhiraj/test", "Hello MQTT World", QoS.BestEfforts, false);
        }

        bool client_PublishArrived(object sender, PublishArrivedArgs e)
        {
            Console.WriteLine("Received Message");
            Console.WriteLine("Topic: " + e.Topic);
            Console.WriteLine("Payload: " + e.Payload);
            Console.WriteLine();
            return true;
        }
    }
}

Can anybody please help me with this ??


问:
using ESI slower than EAX?
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

```<code>jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1
</code>```

```<code>jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1
</code>```

答:
Speed of registers depends on what are you doing with them, because every register has its own circuitry. For example ecx is connected to counter circuits so it will be faster if used as counter, eax is well connected to the ALU so it's the best register for math tasks. Of course now you can use ecx for math and eax as counter, but in the early processors era programmers hadn't this freedom.
In fact esi is used for memory access, so it is connected "better" (please pass the term, I can't express myself better) to the memory.</p>

Title: using ESI slower than EAX?

Body:
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1

jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1


问:
Windows 10 UWP on Desktop Access to Microphone Lost When App Loses Focus
I've written a Windows 10 UWP in Visual Studio 2015 in C# that uses speech recognition to perform certain commands.
All works great until the PC recovers from a display sleep or the app loses focus/is minimised. After that the app doesn't respond to the microphone unless i restart the app again.
The app is designed only to be used on a couple of my Windows 10 Desktop PCs, so not concerned about mobile or other platform functionality.
Is there any way of ensuring the app remains "connected" to the microphone or have I gone down a "blind alley" with UWP and should I have built it in WPF?
I had assumed UWP was the future standard that MS was touting and that new apps should only be written in this format and not Forms, WCF or WPF. Am I wrong and is there still a future for WPF (if "yes" can I convert my UWP app to WPF in the hope that I can still have full access to thing like the microphone as I did in an older vb.net forms version of my app?).

So, to clarify, I need to know the following:

Can a Windows 10 UWP app on Windows 10 Desktop keep connected to a microphone even if app minimised/screen timeout?

If the answer is No, then will WPF be the best route and is support for that format/platform likely to continue to be pushed as much as UWP?

If I have to go down the route of WPF can my UWP app be converted to WPF?

If A Win Forms app is the only way to ensure constant access to microphone how long is support for win forms going to continue as it is not recommended to write new apps in this format?

Any help would be very much appreciated, as I've spent a lot of time re-writing my old vb.net win forms app as a C# UWP app.
Thanks,
Richie

答:
When a UWP app is minimised, it's suspend. There is no way to keep connected to a microphone. For more info, you can check Windows 10 universal Windows platform (UWP) app lifecycle.

Since you only need the app to work on Windows 10 Desktop PCs, then one of the best options would be using WPF, WPF can also work on Windows 10 and would continue to be supported. For example, they've added per-monitor DPI-awareness support for WPF (see https://github.com/Microsoft/WPF-Samples/tree/master/PerMonitorDPI). And a lot of UWP APIs can be used in WPF, you should be able to convert your UWP app to WPF manually. For more information, see this answer.


问:
Broblem in ACTION_CALL code in android studio m
my program stopped when i click on callbutton what is the problem

```<code>public void callbutton(View v) {  try{
             intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:111*"+phone+"#"));
            startActivity(intent);
            }catch (ActivityNotFoundException e){
                Toast.makeText(data.this, "noooo", Toast.LENGTH_SHORT).show();

            }}
</code>```

**i Wrote the permission in manifests   **

```<code><uses-permission android:name="android.permission.CALL_PHONE" />
</code>```

答:
It should be like this</p>

```<code>public void callbutton(View v) {
    try {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:1234567890"));
        startActivity(intent);
    }catch (ActivityNotFoundException e){
        Toast.makeText(Activity.this, "noooo", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
my program stopped when i click on callbutton what is the problem

public void callbutton(View v) {  try{
             intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:111*"+phone+"#"));
            startActivity(intent);
            }catch (ActivityNotFoundException e){
                Toast.makeText(data.this, "noooo", Toast.LENGTH_SHORT).show();

            }}

**i Wrote the permission in manifests   **

<uses-permission android:name="android.permission.CALL_PHONE" />

Body:
It should be like this

public void callbutton(View v) {
    try {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:1234567890"));
        startActivity(intent);
    }catch (ActivityNotFoundException e){
        Toast.makeText(Activity.this, "noooo", Toast.LENGTH_SHORT).show();
    }
}


问:
Retaining n most recent directories in a backup script
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017
</code>```

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
</code>```

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

```<code>find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;
</code>```

Do you guys have another idea to do that?

答:
Here is one way.

Updated answer.

```<code>[dev]$ find backup/*  | grep -vE "$(date '+%Y')|$(date +%Y --date='1 year ago')|$(date +%Y --date='2 year ago')" | xargs  rm -rfv

removed directory: ‘backup/2012’
removed directory: ‘backup/2013’
removed directory: ‘backup/2014’
</code>```

Body:
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

/home/backup/2012
/home/backup/2013
/home/backup/2014

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;

Do you guys have another idea to do that?

Body:
Here is one way.

Updated answer.

[dev]$ find backup/*  | grep -vE "$(date '+%Y')|$(date +%Y --date='1 year ago')|$(date +%Y --date='2 year ago')" | xargs  rm -rfv

removed directory: ‘backup/2012’
removed directory: ‘backup/2013’
removed directory: ‘backup/2014’


问:
Trying to pass SqlCommand in SqlDataAdapter as parameters
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

```<code>if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }
</code>```

Successful connection class code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}
</code>```

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}
</code>```

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

答: The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.</p>

Body:
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }

Successful connection class code

public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...


问:
Django - reload only body page using block not refresh whole page
base.html

```<code><body class="skin-red">
    <!-- Site wrapper -->
    <div class="wrapper">

        <!-- #HEADER -->
        {% include 'HEADER.html' %}
        <!-- /#HEADER -->

        <!-- #SIDEBAR -->
        {% include 'SIDEBAR.html' %}
        <!-- /#SIDEBAR -->

        <!-- #BODY -->
        {% block content %}
        {% endblock %}

        <!-- /#BODY -->

        <!-- #FOOTER -->
        {% include 'FOOTER.html' %}
        <!-- /#FOOTER -->

        {% block extrajavascript %}
        {% endblock %}

  </body>
</code>```

HEADER.html:

```<code>  <header class="main-header">
    <a href="/rm" class="logo"><b>Resource</b> Monitor <i class="fa fa-bar-chart-o" style="color:#ffd400"></i></a>
    <!-- Header Navbar: style can be found in header.less -->
    <nav class="navbar navbar-static-top" role="navigation">
        <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
            <span class="sr-only">Toggle navigation</span>
        </a>

        <ul class="nav navbar-nav">
            <li><a href="/rm">Home <span class="sr-only">(current)</span></a></li>
            <li><a href="/rm/pcinfo"> PC information </a></li>
            <li><a data-toggle="tab" href="#tab_sysuse">??? ???</a></li>
            <li><a data-toggle="tab" href="#tab_procuse">???? ???</a></li>
            <li><a data-toggle="tab" href="#tab_prodet">???? ????</a></li>
            <li><a data-toggle="tab" href="#tab_sdwt">SDWT ????</a></li>
            <li><a data-toggle="tab" href="#tab_pcevents">??? ?? ??</a></li>
            <li><a data-toggle="tab" href="#tab_winevents">??? ?? ID? ??</a></li>
            <li><a data-toggle="tab" href="#tab_agentinfo">Agent ????</a></li>
            <li class="dropdown">
                <a class="dropdown-toggle" data-toggle="dropdown" href="#">Email ?? ?? <span class="caret"></span></a>
                <ul class="dropdown-menu" role="menu">
                    <li><a data-toggle="tab" href="#tab_emailconfigs">??? ??</a></li>
                    <li><a data-toggle="tab" href="#tab_emailreceiver">??? ??</a></li>
                </ul>
            </li>
        </ul>
    </nav>
</header>
</code>```

When I click header tab menu, I want to reload only
 {% block content %}
 {% endblock %}
 not whole pages.. but now It reloaded the whole page..
There are formbox in my side bar and there are some values which user input. so I don't want to loose my user input by refresh whole page. Is there any solution..?

答:
You need javascript AJAX api to get the content and change the html content using javascript DOM api if you need "without reload" function.

Django or any application server or http webserver works in a
  request-response way, when a response is returned to the browser, the
  server has no control to the client.

Body:
base.html

        {% include 'HEADER.html' %}

        {% include 'SIDEBAR.html' %}

        {% block content %}
        {% endblock %}

        {% include 'FOOTER.html' %}

        {% block extrajavascript %}
        {% endblock %}

HEADER.html:

    Resource Monitor

            Toggle navigation

Home (current)

 PC information

??? ???

???? ???

???? ????

SDWT ????

??? ?? ??

??? ?? ID? ??

Agent ????

                Email ?? ??

??? ??

??? ??

When I click header tab menu, I want to reload only
 {% block content %}
 {% endblock %}
 not whole pages.. but now It reloaded the whole page..
There are formbox in my side bar and there are some values which user input. so I don't want to loose my user input by refresh whole page. Is there any solution..?


问:
Java: Possible to use a single for-loop instead of two?
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

```<code>public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}
</code>```

An example input:

```<code>4
1 2 3 4
</code>```

Expected output:

```<code>4 3 2 1
</code>```

答:
Use a StringBuilder and always insert at 0 index.

See: Oracle » JavaDocs » 1.7 » java.lang.StringBuilder.insert(int, int)

```<code>StringBuilder bld = new StringBuilder();

for (int arr_i = 0; arr_i < n; arr_i++) {
    int i = in.nextInt();
    bld.insert(0, i);
}

System.out.println(bld.toString());
</code>```

Body:
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}

An example input:

4
1 2 3 4

Expected output:

4 3 2 1

Body:
Use a StringBuilder and always insert at 0 index.

See: Oracle » JavaDocs » 1.7 » java.lang.StringBuilder.insert(int, int)

StringBuilder bld = new StringBuilder();

for (int arr_i = 0; arr_i < n; arr_i++) {
    int i = in.nextInt();
    bld.insert(0, i);
}

System.out.println(bld.toString());


问:
(Android Studio Speech Recognizer) I'm getting error 9 (insufficient Privileges) even though I have given it RECORD_AUDIO and INTERNET
```<code>package blessupboys.speechtest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.util.Log;

public class VoiceRecognitionTest extends Activity implements OnClickListener
{

    private TextView mText;
    private SpeechRecognizer sr;
    private static final String TAG = "MyStt3Activity";
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_recognition_test);
        Button speakButton = (Button) findViewById(R.id.btn_speak);
        mText = (TextView) findViewById(R.id.textView1);
        speakButton.setOnClickListener(this);
        sr = SpeechRecognizer.createSpeechRecognizer(this);
        sr.setRecognitionListener(new listener());
    }

    class listener implements RecognitionListener
    {
        public void onReadyForSpeech(Bundle params)
        {
            Log.d(TAG, "onReadyForSpeech");
        }
        public void onBeginningOfSpeech()
        {
            Log.d(TAG, "onBeginningOfSpeech");
        }
        public void onRmsChanged(float rmsdB)
        {
            Log.d(TAG, "onRmsChanged");
        }
        public void onBufferReceived(byte[] buffer)
        {
            Log.d(TAG, "onBufferReceived");
        }
        public void onEndOfSpeech()
        {
            Log.d(TAG, "onEndofSpeech");
        }
        public void onError(int error)
        {
            Log.d(TAG,  "error " +  error);
            mText.setText("error " + error);
        }
        public void onResults(Bundle results)
        {
            String str = new String();
            Log.d(TAG, "onResults " + results);
            ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            for (int i = 0; i < data.size(); i++)
            {
                Log.d(TAG, "result " + data.get(i));
                str += data.get(i);
            }
            mText.setText("results: "+String.valueOf(data.size()));
        }
        public void onPartialResults(Bundle partialResults)
        {
            Log.d(TAG, "onPartialResults");
        }
        public void onEvent(int eventType, Bundle params)
        {
            Log.d(TAG, "onEvent " + eventType);
        }
    }
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak)
        {
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");

            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
            sr.startListening(intent);
            Log.i("111111","11111111");
        }
    }
}
</code>```

And My Android Manifest File looks like:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="blessupboys.speechtest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VoiceRecognitionTest"
            android:label="@string/title_activity_voice_recognition_test"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>
</code>```

My logs show that it stops because of error 9 generated in the onError() function.

```<code>01-19 20:04:57.776 18480-18480/? I/art: Not late-enabling -Xcheck:jni (already on)
01-19 20:04:57.925 18480-18480/blessupboys.speechtest W/System: ClassLoader referenced unknown path: /data/app/blessupboys.speechtest-2/lib/x86
01-19 20:04:58.341 18480-18515/blessupboys.speechtest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-19 20:04:58.443 18480-18515/blessupboys.speechtest I/OpenGLRenderer: Initialized EGL, version 1.4
01-19 20:04:58.497 18480-18515/blessupboys.speechtest W/EGL_emulation: eglSurfaceAttrib not implemented
01-19 20:04:58.497 18480-18515/blessupboys.speechtest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad79f260, error=EGL_SUCCESS
01-19 20:04:59.033 18480-18480/blessupboys.speechtest I/Choreographer: Skipped 39 frames!  The application may be doing too much work on its main thread.
01-19 20:10:09.965 18480-18480/blessupboys.speechtest I/111111: 11111111
01-19 20:10:10.049 18480-18480/blessupboys.speechtest D/MyStt3Activity: error 9
</code>```

I am trying to run this sample program to try to get familiar with the Speech Recognizer software..

Could this be an issue being caused by the fact that I'm running it on android studio rather than a real device? I am pretty stuck on this.

答:
In case anyone comes to this question and none of the other answers help, you might want to try requesting permissions using the following code:</p>

```<code>private void requestRecordAudioPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String requiredPermission = Manifest.permission.RECORD_AUDIO;

        // If the user previously denied this permission then show a message explaining why
        // this permission is needed
        if (checkCallingOrSelfPermission(requiredPermission) == PackageManager.PERMISSION_DENIED) {
            requestPermissions(new String[]{requiredPermission}, 101);
        }
    }
}
</code>```

Body:
package blessupboys.speechtest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.util.Log;

public class VoiceRecognitionTest extends Activity implements OnClickListener
{

    private TextView mText;
    private SpeechRecognizer sr;
    private static final String TAG = "MyStt3Activity";
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_recognition_test);
        Button speakButton = (Button) findViewById(R.id.btn_speak);
        mText = (TextView) findViewById(R.id.textView1);
        speakButton.setOnClickListener(this);
        sr = SpeechRecognizer.createSpeechRecognizer(this);
        sr.setRecognitionListener(new listener());
    }

    class listener implements RecognitionListener
    {
        public void onReadyForSpeech(Bundle params)
        {
            Log.d(TAG, "onReadyForSpeech");
        }
        public void onBeginningOfSpeech()
        {
            Log.d(TAG, "onBeginningOfSpeech");
        }
        public void onRmsChanged(float rmsdB)
        {
            Log.d(TAG, "onRmsChanged");
        }
        public void onBufferReceived(byte[] buffer)
        {
            Log.d(TAG, "onBufferReceived");
        }
        public void onEndOfSpeech()
        {
            Log.d(TAG, "onEndofSpeech");
        }
        public void onError(int error)
        {
            Log.d(TAG,  "error " +  error);
            mText.setText("error " + error);
        }
        public void onResults(Bundle results)
        {
            String str = new String();
            Log.d(TAG, "onResults " + results);
            ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            for (int i = 0; i < data.size(); i++)
            {
                Log.d(TAG, "result " + data.get(i));
                str += data.get(i);
            }
            mText.setText("results: "+String.valueOf(data.size()));
        }
        public void onPartialResults(Bundle partialResults)
        {
            Log.d(TAG, "onPartialResults");
        }
        public void onEvent(int eventType, Bundle params)
        {
            Log.d(TAG, "onEvent " + eventType);
        }
    }
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak)
        {
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");

            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
            sr.startListening(intent);
            Log.i("111111","11111111");
        }
    }
}

And My Android Manifest File looks like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="blessupboys.speechtest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VoiceRecognitionTest"
            android:label="@string/title_activity_voice_recognition_test"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>

My logs show that it stops because of error 9 generated in the onError() function.

01-19 20:04:57.776 18480-18480/? I/art: Not late-enabling -Xcheck:jni (already on)
01-19 20:04:57.925 18480-18480/blessupboys.speechtest W/System: ClassLoader referenced unknown path: /data/app/blessupboys.speechtest-2/lib/x86
01-19 20:04:58.341 18480-18515/blessupboys.speechtest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-19 20:04:58.443 18480-18515/blessupboys.speechtest I/OpenGLRenderer: Initialized EGL, version 1.4
01-19 20:04:58.497 18480-18515/blessupboys.speechtest W/EGL_emulation: eglSurfaceAttrib not implemented
01-19 20:04:58.497 18480-18515/blessupboys.speechtest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad79f260, error=EGL_SUCCESS
01-19 20:04:59.033 18480-18480/blessupboys.speechtest I/Choreographer: Skipped 39 frames!  The application may be doing too much work on its main thread.
01-19 20:10:09.965 18480-18480/blessupboys.speechtest I/111111: 11111111
01-19 20:10:10.049 18480-18480/blessupboys.speechtest D/MyStt3Activity: error 9

I am trying to run this sample program to try to get familiar with the Speech Recognizer software..

Could this be an issue being caused by the fact that I'm running it on android studio rather than a real device? I am pretty stuck on this.

Body:
In case anyone comes to this question and none of the other answers help, you might want to try requesting permissions using the following code:

private void requestRecordAudioPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String requiredPermission = Manifest.permission.RECORD_AUDIO;

        // If the user previously denied this permission then show a message explaining why
        // this permission is needed
        if (checkCallingOrSelfPermission(requiredPermission) == PackageManager.PERMISSION_DENIED) {
            requestPermissions(new String[]{requiredPermission}, 101);
        }
    }
}


问:
Split text from a certain word in OpenOffice
I have the following text in column A:

```<code><p>De Buddha Lounge Zenju loungeset uit de new kubu wicker Zenju loungeset collectie in de kleurstelling new kubu wicker met zandkleurige kussens. Deze loungeset wordt compleet geleverd inclusief zandkleurige zit- en rugkussens. De Zenju loungeset bestaat uit twee bank elementen van 155x85xH64 cm, een Hoekelement van 85x85xH64 cm en een lounge hocker van 73x73xH40 cm. De totale afmeting van de set is 240x240 cm.</p><p><strong>Details:</strong><br />- Loungeset: 240x240<br />- Sofa L/R:155x85xH64<br />- Hoek: 85x85xH64<br />- Tafel: 73x73xH40</p>
</code>```

My need is to split the text exactly by:

```<code><p><strong>Details:
</code>```

so that all the text up to this point is in column B, like this:

```<code><p>De Buddha Lounge Zenju loungeset uit de new kubu wicker Zenju loungeset collectie in de kleurstelling new kubu wicker met zandkleurige kussens. Deze loungeset wordt compleet geleverd inclusief zandkleurige zit- en rugkussens. De Zenju loungeset bestaat uit twee bank elementen van 155x85xH64 cm, een Hoekelement van 85x85xH64 cm en een lounge hocker van 73x73xH40 cm. De totale afmeting van de set is 240x240 cm.</p>
</code>```

We have a list that has exactly this format and need to split all the columns.

答:
Please select cells to be truncated, go to Edit > Find & Replace..., and under Search for enter:

```<code><p><strong>Details:(.*)
</code>```

leave Replace with blank but under More Options check Current selection only and Regular expressions, then Replace All.

This deletes the 'surplus' so you might want to work on a copy (say just copy ColumnA into ColumnB and work on that).

Body:
I have the following text in column A:

De Buddha Lounge Zenju loungeset uit de new kubu wicker Zenju loungeset collectie in de kleurstelling new kubu wicker met zandkleurige kussens. Deze loungeset wordt compleet geleverd inclusief zandkleurige zit- en rugkussens. De Zenju loungeset bestaat uit twee bank elementen van 155x85xH64 cm, een Hoekelement van 85x85xH64 cm en een lounge hocker van 73x73xH40 cm. De totale afmeting van de set is 240x240 cm.

Details:
- Loungeset: 240x240
- Sofa L/R:155x85xH64
- Hoek: 85x85xH64
- Tafel: 73x73xH40

My need is to split the text exactly by:

Details:

so that all the text up to this point is in column B, like this:

De Buddha Lounge Zenju loungeset uit de new kubu wicker Zenju loungeset collectie in de kleurstelling new kubu wicker met zandkleurige kussens. Deze loungeset wordt compleet geleverd inclusief zandkleurige zit- en rugkussens. De Zenju loungeset bestaat uit twee bank elementen van 155x85xH64 cm, een Hoekelement van 85x85xH64 cm en een lounge hocker van 73x73xH40 cm. De totale afmeting van de set is 240x240 cm.

We have a list that has exactly this format and need to split all the columns.

Body:
Please select cells to be truncated, go to Edit > Find & Replace..., and under Search for enter:

<p><strong>Details:(.*)

leave Replace with blank but under More Options check Current selection only and Regular expressions, then Replace All.

This deletes the 'surplus' so you might want to work on a copy (say just copy ColumnA into ColumnB and work on that).


问:
How can I use regex to parse an OCC Option Symbol?
The OCC option symbol consists of 4 parts:

Root symbol of the underlying stock or ETF, padded with spaces to 6 characters

Expiration date, 6 digits in the format yymmdd

Option type, either P or C, for put or call

Strike price, as the price x 1000, front padded with 0s to 8 digits

As an example SPX   141122P00019500 means a put on SPX, expiring on 11/22/2014, with a strike price of $19.50.

Is it possible to use regex to parse this out automatically? I'm using JavaScript

答:
You can use RegExp /^[^\s]+(?=\s+|\d{6})|\d{6}(?=C|P)|(C|P)(?=0+)|(?!:\1)0+|\d+$/g to match characters at beginning of string that are not space characters, or date as next six digits followed by C or P, or C or P followed by one or more 0 characters, or one or more 0 characters preceded by C or P, or one or more digits at end of string.

Utilize destructing assignment to define parts of matches within array separate variables.

let quote = "SPX   141122P00019500";

let re = /^[^\s]+(?=\s+|\d{6})|\d{6}(?=C|P)|(C|P)(?=0+)|(?!:\1)0+|\d+$/g;

let [ticker, date, option, strike, price] = quote.match(re);

console.log({ticker, date, option, strike, price});```


问:
Finding pattern in string using indexof
Can someone tell me why this is an infinte loop?    </p>

```<code>private void splitBody()    {
        bodyparts=new Vector();
        String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("<br />",previousIndex)!=-1) {
            int index=body.indexOf("<br />",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }
</code>```

答:
This should fix the issue:

```<code>previousIndex=index + 1;
</code>```

Otherwise you'll always find the first occurance of the pattern.

Or - simplify the whole thing:

```<code>String[] parts = body.split("<br />");
</code>```

Title: Finding pattern in string using indexof

Body:
Can someone tell me why this is an infinte loop?

private void splitBody()    {
        bodyparts=new Vector();
        String body = "
testtestest
fefefefefefefefefef
qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("
",previousIndex)!=-1) {
            int index=body.indexOf("
",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }

Body:
This should fix the issue:

previousIndex=index + 1;

Otherwise you'll always find the first occurance of the pattern.

Or - simplify the whole thing:

String[] parts = body.split("<br />");


答:
Java has inbuilt String method for the same. If your input is a String, you can use the below-</p>

```<code>String s1 = new String("new");
String s2 = s1.reverse();
System.out.println(s2) // wen
</code>```

Title: Java: Possible to use a single for-loop instead of two?

Body:
Java has inbuilt String method for the same. If your input is a String, you can use the below-

String s1 = new String("new");
String s2 = s1.reverse();
System.out.println(s2) // wen


答:
I am not sure about the requirements of your request, but you do not necessarily have to use an array for this. You can concatenate the inputs into a String in reverse order like so.</p>

```<code>public static void main(String[] args) {
    System in = new Scanner(System.in);
    int n = in.nextInt();
    String allNumbers = "";

    for (int i = 0; i < n; i++) {
        int current = in.nextInt();
        allNumbers = current + " " + allNumbers;
    }

    if(allNumbers != ""){
      allNumbers = allNumbers.substring(0,allNumbers.length()-1);
    }

    System.out.println(allNumbers);
}
</code>```

Body:
I am not sure about the requirements of your request, but you do not necessarily have to use an array for this. You can concatenate the inputs into a String in reverse order like so.

public static void main(String[] args) {
    System in = new Scanner(System.in);
    int n = in.nextInt();
    String allNumbers = "";

    for (int i = 0; i < n; i++) {
        int current = in.nextInt();
        allNumbers = current + " " + allNumbers;
    }

    if(allNumbers != ""){
      allNumbers = allNumbers.substring(0,allNumbers.length()-1);
    }

    System.out.println(allNumbers);
}


答:
A more generic solution

I think it is best to traverse the directories in the descending order and then delete the ones after the third.  This way, there is no danger of losing a directory when the script is run again and again:

```<code>#!/bin/bash
backups_to_keep=3
count=0
cd /home/backup
while read -d '' -r dir; do
  [[ -d "$dir" ]]                || continue  # skip if not directory
  ((++count <= backups_to_keep)) && continue  # skip if we are within retaining territory
  echo "Removing old backup directory '$dir'" # it is good to log what was cleaned up
  echo rm -rf -- "$dir"
done < <(find . -maxdepth 1 -name '[2-9][0-9][0-9][0-9]' -type d -print0 | sort -nrz)
</code>```

Remove the echo before rm -rf after testing.  For your example, it gives this output:

```<code>rm -rf -- ./2014
rm -rf -- ./2013
rm -rf -- ./2012
</code>```

cd /home/backup restricts rm -rf to just that directory for extra safety

find . -maxdepth 1 -name '[2-9][0-9][0-9][0-9]' -type d gives the top level directories that match the glob

sort -nrz makes sure newer directories come first, -z processes the null terminated output of find ... -print0

This solution doesn't hardcode the years - it just assumes that the directories to be removed are named in numerically sortable way

It is resilient to any other files or directories being present in the backup directory

There are no side effects if the script is run again and again

This can easily be extended to support different naming conventions for the backup directory - just change the glob expression

Title: Retaining n most recent directories in a backup script

Body:
A more generic solution

I think it is best to traverse the directories in the descending order and then delete the ones after the third.  This way, there is no danger of losing a directory when the script is run again and again:

#!/bin/bash
backups_to_keep=3
count=0
cd /home/backup
while read -d '' -r dir; do
  [[ -d "$dir" ]]                || continue  # skip if not directory
  ((++count <= backups_to_keep)) && continue  # skip if we are within retaining territory
  echo "Removing old backup directory '$dir'" # it is good to log what was cleaned up
  echo rm -rf -- "$dir"
done < <(find . -maxdepth 1 -name '[2-9][0-9][0-9][0-9]' -type d -print0 | sort -nrz)

Remove the echo before rm -rf after testing.  For your example, it gives this output:

rm -rf -- ./2014
rm -rf -- ./2013
rm -rf -- ./2012

cd /home/backup restricts rm -rf to just that directory for extra safety

find . -maxdepth 1 -name '[2-9][0-9][0-9][0-9]' -type d gives the top level directories that match the glob

sort -nrz makes sure newer directories come first, -z processes the null terminated output of find ... -print0

This solution doesn't hardcode the years - it just assumes that the directories to be removed are named in numerically sortable way

It is resilient to any other files or directories being present in the backup directory

There are no side effects if the script is run again and again

This can easily be extended to support different naming conventions for the backup directory - just change the glob expression


问:
Spring security loadByUsername's username field is empty
I'm developing a RESTful web service and had login working. I wanted to add security and access tokens so I added a UserDetailsService as seen below:

```<code>@Component
public class CustomLoginAuthenticationProvider implements UserDetailsService {

    @Autowired
    private BusinessUserService businessUserService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        if(email == null || email.isEmpty() || !email.contains("@")) {
            System.out.println("ERROR - THIS IS THE USERNAME:" + email);
            throw new UsernameNotFoundException(email);
        }
    //... More below, but it doesn't matter. Exception thrown every time
}
</code>```

However, the email string is empty. I can't understand why because I'm having a hard time understanding exactly when this method is called and what value is sent as the parameter for this method as this is a REST back end being sent JSON. Here's my WebSecurityConfigurerAdapter setup:

```<code>@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Bean
    public CustomLoginAuthenticationProvider customLoginAuthenticationProvider() {
        return new CustomLoginAuthenticationProvider();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
          .authorizeRequests()
          .antMatchers("/css/**", "/js/**", "/images/**", "/fonts/**",
                       "/videos/**", "/", "/register", "/login", "/about",
                       "/contact", "/test")
          .permitAll()
        .and()
          .authorizeRequests()
          .anyRequest()
          .authenticated()
        .and()
          .exceptionHandling()
          .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
        .and()
          .formLogin()
          .loginPage("/login")
          .loginProcessingUrl("/login")
          .usernameParameter("email")
          .passwordParameter("password")
        .and()
          .logout()
          .logoutSuccessUrl("/")
          .permitAll()
        .and()
          .csrf()
          .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
          .addFilterAfter(new CsrfTokenFilter(), CsrfFilter.class);
    }
}
</code>```

I specify that an email should be sent to the method when I use .usernameParameter("email") so I'm not really sure why it's not populating the email parameter. I'm using AngularJS in the front end and sending the credentials to the back end using JSON.

答:
Another solution, that is much easier, is to do this in your client application - works fine with Spring Security:

```<code>public login(username: string, password: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return this.http.post(
      `http://www.myserver.com:8080/myApp/login`,
      encodeURI(`username=${username}&password=${password}`),
      { headers }
    );
  }
}
</code>```

This hides the parameters from the url and encodes them as form data, and spring security's default implementation likes this a lot.

Body:
I'm developing a RESTful web service and had login working. I wanted to add security and access tokens so I added a UserDetailsService as seen below:

@Component
public class CustomLoginAuthenticationProvider implements UserDetailsService {

    @Autowired
    private BusinessUserService businessUserService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        if(email == null || email.isEmpty() || !email.contains("@")) {
            System.out.println("ERROR - THIS IS THE USERNAME:" + email);
            throw new UsernameNotFoundException(email);
        }
    //... More below, but it doesn't matter. Exception thrown every time
}

However, the email string is empty. I can't understand why because I'm having a hard time understanding exactly when this method is called and what value is sent as the parameter for this method as this is a REST back end being sent JSON. Here's my WebSecurityConfigurerAdapter setup:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Bean
    public CustomLoginAuthenticationProvider customLoginAuthenticationProvider() {
        return new CustomLoginAuthenticationProvider();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
          .authorizeRequests()
          .antMatchers("/css/**", "/js/**", "/images/**", "/fonts/**",
                       "/videos/**", "/", "/register", "/login", "/about",
                       "/contact", "/test")
          .permitAll()
        .and()
          .authorizeRequests()
          .anyRequest()
          .authenticated()
        .and()
          .exceptionHandling()
          .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
        .and()
          .formLogin()
          .loginPage("/login")
          .loginProcessingUrl("/login")
          .usernameParameter("email")
          .passwordParameter("password")
        .and()
          .logout()
          .logoutSuccessUrl("/")
          .permitAll()
        .and()
          .csrf()
          .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
          .addFilterAfter(new CsrfTokenFilter(), CsrfFilter.class);
    }
}

I specify that an email should be sent to the method when I use .usernameParameter("email") so I'm not really sure why it's not populating the email parameter. I'm using AngularJS in the front end and sending the credentials to the back end using JSON.

Body:
Another solution, that is much easier, is to do this in your client application - works fine with Spring Security:

public login(username: string, password: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return this.http.post(
      `http://www.myserver.com:8080/myApp/login`,
      encodeURI(`username=${username}&password=${password}`),
      { headers }
    );
  }
}

This hides the parameters from the url and encodes them as form data, and spring security's default implementation likes this a lot.


问:
Java for loop i++ as a string
Let's say we have a for loop

```<code>for(int i = 0; i < 10; i++) {
    ...
}
</code>```

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

```<code>for(int i = 0; i < 10; increment) {
    ...
}
</code>```

How can I make this work?

答:
The increment need to be an direct attribution,
you can't use a String to define this, is impossible

One solution to change dynamically how much will be the increment, it's using a variable

```<code>int j=1;

for(int i=0;i<10;i+=j)
</code>```

the += operator it's used for the increment, for example:

```<code>int x = 0;
x += 1; //x is 1
x += 3; //x is 4
x += 2; //x is 6
x++; //x is 7
</code>```

But in the most cases you don't need to use this in a for loop, what you need to do?

Hugs

Title: Java for loop i++ as a string

Body:
Let's say we have a for loop

for(int i = 0; i < 10; i++) {
    ...
}

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

for(int i = 0; i < 10; increment) {
    ...
}

How can I make this work?

Body:
The increment need to be an direct attribution,
you can't use a String to define this, is impossible

One solution to change dynamically how much will be the increment, it's using a variable

int j=1;

for(int i=0;i<10;i+=j)

the += operator it's used for the increment, for example:

int x = 0;
x += 1; //x is 1
x += 3; //x is 4
x += 2; //x is 6
x++; //x is 7

But in the most cases you don't need to use this in a for loop, what you need to do?

Hugs