问:
What is the best method to store default values in database?
I have several tables like Buyers, Shops, Brands, Money_Collectors, e.t.c.

Each one of those has a default value, e.g. the default Buyer is David, the default Shop is Ebay, and so on.

I would like to save those default values in a database (so that user could change them).

I thought to add is_default column to each one of the tables, but it seems to be ineffective because only one row in each table may be the default.

Then I thought that the best would be to have Defaults table that will contain all the default values. This table will have 1 row and N columns, where N is the number of the default values:

```<code>Defaults table:

buyer      shop      brand      money_collector
-----      ----      -----      ---------------
David      Ebay      Dell       NULL   (no default value)
</code>```

But, this seems to be not the best approach because the table structure changes when a new default value is added.

What would be the best approach to store default values ?

答:
You can create a catalog table (some kind of metadata table) containing the default values as strings for the desired table columns. Then you can use the convert function for getting the appropriate value. Below is a sample table definition (Transact-SQL was used):

```<code>create table dbo.cat_default_values
(
    id_column       varchar(30)    not null,
    id_table        varchar(30)    not null,
    datatype        varchar(30)    not null,
    value           varchar(100)   not null,
    f_creation      datetime       not null,
    usr_creation    char(8)        null,
    primary key  clustered  (id_column, id_table)
)

declare @defaultValueInt int,
        @defaultValueVarchar varchar(30)

select @defaultValueInt = convert(int, value)
    from cat_default_values where id_column = "defColumInteger" and id_table = "table1"

select defaultValueVarchar = value
    from cat_default_values where id_column = "defColumVarchar" and id_table = "table1"
</code>```

Body:
I have several tables like Buyers, Shops, Brands, Money_Collectors, e.t.c.

Each one of those has a default value, e.g. the default Buyer is David, the default Shop is Ebay, and so on.

I would like to save those default values in a database (so that user could change them).

I thought to add is_default column to each one of the tables, but it seems to be ineffective because only one row in each table may be the default.

Then I thought that the best would be to have Defaults table that will contain all the default values. This table will have 1 row and N columns, where N is the number of the default values:

Defaults table:

buyer      shop      brand      money_collector
-----      ----      -----      ---------------
David      Ebay      Dell       NULL   (no default value)

But, this seems to be not the best approach because the table structure changes when a new default value is added.

What would be the best approach to store default values ?

Body:
You can create a catalog table (some kind of metadata table) containing the default values as strings for the desired table columns. Then you can use the convert function for getting the appropriate value. Below is a sample table definition (Transact-SQL was used):

create table dbo.cat_default_values
(
    id_column       varchar(30)    not null,
    id_table        varchar(30)    not null,
    datatype        varchar(30)    not null,
    value           varchar(100)   not null,
    f_creation      datetime       not null,
    usr_creation    char(8)        null,
    primary key  clustered  (id_column, id_table)
)

declare @defaultValueInt int,
        @defaultValueVarchar varchar(30)

select @defaultValueInt = convert(int, value)
    from cat_default_values where id_column = "defColumInteger" and id_table = "table1"

select defaultValueVarchar = value
    from cat_default_values where id_column = "defColumVarchar" and id_table = "table1"


来源: stackexchange

问:
Random high content download time in chrome?
We have an API which randomly takes high content download time in chrome, It works fine always in firefox and takes an only few ms. The response size is 20kb uncompressed and 4kb compressed. The same request also works fine using curl.

Things that we have tried:

Disabling If-None-Match header to disable cache response from the browser.

Trying various compressions (gzip, deflate, br).

Disabling compression.

Disabling all chrome extensions.

The same request works fine sometimes on chrome but randomly returns very high content download time.

We are unable to understand the root cause of this issue. What are the other things we can try to minimize this time?

I made three requests here and the 3rd one took the most time (before the last spike). CPU does not seem to be maxing out for a longer period of time. Most of the time is idle time.

Also, When replaying the call using Replay XHR menu, the Content download period drops from 2s to 200 ms.

答:
I think you may be doing it wrong.™

Fundamentally, if this really only happens with Chrome, then perhaps the client-side code is to blame, of which you don't reveal any details.

Otherwise, you are trying to debug what you present as a backend condition (based on the choice on the nginx tag) with front-end tools:

Have you tried using tcpdump(8) to troubleshoot the issue?  What packets gets exchanged and at what times?

Have you tried logging the times of the request being received and processed by nginx?  E.g., $request_time?

Where is the server located?  Perhaps you're experiencing packet loss, which may require timeouts and retransmission of some TCP packets, which invariably will introduce a random delay?

Finally, the last possibility is that the field doesn't mean what you think it does -- it sounds like it may take a hit from CPU load, as this is the result of the XMLHTTPRequest (XHR) processing -- perhaps you run some advertising with user tracking that randomly consumes a significant amount of CPU, slowing down your metrics?

ContentLicense: CC BY-SA 3.0


问:
C++ class definition
I've run across a class defined as follows:

```<code>class SYS_LIB_API Version
{
public:
somefunctions()
...
}
</code>```

I don't understand the class SYS_LIB_API Version line. I'm used to seeing:

```<code>class Version
{
public:
somefunctions()
...
}
</code>```

答: Its just a macro that the API creator uses to define certain this, many of them internal.</p>

ContentLicense: CC BY-SA 2.5

Title: C++ class definition

Body:
I've run across a class defined as follows:

class SYS_LIB_API Version
{
public:
somefunctions()
...
}

I don't understand the class SYS_LIB_API Version line. I'm used to seeing:

class Version
{
public:
somefunctions()
...
}


问:
Split and parse window.location.hash
I'm facing issues with splitting and parsing window.location.hash correctly.

First of all, we get few parameters in hash, ex:

```<code>#loc=austria&mr=1&min=10&max=89
</code>```

As you surely see it's been created for search. When user clicks on pagination link page is being reloaded with the hash. So far so good.

I created function initialise() that is calling every time when there's hash in the URL:

```<code>if (window.location.hash) {
    var params = (window.location.hash.substr(1)).split("&");

    for (i = 0; i < params.length; i++)
    {
        var a = params[i].split("=");
        // Now every parameter from the hash is beind handled this way
        if (a[0] == "loc")
        {
            locationList(a[1]);
        }
    }
}
</code>```

Everythig is almost working... When I choose all search params hash is being... cut. For unknown reason for me. I tried to use if( params.indexOf('loc') ) instead of a[0] == "loc" without any luck.

Could you lend me a hand?

Edit

Of course, I was using var a = ... in the loop, it was only copy-paste error.

答:
This should be a rather simpler way to read from location.hash:

```<code>    var hash = window.location.hash.substring(1);
    var params = {}
    hash.split('&').map(hk => {
      let temp = hk.split('=');
        params[temp[0]] = temp[1]
    });
    console.log(params); //Here are the params to use
</code>```

and then, you could use

```<code>params.access_token //access_token
params.id //id
</code>```

and other params that are available inside the hash

Title: Split and parse window.location.hash

Body:
I'm facing issues with splitting and parsing window.location.hash correctly.

First of all, we get few parameters in hash, ex:

#loc=austria&mr=1&min=10&max=89

As you surely see it's been created for search. When user clicks on pagination link page is being reloaded with the hash. So far so good.

I created function initialise() that is calling every time when there's hash in the URL:

if (window.location.hash) {
    var params = (window.location.hash.substr(1)).split("&");

    for (i = 0; i < params.length; i++)
    {
        var a = params[i].split("=");
        // Now every parameter from the hash is beind handled this way
        if (a[0] == "loc")
        {
            locationList(a[1]);
        }
    }
}

Everythig is almost working... When I choose all search params hash is being... cut. For unknown reason for me. I tried to use if( params.indexOf('loc') ) instead of a[0] == "loc" without any luck.

Could you lend me a hand?

Edit

Of course, I was using var a = ... in the loop, it was only copy-paste error.

Body:
This should be a rather simpler way to read from location.hash:

    var hash = window.location.hash.substring(1);
    var params = {}
    hash.split('&').map(hk => {
      let temp = hk.split('=');
        params[temp[0]] = temp[1]
    });
    console.log(params); //Here are the params to use

and then, you could use

params.access_token //access_token
params.id //id

and other params that are available inside the hash


问:
JQuery append filters out html like tags?
I would like to append below line of text to the select html tag using JQuery:

"<option selected=true value="-1"><new></option>"

The problem is in <new>. This substring is filtered out completely by append function. I know this is not legal html tag, and probably it filters it just of this reason. Can I force JQuery somehow to interpret <new> as substring? Because <new> is not meant as html tag, but only to point out to the user that this is not the value in the list, but a selection to make a new entry on the list.

Body: $('#test').append($('<option>').attr('value', -1).text('<new>')[0]);


问:
How to compare two dates to find time difference in SQL Server 2005, date manipulation
I have two columns:

```<code>job_start                         job_end
2011-11-02 12:20:37.247           2011-11-02 13:35:14.613
</code>```

How would it be possible using T-SQL to find the raw amount of time that has passed between when the job started and when the job ended?

I tried this:

```<code>select    (job_end - job_start) from tableA
</code>```

but ended up with this:

```<code>1900-01-01 01:14:37.367
</code>```

答:
Below code gives in hh:mm format.

select RIGHT(LEFT(job_end- job_start,17),5)

Body:
I have two columns:

job_start                         job_end
2011-11-02 12:20:37.247           2011-11-02 13:35:14.613

How would it be possible using T-SQL to find the raw amount of time that has passed between when the job started and when the job ended?

I tried this:

select    (job_end - job_start) from tableA

but ended up with this:

1900-01-01 01:14:37.367


问:
Run a function returning a set on a set, and get back a larger set
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

