问:
When does Spring ApplicationContext register itself to BeanFactory?
I'm trying to read source code of spring-boot, and I want to find out when Spring ApplicationContext register itself to BeanFactory. As we can get ApplicationContext by Autowire it as a field like:

```<code>@Autowired
private ApplicationContext context;
</code>```

,so I think there must be some where the ApplicationContext register itself to BeanFactory in source code.If someone know where it locates, please show me. I will appreciate it.

答:
It is in the AbstractApplicationContext line 653:</p>

```<code>beanFactory.registerResolvableDependency(ApplicationContext.class, this);
</code>```

Body:
I'm trying to read source code of spring-boot, and I want to find out when Spring ApplicationContext register itself to BeanFactory. As we can get ApplicationContext by Autowire it as a field like:

@Autowired
private ApplicationContext context;

,so I think there must be some where the ApplicationContext register itself to BeanFactory in source code.If someone know where it locates, please show me. I will appreciate it.

Body:
It is in the AbstractApplicationContext line 653:

beanFactory.registerResolvableDependency(ApplicationContext.class, this);


来源: stackexchange

问:
Javascript returning incorrect value from a Javascript object property
So, I have an array of Javascipt objects, that contain extra properties and information corresponding to the items in a select element.

When the user selects an element in the dropdown, it looks the item up in the Javascipt array, and is supposed to populate two other fields on the page with the relevant values from the corresponding Javascipt object.

Here is the js function:

```<code>    function pickedCode(who) {
        who = $(who);
        var opt = who.find(':selected');
        var val = opt.val();

        for (lc = 0; lc < codes.length; lc++) {
            var code = codes[lc];
            if (code.Id == val) {
                var amt = code.Dollars;
                alert(code.Dollars)
                $('input[field=amount]').val((amt > 0 ? amt : ''));
                $('textarea[field=text]').val(code.Text);
                break;
            }
        }
    }
</code>```

... here is the HTML where it is calling the function:

```<code><select onchange="pickedCode(this);" name="ctl00$ContentPlaceHolder1$lstCodes" id="ctl00_ContentPlaceHolder1_lstCodes">
    <option value=""></option>
    <option value="70">3-DAY NOTICE</option>
    <option value="156">A-ABSOLUTE TRANSCRIPT</option>
    <option value="47">ABORTED EVICTION</option>
    <option value="204">ACCESS AGREEMENT</option>
    <option value="174">ADD'L SERVES/MAILINGS</option>
    <option value="124">AFF IN OPP - COMMERCIAL</option>
</select>
</code>```

... and here is the array of Javascipt data:

```<code>var codes = [{
        "Id": 70,
        "Code": "3-DAY NOTICE",
        "Text": "Initiation of Non-Payment Proceeding.",
        "Dollars": "46.20"
    }, {
        "Id": 156,
        "Code": "A-ABSOLUTE TRANSCRIPT",
        "Text": "A-ABSOLUTE TRANSCRIPT",
        "Dollars": "0.00"
    }, {
        "Id": 47,
        "Code": "ABORTED EVICTION",
        "Text": "THE MARSHAL HAD TO ABORT TODAY'S SCHEDULED EVICTION AS ",
        "Dollars": "0.00"
    }, {
        "Id": 204,
        "Code": "ACCESS AGREEMENT",
        "Text": "ACCESS AGREEMENT",
        "Dollars": "0.00"
    }, {
        "Id": 174,
        "Code": "ADD'L SERVES/MAILINGS",
        "Text": "ADD'L MAILINGS",
        "Dollars": "0.00"
    }, {
        "Id": 124,
        "Code": "AFF IN OPP - COMMERCIAL",
        "Text": "Aff in Opp - COMMERCIAL",
        "Dollars": "85.05"
    }
]
</code>```

It is looking up and finding the proper element.

It is getting the text and setting it into the textarea properly.

The problem is with the property Dollars. For some reason it is always returning a value of "0.00" for the Dollars property, even for the items which have an amount greater than 0, and I cannot for the life of me figure out why. Originally, it was named Amount; I thought maybe that was a reserved word or something, so I changed it to Dollars. I also originally had it as an actual number, instead of a string, and still had the same problem (then it always returned 0). I thought maybe it was a problem in assigning it to the variable, so I alerted the actual property itself instead of the variable (the alert is just for debugging), but the property directly is returning 0.

I also thought maybe it was a type issue when checking the code.Id == val, but that can't be the issue, because it is actually finding the right item and getting the property text from it.

I found a couple other questions on here that were similar, but they all seemed to be related to the property itself being an array and the user not indexing into the property. Mine are not arrays though, the individual properties are all just straight up values.

I've tried this in both Firefox (57.0) and Google Chrome (62.0.3202.94) and even tried Opera (49.0.2725.47), and I get the same results in all three browsers.

Just to truly confuse myself, I decided to step through the client-side debugger in Firefox and see what happens. When viewing the source of the page, it clearly has the value of 46.2:

However when stepping through the function, and looking at the variables, when it pulls out that code from the array, it is loading a value of 0.00 into memory:

So, yeah... now I'm completely confused about what is going on, since the values it is loading into memory do not match the actual source. I did a search through the code to make sure the... and BAH! Looking at the screenshot sparked a thought and I figured it out. Details to come in an answer, for posterity.

答:
Please try replacing  var amt = code.Dollars;  with below:</p>

```<code>var amt = Number(code.Dollars);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So, I have an array of Javascipt objects, that contain extra properties and information corresponding to the items in a select element.

When the user selects an element in the dropdown, it looks the item up in the Javascipt array, and is supposed to populate two other fields on the page with the relevant values from the corresponding Javascipt object.

Here is the js function:

    function pickedCode(who) {
        who = $(who);
        var opt = who.find(':selected');
        var val = opt.val();

        for (lc = 0; lc < codes.length; lc++) {
            var code = codes[lc];
            if (code.Id == val) {
                var amt = code.Dollars;
                alert(code.Dollars)
                $('input[field=amount]').val((amt > 0 ? amt : ''));
                $('textarea[field=text]').val(code.Text);
                break;
            }
        }
    }

... here is the HTML where it is calling the function:

<select onchange="pickedCode(this);" name="ctl00$ContentPlaceHolder1$lstCodes" id="ctl00_ContentPlaceHolder1_lstCodes">
    <option value=""></option>
    <option value="70">3-DAY NOTICE</option>
    <option value="156">A-ABSOLUTE TRANSCRIPT</option>
    <option value="47">ABORTED EVICTION</option>
    <option value="204">ACCESS AGREEMENT</option>
    <option value="174">ADD'L SERVES/MAILINGS</option>
    <option value="124">AFF IN OPP - COMMERCIAL</option>
</select>

... and here is the array of Javascipt data:

var codes = [{
        "Id": 70,
        "Code": "3-DAY NOTICE",
        "Text": "Initiation of Non-Payment Proceeding.",
        "Dollars": "46.20"
    }, {
        "Id": 156,
        "Code": "A-ABSOLUTE TRANSCRIPT",
        "Text": "A-ABSOLUTE TRANSCRIPT",
        "Dollars": "0.00"
    }, {
        "Id": 47,
        "Code": "ABORTED EVICTION",
        "Text": "THE MARSHAL HAD TO ABORT TODAY'S SCHEDULED EVICTION AS ",
        "Dollars": "0.00"
    }, {
        "Id": 204,
        "Code": "ACCESS AGREEMENT",
        "Text": "ACCESS AGREEMENT",
        "Dollars": "0.00"
    }, {
        "Id": 174,
        "Code": "ADD'L SERVES/MAILINGS",
        "Text": "ADD'L MAILINGS",
        "Dollars": "0.00"
    }, {
        "Id": 124,
        "Code": "AFF IN OPP - COMMERCIAL",
        "Text": "Aff in Opp - COMMERCIAL",
        "Dollars": "85.05"
    }
]

It is looking up and finding the proper element.

It is getting the text and setting it into the textarea properly.

The problem is with the property Dollars. For some reason it is always returning a value of "0.00" for the Dollars property, even for the items which have an amount greater than 0, and I cannot for the life of me figure out why. Originally, it was named Amount; I thought maybe that was a reserved word or something, so I changed it to Dollars. I also originally had it as an actual number, instead of a string, and still had the same problem (then it always returned 0). I thought maybe it was a problem in assigning it to the variable, so I alerted the actual property itself instead of the variable (the alert is just for debugging), but the property directly is returning 0.

I also thought maybe it was a type issue when checking the code.Id == val, but that can't be the issue, because it is actually finding the right item and getting the property text from it.

I found a couple other questions on here that were similar, but they all seemed to be related to the property itself being an array and the user not indexing into the property. Mine are not arrays though, the individual properties are all just straight up values.

I've tried this in both Firefox (57.0) and Google Chrome (62.0.3202.94) and even tried Opera (49.0.2725.47), and I get the same results in all three browsers.

Just to truly confuse myself, I decided to step through the client-side debugger in Firefox and see what happens. When viewing the source of the page, it clearly has the value of 46.2:

However when stepping through the function, and looking at the variables, when it pulls out that code from the array, it is loading a value of 0.00 into memory:

So, yeah... now I'm completely confused about what is going on, since the values it is loading into memory do not match the actual source. I did a search through the code to make sure the... and BAH! Looking at the screenshot sparked a thought and I figured it out. Details to come in an answer, for posterity.

Body:
Please try replacing  var amt = code.Dollars;  with below:

var amt = Number(code.Dollars);


问:
How to pass RawQuerySet result as a JSONResponse in DJango?
I have two models like this:

```<code>class McqQuestion(models.Model):
    mcq_question_id = models.IntegerField()
    test_id = models.ForeignKey('exam.Test')
    mcq_right_answer = models.IntegerField()

class UserMcqAnswer(models.Model):
    user = models.ForeignKey('exam.UserInfo')
    test_id = models.ForeignKey('exam.Test')
    mcq_question_id=models.ForeignKey('exam.McqQuestion')
    user_answer = models.IntegerField()
</code>```

I need to match the user_answer and mcq_right_answer. Able to do that by executing the below raw query.

```<code>rightAns=UserMcqAnswer.objects.raw('SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\
                    FROM exam_mcqquestion AS A\
                    LEFT JOIN exam_usermcqanswer AS B\
                    ON A.mcq_question_id=B.mcq_question_id_id\
                    WHERE B.test_id_id=%s AND B.user_id=%s AND\
                    A.mcq_right_answer=B.user_answer',[test_id,user_id])
