问:
CSS Grids and Fraction Unit
I'm trying to understand the basics of CSS grids but have a problem with fraction grid-template: repeat(4, 1fr) / repeat(3, 1fr); unit.

.grid-container {
  display: grid;
  grid-template: repeat(4, 1fr) / repeat(3, 1fr);
  grid-gap: 20px;
  grid-template-areas: 'header header header' 'sidebar content content' 'sidebar content content' 'footer footer footer';
}

.item-1 {
  grid-area: content;
  background: #000;
  color: #ffffff;
  text-align: justify;
  padding: 10px;
}

.item-2 {
  grid-area: sidebar;
  background: #852021;
  color: #ffffff;
  padding: 10px;
}

.item-3 {
  grid-area: header;
  background: yellow;
  text-align: center;
  padding: 10px;
}

.item-4 {
  grid-area: footer;
  background: gray;
  color: #fff;
  text-align: center;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="item-1">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>
  <div class="item-2">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>
  <div class="item-3">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>
  <div class="item-4">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>

</div></code>```

答:
It allows you to define a ratio.  So if you use "1fr 1fr 1fr 1fr" this means 4 columns, each with 1 share of the width, so they will each be 25% of the width.  If however you use "1fr 2fr 1fr" then there will be 3 columns, where the first and last will both be 25% but the middle one will be 50%.

It makes adding another column easier, without having to do the maths to work out what all the percentages should be now.

See this article for more information.

Title: CSS Grids and Fraction Unit

Body:
I'm trying to understand the basics of CSS grids but have a problem with fraction grid-template: repeat(4, 1fr) / repeat(3, 1fr); unit.

.grid-container {
  display: grid;
  grid-template: repeat(4, 1fr) / repeat(3, 1fr);
  grid-gap: 20px;
  grid-template-areas: 'header header header' 'sidebar content content' 'sidebar content content' 'footer footer footer';
}

.item-1 {
  grid-area: content;
  background: #000;
  color: #ffffff;
  text-align: justify;
  padding: 10px;
}

.item-2 {
  grid-area: sidebar;
  background: #852021;
  color: #ffffff;
  padding: 10px;
}

.item-3 {
  grid-area: header;
  background: yellow;
  text-align: center;
  padding: 10px;
}

.item-4 {
  grid-area: footer;
  background: gray;
  color: #fff;
  text-align: center;
  padding: 10px;
}

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.


来源: stackexchange

问:
How to change the value of array element in list of arrays? (C#)
I have list of arrays of labels and I want to change visibility of some label in some array in list by index. Tell me, please, how can I do that?</p>

答:
You can just access the specific label on your array location like you would access other variables in an array:

```<code>Label[] labels = new Label[10];
labels[0] = new Label();
labels[0].Text = "blablabla";
labels[0].Visible = true;
...
labels[9] = new Label();
labels[9].Text = "blablabla";
labels[9].Visible = false;
...
</code>```

Of course the same goes for a List, etc.

ContentLicense: CC BY-SA 3.0

Body:
You can just access the specific label on your array location like you would access other variables in an array:

Label[] labels = new Label[10];
labels[0] = new Label();
labels[0].Text = "blablabla";
labels[0].Visible = true;
...
labels[9] = new Label();
labels[9].Text = "blablabla";
labels[9].Visible = false;
...

Of course the same goes for a List, etc.


问:
DocumentDB + Xamarin - The authorization token is not valid
I'm trying to resolve a critical bug in my app made with Xamarin Forms + DocumentDB. I'm using the package Microsoft.Azure.DocumentDB.Core to store data.
Our Azure account is hosted in Brazil South (GMT-3), and the apps works normally. But we notice that in districts with the locale time GMT-4, the app crash with the exception above.

```<code>The authorization token is not valid at the current time. Please
create another token and retry (token start time: Mon, 27 Mar 2017
00:07:41 GMT, token expiry time: Mon, 27 Mar 2017 00:22:41 GMT,
current server time: Mon, 27 Mar 2017 01:08:24 GMT).
ActivityId: 81487924-68ee-4329-bb61-02f88ea7b6ec
</code>```

If I delayed my device one hour to get GMT-4, and run the app I can see the exception.

```<code>    //---------------------------------------------static Repository initialize
    DocumentClient client;
    const string collectionId = "user";
    Uri uri = UriFactory.CreateDocumentCollectionUri(Constants.DB_ID, collectionId);

    //---------------------------------------------static constructor
    UserDataService()
    {
        client = new DocumentClient(
                new Uri(Constants.DB_ACCOUNT_URL),
                        Constants.DB_ACCOUNT_KEY);
    }

    async public Task<User> GetUserByCPF(string cpf)
    {
        var fedOpt = new FeedOptions { MaxItemCount = -1 };
        var query = client.CreateDocumentQuery<User>(uri, fedOpt)
                          .Where(x => x.Id == _id)
                          .AsDocumentQuery();

        var lst = new List<User>();
        while (query.HasMoreResults)
        {
            lst.AddRange(await query.ExecuteNextAsync<User>());
        }

        return lst.FirstOrDefault();
    }
</code>```

The exceptions rises in query.ExecuteNextAsync;

The error message says to create another token, but I'm using the Master Key. Someone know how create a token to Master Key or increase the expiration date?

答:
Base on my experience,  the date portion of the string is the UTC date to generate token by SDK. And I can't repro the issue with differen zone on my side.The only way I get the exception is that local device system is incorrect.

So I assume that the exception is caused by the device using incorrect time.

Body:
I'm trying to resolve a critical bug in my app made with Xamarin Forms + DocumentDB. I'm using the package Microsoft.Azure.DocumentDB.Core to store data.
Our Azure account is hosted in Brazil South (GMT-3), and the apps works normally. But we notice that in districts with the locale time GMT-4, the app crash with the exception above.

The authorization token is not valid at the current time. Please
create another token and retry (token start time: Mon, 27 Mar 2017
00:07:41 GMT, token expiry time: Mon, 27 Mar 2017 00:22:41 GMT,
current server time: Mon, 27 Mar 2017 01:08:24 GMT).
ActivityId: 81487924-68ee-4329-bb61-02f88ea7b6ec

If I delayed my device one hour to get GMT-4, and run the app I can see the exception.

    //---------------------------------------------static Repository initialize
    DocumentClient client;
    const string collectionId = "user";
    Uri uri = UriFactory.CreateDocumentCollectionUri(Constants.DB_ID, collectionId);

    //---------------------------------------------static constructor
    UserDataService()
    {
        client = new DocumentClient(
                new Uri(Constants.DB_ACCOUNT_URL),
                        Constants.DB_ACCOUNT_KEY);
    }

    async public Task<User> GetUserByCPF(string cpf)
    {
        var fedOpt = new FeedOptions { MaxItemCount = -1 };
        var query = client.CreateDocumentQuery<User>(uri, fedOpt)
                          .Where(x => x.Id == _id)
                          .AsDocumentQuery();

        var lst = new List<User>();
        while (query.HasMoreResults)
        {
            lst.AddRange(await query.ExecuteNextAsync<User>());
        }

        return lst.FirstOrDefault();
    }

The exceptions rises in query.ExecuteNextAsync;

The error message says to create another token, but I'm using the Master Key. Someone know how create a token to Master Key or increase the expiration date?


问:
choose the class to be dynamically loaded in python
An event mapper program receives a stream of events based on the event key attribute. Specific handler classes are required to handle that event.

My requirement is that I want to be able to add new event handlers in the future, without restarting the event mapper program.

I am able to load the specific event handler classes dynamically.

```<code>def loadClass(self,module,file_name,class_name):
    try:
        worker_module = getattr(__import__(module+'.'+file_name),file_name)
        return getattr(worker_module, class_name)
    except Exception as e:
        print e
        return None
</code>```

I need a mapping between the event key attribute and the specific module,file_name and class_name

I'm thinking of maintaining the mapping in a seperate file with this mapping infomation, and read that to map every event, but I'm hoping that there is a better way.

答:
In java we try to get the name of the class with forname and using newInstance makes dynamic instanciation of the Class like this :

```<code>Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });
</code>```

In python try to see this url Does python have an equivalent to Java Class.forName()?

Body:
An event mapper program receives a stream of events based on the event key attribute. Specific handler classes are required to handle that event.

My requirement is that I want to be able to add new event handlers in the future, without restarting the event mapper program.

I am able to load the specific event handler classes dynamically.

def loadClass(self,module,file_name,class_name):
    try:
        worker_module = getattr(__import__(module+'.'+file_name),file_name)
        return getattr(worker_module, class_name)
    except Exception as e:
        print e
        return None

I need a mapping between the event key attribute and the specific module,file_name and class_name

I'm thinking of maintaining the mapping in a seperate file with this mapping infomation, and read that to map every event, but I'm hoping that there is a better way.

Body:
In java we try to get the name of the class with forname and using newInstance makes dynamic instanciation of the Class like this :

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });

In python try to see this url Does python have an equivalent to Java Class.forName()?


问:
How to make div states changing dynamically by JQuery?
I have a div working as a button similar to the Youtube "Subscribe" button. There are 3 classes on CSS working as states and styles: .unactive (is not subscribed), active (subscribed) and .remove (when the mouse is over on subscribed).

Per example, when the button is '.unactive and mouse is over, add the class '.active'. Then when the mouse outs, it backs again to '.unactive'. If I click, its change to '.active' (and change the text inside to 'Subscribed'. And much more...

But when I add the class '.unactive' and remove '.active' dinamically, I can't identify/select the div again to remove the '.active' and back again to '.unactive'.

```<code>    $('.btn-circle.unactive').mouseover(function(){
    $(this).addClass('active').removeClass('unactive');
  });
  $('.btn-circle.active').mouseout(function(){
    $(this).addClass('unactive').removeClass('active');
  });