```<code>ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }
</code>```

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

答:
One liner solution:</p>

```<code>z=set(map(lambda x:x**2,q)).union(q)
</code>```

Body:
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

Body:
One liner solution:

z=set(map(lambda x:x**2,q)).union(q)


问:
How to upload multiple files to BlobStore?
I'm trying to upload multiple files in a form to the BlobStore.

Form:

```<code><form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
  <label>Key Name</label><input type="text" name="key_name" size="50"><br/>
  <label>name</label><input type="text" name="name" size="50"><br/>
  <label>image</label><input type="file" name="image" size="50"><br/>
  <label>thumb</label><input type="file" name="thumb" size="50"><br/>
  <input type="submit" name="submit" value="Submit">
</form>
</code>```

I'm then trying to fetch the BlobInfo objects for each of those files uploaded:

```<code>def post(self):
    image_upload_files = self.get_uploads('image')
    thumb_upload_files = self.get_uploads('thumb')
    image_blob_info = image_upload_files[0]
    thumb_blob_info = thumb_upload_files[0]
</code>```

I'm seeing some weird behavior.  Both files are making it into the BlobStore, but I cannot figure out how to get the Keys so that I can store those on another Entity.  The code above manages to get the key for image_blob_info, but not thumb_blob_info.  I don't understand how to use get_uploads.  I want to pass multiple files through the form and then fetch them by name so I can store them in the appropriate BlobReferenceProperties on another Entity.

答:
Each file needs its own unique upload url, so my guess is something wacky is happening when all three files are posted to the same url.

The best solution for supporting multiple file uploads is described in Nick Johnson's blog post:

http://blog.notdot.net/2010/04/Implementing-a-dropbox-service-with-the-Blobstore-API-part-3-Multiple-upload-support

Body:
I'm trying to upload multiple files in a form to the BlobStore.

Form:

<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
  Key Name<input type="text" name="key_name" size="50">

  name<input type="text" name="name" size="50">

  image<input type="file" name="image" size="50">

  thumb<input type="file" name="thumb" size="50">

  <input type="submit" name="submit" value="Submit">
</form>

I'm then trying to fetch the BlobInfo objects for each of those files uploaded:

def post(self):
    image_upload_files = self.get_uploads('image')
    thumb_upload_files = self.get_uploads('thumb')
    image_blob_info = image_upload_files[0]
    thumb_blob_info = thumb_upload_files[0]

I'm seeing some weird behavior.  Both files are making it into the BlobStore, but I cannot figure out how to get the Keys so that I can store those on another Entity.  The code above manages to get the key for image_blob_info, but not thumb_blob_info.  I don't understand how to use get_uploads.  I want to pass multiple files through the form and then fetch them by name so I can store them in the appropriate BlobReferenceProperties on another Entity.


答:
try this

```<code>$('<option/>').attr("value","-1").text("<new>").appendTo("select");
</code>```

Thanks !

Title: JQuery append filters out html like tags?

Body:
I would like to append below line of text to the select html tag using JQuery:

"<option selected=true value="-1"><new></option>"

The problem is in <new>. This substring is filtered out completely by append function. I know this is not legal html tag, and probably it filters it just of this reason. Can I force JQuery somehow to interpret <new> as substring? Because <new> is not meant as html tag, but only to point out to the user that this is not the value in the list, but a selection to make a new entry on the list.

Body:
try this

$('<option/>').attr("value","-1").text("<new>").appendTo("select");

Thanks !


问:
Invert The Sequence
This is a question that was asked to me during an interview. For a Table like this (Which may have hundreds or thousands of records of this kind)

what is the best way to revert the Seq so that A will be seq 4 and B will be seq 1 like this :

I gave him the below query (I used CTE Just to create the sample scenario. In the original case it was a table ) :

```<code>WITH CTE
AS
(
    SELECT
        Seq = 1,Nm = 'A'
    UNION
    SELECT
        Seq = 2,Nm = 'A'
    UNION
    SELECT
        Seq = 3,Nm = 'B'
    UNION
    SELECT
        Seq = 4,Nm = 'B'
)
SELECT
    Seq = ROW_NUMBER() OVER(ORDER BY Seq DESC),
    Seq,
    Nm
    FROM CTE;
</code>```

are there any alternative Dynamic queries of achieving the same in a more efficient way?

答:
I don't think it's appropriate to help with interview questions here, but since this one is so unrealistic, and there are so many complicated answers here, I pose this much simpler solution:</p>

```<code>DECLARE @MaxSeq INT;
SELECT @MaxSeq = MAX(Seq) FROM Table;

UPDATE Table
Set Seq = @MaxSeq - Seq + 1
</code>```

Title: Invert The Sequence

Body:
This is a question that was asked to me during an interview. For a Table like this (Which may have hundreds or thousands of records of this kind)

what is the best way to revert the Seq so that A will be seq 4 and B will be seq 1 like this :

I gave him the below query (I used CTE Just to create the sample scenario. In the original case it was a table ) :

WITH CTE
AS
(
    SELECT
        Seq = 1,Nm = 'A'
    UNION
    SELECT
        Seq = 2,Nm = 'A'
    UNION
    SELECT
        Seq = 3,Nm = 'B'
    UNION
    SELECT
        Seq = 4,Nm = 'B'
)
SELECT
    Seq = ROW_NUMBER() OVER(ORDER BY Seq DESC),
    Seq,
    Nm
    FROM CTE;

are there any alternative Dynamic queries of achieving the same in a more efficient way?

Body:
I don't think it's appropriate to help with interview questions here, but since this one is so unrealistic, and there are so many complicated answers here, I pose this much simpler solution:

DECLARE @MaxSeq INT;
SELECT @MaxSeq = MAX(Seq) FROM Table;

UPDATE Table
Set Seq = @MaxSeq - Seq + 1


问:
Android remove all recyclerview with animation on a button click
I have a recycler view. On a button click I want to remove all the items from the recyclerview but the items must be removed with animation.
I am able to remove all the items at once but I don't know how to remove them with animation. Thanks</p>

答:
This is how I have done without using any libraries - by inserting delays in the loop to remove items & restore (if needed)</p>

```<code>clearItemsView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final List<LineItem> lineItemsCopy = new ArrayList<>(lineItems);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<lineItemsCopy.size(); i++) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                salesOrderItemListAdapter.removeItem(0);
                            }
                        });
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            Snackbar snackbar = Snackbar.make(coordinatorLayout, getString(R.string.items_cleared_message), Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.label_undo), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i=0; i<lineItemsCopy.size(); i++) {
                                        final int finalI = i;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                salesOrderItemListAdapter.restoreItem(lineItemsCopy.get(finalI), 0);
                                            }
                                        });
                                        try {
                                            Thread.sleep(500);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }).start();
                        }
                    }).setActionTextColor(Color.YELLOW);
            snackbar.show();
        }
    });
</code>```

Body:
This is how I have done without using any libraries - by inserting delays in the loop to remove items & restore (if needed)

clearItemsView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final List<LineItem> lineItemsCopy = new ArrayList<>(lineItems);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<lineItemsCopy.size(); i++) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                salesOrderItemListAdapter.removeItem(0);
                            }
                        });
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            Snackbar snackbar = Snackbar.make(coordinatorLayout, getString(R.string.items_cleared_message), Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.label_undo), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i=0; i<lineItemsCopy.size(); i++) {
                                        final int finalI = i;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                salesOrderItemListAdapter.restoreItem(lineItemsCopy.get(finalI), 0);
                                            }
                                        });
                                        try {
                                            Thread.sleep(500);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }).start();
                        }
                    }).setActionTextColor(Color.YELLOW);
            snackbar.show();
        }
    });


问:
Angular Calendar integration not able to load
I'm trying to include angular ui-calendar component. I followed step from the site
1. https://github.com/angular-ui/ui-calendar
and
2. http://www.oodlestechnologies.com/blogs/Fullcalendar-Walk-through-with-AngularJS

Installed the components through

```<code>bower install angular-ui-calendar
</code>```

Loaded components in html file

```<code><link rel="stylesheet" href="bower_components/fullcalendar/dist/fullcalendar.css"/>
</code>```

Included dependency into app

```<code>var app = angular.module('myCalendarApp', ['ui.calendar'])
</code>```

In UI inserted like

```<code><div ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
</code>```

In controller created static events and configuration

```<code>$scope.eventSources = [];
$scope.uiConfig = {
    calendar:{
        height: 450,
        editable: true,
        header:{
            left: 'month basicWeek basicDay agendaWeek agendaDay',
            center: 'title',
            right: 'today prev,next'
        },
        eventClick: $scope.eventClick
    }
};
$scope.eventClick = function(event){
    alert("Clicked event === "+event.title);
};
var events = [
    {title: 'All Day Event',start: new Date('Sun Dec 17 2017 09:00:00 GMT+0530 (IST)')},
    {title: 'Long Event',start: new Date('Thu Dec 21 2017 10:00:00 GMT+0530 (IST)'),end: new Date('Thu Dec 21 2017 17:00:00 GMT+0530 (IST)')},
    {id: 999,title: 'Repeating Event',start: new Date('Mon Dec 4 2017 09:00:00 GMT+0530 (IST)'),allDay: false}
];
$scope.eventSources = [events];
</code>```

When I tried to verify the calendar in browser it is throwing following error

```<code>TypeError: calendar.fullCalendar is not a function
at Scope.scope.initCalendar (calendar.js:286)
at Object.fn (calendar.js:358)
at Scope.$digest (angular.js:15896)
at Scope.$apply (angular.js:16160)
at WindowsCtrl.window.showDialog.$scope.showDialog (controller.js:690)
at HTMLSpanElement.onclick (VM4670 windows:1)
</code>```

