问:
Using WhooshAlchemy with joined table inheritance
I currently have something along the lines of this (taken from the SQLAlchemy documentation):

```<code>class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class Manager(Employee):
    __tablename__ = 'manager'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }
</code>```

Using WhooshAlchemy, I'd like to make the name column searchable, but also engineer_name and manager_name for the Engineer and Manager class respectively.

I've tried putting a separate __searchable__ list containing their columns into each class, but that gives me the following error:

```<code>whoosh.fields.UnknownFieldError: No field named 'name' in <Schema: ['id', 'engineer_name']>
</code>```

I've also tried putting a __searchable__ list into each one that only contains the columns defined on that specific class, but that gives me no results at all when I use whoosh_search on a query, despite having valid search terms that should return at least 1 result.

What's the easiest way to do this?

答:
You have to explicitly define a schema that can handle all of them.
You would override the searchable fields on the inherited classes.

```<code>class Employee(Base):
    __tablename__ = 'employee'
    __searchable__ = ['name']
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    __searchable__ = ['name', 'engineer_name']
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class Manager(Employee):
    __tablename__ = 'manager'
    __searchable__ = ['name', 'manager_name ']
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }
</code>```

Then when you build your index:

```<code>from whooshalchemy import IndexService
from whoosh.fields import Schema, TEXT

# However your app initializes it
index_service = IndexService(config=app.config, session=db.session)

my_schema = Schema(name=TEXT, engineer_name=TEXT, manager_name=TEXT)
index = index_service.index_for_model_class(model)

with index.writer() as writer:

    for engineer in Engineer.query.all():
        index_attrs = {}
        for field in Engineer.__searchable__:
            index_attrs[field] = str(getattr(engineer, field))

        index_attrs["id"] = engineer.id

        writer.add_document(**index_attrs)

    for manager in Manager.query.all():
        index_attrs = {}
        for field in Manager.__searchable__:
            index_attrs[field] = str(getattr(manager, field))

        index_attrs["id"] = manager.id

        writer.add_document(**index_attrs)
</code>```

And later when searching:

```<code>engineer_search_results = Engineer.search_query("SomeText").all()
manager_search_results = Manager.search_query("SomeText").all()
</code>```

Body:
I currently have something along the lines of this (taken from the SQLAlchemy documentation):

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class Manager(Employee):
    __tablename__ = 'manager'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }

Using WhooshAlchemy, I'd like to make the name column searchable, but also engineer_name and manager_name for the Engineer and Manager class respectively.

I've tried putting a separate __searchable__ list containing their columns into each class, but that gives me the following error:

whoosh.fields.UnknownFieldError: No field named 'name' in <Schema: ['id', 'engineer_name']>

I've also tried putting a __searchable__ list into each one that only contains the columns defined on that specific class, but that gives me no results at all when I use whoosh_search on a query, despite having valid search terms that should return at least 1 result.

What's the easiest way to do this?

Body:
You have to explicitly define a schema that can handle all of them.
You would override the searchable fields on the inherited classes.

class Employee(Base):
    __tablename__ = 'employee'
    __searchable__ = ['name']
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    __searchable__ = ['name', 'engineer_name']
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class Manager(Employee):
    __tablename__ = 'manager'
    __searchable__ = ['name', 'manager_name ']
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }

Then when you build your index:

from whooshalchemy import IndexService
from whoosh.fields import Schema, TEXT

# However your app initializes it
index_service = IndexService(config=app.config, session=db.session)

my_schema = Schema(name=TEXT, engineer_name=TEXT, manager_name=TEXT)
index = index_service.index_for_model_class(model)

with index.writer() as writer:

    for engineer in Engineer.query.all():
        index_attrs = {}
        for field in Engineer.__searchable__:
            index_attrs[field] = str(getattr(engineer, field))

        index_attrs["id"] = engineer.id

        writer.add_document(**index_attrs)

    for manager in Manager.query.all():
        index_attrs = {}
        for field in Manager.__searchable__:
            index_attrs[field] = str(getattr(manager, field))

        index_attrs["id"] = manager.id

        writer.add_document(**index_attrs)

And later when searching:

engineer_search_results = Engineer.search_query("SomeText").all()
manager_search_results = Manager.search_query("SomeText").all()


来源: stackexchange

问:
Inheriting class methods Javascript
Lets say I have two APIs and I would like to inherit classes from the first, but modify the response with .prototype.toJSON().

When I inherit from the first class, how can I inherit class methods as well.

An example

```<code>//file v1/models/users.js
var UserModel = function() {
  this.id = 0;
  this.firstName = '';
  this.lastName = '';
}

UserModel.find = function(q, callback) {
  //find any user that matches q and map them to UserModel
  if (err) return callback(err, null);
  callback(null, users);
}

module.exports = UserModel;
</code>```

And the the next version

```<code>//file v2/models/users.js
var UserModel = require('../v1/models/users');

function UserModelV2() {
  UserModel.call(this);
}

UserModelV2 = Object.create(UserModel.prototype);
UserModelV2.prototype.constructor = UserModel;

UserModelV2.prototype.toJSON = function() {
    var obj = {};
    obj.firstName = 'foo';
    return obj;
}
module.exports = UserModelV2;
</code>```

When I now try to call

```<code>var User = require('./v2/models/users');
User.find(1);
</code>```

I get an error saying User.find does not exists.

I am aware I am only inheriting prototypal properties, but I cannot find an example of inheriting class methods anywhere.

答:
Well, you can simply copy the methods over from UserModel

```<code>Object.assign(UserModelV2, UserModel);
</code>```

Or you define that the UserModelV2 function inherits its properties from the UserModel function instead of Function.prototype directly.

```<code>Object.setPrototypeOf(UserModelV2, UserModel);
</code>```

Or you use the new class syntax and let that take care of this:

```<code>class UserModelV2 extends UserModel {
  toJSON(){
    return {firstName: 'foo'};
  }
}
</code>```

maybe in combination with a transpiler like babel, if you need backwards compatibility.

I'd encourage the last option. To me this seems like the cleanest approach and provides you with the ability to not use the transpiler.

And it is semantically clear. Even the JS compiler can tell that you're not just arbitrarily messing around with the prototype of some function and may break something or do something "weird".

ContentLicense: CC BY-SA 3.0

Title: Inheriting class methods Javascript

Body:
Lets say I have two APIs and I would like to inherit classes from the first, but modify the response with .prototype.toJSON().

When I inherit from the first class, how can I inherit class methods as well.

An example

//file v1/models/users.js
var UserModel = function() {
  this.id = 0;
  this.firstName = '';
  this.lastName = '';
}

UserModel.find = function(q, callback) {
  //find any user that matches q and map them to UserModel
  if (err) return callback(err, null);
  callback(null, users);
}

module.exports = UserModel;

And the the next version

//file v2/models/users.js
var UserModel = require('../v1/models/users');

function UserModelV2() {
  UserModel.call(this);
}

UserModelV2 = Object.create(UserModel.prototype);
UserModelV2.prototype.constructor = UserModel;

UserModelV2.prototype.toJSON = function() {
    var obj = {};
    obj.firstName = 'foo';
    return obj;
}
module.exports = UserModelV2;

When I now try to call

var User = require('./v2/models/users');
User.find(1);

I get an error saying User.find does not exists.

I am aware I am only inheriting prototypal properties, but I cannot find an example of inheriting class methods anywhere.

Body:
Well, you can simply copy the methods over from UserModel

Object.assign(UserModelV2, UserModel);

Or you define that the UserModelV2 function inherits its properties from the UserModel function instead of Function.prototype directly.

Object.setPrototypeOf(UserModelV2, UserModel);

Or you use the new class syntax and let that take care of this:

class UserModelV2 extends UserModel {
  toJSON(){
    return {firstName: 'foo'};
  }
}

maybe in combination with a transpiler like babel, if you need backwards compatibility.

I'd encourage the last option. To me this seems like the cleanest approach and provides you with the ability to not use the transpiler.

And it is semantically clear. Even the JS compiler can tell that you're not just arbitrarily messing around with the prototype of some function and may break something or do something "weird".


问:
My random quote generator button isn't displaying quotes. (not working on CodePen or Sublime, only Stack Overflow)
I've been having a little trouble over this since I started last night. After making this part of the generator, I opened it in the browser to see if it works. Even though the HTML part is all set, the button doesn't display the quotes when I click it.

I am following the 'Make a Quote Generator for Absolute Beginners' tutorial on Medium by Sophanarith Sok. I have looked through to check for any mistakes and compared to the tutorial's code, but the button isn't showing any quotes.

I used Sublime Text 3 and Code Pen to check. However, when I posted the snippets in the Stack Overflow coding feature to check if it ran, it was working perfectly. Any suggestions?

This is the JavaScript section.

