问:
Can't update items
I am trying to update items from an app that I created using the app authentication. I first created the items and then I tried to update them but it does not allow me to do so. I am using python and the requests module for doing http requests. I checked and the app allows for the items to be modified by users in the same workspace. Here's the code that I'm using

```<code>update_item_url = "https://api.podio.com/item/%s" % (cid[1])
add_item_url = "https://api.podio.com/item/app/19860772/"
fields = {"fields":{xxx: [sent],xxx: [opened],xxx: [replied],xxx:[bounced],xxx: [prospects],xxx: [queue]}}
update_item = requests.put(update_item_url, json = fields,
headers=headers)
</code>```

The error that I get is:

```<code>403
{"error_parameters":{},"error_detail":null,"error_propagate":false,"request":{"url":"http:\/\/api.podio.com\/item\/11","query_string":"","method":"PUT"},"error_description":"The app with id xxx does not have the right update on item with id xx","error":"forbidden"}
</code>```

答:
As error says The app with id xxx does not have the right update on item with id xx.

Please double check item is from correct app.

Title: Can't update items

Body:
I am trying to update items from an app that I created using the app authentication. I first created the items and then I tried to update them but it does not allow me to do so. I am using python and the requests module for doing http requests. I checked and the app allows for the items to be modified by users in the same workspace. Here's the code that I'm using

update_item_url = "https://api.podio.com/item/%s" % (cid[1])
add_item_url = "https://api.podio.com/item/app/19860772/"
fields = {"fields":{xxx: [sent],xxx: [opened],xxx: [replied],xxx:[bounced],xxx: [prospects],xxx: [queue]}}
update_item = requests.put(update_item_url, json = fields,
headers=headers)

The error that I get is:

403
{"error_parameters":{},"error_detail":null,"error_propagate":false,"request":{"url":"http:\/\/api.podio.com\/item\/11","query_string":"","method":"PUT"},"error_description":"The app with id xxx does not have the right update on item with id xx","error":"forbidden"}


来源: stackexchange

问:
Dapper One To Many Relationship
I have 3 tables structured in the following way:

```<code>CREATE TABLE [User](
    Id int NOT NULL,
    Name varchar(50)
    PRIMARY KEY (Id)
)

CREATE TABLE [Role](
    Id int NOT NULL,
    UserId int NOT NULL,
    Name varchar(50),
    PRIMARY KEY (Id),
    FOREIGN KEY (UserId) REFERENCES [User](Id)
)

CREATE TABLE [Description](
    Id int NOT NULL,
    RoleId int NOT NULL,
    Name varchar(50)
    FOREIGN KEY (RoleId) REFERENCES [Role](Id)
)
</code>```

As you can see it is one to many relationship nested twice. In the code I have the following classes to represent them:

```<code>public class User
{
    public int Id { get; set; }
    public string Name { get; set; }

    public IEnumerable<Role> Roles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Name { get; set; }

    public IEnumerable<Description> Descriptions { get; set; }
}

public class Description
{
    public int Id { get; set; }
    public int RoleId { get; set; }
    public string Name { get; set; }
}
</code>```

Now I need to query for the user and also get all fields that come with it. I have figured out a way to do that using QueryMultiple such as this:

```<code>var queryOne = "SELECT Id, Name FROM [User] WHERE Id = 1";
var queryTwo = "SELECT r.Id, r.UserId, r.Name FROM  [User] u INNER JOIN [Role] r ON u.Id = r.UserId WHERE u.Id = 1";
var queryThree = "SELECT d.Id, d.RoleId, d.Name FROM  [User] u INNER JOIN [Role] r ON u.Id = r.UserId INNER JOIN [Description] d ON r.Id = d.RoleId WHERE u.Id = 1";

var conn = new SqlConnection();

using (var con = conn)
{
    var result = con.QueryMultiple(queryOne + " " + queryTwo + " " + queryThree);
    var users = result.Read<User>().FirstOrDefault();
    var roles = result.Read<Role>();
    var descriptions = result.Read<Description>();
    if (users != null && roles != null)
    {
        users.Roles = roles;
        Console.WriteLine("User: " + users.Name);
        foreach (var role in users.Roles)
        {
            Console.WriteLine("Role: " + role.Name);
            if (descriptions != null)
            {
                role.Descriptions = descriptions.Where(d => d.RoleId == role.Id);
                foreach (var roleDescription in role.Descriptions)
                {
                    Console.WriteLine("Description: " + roleDescription.Name);
                }
            }
        }
    }
}
</code>```

The result is:

User: Bob

  Role: Tester

  Description: Tester First Description

  Description: Tester Second Description

  Description: Tester Third Description

  Role: Manager

  Description: Manager First Description

  Description: Manager Second Description

  Description: Manager Third Description

  Role: Programmer

  Description: Programmer First Description

  Description: Programmer Second Description

  Description: Programmer Third Description

Main Question:
While the above code works it feels too messy. I was wondering if there is a better/easier way to achieve this?

Bonus Points:
Please also feel free to suggest a better way to query this than using inner joins. My goal is to improve performance.

EDIT:

I came up with option two as well, but again I don't think its a good solution. With option 2 I create a 4th object that will contain results of the 3 objects combined such as this:

```<code>public class Combination
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public int DescriptionId { get; set; }
    public string DescriptionName { get; set; }
}
</code>```

Then I process it like this:

```<code>var queryFour = "SELECT u.Id as 'UserId', u.Name as 'UserName', r.Id as 'RoleId', r.Name as 'RoleName', d.Id as 'DescriptionId', d.Name as 'DescriptionName' FROM  [User] u INNER JOIN [Role] r ON u.Id = r.UserId INNER JOIN [Description] d ON r.Id = d.RoleId WHERE u.Id = 1";

var conn = new SqlConnection();
using (var con = conn)
{
    var myUser = new User();
    var result = con.Query<Combination>(queryFour);
    if (result != null)
    {
        var user = result.FirstOrDefault();
        myUser.Id = user.UserId;
        myUser.Name = user.UserName;
        var roles = result.GroupBy(x => x.RoleId).Select(x => x.FirstOrDefault());
        var myRoles = new List<Role>();
        if (roles != null)
        {
            foreach (var role in roles)
            {
                var myRole = new Role
                {
                    Id = role.RoleId,
                    Name = role.RoleName
                };

                var descriptions = result.Where(x => x.RoleId == myRole.Id);
                var descList = new List<Description>();
                foreach (var description in descriptions)
                {
                    var desc = new Description
                    {
                        Id = description.DescriptionId,
                        RoleId = description.RoleId,
                        Name = description.DescriptionName
                    };
                    descList.Add(desc);
                }
                myRole.Descriptions = descList;
                myRoles.Add(myRole);
            }
        }
        myUser.Roles = myRoles;
    }

    Console.WriteLine("User: " + myUser.Name);
    foreach (var myUserRole in myUser.Roles)
    {
        Console.WriteLine("Role: " + myUserRole.Name);
        foreach (var description in myUserRole.Descriptions)
        {
            Console.WriteLine("Description: " + description.Name);
        }
    }
}
</code>```

The resulting output is the same in both methods and the second method uses 1 query as opposed to 3.

EDIT 2: Something to consider, my data for these 3 tables are updated often.

EDIT 3:

```<code>private static void SqlTest()
{
    using (IDbConnection connection = new SqlConnection())
    {
        var queryOne = "SELECT Id FROM [TestTable] With(nolock) WHERE Id = 1";
        var queryTwo = "SELECT B.Id, B.TestTableId FROM [TestTable] A With(nolock) INNER JOIN [TestTable2] B With(nolock) ON A.Id = B.TestTableId WHERE A.Id = 1";
        var queryThree = "SELECT C.Id, C.TestTable2Id FROM [TestTable3] C With(nolock) INNER JOIN [TestTable2] B With(nolock) ON B.Id = C.TestTable2Id INNER JOIN [TestTable] A With(nolock) ON A.Id = B.TestTableId WHERE A.Id = 1";

            var gridReader = connection.QueryMultiple(queryOne + " " + queryTwo + " " + queryThree);
            var user = gridReader.Read<Class1>().FirstOrDefault();

            var roles = gridReader.Read<Class2>().ToList();

            var descriptions = gridReader.Read<Class3>().ToLookup(d => d.Id);

            user.Roles= roles;

            user.Roles.ForEach(r => r.Properties = descriptions[r.Id].ToList());
    }
}
</code>```