Could someone please help me to resolve this issue.

答:
thank you every one who given suggestion to solve the issue.

I solved the issue.
There is some issue in angular-ui-calendar/src/calendar.js file. In init and destroy methods they are creating the component by using angular.element method but if I change it with jQuery it solved the issue.

reference : https://github.com/angular-ui/ui-calendar/issues/267

Body:
I'm trying to include angular ui-calendar component. I followed step from the site
1. https://github.com/angular-ui/ui-calendar
and
2. http://www.oodlestechnologies.com/blogs/Fullcalendar-Walk-through-with-AngularJS

Installed the components through

bower install angular-ui-calendar

Loaded components in html file

<link rel="stylesheet" href="bower_components/fullcalendar/dist/fullcalendar.css"/>

Included dependency into app

var app = angular.module('myCalendarApp', ['ui.calendar'])

In UI inserted like

In controller created static events and configuration

$scope.eventSources = [];
$scope.uiConfig = {
    calendar:{
        height: 450,
        editable: true,
        header:{
            left: 'month basicWeek basicDay agendaWeek agendaDay',
            center: 'title',
            right: 'today prev,next'
        },
        eventClick: $scope.eventClick
    }
};
$scope.eventClick = function(event){
    alert("Clicked event === "+event.title);
};
var events = [
    {title: 'All Day Event',start: new Date('Sun Dec 17 2017 09:00:00 GMT+0530 (IST)')},
    {title: 'Long Event',start: new Date('Thu Dec 21 2017 10:00:00 GMT+0530 (IST)'),end: new Date('Thu Dec 21 2017 17:00:00 GMT+0530 (IST)')},
    {id: 999,title: 'Repeating Event',start: new Date('Mon Dec 4 2017 09:00:00 GMT+0530 (IST)'),allDay: false}
];
$scope.eventSources = [events];

When I tried to verify the calendar in browser it is throwing following error

TypeError: calendar.fullCalendar is not a function
at Scope.scope.initCalendar (calendar.js:286)
at Object.fn (calendar.js:358)
at Scope.$digest (angular.js:15896)
at Scope.$apply (angular.js:16160)
at WindowsCtrl.window.showDialog.$scope.showDialog (controller.js:690)
at HTMLSpanElement.onclick (VM4670 windows:1)

Could someone please help me to resolve this issue.


问:
Convert formatted string to datetime
I have a dataframe with a column that has been formatted as "%w-%U-%Y" (Weekday number-Week number-Year)

I'm currently doing the following to convert it to datetime format:

```<code>for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')
</code>```

Is there a more efficient way of doing this?

答:
Use to_datetime:

```<code>df['DWY'] = pd.to_datetime(df['DWY'],format='%w-%U-%Y')
</code>```

Title: Convert formatted string to datetime

Body:
I have a dataframe with a column that has been formatted as "%w-%U-%Y" (Weekday number-Week number-Year)

I'm currently doing the following to convert it to datetime format:

for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')

Is there a more efficient way of doing this?

Body:
Use to_datetime:

df['DWY'] = pd.to_datetime(df['DWY'],format='%w-%U-%Y')


问:
Android deep linking from uri
I am implementing android deep-linking concept and its working fine and my question is, I want to redirect the link to my play store application page if the app is not installed in the mobile.

Please guide me to find it out, Thanks.

答: I would suggest using this Branch IO. It's much easier to implement in your android app. Follow this tutorial : branch.io deep-linking</p>

Title: Android deep linking from uri


问:
WordPress cannot automatically upgrade after latest version is installed
all. I am trying to update WordPress to the latest version(4.9.1). The installation of new version of WordPress seems to be updated successfully as show in the picture. Except, my site was redirected to previous version's (4.9) about page after installation, and from the dashboard my site still shows the information of 'update available'. I double checked the version.php under wp-include. It shows the latest version number(4.9.1). I am wondering why my site doesn't detect the upgrade of wordpress? Appreciate if any one can advise the problem. Thank you.

Step 1: click the 'update now' to update WP.

Step 2: Update information page. It shows successful installation.

Step 3: Automatically redirect to version about page.

Step 4: Dashboard still showing old version number and prompt new version available.

Step 5: check version.php.

答:
To whom it may concern. It was the cache issue on my server. After flushing the cache, it works.

Thanks.


问:
Resume powershell script after reboot
I have a lot of articles about this subject but none of it is understandable.

My request is very simple. I have two part of my codes ; First of all Code 1 should be work and windows should be restarted. After reboot completion, Code 2 should be work. This process should be done silently at background. Powershell version is 4.0 ( Win 2012 R2 )

CODE 1 - This code is changing Computer Primary DNS Suffix.

```<code>$computerName = $env:computername

$DNSSuffix = "abc.com"

$oldDNSSuffix = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name "NV Domain")."NV Domain"

#Update primary DNS Suffix for FQDN
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name Domain -Value $DNSSuffix
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name "NV Domain" -Value $DNSSuffix

#Update DNS Suffix Search List - Win8/2012 and above - if needed
#Set-DnsClientGlobalSetting -SuffixSearchList $oldDNSSuffix,$DNSSuffix

#Update AD's SPN records for machine if part of an AD domain
if ((gwmi win32_computersystem).partofdomain -eq $true) {
     $searchAD = new-object System.DirectoryServices.DirectorySearcher
     $searchAD.filter = "(&(objectCategory=computer)(cn=$($computerName)))"
     $searchADItem = $searchAD.FindAll() | select -first 1
     $adObj= [ADSI] $searchADItem.Path
     $oldadObjSPN = $searchADItem.Properties.serviceprincipalname
     $adObj.Put('serviceprincipalname',($oldadObjSPN -replace $oldDNSSuffix, $DNSSuffix))
     $oldadObjDNS = $searchADItem.Properties.dnsHostName
     $adObj.Put('dnsHostName',($oldadObjDNS -replace $oldDNSSuffix, $DNSSuffix))
     $adObj.setinfo()
     #$adObj.Get('serviceprincipalname')
     #$adObj.Get('dnsHostName')
}
</code>```

CODE 2 - Installing Terminal Services on this computer

```<code>Import-Module RemoteDesktop
Add-WindowsFeature -Name RDS-RD-Server  -IncludeAllSubFeature
Add-WindowsFeature -Name RDS-Licensing  -IncludeAllSubFeature
</code>```

答:
powershell commands are very complicated, i decided to do this with batch file.

Resume batch script after computer restart

Title: Resume powershell script after reboot

Body:
I have a lot of articles about this subject but none of it is understandable.

My request is very simple. I have two part of my codes ; First of all Code 1 should be work and windows should be restarted. After reboot completion, Code 2 should be work. This process should be done silently at background. Powershell version is 4.0 ( Win 2012 R2 )

CODE 1 - This code is changing Computer Primary DNS Suffix.

$computerName = $env:computername

$DNSSuffix = "abc.com"

$oldDNSSuffix = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name "NV Domain")."NV Domain"

#Update primary DNS Suffix for FQDN
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name Domain -Value $DNSSuffix
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\" -Name "NV Domain" -Value $DNSSuffix

#Update DNS Suffix Search List - Win8/2012 and above - if needed
#Set-DnsClientGlobalSetting -SuffixSearchList $oldDNSSuffix,$DNSSuffix

#Update AD's SPN records for machine if part of an AD domain
if ((gwmi win32_computersystem).partofdomain -eq $true) {
     $searchAD = new-object System.DirectoryServices.DirectorySearcher
     $searchAD.filter = "(&(objectCategory=computer)(cn=$($computerName)))"
     $searchADItem = $searchAD.FindAll() | select -first 1
     $adObj= [ADSI] $searchADItem.Path
     $oldadObjSPN = $searchADItem.Properties.serviceprincipalname
     $adObj.Put('serviceprincipalname',($oldadObjSPN -replace $oldDNSSuffix, $DNSSuffix))
     $oldadObjDNS = $searchADItem.Properties.dnsHostName
     $adObj.Put('dnsHostName',($oldadObjDNS -replace $oldDNSSuffix, $DNSSuffix))
     $adObj.setinfo()
     #$adObj.Get('serviceprincipalname')
     #$adObj.Get('dnsHostName')
}

CODE 2 - Installing Terminal Services on this computer

Import-Module RemoteDesktop
Add-WindowsFeature -Name RDS-RD-Server  -IncludeAllSubFeature
Add-WindowsFeature -Name RDS-Licensing  -IncludeAllSubFeature


答:
It can be done as follows:

```<code>df['DWY'] = df['Date-Time'].dt.strftime('%U-%Y')
df['DWY'] = '3-' + df['DWY'].astype(str)
for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')
</code>```

However if there's a more efficient way of doing this, please let me know.

EDIT:
The for loop can be replaced by this:

```<code>df['DWY'] = pd.to_datetime(df['DWY'],format='%w-%U-%Y')
</code>```

Title: Set month value for entire week as mid-week day month value

Body:
I have the following pandas.Dataframe:

Date-Time           Week Month
2017-07-29 16:05:00 30  Jul-17
2017-07-29 23:58:00 30  Jul-17
2017-07-30 04:46:00 31  Jul-17
2017-07-30 10:57:00 31  Jul-17
2017-07-31 09:36:00 31  Jul-17
2017-07-31 10:46:00 31  Jul-17
2017-08-01 09:06:00 31  Aug-17
2017-08-01 09:13:00 31  Aug-17
2017-08-02 16:02:00 31  Aug-17
2017-08-02 16:06:00 31  Aug-17
2017-08-02 16:55:00 31  Aug-17
2017-08-02 18:57:00 31  Aug-17
2017-08-02 21:56:00 31  Aug-17
2017-08-03 08:49:00 31  Aug-17
2017-08-03 14:16:00 31  Aug-17
2017-08-04 09:09:00 31  Aug-17
2017-08-04 10:08:00 31  Aug-17
2017-08-05 11:24:00 31  Aug-17
2017-08-05 12:42:00 31  Aug-17
2017-08-06 03:47:00 32  Aug-17
2017-08-06 03:55:00 32  Aug-17
2017-08-07 08:57:00 32  Aug-17
2017-08-07 11:35:00 32  Aug-17