```<code>var quotes = [
'To be or not to be, that is the question. -Hamlet',
'Maybe ever\’body in the whole damn world is scared of each other. -Of Mice and Men.',
'Life is to be lived, not controlled; and humanity is won by continuing to play in face of certain defeat. -Invisible Man.',
 'Terror made me cruel -Wuthering Heights.',
 'Some men get the world, some men get ex-hookers and a trip to Arizona. You\'re in with the former, but my God I don\'t envy the blood on your conscience. -LA Confidential.',
 'The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars. -On The Road.',
 'It was a bright cold day in April, and the clocks were striking thirteen. -1984.',
 'We were the people who were not in the papers. We lived in the blank white spaces at the edges of the print. It gave us more freedom. We lived in the gaps between the stories. -A Handmaiden\'s Tale.',
 'It sounds plausible enough tonight, but wait until tomorrow. Wait for the common sense of the morning. -The Time Machine.',
 'It\'s much better to do good in a way that no one knows anything about it. -Anna Karenina.',
 'Life appears to me too short to be spent in nursing animosity or registering wrongs. -Charlotte Bronte.',
  'You forget what you want to remember, and you remember what you want to forget. -The Road.',
  'There is an idea of a Patrick Bateman, some kind of abstraction, but there is no real me, only an entity, something illusory, and though I can hide my cold gaze and you can shake my hand and feel flesh gripping yours and maybe you can even sense our lifestyles are probably comparable: I simply am not there. -American Psycho.',
  'Finally, from so little sleeping and so much reading, his brain dried up and he went completely out of his mind. -Don Quixote.',
   'We cast a shadow on something wherever we stand, and it is no good moving from place to place to save things; because the shadow always follows. Choose a place where you won\'t do harm - yes, choose a place where you won\'t do very much harm and stand in it for all you are worth, facing the sunshine. -A Room with a View.',
    'Memories warm you up from the inside. But they also tear you apart. -Kafka on the Shore.',
    'You are your best thing -Beloved.',
'Some birds are not meant to be caged, that\'s all. Their feathers are too bright, their songs too sweet and wild. So you let them go, or when you open the cage to feed them they somehow fly out past you. And the part of you that knows it was wrong to imprison them in the first place rejoices, but still, the place where you live is that much drabber and empty for their departure. -Shawshank Redemption.'

]

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
</code>```

This is the HTML section.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quote Gen</title>
</head>

<body>
    <h1>Simple Quote Generator</h1>
    <div id="quoteDisplay">
    </div>
    <button onclick = "newQuote()">New Quote</button>
    <script src="javascript.js"></script>
</body>

</html>
</code>```

答: I posted the code on Notepad with the script tag (has code) inside the html file. It worked on the browser. I'll still figure out what's up with Sublime Text 3 but Notepad and the rest work.</p>

Body:
I've been having a little trouble over this since I started last night. After making this part of the generator, I opened it in the browser to see if it works. Even though the HTML part is all set, the button doesn't display the quotes when I click it.

I am following the 'Make a Quote Generator for Absolute Beginners' tutorial on Medium by Sophanarith Sok. I have looked through to check for any mistakes and compared to the tutorial's code, but the button isn't showing any quotes.

I used Sublime Text 3 and Code Pen to check. However, when I posted the snippets in the Stack Overflow coding feature to check if it ran, it was working perfectly. Any suggestions?

This is the JavaScript section.

var quotes = [
'To be or not to be, that is the question. -Hamlet',
'Maybe ever\’body in the whole damn world is scared of each other. -Of Mice and Men.',
'Life is to be lived, not controlled; and humanity is won by continuing to play in face of certain defeat. -Invisible Man.',
 'Terror made me cruel -Wuthering Heights.',
 'Some men get the world, some men get ex-hookers and a trip to Arizona. You\'re in with the former, but my God I don\'t envy the blood on your conscience. -LA Confidential.',
 'The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars. -On The Road.',
 'It was a bright cold day in April, and the clocks were striking thirteen. -1984.',
 'We were the people who were not in the papers. We lived in the blank white spaces at the edges of the print. It gave us more freedom. We lived in the gaps between the stories. -A Handmaiden\'s Tale.',
 'It sounds plausible enough tonight, but wait until tomorrow. Wait for the common sense of the morning. -The Time Machine.',
 'It\'s much better to do good in a way that no one knows anything about it. -Anna Karenina.',
 'Life appears to me too short to be spent in nursing animosity or registering wrongs. -Charlotte Bronte.',
  'You forget what you want to remember, and you remember what you want to forget. -The Road.',
  'There is an idea of a Patrick Bateman, some kind of abstraction, but there is no real me, only an entity, something illusory, and though I can hide my cold gaze and you can shake my hand and feel flesh gripping yours and maybe you can even sense our lifestyles are probably comparable: I simply am not there. -American Psycho.',
  'Finally, from so little sleeping and so much reading, his brain dried up and he went completely out of his mind. -Don Quixote.',
   'We cast a shadow on something wherever we stand, and it is no good moving from place to place to save things; because the shadow always follows. Choose a place where you won\'t do harm - yes, choose a place where you won\'t do very much harm and stand in it for all you are worth, facing the sunshine. -A Room with a View.',
    'Memories warm you up from the inside. But they also tear you apart. -Kafka on the Shore.',
    'You are your best thing -Beloved.',
'Some birds are not meant to be caged, that\'s all. Their feathers are too bright, their songs too sweet and wild. So you let them go, or when you open the cage to feed them they somehow fly out past you. And the part of you that knows it was wrong to imprison them in the first place rejoices, but still, the place where you live is that much drabber and empty for their departure. -Shawshank Redemption.'

]

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}

This is the HTML section.

<!DOCTYPE html>

    <title>Quote Gen</title>

Simple Quote Generator

    <button onclick = "newQuote()">New Quote</button>


问:
Query using subset of path in Postgres
Given this table:

```<code> id |            points (path)                 |
----+------------------------------------------+
  1 | ((1,2),(3,4),(5,6),(7,8))                |
</code>```

Is it possible to achieve the following using a single geometric operator and a path argument (sequential subset of the containing path), like ((3,4),(5,6))?

select * from things where points @> '(3,4)' and points @> '(5,6)';

答:
There is no native geometric operator in Postgres that would fulfill the assumptions. You can use arrays of points instead of paths, however it needs some preparations and an access as a superuser.

You need to create an operator class for the type point which allows to compare values of this type. The whole procedure is described in this post: Creating custom “equality operator” for PostgreSQL type (point). Here you have a copy of my code I needed in one of my projects: Postgres class point_ops.

The solution with arrays needs a simple function which you can use instead of an operator:

```<code>create or replace function is_subpath(point[], point[])
returns boolean language plpgsql as $$
begin
    for p in 1..cardinality($1) loop
        if $1[p] = $2[1] then
            for s in 2..cardinality($2) loop
                p:= p+ 1;
                if $1[p] <> $2[s] then
                    return false;
                end if;
                return true;
            end loop;
        end if;
    end loop;
    return false;
end $$;

drop table if exists things;
create table things(
    id int,
    points point[]
);
insert into things values
(1, '{"(3,4)","(1,2)","(5,6)","(7,8)"}'),
(2, '{"(1,2)","(3,4)","(5,6)","(7,8)"}');

select *
from things
where is_subpath(points, '{"(3,4)","(5,6)"}'::point[]);

 id |              points
----+-----------------------------------
  2 | {"(1,2)","(3,4)","(5,6)","(7,8)"}
(1 row)
</code>```

Title: Query using subset of path in Postgres

Body:
Given this table:

 id |            points (path)                 |
----+------------------------------------------+
  1 | ((1,2),(3,4),(5,6),(7,8))                |

Is it possible to achieve the following using a single geometric operator and a path argument (sequential subset of the containing path), like ((3,4),(5,6))?

select * from things where points @> '(3,4)' and points @> '(5,6)';

Body:
There is no native geometric operator in Postgres that would fulfill the assumptions. You can use arrays of points instead of paths, however it needs some preparations and an access as a superuser.

You need to create an operator class for the type point which allows to compare values of this type. The whole procedure is described in this post: Creating custom “equality operator” for PostgreSQL type (point). Here you have a copy of my code I needed in one of my projects: Postgres class point_ops.

The solution with arrays needs a simple function which you can use instead of an operator:

create or replace function is_subpath(point[], point[])
returns boolean language plpgsql as $$
begin
    for p in 1..cardinality($1) loop
        if $1[p] = $2[1] then
            for s in 2..cardinality($2) loop
                p:= p+ 1;
                if $1[p] <> $2[s] then
                    return false;
                end if;
                return true;
            end loop;
        end if;
    end loop;
    return false;
end $$;

drop table if exists things;
create table things(
    id int,
    points point[]
);
insert into things values
(1, '{"(3,4)","(1,2)","(5,6)","(7,8)"}'),
(2, '{"(1,2)","(3,4)","(5,6)","(7,8)"}');

select *
from things
where is_subpath(points, '{"(3,4)","(5,6)"}'::point[]);

 id |              points
----+-----------------------------------
  2 | {"(1,2)","(3,4)","(5,6)","(7,8)"}
(1 row)


问:
In the child page, I want to find master page's Content placeholder and add text to it. How do I make that possible?
I tried this much:-</p>

```<code>protected void Page_PreInit(object sender, EventArgs e)
  {
        class1 obj = new class1();
        DataTable dt = new DataTable();
        dt = obj.get_text();
        ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        ContentPlaceHolder1. ????

 }
</code>```

答:
You cannot add text to a content placeholder. Since it's in a masterpage, you have to add the text to a control on the page you're loading. If you want the text to appear on the master page, you want to add a label or literal outside the content placeholder on the master page and access it the same way you access the content placeholder in your example.

However, given your example, you don't need to do that. You can just set the text on the page you're viewing.

ContentLicense: CC BY-SA 2.5

Body:
I tried this much:-

protected void Page_PreInit(object sender, EventArgs e)
  {
        class1 obj = new class1();
        DataTable dt = new DataTable();
        dt = obj.get_text();
        ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        ContentPlaceHolder1. ????

 }


问:
Appending to array in closure
Im pulling userUID data from my firebase database and putting it into an array. When I go to print the array outside of the observe closure it doesn't print, but inside of the closure it does. Whats happening here?</p>

```<code>let databaseRef = Database.database().reference()
var userUIDArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    databaseRef.child("Users").observe(.value, with: { (snapshot) in
        let snapshots = snapshot.children.allObjects as! [DataSnapshot]
        for child in snapshots {
            self.userUIDArray.append(child.key)
        }
    })
    print(self.userUIDArray)
}
</code>```

答:
The code inside the closure is executed asynchronously (after a network request is made), which means it executes after the rest of the code inside of viewDidLoad.

Here is a quick ordering of when the code is executed:

```<code>override func viewDidLoad() {

    // #1

    databaseRef.child("Users").observe(.value, with: { (snapshot) in
        // #3
    })

    // #2

}
</code>```

The print statement outside of the closure prints nothing because there are no elements in the array when it is called. The print statement inside the closure works because the array has been modified before it is called.

Here is an example of how to use this data when it is returned from Firebase:

```<code>let databaseRef = Database.database().reference()
var userUIDArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    databaseRef.child("Users").observe(.value, with: { (snapshot) in
        let snapshots = snapshot.children.allObjects as! [DataSnapshot]
        for child in snapshots {
            self.userUIDArray.append(child.key)
        }
        updateUserInterface()
    })

}