</code>```

1) But the problem is that couldn't able to pass the result as JSONResponse because it says TypeError: Object of type 'RawQuerySet' is not JSON serializable
2) Is there any alternative to this raw query by using the objects and filtered querysets?

答:
Using raw query is not recommended in Django.

When the model query APIs don’t go far enough, you can fall back to writing raw SQL.

In your case model query API can solve your problem. You can use the following view:

views.py

```<code>def get_answers(request):
    test = Test.objects.get(name="Test 1")
    answers = UserMcqAnswer.objects.filter(test_id=test, user=request.user).annotate(
        is_correct=Case(
            When(user_answer=F('mcq_question_id__mcq_right_answer'),
            then=Value(True)),
            default=Value(False),
            output_field=BooleanField())
    ).values()
return JsonResponse(list(answers), safe=False)
</code>```

Also you can consider Django Rest Framework for serialization of QuerySet.

Body:
I have two models like this:

class McqQuestion(models.Model):
    mcq_question_id = models.IntegerField()
    test_id = models.ForeignKey('exam.Test')
    mcq_right_answer = models.IntegerField()

class UserMcqAnswer(models.Model):
    user = models.ForeignKey('exam.UserInfo')
    test_id = models.ForeignKey('exam.Test')
    mcq_question_id=models.ForeignKey('exam.McqQuestion')
    user_answer = models.IntegerField()

I need to match the user_answer and mcq_right_answer. Able to do that by executing the below raw query.

rightAns=UserMcqAnswer.objects.raw('SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\
                    FROM exam_mcqquestion AS A\
                    LEFT JOIN exam_usermcqanswer AS B\
                    ON A.mcq_question_id=B.mcq_question_id_id\
                    WHERE B.test_id_id=%s AND B.user_id=%s AND\
                    A.mcq_right_answer=B.user_answer',[test_id,user_id])

1) But the problem is that couldn't able to pass the result as JSONResponse because it says TypeError: Object of type 'RawQuerySet' is not JSON serializable
2) Is there any alternative to this raw query by using the objects and filtered querysets?

Body:
Using raw query is not recommended in Django.

When the model query APIs don’t go far enough, you can fall back to writing raw SQL.

In your case model query API can solve your problem. You can use the following view:

views.py

def get_answers(request):
    test = Test.objects.get(name="Test 1")
    answers = UserMcqAnswer.objects.filter(test_id=test, user=request.user).annotate(
        is_correct=Case(
            When(user_answer=F('mcq_question_id__mcq_right_answer'),
            then=Value(True)),
            default=Value(False),
            output_field=BooleanField())
    ).values()
return JsonResponse(list(answers), safe=False)

Also you can consider Django Rest Framework for serialization of QuerySet.


问:
Conditional compilation in Xcode
I would like to 'turn off' the compiler for a section of my code.  I do not want to use comments to 'hide' the code from the compiler because there are a lot of /*...*/ comments embedded in this section.  I would guess that there is a common way to use compiler directives or #defines or something to control the compilation.  In fact my desire to suppress compilation is not dependent on a condition like the SDK or the platform, I would just like to turn it off.  How does one accomplish this?

答:
You could create a preprocessor flag that is checked at compile time. I use this for multiple targets.

Step 3 Writing Preprocessor Codes, of this tutorial for creating multiple targets:

http://just2us.com/2009/07/tutorial-creating-multiple-targets-for-xcode-iphone-projects/

tells you how to create a flag and use the #if conditional compile.

ContentLicense: CC BY-SA 2.5

Title: Conditional compilation in Xcode


问:
Aggregate values under multiple conditions
Given the following tables

```<code>+-----------+-------------+----------+
|   tours   |  tour_user  | tag_tour |
+-----------+-------------+----------+
| id        | tour_id     | tag_id   |
| startdate | user_id     | tour_id  |
+-----------+-------------+----------+
</code>```

I want to achieve a result set like this:

```<code>+-----------------+----------------+----------------+
| DATE(startdate) | COUNT(user_id) | COUNT(tour_id) |
+-----------------+----------------+----------------+
| 2017-12-01      |             55 |             32 |
+-----------------+----------------+----------------+
</code>```

Described in words the amount of users paticipated on a tour and the amount of tours should be aggregated by days.

Additionaly the count of tour and user participation should be filterable via tags which are attachted to tours via tag_tour table (many-to-may-relation).
E.g. I want only the tour and user count of tours which have tag_id 1 AND 2 attaches.

Currently I go with this Query:

```<code>SELECT DATE(tours.start) AS acum_date,
   COUNT(tour_user.user_id) AS guide_assignments,
   A.tour_count
FROM `tour_user`
LEFT JOIN `tours` ON `tours`.`id` = `tour_user`.`tour_id`
LEFT JOIN
      (SELECT DATE(tours.start) AS tour_date,
      COUNT(DISTINCT tours.id) AS tour_count
FROM tours
GROUP BY DATE(tours.start)) AS A ON `A`.`tour_date` = DATE(tours.start)
GROUP BY `acum_date`
ORDER BY `acum_date` ASC
</code>```

The problem with this is, that only the total tour/user count is returned and not the filtered one.

答:
The base query is:

```<code>select t.startdate, count(tu.user_id) as num_users, count(distinct t.id) as num_tours
from tours t left join
     tour_user tu
     on tu.tour_id = t.id
group by t.startdate;
</code>```

In this case, I would recommend using exists for filtering the tags:

```<code>select t.startdate, count(tu.user_id) as num_users, count(distinct t.id) as num_tours
from tours t left join
     tour_user tu
     on tu.tour_id = t.id
where exists (select 1 from tour_tags tt where tt.tour_id = t.tid and tt.tag_id = <tag1>) and
      exists (select 1 from tour_tags tt where tt.tour_id = t.tid and tt.tag_id = <tag2>)
group by t.startdate;
</code>```

Body:
Given the following tables

+-----------+-------------+----------+
|   tours   |  tour_user  | tag_tour |
+-----------+-------------+----------+
| id        | tour_id     | tag_id   |
| startdate | user_id     | tour_id  |
+-----------+-------------+----------+

I want to achieve a result set like this:

+-----------------+----------------+----------------+
| DATE(startdate) | COUNT(user_id) | COUNT(tour_id) |
+-----------------+----------------+----------------+
| 2017-12-01      |             55 |             32 |
+-----------------+----------------+----------------+

Described in words the amount of users paticipated on a tour and the amount of tours should be aggregated by days.

Additionaly the count of tour and user participation should be filterable via tags which are attachted to tours via tag_tour table (many-to-may-relation).
E.g. I want only the tour and user count of tours which have tag_id 1 AND 2 attaches.

Currently I go with this Query:

SELECT DATE(tours.start) AS acum_date,
   COUNT(tour_user.user_id) AS guide_assignments,
   A.tour_count
FROM `tour_user`
LEFT JOIN `tours` ON `tours`.`id` = `tour_user`.`tour_id`
LEFT JOIN
      (SELECT DATE(tours.start) AS tour_date,
      COUNT(DISTINCT tours.id) AS tour_count
FROM tours
GROUP BY DATE(tours.start)) AS A ON `A`.`tour_date` = DATE(tours.start)
GROUP BY `acum_date`
ORDER BY `acum_date` ASC

The problem with this is, that only the total tour/user count is returned and not the filtered one.

Body:
The base query is:

select t.startdate, count(tu.user_id) as num_users, count(distinct t.id) as num_tours
from tours t left join
     tour_user tu
     on tu.tour_id = t.id
group by t.startdate;

In this case, I would recommend using exists for filtering the tags:

select t.startdate, count(tu.user_id) as num_users, count(distinct t.id) as num_tours
from tours t left join
     tour_user tu
     on tu.tour_id = t.id
where exists (select 1 from tour_tags tt where tt.tour_id = t.tid and tt.tag_id = <tag1>) and
      exists (select 1 from tour_tags tt where tt.tour_id = t.tid and tt.tag_id = <tag2>)
group by t.startdate;


问:
How to use sum function in where clause in SQL Server?
I am new to SQL Server. I want to equal two columns using sum function. Please find the below query.

```<code>select top 1000
    o.orderamount, sum(oi.amount), oi.orderid
from
    orders o
inner join
    orderitem oi on o.orderid = oi.orderid
where
    orderamount = sum(oi.amount)
group by
    oi.orderid, orderamount
order by
    oi.orderid desc
</code>```

Whenever I execute this code, I get an error.

Please help me.

答:
Try using HAVING instead of WHERE clauses in sum queries.
Also: add indentation and UPPER CASE for readability</p>

```<code>SELECT TOP 1000  o.OrderAmount, sum(oi.Amount), oi.OrderID
  FROM  Orders o
        INNER JOIN OrderItem oi ON oi.OrderID = o.OrderID
  GROUP BY  oi.OrderID, OrderAmount
    HAVING  OrderAmount = sum(oi.Amount)
  ORDER BY  oi.OrderID DESC;
</code>```

Body:
I am new to SQL Server. I want to equal two columns using sum function. Please find the below query.

select top 1000
    o.orderamount, sum(oi.amount), oi.orderid
from
    orders o
inner join
    orderitem oi on o.orderid = oi.orderid
where
    orderamount = sum(oi.amount)
group by
    oi.orderid, orderamount
order by
    oi.orderid desc

Whenever I execute this code, I get an error.

Please help me.

Body:
Try using HAVING instead of WHERE clauses in sum queries.
Also: add indentation and UPPER CASE for readability

SELECT TOP 1000  o.OrderAmount, sum(oi.Amount), oi.OrderID
  FROM  Orders o
        INNER JOIN OrderItem oi ON oi.OrderID = o.OrderID
  GROUP BY  oi.OrderID, OrderAmount
    HAVING  OrderAmount = sum(oi.Amount)
  ORDER BY  oi.OrderID DESC;


问:
std::ostream : class is inaccesible [C++]
I am getting this error in my implementation:

struct bookdatabase::Bookdatabase::Book

class "bookdatabase::BookDatabase::Book" is inaccessible

None of the following solutions solved my problem:

std::basic_ostream is inaccessible in C++

cannot access private members in friend ostream

My ostream and istream friend function can't access private class members

member of class inaccessible

Inaccessible Members ?

Here's a picture of what visual studio has issue with in the .cpp file.

Here's a picture of the declaration in the header file.

Database.h

```<code>#include <string>
#include <vector>

#ifndef BOOKDATABASE_H
#define BOOKDATABASE_H

namespace bookdatabase {
    class BookDatabase {
    private:
        struct Book {
        private:
            std::string authorFirstName, authorLastName, authorFullName, bookTitle, pubDate;
        public:
            Book(const std::string &authFirst, const std::string &authLast, const std::string &title, const std::string &date);
            std::string getAuthor() const;
            std::string getBookTitle() const;
            std::string getPubDate() const;
            bool operator < (const Book &rhs) const;
            friend std::ostream& operator << (std::ostream& out, const bookdatabase::BookDatabase::Book& book);
        };
        void sortBooks();
        std::vector<Book>::iterator search(const std::string &title);
    public:
        BookDatabase();
        void printBookList();
        std::vector<Book> getDatabase() const;
        void removeBook(const std::string &title);