答:
An alternative approach (Working code snippet with .Net Core):

Why not create a database View like this -

create view myview
      As
      SELECT u.Id as 'UserId', u.Name as 'UserName', r.Id as 'RoleId',
      r.Name as 'RoleName', d.Id as 'DescriptionId', d.Name as 'DescriptionName'
      FROM  User u INNER JOIN Role r ON u.Id = r.UserId
      INNER JOIN Description d ON r.Id = d.RoleId;

Then you can use your cleaner query as below :

```<code>    public List<Combination> GetData(int userId)
    {
        String query = "select * from myview" + " where userId = " + userId + ";";

        using (System.Data.Common.DbConnection _Connection = database.Connection)
        {
            _Connection.Open();
            return _Connection.Query<Combination>(query).ToList();
        }
    }
</code>```

And your processing code will look like this :

[Note: This can be enhanced even further.]

```<code>        public static void process (List<Combination> list)
        {
            User myUser = new User(); myUser.Id = list[0].UserId; myUser.Name = list[0].UserName;
            var myroles = new List<Role>(); var r = new Role(); string currentRole = list[0].RoleName;
            var descList = new List<Description>(); var d = new Description();

            // All stuff done in a single loop.
            foreach (var v in list)
            {
                d = new Description() { Id = v.DescriptionId, RoleId = v.RoleId, Name = v.DescriptionName };
                if (currentRole == v.RoleName)
                {
                    r = new Role() { Id = v.RoleId, Name = v.RoleName, UserId = v.UserId, Descriptions = descList };
                    descList.Add(d);
                }
                else
                {
                    myroles.Add(r);
                    descList = new List<Description>(); descList.Add(d);
                    currentRole = v.RoleName;
                }
            }
            myroles.Add(r);
            myUser.Roles = myroles;

            Console.WriteLine("User: " + myUser.Name);
            foreach (var myUserRole in myUser.Roles)
            {
                Console.WriteLine("Role: " + myUserRole.Name);
                foreach (var description in myUserRole.Descriptions)
                {
                    Console.WriteLine("Description: " + description.Name);
                }
            }
        }
</code>```

From the performance standpoint, Inner Joins are better than other forms of query like subquery, Co-related subquery, etc. But ultimately everything boils down to the SQL execution plan.

ContentLicense: CC BY-SA 3.0

Title: Dapper One To Many Relationship

Body:
I have 3 tables structured in the following way:

CREATE TABLE [User](
    Id int NOT NULL,
    Name varchar(50)
    PRIMARY KEY (Id)
)

CREATE TABLE [Role](
    Id int NOT NULL,
    UserId int NOT NULL,
    Name varchar(50),
    PRIMARY KEY (Id),
    FOREIGN KEY (UserId) REFERENCES [User](Id)
)

CREATE TABLE [Description](
    Id int NOT NULL,
    RoleId int NOT NULL,
    Name varchar(50)
    FOREIGN KEY (RoleId) REFERENCES [Role](Id)
)

As you can see it is one to many relationship nested twice. In the code I have the following classes to represent them:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }

    public IEnumerable<Role> Roles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Name { get; set; }

    public IEnumerable<Description> Descriptions { get; set; }
}

public class Description
{
    public int Id { get; set; }
    public int RoleId { get; set; }
    public string Name { get; set; }
}

Now I need to query for the user and also get all fields that come with it. I have figured out a way to do that using QueryMultiple such as this:

var queryOne = "SELECT Id, Name FROM [User] WHERE Id = 1";
var queryTwo = "SELECT r.Id, r.UserId, r.Name FROM  [User] u INNER JOIN [Role] r ON u.Id = r.UserId WHERE u.Id = 1";
var queryThree = "SELECT d.Id, d.RoleId, d.Name FROM  [User] u INNER JOIN [Role] r ON u.Id = r.UserId INNER JOIN [Description] d ON r.Id = d.RoleId WHERE u.Id = 1";

var conn = new SqlConnection();

using (var con = conn)
{
    var result = con.QueryMultiple(queryOne + " " + queryTwo + " " + queryThree);
    var users = result.Read<User>().FirstOrDefault();
    var roles = result.Read<Role>();
    var descriptions = result.Read<Description>();
    if (users != null && roles != null)
    {
        users.Roles = roles;
        Console.WriteLine("User: " + users.Name);
        foreach (var role in users.Roles)
        {
            Console.WriteLine("Role: " + role.Name);
            if (descriptions != null)
            {
                role.Descriptions = descriptions.Where(d => d.RoleId == role.Id);
                foreach (var roleDescription in role.Descriptions)
                {
                    Console.WriteLine("Description: " + roleDescription.Name);
                }
            }
        }
    }
}

The result is:

User: Bob

  Role: Tester

  Description: Tester First Description

  Description: Tester Second Description

  Description: Tester Third Description

  Role: Manager

  Description: Manager First Description

  Description: Manager Second Description

  Description: Manager Third Description

  Role: Programmer

  Description: Programmer First Description

  Description: Programmer Second Description

  Description: Programmer Third Description

Main Question:
While the above code works it feels too messy. I was wondering if there is a better/easier way to achieve this?

Bonus Points:
Please also feel free to suggest a better way to query this than using inner joins. My goal is to improve performance.

EDIT:

I came up with option two as well, but again I don't think its a good solution. With option 2 I create a 4th object that will contain results of the 3 objects combined such as this:

public class Combination
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public int DescriptionId { get; set; }
    public string DescriptionName { get; set; }
}

Then I process it like this:

var queryFour = "SELECT u.Id as 'UserId', u.Name as 'UserName', r.Id as 'RoleId', r.Name as 'RoleName', d.Id as 'DescriptionId', d.Name as 'DescriptionName' FROM  [User] u INNER JOIN [Role] r ON u.Id = r.UserId INNER JOIN [Description] d ON r.Id = d.RoleId WHERE u.Id = 1";

var conn = new SqlConnection();
using (var con = conn)
{
    var myUser = new User();
    var result = con.Query<Combination>(queryFour);
    if (result != null)
    {
        var user = result.FirstOrDefault();
        myUser.Id = user.UserId;
        myUser.Name = user.UserName;
        var roles = result.GroupBy(x => x.RoleId).Select(x => x.FirstOrDefault());
        var myRoles = new List<Role>();
        if (roles != null)
        {
            foreach (var role in roles)
            {
                var myRole = new Role
                {
                    Id = role.RoleId,
                    Name = role.RoleName
                };

                var descriptions = result.Where(x => x.RoleId == myRole.Id);
                var descList = new List<Description>();
                foreach (var description in descriptions)
                {
                    var desc = new Description
                    {
                        Id = description.DescriptionId,
                        RoleId = description.RoleId,
                        Name = description.DescriptionName
                    };
                    descList.Add(desc);
                }
                myRole.Descriptions = descList;
                myRoles.Add(myRole);
            }
        }
        myUser.Roles = myRoles;
    }

    Console.WriteLine("User: " + myUser.Name);
    foreach (var myUserRole in myUser.Roles)
    {
        Console.WriteLine("Role: " + myUserRole.Name);
        foreach (var description in myUserRole.Descriptions)
        {
            Console.WriteLine("Description: " + description.Name);
        }
    }
}

The resulting output is the same in both methods and the second method uses 1 query as opposed to 3.

EDIT 2: Something to consider, my data for these 3 tables are updated often.

EDIT 3:

private static void SqlTest()
{
    using (IDbConnection connection = new SqlConnection())
    {
        var queryOne = "SELECT Id FROM [TestTable] With(nolock) WHERE Id = 1";
        var queryTwo = "SELECT B.Id, B.TestTableId FROM [TestTable] A With(nolock) INNER JOIN [TestTable2] B With(nolock) ON A.Id = B.TestTableId WHERE A.Id = 1";
        var queryThree = "SELECT C.Id, C.TestTable2Id FROM [TestTable3] C With(nolock) INNER JOIN [TestTable2] B With(nolock) ON B.Id = C.TestTable2Id INNER JOIN [TestTable] A With(nolock) ON A.Id = B.TestTableId WHERE A.Id = 1";

            var gridReader = connection.QueryMultiple(queryOne + " " + queryTwo + " " + queryThree);
            var user = gridReader.Read<Class1>().FirstOrDefault();

            var roles = gridReader.Read<Class2>().ToList();

            var descriptions = gridReader.Read<Class3>().ToLookup(d => d.Id);

            user.Roles= roles;

            user.Roles.ForEach(r => r.Properties = descriptions[r.Id].ToList());
    }
}

Body:
An alternative approach (Working code snippet with .Net Core):

Why not create a database View like this -

create view myview
      As
      SELECT u.Id as 'UserId', u.Name as 'UserName', r.Id as 'RoleId',
      r.Name as 'RoleName', d.Id as 'DescriptionId', d.Name as 'DescriptionName'
      FROM  User u INNER JOIN Role r ON u.Id = r.UserId
      INNER JOIN Description d ON r.Id = d.RoleId;

Then you can use your cleaner query as below :

    public List<Combination> GetData(int userId)
    {
        String query = "select * from myview" + " where userId = " + userId + ";";

        using (System.Data.Common.DbConnection _Connection = database.Connection)
        {
            _Connection.Open();
            return _Connection.Query<Combination>(query).ToList();
        }
    }

And your processing code will look like this :

[Note: This can be enhanced even further.]

        public static void process (List<Combination> list)
        {
            User myUser = new User(); myUser.Id = list[0].UserId; myUser.Name = list[0].UserName;
            var myroles = new List<Role>(); var r = new Role(); string currentRole = list[0].RoleName;
            var descList = new List<Description>(); var d = new Description();

            // All stuff done in a single loop.
            foreach (var v in list)
            {
                d = new Description() { Id = v.DescriptionId, RoleId = v.RoleId, Name = v.DescriptionName };
                if (currentRole == v.RoleName)
                {
                    r = new Role() { Id = v.RoleId, Name = v.RoleName, UserId = v.UserId, Descriptions = descList };
                    descList.Add(d);
                }
                else
                {
                    myroles.Add(r);
                    descList = new List<Description>(); descList.Add(d);
                    currentRole = v.RoleName;
                }
            }
            myroles.Add(r);
            myUser.Roles = myroles;

            Console.WriteLine("User: " + myUser.Name);
            foreach (var myUserRole in myUser.Roles)
            {
                Console.WriteLine("Role: " + myUserRole.Name);
                foreach (var description in myUserRole.Descriptions)
                {
                    Console.WriteLine("Description: " + description.Name);
                }
            }
        }

From the performance standpoint, Inner Joins are better than other forms of query like subquery, Co-related subquery, etc. But ultimately everything boils down to the SQL execution plan.


问:
Android Studio - AVD Manager is not visible
I have installed Android Studio 2.3.2 and
The AVD Manager (which should be under the tools menu is not visible).

Is there any way that i could make it available?

Tools menu in Android Studio

Menus and Toolbars

答:
Check if you have Android plugin Enabled in your Studio:

File --> Settings-- > Type Plugin

Check Android and Restart Android Studio


问:
Django rest framework: how to turn off/on pagination in ModelViewSet
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

```<code>class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"
</code>```

Thanks.

答:
One option would be to dynamically disable pagination on the view by setting a no_page query parameter:

```<code>def paginate_queryset(self, queryset, request, view=None):
    if 'no_page' in request.query_params:
        return None

    return super().paginate_queryset(queryset, request, view)
</code>```

Body:
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"

Thanks.

Body:
One option would be to dynamically disable pagination on the view by setting a no_page query parameter:

def paginate_queryset(self, queryset, request, view=None):
    if 'no_page' in request.query_params:
        return None

    return super().paginate_queryset(queryset, request, view)

ContentLicense: CC BY-SA 4.0


问:
What's the difference between this and super keywords in java?
Check my coolMethod, babes:

```<code>package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}
</code>```

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

```<code>package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}
</code>```

And my main, that calls my Moo class functionalities.

```<code>package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}
</code>```

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

答: I suggest you, to create a coolMethod in your Moo class, that print something different, from the one in the Zoo class</p>

ContentLicense: CC BY-SA 2.5

Body:
Check my coolMethod, babes:

package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

And my main, that calls my Moo class functionalities.

package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?


问:
Reference click method from another source file in XAML?
I have a button with a click method assigned to it. I'd like to move that method to another CS file so I may reuse it in other places. Is it possible in XAML to reference a method, click method, from a CS source file outside of the Pages source file?

<Button x:Name="TheRedButton" Click="DoNotPressTheRedButton_Click" />

I want to locate DoNotPressTheRedButton_Click in another source file.

ButtonMethods.cs

and then use it in my Page from XAML

MyPage.xaml

What do I need to write in XAML in order to do this?

I thought I need:

xmlns:helpermethods="using:CoreProject.HelperMethods"

then,

<Button x:Name="TheRedButton" Click="helpermethods:ButtonMethods.DoNotPressTheRedButton_Click" />

But I'm getting compiler errors... CS1002 and CS1513. So obviously it's not the right syntax. Is this even possible?

答:
You could call your method in ButtonMethods from the click handler of your TheRedButton.

Like this:

```<code>private void OnSomebodyClickedTheRedButtonWhenTheyWereNotMeantTo(object sender, RoutedEventArgs args)
{
    // do some other stuff with sender - find out which button was clicked, etc.

    ButtonMethods.RedButtonClicked(sender, args);
}
</code>```

This would allow you to also do "other stuff" that you might need, within this class, from this event handler (if you wanted to).

Make sure your method is static, otherwise you would need to (unnecessarily) create an instance of the ButtonMethods class each time.

Body:
You could call your method in ButtonMethods from the click handler of your TheRedButton.

Like this:

private void OnSomebodyClickedTheRedButtonWhenTheyWereNotMeantTo(object sender, RoutedEventArgs args)
{
    // do some other stuff with sender - find out which button was clicked, etc.

    ButtonMethods.RedButtonClicked(sender, args);
}

This would allow you to also do "other stuff" that you might need, within this class, from this event handler (if you wanted to).

Make sure your method is static, otherwise you would need to (unnecessarily) create an instance of the ButtonMethods class each time.


问:
Extract archives to S3
I need to download zip archives, extract them and load to S3. I thought about using Lambda to handle downloading and unarchiving, but it has disk size limits.

What would be the best service to do this? I can't use my local machine, because I expect the job to run for several days.

答:
You are correct that AWS Lambda is not appropriate for this task. The 500MB disk size limit will not allow you to expand the zip files.

Regardless, you'd also need to write a "management layer" to spawn the Lambda tasks, which is actually the more complex task.

The hardest part of the operation will be tracking progress to ensure that all files have been converted and uploaded, taking into account random failures that might happen along the way.

I would recommend something along these lines:

1. Obtain a list of source files

Somehow you'll need a list of the source zip files that you want to convert. This might be complicated if more files are appearing all the time (eg if it is a live system). You can always do a second run afterwards for additional files that appear.

2. Create a Work Tracker

You will need to track the work in some way so that the system knows which files have been processed and which ones are in-progress (especially if you work in parallel). While you don't state the number of input files, it would appear to be in the tens-of-thousands.

A very reliable method would be to create an Amazon SQS message for each file to be processed. Then the workers would pull from this queue (see next step). Alternatively, use a simple database to store the information.

3. Do the work

The simplest method would be to launch an Amazon EC2 instance with a script that:

Determines the next file to process (by pulling a message from SQS or consulting a database)

Does the work (download, unzip, upload)

Marks the work as done (or marks it as an error, to be re-tried in a separate pass later)

Start with a small list of files to confirm that the process is working okay, then ramp-up the quantity.

To fully-utilize the bandwidth and CPU, you could run multiple processes on the instance. Each would operate as an independent worker.