func updateUserInterface() {
    // update the UI here using the `userUIDArray` variable
    myTableView.reloadData()
}
</code>```

Title: Appending to array in closure

Body:
Im pulling userUID data from my firebase database and putting it into an array. When I go to print the array outside of the observe closure it doesn't print, but inside of the closure it does. Whats happening here?

let databaseRef = Database.database().reference()
var userUIDArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    databaseRef.child("Users").observe(.value, with: { (snapshot) in
        let snapshots = snapshot.children.allObjects as! [DataSnapshot]
        for child in snapshots {
            self.userUIDArray.append(child.key)
        }
    })
    print(self.userUIDArray)
}

Body:
The code inside the closure is executed asynchronously (after a network request is made), which means it executes after the rest of the code inside of viewDidLoad.

Here is a quick ordering of when the code is executed:

override func viewDidLoad() {

    // #1

    databaseRef.child("Users").observe(.value, with: { (snapshot) in
        // #3
    })

    // #2

}

The print statement outside of the closure prints nothing because there are no elements in the array when it is called. The print statement inside the closure works because the array has been modified before it is called.

Here is an example of how to use this data when it is returned from Firebase:

let databaseRef = Database.database().reference()
var userUIDArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    databaseRef.child("Users").observe(.value, with: { (snapshot) in
        let snapshots = snapshot.children.allObjects as! [DataSnapshot]
        for child in snapshots {
            self.userUIDArray.append(child.key)
        }
        updateUserInterface()
    })

}

func updateUserInterface() {
    // update the UI here using the `userUIDArray` variable
    myTableView.reloadData()
}


问:
I'm Unable to setText of a TextView in a class (Android)
I'm using SOAP, In AsyncTask classs I'm trtying to set text of driverIDText, shipmentIDText, freightShipment textviews but it's saying unable to resolve setText()

Here is my code:

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_up);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

         TextView driverIDText = (TextView) findViewById(R.id.text_DriverID);
         TextView shipmentIDText = (TextView) findViewById(R.id.text_ShipmentID);
         TextView freightShipment = (TextView) findViewById(R.id.text_FreightShipment);

new RetrieveFeedTask(driverIDText.getText.toString(),
shipmentIDText.getText().toString(),
freightShipment.getText().toString()
).execute();

    }

    class RetrieveFeedTask extends AsyncTask<String, String, Void> {

        private String driverIDText, shipmentIDText, freightShipment;

        RetrieveFeedTask(String driverIDText, String shipmentIDText, String freightShipment) {
            this.driverIDText = driverIDText;
            this.shipmentIDText = shipmentIDText;
            this.freightShipment = freightShipment;
        }

        protected Void doInBackground(String... urls) {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("DriverID", driverIDText);
            request.addProperty("ShipmentID", shipmentIDText);
            request.addProperty("FreightShipment", freightShipment);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {

                    // HERE IS PROBLEM IN SETTEXT()
                    driverIDText.setText(result.getProperty(0).toString());

                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

    }
</code>```

答:
Inside AsyncTask you declared driverIDText as String not TextView, So Create one more param for TextView and send driverIDText(TextView) from Oncreate and set the data in textView in onPostExecute.

Ex:

```<code>    class RetrieveFeedTask extends AsyncTask<String, String, String> {

        private String driverIDText, shipmentIDText, freightShipment;

        private TextView driverIDTextTv;

        RetrieveFeedTask(String driverIDText, String shipmentIDText, String freightShipment, TextView textView) {
            this.driverIDText = driverIDText;
            this.shipmentIDText = shipmentIDText;
            this.freightShipment = freightShipment;
            driverIDTextTv = textView;
        }

        @Override
        protected void onPostExecute(String text) {
            super.onPostExecute(text);

            driverIDTextTv.setText(text);
        }

        protected String doInBackground(String... urls) {

            String localDriverId = "";

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("DriverID", driverIDText);
            request.addProperty("ShipmentID", shipmentIDText);
            request.addProperty("FreightShipment", freightShipment);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {

                    // HERE IS PROBLEM IN SETTEXT()
//                    driverIDText.setText(result.getProperty(0).toString());

                    localDriverId = result.getProperty(0).toString();

                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                e.printStackTrace();

            }
            return localDriverId;
        }

    }
</code>```

and you can call AsyncTask like this,

```<code>new RetrieveFeedTask(driverIDText.getText.toString(),
                shipmentIDText.getText().toString(),
                freightShipment.getText().toString(), driverIDText
        ).execute();
</code>```

Body:
I'm using SOAP, In AsyncTask classs I'm trtying to set text of driverIDText, shipmentIDText, freightShipment textviews but it's saying unable to resolve setText()

Here is my code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_up);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

         TextView driverIDText = (TextView) findViewById(R.id.text_DriverID);
         TextView shipmentIDText = (TextView) findViewById(R.id.text_ShipmentID);
         TextView freightShipment = (TextView) findViewById(R.id.text_FreightShipment);

new RetrieveFeedTask(driverIDText.getText.toString(),
shipmentIDText.getText().toString(),
freightShipment.getText().toString()
).execute();

    }

    class RetrieveFeedTask extends AsyncTask<String, String, Void> {

        private String driverIDText, shipmentIDText, freightShipment;

        RetrieveFeedTask(String driverIDText, String shipmentIDText, String freightShipment) {
            this.driverIDText = driverIDText;
            this.shipmentIDText = shipmentIDText;
            this.freightShipment = freightShipment;
        }

        protected Void doInBackground(String... urls) {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("DriverID", driverIDText);
            request.addProperty("ShipmentID", shipmentIDText);
            request.addProperty("FreightShipment", freightShipment);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {

                    // HERE IS PROBLEM IN SETTEXT()
                    driverIDText.setText(result.getProperty(0).toString());

                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

    }

Body:
Inside AsyncTask you declared driverIDText as String not TextView, So Create one more param for TextView and send driverIDText(TextView) from Oncreate and set the data in textView in onPostExecute.

Ex:

    class RetrieveFeedTask extends AsyncTask<String, String, String> {

        private String driverIDText, shipmentIDText, freightShipment;

        private TextView driverIDTextTv;

        RetrieveFeedTask(String driverIDText, String shipmentIDText, String freightShipment, TextView textView) {
            this.driverIDText = driverIDText;
            this.shipmentIDText = shipmentIDText;
            this.freightShipment = freightShipment;
            driverIDTextTv = textView;
        }

        @Override
        protected void onPostExecute(String text) {
            super.onPostExecute(text);

            driverIDTextTv.setText(text);
        }

        protected String doInBackground(String... urls) {

            String localDriverId = "";

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("DriverID", driverIDText);
            request.addProperty("ShipmentID", shipmentIDText);
            request.addProperty("FreightShipment", freightShipment);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {

                    // HERE IS PROBLEM IN SETTEXT()
//                    driverIDText.setText(result.getProperty(0).toString());

                    localDriverId = result.getProperty(0).toString();

                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                e.printStackTrace();

            }
            return localDriverId;
        }

    }

and you can call AsyncTask like this,

new RetrieveFeedTask(driverIDText.getText.toString(),
                shipmentIDText.getText().toString(),
                freightShipment.getText().toString(), driverIDText
        ).execute();


问:
404 Not Found exception handling
I have a controller that, in case there is no user with the given name, will return 404 NOT FOUND.

```<code>@GetMapping(value = "/profile/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<User> getUsers(@PathVariable("username") String username) {
    User user = userService.findOneByUsername(username);

    if(user != null) {
        return ResponseEntity.ok(user);
    }

    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
</code>```

Then I created a controller that will be able to handle this exception

```<code>    @ControllerAdvice
    public class ExceptionHandlerController {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public ModelAndView handleNotFound(NoHandlerFoundException e) {
        return new ModelAndView("redirect:/signIn");
    }
}
</code>```

However, it has no effect. The controller returns the normal default 404 error page. It does not respond to my controller.

EDIT: I set spring.mvc.throw-exception-if-no-handler-found = true, but that also did not help. I'm using Spring Boot.

答: You're not throwing NoHandlerFoundException in your controller. This way the ControllerAdvice will not run.</p>

Title: 404 Not Found exception handling

Body:
I have a controller that, in case there is no user with the given name, will return 404 NOT FOUND.

@GetMapping(value = "/profile/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<User> getUsers(@PathVariable("username") String username) {
    User user = userService.findOneByUsername(username);

    if(user != null) {
        return ResponseEntity.ok(user);
    }

    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

Then I created a controller that will be able to handle this exception

    @ControllerAdvice
    public class ExceptionHandlerController {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public ModelAndView handleNotFound(NoHandlerFoundException e) {
        return new ModelAndView("redirect:/signIn");
    }
}

However, it has no effect. The controller returns the normal default 404 error page. It does not respond to my controller.

EDIT: I set spring.mvc.throw-exception-if-no-handler-found = true, but that also did not help. I'm using Spring Boot.


问:
Angular 2 RC 5 Attempting to Get and Display a PDF from a Server
I am trying to display a PDF that is generated from a server onto a view in my Angular 2 RC 5 project. Right now, the ASPNETCORE server is returning the object as an 'application/pdf' and the Angular client is trying to parse the response as a blob. However, I get the following error on the client side:

Error: The request body isn't either a blob or an array buffer

The code that I'm using to call the PDF server is essentially:

```<code>getHeaders() : Headers {
    var headers = new Headers({
        'responseType': 'application/blob'
    });
    return headers;
}

getBlob() {
    return this.http.get(uri, new RequestOptions({headers: this.getHeaders()}, body: "" }))
    .map(response => (<Response>response).blob());
}
</code>```

答:
Work's for me :

Component :

```<code>downloadInvoice(invoice) {
  this.loading = true;
  this.invoiceDataService
  .downloadInvoice(invoice)
  .subscribe(
    (blob) => {
      FileSaver.saveAs(blob, 'test.pdf');
    },
    error => this.error = error,
    () =>  {
      this.loading = false;
      console.log('downloadInvoices : Request Complete')
    }
  )
}
</code>```

Data service :

```<code>downloadInvoice(invoice): Observable<Blob> {
  return this.api.downloadInvoice(invoice);
}
</code>```

Api service :

```<code>downloadInvoice(invoice: Invoice):  Observable<Blob> {
  return this.authHttp
  .get(this.apiBase + '/invoices/' + invoice.hashid + '/download', {responseType: ResponseContentType.Blob})
  .map(response => {
    return new Blob([response.blob()], {type: 'application/pdf'});
  })
  .catch(this.handleError.bind(this));
}
</code>```

Enjoy :)

Body:
I am trying to display a PDF that is generated from a server onto a view in my Angular 2 RC 5 project. Right now, the ASPNETCORE server is returning the object as an 'application/pdf' and the Angular client is trying to parse the response as a blob. However, I get the following error on the client side:

Error: The request body isn't either a blob or an array buffer

The code that I'm using to call the PDF server is essentially:

getHeaders() : Headers {
    var headers = new Headers({
        'responseType': 'application/blob'
    });
    return headers;
}

getBlob() {
    return this.http.get(uri, new RequestOptions({headers: this.getHeaders()}, body: "" }))
    .map(response => (<Response>response).blob());
}

Body:
Work's for me :

Component :

downloadInvoice(invoice) {
  this.loading = true;
  this.invoiceDataService
  .downloadInvoice(invoice)
  .subscribe(
    (blob) => {
      FileSaver.saveAs(blob, 'test.pdf');
    },
    error => this.error = error,
    () =>  {
      this.loading = false;
      console.log('downloadInvoices : Request Complete')
    }
  )
}

Data service :

downloadInvoice(invoice): Observable<Blob> {
  return this.api.downloadInvoice(invoice);
}

Api service :

downloadInvoice(invoice: Invoice):  Observable<Blob> {
  return this.authHttp
  .get(this.apiBase + '/invoices/' + invoice.hashid + '/download', {responseType: ResponseContentType.Blob})
  .map(response => {
    return new Blob([response.blob()], {type: 'application/pdf'});
  })
  .catch(this.handleError.bind(this));
}

Enjoy :)