        void addBook(const std::string &authFirst, const std::string &authLast, const std::string &title, const std::string &date);
    private:
        std::vector<Book> database;
    };
}

#endif // BOOKDATABASE_H
</code>```

Database.cpp

```<code>std::ostream & bookdatabase::operator<<(std::ostream & out, const bookdatabase::BookDatabase::Book & book) {
    out << authorFullName << ". " << bookTitle << ". " << pubDate;
    return out;
}
</code>```

Am I having this issue because the Book class is a nested class?

答:
My answer for most operator << woes is to declare a member print() method that does the hard work and call it from operator <<.
Usually I am happy for the print method to be public, and get rid of all the friend nastiness.</p>

Body:
I am getting this error in my implementation:

struct bookdatabase::Bookdatabase::Book

class "bookdatabase::BookDatabase::Book" is inaccessible

None of the following solutions solved my problem:

std::basic_ostream is inaccessible in C++

cannot access private members in friend ostream

My ostream and istream friend function can't access private class members

member of class inaccessible

Inaccessible Members ?

Here's a picture of what visual studio has issue with in the .cpp file.

Here's a picture of the declaration in the header file.

Database.h

#include <string>
#include <vector>

#ifndef BOOKDATABASE_H
#define BOOKDATABASE_H

namespace bookdatabase {
    class BookDatabase {
    private:
        struct Book {
        private:
            std::string authorFirstName, authorLastName, authorFullName, bookTitle, pubDate;
        public:
            Book(const std::string &authFirst, const std::string &authLast, const std::string &title, const std::string &date);
            std::string getAuthor() const;
            std::string getBookTitle() const;
            std::string getPubDate() const;
            bool operator < (const Book &rhs) const;
            friend std::ostream& operator << (std::ostream& out, const bookdatabase::BookDatabase::Book& book);
        };
        void sortBooks();
        std::vector<Book>::iterator search(const std::string &title);
    public:
        BookDatabase();
        void printBookList();
        std::vector<Book> getDatabase() const;
        void removeBook(const std::string &title);

        void addBook(const std::string &authFirst, const std::string &authLast, const std::string &title, const std::string &date);
    private:
        std::vector<Book> database;
    };
}

#endif // BOOKDATABASE_H

Database.cpp

std::ostream & bookdatabase::operator<<(std::ostream & out, const bookdatabase::BookDatabase::Book & book) {
    out << authorFullName << ". " << bookTitle << ". " << pubDate;
    return out;
}

Am I having this issue because the Book class is a nested class?


问:
How do I access Dependency Injection graph in .NET Core 2.0 ConfigureServices()
I am trying to migrate from .NET Core 1.1 to 2.0, and am stuck migrating the JWT Token configuration. I have an interface/class that provides the JWTBearerOptions, and in .NET Core 2.0 I cannot access my DI Graph objects (since in 2.0, JWT is configured in the ConfigureServices() function). I want to keep my Startup.cs file clean of so many lines of code configuring JWT.

Is there any way to delegate the JWTBearerOptions object creation to a provider created through DI? I want something like the below:

```<code>public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication()
            .AddJwtBearer(MyAuthicationScheme.JwtAuthName, options =>
            {
                myInjectedInstance.SetJwtBearOptions(options, Configuration);
            })
    }
</code>```

答: Found the answer on microsoft's docs. It is impossible to access DI objects during the ConfigureServices call: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/index?tabs=basicconfiguration#additional-notes</p>

Body:
I am trying to migrate from .NET Core 1.1 to 2.0, and am stuck migrating the JWT Token configuration. I have an interface/class that provides the JWTBearerOptions, and in .NET Core 2.0 I cannot access my DI Graph objects (since in 2.0, JWT is configured in the ConfigureServices() function). I want to keep my Startup.cs file clean of so many lines of code configuring JWT.

Is there any way to delegate the JWTBearerOptions object creation to a provider created through DI? I want something like the below:

public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication()
            .AddJwtBearer(MyAuthicationScheme.JwtAuthName, options =>
            {
                myInjectedInstance.SetJwtBearOptions(options, Configuration);
            })
    }


问:
Rails + Authlogic @current_user problem - "Show" method no longer works
I implemented Authlogic in my rails app which works and tests great. Users can login, logout, etc.

However, since I changed my methods in the users_controller to use the @current_user variable, none of my user methods or forms (other than "index" strangely...) work!

For example, this "Show" methods works and shows the user profile for any user (Note: I want to eventually restrict this to the currently logged in user somehow):

```<code>def show
    @user = User.find(params[:id])
end
</code>```

If I follow the show method as shown in the Authlogic rails cast and the official example to:

```<code>def show
    @user = @current_user
end
</code>```

I get all kinds of undefined method METHOD for nil:NilClass errors. It seems as the though the @current_user variable doesn't contain any of the user's information.

I assume the @current_user is pulling info from the current_user method as defined in the application controller below:

```<code>def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end
</code>```

What am I missing? My hunch is that there is no mapping between the User object from the user model and the current_user method. Any help would be greatly appreciated!

Thanks in advance!

~Dan

答:
```<code>def
if @current_user
 @user = @current_user
else
 @user = User.find(params[:id])
end
end
</code>```

Just a guess, give a try on it.

Body:
I implemented Authlogic in my rails app which works and tests great. Users can login, logout, etc.

However, since I changed my methods in the users_controller to use the @current_user variable, none of my user methods or forms (other than "index" strangely...) work!

For example, this "Show" methods works and shows the user profile for any user (Note: I want to eventually restrict this to the currently logged in user somehow):

def show
    @user = User.find(params[:id])
end

If I follow the show method as shown in the Authlogic rails cast and the official example to:

def show
    @user = @current_user
end

I get all kinds of undefined method METHOD for nil:NilClass errors. It seems as the though the @current_user variable doesn't contain any of the user's information.

I assume the @current_user is pulling info from the current_user method as defined in the application controller below:

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

What am I missing? My hunch is that there is no mapping between the User object from the user model and the current_user method. Any help would be greatly appreciated!

Thanks in advance!

~Dan

Body:
def
if @current_user
 @user = @current_user
else
 @user = User.find(params[:id])
end
end

Just a guess, give a try on it.


问:
.OldValue property in Undo button handler of form gives run-time error 2448
This is my first question, so I hope I get it right.

I am working on a project to review Employee information. I am using two forms, the first one is "ReadOnly," the second is "EditOnly."

The "ReadOnly" form is bound to a query, which defines criteria for specific records to be displayed.

The "EditOnly" form has a subform, bound to 2 tables (which are also part of the query that is the source for the "ReadOnly" form), that have a 1-to-many relation (using info from this answer:
Error 3251 on .oldValue control property).

The "EditOnly" form is opened via a button and is used to edit the data of a specific Employee. In this form I have an Undo button, using this code:

```<code>Sub UndoEdits()
  If Me.Dirty Then
    Me!btnUndo.Enabled = True
  Else
    Me!btnUndo.Enabled = False
  End If
End Sub

Sub btnUndo Click()
  Dim ctlC As Control
  For Each ctlC in Me.Controls
    If ctlC.ControlType = acTextBox Then
      ctlC.Value = ctlC.OldValue
    End If
  Next ctlC
End Sub
</code>```

which reverts unwanted changes. But when testing the function, after changing some data I get run-time error 2448. Using Debug highlights this row:

```<code>ctlC.Value = ctlC.OldValue
</code>```

Is there a way to make the Undo button work?

答:
Error 2448 is "Can't assign a value to this object".

You will get this error if you try to assign a value to any text boxes on the form that are read only/locked or disabled.

Modify your code to check ctlc for Enabled and Locked and skip any controls that aren't assignable, like this:

```<code>  Dim ctlC As Control

  For Each ctlC in Me.Controls
    If ctlC.ControlType = acTextBox Then
        If ctlC.Enabled And Not ctlC.Locked Then
            ctlC.Value = ctlC.OldValue
        End If
    End If
  Next ctlC
</code>```

Debugging Tip:

You can check the value of ctlc.Name either by stepping or by writing to the immediate window (Debug.Print ctlc.Name) to see which text box is the source of the problem.

Body:
This is my first question, so I hope I get it right.

I am working on a project to review Employee information. I am using two forms, the first one is "ReadOnly," the second is "EditOnly."

The "ReadOnly" form is bound to a query, which defines criteria for specific records to be displayed.

The "EditOnly" form has a subform, bound to 2 tables (which are also part of the query that is the source for the "ReadOnly" form), that have a 1-to-many relation (using info from this answer:
Error 3251 on .oldValue control property).

The "EditOnly" form is opened via a button and is used to edit the data of a specific Employee. In this form I have an Undo button, using this code:

Sub UndoEdits()
  If Me.Dirty Then
    Me!btnUndo.Enabled = True
  Else
    Me!btnUndo.Enabled = False
  End If
End Sub

Sub btnUndo Click()
  Dim ctlC As Control
  For Each ctlC in Me.Controls
    If ctlC.ControlType = acTextBox Then
      ctlC.Value = ctlC.OldValue
    End If
  Next ctlC
End Sub

which reverts unwanted changes. But when testing the function, after changing some data I get run-time error 2448. Using Debug highlights this row:

ctlC.Value = ctlC.OldValue

Is there a way to make the Undo button work?

Body:
Error 2448 is "Can't assign a value to this object".

You will get this error if you try to assign a value to any text boxes on the form that are read only/locked or disabled.

Modify your code to check ctlc for Enabled and Locked and skip any controls that aren't assignable, like this:

  Dim ctlC As Control

  For Each ctlC in Me.Controls
    If ctlC.ControlType = acTextBox Then
        If ctlC.Enabled And Not ctlC.Locked Then
            ctlC.Value = ctlC.OldValue
        End If
    End If
  Next ctlC

Debugging Tip:

You can check the value of ctlc.Name either by stepping or by writing to the immediate window (Debug.Print ctlc.Name) to see which text box is the source of the problem.


问:
Is there a way to close and open a VBA macro while running and start running again?
I have a VBA macro that opens up ETABS using API, but the command myETABSObject.ApplicationStart sometimes doesn't work, it gets stuck while opening ETABS. I would like to know if there is a way to force quit ETABS, close and open Excel, and then start running the macro again?

```<code>If AttachToInstance Then
    'attach to a running instance of ETABS
    'get the active ETABS object
    Set myETABSObject = GetObject(, "CSI.ETABS.API.ETABSObject")
  Else
    If SpecifyPath Then
      'create an instance of the ETABS object from the specified path
      Set myETABSObject = myHelper.CreateObject(ProgramPath)
    Else
      'create an instance of the ETABS object from the latest installed ETABS
      Set myETABSObject = myHelper.CreateObjectProgID("CSI.ETABS.API.ETABSObject")
    End If
    'start ETABS application
    myETABSObject.ApplicationStart
  End If