Use Amazon EC2 Spot Instances to lower the cost of processing. Try a variety of instance types to find the best combination -- some have Instance Store that provides very fast local storage (especially those with SSD). Having some form of logging will help you track progress and determine which instance types seem to be performing the best, and the optimal number of parallel processes to run on each worker.

By tracking the work in SQS or a database, the process can be stopped/started without losing progress. It can also be scaled across multiple instances with multiple workers per instance.

4. Handle the errors

Problems will occur (bad zip files, networking glitches, random errors) so you'll want to do a second pass to try them again and investigate specific errors. Your system needs to keep track of such problems so they can be re-processed.

5. Audit the results

Assuming that you want all the files processed, you should do a final pass where you compare the list of source files against the final list of uploaded files.

The method would depend upon how you are uploading the files to S3 -- this job would be a lot easier if S3 objects are named based upon their source (eg a source file of A01.zip would be expanded to A01/file1, A01/file2, etc).

Bottom line: The work you are doing is quite simple. Tracking the work will take more effort than actually doing the work.

Title: Extract archives to S3


问:
How do I keep the user logged-in with Implicit flow?
From what I understand, the end-result of the implicit flow is the access token, which allows the client (in my case a JS SPA) to authenticate into resource servers (APIs).

The access token is usually only valid for ~1 hour, then it expires - making it useless.

What should my JS app do then? Redirecting the user back to the auth server is unrealistic since then the user will have to reenter their credentials every 1 hour!

I also know that the implicit flow doesn't support refresh tokens so I can't use those either.

Is there a way to persist the user's login? How do things like Facebook keep you logged-in indefinitely?

答:
If the session at the OP is still active (via a cookie perhaps), then OpenID Connect has a mechanism to refresh tokens in a (hidden) iframe: prompt=none.

According to the spec, when sending this flow...

The Authorization Server MUST NOT display any authentication or consent user interface pages. An error is returned if an End-User is not already authenticated or the Client does not have pre-configured consent for the requested Claims or does not fulfill other conditions for processing the request. The error code will typically be login_required, interaction_required, or another code defined in Section 3.1.2.6. This can be used as a method to check for existing authentication and/or consent.

prompt=none is also referred to from the Session Management specification.


问:
How to remove Home from HomeController in Mvc
I have a HomeController and it has many Actions in it. I would like users to visit my actions without typing Home. Here is the Route below

```<code>routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
</code>```

I would like users not to enter controller name, which is Home in this case. How can I do that? Or is it mandatory?

答:
Solution 01 (attribute routing)

Add below line on the top of the other routes in RouteConfig

```<code>        routes.MapMvcAttributeRoutes();
</code>```

Then add an attribute route on top of each action as you want. (actions in the home controller in this case)

eg. Below code sample will remove "/Home" from http://site/Home/About and be available on http://site/About

```<code>[Route("About")]
public ActionResult About()
{
</code>```

Solution 02  (using a Route constraint)  [ Source ]