问:
How to get binary post data in Django !nicely?
forgive me if this is a bit of a newbie question, I started to learn Django yesterday, and I'm trying not to get into bad habits, i.e. I am trying to do things "the django way" from the start.

I have a view that recieves binary data as a http post field. Now Django of course autoconverts my binary data to a unicode string.

My question is, how do I just get the raw binary data?

A couple of things occurred to me. Let request be the request I'm processing.

Using request.raw_post_data would involve parsing the data again - when appearantly request.POST actually stores raw data and I am actually just trying to get around the on-the-fly conversion (and besides, that is new in the development version).

Using base64 or so to transfer the data would work, but seems like too much overhead when the data transfer itself is not the problem.

doing request.encoding="foo" before getting that field (and reassigning afterwards) doesn't work either because I still get a unicode string, besides feeling like a bit of a dirty hack. Using "base64" here (not as bad as for the transfer encoding) gives me an
AssertionError.

Thanks in advance for your ideas!

EDIT:
To clarify - I am not talking about a classic file upload here, but as binary data stored in a POST field. I'd like to do it that way because the only way I want to interface with that view is via an upload script. Using a normal POST field makes both the client and the server much simpler in that case.

答:
Some might say that storing binary data in a standard form field is a bad habit in some way :)

You could use standard library methods of Python to convert your string back to a binary representation.

Take a look at binascii — Convert between binary and ASCI

Posting before edit:

What about this piece of code (receiving data from a POST)

```<code>def handleFile(self, request):
    file = request.FILES["file"]
    destination = open('filename.ext', 'wb')
        for chunk in file.chunks():
            destination.write(chunk)
    destination.close()
</code>```

Works for me.

Body:
Some might say that storing binary data in a standard form field is a bad habit in some way :)

You could use standard library methods of Python to convert your string back to a binary representation.

Take a look at binascii — Convert between binary and ASCI

Posting before edit:

What about this piece of code (receiving data from a POST)

def handleFile(self, request):
    file = request.FILES["file"]
    destination = open('filename.ext', 'wb')
        for chunk in file.chunks():
            destination.write(chunk)
    destination.close()

Works for me.