</code>```

What is the best way to make it?

答:
You can make it as below mentioned.

 jQuery(document).ready(function($){
    $(".subscribe-btn").hover(function(){
     $(this).addClass("active");
     $(this).removeClass("unActive");

    }, function(){
     $(this).removeClass("active");
     $(this).addClass("unActive");
    });

 }); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.subscribe-btn{font:16px arial; color: #000; border-radius:6px; padding:7px 20px; cursor: pointer}
 .subscribe-btn.unActive{background: #ccc; border:2px solid #666; }
 .subscribe-btn.active{background: #333; border:2px solid #666; color: #fff;} </code>```

 <button class="subscribe-btn unActive" type="button">Subscribe</button>```

Body:
I have a div working as a button similar to the Youtube "Subscribe" button. There are 3 classes on CSS working as states and styles: .unactive (is not subscribed), active (subscribed) and .remove (when the mouse is over on subscribed).

Per example, when the button is '.unactive and mouse is over, add the class '.active'. Then when the mouse outs, it backs again to '.unactive'. If I click, its change to '.active' (and change the text inside to 'Subscribed'. And much more...

But when I add the class '.unactive' and remove '.active' dinamically, I can't identify/select the div again to remove the '.active' and back again to '.unactive'.

    $('.btn-circle.unactive').mouseover(function(){
    $(this).addClass('active').removeClass('unactive');
  });
  $('.btn-circle.active').mouseout(function(){
    $(this).addClass('unactive').removeClass('active');
  });

What is the best way to make it?

Body:
You can make it as below mentioned.

 jQuery(document).ready(function($){
    $(".subscribe-btn").hover(function(){
     $(this).addClass("active");
     $(this).removeClass("unActive");

    }, function(){
     $(this).removeClass("active");
     $(this).addClass("unActive");
    });

 });

.subscribe-btn{font:16px arial; color: #000; border-radius:6px; padding:7px 20px; cursor: pointer}
 .subscribe-btn.unActive{background: #ccc; border:2px solid #666; }
 .subscribe-btn.active{background: #333; border:2px solid #666; color: #fff;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <button class="subscribe-btn unActive" type="button">Subscribe</button>


问:
How do I talk to ADFS 3.0 from javascript or ionic?
I have an adfs 3.0 server configured to accept oAuth2.
It was easy with c# to talk to the server using  WIF.

However, I'm not sure how should go about using Javascript?(html5/css/Javascript) or (ionic to be precise)

I googled, did not find any good reference.
I'm using javascript to talk to my protected api which would accept the Oauth2 token from ADFS.

Any help is much appreciated.

答: Microsoft provides the ADAL library to request security tokens.  This library has been written in many different languages.  For Javascript you can use https://github.com/AzureAD/azure-activedirectory-library-for-js .  I haven't tried it myself but in essence this library encapsulates the these processes for you.  Here is a reply from Bertocci himself : https://github.com/AzureAD/azure-activedirectory-library-for-js/issues/222 on usage with ADFS.</p>


问:
python get docstring from terminal using option
Let us say I have a file

myfile.py

```<code>"""
long documentation of myfile.py
...
"""

# tons of stuf
# this include some functions and their documentation
</code>```

and I would like to do

```<code>bash $ python myfile.py -h
</code>```

such that it displays all the documentation but does not execute the tons of stuff. (I don't care if the option is --help instead of -h.)

I am pretty sure I have already seen it somewhere but I can't find it. Is it related to this question and to this second question?

答:
```<code>argparse
</code>```

Using argparse, You can display the __doc__ string by passing it to the description parameter of Argparse

```<code>#!/usr/bin/env python
"""
long documentation of myfile.py
...
"""

# tons of stuf
# this include some functions and their documentation
if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    # Add your arguments here
    parser.add_argument("-f", "--file", dest="myFilenameVariable",
                        required=True,
                        help="write report to FILE", metavar="FILE")
    args = parser.parse_args()
    print(args.myFilenameVariable)