</code>```

答:
As you can see in the comments, it's not possible. But you can do a very crude workaround.

Create a sub that runs when the workbook is opened. This sub will contain the code that you want to run again. But the first step of the sub should be checking some parameter, so it wouldn't run every time you open it, but only on restart. The parameter can be for example a value in some cell, that you put there before you closed the workbook.

Now the only problem is how to open the workbook once it is closed. You can create a helper Excel workbook, also with a sub that run when the workbook is opened. The only thing that the sub does is to set a timer and after the wait period, it opens the workbook you want to restart. You need to open the helper workbook before closing the other one.

This should get you what you need. Of course, it is nothing you can publish, but for your purposes (e.g. weekly report) should be fine.

Body:
I have a VBA macro that opens up ETABS using API, but the command myETABSObject.ApplicationStart sometimes doesn't work, it gets stuck while opening ETABS. I would like to know if there is a way to force quit ETABS, close and open Excel, and then start running the macro again?

If AttachToInstance Then
    'attach to a running instance of ETABS
    'get the active ETABS object
    Set myETABSObject = GetObject(, "CSI.ETABS.API.ETABSObject")
  Else
    If SpecifyPath Then
      'create an instance of the ETABS object from the specified path
      Set myETABSObject = myHelper.CreateObject(ProgramPath)
    Else
      'create an instance of the ETABS object from the latest installed ETABS
      Set myETABSObject = myHelper.CreateObjectProgID("CSI.ETABS.API.ETABSObject")
    End If
    'start ETABS application
    myETABSObject.ApplicationStart
  End If


问:
Result list is not being displayed (google-fusion-tables template derek)
I am trying to make a searchable map with the great template Derek made.

I have tried everything but somehow I do not manage to get my result list to display. Div is visible but no results. Hope someone can help me. I followed these instructions:

This is part of the index

```<code><a class='btn btn-primary' id='search' href='#'>
          <i class='glyphicon glyphicon-search'></i>
          Zoeken
        </a>
        <a class='btn btn-default' id='reset' href='#'>
          <i class='glyphicon glyphicon-repeat'></i>
          Reset
        </a>
      </div>
      <div class='alert alert-info' id='result_box' ><strong id='result_count'></strong></div>
       <div class='well'> <div id='results_list'></div> </div>
    </div>
    <div class='col-md-8'>
      <noscript>
        <div class='alert alert-info'>
          <h4>Your JavaScript is disabled</h4>
          <p>Please enable JavaScript to view the map.</p>
        </div>
      </noscript>
      <div id='map_canvas'></div>
</code>```

And this the maps_lib.js

```<code>submitSearch: function(whereClause, map, location) {
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles

MapsLib.searchrecords = new google.maps.FusionTablesLayer({
  query: {
    from:   MapsLib.fusionTableId,
    select: MapsLib.locationColumn,
    where:  whereClause
  },
  styleId: 2,
  templateId: 2
});
MapsLib.searchrecords.setMap(map);
MapsLib.getCount(whereClause);
MapsLib.getList(whereClause);},
</code>```

And this:

```<code>    getCount: function(whereClause) {
    var selectColumns = "Count()";
    MapsLib.query(selectColumns, whereClause, "", "", "MapsLib.displaySearchCount");
  },

  displaySearchCount: function(json) {
    MapsLib.handleError(json);
    var numRows = 0;
    if (json["rows"] != null)
      numRows = json["rows"][0];

    var name = MapsLib.recordNamePlural;
    if (numRows == 1)
    name = MapsLib.recordName;
    $( "#result_box" ).fadeOut(function() {
        $( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " gevonden");
      });
    $( "#result_box" ).fadeIn();
  },

getList: function(whereClause) {
  var selectColumns = "Achternaam, Adres, Postcode, Woonplaats";
  MapsLib.query(selectColumns, whereClause, "MapsLib.displayList");
},

displayList: function(json) {
  MapsLib.handleError(json);
  var data = json["rows"];
  var template = "";

  var results = $("#results_list");
  results.hide().empty(); //hide the existing list and empty it out first

  if (data == null) {
    //clear results list
    results.append("<li><span class='lead'>No results found</span></li>");
  }
  else {
    for (var row in data) {
      template = "\
        <div class='row-fluid item-list'>\
          <div class='span12'>\
            <strong>" + data[row][0] + "</strong>\
            <br />\
            " + data[row][1] + "\
            <br />\
            " + data[row][2] + "\
            <br />\
            " + data[row][3] + "\
          </div>\
        </div>"
      results.append(template);
    }
  }
  results.fadeIn();
},
</code>```

答:
I don’t know if you are still looking for an answer to this question but maybe somebody else is as they browse these topics.
 Using Derek’s awesome template –
Here is the code I used to create the container box on the main (index) page.

```<code><div class='well'>
  <div class="scrollr" id='results_list'></div>
</div>
</code>```

Note: I added the “scrollr” reference and created the code for it in the “custom.css” file.
This simply puts a border around the result list box and makes it scrollable. Here is style code I added to the custom.css file:

```<code>.scrollr {
    height: 400px;
    overflow: scroll;
    border-style: solid;
    border-color: darkgray;
    background-color: lightgray;
}
</code>```

Finally, here is the code I added to the “maps_lib.js” file after the “displaySearchCount” function.
//DISPLAY RESULTS FUNCIION----------------------------------------------------------------------------------------

```<code>MapsLib.prototype.getList = function(whereClause) {
    var self = this;
    var selectColumns = 'Column1, Column2, Column3, Column4, Column5';

    self.query({
      select: selectColumns,
      where: whereClause
    }, function(response) {
      self.displayList(response);
     });

  },

  MapsLib.prototype.displayList = function(json) {
    var self = this;

    var data = json['rows'];
    var template = '';

    var results = $('#results_list');
    results.hide().empty(); //hide the existing list and empty it out first

    if (data == null) {
      //clear results list
      results.append("<li><span class='lead'>No results found</span></li>");
    }
    else {
      for (var row in data) {
        template = "\
          <div class='row-fluid item-list'>\
            <div class='span12'>\
              <strong>" + data[row][0] + "</strong>\
              <br />\
              " + data[row][1] + "\
              <br />\
              " + data[row][2] + "\
              <br />\
              " + data[row][3] + "\
               <br />\
              " + data[row][4] + "<br>\
            </div>\
          </div>";
        results.append(template);
      }
    }
    results.fadeIn();
  },
</code>```

Hope this helps someone.

Body:
I am trying to make a searchable map with the great template Derek made.

I have tried everything but somehow I do not manage to get my result list to display. Div is visible but no results. Hope someone can help me. I followed these instructions:

This is part of the index

          Zoeken

          Reset

Your JavaScript is disabled

Please enable JavaScript to view the map.

And this the maps_lib.js

submitSearch: function(whereClause, map, location) {
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles

MapsLib.searchrecords = new google.maps.FusionTablesLayer({
  query: {
    from:   MapsLib.fusionTableId,
    select: MapsLib.locationColumn,
    where:  whereClause
  },
  styleId: 2,
  templateId: 2
});
MapsLib.searchrecords.setMap(map);
MapsLib.getCount(whereClause);
MapsLib.getList(whereClause);},

And this:

    getCount: function(whereClause) {
    var selectColumns = "Count()";
    MapsLib.query(selectColumns, whereClause, "", "", "MapsLib.displaySearchCount");
  },

  displaySearchCount: function(json) {
    MapsLib.handleError(json);
    var numRows = 0;
    if (json["rows"] != null)
      numRows = json["rows"][0];

    var name = MapsLib.recordNamePlural;
    if (numRows == 1)
    name = MapsLib.recordName;
    $( "#result_box" ).fadeOut(function() {
        $( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " gevonden");
      });
    $( "#result_box" ).fadeIn();
  },

getList: function(whereClause) {
  var selectColumns = "Achternaam, Adres, Postcode, Woonplaats";
  MapsLib.query(selectColumns, whereClause, "MapsLib.displayList");
},

displayList: function(json) {
  MapsLib.handleError(json);
  var data = json["rows"];
  var template = "";

  var results = $("#results_list");
  results.hide().empty(); //hide the existing list and empty it out first

  if (data == null) {
    //clear results list
    results.append("
No results found
");
  }
  else {
    for (var row in data) {
      template = "\

\

\
            " + data[row][0] + "\

\
            " + data[row][1] + "\

\
            " + data[row][2] + "\

\
            " + data[row][3] + "\

\

"
      results.append(template);
    }
  }
  results.fadeIn();
},

Body:
I don’t know if you are still looking for an answer to this question but maybe somebody else is as they browse these topics.
 Using Derek’s awesome template –
Here is the code I used to create the container box on the main (index) page.

<div class='well'>
  <div class="scrollr" id='results_list'></div>
</div>

Note: I added the “scrollr” reference and created the code for it in the “custom.css” file.
This simply puts a border around the result list box and makes it scrollable. Here is style code I added to the custom.css file:

.scrollr {
    height: 400px;
    overflow: scroll;
    border-style: solid;
    border-color: darkgray;
    background-color: lightgray;
}

Finally, here is the code I added to the “maps_lib.js” file after the “displaySearchCount” function.
//DISPLAY RESULTS FUNCIION----------------------------------------------------------------------------------------

MapsLib.prototype.getList = function(whereClause) {
    var self = this;
    var selectColumns = 'Column1, Column2, Column3, Column4, Column5';

    self.query({
      select: selectColumns,
      where: whereClause
    }, function(response) {
      self.displayList(response);
     });

  },

  MapsLib.prototype.displayList = function(json) {
    var self = this;

    var data = json['rows'];
    var template = '';

    var results = $('#results_list');
    results.hide().empty(); //hide the existing list and empty it out first

    if (data == null) {
      //clear results list
      results.append("<li><span class='lead'>No results found</span></li>");
    }
    else {
      for (var row in data) {
        template = "\
          <div class='row-fluid item-list'>\
            <div class='span12'>\
              <strong>" + data[row][0] + "</strong>\
              <br />\
              " + data[row][1] + "\
              <br />\
              " + data[row][2] + "\
              <br />\
              " + data[row][3] + "\
               <br />\
              " + data[row][4] + "<br>\
            </div>\
          </div>";
        results.append(template);
      }
    }
    results.fadeIn();
  },

Hope this helps someone.


问:
php mysql sum row values starting with MIN and ending at a fixed number
First, I am querying my database in such a way to only retrieve rows that will add up to a predetermined number starting with the smallest value

```<code>$value = $_POST['number'];//75
$query = SELECT * FROM t WHERE t.col <= '$value' Order By ASC
</code>```

Request: Then only select and print the rows that sum up to $value starting with the smallest. Adding rows until it reaches 75

```<code>while($rows = mysql_fetch_array($query)){
$row = $rows['t.col'];
//need rows that add to 75
echo $row
}
</code>```

答:
this should echo out the t.col values untill the sum matches 75</p>

```<code><?php
$row = 0;
while ( $rows = mysql_fetch_array($query) ){
    $row += $rows['t.col'];
    // need rows that add to 75
    echo $rows['t.col'];

    if ($row >= 75){
        break; // exit loop
    }
}
</code>```

Body:
First, I am querying my database in such a way to only retrieve rows that will add up to a predetermined number starting with the smallest value

$value = $_POST['number'];//75
$query = SELECT * FROM t WHERE t.col <= '$value' Order By ASC

Request: Then only select and print the rows that sum up to $value starting with the smallest. Adding rows until it reaches 75

while($rows = mysql_fetch_array($query)){
$row = $rows['t.col'];
//need rows that add to 75
echo $row
}

Body:
this should echo out the t.col values untill the sum matches 75

<?php
$row = 0;
while ( $rows = mysql_fetch_array($query) ){
    $row += $rows['t.col'];
    // need rows that add to 75
    echo $rows['t.col'];

    if ($row >= 75){
        break; // exit loop
    }
}


问:
How to record desktop while on x2go session via a command line tool?

the Goal:

I am trying to record a specific X display on a remote server with a command line tool.

the Problem:

The output file contains a pure black video stream for the whole duration of the recording.

My Approach:
I am connecting to a remote server via x2go. The Server runs Ubuntu 16.04.2 with Xfce Desktop Environment. The Display I try to record is :50 (which gets created when I connect to the x2go server). I can control the remote server totally fine through x2go.

My commands for recording via ffmpeg (or avconv/recordmydesktop, which use ffmpeg underneath) all look more or less the same and are like this:

ffmpeg -f x11grab -r 25 -s 1854x1176 -i :50.0 -c:v libx264 screencast.mkv

Sample output:

```<code>user@machine:~/$ ffmpeg -f x11grab -r 25 -s 1854x1176 -i :50.0+0,0 -c:v libx264 -vb 4000k -an screencast.mkv
ffmpeg version N-86766-g264f6c6 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.4) 20160609
  configuration: --prefix=/home/user/ffmpeg_build --pkg-config-flags=--static --extra-cflags=-I/home/user/ffmpeg_build/include --extra-ldflags=-L/home/user/ffmpeg_build/lib --bindir=/home/user/bin --enable-gpl --enable-libass --enable-libfdk-aac --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-nonfree
  libavutil      55. 67.100 / 55. 67.100
  libavcodec     57.100.104 / 57.100.104
  libavformat    57. 75.100 / 57. 75.100
  libavdevice    57.  7.100 / 57.  7.100
  libavfilter     6. 95.100 /  6. 95.100
  libswscale      4.  7.101 /  4.  7.101
  libswresample   2.  8.100 /  2.  8.100
  libpostproc    54.  6.100 / 54.  6.100