问:
decorator approach to JSON serializing?
I am using JSON to send data from Python to R (note: I'm much more familiar with R than Python). For primitives, the json module works great. For many other Python objects (e.g. numpy arrays) you have to define a custom encoder, like in this stack overflow answer. However, that requires you to pass the encoder as an argument to json.dumps, which doesn't work that well for my case.
I know there are other packages like json_tricks that have much more advanced capabilities for JSON serialization, but since I don't have control over what Python distribution a user has I don't want to rely on any non-default modules for serializing objects to JSON.

I'm wondering if there is a way to use <s>contextlib</s> decorators to define additional ways for serializing JSON objects. Ideally, I'm looking for a way that would allow users to overload some standard function standard_wrapper that I provide to add new methods for their own classes (or types from modules that they load) without requiring them to modify standard_wrapper. Some psuedocode below:

```<code>import json

def standard_wrapper(o):
  return o

obj = [44,64,13,4,79,2,454,89,0]

json.dumps(obj)
json.dumps(standard_wrapper(obj))

import numpy as np
objnp = np.sort(obj)

json.dumps(objnp)  # FAILS

@some_decorator_to_overload_standard_wrapper
# some code

json.dumps(standard_wrapper(objnp))  # HOPEFULLY WORKS
</code>```

This is essentially function overloading by type---I've seen examples for overloading by arguments in Python, but I don't see how to do it by type.

EDIT I was mixing up decorators with contextlib (which I had only ever seen used a decorator).

答:
It's easy to use singledispatch from functools module to overload a function by type, as shown in this answer to a different post. However, a simpler  solution that may fit my needs is to create a dictionary of functions where the keys correspond to the object type.

```<code>import numpy
func_dict = {}
a = [2,5,2,9,75,8,36,2,8]
an = numpy.sort(a)

func_dict[type(an)] = lambda x: x.tolist()
func_dict[type(a)] = lambda x: x

import json
json.dumps(func_dict[type(a)](a))
json.dumps(func_dict[type(an)](an))
</code>```

Adding support for another type is achieved by adding another function to the dictionary.

Title: decorator approach to JSON serializing?

Body:
I am using JSON to send data from Python to R (note: I'm much more familiar with R than Python). For primitives, the json module works great. For many other Python objects (e.g. numpy arrays) you have to define a custom encoder, like in this stack overflow answer. However, that requires you to pass the encoder as an argument to json.dumps, which doesn't work that well for my case.
I know there are other packages like json_tricks that have much more advanced capabilities for JSON serialization, but since I don't have control over what Python distribution a user has I don't want to rely on any non-default modules for serializing objects to JSON.

I'm wondering if there is a way to use <s>contextlib</s> decorators to define additional ways for serializing JSON objects. Ideally, I'm looking for a way that would allow users to overload some standard function standard_wrapper that I provide to add new methods for their own classes (or types from modules that they load) without requiring them to modify standard_wrapper. Some psuedocode below:

import json

def standard_wrapper(o):
  return o

obj = [44,64,13,4,79,2,454,89,0]

json.dumps(obj)
json.dumps(standard_wrapper(obj))

import numpy as np
objnp = np.sort(obj)

json.dumps(objnp)  # FAILS

@some_decorator_to_overload_standard_wrapper
# some code

json.dumps(standard_wrapper(objnp))  # HOPEFULLY WORKS

This is essentially function overloading by type---I've seen examples for overloading by arguments in Python, but I don't see how to do it by type.

EDIT I was mixing up decorators with contextlib (which I had only ever seen used a decorator).

Body:
It's easy to use singledispatch from functools module to overload a function by type, as shown in this answer to a different post. However, a simpler  solution that may fit my needs is to create a dictionary of functions where the keys correspond to the object type.

import numpy
func_dict = {}
a = [2,5,2,9,75,8,36,2,8]
an = numpy.sort(a)

func_dict[type(an)] = lambda x: x.tolist()
func_dict[type(a)] = lambda x: x

import json
json.dumps(func_dict[type(a)](a))
json.dumps(func_dict[type(an)](an))

Adding support for another type is achieved by adding another function to the dictionary.


问:
Alias to set default CLI options on PowerShell
I want to use new-alias or set-alias aliases to set --includeuser as a default switch for get-process cmdlet.

I do:

```<code>new-alias get-process 'get-process -includeuser'
</code>```

but I get the following error on executing get-process:

get-process : The term 'get-process -includeuser $*' is not recognized
  as the name of a cmdlet, function, script file, or operable program.
  Check the spelling of the name, or if a path was included, verify that
  the path is correct and try again.

Please help me with that.

For comparison cmd.exe aliaseses can be set with doskey as follows:

```<code>doskey task=tasklist
</code>```

$* can be used if there's input arguments to the command.

答:
Aliases in PowerShell don't accept arguments. The usual workaround is to define a short function; e.g.:

```<code>function task { tasklist $args }
</code>```

The $args variable would be the rough equivalent to $* in doskey.

In PowerShell v3 and later, you can also use the built-in $PSDefaultParameterValues variable (a hashtable) to assign default parameter values to cmdlets. For example:

```<code>$PSDefaultParameterValues.Add("Get-Process:IncludeUserName",$true)
</code>```

This would specify that the Get-Process cmdlet uses -IncludeUserName as a default.

The hashtable key is the cmdlet name, the : character and the parameter name (without leading -), and the hashtable value is the value for the parameter.

Body:
I want to use new-alias or set-alias aliases to set --includeuser as a default switch for get-process cmdlet.

I do:

new-alias get-process 'get-process -includeuser'

but I get the following error on executing get-process:

get-process : The term 'get-process -includeuser $*' is not recognized
  as the name of a cmdlet, function, script file, or operable program.
  Check the spelling of the name, or if a path was included, verify that
  the path is correct and try again.

Please help me with that.

For comparison cmd.exe aliaseses can be set with doskey as follows:

doskey task=tasklist

$* can be used if there's input arguments to the command.

Body:
Aliases in PowerShell don't accept arguments. The usual workaround is to define a short function; e.g.:

function task { tasklist $args }

The $args variable would be the rough equivalent to $* in doskey.

In PowerShell v3 and later, you can also use the built-in $PSDefaultParameterValues variable (a hashtable) to assign default parameter values to cmdlets. For example:

$PSDefaultParameterValues.Add("Get-Process:IncludeUserName",$true)

This would specify that the Get-Process cmdlet uses -IncludeUserName as a default.

The hashtable key is the cmdlet name, the : character and the parameter name (without leading -), and the hashtable value is the value for the parameter.


问:
How do I import files in Python?
I'm trying to use pytest to check a function—here is my code:

```<code># src/return_self.py
def return_self(n):
    return n

# tests/return_self_test.py
import pytest

def test_1():
    value = return_self(1)
    assert value == 1
</code>```

How do I require in my src file so that I can test it with pytest? I have tried a few things:

```<code>1. import return_self
2. from src.return_self import *
3. import sys
   sys.path.append('../src')
4. import imp
   return_self = imp.load_source('return_self', '/source/return_self.py')
</code>```

I have also tried them with and without __init__.py files in the root and src directories. But each time, I get some variation on the error E   ModuleNotFoundError: No module named 'return_self'. How can I require in my file?

答:
I will suggest you the setuptools approach (which makes your package distributable :D)

Project files' structure:

```<code>.
├── sample
│   ├── __init__.py
│   └── return_self.py
├── setup.cfg
├── setup.py
└── tests
    └── test_return_self.py
</code>```

where the sample/ directory matches the package's name and also must contain the source.

Minimal setup.py file content:

```<code>from setuptools import setup

setup(
    setup_requires=['pytest-runner'],
    tests_require=['pytest'],
    name='sample'
)
</code>```

Here we are configuring our test environment (you can extend the tests_require variable to include more testing requirements).

setup.cfg file content:

```<code>[aliases]
test=pytest
</code>```

And here we specify we want to run the command pytest every time the developer does: python setup.py test

tests/test_return_self.py

```<code>from pytest import *

from sample.return_self import return_self

def test_return_self():
     assert return_self(4) == 4
</code>```

sample/return_self.py

```<code>def return_self(n):
    return n
</code>```

So, the next thing to do is to run:

```<code>python setup.py develop
</code>```

to make your package available (while running the tests). If you're having problems with permission denied issues: append the --user option to the previous command to instruct python you wanna use the package without root permissions --in short the package will be installed into userland directories.

And finally run the tests using:

```<code>python setup.py test
</code>```

Notes:

By using this approach, you'll be able to alter your project code on the fly (python setup.py develop needs to be run just once)

No ugly statements to inject the source directory into the current python path.

References:

Integrating with setuptools / python setup.py test / pytest-runner

Building and Distributing Packages with Setuptools

Title: How do I import files in Python?

Body:
I'm trying to use pytest to check a function—here is my code:

# src/return_self.py
def return_self(n):
    return n

# tests/return_self_test.py
import pytest

def test_1():
    value = return_self(1)
    assert value == 1

How do I require in my src file so that I can test it with pytest? I have tried a few things:

1. import return_self
2. from src.return_self import *
3. import sys
   sys.path.append('../src')
4. import imp
   return_self = imp.load_source('return_self', '/source/return_self.py')

I have also tried them with and without __init__.py files in the root and src directories. But each time, I get some variation on the error E   ModuleNotFoundError: No module named 'return_self'. How can I require in my file?

Body:
I will suggest you the setuptools approach (which makes your package distributable :D)

Project files' structure:

.
├── sample
│   ├── __init__.py
│   └── return_self.py
├── setup.cfg
├── setup.py
└── tests
    └── test_return_self.py

where the sample/ directory matches the package's name and also must contain the source.

Minimal setup.py file content:

from setuptools import setup

setup(
    setup_requires=['pytest-runner'],
    tests_require=['pytest'],
    name='sample'
)

Here we are configuring our test environment (you can extend the tests_require variable to include more testing requirements).

setup.cfg file content:

[aliases]
test=pytest

And here we specify we want to run the command pytest every time the developer does: python setup.py test

tests/test_return_self.py

from pytest import *

from sample.return_self import return_self

def test_return_self():
     assert return_self(4) == 4

sample/return_self.py

def return_self(n):
    return n

So, the next thing to do is to run:

python setup.py develop

to make your package available (while running the tests). If you're having problems with permission denied issues: append the --user option to the previous command to instruct python you wanna use the package without root permissions --in short the package will be installed into userland directories.

And finally run the tests using:

python setup.py test

Notes:

By using this approach, you'll be able to alter your project code on the fly (python setup.py develop needs to be run just once)

No ugly statements to inject the source directory into the current python path.

References:

Integrating with setuptools / python setup.py test / pytest-runner

Building and Distributing Packages with Setuptools


问:
in_array() and multidimensional array
I use in_array() to check whether a value exists in an array like below,

```<code>$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
    echo "Got Irix";
}

//print_r($a);
</code>```

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

```<code>$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);
</code>```

or I shouldn't be using in_array() when comes to the multidimensional array?

答:
you can use like this

```<code>$result = array_intersect($array1, $array2);
print_r($result);
</code>```

http://php.net/manual/tr/function.array-intersect.php

Title: in_array() and multidimensional array

Body:
I use in_array() to check whether a value exists in an array like below,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
    echo "Got Irix";
}

//print_r($a);

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

or I shouldn't be using in_array() when comes to the multidimensional array?

Body:
you can use like this

$result = array_intersect($array1, $array2);
print_r($result);

http://php.net/manual/tr/function.array-intersect.php


问:
codeigniter login after email verified
I am trying to make sure user can login after confirming their email verification in which STATUS in the database changes from 0 to 1. how do I log users in based on the change of status in the database. Thanks in advance

MODEL:

```<code>   public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}
</code>```

CONTROLLER:

```<code>   public function login(){
    $data['title'] = 'Login';

    $this->form_validation-> set_rules('username', 'Username', 'required');
    $this->form_validation-> set_rules('password', 'Password', 'required');

    if($this->form_validation->run() === FALSE){

    $this->load->view('templates/header');
    $this->load->view('users/login', $data);
    $this->load->view('templates/footer');
    } else {

        // fetching user
    $username = $this->input->post('username');
        //password
    $password = ($this->input->post('password'));

    //login user
    $user_id = $this->user_model->login($username, $password);

    if($user_id){
        //creating session
        $user_data = array(
            'user_id' => $user_id,
            'username' => $username,
            'logged_in' => TRUE,

        );
        $this->session->set_userdata($user_data);
                // Set message to be sent
    $this->session->set_flashdata('user_login', 'Welcome');
    redirect('posts');
    } else {
        // Set message to be sent
    $this->session->set_flashdata('login_fail', 'Login Failed');
    redirect('users/login');
    }

    }

}
</code>```

答:
You just need to verify that the user who's trying to login is verified (if am getting your query right).

for this you can just add another where statement in your query builder while checking username and password. So your model will be like

```<code>public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);
    $this->db->where('status', '1');

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}
</code>```

So now even if user have submitted correct login details but haven't verified his account yet, he'll be unable to login.

Title: codeigniter login after email verified

Body:
I am trying to make sure user can login after confirming their email verification in which STATUS in the database changes from 0 to 1. how do I log users in based on the change of status in the database. Thanks in advance

MODEL:

   public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}

CONTROLLER:

   public function login(){
    $data['title'] = 'Login';

    $this->form_validation-> set_rules('username', 'Username', 'required');
    $this->form_validation-> set_rules('password', 'Password', 'required');

    if($this->form_validation->run() === FALSE){

    $this->load->view('templates/header');
    $this->load->view('users/login', $data);
    $this->load->view('templates/footer');
    } else {

        // fetching user
    $username = $this->input->post('username');
        //password
    $password = ($this->input->post('password'));

    //login user
    $user_id = $this->user_model->login($username, $password);

    if($user_id){
        //creating session
        $user_data = array(
            'user_id' => $user_id,
            'username' => $username,
            'logged_in' => TRUE,

        );
        $this->session->set_userdata($user_data);
                // Set message to be sent
    $this->session->set_flashdata('user_login', 'Welcome');
    redirect('posts');
    } else {
        // Set message to be sent
    $this->session->set_flashdata('login_fail', 'Login Failed');
    redirect('users/login');
    }

    }

}