</code>```

Run the python file

```<code>$ python myfile.py --help
</code>```

Body:
Let us say I have a file

myfile.py

"""
long documentation of myfile.py
...
"""

# tons of stuf
# this include some functions and their documentation

and I would like to do

bash $ python myfile.py -h

such that it displays all the documentation but does not execute the tons of stuff. (I don't care if the option is --help instead of -h.)

I am pretty sure I have already seen it somewhere but I can't find it. Is it related to this question and to this second question?

Body:
argparse

Using argparse, You can display the __doc__ string by passing it to the description parameter of Argparse

#!/usr/bin/env python
"""
long documentation of myfile.py
...
"""

# tons of stuf
# this include some functions and their documentation
if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    # Add your arguments here
    parser.add_argument("-f", "--file", dest="myFilenameVariable",
                        required=True,
                        help="write report to FILE", metavar="FILE")
    args = parser.parse_args()
    print(args.myFilenameVariable)

Run the python file

$ python myfile.py --help


问:
Call function after function return
i have the folowing situation:
I have a function "foo" and want the the foo-return the function bar sould be call. Here a little example what i mean:

```<code>function foo() {
     echo "FOO";
     return "1";
}
function bar() {
    echo "BAR";
}
echo foo();
</code>```

And the output should be display this

FOO

  1

  BAR

All this in PHP!!!
Have anyone a idea how to can realise this WITHOUT call bar() in after each foo()?

答:
Or if you have got two functions then, just add foo() like the following:

```<code>function bar(){
foo();
echo "BAR";
}
</code>```

And remove the return statement from foo() function. or write return 0;

Updated:

You can keep the return function in foo().

Title: Call function after function return

Body:
i have the folowing situation:
I have a function "foo" and want the the foo-return the function bar sould be call. Here a little example what i mean:

function foo() {
     echo "FOO";
     return "1";
}
function bar() {
    echo "BAR";
}
echo foo();

And the output should be display this

FOO

  1

  BAR

All this in PHP!!!
Have anyone a idea how to can realise this WITHOUT call bar() in after each foo()?

Body:
Or if you have got two functions then, just add foo() like the following:

function bar(){
foo();
echo "BAR";
}

And remove the return statement from foo() function. or write return 0;

Updated:

You can keep the return function in foo().


问:
ListBox duplicate check
I did post another question yesterday but I haven't had any further responses because there were two answers posted. Unfortunately none of them will work for me. Apologies if this is against the rules to repost a similar question.

I am trying to check a ListBox for duplicates when pressing a button. It should be adding the value of what's a ComboBox to the ListBox.

All the answers suggested using Linq queries, like this

```<code>myListBox.Items.Any(item=>((EnquiryListItem)item).Text == ComboBox1.SelectedText.ToString())
</code>```

or this

```<code>if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){
</code>```

However, my control doesn't have an entry for Any or Cast.

I tried using a foreach loop like the one below, but I get an error, object does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'object' could be found.

```<code>            foreach (var item in ListBox1.Items)
            {
               if (item.Text.Contains(Combobox1.SelectedText.ToString()))
               {
                   //select item in the ListBox
                   debugMsg("Duplicate","");
                   break;
               } else {
                ListBox1.Items.Add(Combobox1.SelectedItem); }
            }
</code>```

Is there any other method I can use? I've searched both SO and the internet in general but come across the same suggestions each time - almost always using Linq, which apparently won't work for my vendor specific SDK windows form application. They have documented their ListBox control and suggest that it inherits the .NET control but only supply code to add/remove items, with no duplicate checking.

答:
Make sure you are using System.Linq because Cast should work.

I accomplished your desired result by using this code:

```<code>if ( listBox1.Items.Cast<string>().Contains( comboBox1.SelectedItem.ToString() ) )
{
    MessageBox.Show( "duplicate" );
}
else
{
    listBox1.Items.Add( comboBox1.SelectedItem );
}
</code>```

Custom controls (OP's situation):

If the foreach solution works for your custom control and .Text isn't a valid extension method just use:

```<code>item.ToString().Contains(Combobox1.SelectedItem.ToString())
</code>```

Title: ListBox duplicate check

Body:
I did post another question yesterday but I haven't had any further responses because there were two answers posted. Unfortunately none of them will work for me. Apologies if this is against the rules to repost a similar question.

I am trying to check a ListBox for duplicates when pressing a button. It should be adding the value of what's a ComboBox to the ListBox.

All the answers suggested using Linq queries, like this

myListBox.Items.Any(item=>((EnquiryListItem)item).Text == ComboBox1.SelectedText.ToString())

or this

if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){

However, my control doesn't have an entry for Any or Cast.

I tried using a foreach loop like the one below, but I get an error, object does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'object' could be found.

            foreach (var item in ListBox1.Items)
            {
               if (item.Text.Contains(Combobox1.SelectedText.ToString()))
               {
                   //select item in the ListBox
                   debugMsg("Duplicate","");
                   break;
               } else {
                ListBox1.Items.Add(Combobox1.SelectedItem); }
            }

Is there any other method I can use? I've searched both SO and the internet in general but come across the same suggestions each time - almost always using Linq, which apparently won't work for my vendor specific SDK windows form application. They have documented their ListBox control and suggest that it inherits the .NET control but only supply code to add/remove items, with no duplicate checking.

Body:
Make sure you are using System.Linq because Cast should work.

I accomplished your desired result by using this code:

if ( listBox1.Items.Cast<string>().Contains( comboBox1.SelectedItem.ToString() ) )
{
    MessageBox.Show( "duplicate" );
}
else
{
    listBox1.Items.Add( comboBox1.SelectedItem );
}

Custom controls (OP's situation):

If the foreach solution works for your custom control and .Text isn't a valid extension method just use:

item.ToString().Contains(Combobox1.SelectedItem.ToString())


问:
Is it possible to have a dynamic choice field with ng-admin?
When creating or editing an entity, is it possible to have a second choices field where the options are dependent on the first choices field?

For example, I have categories and subcategories. The choices/options for the subcategory field are dependent on the currently selected choice/option in the category field.

In the docs, there is an example with categories and subcategories but when I attempt to do it the way shown, the subcategories only get updated on the page load and do not change when a different category is specified. You can find the example through the link below.
https://github.com/marmelab/ng-admin/blob/master/doc/reference/Field.md#-reference-field-type

答:
The only way to have a dynamic choice field si to write a new custom directive and use it as a template as your field.</p>

```<code>nga.field('my_field')
    .template('<my-custom-field field="::field" values="::entry.values"></my-custom-field>'),
</code>```

Body:
The only way to have a dynamic choice field si to write a new custom directive and use it as a template as your field.

nga.field('my_field')
    .template('<my-custom-field field="::field" values="::entry.values"></my-custom-field>'),


问:
Comparing two strings in which one starts with a zero
I wanted to check two strings with each other, one which starts with a zero and one without. But this seems to result in a true. An example:

```<code>if("098" == "98"){
   return true;
}
</code>```

Can somebody explain why this statement results to true with PHP?

答:
The simple reason i can think of is that The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.

So from your example,

```<code>if("098" == "98"){
   //true
}
</code>```

Also a couple of PHP functions also have parameters to imply strict checking. An example is in_array

Body:
I wanted to check two strings with each other, one which starts with a zero and one without. But this seems to result in a true. An example:

if("098" == "98"){
   return true;
}

Can somebody explain why this statement results to true with PHP?

Body:
The simple reason i can think of is that The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.

So from your example,

if("098" == "98"){
   //true
}

Also a couple of PHP functions also have parameters to imply strict checking. An example is in_array


问:
HTML table doesn’t refresh after Jquery ajax request
I want to cancel all user changes in the html form ( id=”edit_cat_frm”) (edit cells in tables, delete rows in table( id ‘cat_list’) and  changes order with  drag’n’drop) with reset button (id=”reset_edit_cat”), so I decide to do this with AJAX.

Jquery ajax request is OK, but my main HTML table with id ‘cat_list’ doesn’t refresh after it.

I can watch only old data in the table that were before AJAX request with all user changes.

What is wrong?

My jQuery code  from edit_category.js.

```<code>$("#reset_edit_cat").click(function(){

    $('#name_cat').hide();
    $('#desc_cat').hide();
    $('#access2').hide();

    $('<div id="loading"><div></div></div>').appendTo('body');
    $.ajax({
            type     : "POST",
            cache    : false,
            url      : "ajax_request.php",
            data     : { action: 'sel_all_cat'},
            dataType : "json",
            success: function(jsonObject) {

                if (jsonObject.dat0 != "" && jsonObject.dat1 != "" && jsonObject.dat2 != "")
                {
                    var dat0 = '<table id="cat_list" class="table-bordered table-striped table-condensed"><thead><tr><th>Назва</th><th>Порядок показу</th>'+
                    '<th>Спорідненість</th><th>Порядок в табл.</th><th></th></tr></thead><tbody>'+jsonObject.dat0+'</tbody></table>';
                    var dat1 = '<table id="access5"><thead><tr><th>Перегляд категорії</th><th>Перегляд зображень</th><th>Додавання зображень</th><th>Голосування</th>'
                    +'<th>Відправлення листівок</th><th>Читання коментар.</th><th>Додавання коментар.</th></tr></thead><tbody>'+jsonObject.dat1+'</tbody></table>';
                    var dat2 = '<table id="desc5">'+jsonObject.dat2+'</table>';

                    $('#acs').html(dat1).hide();
                    $('#dsc').html(dat2).hide();
                    $('#cat_list').hide("drop", { }, 1000);
                    $('#inner').html(dat0);
                    $('#loading').remove();
                    $('#cat_list').show("clip", { }, 1000);
                }
            }

    });

});
</code>```

Here is code from ajax_request.php

```<code>public function select_all_cat($par)
{
    $sql = "SELECT @i:=@i+1 as RowNumber, cat_id,  cat_name,  left(cat_description,256) as cat_desc, cat_parent_id,  cat_order,  auth_viewcat,  auth_viewimage, auth_upload, auth_vote,  auth_sendpostcard,  auth_readcomment,  auth_postcomment FROM myfotogallery_categories, (SELECT @i:=0) as RowNumberTable ORDER BY cat_order";

    $row = $this->process($sql,true);
    if (array_key_exists('1', $row))
    {
        $i=1;
        $subcat_info = $this->list_cat_for_subcat($row);
        foreach ($row as $value) {
            $rezult['dat0'] .= "<tr class='draggable' data-row='".$value['cat_id']."'>".PHP_EOL;
            $rezult['dat0'] .= "<td class='col1'><span data-type='text' data-elemName='cat_name'>".$value['cat_name']."</span>".PHP_EOL;
            $rezult['dat0'] .= "<input class='person-id' name='person-$i-id' value='person-$i' type='hidden' />".PHP_EOL;
            $rezult['dat0'] .= "<input class='row-depth' name='person-$i-depth' value='";
            $rezult['dat0'] .= ($value['cat_parent_id'] == 0) ? '1': '2';
            $rezult['dat0'] .= "' type='hidden' />".PHP_EOL;
            $rezult['dat0'] .= "</td>".PHP_EOL;
            $rezult['dat0'] .= "<td>".PHP_EOL;
            $rezult['dat0'] .= "<select class='row-weight' name='person-$i-weight'>".PHP_EOL;

            $arr = $this->category_opt($row,$i,$subcat_info);
            $rezult['dat0'] .= $arr[0];
            $rezult['dat0'] .= "</select>".PHP_EOL;
            $rezult['dat0'] .= "</td>".PHP_EOL;
            $rezult['dat0'] .= "<td>".PHP_EOL;
            $rezult['dat0'] .= "<select class='row-parent' name='person-$i-parent'>".PHP_EOL;
            $rezult['dat0'] .= $arr[1];
            $rezult['dat0'] .= "</select>".PHP_EOL;
            $rezult['dat0'] .= "</td>".PHP_EOL;

            $rezult['dat0'] .= "<td class='col3'>".($value['cat_order']/10)."</td>".PHP_EOL;
            $rezult['dat0'] .= "<td class='col4'><a href='#' class='row-delete' title='Видалити цей рядок'><span class='glyphicon glyphicon-remove'></span></a></td>".PHP_EOL;
            $rezult['dat0'] .= "</tr>".PHP_EOL;

            $rezult['dat1'].= "<tr data-row='".$value['cat_id']."'>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='viewcat'>";
            $rezult['dat1'] .= $value['auth_viewcat']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='viewimage'>";
            $rezult['dat1'] .= $value['auth_viewimage']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='upload'>";
            $rezult['dat1'] .= $value['auth_upload']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='vote'>";
            $rezult['dat1'] .= $value['auth_vote']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='sendpostcard'>";
            $rezult['dat1'] .= $value['auth_sendpostcard']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='readcomment'>";
            $rezult['dat1'] .= $value['auth_readcomment']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='postcomment'>";
            $rezult['dat1'] .= $value['auth_postcomment']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "</span></td>".PHP_EOL;
            $rezult['dat1'] .= "</tr>".PHP_EOL;

            $rezult['dat2'] .= "<tr data-row='".$value['cat_id']."'><td>".$value['cat_desc']."</td></tr>".PHP_EOL;
            $i++;
        }
    }
    else {
        $rezult['dat0'] .= "<tr>".PHP_EOL;
        $rezult['dat0'] .= "<td class='col1'><span data-type='text' data-elemName='cat_name'>".$row['cat_name']."</span></td>".PHP_EOL;
        $rezult['dat0'] .= "<td class='col3'>".($row['cat_order']/10)."</td>".PHP_EOL;
        $rezult['dat0'] .= "<td class='col4'><a href='#' class='row-delete'><span class='glyphicon glyphicon-remove'></span></a></td>".PHP_EOL;
        $rezult['dat0'] .= "</tr>".PHP_EOL;
        $rezult['dat1'].= "<tr data-row='".$row['cat_id']."'>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='viewcat'>";
        $rezult['dat1'] .= $row['auth_viewcat']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='viewimage'>";
        $rezult['dat1'] .= $row['auth_viewimage']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='upload'>";
        $rezult['dat1'] .= $row['auth_upload']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='vote'>";
        $rezult['dat1'] .= $row['auth_vote']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='sendpostcard'>";
        $rezult['dat1'] .= $row['auth_sendpostcard']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='readcomment'>";
        $rezult['dat1'] .= $row['auth_readcomment']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "<td><span data-type='boolean' data-elemName='postcomment'>";
        $rezult['dat1'] .= $row['auth_postcomment']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "</span></td>".PHP_EOL;
        $rezult['dat1'] .= "</tr>".PHP_EOL;
        $rezult['dat2'] .= "<tr data-row='".$row['cat_id']."'><td>".$row['cat_desc']."</td></tr>".PHP_EOL;}
    if($par == "2")
    { return $rezult;}
    else { echo json_encode($rezult); }
}
</code>```

This is my html code from browser.

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD/XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml11-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ua" lang="ua">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8;charset=utf-8" />
    <meta name="viewport" content="initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Сайт - Фотогалерея - Мій фотоальбом - Редагувати, видалити, змінити порядок категорії/підкатегорії</title>
    <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <link rel="stylesheet" href="css/style.min1.css" media="screen">
    <!--[if lte IE 7]><link rel="stylesheet" href="css/style.ie7.css" media="screen" /><![endif]-->
    <link rel="stylesheet" href="css/style.responsive.css" media="all">
    <!-- Add jQuery main library  -->
    <script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
    <!-- Add jQuery UI library  -->
    <script type="text/javascript" src="scripts/jquery-ui-1.10.2.custom.min.js"></script>
    <link rel="stylesheet" type="text/css" href="scripts/ui-lightness/jquery-ui-1.10.2.custom.min.css" />
    <link href="css/bootstrap/css/bootstrap_my.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/dialog-error.css" />
    <script type="text/javascript" src="scripts/logout.js"></script>
<script type="text/javascript" src="scripts/profile-other.js"></script>
<script type="text/javascript" src="scripts/reindex_category.js"></script>
<link rel="stylesheet" type="text/css" media="screen,projection" href="css/ajax_loading.css"/>
    <style>
    .button.ui-button {font-family: verdana, arial, helvetica, sans-serif; font-size: 11px; margin-top: 4px;}
    </style><link rel="stylesheet" type="text/css" media="screen,projection" href="css/edit_category.css"/>
<link rel="stylesheet" type="text/css" media="screen,projection" href="css/assets/jquery.tabledrag.css"/>
<script src="scripts/edit_category.js" type="text/javascript"></script>
    <script type="text/javascript" src="scripts/jquery.tabledrag.js"></script>
    <script src="scripts/jquery.cookie.js"></script>
    <script src="scripts/jQuery.makeEditable.js"></script>

</head><body>
    <div id="art-main">
        <header class="art-header clearfix">
        <div class="art-shapes"></div>
        </header>
        <nav class="art-nav clearfix desktop-nav">
        <table class="main_menu">
        <tr>
        <td width='80%'>
        <ul class="art-hmenu"><li><a href="fotoalbum-new.php" >Головна</a></li><li><a href="#" >Фотогалерея</a><ul><li><a id="y2012" href="#" target="_self" title="Фото 2012 року">2012 рік</a><ul><li><a id="y2012-slavsko" href="#" target="_self" title="Поїздка в Славсько взимку. Лижі">Славсько-січень</a><ul><li><a id="y2012-1901" href="foto.php?date=2012-01-19" target="_self" title="">19.01.2012</a></li><li><a id="y2012-2101" href="foto.php?date=2012-01-21" target="_self" title="">21.01.2012</a></li><li><a id="y2012-2301" href="foto.php?date=2012-01-23" target="_self" title="">23.01.2012</a></li><li><a id="y2012-2401" href="foto.php?date=2012-01-24" target="_self" title="">24.01.2012</a></li></ul></li></ul></li><li><a id="y2013" href="#" target="_self" title="Фото 2013 року">2013 рік</a></li><li><a href="upload%20image.php"  title="Завантажити нове зображення на сайт">Додати фото</a></li><li><a href="uploaded_recently.php"  title="Нещодавно завантажені Вами зображення">Нещодавно Ви завантажили</a></li><li><a id="lastdnld"  href="lastdnld.php" target="_self" title="">Останні 10 завантажених зображень</a></li><li><a id="lastcomm"  href="top10_comment.php" target="_self" title="">Останні 10 коментарів</a></li><li><a id="top10" href="#" target="_self" title="Топ 10">Топ 10</a><ul><li><a  href="top10.php?param=rating" target="_self" title="">за рейтингом</a></li><li><a  href="top10.php?param=votes" target="_self" title="">за голосами</a></li><li><a  href="top10.php?param=hits" target="_self" title="">за переглядами</a></li></ul></li></ul></li><li><a href="#" >Меню адміністратора</a><ul><li><a href="approve_uploaded_images.php"  title="Перевірити завантажені користувачами зображення">Перевірка завантажених зображень</a></li><li><a href="check_comment.php"  title="Перевірити додані користувачами коментарі">Перевірка коментарів</a></li><li><a href="#"  title="">Категорія/підкатегорія</a><ul><li><a href="add_category.php"  title="Створити нову категорію/підкатегорію">Створити</a></li><li><a href="edit_category.php" class="active" title="Редагувати, видалити, змінити порядок категорії/підкатегорії">Редагувати</a></li><li><a id="reind" href="#" title="Переіндексувати порядок показу категорії/підкатегорії">Переіндексація</a></li></ul></li></ul></li><li><a href="#" >Меню користувача</a><ul><li><a id="profile_option" href="#"  title="">Профіль</a><ul><li><a href="profile-new.php?id=1" target="_self" title="редагування власного профілю">редагувати мій власний</a></li><li><a id="profile_other"  title="переглянути профіль користувача">іншого користувача</a></li></ul></li></ul></li><li><a  href="#">Контакти</a></li><li><a  id="id_logout" href="#">Вихід з сайту</a></li></ul>        </td>
        <td class="main_menu menu_2">
        Привіт <b>vga</b>! Радий Вас бачити.        </td>
        </tr>
        </table>
        </nav>
        <!-- внутр зміст початок-->
        <div class="art-sheet clearfix">
            <div class="art-layout-wrapper clearfix">
                <div class="art-content-layout">
                    <div class="art-content-layout-row">
                            <table width=100% border=0 cellpadding=0 cellspacing=0>
    <tr>
    <td width=25% height=400 align=left valign=top>
    </td>
    <td id="middle" align=center>
    <form id="edit_cat_frm" method="POST" action="">
    <p class="head1">Редагувати категорії / підкатегорії</p>
    <div class="scroll_img"><div class="inner">
    <table id="cat_list" class="table-bordered table-striped table-condensed">
    <thead>
    <tr>
    <th>Назва</th>
    <th>Порядок показу</th>
    <th>Спорідненість</th>
    <th>Порядок в табл.</th>
    <th></th>
    </tr>
    </thead>
    <tbody>
    <tr class='draggable' data-row='59'>
<td class='col1'><span data-type='text' data-elemName='cat_name'>Нова категорія</span>
<input class='person-id' name='person-1-id' value='person-1' type='hidden' />
<input class='row-depth' name='person-1-depth' value='1' type='hidden' />
</td>
<td>
<select class='row-weight' name='person-1-weight'>
<option selected value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>
</td>
<td>
<select class='row-parent' name='person-1-parent'>
<option selected value='0'>Відсутній</option>
<option value='person-2'>Літаки</option>
<option value='person-3'>Гори</option>
<option value='person-4'>Міста України</option>
<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>
</td>
<td class='col3'>1</td>
<td class='col4'><a href='#' class='row-delete' title='Видалити цей рядок'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<tr class='draggable' data-row='31'>
<td class='col1'><span data-type='text' data-elemName='cat_name'>Літаки</span>
<input class='person-id' name='person-2-id' value='person-2' type='hidden' />
<input class='row-depth' name='person-2-depth' value='1' type='hidden' />
</td>
<td>
<select class='row-weight' name='person-2-weight'>
<option value='1'>1</option>
<option selected value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>
</td>
<td>
<select class='row-parent' name='person-2-parent'>
<option selected value='0'>Відсутній</option><option value='person-1'>Нова категорія</option>

<option value='person-3'>Гори</option>
<option value='person-4'>Міста України</option>
<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>
</td>
<td class='col3'>2</td>
<td class='col4'><a href='#' class='row-delete' title='Видалити цей рядок'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<tr class='draggable' data-row='23'>
<td class='col1'><span data-type='text' data-elemName='cat_name'>Гори</span>
<input class='person-id' name='person-3-id' value='person-3' type='hidden' />
<input class='row-depth' name='person-3-depth' value='1' type='hidden' />
</td>
<td>
<select class='row-weight' name='person-3-weight'>
<option value='1'>1</option>
<option value='2'>2</option>
<option selected value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>
</td>
<td>
<select class='row-parent' name='person-3-parent'>
<option selected value='0'>Відсутній</option><option value='person-1'>Нова категорія</option>
<option value='person-2'>Літаки</option>

<option value='person-4'>Міста України</option>
<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>
</td>
<td class='col3'>3</td>
<td class='col4'><a href='#' class='row-delete' title='Видалити цей рядок'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<tr class='draggable' data-row='25'>
<td class='col1'><span data-type='text' data-elemName='cat_name'>Міста України</span>
<input class='person-id' name='person-4-id' value='person-4' type='hidden' />
<input class='row-depth' name='person-4-depth' value='1' type='hidden' />
</td>
<td>
<select class='row-weight' name='person-4-weight'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option selected value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>
</td>
<td>
<select class='row-parent' name='person-4-parent'>
<option selected value='0'>Відсутній</option><option value='person-1'>Нова категорія</option>
<option value='person-2'>Літаки</option>
<option value='person-3'>Гори</option>

<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>
</td>
<td class='col3'>4</td>
<td class='col4'><a href='#' class='row-delete' title='Видалити цей рядок'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>

    </tbody>
    </table>
    </div></div>
    <br>
    <div id="acs">
    <table id="access">
    <thead>
    <tr>
    <th>Перегляд категорії</th>
    <th>Перегляд зображень</th>
    <th>Додавання зображень</th>
    <th>Голосування</th>
    <th>Відправлення листівок</th>
    <th>Читання коментар.</th>
    <th>Додавання коментар.</th>
    </tr>
    </thead>
    <tbody>
    <tr data-row='59'>
<td><span data-type='boolean' data-elemName='viewcat'>Ні</span></td>
<td><span data-type='boolean' data-elemName='viewimage'>Ні</span></td>
<td><span data-type='boolean' data-elemName='upload'>Ні</span></td>
<td><span data-type='boolean' data-elemName='vote'>Ні</span></td>
<td><span data-type='boolean' data-elemName='sendpostcard'>Ні</span></td>
<td><span data-type='boolean' data-elemName='readcomment'>Ні</span></td>
<td><span data-type='boolean' data-elemName='postcomment'>Ні</span></td>
</tr>
<tr data-row='31'>
<td><span data-type='boolean' data-elemName='viewcat'>Ні</span></td>
<td><span data-type='boolean' data-elemName='viewimage'>Ні</span></td>
<td><span data-type='boolean' data-elemName='upload'>Ні</span></td>
<td><span data-type='boolean' data-elemName='vote'>Ні</span></td>
<td><span data-type='boolean' data-elemName='sendpostcard'>Ні</span></td>
<td><span data-type='boolean' data-elemName='readcomment'>Ні</span></td>
<td><span data-type='boolean' data-elemName='postcomment'>Ні</span></td>
</tr>
<tr data-row='23'>
<td><span data-type='boolean' data-elemName='viewcat'>Так</span></td>
<td><span data-type='boolean' data-elemName='viewimage'>Так</span></td>
<td><span data-type='boolean' data-elemName='upload'>Так</span></td>
<td><span data-type='boolean' data-elemName='vote'>Ні</span></td>
<td><span data-type='boolean' data-elemName='sendpostcard'>Ні</span></td>
<td><span data-type='boolean' data-elemName='readcomment'>Ні</span></td>
<td><span data-type='boolean' data-elemName='postcomment'>Ні</span></td>
</tr>
<tr data-row='25'>
<td><span data-type='boolean' data-elemName='viewcat'>Так</span></td>
<td><span data-type='boolean' data-elemName='viewimage'>Так</span></td>
<td><span data-type='boolean' data-elemName='upload'>Так</span></td>
<td><span data-type='boolean' data-elemName='vote'>Так</span></td>
<td><span data-type='boolean' data-elemName='sendpostcard'>Так</span></td>
<td><span data-type='boolean' data-elemName='readcomment'>Так</span></td>
<td><span data-type='boolean' data-elemName='postcomment'>Так</span></td>
</tr>

    </tbody>
    </table></div>
    <div id="dsc">
    <table id="desc">
    <tr data-row='59'><td>опис нової категорії</td></tr>
<tr data-row='31'><td>фото літаків</td></tr>
<tr data-row='23'><td>  фото гір</td></tr>
<tr data-row='25'><td></td></tr>

    </table></div>
    <table id="name_cat"></table>
    <table id="desc_cat">
    <thead><tr><th>Опис категорії</th></tr></thead><tbody></tbody>
    </table>
    <table id="access2">
    </table>
    <input type="hidden" name="action" value="edit_cat"/>
    <div id="dat_name"></div>
    <table id="butn" align="center">
    <tr>
    <td class="btn2">
    <input type="submit" class="button" name="create" value="Записати"/>
    </td>
    <td class="btn2">
    <input id="reset_edit_cat" type="reset" class="button" name="Cancel" value="Відмінити"/>
    </td>
    </tr>
    </table>
    </form>
    <!--// 3 колонка-->
    <td width=25% height=400 valign=center></td>
    </tr>
    </table>
    <!-- нижня таблиця -->
    <table align="center" class="tab_below">
    <tr>
    <td style="padding-top:30px;">
    <p align="center">
    <a class="button" title="На головну сторінку" href="fotoalbum-new.php"><img src="fotogallery/images/house.png"></a>
    </p>
    </td>
    </tr>
    </table>                    </div>
                </div>
            </div>
        </div>
        <!-- внутр зміст кінець -->
        <footer class="art-footer clearfix">
              <div class="art-footer-inner">
                    <p>Авторське право © 2013, Гладких Владислав. Всі права захищені.</p>
                    <p class="art-page-footer">
                        <span id="art-footnote-links">Веб-шаблон створений з допомогою Artisteer.</span>
                    </p>
              </div>
        </footer>
    </div>
</body>
</html>
</code>```

答:
You do not have an element with the id #inner, as indicated in edit_category.js, via the following line:

```<code>$('#inner').html(dat0);
</code>```

You instead have an element with a class of inner, therefore just need to amend line above to the following:

```<code>$('.inner').html(dat0);
</code>```

Body:
I want to cancel all user changes in the html form ( id=”edit_cat_frm”) (edit cells in tables, delete rows in table( id ‘cat_list’) and  changes order with  drag’n’drop) with reset button (id=”reset_edit_cat”), so I decide to do this with AJAX.

Jquery ajax request is OK, but my main HTML table with id ‘cat_list’ doesn’t refresh after it.

I can watch only old data in the table that were before AJAX request with all user changes.

What is wrong?

My jQuery code  from edit_category.js.

$("#reset_edit_cat").click(function(){

    $('#name_cat').hide();
    $('#desc_cat').hide();
    $('#access2').hide();

    $('

').appendTo('body');
    $.ajax({
            type     : "POST",
            cache    : false,
            url      : "ajax_request.php",
            data     : { action: 'sel_all_cat'},
            dataType : "json",
            success: function(jsonObject) {

                if (jsonObject.dat0 != "" && jsonObject.dat1 != "" && jsonObject.dat2 != "")
                {
                    var dat0 = '

Назва	Порядок показу	'+
                    'Спорідненість	Порядок в табл.

'+jsonObject.dat0+'

';
                    var dat1 = '

Перегляд категорії	Перегляд зображень	Додавання зображень	Голосування	'
                    +'Відправлення листівок	Читання коментар.	Додавання коментар.

'+jsonObject.dat1+'

';
                    var dat2 = '
'+jsonObject.dat2+'
';

                    $('#acs').html(dat1).hide();
                    $('#dsc').html(dat2).hide();
                    $('#cat_list').hide("drop", { }, 1000);
                    $('#inner').html(dat0);
                    $('#loading').remove();
                    $('#cat_list').show("clip", { }, 1000);
                }
            }

    });

});

Here is code from ajax_request.php

public function select_all_cat($par)
{
    $sql = "SELECT @i:=@i+1 as RowNumber, cat_id,  cat_name,  left(cat_description,256) as cat_desc, cat_parent_id,  cat_order,  auth_viewcat,  auth_viewimage, auth_upload, auth_vote,  auth_sendpostcard,  auth_readcomment,  auth_postcomment FROM myfotogallery_categories, (SELECT @i:=0) as RowNumberTable ORDER BY cat_order";

    $row = $this->process($sql,true);
    if (array_key_exists('1', $row))
    {
        $i=1;
        $subcat_info = $this->list_cat_for_subcat($row);
        foreach ($row as $value) {
            $rezult['dat0'] .= "
".PHP_EOL;
            $rezult['dat0'] .= "".$value['cat_name']."".PHP_EOL;
            $rezult['dat0'] .= "<input class='person-id' name='person-$i-id' value='person-$i' type='hidden' />".PHP_EOL;
            $rezult['dat0'] .= "<input class='row-depth' name='person-$i-depth' value='";
            $rezult['dat0'] .= ($value['cat_parent_id'] == 0) ? '1': '2';
            $rezult['dat0'] .= "' type='hidden' />".PHP_EOL;
            $rezult['dat0'] .= "	".PHP_EOL;
            $rezult['dat0'] .= "".PHP_EOL;
            $rezult['dat0'] .= "<select class='row-weight' name='person-$i-weight'>".PHP_EOL;

            $arr = $this->category_opt($row,$i,$subcat_info);
            $rezult['dat0'] .= $arr[0];
            $rezult['dat0'] .= "</select>".PHP_EOL;
            $rezult['dat0'] .= "	".PHP_EOL;
            $rezult['dat0'] .= "".PHP_EOL;
            $rezult['dat0'] .= "<select class='row-parent' name='person-$i-parent'>".PHP_EOL;
            $rezult['dat0'] .= $arr[1];
            $rezult['dat0'] .= "</select>".PHP_EOL;
            $rezult['dat0'] .= "	".PHP_EOL;

            $rezult['dat0'] .= "".($value['cat_order']/10)."	".PHP_EOL;
            $rezult['dat0'] .= "	".PHP_EOL;
            $rezult['dat0'] .= "
".PHP_EOL;

            $rezult['dat1'].= "
".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_viewcat']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_viewimage']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_upload']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_vote']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_sendpostcard']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_readcomment']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "";
            $rezult['dat1'] .= $value['auth_postcomment']==1 ? "Так" : "Ні";
            $rezult['dat1'] .= "	".PHP_EOL;
            $rezult['dat1'] .= "
".PHP_EOL;

            $rezult['dat2'] .= "
".$value['cat_desc']."
".PHP_EOL;
            $i++;
        }
    }
    else {
        $rezult['dat0'] .= "
".PHP_EOL;
        $rezult['dat0'] .= "".$row['cat_name']."	".PHP_EOL;
        $rezult['dat0'] .= "".($row['cat_order']/10)."	".PHP_EOL;
        $rezult['dat0'] .= "	".PHP_EOL;
        $rezult['dat0'] .= "
".PHP_EOL;
        $rezult['dat1'].= "
".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_viewcat']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_viewimage']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_upload']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_vote']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_sendpostcard']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_readcomment']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "";
        $rezult['dat1'] .= $row['auth_postcomment']==1 ? "Так" : "Ні";
        $rezult['dat1'] .= "	".PHP_EOL;
        $rezult['dat1'] .= "
".PHP_EOL;
        $rezult['dat2'] .= "
".$row['cat_desc']."
".PHP_EOL;}
    if($par == "2")
    { return $rezult;}
    else { echo json_encode($rezult); }
}

This is my html code from browser.

    <!DOCTYPE html PUBLIC "-//W3C//DTD/XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml11-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8;charset=utf-8" />
    <meta name="viewport" content="initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Сайт - Фотогалерея - Мій фотоальбом - Редагувати, видалити, змінити порядок категорії/підкатегорії</title>

    <link rel="stylesheet" href="css/style.min1.css" media="screen">

    <link rel="stylesheet" href="css/style.responsive.css" media="all">

    <link rel="stylesheet" type="text/css" href="scripts/ui-lightness/jquery-ui-1.10.2.custom.min.css" />
    <link href="css/bootstrap/css/bootstrap_my.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/dialog-error.css" />

<link rel="stylesheet" type="text/css" media="screen,projection" href="css/ajax_loading.css"/>
    <link rel="stylesheet" type="text/css" media="screen,projection" href="css/edit_category.css"/>
<link rel="stylesheet" type="text/css" media="screen,projection" href="css/assets/jquery.tabledrag.css"/>

Головна

Фотогалерея

2012 рік

Славсько-січень

19.01.2012

21.01.2012

23.01.2012

24.01.2012

2013 рік

Додати фото

Нещодавно Ви завантажили

Останні 10 завантажених зображень

Останні 10 коментарів

Топ 10

за рейтингом

за голосами

за переглядами

Меню адміністратора

Перевірка завантажених зображень

Перевірка коментарів

Категорія/підкатегорія

Створити

Редагувати

Переіндексація

Меню користувача

Профіль

редагувати мій власний

іншого користувача

Контакти

Вихід з сайту

        Привіт vga! Радий Вас бачити.

    <form id="edit_cat_frm" method="POST" action="">

Редагувати категорії / підкатегорії

    Назва
    Порядок показу
    Спорідненість
    Порядок в табл.

Нова категорія
<input class='person-id' name='person-1-id' value='person-1' type='hidden' />
<input class='row-depth' name='person-1-depth' value='1' type='hidden' />

<select class='row-weight' name='person-1-weight'>
<option selected value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>

<select class='row-parent' name='person-1-parent'>
<option selected value='0'>Відсутній</option>
<option value='person-2'>Літаки</option>
<option value='person-3'>Гори</option>
<option value='person-4'>Міста України</option>
<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>

1

Літаки
<input class='person-id' name='person-2-id' value='person-2' type='hidden' />
<input class='row-depth' name='person-2-depth' value='1' type='hidden' />

<select class='row-weight' name='person-2-weight'>
<option value='1'>1</option>
<option selected value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>

<select class='row-parent' name='person-2-parent'>
<option selected value='0'>Відсутній</option><option value='person-1'>Нова категорія</option>

<option value='person-3'>Гори</option>
<option value='person-4'>Міста України</option>
<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>

2

Гори
<input class='person-id' name='person-3-id' value='person-3' type='hidden' />
<input class='row-depth' name='person-3-depth' value='1' type='hidden' />

<select class='row-weight' name='person-3-weight'>
<option value='1'>1</option>
<option value='2'>2</option>
<option selected value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>

<select class='row-parent' name='person-3-parent'>
<option selected value='0'>Відсутній</option><option value='person-1'>Нова категорія</option>
<option value='person-2'>Літаки</option>

<option value='person-4'>Міста України</option>
<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>

3

Міста України
<input class='person-id' name='person-4-id' value='person-4' type='hidden' />
<input class='row-depth' name='person-4-depth' value='1' type='hidden' />

<select class='row-weight' name='person-4-weight'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option selected value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
</select>

<select class='row-parent' name='person-4-parent'>
<option selected value='0'>Відсутній</option><option value='person-1'>Нова категорія</option>
<option value='person-2'>Літаки</option>
<option value='person-3'>Гори</option>

<option value='person-5'>Cars</option>
<option value='person-6'>Girls and boys123</option>
<option value='person-7'>Nature</option>
<option value='person-8'>Aircraft</option>
<option value='person-9'>Animals</option>
<option value='person-10'>Buildings</option>
<option value='person-11'>Universe</option>
<option value='person-12'>Рибалка</option>
<option value='person-13'>Турпохід</option>
<option value='person-14'>Рідні краєвиди</option>
<option value='person-15'>Подорожі</option>
<option value='person-16'>Світ каміння</option>
<option value='person-17'>Вояки</option>
<option value='person-18'>Вояки і собаки</option>
<option value='person-19'>Котики та котяри</option>
<option value='person-20'>Мишки</option>
<option value='person-21'>Комашки</option>
<option value='person-22'>Кукурудза</option>
</select>

4

    Перегляд категорії
    Перегляд зображень
    Додавання зображень
    Голосування
    Відправлення листівок
    Читання коментар.
    Додавання коментар.

Ні
Ні
Ні
Ні
Ні
Ні
Ні

Ні
Ні
Ні
Ні
Ні
Ні
Ні

Так
Так
Так
Ні
Ні
Ні
Ні

Так
Так
Так
Так
Так
Так
Так

опис нової категорії

фото літаків

  фото гір

Опис категорії

    <input type="hidden" name="action" value="edit_cat"/>

    <input type="submit" class="button" name="create" value="Записати"/>

    <input id="reset_edit_cat" type="reset" class="button" name="Cancel" value="Відмінити"/>

    </form>

Авторське право © 2013, Гладких Владислав. Всі права захищені.

                        Веб-шаблон створений з допомогою Artisteer.

Body:
You do not have an element with the id #inner, as indicated in edit_category.js, via the following line:

$('#inner').html(dat0);

You instead have an element with a class of inner, therefore just need to amend line above to the following:

$('.inner').html(dat0);


问:
What is the best/simplest way to read in an XML file in Java application?
Currently our Java application uses the values held within a tab delimited *.cfg file. We need to change this application so that it now uses an XML file.

What is the best/simplest library to use in order to read in values from this file?

答:
Use java.beans.XMLDecoder, part of core Java SE since 1.4.

```<code>XMLDecoder input = new XMLDecoder(new FileInputStream("some/path.xml"));
MyConfig config = (MyConfig) input.readObject();
input.close();
</code>```

It's easy to write the configuration files by hand, or use the corresponding XMLEncoder with some setup to write new objects at run-time.

OwnerDisplayName: ryanmcc

ContentLicense: CC BY-SA 2.5

Body:
Use java.beans.XMLDecoder, part of core Java SE since 1.4.

XMLDecoder input = new XMLDecoder(new FileInputStream("some/path.xml"));
MyConfig config = (MyConfig) input.readObject();
input.close();

It's easy to write the configuration files by hand, or use the corresponding XMLEncoder with some setup to write new objects at run-time.

OwnerDisplayName: erickson


问:
Create Own Column Property in SQL
i want to create my one own property for every column.

ex. every column has description property but i require one more property for me.

i want required for auto code generate from that property.

what is best way for that?

答:
In the Object Explorer, right click the column in question and click properties.

This should open the Column Properties Window.

Select Extended Properties, and here you can add your data.

Title: Create Own Column Property in SQL


问:
NLP NaiveBayesClassifier for utf-8 in Python NLTK
I'm trying to use NLTK to perform some NLP NLTK classification for Arabic phrases. If I enter the native words as is in the classifier then it complains about non-ascii characters. Currently, I'm doing word.decode('utf-8') and then entering that as input to the trainer.

When I test the classifier, the results make some sense if there was an exact match. However, if I test a substring of a word in the original training words then results looks somewhat random.

I just want to distinguish if this was a bad classifier or if there's something fundamental in the encoding that degrades the performance of the classifier. Is this a reasonable way to input non-ascii text to classifiers?

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

from textblob.classifiers import NaiveBayesClassifier

x = "الكتاب".decode('utf-8')
...

train = [
(x,'pos'),
]

cl = NaiveBayesClassifier(train)

t = "كتاب".decode('utf-8')
cl.classify(t)
</code>```

The word in t is simply x with the first two letters removed. I'm running this with a much bigger dataset of course.

答:
Your post contains, basically, two questions. The first is concerned with encoding, the second one is about predicting substrings of words seen in training.

For encoding, you should use unicode literals directly, so you can omit the decode() part. Like this:

```<code>x = u"الكتاب"
</code>```

Then you will have a decoded representation already.

Concerning substrings, the classifier won't do that for you. If you ask for predictions for a token that wasn't included in the training in exactly the same spelling, then it will be treated as an unknown word – no matter if it's a substring of a word that occurred in training or not.

The substring case wouldn't be well-defined, anyway: Let's say you look up the single letter Alif – probably, a whole lot of words seen in training contain it. Which one should be used? A random one? The one with the highest probability? The sum of the probabilities of all matching ones? There's no easy answer to this.

I suspect that you are trying to match morphological variants of the same root. If this is the case, then you should try using a lemmatiser. So, before training, and also before prediction, you preprocess all tokens by converting them to their lemma (which is usually the root in Arabic, I think). I doubt that NLTK ships with a morphological model for Arabic, though, so you probably need to look for that elsewhere (but this is beyond the scope of this answer now).

Body:
I'm trying to use NLTK to perform some NLP NLTK classification for Arabic phrases. If I enter the native words as is in the classifier then it complains about non-ascii characters. Currently, I'm doing word.decode('utf-8') and then entering that as input to the trainer.

When I test the classifier, the results make some sense if there was an exact match. However, if I test a substring of a word in the original training words then results looks somewhat random.

I just want to distinguish if this was a bad classifier or if there's something fundamental in the encoding that degrades the performance of the classifier. Is this a reasonable way to input non-ascii text to classifiers?

#!/usr/bin/python
# -*- coding: utf-8 -*-

from textblob.classifiers import NaiveBayesClassifier

x = "الكتاب".decode('utf-8')
...

train = [
(x,'pos'),
]

cl = NaiveBayesClassifier(train)

t = "كتاب".decode('utf-8')
cl.classify(t)

The word in t is simply x with the first two letters removed. I'm running this with a much bigger dataset of course.

Body:
Your post contains, basically, two questions. The first is concerned with encoding, the second one is about predicting substrings of words seen in training.

For encoding, you should use unicode literals directly, so you can omit the decode() part. Like this:

x = u"الكتاب"

Then you will have a decoded representation already.

Concerning substrings, the classifier won't do that for you. If you ask for predictions for a token that wasn't included in the training in exactly the same spelling, then it will be treated as an unknown word – no matter if it's a substring of a word that occurred in training or not.

The substring case wouldn't be well-defined, anyway: Let's say you look up the single letter Alif – probably, a whole lot of words seen in training contain it. Which one should be used? A random one? The one with the highest probability? The sum of the probabilities of all matching ones? There's no easy answer to this.

I suspect that you are trying to match morphological variants of the same root. If this is the case, then you should try using a lemmatiser. So, before training, and also before prediction, you preprocess all tokens by converting them to their lemma (which is usually the root in Arabic, I think). I doubt that NLTK ships with a morphological model for Arabic, though, so you probably need to look for that elsewhere (but this is beyond the scope of this answer now).


问:
Is it considered bad practice to throw errors in a JavaScript class?
I have a JavaScript class like the following and I need to control the data type of my input variables.

```<code>class Store
{
    constructor (name)
    {
        if (typeof name !== "string")
            throw new Error("The first argument must be a string!");

        createStore(name);
    }

    // [...]
}
</code>```

Is it considered a bad practice? There is a better solution?

答:
Well, in some cases it might actually be better to not throw the error.
Let's say you have a method that returns a promise. In that case you would probably be better off rejecting it so that it can be be caught using <code>.catch</code>.  </p>

```<code>class Example {
    test(name) {
        return new Promise( (resolve, reject) => {
            if (typeof name !== "string")
                reject("The first argument must be a string!")
            else
                resolve()
        })
    }
}

let ex = new Example()
ex.test(['array']).then( () => {
    console.log('We successfully passed a string!')
}).catch( err => {
    console.error(err)
})
</code>```

Body:
I have a JavaScript class like the following and I need to control the data type of my input variables.

class Store
{
    constructor (name)
    {
        if (typeof name !== "string")
            throw new Error("The first argument must be a string!");

        createStore(name);
    }

    // [...]
}

Is it considered a bad practice? There is a better solution?

Body:
Well, in some cases it might actually be better to not throw the error.
Let's say you have a method that returns a promise. In that case you would probably be better off rejecting it so that it can be be caught using .catch.

class Example {
    test(name) {
        return new Promise( (resolve, reject) => {
            if (typeof name !== "string")
                reject("The first argument must be a string!")
            else
                resolve()
        })
    }
}

let ex = new Example()
ex.test(['array']).then( () => {
    console.log('We successfully passed a string!')
}).catch( err => {
    console.error(err)
})


问:
Regex match depending on lookbehind match
I need to match these values:

(First approach to a regex that roughly does what I want)

```<code>\d+([.,]\d{3})*[.,]\d{2}
</code>```

like

```<code>24,56
24.56
1.234,56
1,234.56
1234,56
1234.56
</code>```

but I need to not match

```<code>1.234.56
1,234,56
</code>```

So somehow I need to check the last occurrence of "." or "," to not be the same as the previous "." or ",".

Background: Amounts shall be matched in English and German format with (optional) 1000-Separators.

But even with help of regex101 I completely fail at coming up with a correctly working look-behind. Any suggestions are highly appreciated.

UPDATE

Based on the answers I got so far, I came up with this (demo):

```<code>\d{1,3}(?:([\.,'])?\d{3})*(?!\1)[\.,\s]\d{2}
</code>```

But it matches for example 1234.567,23 which is not desirable.

答:
You may capture the digit grouping symbol and use a negative lookahead with a backreference to restrict the decimal separator:

```<code>^(?:\d+|\d{1,3}(?:([.,])\d{3})*)(?!\1)[.,]\d{2}$
                  ^    ^        ^^^^^
</code>```

See the regex demo

Group 1 will contain the last value of the digit grouping symbol and (?!\1)[.,] will match the other symbol.

Details:

^ - start of string

(?:\d+|\d{1,3}(?:([.,])\d{3})*) - either of the two alternatives:

\d+  - 1+ digits

| - or

\d{1,3} - 1 to 3 digits,

(?:([.,])\d{3})* - zero or more sequences of:

([.,]) - Group 1 capturing . or ,

\d{3} - 3 digits

(?!\1)[.,] - a . or , but not equal to what was last captured with ([.,]) pattern above

\d{2} - 2 digits

$ - end of string.

Body:
I need to match these values:

(First approach to a regex that roughly does what I want)

\d+([.,]\d{3})*[.,]\d{2}

like

24,56
24.56
1.234,56
1,234.56
1234,56
1234.56

but I need to not match

1.234.56
1,234,56

So somehow I need to check the last occurrence of "." or "," to not be the same as the previous "." or ",".

Background: Amounts shall be matched in English and German format with (optional) 1000-Separators.

But even with help of regex101 I completely fail at coming up with a correctly working look-behind. Any suggestions are highly appreciated.

UPDATE

Based on the answers I got so far, I came up with this (demo):

\d{1,3}(?:([\.,'])?\d{3})*(?!\1)[\.,\s]\d{2}

But it matches for example 1234.567,23 which is not desirable.

Body:
You may capture the digit grouping symbol and use a negative lookahead with a backreference to restrict the decimal separator:

^(?:\d+|\d{1,3}(?:([.,])\d{3})*)(?!\1)[.,]\d{2}$
                  ^    ^        ^^^^^

See the regex demo

Group 1 will contain the last value of the digit grouping symbol and (?!\1)[.,] will match the other symbol.

Details:

^ - start of string

(?:\d+|\d{1,3}(?:([.,])\d{3})*) - either of the two alternatives:

\d+  - 1+ digits

| - or

\d{1,3} - 1 to 3 digits,

(?:([.,])\d{3})* - zero or more sequences of:

([.,]) - Group 1 capturing . or ,

\d{3} - 3 digits

(?!\1)[.,] - a . or , but not equal to what was last captured with ([.,]) pattern above

\d{2} - 2 digits

$ - end of string.


问:
Getting image path in public folder in laravel
I'm making direction using this method to upload my image

```<code> mkdir(public_path().'/website/'.$path,0777, true);
</code>```

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

```<code> <img src="{{url('public/website/'.$file->path.$file->file)}}"  />
</code>```

how to get the correct path of the image or even create the folder on the public_html root path ?

答:
```<code>you can use public_path(); function in laravel
or
<img src="{{ public_path().'/website/'.$file->path.'/'.$file->file;}}"  />
or
<img src="/website/{{$file->path.$file->file}}"  />
</code>```

Body:
I'm making direction using this method to upload my image

 mkdir(public_path().'/website/'.$path,0777, true);

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

 path.$file->file)}}"  />

how to get the correct path of the image or even create the folder on the public_html root path ?


问:
Javascript - Change event trigger multiple times
I have the following table.

```<code><table class="table invoice-items-table">
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr class="invoice-item-row">
            <td>
                <select class="selectpicker invoice-item-select" title="Select an Item">
                    <option value="1">PHP Development</option>
                </select>
            </td>
            <td class="text-right">
                <input class="form-control invoice-item-quantity" value="1" type="text">
            </td>
            <td class="text-right">
                <input class="form-control invoice-item-price" value="0.00" type="text">
            </td>
            <td class="text-right" style="padding-top:18px!important;">
                <span class="invoice-item-amount">0 </span>
                <span class="invoice-currency">₹</span>
            </td>
        </tr>
        <tr class="invoice-item-add-row">
            <td colspan="7">
                <a href="#" class="link invoice-item-add text-center">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                    Add an Item
                </a>
            </td>
        </tr>
    </tbody>
</table>
</code>```

For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.

```<code>$('.invoice-item-add').on('click', function() {
    var itemRowClone = $('.invoice-item-row').last().clone();
    itemRowClone.find('input, textarea').val('');
    itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    itemRowClone.find('.selectpicker').selectpicker();
    $('.invoice-item-add-row').before(itemRowClone);
    return false;
});
</code>```

This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.

```<code>$(document).on('change', '.invoice-item-select', function() {
    // Code here...
});
</code>```

my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.

I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.

How do I make sure this on-change event is fired only once?

Thanks.

答:
I ended up using this solution

```<code>$(document).on('change', '.invoice-item-select', function(e) {
    if (e.handled !== true) {
        e.handled = true;
        return;
    }
    // Code here
});
</code>```

Although this does not stop from multiple firing of events, I can at-least stop the code execution for subsequent triggers.

Body:
I have the following table.

            Item
            Quantity
            Price
            Amount

                <select class="selectpicker invoice-item-select" title="Select an Item">
                    <option value="1">PHP Development</option>
                </select>

                <input class="form-control invoice-item-quantity" value="1" type="text">

                <input class="form-control invoice-item-price" value="0.00" type="text">

                0
                ₹

                    Add an Item

For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.

$('.invoice-item-add').on('click', function() {
    var itemRowClone = $('.invoice-item-row').last().clone();
    itemRowClone.find('input, textarea').val('');
    itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    itemRowClone.find('.selectpicker').selectpicker();
    $('.invoice-item-add-row').before(itemRowClone);
    return false;
});

This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.

$(document).on('change', '.invoice-item-select', function() {
    // Code here...
});

my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.

I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.

How do I make sure this on-change event is fired only once?

Thanks.

Body:
I ended up using this solution

$(document).on('change', '.invoice-item-select', function(e) {
    if (e.handled !== true) {
        e.handled = true;
        return;
    }
    // Code here
});

Although this does not stop from multiple firing of events, I can at-least stop the code execution for subsequent triggers.


问:
Show/hide a image & radio button when it is checked and unchecked
Im working on a logic, where if I check the radio button the radio button should hide and an icon should display and this has to be over a three radio buttons.

My condition is there are three radio buttons which are 'Approved' & 'Declined' & 'Waitlisted'. When i check radio button 'Approved' an image shld be visible and that 'Approved' radio button should be hidden, then when i check other button this 'Approved'radio should show and image should hide. so this has to work with all three radio buttons.

Any ideas?

答:
     Approved

     Declined

     Waitlisted

function ShowHideImage(id)
 {
  $('.ImageShow').each(function(){
   $(this).hide();
  });
  $('#Image'+id).show();
  var RadioClass = $('#'+id).attr('class');
  $('.'+RadioClass).each(function(){
   $(this).parent().show();
  });
  $('.'+id).hide();
 }

 $(document).on('click','.RadioButton',function(){
  var id = $(this).attr('id');
  ShowHideImage(id);
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="images/final_fantasy.jpg" width="150px" height="150px" style="display: none;" class="ImageShow" id="ImageRadioApproved" alt="image1">
<img src="images/Koala.jpg" width="150px" height="150px" style="display: none;" class="ImageShow" id="ImageRadioDeclined" alt="image2">
<img src="images/Desert.jpg" width="150px" height="150px" style="display: none;" class="ImageShow" id="ImageRadioWaitlisted" alt="image3">

<div class="RadioApproved">
  <input type="radio" class="RadioButton" id="RadioApproved" name="RadioSelect"> Approved
</div>
<div class="RadioDeclined">
  <input type="radio" class="RadioButton" id="RadioDeclined" name="RadioSelect"> Declined
</div>
<div class="RadioWaitlisted">
  <input type="radio" class="RadioButton" id="RadioWaitlisted" name="RadioSelect"> Waitlisted
</div></code>```

Body:
     Approved

     Declined

     Waitlisted

function ShowHideImage(id)
 {
  $('.ImageShow').each(function(){
   $(this).hide();
  });
  $('#Image'+id).show();
  var RadioClass = $('#'+id).attr('class');
  $('.'+RadioClass).each(function(){
   $(this).parent().show();
  });
  $('.'+id).hide();
 }

 $(document).on('click','.RadioButton',function(){
  var id = $(this).attr('id');
  ShowHideImage(id);
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="images/final_fantasy.jpg" width="150px" height="150px" style="display: none;" class="ImageShow" id="ImageRadioApproved" alt="image1">
<img src="images/Koala.jpg" width="150px" height="150px" style="display: none;" class="ImageShow" id="ImageRadioDeclined" alt="image2">
<img src="images/Desert.jpg" width="150px" height="150px" style="display: none;" class="ImageShow" id="ImageRadioWaitlisted" alt="image3">

<div class="RadioApproved">
  <input type="radio" class="RadioButton" id="RadioApproved" name="RadioSelect"> Approved
</div>
<div class="RadioDeclined">
  <input type="radio" class="RadioButton" id="RadioDeclined" name="RadioSelect"> Declined
</div>
<div class="RadioWaitlisted">
  <input type="radio" class="RadioButton" id="RadioWaitlisted" name="RadioSelect"> Waitlisted
</div>


Title: Regex match depending on lookbehind match

Body:
You can use

^\d+(([.,])\d{3})*(?!\2)[.,]\d{2}$

live demo


答:
if you compare with ==, php tries to compare them without respecting the type. So what actually happens, php converts the two numbers to an integer, and as 98 is equal to 98, "098" == "98" is also true.

The best way to avoid this is, use ===, which compares also the type without any conversions.

```<code>if("098" === "98"){
    return true;
}
</code>```

Title: Comparing two strings in which one starts with a zero

Body:
if you compare with ==, php tries to compare them without respecting the type. So what actually happens, php converts the two numbers to an integer, and as 98 is equal to 98, "098" == "98" is also true.

The best way to avoid this is, use ===, which compares also the type without any conversions.

if("098" === "98"){
    return true;
}


问:
Forwarding EventHandlers
I have a method registered as an EventHandler:

```<code>handler.Actiontriggered += LocalMethod;
</code>```

Now I want to replace the handler with an interface. I ended up with something like this:

```<code>public interface IHandler
{
  event EventHandler<EventArgs> Actiontriggered;
}
</code>```

and implemented as

```<code>public class SpecificHandler : IHandler
{
    ....
    public event EventHandler<EventArgs> Actiontriggered
    {
        add
        {
            this.handler.Actiontriggered+= value; // handler is the same as in the snippet above
        }

        remove
        {
            this.handler.Actiontriggered-= value;
        }
    }
}
</code>```

Now the problem is that I get an error that EventHandler<EventArgs> cannot be implicitly converted to a type specific to the handler.

```<code>Cannot implicitly convert type 'System.EventHandler<System.EventArgs>' to 'Handler.ActiontriggeredEventHandler'
</code>```

As this worked in the original direct assignment: What to rewrite for this to function with the interface as well?

答:
The ActionTriggered event in the type of handler is not declared as

```<code>public class Handler
{
    public event EventHandler<EventArgs> Actiontriggered;
}
</code>```

but as

```<code>public class Handler
{
    public delegate void ActionTriggered (object sender, EventArgs e);
    public event Actiontriggered Actiontriggered;
}
</code>```

So you need to change your interface to:

```<code>public interface IHandler
{
     event Handler.Actiontriggered Actiontriggered;
}
</code>```

and the implementing class accordingly:

```<code>public class SpecificHandler : IHandler
{
    ....
    public event Handler.Actiontriggered Actiontriggered
    {
        add
        {
            this.handler.Actiontriggered+= value; // handler is the same as in the snippet above
        }

        remove
        {
            this.handler.Actiontriggered-= value;
        }
    }
}
</code>```

Although Handler.Actiontriggered is a delegate type with the same signature as an EventHandler<EventArgs>, they are not the same type, hence the compiler error.

Title: Forwarding EventHandlers

Body:
I have a method registered as an EventHandler:

handler.Actiontriggered += LocalMethod;

Now I want to replace the handler with an interface. I ended up with something like this:

public interface IHandler
{
  event EventHandler<EventArgs> Actiontriggered;
}

and implemented as

public class SpecificHandler : IHandler
{
    ....
    public event EventHandler<EventArgs> Actiontriggered
    {
        add
        {
            this.handler.Actiontriggered+= value; // handler is the same as in the snippet above
        }

        remove
        {
            this.handler.Actiontriggered-= value;
        }
    }
}

Now the problem is that I get an error that EventHandler<EventArgs> cannot be implicitly converted to a type specific to the handler.

Cannot implicitly convert type 'System.EventHandler<System.EventArgs>' to 'Handler.ActiontriggeredEventHandler'

As this worked in the original direct assignment: What to rewrite for this to function with the interface as well?

Body:
The ActionTriggered event in the type of handler is not declared as

public class Handler
{
    public event EventHandler<EventArgs> Actiontriggered;
}

but as

public class Handler
{
    public delegate void ActionTriggered (object sender, EventArgs e);
    public event Actiontriggered Actiontriggered;
}

So you need to change your interface to:

public interface IHandler
{
     event Handler.Actiontriggered Actiontriggered;
}

and the implementing class accordingly:

public class SpecificHandler : IHandler
{
    ....
    public event Handler.Actiontriggered Actiontriggered
    {
        add
        {
            this.handler.Actiontriggered+= value; // handler is the same as in the snippet above
        }

        remove
        {
            this.handler.Actiontriggered-= value;
        }
    }
}

Although Handler.Actiontriggered is a delegate type with the same signature as an EventHandler<EventArgs>, they are not the same type, hence the compiler error.