[x11grab @ 0x1fd9b40] XFixes not available, cannot draw the mouse.
[x11grab @ 0x1fd9b40] Stream #0: not enough frames to estimate rate; consider increasing probesize
Input #0, x11grab, from ':50.0+0,0':
  Duration: N/A, start: 1500041497.684675, bitrate: N/A
    Stream #0:0: Video: rawvideo (BGR[0] / 0x524742), bgr0, 1854x1176, 25 fps, 1000k tbr, 1000k tbn, 1000k tbc
File 'screencast.mkv' already exists. Overwrite ? [y/N] y
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> h264 (libx264))
Press [q] to stop, [?] for help
[libx264 @ 0x1fe3040] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0x1fe3040] profile High 4:4:4 Predictive, level 4.2, 4:4:4 8-bit
[libx264 @ 0x1fe3040] 264 - core 148 r2643 5c65704 - H.264/MPEG-4 AVC codec - Copyleft 2003-2015 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=4 threads=12 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=abr mbtree=1 bitrate=4000 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, matroska, to 'screencast.mkv':
  Metadata:
    encoder         : Lavf57.75.100
    Stream #0:0: Video: h264 (libx264) (H264 / 0x34363248), yuv444p, 1854x1176, q=-1--1, 4000 kb/s, 25 fps, 1k tbn, 25 tbc
    Metadata:
      encoder         : Lavc57.100.104 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/4000000 buffer size: 0 vbv_delay: -1
[swscaler @ 0x1fe94e0] Warning: data is not aligned! This can lead to a speedloss
frame=  179 fps= 36 q=-1.0 Lsize=      16kB time=00:00:07.04 bitrate=  18.8kbits/s speed=1.43x
video:14kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 12.869934%
[libx264 @ 0x1fe3040] frame I:1     Avg QP: 6.00  size:   518
[libx264 @ 0x1fe3040] frame P:45    Avg QP: 0.44  size:    81
[libx264 @ 0x1fe3040] frame B:133   Avg QP: 0.94  size:    73
[libx264 @ 0x1fe3040] consecutive B-frames:  0.6%  1.1%  0.0% 98.3%
[libx264 @ 0x1fe3040] mb I  I16..4:  0.0% 100.0%  0.0%
[libx264 @ 0x1fe3040] mb P  I16..4:  0.0%  0.0%  0.0%  P16..4:  0.0%  0.0%  0.0%  0.0%  0.0%    skip:100.0%
[libx264 @ 0x1fe3040] mb B  I16..4:  0.0%  0.0%  0.0%  B16..8:  0.0%  0.0%  0.0%  direct: 0.0%  skip:100.0%
[libx264 @ 0x1fe3040] final ratefactor: -23.85
[libx264 @ 0x1fe3040] 8x8 transform intra:100.0%
[libx264 @ 0x1fe3040] coded y,u,v intra: 0.0% 0.0% 0.0% inter: 0.0% 0.0% 0.0%
[libx264 @ 0x1fe3040] i16 v,h,dc,p:  0%  0% 100%  0%
[libx264 @ 0x1fe3040] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu:  0%  0% 100%  0%  0%  0%  0%  0%  0%
[libx264 @ 0x1fe3040] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0x1fe3040] kb/s:15.56
</code>```

Using: Ubuntu 16.04.2 LTS

I have successfully accomplished to capture the display :50 with "simplescreenrecorder", but that tool has no command line interface. It uses ffmpeg also, so it somehow should be possible to caputure the display but I can´t get it to work properly.

答:
I think I've managed to find the cause. I need to setup a similar system and using a software other than x2go is not an option. Anyway to those searching for a possible solution pay attention to the following message:

```<code>[x11grab @ 0x1fd9b40] XFixes not available, cannot draw the mouse.
</code>```

The xfixes extension is required by FFmpeg to record the screen through the xcblib and aparently, xfixes is disabled by default on recent x2goserver versions due to a bug. You can enable it editing the x2goagent.options file (normally  /etc/x2go/x2goagent.options) and removing the following parameter:

```<code># Disable XFIXES.
# Workaround for https://bugs.launchpad.net/ubuntu/+source/libxfixes/+bug/985202
#
X2GO_NXAGENT_DEFAULT_OPTIONS+=" -extension XFIXES"
</code>```

You can leave it as

```<code>    X2GO_NXAGENT_DEFAULT_OPTIONS+=""
</code>```

As for the bug itself I have no idea if it will bite me. If its not a KDE machine then I think it should be ok.

Body:
the Goal:

I am trying to record a specific X display on a remote server with a command line tool.

the Problem:

The output file contains a pure black video stream for the whole duration of the recording.

My Approach:
I am connecting to a remote server via x2go. The Server runs Ubuntu 16.04.2 with Xfce Desktop Environment. The Display I try to record is :50 (which gets created when I connect to the x2go server). I can control the remote server totally fine through x2go.

My commands for recording via ffmpeg (or avconv/recordmydesktop, which use ffmpeg underneath) all look more or less the same and are like this:

ffmpeg -f x11grab -r 25 -s 1854x1176 -i :50.0 -c:v libx264 screencast.mkv

Sample output:

user@machine:~/$ ffmpeg -f x11grab -r 25 -s 1854x1176 -i :50.0+0,0 -c:v libx264 -vb 4000k -an screencast.mkv
ffmpeg version N-86766-g264f6c6 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.4) 20160609
  configuration: --prefix=/home/user/ffmpeg_build --pkg-config-flags=--static --extra-cflags=-I/home/user/ffmpeg_build/include --extra-ldflags=-L/home/user/ffmpeg_build/lib --bindir=/home/user/bin --enable-gpl --enable-libass --enable-libfdk-aac --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-nonfree
  libavutil      55. 67.100 / 55. 67.100
  libavcodec     57.100.104 / 57.100.104
  libavformat    57. 75.100 / 57. 75.100
  libavdevice    57.  7.100 / 57.  7.100
  libavfilter     6. 95.100 /  6. 95.100
  libswscale      4.  7.101 /  4.  7.101
  libswresample   2.  8.100 /  2.  8.100
  libpostproc    54.  6.100 / 54.  6.100
[x11grab @ 0x1fd9b40] XFixes not available, cannot draw the mouse.
[x11grab @ 0x1fd9b40] Stream #0: not enough frames to estimate rate; consider increasing probesize
Input #0, x11grab, from ':50.0+0,0':
  Duration: N/A, start: 1500041497.684675, bitrate: N/A
    Stream #0:0: Video: rawvideo (BGR[0] / 0x524742), bgr0, 1854x1176, 25 fps, 1000k tbr, 1000k tbn, 1000k tbc
File 'screencast.mkv' already exists. Overwrite ? [y/N] y
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> h264 (libx264))
Press [q] to stop, [?] for help
[libx264 @ 0x1fe3040] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0x1fe3040] profile High 4:4:4 Predictive, level 4.2, 4:4:4 8-bit
[libx264 @ 0x1fe3040] 264 - core 148 r2643 5c65704 - H.264/MPEG-4 AVC codec - Copyleft 2003-2015 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=4 threads=12 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=abr mbtree=1 bitrate=4000 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, matroska, to 'screencast.mkv':
  Metadata:
    encoder         : Lavf57.75.100
    Stream #0:0: Video: h264 (libx264) (H264 / 0x34363248), yuv444p, 1854x1176, q=-1--1, 4000 kb/s, 25 fps, 1k tbn, 25 tbc
    Metadata:
      encoder         : Lavc57.100.104 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/4000000 buffer size: 0 vbv_delay: -1
[swscaler @ 0x1fe94e0] Warning: data is not aligned! This can lead to a speedloss
frame=  179 fps= 36 q=-1.0 Lsize=      16kB time=00:00:07.04 bitrate=  18.8kbits/s speed=1.43x
video:14kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 12.869934%
[libx264 @ 0x1fe3040] frame I:1     Avg QP: 6.00  size:   518
[libx264 @ 0x1fe3040] frame P:45    Avg QP: 0.44  size:    81
[libx264 @ 0x1fe3040] frame B:133   Avg QP: 0.94  size:    73
[libx264 @ 0x1fe3040] consecutive B-frames:  0.6%  1.1%  0.0% 98.3%
[libx264 @ 0x1fe3040] mb I  I16..4:  0.0% 100.0%  0.0%
[libx264 @ 0x1fe3040] mb P  I16..4:  0.0%  0.0%  0.0%  P16..4:  0.0%  0.0%  0.0%  0.0%  0.0%    skip:100.0%
[libx264 @ 0x1fe3040] mb B  I16..4:  0.0%  0.0%  0.0%  B16..8:  0.0%  0.0%  0.0%  direct: 0.0%  skip:100.0%
[libx264 @ 0x1fe3040] final ratefactor: -23.85
[libx264 @ 0x1fe3040] 8x8 transform intra:100.0%
[libx264 @ 0x1fe3040] coded y,u,v intra: 0.0% 0.0% 0.0% inter: 0.0% 0.0% 0.0%
[libx264 @ 0x1fe3040] i16 v,h,dc,p:  0%  0% 100%  0%
[libx264 @ 0x1fe3040] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu:  0%  0% 100%  0%  0%  0%  0%  0%  0%
[libx264 @ 0x1fe3040] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0x1fe3040] kb/s:15.56

Using: Ubuntu 16.04.2 LTS

I have successfully accomplished to capture the display :50 with "simplescreenrecorder", but that tool has no command line interface. It uses ffmpeg also, so it somehow should be possible to caputure the display but I can´t get it to work properly.

Body:
I think I've managed to find the cause. I need to setup a similar system and using a software other than x2go is not an option. Anyway to those searching for a possible solution pay attention to the following message:

[x11grab @ 0x1fd9b40] XFixes not available, cannot draw the mouse.

The xfixes extension is required by FFmpeg to record the screen through the xcblib and aparently, xfixes is disabled by default on recent x2goserver versions due to a bug. You can enable it editing the x2goagent.options file (normally  /etc/x2go/x2goagent.options) and removing the following parameter:

# Disable XFIXES.
# Workaround for https://bugs.launchpad.net/ubuntu/+source/libxfixes/+bug/985202
#
X2GO_NXAGENT_DEFAULT_OPTIONS+=" -extension XFIXES"

You can leave it as

    X2GO_NXAGENT_DEFAULT_OPTIONS+=""

As for the bug itself I have no idea if it will bite me. If its not a KDE machine then I think it should be ok.


问:
not able to create a dictionary from a one-element list
I am new in python programming and webscraping, I am able to get the relevant information from the website but it generates only one element with all the information needed in the list. The problem is that I cannot delete the unwanted things in this one element list. I am not sure if it is at all possible to do this from a single element list.Is there any way to create a python dictionary as in the example below:

```<code>{Kabul: River Kabul, Tirana: River Tirane, etc}
</code>```

Any help will be really appreciated. Thanks in advance.

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class":"sites-layout-tile sites-tile-name-content-1"}
rivers = soup.find_all(["table", "tr", "td","div","div","div"], attrs=attr)

data = [div.text for div in rivers]

print(data[0])
</code>```