Is there a way I can normalize the month value for each week to be the value of the month to which the mid-week day (Wednesday) belongs?

In the above dataframe, Wednesday of week 31 lies in August, so the month column for week 31 should be as follows:

Date-Time           Week Month
2017-07-29 16:05:00 30  Jul-17
2017-07-29 23:58:00 30  Jul-17
2017-07-30 04:46:00 31  Aug-17
2017-07-30 10:57:00 31  Aug-17
2017-07-31 09:36:00 31  Aug-17
2017-07-31 10:46:00 31  Aug-17
2017-08-01 09:06:00 31  Aug-17
2017-08-01 09:13:00 31  Aug-17
2017-08-02 16:02:00 31  Aug-17
2017-08-02 16:06:00 31  Aug-17
2017-08-02 16:55:00 31  Aug-17
2017-08-02 18:57:00 31  Aug-17
2017-08-02 21:56:00 31  Aug-17
2017-08-03 08:49:00 31  Aug-17
2017-08-03 14:16:00 31  Aug-17
2017-08-04 09:09:00 31  Aug-17
2017-08-04 10:08:00 31  Aug-17
2017-08-05 11:24:00 31  Aug-17
2017-08-05 12:42:00 31  Aug-17
2017-08-06 03:47:00 32  Aug-17
2017-08-06 03:55:00 32  Aug-17
2017-08-07 08:57:00 32  Aug-17
2017-08-07 11:35:00 32  Aug-17

Please note that, both the Week and Month column of the dataframe are derived from the Date-Time column of the same dataframe.

Body:
It can be done as follows:

df['DWY'] = df['Date-Time'].dt.strftime('%U-%Y')
df['DWY'] = '3-' + df['DWY'].astype(str)
for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')

However if there's a more efficient way of doing this, please let me know.

EDIT:
The for loop can be replaced by this:

df['DWY'] = pd.to_datetime(df['DWY'],format='%w-%U-%Y')


问:
Custom property editor for Web parts in SharePoint
I have created a custom WebPart that has some configuration properties. The values for these properties are a Site URL and list name. I want to show a drop down list with all site names and lists for the selected sites. How can I get to show a custom editor component for a property in SharePoint? I don't want to get the default text editor.</p>

答:
You will want to create a custom ToolPart.  Here is a guide: http://sharepoint-insight.blogspot.com/2008/10/sharepoint-creating-web-part-with.html

Basically in your WebPart code you will need to override the GetToolParts function and return a ToolPart[]

Change your toolpart constructor to accept an SPWeb object (pass it the SPContext.Current.Web object from your Web Part). To get the list of lists, in your toolpart you will need to create a dropdownlist inside your CreateChildControls() method. Using the SPWeb object you got from the Constructor you can use a for each to get all the lists for the current site.

So in your web part do this:

```<code>public override ToolPart[] GetToolParts()
{
    ToolPart[] tps = new ToolPart[3];

    WebPartToolPart wptp = new WebPartToolPart();
    CustomPropertyToolPart cptp = new CustomPropertyToolPart();
    tps(0) = cptp;
    tps(1) = wptp;
    tps(2) = new ListSelectionToolPart(SPContext.Current.Web, "List Settings");

    return tps;
}

private string _TargetListGUID;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(false)]
[WebDisplayName("Target List GUID")]
[WebDescription("GUID of the Target List")]
[SPWebCategoryName("Internal")]
public string TargetListGUID {
  get { return _TargetListGUID; }
  set { _TargetListGUID = value; }
}
</code>```

Add a class like this:

```<code>public class ListSelectionToolPart : WebPartPages.ToolPart
{
  private SPWeb _web;
  protected DropDownList ddlLists;

  public New(SPWeb Web, string ToolTitle)
  {
    _web = System.Web;
    this.Title = ToolTitle;
  }

  protected override void CreateChildControls()
  {
        Literal litLists = new Literal { Text = "<b>List:</b><br />" };
        ddlLists = new DropDownList {
        AutoPostBack = true,
        ID = "ddlLists"
        };
        ddlLists.Style.Add("width", "100%");
        foreach (SPList list in _web.Lists)
        {
         ddlLists.Items.Add(new ListItem(list.Title, list.ID.ToString()));
        }
        this.Controls.Add(litLists);
        this.Controls.Add(ddlLists);
  }

  public override void ApplyChanges()
  {
    (this.ParentToolPane.SelectedWebPart as MyWebPart).TargetListGUID = ddlLists.SelectedValue;
  }

}
</code>```

The above code assumes the name of your WebPart is MyWebPart and that there is a TargetListGUID property. To add a site selection you can do pretty much the same thing in the toolpart (add another dropdownlist). If you use the SelectionChanged event on it you can use it to populate the lists dropdown.

Body:
You will want to create a custom ToolPart.  Here is a guide: http://sharepoint-insight.blogspot.com/2008/10/sharepoint-creating-web-part-with.html

Basically in your WebPart code you will need to override the GetToolParts function and return a ToolPart[]

Change your toolpart constructor to accept an SPWeb object (pass it the SPContext.Current.Web object from your Web Part). To get the list of lists, in your toolpart you will need to create a dropdownlist inside your CreateChildControls() method. Using the SPWeb object you got from the Constructor you can use a for each to get all the lists for the current site.

So in your web part do this:

public override ToolPart[] GetToolParts()
{
    ToolPart[] tps = new ToolPart[3];

    WebPartToolPart wptp = new WebPartToolPart();
    CustomPropertyToolPart cptp = new CustomPropertyToolPart();
    tps(0) = cptp;
    tps(1) = wptp;
    tps(2) = new ListSelectionToolPart(SPContext.Current.Web, "List Settings");

    return tps;
}

private string _TargetListGUID;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(false)]
[WebDisplayName("Target List GUID")]
[WebDescription("GUID of the Target List")]
[SPWebCategoryName("Internal")]
public string TargetListGUID {
  get { return _TargetListGUID; }
  set { _TargetListGUID = value; }
}

Add a class like this:

public class ListSelectionToolPart : WebPartPages.ToolPart
{
  private SPWeb _web;
  protected DropDownList ddlLists;

  public New(SPWeb Web, string ToolTitle)
  {
    _web = System.Web;
    this.Title = ToolTitle;
  }

  protected override void CreateChildControls()
  {
        Literal litLists = new Literal { Text = "<b>List:</b><br />" };
        ddlLists = new DropDownList {
        AutoPostBack = true,
        ID = "ddlLists"
        };
        ddlLists.Style.Add("width", "100%");
        foreach (SPList list in _web.Lists)
        {
         ddlLists.Items.Add(new ListItem(list.Title, list.ID.ToString()));
        }
        this.Controls.Add(litLists);
        this.Controls.Add(ddlLists);
  }

  public override void ApplyChanges()
  {
    (this.ParentToolPane.SelectedWebPart as MyWebPart).TargetListGUID = ddlLists.SelectedValue;
  }

}

The above code assumes the name of your WebPart is MyWebPart and that there is a TargetListGUID property. To add a site selection you can do pretty much the same thing in the toolpart (add another dropdownlist). If you use the SelectionChanged event on it you can use it to populate the lists dropdown.


问:
compare and merge output of different files with conditions
I have three files as below:

File1.txt

```<code>Add,abc,5
Add,xyz,10
Del,test,14
</code>```

File2.txt

```<code>abc,123,567
abc,123,568
xyz,234,879
xyz,234,880
test,435,227
test,435,228
</code>```

File3.txt

```<code>23
28
30
40
50
36
</code>```

Where final desired output should looks like:

```<code>abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14
</code>```

final output should be merged on comparing (abc,xyz,test).
I tried merging above files using "paste -d" command.

答:
Try:

```<code>$ paste -d "" <(paste -d, File2.txt File3.txt) <(sed 's/^/\n,/' File1.txt )
abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14
</code>```

How it works

The first step is that you need to combine File2.txt with File3.txt:

```<code>$ paste -d, File2.txt File3.txt
abc,123,567,23
abc,123,568,28
xyz,234,879,30
xyz,234,880,40
test,435,227,50
test,435,228,36
</code>```

Secondly, we need to doublespace File1.txt like this:

```<code>$ sed 's/^/\n,/' File1.txt

,Add,abc,5

,Add,xyz,10

,Del,test,14
</code>```

Lastly we need to combine both of the above together with another paste command:

```<code>$ paste -d "" <(paste -d, File2.txt File3.txt) <(sed 's/^/\n,/' File1.txt)
abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14
</code>```

paste expects files for arguments.  We have commands.  The construct <(...) converts the output of commands like paste -d, File2.txt File3.txt into file-like objects that paste can use.  <(...) is called process substitution.

We could have done the same thing using temporary files:

```<code>$ paste -d, File2.txt File3.txt >tmp1; sed 's/^/\n,/' File1.txt >tmp2; paste -d "" tmp1 tmp2
abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14
</code>```

Process substitution eliminates the need for temporary files.

Body:
I have three files as below:

File1.txt

Add,abc,5
Add,xyz,10
Del,test,14

File2.txt

abc,123,567
abc,123,568
xyz,234,879
xyz,234,880
test,435,227
test,435,228

File3.txt

23
28
30
40
50
36

Where final desired output should looks like:

abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14

final output should be merged on comparing (abc,xyz,test).
I tried merging above files using "paste -d" command.

Body:
Try:

$ paste -d "" <(paste -d, File2.txt File3.txt) <(sed 's/^/\n,/' File1.txt )
abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14

How it works

The first step is that you need to combine File2.txt with File3.txt:

$ paste -d, File2.txt File3.txt
abc,123,567,23
abc,123,568,28
xyz,234,879,30
xyz,234,880,40
test,435,227,50
test,435,228,36

Secondly, we need to doublespace File1.txt like this:

$ sed 's/^/\n,/' File1.txt

,Add,abc,5

,Add,xyz,10

,Del,test,14

Lastly we need to combine both of the above together with another paste command:

$ paste -d "" <(paste -d, File2.txt File3.txt) <(sed 's/^/\n,/' File1.txt)
abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14

paste expects files for arguments.  We have commands.  The construct <(...) converts the output of commands like paste -d, File2.txt File3.txt into file-like objects that paste can use.  <(...) is called process substitution.

We could have done the same thing using temporary files:

$ paste -d, File2.txt File3.txt >tmp1; sed 's/^/\n,/' File1.txt >tmp2; paste -d "" tmp1 tmp2
abc,123,567,23
abc,123,568,28,Add,abc,5
xyz,234,879,30
xyz,234,880,40,Add,xyz,10
test,435,227,50
test,435,228,36,Del,test,14

Process substitution eliminates the need for temporary files.


问:
How to Accurate FusedApi between 10 meter
Incorrect Fused Location API location LAtitiude Longitude.Is there any API to provide accurate location?</p>

答:
If I understand right you want to snap to the road or use a Map Matching algorithm. For that task you can use e.g.

GoogleMapsRoads API,

MapBox Map Matching API

Graphhopper Map-Matching

ContentLicense: CC BY-SA 4.0


问:
How to override a superclass __init__ argument?
How do I override the super class attribute?
In the example below, I want to use some other value for name.

```<code>class A:
    def __init__(self,name):
        self.name=name

class B(A):
    def __init__(self, config, address, phone):
        super(B, self).__init__(name)
        self.address=address
        self.phone=phone
        self.config=config
        self.name=self.config.name + "__value_only"
</code>```

答:
Just pass the desired "other" value to the super(...).__init__(). Also, name in your example is not a class, but an instance attribute:

```<code>class B(A):
    def __init__(self, config, address, phone):
        super(B, self).__init__(config.name + "__value_only")
        self.address=address
        self.phone=phone
        self.config=config
</code>```

Body:
How do I override the super class attribute?
In the example below, I want to use some other value for name.

class A:
    def __init__(self,name):
        self.name=name

class B(A):
    def __init__(self, config, address, phone):
        super(B, self).__init__(name)
        self.address=address
        self.phone=phone
        self.config=config
        self.name=self.config.name + "__value_only"

Body:
Just pass the desired "other" value to the super(...).__init__(). Also, name in your example is not a class, but an instance attribute:

class B(A):
    def __init__(self, config, address, phone):
        super(B, self).__init__(config.name + "__value_only")
        self.address=address
        self.phone=phone
        self.config=config


问:
How to implement a mechanism for users to block abusive users using firebase with help of JSQMessagesViewController in swift 4
I have implemented one-to-one chat using "Firebase" with the help of "JSQMessagesViewController" in swift 4 and I have submitted my app to Appstore. But, app gets rejected and asking for "A mechanism for users to block abusive users".

So, how I can achieve this mechanism in swift 4. I am not able to implement it, any code/suggestions will more appreciate.

Thank you in advance.

答:
For JSQMessage you can make use of provided delegate method

```<code>override func collectionView(collectionView: JSQMessagesCollectionView, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
    super.collectionView(collectionView, didTapMessageBubbleAtIndexPath: indexPath)
    print("Present option to block here.")
}
</code>```

using this you can get message index and perform any suitable Action

Present a Screen or any Action

You need to get USERID to whom you will block

Body:
For JSQMessage you can make use of provided delegate method

override func collectionView(collectionView: JSQMessagesCollectionView, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
    super.collectionView(collectionView, didTapMessageBubbleAtIndexPath: indexPath)
    print("Present option to block here.")
}

using this you can get message index and perform any suitable Action

Present a Screen or any Action

You need to get USERID to whom you will block


问:
xml format needed in rails 3.0.1??? answer should be NO
what the heck am I doing wrong.

I changed nothing, but now that it is 2011 this call doesn't work as it used to.

Using Active Resource, I can make the following call:

```
>> Member.find(:all, :params => {:code => "1stb48024957856464d436e79ad9d7bc0c2d46d5a02"})
GET http://localhost:3000/members.xml?code=1stb48024957856464d436e79ad9d7bc0c2d46d5a02
--> 500 Internal Server Error  (1601 371ms)
ActiveResource::ServerError: Failed with 500 Internal Server Error
```

As you can see, I get a 500 error.  So i go to my server to where i'm making the call.

The code is here in the controller:

```<code>def index
  @store = Store.first
  @members = @store.members.find_by_code(params[:code])

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render @members.to_xml } # i also tried :xml => @members but that screws up too the same way.
  end
end
</code>```

But below is the stack trace.  It's doing my head in why this just stopped working.

```<code>
Started GET "/members.xml?code=1stb48024957856464d436e79ad9d7bc0c2d46d5a02" for 127.0.0.1 at 2011-01-21 13:58:00 -0500
  Processing by MembersController#index as XML
  Parameters: {"code"=>"1stb48024957856464d436e79ad9d7bc0c2d46d5a02"}
  SQL (0.8ms)  SHOW TABLES
  Store Load (0.4ms)  SELECT `stores`.* FROM `stores` LIMIT 1
  Member Load (0.8ms)  SELECT `members`.* FROM `members` WHERE (`members`.store_id = 1) AND (`members`.`code` = '1stb48024957856464d436e79ad9d7bc0c2d46d5a02') LIMIT 1
Completed   in 268ms

ActionView::MissingTemplate (Missing template

  4
  <code>1stb48024957856464d436e79ad9d7bc0c2d46d5a02</code>
  2010-12-02T20:14:54Z
  3
  70.2
  10
  http://fnd.nu/7
  1
  2010-12-09T15:37:42Z

 with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:xml], :locale=>[:en, :en]} in view paths "/Users/nerb/current_project/fund/app/views", "/Users/nerb/.rvm/gems/ruby-1.9.2-p0/gems/devise-1.1.3/app/views", "/Users/nerb/current_project/fund", "/"):
  app/controllers/members_controller.rb:16:in `block (2 levels) in index'
  app/controllers/members_controller.rb:14:in `index'

Rendered /Users/nerb/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (31.6ms)

</code>```

Any thoughts are appreciated.  I thought xml formats were expempt from render?  Jose said as much in this lighthouse ticket, but i can't find what he is talking about.

UPDATE:

Andy that worked as the Server seems to be sending a 200 so thanks, but now i get this error:

```
Member.find(:all, :params => {:code => "1stb48024957856464d436e79ad9d7bc0c2d46d5a02"})
GET http://localhost:3000/members.xml?code=1stb48024957856464d436e79ad9d7bc0c2d46d5a02
--> 200 OK  (472 399ms)
NoMethodError: undefined method `collect!' for #
    from /Users/nerb/.rvm/gems/ruby-1.8.7-p249/gems/activeresource-2.3.5/lib/active_resource/base.rb:662:in `instantiate_collection'
    from /Users/nerb/.rvm/gems/ruby-1.8.7-p249/gems/activeresource-2.3.5/lib/active_resource/base.rb:639:in `find_every'
    from /Users/nerb/.rvm/gems/ruby-1.8.7-p249/gems/activeresource-2.3.5/lib/active_resource/base.rb:582:in `find'
    from (irb):1

```

Thoughts?  should it just be an array coming back, even if it's ONE record?

答:
render :xml => @members is the way to go.

Make sure you reload/restart your server after making this change if in production.

Body:
what the heck am I doing wrong.

I changed nothing, but now that it is 2011 this call doesn't work as it used to.

Using Active Resource, I can make the following call:

>> Member.find(:all, :params => {:code => "1stb48024957856464d436e79ad9d7bc0c2d46d5a02"})
GET http://localhost:3000/members.xml?code=1stb48024957856464d436e79ad9d7bc0c2d46d5a02
--> 500 Internal Server Error  (1601 371ms)
ActiveResource::ServerError: Failed with 500 Internal Server Error

As you can see, I get a 500 error.  So i go to my server to where i'm making the call.

The code is here in the controller:

def index
  @store = Store.first
  @members = @store.members.find_by_code(params[:code])

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render @members.to_xml } # i also tried :xml => @members but that screws up too the same way.
  end
end

But below is the stack trace.  It's doing my head in why this just stopped working.

Started GET "/members.xml?code=1stb48024957856464d436e79ad9d7bc0c2d46d5a02" for 127.0.0.1 at 2011-01-21 13:58:00 -0500
  Processing by MembersController#index as XML
  Parameters: {"code"=>"1stb48024957856464d436e79ad9d7bc0c2d46d5a02"}
  SQL (0.8ms)  SHOW TABLES
  Store Load (0.4ms)  SELECT `stores`.* FROM `stores` LIMIT 1
  Member Load (0.8ms)  SELECT `members`.* FROM `members` WHERE (`members`.store_id = 1) AND (`members`.`code` = '1stb48024957856464d436e79ad9d7bc0c2d46d5a02') LIMIT 1
Completed   in 268ms