Body:
You just need to verify that the user who's trying to login is verified (if am getting your query right).

for this you can just add another where statement in your query builder while checking username and password. So your model will be like

public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);
    $this->db->where('status', '1');

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}

So now even if user have submitted correct login details but haven't verified his account yet, he'll be unable to login.


问:
Remove a fixed prefix/suffix from a string in Bash
I want to remove the prefix/suffix from a string. For example, given:

```<code>string="hello-world"
prefix="hell"
suffix="ld"
</code>```

How do I get the following result?

```<code>"o-wor"
</code>```

答:
Small and universal solution:</p>

```<code>expr "$string" : "$prefix\(.*\)$suffix"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to remove the prefix/suffix from a string. For example, given:

string="hello-world"
prefix="hell"
suffix="ld"

How do I get the following result?

"o-wor"

Body:
Small and universal solution:

expr "$string" : "$prefix\(.*\)$suffix"


问:
One entityManger finds entity , the other does not
I have a very strange behavior in my program. I have 2 classes (class LogIn and CreateGame) where i have injected an EntityManager in each using the annotation

```<code>  @PersistenceContext(unitName="myUnitPU")
  EntityManager entitymanger;
</code>```

In some point i remove an object called "user" from the database using entitymanger.remove(user) from a method in LogIn class. The business logic is that a user can host and join games ( in the same time) so removing the user all the entries in database about the games the user has created are removed and all the entries showing in which games the user has joined are removed also.

After that, i call another function which checks if the user exists using a method in the LogIn class

```<code>  entitymanager.find(user)
</code>```

which surprisingly enough, finds the user. After that I call a method in CreateGame class which tries to find the user by using again

```<code>  entitymanger.find(user)
</code>```

the entitymanger in that class fails to find the user (which is the expected result as the user is removed and it's not in the database)

So the question is : Why the entitymanager in one class finds the user (which is wrong) where the other doesn't find it?
Does anyone has ever the same problem?

PS : This "bug" occurs when the user has hosted a game which is joined by another user (lets call him Buser)  and the Buser has made a game which is joined by the current user.

```<code> GAME  |  HOST  | CLIENTS
 game1 |  user  | userB
 game2 |  userB | user
</code>```

where in this case by removing the user,  the game1 is deleted and the user is removed from game2
so the result is

```<code> GAME  |  HOST  | CLIENTS
 game2 |  userB |
</code>```

PS2 :
 The Beans are EJB3.0. The methods are called from a delegate class. The beans in the delegate class are instantiated using the InitialContext.lookup() method.
Note that for logging in ,creating , joining games the appropriate delegate class calls the correspondent EJB which does the transactions. In the case of logOut, the delegate calls an EJB to logout the user but becuase other stuff must be done (as said above) this EJB calls other EJB (again using lookup() ) which has methods like removegame(), removeUserFromGame() etc. After those methods are executed the user is then logged out. Maybe it has something to do with the fact the the first entity manager is called by a delegate but the second from inside an EJb and thats why the one entitymanger can see the non-existent user while the other cannot? Also all the methods have TRANSACTIONTYPE.REQUIRED

Thank you in advance

答: Most probably, user deletion transaction has not been committed while that user has been queried. therefore, I would suggest you to check the transactions. And also, querying that user should be a different transaction, if both operations were in the same transaction, entity manager would not find the deleted user. </p>

Body:
I have a very strange behavior in my program. I have 2 classes (class LogIn and CreateGame) where i have injected an EntityManager in each using the annotation

  @PersistenceContext(unitName="myUnitPU")
  EntityManager entitymanger;

In some point i remove an object called "user" from the database using entitymanger.remove(user) from a method in LogIn class. The business logic is that a user can host and join games ( in the same time) so removing the user all the entries in database about the games the user has created are removed and all the entries showing in which games the user has joined are removed also.

After that, i call another function which checks if the user exists using a method in the LogIn class

  entitymanager.find(user)

which surprisingly enough, finds the user. After that I call a method in CreateGame class which tries to find the user by using again

  entitymanger.find(user)

the entitymanger in that class fails to find the user (which is the expected result as the user is removed and it's not in the database)

So the question is : Why the entitymanager in one class finds the user (which is wrong) where the other doesn't find it?
Does anyone has ever the same problem?

PS : This "bug" occurs when the user has hosted a game which is joined by another user (lets call him Buser)  and the Buser has made a game which is joined by the current user.

 GAME  |  HOST  | CLIENTS
 game1 |  user  | userB
 game2 |  userB | user

where in this case by removing the user,  the game1 is deleted and the user is removed from game2
so the result is

 GAME  |  HOST  | CLIENTS
 game2 |  userB |

PS2 :
 The Beans are EJB3.0. The methods are called from a delegate class. The beans in the delegate class are instantiated using the InitialContext.lookup() method.
Note that for logging in ,creating , joining games the appropriate delegate class calls the correspondent EJB which does the transactions. In the case of logOut, the delegate calls an EJB to logout the user but becuase other stuff must be done (as said above) this EJB calls other EJB (again using lookup() ) which has methods like removegame(), removeUserFromGame() etc. After those methods are executed the user is then logged out. Maybe it has something to do with the fact the the first entity manager is called by a delegate but the second from inside an EJb and thats why the one entitymanger can see the non-existent user while the other cannot? Also all the methods have TRANSACTIONTYPE.REQUIRED

Thank you in advance


问:
How is `getattr` related to `object.__getattribute__` and to `object.__getattr__`?
From https://docs.python.org/3.6/library/functions.html#getattr

```<code>getattr(object, name[, default])
</code>```

Return the value of the named attribute of object. name must be a
  string. If the string is the name of one of the object’s attributes,
  the result is the value of that attribute. For example, getattr(x,
  'foobar') is equivalent to x.foobar. If the named attribute does
  not exist, default is returned if provided, otherwise
  AttributeError is raised.

How is getattr related to object.__getattribute__ and to object.__getattr__?

Does getattr call object.__getattribute__ or object.__getattr__? I would guess the former?

答:
Summary Answer

In general, a dotted lookup invokes __getattribute__.

If the code in __getattribute__ doesn't find the attribute, it looks to see if __getattr__ is defined.  If so, it is called.  Otherwise, AttributeError is raised.

The getattr() function is just an alternative way to call the above methods.  For example getattr(a, 'x') is equivalent to a.x.

The getattr() function is mainly useful when you don't know the name of an attribute in advance (i.e. when it is stored in a variable).  For example, k = 'x'; getattr(a, k) is equivalent to a.x.

Analogy and high level point-of-view

The best way to think of it is that __getattribute__ is the first called primary method and __getattr__ is the fallback which is called when attributes are missing.  In this way, it is very much like the relationship between __getitem__ and __missing__ for square bracket lookups in dictionaries.

Demonstration code

Here is a worked-out example:

```<code>>>> class A(object):
    x = 10
    def __getattribute__(self, attr):
        print(f'Looking up {attr!r}')
        return object.__getattribute__(self, attr)
    def __getattr__(self, attr):
        print(f'Invoked the fallback method for missing {attr!r}')
        return 42

>>> a = A()
>>> a.x
Looking up 'x'
10
>>> a.y
Looking up 'y'
Invoked the fallback method for missing 'y'
42