答:
If you can figure out a better way to pull your data from the webpage you might want to, but assuming you don't, this will get you a usable and modifiable dictionary:

```<code>web_ele = ['COUNTRY - CAPITAL CITY - RIVER A Afghanistan - Kabul - River Kabul. Albania - Tirana - River Tirane. Andorra - Andorra La Vella - The Gran Valira. Argentina - Buenos Aries - River Plate. ']

web_ele[0] = web_ele[0].replace('COUNTRY - CAPITAL CITY - RIVER A ', '')
rows = web_ele[0].split('.')

data_dict = {}
for row in rows:
  data = row.split(' - ')
  if len(data) == 3:
    data_dict[data[0].strip()] = {
      'Capital':data[1].strip(),
      'River':data[2].strip(),
    }

print(data_dict)
# output: {'Afghanistan': {'Capital': 'Kabul', 'River': 'River Kabul'}, 'Albania': {'Capital': 'Tirana', 'River': 'River Tirane'}, 'Andorra': {'Capital': 'Andorra La Vella', 'River': 'The Gran Valira'}, 'Argentina': {'Capital': 'Buenos Aries', 'River': 'River Plate'}}
</code>```

You'll probably have to account for the various 'A', 'B', 'C' ... elements that seem to be part of your string but the header shouldn't pop back up any more than the one time it did but if it does you should be able to parse it out.

Again, I would probably suggest finding a cleaner way to pull your data but this will get you something to work with.

Body:
I am new in python programming and webscraping, I am able to get the relevant information from the website but it generates only one element with all the information needed in the list. The problem is that I cannot delete the unwanted things in this one element list. I am not sure if it is at all possible to do this from a single element list.Is there any way to create a python dictionary as in the example below:

{Kabul: River Kabul, Tirana: River Tirane, etc}

Any help will be really appreciated. Thanks in advance.

from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class":"sites-layout-tile sites-tile-name-content-1"}
rivers = soup.find_all(["table", "tr", "td","div","div","div"], attrs=attr)

data = [div.text for div in rivers]

print(data[0])

Body:
If you can figure out a better way to pull your data from the webpage you might want to, but assuming you don't, this will get you a usable and modifiable dictionary:

web_ele = ['COUNTRY - CAPITAL CITY - RIVER A Afghanistan - Kabul - River Kabul. Albania - Tirana - River Tirane. Andorra - Andorra La Vella - The Gran Valira. Argentina - Buenos Aries - River Plate. ']

web_ele[0] = web_ele[0].replace('COUNTRY - CAPITAL CITY - RIVER A ', '')
rows = web_ele[0].split('.')

data_dict = {}
for row in rows:
  data = row.split(' - ')
  if len(data) == 3:
    data_dict[data[0].strip()] = {
      'Capital':data[1].strip(),
      'River':data[2].strip(),
    }

print(data_dict)
# output: {'Afghanistan': {'Capital': 'Kabul', 'River': 'River Kabul'}, 'Albania': {'Capital': 'Tirana', 'River': 'River Tirane'}, 'Andorra': {'Capital': 'Andorra La Vella', 'River': 'The Gran Valira'}, 'Argentina': {'Capital': 'Buenos Aries', 'River': 'River Plate'}}

You'll probably have to account for the various 'A', 'B', 'C' ... elements that seem to be part of your string but the header shouldn't pop back up any more than the one time it did but if it does you should be able to parse it out.

Again, I would probably suggest finding a cleaner way to pull your data but this will get you something to work with.


问:
Get only values from array (without key)
I've have the function:

```<code>function getCotas() {
  var values = [];
  values['first'] = 10;
  $('.loop.scota').each(function(key, value) {
    var id = key + 1;
    values[$('.sdate.id' + id).text()] = parseInt($(this).text());
  });

  return values;
}
</code>```

The output is the array with the keys:

[first: 160, 01/12/2017: 157, 04/12/2017: 153]

What I need is just the values of the array, without the keys:

[160,157,153]

I already tried to do a loop with the values, like this answer, but always return an empty [] or an error with the functions.

Someone knows how to resolve this problem?

答:
You could remove the loop if the keys are not important:</p>

```<code>function getCotas() {
  var values = [];
  values[0] = 10; // first value
  var elArr = $('.loop.scota').toArray();
  values = values.concat(elArr.map(function (el) { return parseInt( $(el).text()); }));

  return values;
}

console.info(getCotas());
</code>```

Body:
I've have the function:

function getCotas() {
  var values = [];
  values['first'] = 10;
  $('.loop.scota').each(function(key, value) {
    var id = key + 1;
    values[$('.sdate.id' + id).text()] = parseInt($(this).text());
  });

  return values;
}

The output is the array with the keys:

[first: 160, 01/12/2017: 157, 04/12/2017: 153]

What I need is just the values of the array, without the keys:

[160,157,153]

I already tried to do a loop with the values, like this answer, but always return an empty [] or an error with the functions.

Someone knows how to resolve this problem?

Body:
You could remove the loop if the keys are not important:

function getCotas() {
  var values = [];
  values[0] = 10; // first value
  var elArr = $('.loop.scota').toArray();
  values = values.concat(elArr.map(function (el) { return parseInt( $(el).text()); }));

  return values;
}

console.info(getCotas());


问:
Calculating nth root in Java using power method
I was trying to get a cubic root in java using Math.pow(n, 1.0/3) but because it divides doubles, it doesn't return the exact answer. For example, with 125, this gives 4.9999999999. Is there a work-around for this? I know there is a cubic root function but I'd like to fix this so I can calculate higher roots.

I would not like to round because I want to know whether a number has an integer root by doing something like this: Math.pow(n, 1.0 / 3) % ((int) Math.pow(n, 1.0 / 3)).

答:
It's a pretty ugly hack, but you could reach a few of them through indenting.

```<code>System.out.println(Math.sqrt(Math.sqrt(256)));
    System.out.println(Math.pow(4, 4));
    System.out.println(Math.pow(4, 9));
    System.out.println(Math.cbrt(Math.cbrt(262144)));
Result:
4.0
256.0
262144.0
4.0
</code>```

Which will give you every n^3th cube and every n^2th root.

Body:
It's a pretty ugly hack, but you could reach a few of them through indenting.

System.out.println(Math.sqrt(Math.sqrt(256)));
    System.out.println(Math.pow(4, 4));
    System.out.println(Math.pow(4, 9));
    System.out.println(Math.cbrt(Math.cbrt(262144)));
Result:
4.0
256.0
262144.0
4.0

Which will give you every n^3th cube and every n^2th root.


问:
DataFrame by especific columns in Python pandas to a JSON response?
I can't figure out how to generate this output:

```<code>       "name"    "hp"    "hpperlevel"
"1"    Annie     524     88
"2"    Olaf      597.24  93
</code>```

With this:

```<code>{
    "type": "champion",
    "version": "7.24.1",
    "data": {
        "1": {
            "title": "the Dark Child",
            "stats": {
                "armorperlevel": 4,
                "attackdamage": 50.41,
                "mpperlevel": 50,
                "attackspeedoffset": 0.08,
                "mp": 334,
                "armor": 19.22,
                "hp": 524,
                "hpregenperlevel": 0.55,
                "attackspeedperlevel": 1.36,
                "attackrange": 575,
                "movespeed": 335,
                "attackdamageperlevel": 2.625,
                "mpregenperlevel": 0.8,
                "critperlevel": 0,
                "spellblockperlevel": 0.5,
                "crit": 0,
                "mpregen": 6,
                "spellblock": 30,
                "hpregen": 5.424,
                "hpperlevel": 88
            },
            "id": 1,
            "key": "Annie",
            "name": "Annie"
        },
        "2": {
            "title": "the Berserker",
            "stats": {
                "armorperlevel": 3,
                "attackdamage": 68,
                "mpperlevel": 42,
                "attackspeedoffset": -0.1,
                "mp": 315.6,
                "armor": 35,
                "hp": 597.24,
                "hpregenperlevel": 0.9,
                "attackspeedperlevel": 2.7,
                "attackrange": 125,
                "movespeed": 350,
                "attackdamageperlevel": 3.5,
                "mpregenperlevel": 0.575,
                "critperlevel": 0,
                "spellblockperlevel": 1.25,
                "crit": 0,
                "mpregen": 7.466,
                "spellblock": 32.1,
                "hpregen": 8.512,
                "hpperlevel": 93
            },
            "id": 2,
            "key": "Olaf",
            "name": "Olaf"
        },
</code>```

The goal is DataFrame the first table with the JSON response (the second code) in Python pandas, or if I need to do something with the JSON response first i will be happy to know a hint.

The only method I know is pandas.DataFrame(Data["data"]) but the output is not the desired, yet i don't want to make a pandas.DataFrame(Data["data"]["1"]["stats"], index = [0], columns = ["hp", "hpperlevel"]) more than 100 times (the total numbers from the API) multiplied by the groups I want to make and merge them all.

The final output of my program is save the data as a excel file but the only big problem is make the groups first.

Any response will be greatly appreciated!

答:
You can create a single dataframe with a couple of list comprehensions passed to the dataframe constructor:

```<code>import pandas

def get_stats(data):
    return (data['id'], data['name'], data['stats']['hp'], data['stats']['hpperlevel'])

response = {
    "data": {
        "1": {
            "stats": {"hp": 524, "hpperlevel": 88},
            "id": 1,
            "name": "Annie"
        },
        "2": {
            "stats": {"hp": 597.24, "hpperlevel": 93},
            "id": 2,
            "name": "Olaf"
        }
    }
}

df = pandas.DataFrame(
    data=[get_stats(response['data'][key]) for key in response['data']],
    index=[int(key) for key in response['data']],
    columns=['id', 'name', 'hp', 'hpperlevel']
).set_index('id')
</code>```

And that gives me:

```<code>     name      hp  hpperlevel
id
1   Annie  524.00          88
2    Olaf  597.24          93
</code>```

Body:
I can't figure out how to generate this output:

       "name"    "hp"    "hpperlevel"
"1"    Annie     524     88
"2"    Olaf      597.24  93

With this:

{
    "type": "champion",
    "version": "7.24.1",
    "data": {
        "1": {
            "title": "the Dark Child",
            "stats": {
                "armorperlevel": 4,
                "attackdamage": 50.41,
                "mpperlevel": 50,
                "attackspeedoffset": 0.08,
                "mp": 334,
                "armor": 19.22,
                "hp": 524,
                "hpregenperlevel": 0.55,
                "attackspeedperlevel": 1.36,
                "attackrange": 575,
                "movespeed": 335,
                "attackdamageperlevel": 2.625,
                "mpregenperlevel": 0.8,
                "critperlevel": 0,
                "spellblockperlevel": 0.5,
                "crit": 0,
                "mpregen": 6,
                "spellblock": 30,
                "hpregen": 5.424,
                "hpperlevel": 88
            },
            "id": 1,
            "key": "Annie",
            "name": "Annie"
        },
        "2": {
            "title": "the Berserker",
            "stats": {
                "armorperlevel": 3,
                "attackdamage": 68,
                "mpperlevel": 42,
                "attackspeedoffset": -0.1,
                "mp": 315.6,
                "armor": 35,
                "hp": 597.24,
                "hpregenperlevel": 0.9,
                "attackspeedperlevel": 2.7,
                "attackrange": 125,
                "movespeed": 350,
                "attackdamageperlevel": 3.5,
                "mpregenperlevel": 0.575,
                "critperlevel": 0,
                "spellblockperlevel": 1.25,
                "crit": 0,
                "mpregen": 7.466,
                "spellblock": 32.1,
                "hpregen": 8.512,
                "hpperlevel": 93
            },
            "id": 2,
            "key": "Olaf",
            "name": "Olaf"
        },

The goal is DataFrame the first table with the JSON response (the second code) in Python pandas, or if I need to do something with the JSON response first i will be happy to know a hint.

The only method I know is pandas.DataFrame(Data["data"]) but the output is not the desired, yet i don't want to make a pandas.DataFrame(Data["data"]["1"]["stats"], index = [0], columns = ["hp", "hpperlevel"]) more than 100 times (the total numbers from the API) multiplied by the groups I want to make and merge them all.

The final output of my program is save the data as a excel file but the only big problem is make the groups first.

Any response will be greatly appreciated!

Body:
You can create a single dataframe with a couple of list comprehensions passed to the dataframe constructor:

import pandas

def get_stats(data):
    return (data['id'], data['name'], data['stats']['hp'], data['stats']['hpperlevel'])

response = {
    "data": {
        "1": {
            "stats": {"hp": 524, "hpperlevel": 88},
            "id": 1,
            "name": "Annie"
        },
        "2": {
            "stats": {"hp": 597.24, "hpperlevel": 93},
            "id": 2,
            "name": "Olaf"
        }
    }
}

df = pandas.DataFrame(
    data=[get_stats(response['data'][key]) for key in response['data']],
    index=[int(key) for key in response['data']],
    columns=['id', 'name', 'hp', 'hpperlevel']
).set_index('id')

And that gives me:

     name      hp  hpperlevel
id
1   Annie  524.00          88
2    Olaf  597.24          93


问:
Session not working for first time, from second time it works
I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.

First Page

```<code><?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];

$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from  user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);

if($data1>0)
{
   $_SESSION['user_id']=$val['user_id'];
   echo "<script>window.location.href='index.php'</script>";

}
else
{
    echo "<script>window.location.href='login.php'</script>";

}
?>
</code>```

Second Page

```<code><?php
  session_start();
  $val=$_SESSION['user_id'];
  echo $val;
?>
</code>```

答:
session_start(); should be at the very top of both scripts!

Session variables are saved on server and assigned a unique code that are passed to browser in cookies.

Because the cookies are set by the headers they need to be sent before anything else!

Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.

So always start the both scripts like this:

```<code><?php
session_start();

// Rest of the code....
</code>```

It looks like they are on top on your question but I think you edited question later to put there.

That's the only reason sessions are not working the first time and they are working on second time.

Body:
I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.

First Page

<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];

$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from  user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);

if($data1>0)
{
   $_SESSION['user_id']=$val['user_id'];
   echo "";

}
else
{
    echo "";

}
?>

Second Page

<?php
  session_start();
  $val=$_SESSION['user_id'];
  echo $val;
?>

Body:
session_start(); should be at the very top of both scripts!

Session variables are saved on server and assigned a unique code that are passed to browser in cookies.

Because the cookies are set by the headers they need to be sent before anything else!

Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.

So always start the both scripts like this:

<?php
session_start();

// Rest of the code....

It looks like they are on top on your question but I think you edited question later to put there.

That's the only reason sessions are not working the first time and they are working on second time.


问:
Data entered offline does not synchronize when going back online
Some users report that they create offline content and when they go online they lose their data. They just disappear.

I do not know where to start, in my tests this does not occur.

Is there an authentication problem? I use today the form E-mail and password.

I'm using minSdkVersion 16 and compile 'com.google.firebase: firebase-auth: 10.2.1'

I mentioned Auth, why it is not clear how the firebase behaves when the user loses authentication. Let's assume that it loses authentication and inserts new data (after losing authentication), what does firebase do?

1 - Block the insertion - if this is the behavior, my problem will not be the tightening, because the data is inserted and I can see it in the APP.

2 - Does not block the insertion, but when it is online this data will be lost (it is my suspicion)

3 - Does not block the insertion, puts the insert in the queue and updates the base (this is what I hope, because if the user for an unexpected reason lose the offline authentication I will not have to authenticate again until it goes online).

答:
It's normal for apps to go offline, go to the background, and eventually killed by Android to save resources.  If you want to persist any data written while the app is offline and is later killed, you should enable persistence, which is off by default:

```<code>FirebaseDatabase.getInstance().setPersistenceEnabled(true);
</code>```

The written data will be synchronized when the app is launched again and comes online.

Transactions are not supported when offline.

Body:
It's normal for apps to go offline, go to the background, and eventually killed by Android to save resources.  If you want to persist any data written while the app is offline and is later killed, you should enable persistence, which is off by default:

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

The written data will be synchronized when the app is launched again and comes online.

Transactions are not supported when offline.


问:
Finding gradient of an unknown function at a given point in Python
I am asked to write an implementation of the gradient descent in python with the signature gradient(f, P0, gamma, epsilon) where f is an unknown and possibly multivariate function, P0 is the starting point for the gradient descent, gamma is the constant step and epsilon the stopping criteria.

What I find tricky is how to evaluate the gradient of f at the point P0 without knowing anything on f. I know there is numpy.gradient but I don't know how to use it in the case where I don't know the dimensions of f. Also, numpy.gradient works with samples of the function, so how to choose the right samples to compute the gradient at a point without any information on the function and the point?

答:
I'm assuming here, So how can i choose a generic set of samples each time I need to compute the gradient at a given point? means, that the dimension of the function is fixed and can be deduced from your start point.

Consider this a demo, using scipy's approx_fprime, which is an easier to use wrapper-method for numerical-differentiation and also used in scipy's optimizers when a jacobian is needed, but not given.

Of course you can't ignore the parameter epsilon, which can make a difference depending on the data.

(This code is also ignoring optimize's args-parameter which is usually a good idea; i'm using the fact that A and b are inside the scope here; surely not best-practice)

```<code>import numpy as np
from scipy.optimize import approx_fprime, minimize
np.random.seed(1)

# Synthetic data
A = np.random.random(size=(1000, 20))
noiseless_x = np.random.random(size=20)
b = A.dot(noiseless_x) + np.random.random(size=1000) * 0.01

# Loss function
def fun(x):
    return np.linalg.norm(A.dot(x) - b, 2)

# Optimize without any explicit jacobian
x0 = np.zeros(len(noiseless_x))
res = minimize(fun, x0)
print(res.message)
print(res.fun)

# Get numerical-gradient function
eps = np.sqrt(np.finfo(float).eps)
my_gradient = lambda x: approx_fprime(x, fun, eps)

# Optimize with our gradient
res = res = minimize(fun, x0, jac=my_gradient)
print(res.message)
print(res.fun)

# Eval gradient at some point
print(my_gradient(np.ones(len(noiseless_x))))
</code>```