ActionView::MissingTemplate (Missing template

  4
  1stb48024957856464d436e79ad9d7bc0c2d46d5a02
  2010-12-02T20:14:54Z
  3
  70.2
  10
  http://fnd.nu/7
  1
  2010-12-09T15:37:42Z

 with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:xml], :locale=>[:en, :en]} in view paths "/Users/nerb/current_project/fund/app/views", "/Users/nerb/.rvm/gems/ruby-1.9.2-p0/gems/devise-1.1.3/app/views", "/Users/nerb/current_project/fund", "/"):
  app/controllers/members_controller.rb:16:in `block (2 levels) in index'
  app/controllers/members_controller.rb:14:in `index'

Rendered /Users/nerb/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (31.6ms)

Any thoughts are appreciated.  I thought xml formats were expempt from render?  Jose said as much in this lighthouse ticket, but i can't find what he is talking about.

UPDATE:

Andy that worked as the Server seems to be sending a 200 so thanks, but now i get this error:

Member.find(:all, :params => {:code => "1stb48024957856464d436e79ad9d7bc0c2d46d5a02"})
GET http://localhost:3000/members.xml?code=1stb48024957856464d436e79ad9d7bc0c2d46d5a02
--> 200 OK  (472 399ms)
NoMethodError: undefined method `collect!' for #
    from /Users/nerb/.rvm/gems/ruby-1.8.7-p249/gems/activeresource-2.3.5/lib/active_resource/base.rb:662:in `instantiate_collection'
    from /Users/nerb/.rvm/gems/ruby-1.8.7-p249/gems/activeresource-2.3.5/lib/active_resource/base.rb:639:in `find_every'
    from /Users/nerb/.rvm/gems/ruby-1.8.7-p249/gems/activeresource-2.3.5/lib/active_resource/base.rb:582:in `find'
    from (irb):1

Thoughts?  should it just be an array coming back, even if it's ONE record?


问:
Python hyper parameter for rounding float numbers
This question must be an easy one but I couldn't find anything about it here.

Is there a way in python to define or use 1 command line so that every float number across the script will be rounded by X digists.

For example if I define:

```<code>max_float_digits = 4
</code>```

and the program wants to outputs or print the following number 5.1355895682, all I will see is 5.1356

This necessity rises when some module return this value to my script:

```<code>[('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664), ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618), ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347), ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996), ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993), ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472), ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117)]
</code>```

Instead of trying to access each value and round them I'd like a 1 command line that will round them all for me.

答:
How about having you own method defined and put it as a decorator for each of the methods you need output in the format you want :

Try out this sample :

```<code>import math
max_float_digits = 4
v = 8.8333333333333339
def hyper(v,max_no_float):
    rounding = pow(10,max_no_float)
    return (math.ceil(v * rounding) / rounding)
print hyper(v,max_float_digits)
print hyper(v,3)
</code>```

Output :

```<code>>>>8.8334
>>>8.834
</code>```

Give it a try .

Body:
This question must be an easy one but I couldn't find anything about it here.

Is there a way in python to define or use 1 command line so that every float number across the script will be rounded by X digists.

For example if I define:

max_float_digits = 4

and the program wants to outputs or print the following number 5.1355895682, all I will see is 5.1356

This necessity rises when some module return this value to my script:

[('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664), ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618), ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347), ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996), ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993), ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472), ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117)]

Instead of trying to access each value and round them I'd like a 1 command line that will round them all for me.

Body:
How about having you own method defined and put it as a decorator for each of the methods you need output in the format you want :

Try out this sample :

import math
max_float_digits = 4
v = 8.8333333333333339
def hyper(v,max_no_float):
    rounding = pow(10,max_no_float)
    return (math.ceil(v * rounding) / rounding)
print hyper(v,max_float_digits)
print hyper(v,3)

Output :

>>>8.8334
>>>8.834

Give it a try .


问:
horizontal scroll on android chrome, works in funny way
in my site I have a responsive table, it is work fine on all browsers on Desktop (windows and Linux), but when I open the page with android chrome (and also ios browser) vertical scroll work just fine, but horizontal is messed up,

it works on last three rows of my table,

it doesn't work on upper rows of table

if I scroll down to see more rows, the problem still exist

I find one more interesting things, when I'm on the page, and horizontal scroll doesn't work well, and I open the setting of browser and closed it, after this horizontal scroll work fine on all rows.

address of the page:

http://yellowpart.ir/?product_cat=%D8%B4%D8%A7%D8%B3%DB%8C-%D9%BE%D8%A7%DB%8C%DB%8C%D9%86&product_list=149

答:
It was because of "top" attribute, my table css was:

```<code>table {
         top: 70vh;
}
</code>```

and it worked fine on pc, but somehow on android chrome, although I did scroll page and table to bottom of it but the table in first 70% of screen's height didn't worked, so I changed the code to :

```<code>table{
      padding-top: 70vh;
}
</code>```

and it start to work fine on both desktop and android chrome.

Body:
It was because of "top" attribute, my table css was:

table {
         top: 70vh;
}

and it worked fine on pc, but somehow on android chrome, although I did scroll page and table to bottom of it but the table in first 70% of screen's height didn't worked, so I changed the code to :

table{
      padding-top: 70vh;
}

and it start to work fine on both desktop and android chrome.


问:
3 duplicated symbols in PHP
Other languages are fine except PHP.

How to fix this?

Installed Extensions

答: I solved this. Just disable some extensions</p>

Title: 3 duplicated symbols in PHP


问:
when uncheck all the childs parent check box also should be unchecked using jquery
I have nested checkbox list items. In my case, if I select parent, all the child's checkboxes checked fine.

If I uncheck parent-child checkboxes unchecking fine and all the child checkboxes check parent checkbox is checking fine.

But my problem is, if I uncheck all the child checkboxes parent checkbox is still checked state only.

I'm new to jQuery and javascript.where to change my code.Any help would be appreciated.Thanks in Advance.

$(function() {
  $('li :checkbox').on('click', function() {
    var $chk = $(this),
      $li = $chk.closest('li'),
      $ul, $parent;
    if ($li.has('ul')) {
      $li.find(':checkbox').not(this).prop('checked', this.checked)
    }
    do {
      $ul = $li.parent();
      $parent = $ul.siblings(':checkbox');
      if ($chk.is(':checked')) {
        $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
      } else {
        $parent.prop('checked', true)
      }
      $chk = $parent;
      $li = $chk.closest('li');
    } while ($ul.is(':not(.someclass)'));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="1" class="tab-pane fade in active">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='5'>A1
    <ul>
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='26'>a2
        <ul>
          <li class='chkbox' ;>
            <input type='checkbox' class='myCheckbox' name='names[]' value='29'>a3
            <li class='chkbox' ;>
              <input type='checkbox' class='myCheckbox' name='names[]' value='30'>a4
        </ul>
        <li class='chkbox'>
          <input type='checkbox' class='myCheckbox' name='names[]' value='25'>a1
          <ul>
            <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='27'>aaaaaa
              <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='28'>abbbbbb
          </ul>
    </ul>
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='6'>A2
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='7'>A3
        <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='8'>A4
          <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='9'>A5
            <div style="clear:both">
            </div>
</div>
<div id="2" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='10'> B1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='11'>B2
      <div style="clear:both">
      </div>
</div>
<div id="3" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='12'>C1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='13'>C2
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='14'>C3
        <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='17'>A6
          <ul>
            <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='19'>A8
              <ul>
                <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='21'>A10
                  <ul>
                    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='23'>A13
                      <ul>
                        <li class='chkbox' ;><input type='checkbox' name='names[]' value='31'>jjj
                          <li class='chkbox' ;><input type='checkbox' name='names[]' value='32'>kkk
                      </ul>
                      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='24'>A14
                        <ul>
                        </ul>
                  </ul>
                  <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='22'>A11
              </ul>
              <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='20'>A9
          </ul>
          <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='18'>A7
            <div style="clear:both"></div>
</div>
<div id="4" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='15'>D1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='16'>D2
      <div style="clear:both"></div></code>```

答:
You just forgot one corner case below one

if($ul.get(0))
    if($ul.find(':checkbox:checked').length !== 0)
        $parent.prop('checked', true)

$(function() {
  $('li :checkbox').on('click', function() {
    var $chk = $(this),
      $li = $chk.closest('li'),
      $ul, $parent;
    if ($li.has('ul')) {
      $li.find(':checkbox').not(this).prop('checked', this.checked)
    }
    do {
      $ul = $li.parent();
      $parent = $ul.siblings(':checkbox');
      if ($chk.is(':checked')) {
        $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
      } else {
        $parent.prop('checked', false)
      }
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
      if($ul.get(0))
   if($ul.find(':checkbox:checked').length !== 0)
          $parent.prop('checked', true)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
      $chk = $parent;
      $li = $chk.closest('li');

    } while ($ul.is(':not(.someclass)'));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="1" class="tab-pane fade in active">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='5'>A1
    <ul>
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='26'>a2
        <ul>
          <li class='chkbox' ;>
            <input type='checkbox' class='myCheckbox' name='names[]' value='29'>a3
            <li class='chkbox' ;>
              <input type='checkbox' class='myCheckbox' name='names[]' value='30'>a4
        </ul>
        <li class='chkbox'>
          <input type='checkbox' class='myCheckbox' name='names[]' value='25'>a1
          <ul>
            <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='27'>aaaaaa
              <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='28'>abbbbbb
          </ul>
    </ul>
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='6'>A2
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='7'>A3
        <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='8'>A4
          <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='9'>A5
            <div style="clear:both">
            </div>
</div>
<div id="2" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='10'> B1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='11'>B2
      <div style="clear:both">
      </div>
</div>
<div id="3" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='12'>C1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='13'>C2
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='14'>C3
        <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='17'>A6
          <ul>
            <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='19'>A8
              <ul>
                <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='21'>A10
                  <ul>
                    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='23'>A13
                      <ul>
                        <li class='chkbox' ;><input type='checkbox' name='names[]' value='31'>jjj
                          <li class='chkbox' ;><input type='checkbox' name='names[]' value='32'>kkk
                      </ul>
                      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='24'>A14
                        <ul>
                        </ul>
                  </ul>
                  <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='22'>A11
              </ul>
              <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='20'>A9
          </ul>
          <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='18'>A7
            <div style="clear:both"></div>
</div>
<div id="4" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='15'>D1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='16'>D2
      <div style="clear:both"></div></code>```

Body:
I have nested checkbox list items. In my case, if I select parent, all the child's checkboxes checked fine.

If I uncheck parent-child checkboxes unchecking fine and all the child checkboxes check parent checkbox is checking fine.

But my problem is, if I uncheck all the child checkboxes parent checkbox is still checked state only.

I'm new to jQuery and javascript.where to change my code.Any help would be appreciated.Thanks in Advance.

$(function() {
  $('li :checkbox').on('click', function() {
    var $chk = $(this),
      $li = $chk.closest('li'),
      $ul, $parent;
    if ($li.has('ul')) {
      $li.find(':checkbox').not(this).prop('checked', this.checked)
    }
    do {
      $ul = $li.parent();
      $parent = $ul.siblings(':checkbox');
      if ($chk.is(':checked')) {
        $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
      } else {
        $parent.prop('checked', true)
      }
      $chk = $parent;
      $li = $chk.closest('li');
    } while ($ul.is(':not(.someclass)'));
  });
});

<input type='checkbox' class='myCheckbox' name='names[]' value='5'>A1

<input type='checkbox' class='myCheckbox' name='names[]' value='26'>a2

            <input type='checkbox' class='myCheckbox' name='names[]' value='29'>a3

              <input type='checkbox' class='myCheckbox' name='names[]' value='30'>a4

          <input type='checkbox' class='myCheckbox' name='names[]' value='25'>a1

<input type='checkbox' class='myCheckbox' name='names[]' value='27'>aaaaaa

<input type='checkbox' class='myCheckbox' name='names[]' value='28'>abbbbbb

<input type='checkbox' class='myCheckbox' name='names[]' value='6'>A2

<input type='checkbox' class='myCheckbox' name='names[]' value='7'>A3

<input type='checkbox' class='myCheckbox' name='names[]' value='8'>A4

<input type='checkbox' class='myCheckbox' name='names[]' value='9'>A5

<input type='checkbox' class='myCheckbox' name='names[]' value='10'> B1

<input type='checkbox' class='myCheckbox' name='names[]' value='11'>B2

<input type='checkbox' class='myCheckbox' name='names[]' value='12'>C1

<input type='checkbox' class='myCheckbox' name='names[]' value='13'>C2

<input type='checkbox' class='myCheckbox' name='names[]' value='14'>C3

<input type='checkbox' class='myCheckbox' name='names[]' value='17'>A6

<input type='checkbox' class='myCheckbox' name='names[]' value='19'>A8

<input type='checkbox' class='myCheckbox' name='names[]' value='21'>A10

<input type='checkbox' class='myCheckbox' name='names[]' value='23'>A13

<input type='checkbox' name='names[]' value='31'>jjj

<input type='checkbox' name='names[]' value='32'>kkk

<input type='checkbox' class='myCheckbox' name='names[]' value='24'>A14

<input type='checkbox' class='myCheckbox' name='names[]' value='22'>A11

<input type='checkbox' class='myCheckbox' name='names[]' value='20'>A9

<input type='checkbox' class='myCheckbox' name='names[]' value='18'>A7

<input type='checkbox' class='myCheckbox' name='names[]' value='15'>D1

<input type='checkbox' class='myCheckbox' name='names[]' value='16'>D2

Body:
You just forgot one corner case below one

if($ul.get(0))
    if($ul.find(':checkbox:checked').length !== 0)
        $parent.prop('checked', true)

$(function() {
  $('li :checkbox').on('click', function() {
    var $chk = $(this),
      $li = $chk.closest('li'),
      $ul, $parent;
    if ($li.has('ul')) {
      $li.find(':checkbox').not(this).prop('checked', this.checked)
    }
    do {
      $ul = $li.parent();
      $parent = $ul.siblings(':checkbox');
      if ($chk.is(':checked')) {
        $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
      } else {
        $parent.prop('checked', false)
      }
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
      if($ul.get(0))
   if($ul.find(':checkbox:checked').length !== 0)
          $parent.prop('checked', true)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
      $chk = $parent;
      $li = $chk.closest('li');

    } while ($ul.is(':not(.someclass)'));
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="1" class="tab-pane fade in active">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='5'>A1
    <ul>
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='26'>a2
        <ul>
          <li class='chkbox' ;>
            <input type='checkbox' class='myCheckbox' name='names[]' value='29'>a3
            <li class='chkbox' ;>
              <input type='checkbox' class='myCheckbox' name='names[]' value='30'>a4
        </ul>
        <li class='chkbox'>
          <input type='checkbox' class='myCheckbox' name='names[]' value='25'>a1
          <ul>
            <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='27'>aaaaaa
              <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='28'>abbbbbb
          </ul>
    </ul>
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='6'>A2
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='7'>A3
        <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='8'>A4
          <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='9'>A5
            <div style="clear:both">
            </div>
</div>
<div id="2" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='10'> B1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='11'>B2
      <div style="clear:both">
      </div>
</div>
<div id="3" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='12'>C1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='13'>C2
      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='14'>C3
        <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='17'>A6
          <ul>
            <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='19'>A8
              <ul>
                <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='21'>A10
                  <ul>
                    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='23'>A13
                      <ul>
                        <li class='chkbox' ;><input type='checkbox' name='names[]' value='31'>jjj
                          <li class='chkbox' ;><input type='checkbox' name='names[]' value='32'>kkk
                      </ul>
                      <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='24'>A14
                        <ul>
                        </ul>
                  </ul>
                  <li class='chkbox' ;><input type='checkbox' class='myCheckbox' name='names[]' value='22'>A11
              </ul>
              <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='20'>A9
          </ul>
          <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='18'>A7
            <div style="clear:both"></div>
</div>
<div id="4" class="tab-pane fade">
  <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='15'>D1
    <li class='chkbox'><input type='checkbox' class='myCheckbox' name='names[]' value='16'>D2
      <div style="clear:both"></div>


问:
Paramiko server: Redirect the output of a SUBPROCESS to a channel
I am trying to implement a (local fake) server with paramiko that responds to custom commands just like the original for testing purposes. Mainly copying from the supplied demo server, I managed to come up with this custom method to handle exec_requests for the server implemented via paramiko.ServerInterface:

```<code>def check_channel_exec_request(self,channel,command):
    print("User wants to execute '%s'" %(command))
    comm_main, comm_add = command.decode().split(sep=" ",maxsplit=1)
    if comm_main in self.allowed_commands:
        chout = channel.makefile("w")
        subprocess.Popen(command,stdout=chout)
        return True
        else:
            return False
</code>```

After the server is running via:

```<code>PORT = 50007 # The same port as used by the server
HOST = 'localhost'
host_key = paramiko.RSAKey(filename = <FILEPATH>)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((HOST,PORT))
    sock.listen(1)
    conn, addr = sock.accept() # Connected!
    with conn:
        trans = paramiko.Transport(conn)
        trans.add_server_key(host_key)
        trans.set_subsystem_handler("job",JobHandler)
        server = FakeCluster() # Custom class sublassing paramiko.ServerInterface
        trans.start_server(server=server)
        chan = trans.accept() # Accept authentication from client
        while trans.is_active(): # Do not close until inactive
            time.sleep(1)
        chan.close()
</code>```

the client would try to execute echo 123 in the following manner:

```<code>PORT = 50007 # The same port as used by the server
HOST = 'localhost'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind((HOST,PORT))

    ssh = paramiko.client.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(HOST, PORT,username=<USERNAME>,password=<PASSWORD>)
    ssh.exec_command("echo 123")
</code>```

Right now, I am getting the error trying to execute the subprocess that 'ChannelFile' has no attribute 'fileno'. Furthermore I am wondering how to later execute a python script as a custom command called by exec_command. (Maybe by calling a batchfile that calls the python script?)

答:
your question is really very confusing , here is what i did for communicating with remote server .

local machine : window

Remote Machine :ubuntu

Command on remote machine :'who'

```<code>import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.268.21.26',port=22,username='root',password='default')
stdin,stdout,stderr=ssh.exec_command('who')
output=stdout.readlines()
print '\n'.join(output)

#output
#root    tty7         2017-11-28 14:13 (:0)

#if you wish to execute a python file there , this should work
stdin,stdout,stderr=ssh.exec_command('python file.py')
</code>```

Body:
I am trying to implement a (local fake) server with paramiko that responds to custom commands just like the original for testing purposes. Mainly copying from the supplied demo server, I managed to come up with this custom method to handle exec_requests for the server implemented via paramiko.ServerInterface:

def check_channel_exec_request(self,channel,command):
    print("User wants to execute '%s'" %(command))
    comm_main, comm_add = command.decode().split(sep=" ",maxsplit=1)
    if comm_main in self.allowed_commands:
        chout = channel.makefile("w")
        subprocess.Popen(command,stdout=chout)
        return True
        else:
            return False

After the server is running via:

PORT = 50007 # The same port as used by the server
HOST = 'localhost'
host_key = paramiko.RSAKey(filename = <FILEPATH>)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((HOST,PORT))
    sock.listen(1)
    conn, addr = sock.accept() # Connected!
    with conn:
        trans = paramiko.Transport(conn)
        trans.add_server_key(host_key)
        trans.set_subsystem_handler("job",JobHandler)
        server = FakeCluster() # Custom class sublassing paramiko.ServerInterface
        trans.start_server(server=server)
        chan = trans.accept() # Accept authentication from client
        while trans.is_active(): # Do not close until inactive
            time.sleep(1)
        chan.close()

the client would try to execute echo 123 in the following manner:

PORT = 50007 # The same port as used by the server
HOST = 'localhost'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind((HOST,PORT))

    ssh = paramiko.client.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(HOST, PORT,username=<USERNAME>,password=<PASSWORD>)
    ssh.exec_command("echo 123")

Right now, I am getting the error trying to execute the subprocess that 'ChannelFile' has no attribute 'fileno'. Furthermore I am wondering how to later execute a python script as a custom command called by exec_command. (Maybe by calling a batchfile that calls the python script?)

Body:
your question is really very confusing , here is what i did for communicating with remote server .

local machine : window

Remote Machine :ubuntu

Command on remote machine :'who'

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.268.21.26',port=22,username='root',password='default')
stdin,stdout,stderr=ssh.exec_command('who')
output=stdout.readlines()
print '\n'.join(output)

#output
#root    tty7         2017-11-28 14:13 (:0)

#if you wish to execute a python file there , this should work
stdin,stdout,stderr=ssh.exec_command('python file.py')


问:
XPath:: Get following Sibling
I have following HTML Structure: I am trying to build a robust method to extract second color digest element since there will be many of these tag within the DOM.

```<code><table>
  <tbody>
    <tr bgcolor="#AAAAAA">
    <tr>
    <tr>
    <tr>
    <tr>
      <td>Color Digest </td>
      <td>AgArAQICGQMVBBwTIRQHIwg0GUMURAZTBWQJcwV0AoEDAQ </td>
    </tr>
    <tr>
      <td>Color Digest </td>
      <td>2,43,2,25,21,28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,33,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, </td>
    </tr>
  </tbody>
</table>
</code>```

I am trying to extract the Second "Color Digest" td element that has the decoded value.

I wrote the following xpath but instead of getting the second i am not getting the second td element.

```<code>//td[text() = ' Color Digest ']/following-sibling::td[2]
</code>```

And when I change it to td[2] to td[1] I get both the elements.

答:
You can go for identifying a list of elements with xPath:

```<code>//td[text() = ' Color Digest ']/following-sibling::td[1]
</code>```

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

```<code>List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))
</code>```

Now, you can use the 2nd element as your intended element, which is elements.get(1)

Title: XPath:: Get following Sibling

Body:
I have following HTML Structure: I am trying to build a robust method to extract second color digest element since there will be many of these tag within the DOM.

      Color Digest
      AgArAQICGQMVBBwTIRQHIwg0GUMURAZTBWQJcwV0AoEDAQ

      Color Digest
      2,43,2,25,21,28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,33,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

I am trying to extract the Second "Color Digest" td element that has the decoded value.

I wrote the following xpath but instead of getting the second i am not getting the second td element.

//td[text() = ' Color Digest ']/following-sibling::td[2]

And when I change it to td[2] to td[1] I get both the elements.

Body:
You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)


问:
UWP: ConnectionProfile.GetNetworkUsageAsync doesn't work
I'm trying to get the incoming and outgoing traffic from a WAN Miniport (IKEv2) interface but it doesn't work.
First I'm creating a new VPN profile and then I'm connecting the profile. This works fine. After that I would like to get the incoming and outgoing traffic but I get every time 0. Here is my code

```<code>var internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile.ProfileName != profileName) // I'm checking to see if this is my VPN profile
{
    return;
}

var usageStates = new NetworkUsageStates
{
    Roaming = TriStates.DoNotCare,
    Shared = TriStates.DoNotCare
};

var networkUsage = await internetConnectionProfile.GetNetworkUsageAsync(
    this.startTime, //Saved when the profile is connected
    DateTimeOffset.Now,
    DataUsageGranularity.Total,
    usageStates);

ulong completeTrafic = 0;
foreach(var usage in networkUsage)
{
    completeTrafic = usage.BytesReceived + usage.BytesSent; //Everytime it's 0
}
</code>```

One interesting point is that usage.ConnectionDuration it's not 0, it's somehow correct. I think is 10 seconds less than what I see in Network and Sharing Center -> Right click on the interface -> Status. In the Status dialog it's showing correctly the Sent and Receive bytes.

My project settings:

My Windows version is Windows 10 1703.

答:
By testing on my side, the above code snippet can work well and both the sent and receive bytes are not 0. So that there's nothing wrong with the code itself.

Please try to check if any parameters are incorrect. For example, the profileName is the correct one you want to test, the startTime is setting correctly to be able to get the usage. Otherwise there may be somethings wrong with the connection profile. Please try to check the internet connection, or try another connection profile for testing.

More details please reference the  official sample.

Body:
I'm trying to get the incoming and outgoing traffic from a WAN Miniport (IKEv2) interface but it doesn't work.
First I'm creating a new VPN profile and then I'm connecting the profile. This works fine. After that I would like to get the incoming and outgoing traffic but I get every time 0. Here is my code

var internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile.ProfileName != profileName) // I'm checking to see if this is my VPN profile
{
    return;
}

var usageStates = new NetworkUsageStates
{
    Roaming = TriStates.DoNotCare,
    Shared = TriStates.DoNotCare
};

var networkUsage = await internetConnectionProfile.GetNetworkUsageAsync(
    this.startTime, //Saved when the profile is connected
    DateTimeOffset.Now,
    DataUsageGranularity.Total,
    usageStates);

ulong completeTrafic = 0;
foreach(var usage in networkUsage)
{
    completeTrafic = usage.BytesReceived + usage.BytesSent; //Everytime it's 0
}

One interesting point is that usage.ConnectionDuration it's not 0, it's somehow correct. I think is 10 seconds less than what I see in Network and Sharing Center -> Right click on the interface -> Status. In the Status dialog it's showing correctly the Sent and Receive bytes.

My project settings:

My Windows version is Windows 10 1703.


问:
How to save NSDictionary to CoreData using NSManagedObject?
I have a huge NSDictionary, having three levels hierarchy.

It looks hierarchy as below

A main JSON contains a Object  {}

It has few values on root, like and than an array, which has dictionary and that dictionary has also a dictionary.

```<code>{

 "id" = "123",
"name" = "Hello",
"title_image" = "URL"

 "sub_array" : [
   {
    "id" = "123",
    "name" = "Hello",
    "title_image" = "URL"
     "another_dictionary":{
       "abc":{

        },
        "abcd":{

         }
      }
   },
   {
    "id" = "123",
    "name" = "Hello",
    "title_image" = "URL"
      "another_dictionary":{
       "abc":{

        },
        "abcd":{

         }
      }
    }
 ]

 }
</code>```

Now I am confused, whether I should go for making separate NSManagedObject,  or make ONE NSManagedObject and make some relationships with other tables, or any other appraoch.

Can one tell me what should I do when I have huge NSDictionary(JSON from Server, which is converted to NSDictionary) and I want to save this in Core Data.

Thanks.

答:
Solution:

```<code>id delegate_info = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context_info = [delegate_info managedObjectContext];
NSManagedObject *ManagedObject_info = [NSEntityDescription
                                               insertNewObjectForEntityForName:@“localDBname” inManagedObjectContext:context_info];

[ManagedObject_info setValue:[[yourDictName valueForKey:@“key1”] valueForKey:@"user_email"] forKey:@“localdbkey1”];
[ManagedObject_info setValue:[yourDictName valueForKey:@“key2”] forKey:@"localdbkey2”];
[ManagedObject_info setValue:[yourDictName valueForKey:@“key3”] forKey:@"localdbkey3”];

NSError *error;
[context_info save:&error];
</code>```

Note: If a value is an array or dictionary it will not work and crash when running.Because you defined that local db key as nsstring.

Body:
I have a huge NSDictionary, having three levels hierarchy.

It looks hierarchy as below

A main JSON contains a Object  {}

It has few values on root, like and than an array, which has dictionary and that dictionary has also a dictionary.

{

 "id" = "123",
"name" = "Hello",
"title_image" = "URL"

 "sub_array" : [
   {
    "id" = "123",
    "name" = "Hello",
    "title_image" = "URL"
     "another_dictionary":{
       "abc":{

        },
        "abcd":{

         }
      }
   },
   {
    "id" = "123",
    "name" = "Hello",
    "title_image" = "URL"
      "another_dictionary":{
       "abc":{

        },
        "abcd":{

         }
      }
    }
 ]

 }

Now I am confused, whether I should go for making separate NSManagedObject,  or make ONE NSManagedObject and make some relationships with other tables, or any other appraoch.

Can one tell me what should I do when I have huge NSDictionary(JSON from Server, which is converted to NSDictionary) and I want to save this in Core Data.

Thanks.

Body:
Solution:

id delegate_info = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context_info = [delegate_info managedObjectContext];
NSManagedObject *ManagedObject_info = [NSEntityDescription
                                               insertNewObjectForEntityForName:@“localDBname” inManagedObjectContext:context_info];

[ManagedObject_info setValue:[[yourDictName valueForKey:@“key1”] valueForKey:@"user_email"] forKey:@“localdbkey1”];
[ManagedObject_info setValue:[yourDictName valueForKey:@“key2”] forKey:@"localdbkey2”];
[ManagedObject_info setValue:[yourDictName valueForKey:@“key3”] forKey:@"localdbkey3”];

NSError *error;
[context_info save:&error];

Note: If a value is an array or dictionary it will not work and crash when running.Because you defined that local db key as nsstring.