>>> # Equivalent calls with getattr()
>>> getattr(a, 'x')
Looking up 'x'
10
>>> getattr(a, 'y')
Looking up 'y'
Invoked the fallback method for missing 'y'
42
</code>```

Official Documentation

Here are the relevant parts of the docs:

object.__getattr__(self, name) Called when an attribute lookup has
  not found the attribute in the usual places (i.e. it is not an
  instance attribute nor is it found in the class tree for self). name
  is the attribute name. This method should return the (computed)
  attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism,
  __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to
  access other attributes of the instance. Note that at least for
  instance variables, you can fake total control by not inserting any
  values in the instance attribute dictionary (but instead inserting
  them in another object). See the __getattribute__() method below for a
  way to actually get total control over attribute access.

object.__getattribute__(self, name) Called unconditionally to
  implement attribute accesses for instances of the class. If the class
  also defines __getattr__(), the latter will not be called unless
  __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute
  value or raise an AttributeError exception. In order to avoid infinite
  recursion in this method, its implementation should always call the
  base class method with the same name to access any attributes it
  needs, for example, object.__getattribute__(self, name).

Body:
From https://docs.python.org/3.6/library/functions.html#getattr

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a
  string. If the string is the name of one of the object’s attributes,
  the result is the value of that attribute. For example, getattr(x,
  'foobar') is equivalent to x.foobar. If the named attribute does
  not exist, default is returned if provided, otherwise
  AttributeError is raised.

How is getattr related to object.__getattribute__ and to object.__getattr__?

Does getattr call object.__getattribute__ or object.__getattr__? I would guess the former?

Body:
Summary Answer

In general, a dotted lookup invokes __getattribute__.

If the code in __getattribute__ doesn't find the attribute, it looks to see if __getattr__ is defined.  If so, it is called.  Otherwise, AttributeError is raised.

The getattr() function is just an alternative way to call the above methods.  For example getattr(a, 'x') is equivalent to a.x.

The getattr() function is mainly useful when you don't know the name of an attribute in advance (i.e. when it is stored in a variable).  For example, k = 'x'; getattr(a, k) is equivalent to a.x.

Analogy and high level point-of-view

The best way to think of it is that __getattribute__ is the first called primary method and __getattr__ is the fallback which is called when attributes are missing.  In this way, it is very much like the relationship between __getitem__ and __missing__ for square bracket lookups in dictionaries.

Demonstration code

Here is a worked-out example:

>>> class A(object):
    x = 10
    def __getattribute__(self, attr):
        print(f'Looking up {attr!r}')
        return object.__getattribute__(self, attr)
    def __getattr__(self, attr):
        print(f'Invoked the fallback method for missing {attr!r}')
        return 42

>>> a = A()
>>> a.x
Looking up 'x'
10
>>> a.y
Looking up 'y'
Invoked the fallback method for missing 'y'
42

>>> # Equivalent calls with getattr()
>>> getattr(a, 'x')
Looking up 'x'
10
>>> getattr(a, 'y')
Looking up 'y'
Invoked the fallback method for missing 'y'
42

Official Documentation

Here are the relevant parts of the docs:

object.__getattr__(self, name) Called when an attribute lookup has
  not found the attribute in the usual places (i.e. it is not an
  instance attribute nor is it found in the class tree for self). name
  is the attribute name. This method should return the (computed)
  attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism,
  __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to
  access other attributes of the instance. Note that at least for
  instance variables, you can fake total control by not inserting any
  values in the instance attribute dictionary (but instead inserting
  them in another object). See the __getattribute__() method below for a
  way to actually get total control over attribute access.

object.__getattribute__(self, name) Called unconditionally to
  implement attribute accesses for instances of the class. If the class
  also defines __getattr__(), the latter will not be called unless
  __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute
  value or raise an AttributeError exception. In order to avoid infinite
  recursion in this method, its implementation should always call the
  base class method with the same name to access any attributes it
  needs, for example, object.__getattribute__(self, name).


问:
Extract data from html
I have a scraper class, what collects players from a popular odds portal.
The exact first names are not present, the site uses short forms. eg Rafael -> R. Fortunately they can be found in the links in slugified form (nadal-rafael)

I made a method processPlayers, what tries solve this. It works in simpler cases, but fails if the player have hyphen in his/her first name or she/he has two first names.

I wrote some tests to demonstrate the html structure, and the problem.

class Scraper {
  /**
   * Converts a html string to a cheerio object
   * @param {String} html The html string
   * @return {Object} The cheerio object
   */
  htmlToDom(html) {
    return cheerio.load(html)
  }
  /**
   * Gives back the number of parts if the name would slugify
   * It takes in account, that the name could contains hyphen
   * Leopold von Sacher-Masoch -> leopold-von-sacher-masoch
   * @param {Array} a_name The name splitted by space (' ')
   * @return {Integer} The length of the name
   */
  getNameLength(a_name) {
    let name = a_name.length > 1 ? a_name.join(' ') : a_name[0]
    return a_name.length + name.split('-').length - 1
  }

  capitalize(a_name) {
    let res = []
    a_name.forEach(str => {
      res.push(str.substr(0, 1).toUpperCase() + str.substr(1))
    })
    return res.join(' ')
  }

  processPlayers(players) {
    let link = players('a')
    let href = link.attr('href')
    let a_players = link.text().split(' - ')
    let a_href = href.split('/')
    let a_link = a_href[a_href.length - 2].split('-')
    let a_player1 = a_players[0].trim().split(' ')
    let a_player2 = a_players[1].trim().split(' ')
    let a_player1_lastName = a_player1.slice(0, -1)
    let a_player2_lastName = a_player2.slice(0, -1)
    let a_player1ShortFirstName = [a_player1[a_player1.length - 1]]
    let a_player2ShortFirstName = [a_player2[a_player2.length - 1]]

    let p1_lnLength = this.getNameLength(a_player1_lastName)
    let p1_fnLength = this.getNameLength(a_player1ShortFirstName)
    let p2_lnLength = this.getNameLength(a_player2_lastName)
    let p2_fnLength = this.getNameLength(a_player2ShortFirstName)
    let p1_length = p1_lnLength + p1_fnLength
    let p2_length = p2_lnLength + p2_fnLength
    let player1FirstName = this.capitalize(a_link.slice(p1_lnLength, p1_length))
    let player2FirstName = this.capitalize(a_link.slice(p1_length + p2_lnLength, p1_length + p2_length))

    return {
      p1: {
        firstName: player1FirstName,
        lastName: a_player1_lastName.join(' ')
      },
      p2: {
        firstName: player2FirstName,
        lastName: a_player2_lastName.join(' ')
      }
    }
  }
}

// test ===========================================================

test('simple case', function() {
  let playersCell = `

        Pavlyuchenkova A.
         - Sorribes Tormo S.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p1.firstName, 'Anastasia')
  equal(players.p1.lastName, 'Pavlyuchenkova')

  deepEqual(players.p2, {
    firstName: 'Sara',
    lastName: 'Sorribes Tormo',
  })
});

// =====================================================================

test('hyphen in last name', function() {
  let playersCell = `

      Kudermetova V. - Duque-Marino M.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p2.firstName, 'Mariana')
  equal(players.p2.lastName, 'Duque-Marino')
});

// =====================================================================

test('hyphen in first name', function() {
  let playersCell = `

        Tsonga J-W.
        - Mayer F.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p1.firstName, 'Jo-Wilfried')
  equal(players.p1.lastName, 'Tsonga')
});