Output:

```<code>Optimization terminated successfully.
0.09272331925776327
Optimization terminated successfully.
0.09272331925776327
[15.77418041 16.43476772 15.40369129 15.79804516 15.61699104 15.52977276
 15.60408688 16.29286766 16.13469887 16.29916573 15.57258797 15.75262356
 16.3483305  15.40844536 16.8921814  15.18487358 15.95994091 15.45903492
 16.2035532  16.68831635]
</code>```

Using:

```<code># Get numerical-gradient function with a way too big eps-value
eps = 1e-3
my_gradient = lambda x: approx_fprime(x, fun, eps)
</code>```

shows that eps is a critical parameter resulting in:

```<code>Desired error not necessarily achieved due to precision loss.
0.09323354898565098
</code>```

Body:
I'm assuming here, So how can i choose a generic set of samples each time I need to compute the gradient at a given point? means, that the dimension of the function is fixed and can be deduced from your start point.

Consider this a demo, using scipy's approx_fprime, which is an easier to use wrapper-method for numerical-differentiation and also used in scipy's optimizers when a jacobian is needed, but not given.

Of course you can't ignore the parameter epsilon, which can make a difference depending on the data.

(This code is also ignoring optimize's args-parameter which is usually a good idea; i'm using the fact that A and b are inside the scope here; surely not best-practice)

import numpy as np
from scipy.optimize import approx_fprime, minimize
np.random.seed(1)

# Synthetic data
A = np.random.random(size=(1000, 20))
noiseless_x = np.random.random(size=20)
b = A.dot(noiseless_x) + np.random.random(size=1000) * 0.01

# Loss function
def fun(x):
    return np.linalg.norm(A.dot(x) - b, 2)

# Optimize without any explicit jacobian
x0 = np.zeros(len(noiseless_x))
res = minimize(fun, x0)
print(res.message)
print(res.fun)

# Get numerical-gradient function
eps = np.sqrt(np.finfo(float).eps)
my_gradient = lambda x: approx_fprime(x, fun, eps)

# Optimize with our gradient
res = res = minimize(fun, x0, jac=my_gradient)
print(res.message)
print(res.fun)

# Eval gradient at some point
print(my_gradient(np.ones(len(noiseless_x))))

Output:

Optimization terminated successfully.
0.09272331925776327
Optimization terminated successfully.
0.09272331925776327
[15.77418041 16.43476772 15.40369129 15.79804516 15.61699104 15.52977276
 15.60408688 16.29286766 16.13469887 16.29916573 15.57258797 15.75262356
 16.3483305  15.40844536 16.8921814  15.18487358 15.95994091 15.45903492
 16.2035532  16.68831635]

Using:

# Get numerical-gradient function with a way too big eps-value
eps = 1e-3
my_gradient = lambda x: approx_fprime(x, fun, eps)

shows that eps is a critical parameter resulting in:

Desired error not necessarily achieved due to precision loss.
0.09323354898565098


问:
Remove an item from a list view
If I want to remove an item from my list view by tapping it, do I remove the object from the ArrayList I'm using with my ArrayAdapter, or do I remove the object directly from the adapter and call the notifyDatasetChange?

Also I want to store the data from the list on the disk, do I save the adapter or the arraylist I use?

Here is the code: The idea I'm going for is to save the data from the list and load it back when the activity launches again, however once this happens I cannot delete items from the list anymore.

```<code>public class EditKeywords extends ListActivity implements Serializable{

    private ArrayList<String> keyWordList;
    private EditText keywordEditText;
    private IconicAdapter adapter;
    private Button enterButton;
    private int position;
    private Button finishedButton;
    public static final String KEYWORDS = "keywords";
    public static final String ADAPTER = "adapter";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editkeyowords);
        getKeywordsAndAdapter();
        keywordEditText = (EditText) findViewById(R.id.keywordedittext);
        setListAdapter(adapter);

        enterButton = (Button) findViewById(R.id.enterkeywords);
        enterButton.setOnClickListener(enterButtonListener);

        finishedButton = (Button) findViewById(R.id.finishedbutton);
        finishedButton.setOnClickListener(finishedButtonListener);
    }

    public void onResume(){
    super.onResume();
    getKeywordsAndAdapter();
    }

    public void onPause(Bundle savedInstanceState){
    super.onPause();
    writeKeywordsAndAdapter();
    }

    public void getKeywordsAndAdapter(){
    try {
        InputStream fi = openFileInput(KEYWORDS);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                    keyWordList = (ArrayList<String>) in.readObject();
                    in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(keyWordList == null){
        keyWordList = new ArrayList<String>();
    }

    try {
        InputStream fi = openFileInput(ADAPTER);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                adapter = (IconicAdapter) in.readObject();
                in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(adapter == null){
        adapter = new IconicAdapter();
    }
    }

    public void writeKeywordsAndAdapter(){

    try {
        OutputStream fi = openFileOutput(KEYWORDS, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
                out.writeObject(keyWordList);
                out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    try {
        OutputStream fi = openFileOutput(ADAPTER, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
            out.writeObject(adapter);
            out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    }

    public void onListItemClick(ListView parent, View v,
        int aPosition, long id) {

        ImageView image = (ImageView) findViewById(R.id.icon1);
        image.setImageResource(R.drawable.delete);
        image.setOnClickListener(deleteImageListener);
        getListView().getChildAt(aPosition).invalidate();
        //adapter.notifyDataSetInvalidated();
        position = aPosition;
    }

    public void startHome() {
    Intent intent = new Intent(this, ECS.class);
    this.startActivity(intent);
    finish();
    }

    public class IconicAdapter extends ArrayAdapter<String> implements Serializable {
    private static final long serialVersionUID = 6175078429973952022L;

    IconicAdapter() {
        super(EditKeywords.this, R.layout.rowkeywords, keyWordList);
    }

    public View getView(int position, View convertView,ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();

        View row=inflater.inflate(R.layout.rowkeywords, parent, false);
        TextView label=(TextView)row.findViewById(R.id.label1);

        label.setText(keyWordList.get(position));
        return(row);
    }
    }

    private OnClickListener enterButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){

        if(keywordEditText.getText().toString() != ""){
        boolean unique = true;
        for(String s : keyWordList){
            if(s.equals(keywordEditText.getText().toString())){
            unique = false;
            }
        }
        if(unique == true){
            adapter.add(keywordEditText.getText().toString());
            keywordEditText.setText("");
            adapter.notifyDataSetChanged();
        }
        }
    }
    };

    private OnClickListener deleteImageListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
        //keyWordList.remove(position);
        adapter.remove(keyWordList.get(0));
        adapter.notifyDataSetChanged();
        writeKeywordsAndAdapter();

    }
    };

    private OnClickListener finishedButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
       writeKeywordsAndAdapter();
       startHome();
    }
    };

}
</code>```

答: you have to remove it from your arrayList and set then: adapter.notifyDataSetChanged();

Title: Remove an item from a list view

Body:
If I want to remove an item from my list view by tapping it, do I remove the object from the ArrayList I'm using with my ArrayAdapter, or do I remove the object directly from the adapter and call the notifyDatasetChange?

Also I want to store the data from the list on the disk, do I save the adapter or the arraylist I use?

Here is the code: The idea I'm going for is to save the data from the list and load it back when the activity launches again, however once this happens I cannot delete items from the list anymore.

public class EditKeywords extends ListActivity implements Serializable{

    private ArrayList<String> keyWordList;
    private EditText keywordEditText;
    private IconicAdapter adapter;
    private Button enterButton;
    private int position;
    private Button finishedButton;
    public static final String KEYWORDS = "keywords";
    public static final String ADAPTER = "adapter";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editkeyowords);
        getKeywordsAndAdapter();
        keywordEditText = (EditText) findViewById(R.id.keywordedittext);
        setListAdapter(adapter);

        enterButton = (Button) findViewById(R.id.enterkeywords);
        enterButton.setOnClickListener(enterButtonListener);

        finishedButton = (Button) findViewById(R.id.finishedbutton);
        finishedButton.setOnClickListener(finishedButtonListener);
    }

    public void onResume(){
    super.onResume();
    getKeywordsAndAdapter();
    }

    public void onPause(Bundle savedInstanceState){
    super.onPause();
    writeKeywordsAndAdapter();
    }

    public void getKeywordsAndAdapter(){
    try {
        InputStream fi = openFileInput(KEYWORDS);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                    keyWordList = (ArrayList<String>) in.readObject();
                    in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(keyWordList == null){
        keyWordList = new ArrayList<String>();
    }

    try {
        InputStream fi = openFileInput(ADAPTER);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                adapter = (IconicAdapter) in.readObject();
                in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(adapter == null){
        adapter = new IconicAdapter();
    }
    }

    public void writeKeywordsAndAdapter(){

    try {
        OutputStream fi = openFileOutput(KEYWORDS, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
                out.writeObject(keyWordList);
                out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    try {
        OutputStream fi = openFileOutput(ADAPTER, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
            out.writeObject(adapter);
            out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    }

    public void onListItemClick(ListView parent, View v,
        int aPosition, long id) {

        ImageView image = (ImageView) findViewById(R.id.icon1);
        image.setImageResource(R.drawable.delete);
        image.setOnClickListener(deleteImageListener);
        getListView().getChildAt(aPosition).invalidate();
        //adapter.notifyDataSetInvalidated();
        position = aPosition;
    }

    public void startHome() {
    Intent intent = new Intent(this, ECS.class);
    this.startActivity(intent);
    finish();
    }

    public class IconicAdapter extends ArrayAdapter<String> implements Serializable {
    private static final long serialVersionUID = 6175078429973952022L;

    IconicAdapter() {
        super(EditKeywords.this, R.layout.rowkeywords, keyWordList);
    }

    public View getView(int position, View convertView,ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();

        View row=inflater.inflate(R.layout.rowkeywords, parent, false);
        TextView label=(TextView)row.findViewById(R.id.label1);

        label.setText(keyWordList.get(position));
        return(row);
    }
    }

    private OnClickListener enterButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){

        if(keywordEditText.getText().toString() != ""){
        boolean unique = true;
        for(String s : keyWordList){
            if(s.equals(keywordEditText.getText().toString())){
            unique = false;
            }
        }
        if(unique == true){
            adapter.add(keywordEditText.getText().toString());
            keywordEditText.setText("");
            adapter.notifyDataSetChanged();
        }
        }
    }
    };

    private OnClickListener deleteImageListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
        //keyWordList.remove(position);
        adapter.remove(keyWordList.get(0));
        adapter.notifyDataSetChanged();
        writeKeywordsAndAdapter();

    }
    };

    private OnClickListener finishedButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
       writeKeywordsAndAdapter();
       startHome();
    }
    };

}