Add a new route mapping to RouteConfig as below. (Remember to add these specific routes before the default (generic) routes.

```<code>routes.MapRoute(
    "Root",
    "{action}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { isMethodInHomeController = new RootRouteConstraint<HomeController>() }
);
</code>```

This will remove "Home" from all the actions (routes) of the Home controller
RootRouteConstraint class

```<code>public class RootRouteConstraint<T> : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
        return rootMethodNames.Contains(values["action"].ToString().ToLower());
    }
}
</code>```

Optional Info: This line (constraint) will make sure to apply this routing only for the HomeController

```<code>new { isMethodInHomeController = new RootRouteConstraint<HomeController>
</code>```

Body:
I have a HomeController and it has many Actions in it. I would like users to visit my actions without typing Home. Here is the Route below

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

I would like users not to enter controller name, which is Home in this case. How can I do that? Or is it mandatory?

Body:
Solution 01 (attribute routing)

Add below line on the top of the other routes in RouteConfig

        routes.MapMvcAttributeRoutes();

Then add an attribute route on top of each action as you want. (actions in the home controller in this case)

eg. Below code sample will remove "/Home" from http://site/Home/About and be available on http://site/About

[Route("About")]
public ActionResult About()
{

Solution 02  (using a Route constraint)  [ Source ]

Add a new route mapping to RouteConfig as below. (Remember to add these specific routes before the default (generic) routes.

routes.MapRoute(
    "Root",
    "{action}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { isMethodInHomeController = new RootRouteConstraint<HomeController>() }
);

This will remove "Home" from all the actions (routes) of the Home controller
RootRouteConstraint class

public class RootRouteConstraint<T> : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
        return rootMethodNames.Contains(values["action"].ToString().ToLower());
    }
}

Optional Info: This line (constraint) will make sure to apply this routing only for the HomeController

new { isMethodInHomeController = new RootRouteConstraint<HomeController>


问:
Having trouble creating an object within a switch statement, "Object cannot be resolved" in later code (java)
I am writing a method that takes in a string variable type that is used to determine which list class to implement. The method uses a switch statement to create the appropriate type of list using the variable name newList.

The switch statement looks like this:

```<code>switch (type) {
    case "unsorted": {
        UnsortedList newList = new UnsortedList();
        break;
    }
    case "sorted": {
        SortedList newList = new SortedList();
        break;
    }
    case "new sorted": {
        NewSortedList newList = new NewSortedList();
        break;
    }
    default: {
        System.out.print("Something went wrong! List type unrecognized. I have initialized newList to be an unsorted list.");
        UnsortedList newList = new UnsortedList();
    }
}
</code>```

According to this, I believe that newList will always be instantiated due to the default case of the switch statement. However I receive the compile error "newList cannot be resolved".

Is there anything I can do to prevent this?

答:
I implemented an interface for the list types called List and instantiated newList as type List before the switch statement. This allowed newListto be visible outside of the switch and still gain the properties of each list type.

Here's a revised version of my code:

```<code>    List newList;
    switch (type)
    {
        case "unsorted":
        {
            newList = new UnsortedList();
            break;
        }
        case "sorted":
        {
            newList = new SortedList();
            break;
        }
        case "new sorted":
        {
            newList = new NewSortedList();
            break;
        }
        default:
        {
            System.out.print("Something went wrong! I have initialized newList to be an unsorted list");
            newList = new UnsortedList();
        }
    }
</code>```

Thank you to everyone for your help. I'm still learning so every comment helps!

Body:
I am writing a method that takes in a string variable type that is used to determine which list class to implement. The method uses a switch statement to create the appropriate type of list using the variable name newList.

The switch statement looks like this:

switch (type) {
    case "unsorted": {
        UnsortedList newList = new UnsortedList();
        break;
    }
    case "sorted": {
        SortedList newList = new SortedList();
        break;
    }
    case "new sorted": {
        NewSortedList newList = new NewSortedList();
        break;
    }
    default: {
        System.out.print("Something went wrong! List type unrecognized. I have initialized newList to be an unsorted list.");
        UnsortedList newList = new UnsortedList();
    }
}

According to this, I believe that newList will always be instantiated due to the default case of the switch statement. However I receive the compile error "newList cannot be resolved".

Is there anything I can do to prevent this?

Body:
I implemented an interface for the list types called List and instantiated newList as type List before the switch statement. This allowed newListto be visible outside of the switch and still gain the properties of each list type.

Here's a revised version of my code:

    List newList;
    switch (type)
    {
        case "unsorted":
        {
            newList = new UnsortedList();
            break;
        }
        case "sorted":
        {
            newList = new SortedList();
            break;
        }
        case "new sorted":
        {
            newList = new NewSortedList();
            break;
        }
        default:
        {
            System.out.print("Something went wrong! I have initialized newList to be an unsorted list");
            newList = new UnsortedList();
        }
    }

Thank you to everyone for your help. I'm still learning so every comment helps!


答:
df.sort_values() returns sorted DF, but it doesn't sort in place.

So either use:

```<code>df = df.sort_values(by='date')
</code>```

or

```<code>df.sort_values(by='date', inplace=True)
</code>```

Title: How can I sort DataFrame by date in Python?

Body:
I try to sort dataframe shown below by date using df.sort_values(by='date') however it doesn't work. Any ideas how can I do this to be sure that it is sorted properly?

     symbol        date     open    close     high      low
0      GOOG  2007-01-03   232.77   233.56   238.09   230.32
1      GOOG  2007-01-05   241.01   243.35   243.51   238.82
2      GOOG  2007-01-04   234.27   241.39   241.73   233.94

...
2692   GOOG  2017-11-30  1022.37  1021.41  1028.49  1015.00
2693   GOOG  2017-11-29  1042.68  1021.66  1044.08  1015.65
2694   GOOG  2017-12-01  1015.80  1010.17  1022.49  1002.02

Body:
df.sort_values() returns sorted DF, but it doesn't sort in place.

So either use:

df = df.sort_values(by='date')

or

df.sort_values(by='date', inplace=True)


问:
Proxy model error: Local field in class clashes with field of the same name from base class
```<code>class EmailUser(User):

    class Meta:
        proxy = True

    email = models.EmailField(_('email address'), unique=True)
</code>```

In the above, I'm trying to implement a proxy model, but I'm getting this error message:

```<code>Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10e04ed08>
Traceback (most recent call last):
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models()
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/models.py", line 28, in <module>
    class EmailUser(User):
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/base.py", line 231, in __new__
    base.__name__,
django.core.exceptions.FieldError: Local field 'username' in class 'EmailUser' clashes with field of the same name from base class 'User'.
</code>```

I wonder why I get this error, and what to do about it. I'm using Django version 1.11.

答: You can't do what you're trying to do with a proxy model. Luckily, Django makes it easy to extend the built-in User model: create a normal concrete model that inherits from AbstractUser, and set the AUTH_USER_MODEL setting to the name of your model.</p>

Body:
class EmailUser(User):

    class Meta:
        proxy = True

    email = models.EmailField(_('email address'), unique=True)

In the above, I'm trying to implement a proxy model, but I'm getting this error message:

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10e04ed08>
Traceback (most recent call last):
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models()
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/models.py", line 28, in <module>
    class EmailUser(User):
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/base.py", line 231, in __new__
    base.__name__,
django.core.exceptions.FieldError: Local field 'username' in class 'EmailUser' clashes with field of the same name from base class 'User'.

I wonder why I get this error, and what to do about it. I'm using Django version 1.11.


问:
Twilio Cant make call but no errors
I am trying make phonecall via Twilio using c# i am using the below code to make call.code executes successfully but i wont receive call.In my twilio page it shows staus as completed and durations.</p>

```<code>        const string accountSid = "ACe200aeb6115e1f3038a012e1103bd874";
        const string authToken = "6XXXXXX";
        TwilioClient.Init(accountSid, authToken);

        var to = new PhoneNumber("+12025688652");
        var from = new PhoneNumber("+919500553163");
        var call = CallResource.Create(to,
                                       from,
                                       url: new Uri("https://demo.twilio.com/welcome/voice/"));

        Console.WriteLine(call.Sid);
</code>```

答:
Twilio developer evangelist here.

I believe that you are actually making that call successfully. You are not experiencing the call yourself because of the parameters you have used.

You are making the call from your verified number. This is your real phone number, but when you set it to be the from address that just means Twilio will use it as the caller ID for the call.

For the to address you are using your Twilio number that you have bought within your account. When you make calls to that number, Twilio makes a webhook (HTTP) request to the URL that is set as the voice response in the number's settings. Currently, that is still set to the default, so Twilio retrieves this URL: https://demo.twilio.com/welcome/voice/. If you click through, you will see that this just reads out a message.

The URL you use when you create the call is also the default URL.

So what is happening with the call is that Twilio is using your caller ID to dial your Twilio number and when the call is answered, both sides of the call are reading out that message to each other.

If you want to at least make your own phone ring, then I'd start by reversing the to and from numbers in your API call. If you do that, then you should receive a call on your phone and when you answer it you will hear the demo message. Then, once you've done that you can start writing your own TwiML responses, possibly using Twimlbins to get started or by building your own application.

Let me know if this helps.

Title: Twilio Cant make call but no errors

Body:
I am trying make phonecall via Twilio using c# i am using the below code to make call.code executes successfully but i wont receive call.In my twilio page it shows staus as completed and durations.

        const string accountSid = "ACe200aeb6115e1f3038a012e1103bd874";
        const string authToken = "6XXXXXX";
        TwilioClient.Init(accountSid, authToken);

        var to = new PhoneNumber("+12025688652");
        var from = new PhoneNumber("+919500553163");
        var call = CallResource.Create(to,
                                       from,
                                       url: new Uri("https://demo.twilio.com/welcome/voice/"));

        Console.WriteLine(call.Sid);


问:
Anders Hejlsberg's C# 4.0 REPL
During the last 10 minutes of Ander's talk The Future of C# he demonstrates a really cool C# Read-Eval-Print loop which would be a tremendous help in learning the language.

Several .NET4 related downloads are already available: Visual Studio 2010 and .NET Framework 4.0 CTP, Visual Studio 2010 and .NET Framework 4 Training Kit. Do you know what happened to this REPL? Is it somewhere hidden among examples?

I know about mono repl. Please, no alternative solutions.

答:
The Immediate window (Debug>Windows>Immediate Ctrl+D, I ) is fairly good replacement that's built in.  It does require you start the IDE and put a breakpoint on something.

It does give you the context of where you would like to do experimentation.

Title: Anders Hejlsberg's C# 4.0 REPL


问:
Trying to return "basenames" of filenames with and without version tags
I've been trying to write a regex that will return the base names of versioned files but also return the base name of a non-versioned file in the same list.

```<code>import re

file_list = [
    "ThisFile_v01.ext",
    "ThisFile_v02.ext",
    "ThatFile_v01.ext",
    "ThatFile_v02.ext",
    "NonVersionedFile.ext",
    "Non_VersionedFile.ext",
]

r = re.compile(r"^(?P<basename>.*(?!_v))(?P<version>_v\d+\.)?(?(version).*$|\..*$)")
for f in file_list:
    match = r.match(f)
    print(match.group('basename'))
</code>```

I'm trying to return a list like this:

```<code>ThisFile
ThisFile
ThatFile
ThatFile
NonVersionedFile
Non_VersionedFile
</code>```

I'm currently getting this:

```<code>ThisFile_v01
ThisFile_v02
ThatFile_v01
ThatFile_v02
NonVersionedFile
Non_VersionedFile
</code>```

I'm probably over thinking it but I've been thru a lot of iterations and I can't seem to figure this one out. Any help would be appreciated.

答:
Super simple change to your regex fixes your problem. The underlying issue with your regex was that you were using "greedy" calls. If you tell them to be "non-greedy" you'll get your desired output.

r = re.compile(r"^(?P<basename>.*?)(?P<version>_v[0-9]+)?\.ext")

The above regex forces the basename search to be minimal (the ? at the end of the group is what causes that) meaning the .* will stop searching as soon as it can instead of gobbling up every character it can get its hands on.

Body:
I've been trying to write a regex that will return the base names of versioned files but also return the base name of a non-versioned file in the same list.

import re

file_list = [
    "ThisFile_v01.ext",
    "ThisFile_v02.ext",
    "ThatFile_v01.ext",
    "ThatFile_v02.ext",
    "NonVersionedFile.ext",
    "Non_VersionedFile.ext",
]

r = re.compile(r"^(?P<basename>.*(?!_v))(?P<version>_v\d+\.)?(?(version).*$|\..*$)")
for f in file_list:
    match = r.match(f)
    print(match.group('basename'))

I'm trying to return a list like this:

ThisFile
ThisFile
ThatFile
ThatFile
NonVersionedFile
Non_VersionedFile

I'm currently getting this:

ThisFile_v01
ThisFile_v02
ThatFile_v01
ThatFile_v02
NonVersionedFile
Non_VersionedFile

I'm probably over thinking it but I've been thru a lot of iterations and I can't seem to figure this one out. Any help would be appreciated.


问:
Missing Data in Excel between 2 columns
I'm working with a fairly large data set, I have a list of names which appear more than once in column B and in column C i have the team they are part of.

In column C which displays there team name most the data is there but I do have a few 1000 where no team name is not present. Is excel smart enough to go for example Jamie@soso is part of design because it case in "B36" "C36" and then assign design to the missing field?

Here is an example of the data with the missing team names

And here is a view with what im looking for end result wise.

If I need to explain this better please let me know and thank you in advance.

答:
To do without VBA, add a helper column in column C and insert this array formula:

```<code>{=INDEX($B$1:$B$17,MATCH(A1 & "?*",$A$1:$A$17&$B$1:$B$17,0))}
</code>```

To create an array formula, type in the formula without the curly brackets, then press CTRL+SHFT+ENTER. Excel will add the curly brackets.

When you have your column C results, you can copy and paste values to overwrite column B if you want to get rid of your helper column.

This formula looks for rows with a value in A that matches the current row (i.e. same name), and any value in B that isn't blank; "?*" ensures at least one character. The match look up value is therefore A & non-blank B, and the array it's looking in is both A column range and B column range. The INDEX part provides the value from column B if it exists.

Names with no matching column B already completed will give you #N/A so you can manually enter those.

Title: Missing Data in Excel between 2 columns

Body:
To do without VBA, add a helper column in column C and insert this array formula:

{=INDEX($B$1:$B$17,MATCH(A1 & "?*",$A$1:$A$17&$B$1:$B$17,0))}

To create an array formula, type in the formula without the curly brackets, then press CTRL+SHFT+ENTER. Excel will add the curly brackets.

When you have your column C results, you can copy and paste values to overwrite column B if you want to get rid of your helper column.

This formula looks for rows with a value in A that matches the current row (i.e. same name), and any value in B that isn't blank; "?*" ensures at least one character. The match look up value is therefore A & non-blank B, and the array it's looking in is both A column range and B column range. The INDEX part provides the value from column B if it exists.

Names with no matching column B already completed will give you #N/A so you can manually enter those.


问:
python text.strip() returns empty
Good morning everyone;
I'm trying to extract SGML documents using this code, but I got empty documents as a result, this is my python code :

```<code>from os import listdir
from os import makedirs
from os.path import isfile, join
from re import sub
import ast
import numpy
import xml.etree.ElementTree as ElementTree
from lxml import etree

parser = etree.XMLParser(recover=True) # escaping malformed strings
pathCol="C:/Users/Desktop/FR"
pathExtr="C:/Users/Desktop/FRExt"
i=0
for f in listdir(pathCol):
    with open(join(pathCol,f), 'r') as f:   # Reading file
        xml = f.read()

    xml = '<ROOT>' + xml + '</ROOT>'   # Let's add a root tag
    root = etree.fromstring(xml, parser=parser)
    for doc in root:
        try :
            docNo=doc.find('DOCNO').text.strip()
        except :
            i+=1
            docNo="LATIMES"+str(i)
        try :
            text=doc.find('TEXT').text.strip()
        except :
            try :
                text=doc.find('HEADLINE').text.strip()
            except :
                try :
                    text=doc.find('GRAPHIC').text.strip()
                except :
                    text=" "

        fi=open(join(pathExtr,docNo),'w')
        fi.write(text)
        fi.close()
        print("%s OK" %(docNo))
    f.close()
</code>```

And this is a structure of a sample document :

```<code><DOC>
<DOCNO> LA010189-0001 </DOCNO>
<DOCID> 1 </DOCID>
<DATE>
<P>
January 1, 1989, Sunday, Home Edition
</P>
</DATE>
<SECTION>
<P>
Book Review; Page 1; Book Review Desk
</P>
</SECTION>
<LENGTH>
<P>
1206 words
</P>
</LENGTH>
<HEADLINE>
<P>
NEW FALLOUT FROM CHERNOBYL;
</P>
<P>
THE SOCIAL IMPACT OF THE ...
</P>
</HEADLINE>
<BYLINE>
<P>
By James E. ...
</P>
</BYLINE>
<TEXT>
<P>
The onset of the new Gorbachev policy of glasnost,...
</P>
...
</TEXT>
</DOC>
<DOC>
... etc
</DOC>
</code>```

I want to get the content between <TEXT> labels for each document between <DOC> and </DOC>, instead I've got empty documents :(
Please, is there someone that can help me ?
Thanks a lot.

答:
There is no text node in the //ROOT/DOC/TEXT Element, that's why doc.find('TEXT').text returns an empty string.

Instead, there are Element nodes (aka
) that you can iter through.

Finally, to 'stringify' an Element, you can use ET.tostring()

TLDR

```<code>text = ''.join(map(ET.tostring, doc.find('TEXT'))).strip()
</code>```

Title: python text.strip() returns empty

Body:
Good morning everyone;
I'm trying to extract SGML documents using this code, but I got empty documents as a result, this is my python code :

from os import listdir
from os import makedirs
from os.path import isfile, join
from re import sub
import ast
import numpy
import xml.etree.ElementTree as ElementTree
from lxml import etree

parser = etree.XMLParser(recover=True) # escaping malformed strings
pathCol="C:/Users/Desktop/FR"
pathExtr="C:/Users/Desktop/FRExt"
i=0
for f in listdir(pathCol):
    with open(join(pathCol,f), 'r') as f:   # Reading file
        xml = f.read()

    xml = '<ROOT>' + xml + '</ROOT>'   # Let's add a root tag
    root = etree.fromstring(xml, parser=parser)
    for doc in root:
        try :
            docNo=doc.find('DOCNO').text.strip()
        except :
            i+=1
            docNo="LATIMES"+str(i)
        try :
            text=doc.find('TEXT').text.strip()
        except :
            try :
                text=doc.find('HEADLINE').text.strip()
            except :
                try :
                    text=doc.find('GRAPHIC').text.strip()
                except :
                    text=" "

        fi=open(join(pathExtr,docNo),'w')
        fi.write(text)
        fi.close()
        print("%s OK" %(docNo))
    f.close()

And this is a structure of a sample document :

<DOC>
<DOCNO> LA010189-0001 </DOCNO>
<DOCID> 1 </DOCID>
<DATE>

January 1, 1989, Sunday, Home Edition

</DATE>

Book Review; Page 1; Book Review Desk

<LENGTH>

1206 words

</LENGTH>
<HEADLINE>

NEW FALLOUT FROM CHERNOBYL;

THE SOCIAL IMPACT OF THE ...

</HEADLINE>
<BYLINE>

By James E. ...

</BYLINE>
<TEXT>

The onset of the new Gorbachev policy of glasnost,...

...
</TEXT>
</DOC>
<DOC>
... etc
</DOC>

I want to get the content between <TEXT> labels for each document between <DOC> and </DOC>, instead I've got empty documents :(
Please, is there someone that can help me ?
Thanks a lot.

Body:
There is no text node in the //ROOT/DOC/TEXT Element, that's why doc.find('TEXT').text returns an empty string.

Instead, there are Element nodes (aka <P>) that you can iter through.

Finally, to 'stringify' an Element, you can use ET.tostring()

TLDR

text = ''.join(map(ET.tostring, doc.find('TEXT'))).strip()


问:
Distribute small collection output to multiple workers using Apache Beam Python over Google Dataflow
I have a pipeline that looks roughly like this:

```<code>_ (
  p |
  SomeSourceProducingListOfFiles() |
  beam.Map(some_expensive_fn) |
  beam.FlatMap(some_inexpensive_agg)
)
</code>```

SomeSourceProducingListOfFiles in my case is reading from a single CSV/TSV and doesn't currently support splitting.

some_expensive_fn is an expensive operation that may take a minute to run.

some_inexpensive_agg is perhaps not that important for the question but is to show that there are some results brought together for aggregation purpose.

In the case where SomeSourceProducingListOfFiles produces say 100 items, the load doesn't seem to get split across multiple works.

I understand that in general Apache Beam tries to keep things on one worker to reduce serialisation overhead. (And there is some hard coded limit of 1000 items). How can I convince Apache Beam to split the load across multiple workers even for a very small number of items. If I say have three items and three workers I would like each worker to execute one item.

Note: I disabled auto scaling and am using a fixed number of workers.

答: https://cloud.google.com/dataflow/service/dataflow-service-desc#preventing-fusion discusses ways to prevent fusion. Beam Java 2.2+ has a built-in transform to do this, Reshuffle.viaRandomKey(); Beam Python doesn't yet have it so you'll need to code something similar manually using one of the methods by that link.

Body:
I have a pipeline that looks roughly like this:

_ (
  p |
  SomeSourceProducingListOfFiles() |
  beam.Map(some_expensive_fn) |
  beam.FlatMap(some_inexpensive_agg)
)

SomeSourceProducingListOfFiles in my case is reading from a single CSV/TSV and doesn't currently support splitting.

some_expensive_fn is an expensive operation that may take a minute to run.

some_inexpensive_agg is perhaps not that important for the question but is to show that there are some results brought together for aggregation purpose.

In the case where SomeSourceProducingListOfFiles produces say 100 items, the load doesn't seem to get split across multiple works.

I understand that in general Apache Beam tries to keep things on one worker to reduce serialisation overhead. (And there is some hard coded limit of 1000 items). How can I convince Apache Beam to split the load across multiple workers even for a very small number of items. If I say have three items and three workers I would like each worker to execute one item.

Note: I disabled auto scaling and am using a fixed number of workers.


问:
Qt Creator - Opinions and Thoughts
I'm looking for some feedback from anyone that has had a chance to spend some time using Troll Tech's new IDE, Qt Creator. It's in public beta at this point, so there might not be many using it just yet.  But, I think any 3rd party feedback might be useful.

Also, if you do a lot of Qt development, it would also be great to hear about what IDE you do rely on and why you think it is the best option for Qt development.

答:
I'm using Visual Studio 2008 with the commercial QT integration for Visual Studio and it's the best. unfortunately I hadn't had the chance to try the Qt Creator.

Edit: QT integration is indeed not available for open source development. Atleast not legally...

Previously I've worked with QT using KDevelop, using minGW and using just Visual Studio without the integration, creating the .vcproj using qmake and using the designer to edit controls.

The integration plugin has a few advantages over most of the above:

it contains all the features of the designer and more related features that are you don't get in the designer such as the ability to double click a widget to easily connect a signal from it to a slot in the widget's class.

Full debugger support for all of QT's types and generic containers. this is basically an addition to VC's autoexp.dat file.

Visually manage embedded images, much like VC's resource manager

creates moc files automatically for classes deriving from QObject without a need to pass through qmake. infact, you don't even need to know about qmake.

OwnerDisplayName: Fostah

Title: Qt Creator - Opinions and Thoughts

LastEditorDisplayName: Fostah

OwnerDisplayName: Shy

LastEditorDisplayName: Shy


问:
Script working with os.path but not with pathlib (SIGTRAP)
I was advised to take advantage of the pathlib module in Python 3.6, as I am designing a script on Linux that'll be used in production on Windows machines.

pathlib does seem promising, but while my code with the os module works great:

```<code>class Watcher:
    DIRECTORY_TO_WATCH = os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs')

    print(DIRECTORY_TO_WATCH)

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()
</code>```

If I change to the pathlib equivalent:

```<code>from pathlib import Path as p

class Watcher:
    DIRECTORY_TO_WATCH = p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/')
    print(DIRECTORY_TO_WATCH)

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()
</code>```

80% I'll get this error in Pycharm:

Process finished with exit code 133 (interrupted by signal 5: SIGTRAP)

or the script will run, but my triggers won't fire at all.  Confusing.

答:
Ok. I've found the solution:

```<code>os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs')
</code>```

returns an str, while:

```<code>p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/')
</code>```

returns a PosixPath

I ended up casting the latter as a string by using str(), although this looks ugly to me. I'm keeping the question open for better answers.

Body:
I was advised to take advantage of the pathlib module in Python 3.6, as I am designing a script on Linux that'll be used in production on Windows machines.

pathlib does seem promising, but while my code with the os module works great:

class Watcher:
    DIRECTORY_TO_WATCH = os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs')

    print(DIRECTORY_TO_WATCH)

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()

If I change to the pathlib equivalent:

from pathlib import Path as p

class Watcher:
    DIRECTORY_TO_WATCH = p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/')
    print(DIRECTORY_TO_WATCH)

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()

80% I'll get this error in Pycharm:

Process finished with exit code 133 (interrupted by signal 5: SIGTRAP)

or the script will run, but my triggers won't fire at all.  Confusing.

Body:
Ok. I've found the solution:

os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs')

returns an str, while:

p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/')

returns a PosixPath

I ended up casting the latter as a string by using str(), although this looks ugly to me. I'm keeping the question open for better answers.


问:
Kubernetes NetworkPolicy allow loadbalancer
I have a Kubernetes cluster running on Google Kubernetes Engine (GKE) with network policy support enabled.
I created an nginx deployment and load balancer for it:

```<code>kubectl run nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=LoadBalancer
</code>```

Then I created this network policy to make sure other pods in the cluster won't be able to connect to it anymore:

```<code>kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: access-nginx
spec:
  podSelector:
    matchLabels:
      run: nginx
  ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            name: kube-system
    ports:
    - protocol: TCP
      port: 80
</code>```

Now other pods in my cluster can't reach it (as intended):

```<code>kubectl run busybox --rm -ti --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # wget --spider --timeout=1 nginx
Connecting to nginx (10.63.254.50:80)
wget: download timed out
</code>```

However, it surprised me that using my external browser I also can't connect anymore to it through the load balancer:

```<code>open http://$(kubectl get svc nginx --output=jsonpath={.status.loadBalancer.ingress[0].ip})
</code>```

If I delete the policy it starts to work again.

So, my question is: how do I block other pods from reaching nginx, but keep access through the load balancer open?

答:
I talked about this in my Network Policy recipes repository.

"Allowing EXTERNAL load balancers while DENYING local traffic" is not a use case that makes sense, therefore it's not possible to using network policy.

For Service type=LoadBalancer and Ingress resources to work, you must allow ALL traffic to the pods selected by these resources.

If you REALLY want you can use the from.ipBlock.cidr and from.ipBlock.cidr.except resources to allow traffic from 0.0.0.0/0 (all IPv4) and then excluding 10.0.0.0/8 (or whatever private IP range GKE uses).

Body:
I have a Kubernetes cluster running on Google Kubernetes Engine (GKE) with network policy support enabled.
I created an nginx deployment and load balancer for it:

kubectl run nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=LoadBalancer

Then I created this network policy to make sure other pods in the cluster won't be able to connect to it anymore:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: access-nginx
spec:
  podSelector:
    matchLabels:
      run: nginx
  ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            name: kube-system
    ports:
    - protocol: TCP
      port: 80

Now other pods in my cluster can't reach it (as intended):

kubectl run busybox --rm -ti --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # wget --spider --timeout=1 nginx
Connecting to nginx (10.63.254.50:80)
wget: download timed out

However, it surprised me that using my external browser I also can't connect anymore to it through the load balancer:

open http://$(kubectl get svc nginx --output=jsonpath={.status.loadBalancer.ingress[0].ip})

If I delete the policy it starts to work again.

So, my question is: how do I block other pods from reaching nginx, but keep access through the load balancer open?


问:
Change styles on ngb-tab title
I would like to style the title in ngb-tab so that it is not the default blue of an anchor tag. Ideally something like this, but the class property doesn't seem to have an effect on ngb-tab.

The HTML:

```<code><ngb-tabset #t="ngbTabset">
    <ngb-tab [title]="'Followers'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
    <ngb-tab [title]="'Following'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
</ngb-tabset>
</code>```

The CSS:

```<code>.tab-title {
  color: inherit;
}
</code>```

答:
The better option it's the Everest's answer. But as another answer you can use in your component encapsulation: ViewEncapsulation.None

```<code>@Component({
  ...
  templateUrl: 'my-component.component.html',
  styleUrls: ['./my-component.component.css'],
  encapsulation: ViewEncapsulation.None
})
</code>```

This make the css are written to the document head. So, this css apply to entire application. If you want not, you can enclosed the navtab in a div

```<code><div class="customTab">
 <ngb-tabset>
  <ngb-tab title="Simple" class="myClass">
    <ng-template ngbTabContent>
      ...
 <ngb-tabset>
</div>
</code>```

And your .css like

```<code>.customTab .nav-tabs .nav-link.active
{
    color:black;
}
.customTab .nav-tabs .nav-link
{
    color:cyan;
}
</code>```

for more information about ViewEncapsulation see, e.g. https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

Title: Change styles on ngb-tab title

Body:
I would like to style the title in ngb-tab so that it is not the default blue of an anchor tag. Ideally something like this, but the class property doesn't seem to have an effect on ngb-tab.

The HTML:

<ngb-tabset #t="ngbTabset">
    <ngb-tab [title]="'Followers'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
    <ngb-tab [title]="'Following'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
</ngb-tabset>

The CSS:

.tab-title {
  color: inherit;
}

Body:
The better option it's the Everest's answer. But as another answer you can use in your component encapsulation: ViewEncapsulation.None

@Component({
  ...
  templateUrl: 'my-component.component.html',
  styleUrls: ['./my-component.component.css'],
  encapsulation: ViewEncapsulation.None
})

This make the css are written to the document head. So, this css apply to entire application. If you want not, you can enclosed the navtab in a div

<div class="customTab">
 <ngb-tabset>
  <ngb-tab title="Simple" class="myClass">
    <ng-template ngbTabContent>
      ...
 <ngb-tabset>
</div>

And your .css like

.customTab .nav-tabs .nav-link.active
{
    color:black;
}
.customTab .nav-tabs .nav-link
{
    color:cyan;
}

for more information about ViewEncapsulation see, e.g. https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html


问:
JQuery dynamic height issue
1- I want the right sidebar to take the same video height

2- also when I change the video it doesn't take the same height, please click on chapter 2 to see the issue

its work only when I resize the page

I don't know why the sidebar didn't take the same video height can anyone help me, please?

https://codepen.io/kemozzz/full/gXEjjJ/

var vidHeight = $('.video-container').height();
$('.description').css('height', vidHeight + 'px');
$(window).resize(function() {
  var vidHeight = $('.video-container').height();
  $('.description').css('height', vidHeight + 'px');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Tools */

.no-padding {
  padding: 0!important;
}

.slow-effect {
  transition: all .2s ease-in-out;
  -webkit-transition: all .2s ease-in-out;
}

/* ======================================================================================= */

/* Layout ================================================================================ */

.space {
  height: 50px;
}

.container-fluid {
  padding: 0 4%;
}

/* Global Styles ========================================================================= */

/* Form Elements */

/*start places*/

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

.description ul {
  margin: 0;
  padding: 0;
}

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<video controls="" width="100%"><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="test.WEBM" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

```

答:
It's because you need to apply the change on the click event. So you may add this code to resize the video each time you click on a chapter (you may add some delay to be sure you get the correct size) :

```<code>$('ul.nav-tabs a').click(function() {
  setTimeout(function() {
    var vidHeight = $('.video-container').height();
    $('.description').css('height', vidHeight + 'px');
  }, 500);

});
</code>```

You may also use $(document).ready function in order to be sure the resize code works well at page load.

Full code :

$(document).ready(function() {
  setTimeout(function() {
    var vidHeight = $('.video-container').height();
    $('.description').css('height', vidHeight + 'px');
  }, 500);
  $(window).resize(function() {
    var vidHeight = $('.video-container').height();
    $('.description').css('height', vidHeight + 'px');
  });

  $('ul.nav-tabs a').click(function() {
    setTimeout(function() {
      var vidHeight = $('.video-container').height();
      $('.description').css('height', vidHeight + 'px');
    }, 500);

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Tools */

.no-padding {
  padding: 0!important;
}

.slow-effect {
  transition: all .2s ease-in-out;
  -webkit-transition: all .2s ease-in-out;
}

/* ======================================================================================= */

/* Layout ================================================================================ */

.space {
  height: 50px;
}

.container-fluid {
  padding: 0 4%;
}

/* Global Styles ========================================================================= */

/* Form Elements */

/*start places*/

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

.description ul {
  margin: 0;
  padding: 0;
}

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<video controls="" width="100%"><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="test.WEBM" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

```

Title: JQuery dynamic height issue

Body:
1- I want the right sidebar to take the same video height

2- also when I change the video it doesn't take the same height, please click on chapter 2 to see the issue

its work only when I resize the page

I don't know why the sidebar didn't take the same video height can anyone help me, please?

https://codepen.io/kemozzz/full/gXEjjJ/

var vidHeight = $('.video-container').height();
$('.description').css('height', vidHeight + 'px');
$(window).resize(function() {
  var vidHeight = $('.video-container').height();
  $('.description').css('height', vidHeight + 'px');
});

/* Tools */

.no-padding {
  padding: 0!important;
}

.slow-effect {
  transition: all .2s ease-in-out;
  -webkit-transition: all .2s ease-in-out;
}

/* ======================================================================================= */

/* Layout ================================================================================ */

.space {
  height: 50px;
}

.container-fluid {
  padding: 0 4%;
}

/* Global Styles ========================================================================= */

/* Form Elements */

/*start places*/

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

.description ul {
  margin: 0;
  padding: 0;
}

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<video controls="" width="100%"><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="test.WEBM" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

Body:
It's because you need to apply the change on the click event. So you may add this code to resize the video each time you click on a chapter (you may add some delay to be sure you get the correct size) :

$('ul.nav-tabs a').click(function() {
  setTimeout(function() {
    var vidHeight = $('.video-container').height();
    $('.description').css('height', vidHeight + 'px');
  }, 500);

});

You may also use $(document).ready function in order to be sure the resize code works well at page load.

Full code :

$(document).ready(function() {
  setTimeout(function() {
    var vidHeight = $('.video-container').height();
    $('.description').css('height', vidHeight + 'px');
  }, 500);
  $(window).resize(function() {
    var vidHeight = $('.video-container').height();
    $('.description').css('height', vidHeight + 'px');
  });

  $('ul.nav-tabs a').click(function() {
    setTimeout(function() {
      var vidHeight = $('.video-container').height();
      $('.description').css('height', vidHeight + 'px');
    }, 500);

  });
});

/* Tools */

.no-padding {
  padding: 0!important;
}

.slow-effect {
  transition: all .2s ease-in-out;
  -webkit-transition: all .2s ease-in-out;
}

/* ======================================================================================= */

/* Layout ================================================================================ */

.space {
  height: 50px;
}

.container-fluid {
  padding: 0 4%;
}

/* Global Styles ========================================================================= */

/* Form Elements */

/*start places*/

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

.description ul {
  margin: 0;
  padding: 0;
}

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="space"></div>
    <div id="exTab2" class="col-xs-12 no-padding main-container">
      <div class="col-md-9 no-padding video-container tab-content">
        <div id="1" class="tabs-container tab-pane fade in active">
          <!-- Item-1 -->
          <div class="tools slow-effect"></div><video controls="" width="100%"><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
        <div id="2" class="tabs-container tab-pane fade">
          <!-- Item-2 -->
          <div class="tools slow-effect"></div><video controls="" width="100%"><source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
        <div id="3" class="tabs-container tab-pane fade">
          <!-- Item-3 -->
          <div class="tools slow-effect"></div><video controls="" width="100%"><source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
        <div id="4" class="tabs-container tab-pane fade">
          <!-- Item-4 -->
          <div class="tools slow-effect"></div><video controls="" width="100%"><source src="test.WEBM" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
      </div>
      <!-- Item-2 -->
      <div class="col-md-3 description" id="style-1">
        <ul class="nav nav-tabs">
          <li class="active">
            <a data-toggle="tab" href="#1">
              <h2>Chapter 1</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.</p>
            </a>
          </li>
          <li>
            <a data-toggle="tab" href="#2">
              <h2>Chapter 2</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.</p>
            </a>
          </li>
          <li>
            <a data-toggle="tab" href="#3">
              <h2>Chapter 3</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.</p>
            </a>
          </li>
          <li>
            <a data-toggle="tab" href="#4">
              <h2>Chapter 4</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.</p>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>