test('two first names', function() {
  let playersCell = `

        Alexandrova E. - Muguruza B. G.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p2.firstName, 'Blanco Garbine')
  equal(players.p2.lastName, 'Muguruza')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset=utf-8 />
  <title></title>
  <script src="https://wzrd.in/standalone/cheerio@latest"></script>
  <link rel="StyleSheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css" type="text/css">
</head>

<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="http://code.jquery.com/qunit/qunit-1.12.0.js" type="text/javascript">
  </script>
</body>

</html></code>```

It looks like stackoverflow's snippet has some problem with qunit. So here is the JsBin link:

http://jsbin.com/tohafiqivo/1/edit?html,js,output

答:
Looks like the problem is to determine the last name and the first name correctly in the 'difficult' cases.

You're splitting the text in two full names, OK.

Then you're splitting full name in several words, OK.

And then you're making a mistake assuming that the first name is always the last word, and the rest is the last name.

In fact, the last name is all the words which are not in the short form, and the rest is the first name.

I've solved your problem this way.

Please find the updated class Scraper below (I've removed the functions which are not in use anymore):

```<code>class Scraper {
  /**
   * Converts a html string to a cheerio object
   * @param {String} html The html string
   * @return {Object} The cheerio object
   */
  htmlToDom(html) {
    return cheerio.load(html)
  }

  processPlayers(players) {
    let href = players('a').attr('href')
    let N = players('a').text().trim().split(/\s+-\s+/).map(n => {
        let r = new RegExp('.+('+n.replace(/-/g,'\\S+').replace(/\./g,'[^-]+').replace(/\s/g,'.')+').+','i')
        let p = {lastName: n.replace(/\s\S+\./g,'')}
        href.match(r).map(m => {
          r = new RegExp(p.lastName.replace(/\s/g,'.') + '-', 'i')
          m = m.replace(r,'').split(/-/).map(i => {return i.substring(0,1).toUpperCase() + i.substring(1)})
          p.firstName = n.split(p.lastName + ' ')[1].replace(/\./g,'').split('').map(l => {return m[0] && m[0].indexOf(l) === 0 ? m.shift() : l}).join('')
        })
        return p
      })
    return {p1: N[0], p2: N[1]}
  }
}
</code>```

It passes all the tests.
Sorry if it's not very readable.

Title: Extract data from html

Body:
I have a scraper class, what collects players from a popular odds portal.
The exact first names are not present, the site uses short forms. eg Rafael -> R. Fortunately they can be found in the links in slugified form (nadal-rafael)

I made a method processPlayers, what tries solve this. It works in simpler cases, but fails if the player have hyphen in his/her first name or she/he has two first names.

I wrote some tests to demonstrate the html structure, and the problem.

class Scraper {
  /**
   * Converts a html string to a cheerio object
   * @param {String} html The html string
   * @return {Object} The cheerio object
   */
  htmlToDom(html) {
    return cheerio.load(html)
  }
  /**
   * Gives back the number of parts if the name would slugify
   * It takes in account, that the name could contains hyphen
   * Leopold von Sacher-Masoch -> leopold-von-sacher-masoch
   * @param {Array} a_name The name splitted by space (' ')
   * @return {Integer} The length of the name
   */
  getNameLength(a_name) {
    let name = a_name.length > 1 ? a_name.join(' ') : a_name[0]
    return a_name.length + name.split('-').length - 1
  }

  capitalize(a_name) {
    let res = []
    a_name.forEach(str => {
      res.push(str.substr(0, 1).toUpperCase() + str.substr(1))
    })
    return res.join(' ')
  }

  processPlayers(players) {
    let link = players('a')
    let href = link.attr('href')
    let a_players = link.text().split(' - ')
    let a_href = href.split('/')
    let a_link = a_href[a_href.length - 2].split('-')
    let a_player1 = a_players[0].trim().split(' ')
    let a_player2 = a_players[1].trim().split(' ')
    let a_player1_lastName = a_player1.slice(0, -1)
    let a_player2_lastName = a_player2.slice(0, -1)
    let a_player1ShortFirstName = [a_player1[a_player1.length - 1]]
    let a_player2ShortFirstName = [a_player2[a_player2.length - 1]]

    let p1_lnLength = this.getNameLength(a_player1_lastName)
    let p1_fnLength = this.getNameLength(a_player1ShortFirstName)
    let p2_lnLength = this.getNameLength(a_player2_lastName)
    let p2_fnLength = this.getNameLength(a_player2ShortFirstName)
    let p1_length = p1_lnLength + p1_fnLength
    let p2_length = p2_lnLength + p2_fnLength
    let player1FirstName = this.capitalize(a_link.slice(p1_lnLength, p1_length))
    let player2FirstName = this.capitalize(a_link.slice(p1_length + p2_lnLength, p1_length + p2_length))

    return {
      p1: {
        firstName: player1FirstName,
        lastName: a_player1_lastName.join(' ')
      },
      p2: {
        firstName: player2FirstName,
        lastName: a_player2_lastName.join(' ')
      }
    }
  }
}

// test ===========================================================

test('simple case', function() {
  let playersCell = `

        Pavlyuchenkova A.
         - Sorribes Tormo S.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p1.firstName, 'Anastasia')
  equal(players.p1.lastName, 'Pavlyuchenkova')

  deepEqual(players.p2, {
    firstName: 'Sara',
    lastName: 'Sorribes Tormo',
  })
});

// =====================================================================

test('hyphen in last name', function() {
  let playersCell = `

      Kudermetova V. - Duque-Marino M.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p2.firstName, 'Mariana')
  equal(players.p2.lastName, 'Duque-Marino')
});

// =====================================================================

test('hyphen in first name', function() {
  let playersCell = `

        Tsonga J-W.
        - Mayer F.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p1.firstName, 'Jo-Wilfried')
  equal(players.p1.lastName, 'Tsonga')
});

test('two first names', function() {
  let playersCell = `

        Alexandrova E. - Muguruza B. G.

    `
  const scraper = new Scraper()
  const td = scraper.htmlToDom(playersCell)
  const players = scraper.processPlayers(td)

  equal(players.p2.firstName, 'Blanco Garbine')
  equal(players.p2.lastName, 'Muguruza')
});

<!DOCTYPE html>

  <meta charset=utf-8 />
  <title></title>

  <link rel="StyleSheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css" type="text/css">

It looks like stackoverflow's snippet has some problem with qunit. So here is the JsBin link:

http://jsbin.com/tohafiqivo/1/edit?html,js,output

Body:
Looks like the problem is to determine the last name and the first name correctly in the 'difficult' cases.

You're splitting the text in two full names, OK.

Then you're splitting full name in several words, OK.

And then you're making a mistake assuming that the first name is always the last word, and the rest is the last name.

In fact, the last name is all the words which are not in the short form, and the rest is the first name.

I've solved your problem this way.

Please find the updated class Scraper below (I've removed the functions which are not in use anymore):

class Scraper {
  /**
   * Converts a html string to a cheerio object
   * @param {String} html The html string
   * @return {Object} The cheerio object
   */
  htmlToDom(html) {
    return cheerio.load(html)
  }

  processPlayers(players) {
    let href = players('a').attr('href')
    let N = players('a').text().trim().split(/\s+-\s+/).map(n => {
        let r = new RegExp('.+('+n.replace(/-/g,'\\S+').replace(/\./g,'[^-]+').replace(/\s/g,'.')+').+','i')
        let p = {lastName: n.replace(/\s\S+\./g,'')}
        href.match(r).map(m => {
          r = new RegExp(p.lastName.replace(/\s/g,'.') + '-', 'i')
          m = m.replace(r,'').split(/-/).map(i => {return i.substring(0,1).toUpperCase() + i.substring(1)})
          p.firstName = n.split(p.lastName + ' ')[1].replace(/\./g,'').split('').map(l => {return m[0] && m[0].indexOf(l) === 0 ? m.shift() : l}).join('')
        })
        return p
      })
    return {p1: N[0], p2: N[1]}
  }
}

It passes all the tests.
Sorry if it's not very readable.


问:
I can't edit a object in an array, ng-model doesn't change with ng-click
I am making a movie library. I use ng-repeat to show the movies and, for each movie there is a button to edit it and another one to remove it. The remove button works just fine, but the edit button doesn't.
It should open a panel and fill it with the movie data, but it only opens the panel with the first value I defined for the index.

```<code>button
<i class="glyphicon glyphicon-pencil small btnEdit" ng-click="i =(movies.indexOf(movie));"></i>

input
<input type="text" class="form-control" placeholder="Title" id="title" ng-model="movies[i].title">
</code>```

the whole code is here: https://jsfiddle.net/victoorns/mwgcnsno/2/

答:
Your controller's $scope property 'i' is being hidden via the rules behind scope inheritance. Ng-repeat creates its own isolate scope and since 'i' is a primitive (its just an integer), 'i' is only being set on that child $scope, as opposed to the main parent controller's scope.

```<code><input type="text" class="form-control" placeholder="Title" id="title"
       ng-model="movies[selected.movieIndex].title">

<i class="glyphicon glyphicon-pencil small btnEdit"
   ng-click="selected.movieIndex =(movies.indexOf(movie));"></i>
</code>```

Heres an updated jsfiddle here.

Notice how I am using an object (selected.movieIndex) so that is correctly updating the right property.

Heres more on understanding the exact behavior going on with the scope here

Body:
I am making a movie library. I use ng-repeat to show the movies and, for each movie there is a button to edit it and another one to remove it. The remove button works just fine, but the edit button doesn't.
It should open a panel and fill it with the movie data, but it only opens the panel with the first value I defined for the index.

button

input
<input type="text" class="form-control" placeholder="Title" id="title" ng-model="movies[i].title">

the whole code is here: https://jsfiddle.net/victoorns/mwgcnsno/2/

Body:
Your controller's $scope property 'i' is being hidden via the rules behind scope inheritance. Ng-repeat creates its own isolate scope and since 'i' is a primitive (its just an integer), 'i' is only being set on that child $scope, as opposed to the main parent controller's scope.

<input type="text" class="form-control" placeholder="Title" id="title"
       ng-model="movies[selected.movieIndex].title">

<i class="glyphicon glyphicon-pencil small btnEdit"
   ng-click="selected.movieIndex =(movies.indexOf(movie));"></i>

Heres an updated jsfiddle here.

Notice how I am using an object (selected.movieIndex) so that is correctly updating the right property.

Heres more on understanding the exact behavior going on with the scope here


问:
Jenkins.log location on Ubuntu 14.04 desktop

Setup

I am currently running a Jenkins instance on an Ubuntu 14.04 desktop machine. I have installed Jenkins via WAR distribution and am running Jenkins as a service on the host machine.

Issue

I am trying to access the jenkins.log file described here in the logging documentation on the Jenkins wiki. The purpose of accessing this file is to be sure we have a log to use in the event that Jenkins web UI is unavailable and there is an issue with Jenkins.

I've taken a look in /var/log/jenkins/ as the documentation suggests, however the only file in that folder is a config file.

Also, per the documentation, I have double checked the /etc/default/jenkins as well as the /etc/sysconfig/jenkins directories. Each one of these two directories does not exist on my machine.

I have also tried searching from command line using the 'find' command, as well as searching my system using the Ubuntu file explorer. Each of these approaches yielded no jenkins.log file.

Questions

Am I correct in my understanding that Jenkins system logs are output
to the jenkins.log file?

Where might the jenkins.log file be located on my machine?

Is this the best approach in troubleshooting issues with Jenkins when the web UI is inaccessible?

答:
Jenkins does not write to any file, so there is no jenkins.log by default, instead it writes to the standard output.

So here is something we used in the init.d file:

```<code>JENKINS_WAR=/path/to/jenkins/war/jenkins.war
JENKINS_LOG=/path/to/jenkins/log/jenkins.log
JAVA_HOME=/path/to/java/home

STARTUP="$JAVA_HOME/bin/java -Xms4096m -Xmx8192m -Dhudson.model.DirectoryBrowserSupport.CSP= -jar $JENKINS_WAR > $JENKINS_LOG 2>&1 &"
</code>```

Also as suggested in the doc, you can use hook script to make it rotated.

You might also be interested in Audit Trail Plugin.

Body:
Jenkins does not write to any file, so there is no jenkins.log by default, instead it writes to the standard output.

So here is something we used in the init.d file:

JENKINS_WAR=/path/to/jenkins/war/jenkins.war
JENKINS_LOG=/path/to/jenkins/log/jenkins.log
JAVA_HOME=/path/to/java/home

STARTUP="$JAVA_HOME/bin/java -Xms4096m -Xmx8192m -Dhudson.model.DirectoryBrowserSupport.CSP= -jar $JENKINS_WAR > $JENKINS_LOG 2>&1 &"

Also as suggested in the doc, you can use hook script to make it rotated.

You might also be interested in Audit Trail Plugin.


问:
mysql performance question
Is a search through numbers (INT) faster than characters in an mySQL database?
Regards,
Thijs</p>

答:
Yes, it should be. An int is only 4 bytes, while in a text (varchar) might be considerably bigger.

Besides, if you have an index on the field you are searching, it will be smaller in size. Hence, you might need fewer disk accesses to do an index scan.

Title: mysql performance question


问:
I want call php page by clicking on a button but I want to verify it first through javascript that entered value is correct or not
```<code><head>
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>
</head>
</code>```

I'm using this code for verify entered value and after verification I want call php page to get the entered value for further task

```<code><body>
<form>
    <input type="text" id="search" onsubmit="search()" name="bg">
</form>
</body>
</code>```

答:
Not 100% sure what your asking!
If you are trying to get the value of the input field you need to change your document.getElementid("search");
To document.getElementid("search").value;
As this will be a string you will also need to change your if statement to make sure the value is equal to a 'A' ||'B'</p>

Body:
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>

I'm using this code for verify entered value and after verification I want call php page to get the entered value for further task

<form>
    <input type="text" id="search" onsubmit="search()" name="bg">
</form>