signature:
def queue ( users , label , extra_context = None , sender = None ) :
    """Queue the notification in NoticeQueueBatch . This allows for large amounts
 of user notifications to be deferred to a seperate process running outside
 the webserver ."""

implementation:
if extra_context is None :
    extra_context = { }
if isinstance ( users , QuerySet ) :
    users = [ row [ "pk" ] for row in users . values ( "pk" ) ]
else :
    users = [ user . pk for user in users ]
notices = [ ]
for user in users :
    notices . append ( ( user , label , extra_context , sender ) )
NoticeQueueBatch ( pickled_data = base64 . b64encode ( pickle . dumps ( notices ) ) ) . save ( )


signature:
def write_table_pair_potential ( func , dfunc = None , bounds = ( 1.0 , 10.0 ) , samples = 1000 , tollerance = 1e-6 , keyword = 'PAIR' ) :
    """A helper function to write lammps pair potentials to string . Assumes that
 functions are vectorized .
 Parameters
 func : function
 A function that will be evaluated for the force at each radius . Required to
 be numpy vectorizable .
 dfunc : function
 Optional . A function that will be evaluated for the energy at each
 radius . If not supplied the centered difference method will be
 used . Required to be numpy vectorizable .
 bounds : tuple , list
 Optional . specifies min and max radius to evaluate the
 potential . Default 1 length unit , 10 length unit .
 samples : int
 Number of points to evaluate potential . Default 1000 . Note that
 a low number of sample points will reduce accuracy .
 tollerance : float
 Value used to centered difference differentiation .
 keyword : string
 Lammps keyword to use to pair potential . This keyword will need
 to be used in the lammps pair _ coeff . Default ` ` PAIR ` `
 filename : string
 Optional . filename to write lammps table potential as . Default
 ` ` lammps . table ` ` it is highly recomended to change the value .
 A file for each unique pair potential is required ."""

implementation:
r_min , r_max = bounds
if dfunc is None :
    dfunc = lambda r : ( func ( r + tollerance ) - func ( r - tollerance ) ) / ( 2 * tollerance )
i = np . arange ( 1 , samples + 1 )
r = np . linspace ( r_min , r_max , samples )
forces = func ( r )
energies = dfunc ( r )
lines = [ '%d %f %f %f\n' % ( index , radius , force , energy ) for index , radius , force , energy in zip ( i , r , forces , energies ) ]
return "%s\nN %d\n\n" % ( keyword , samples ) + '' . join ( lines )


signature:
def write_tersoff_potential ( parameters ) :
    """Write tersoff potential file from parameters to string
 Parameters
 parameters : dict
 keys are tuple of elements with the values being the parameters length 14"""

implementation:
lines = [ ]
for ( e1 , e2 , e3 ) , params in parameters . items ( ) :
    if len ( params ) != 14 :
        raise ValueError ( 'tersoff three body potential expects 14 parameters' )
    lines . append ( ' ' . join ( [ e1 , e2 , e3 ] + [ '{:16.8g}' . format ( _ ) for _ in params ] ) )
return '\n' . join ( lines )


signature:
def subset ( self , * args ) :
    """Subset only some of the columns of the DataFrame .
 : param args : list of column names of the object that should be subsetted
 : type args : tuple
 : return : returns DataFrame with only the columns you selected
 : rtype : DataFrame"""

implementation:
args = list ( args )
args . extend ( [ x for x in self . __grouping . grouping_colnames if x not in args ] )
return GroupedDataFrame ( self . __grouping . ungroup ( ) . subset ( * args ) , * self . __grouping . grouping_colnames )


signature:
def modify ( self , clazz , new_col , * args ) :
    """Modify some columns ( i . e . apply a function )
 and add the result to the table .
 : param clazz : name of a class that extends class Callable
 : type clazz : class
 : param new _ col : name of the new column
 : type new _ col : str
 : param args : list of column names of the object that
 function should be applied to
 : type args : tuple
 : return : returns a new GroupedDataFrame object with the modified
 values , i . e . the new column of values
 : rtype : GroupedDataFrame"""

implementation:
if is_callable ( clazz ) and not is_none ( new_col ) and has_elements ( * args ) and is_disjoint ( self . __grouping . grouping_colnames , args , __DISJOINT_SETS_ERROR__ ) :
    return self . __do_modify ( clazz , new_col , * args )


signature:
def aggregate ( self , clazz , new_col , * args ) :
    """Aggregate the rows of each group into a single value .
 : param clazz : name of a class that extends class Callable
 : type clazz : class
 : param new _ col : name of the new column
 : type new _ col : str
 : param args : list of column names of the object that
 function should be applied to
 : type args : varargs
 : return : returns a new dataframe object with the aggregated value
 : rtype : DataFrame"""

implementation:
if is_callable ( clazz ) and not is_none ( new_col ) and has_elements ( * args ) and is_disjoint ( self . __grouping . grouping_colnames , args , __DISJOINT_SETS_ERROR__ ) :
    return self . __do_aggregate ( clazz , new_col , * args )


signature:
def reader ( ltsvfile , labels = None ) :
    """Make LTSV Reader for reading selected labels .
 : param ltsvfile : iterable of lines .
 : param labels : sequence of labels . ( optional )
 : return : generator of record in [ [ label , value ] , . . . ] form ."""

implementation:
label_pattern = re . compile ( r"^[0-9A-Za-z_.-]+:" )
if labels is not None :
    prefixes = tuple ( L + ':' for L in labels if label_pattern . match ( L + ':' ) )
    for record in ltsvfile :
        record = record . rstrip ( '\r\n' )
        yield [ x . split ( ':' , 1 ) for x in record . split ( '\t' ) if x . startswith ( prefixes ) ]
    return
for record in ltsvfile :
    record = record . rstrip ( '\r\n' )
    yield [ x . split ( ':' , 1 ) for x in record . split ( '\t' ) if label_pattern . match ( x ) ]


signature:
def DictReader ( ltsvfile , labels = None , dict_type = dict ) :
    """Make LTSV Reader for reading selected labels .
 : param ltsvfile : iterable of lines .
 : param labels : sequence of labels .
 : return : generator of record in { label : value , . . . } form ."""

implementation:
for rec in reader ( ltsvfile , labels ) :
    yield dict_type ( rec )


signature:
def is_disjoint ( set1 , set2 , warn ) :
    """Checks if elements of set2 are in set1.
 : param set1 : a set of values
 : param set2 : a set of values
 : param warn : the error message that should be thrown
 when the sets are NOT disjoint
 : return : returns true no elements of set2 are in set1"""

implementation:
for elem in set2 :
    if elem in set1 :
        raise ValueError ( warn )
return True


signature:
def contains_all ( set1 , set2 , warn ) :
    """Checks if all elements from set2 are in set1.
 : param set1 : a set of values
 : param set2 : a set of values
 : param warn : the error message that should be thrown
 when the sets are not containd
 : return : returns true if all values of set2 are in set1"""

implementation:
for elem in set2 :
    if elem not in set1 :
        raise ValueError ( warn )
return True


signature:
def to_XML ( self ) :
    """Serialize object back to XML string .
 Returns :
 str : String which should be same as original input , if everything works as expected ."""

implementation:
marcxml_template = """<record xmlns="http://www.loc.gov/MARC21/slim/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.loc.gov/MARC21/slim
http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd">
$LEADER
$CONTROL_FIELDS
$DATA_FIELDS
</record>
"""
oai_template = """<record>
<metadata>
<oai_marc>
$LEADER$CONTROL_FIELDS
$DATA_FIELDS
</oai_marc>
</metadata>
</record>
"""
# serialize leader , if it is present and record is marc xml
leader = self . leader if self . leader is not None else ""
if leader : # print only visible leaders
    leader = "<leader>" + leader + "</leader>"
# discard leader for oai
if self . oai_marc :
    leader = ""
# serialize
xml_template = oai_template if self . oai_marc else marcxml_template
xml_output = Template ( xml_template ) . substitute ( LEADER = leader . strip ( ) , CONTROL_FIELDS = self . _serialize_ctl_fields ( ) . strip ( ) , DATA_FIELDS = self . _serialize_data_fields ( ) . strip ( ) )
return xml_output


signature:
def _parse_string ( self , xml ) :
    """Parse MARC XML document to dicts , which are contained in
 self . controlfields and self . datafields .
 Args :
 xml ( str or HTMLElement ) : input data
 Also detect if this is oai marc format or not ( see elf . oai _ marc ) ."""

implementation:
if not isinstance ( xml , HTMLElement ) :
    xml = dhtmlparser . parseString ( str ( xml ) )
# check if there are any records
record = xml . find ( "record" )
if not record :
    raise ValueError ( "There is no <record> in your MARC XML document!" )
record = record [ 0 ]
self . oai_marc = len ( record . find ( "oai_marc" ) ) > 0
# leader is separate only in marc21
if not self . oai_marc :
    leader = record . find ( "leader" )
    if len ( leader ) >= 1 :
        self . leader = leader [ 0 ] . getContent ( )
# parse body in respect of OAI MARC format possibility
if self . oai_marc :
    self . _parse_control_fields ( record . find ( "fixfield" ) , "id" )
    self . _parse_data_fields ( record . find ( "varfield" ) , "id" , "label" )
else :
    self . _parse_control_fields ( record . find ( "controlfield" ) , "tag" )
    self . _parse_data_fields ( record . find ( "datafield" ) , "tag" , "code" )
# for backward compatibility of MARC XML with OAI
if self . oai_marc and "LDR" in self . controlfields :
    self . leader = self . controlfields [ "LDR" ]


signature:
def _parse_control_fields ( self , fields , tag_id = "tag" ) :
    """Parse control fields .
 Args :
 fields ( list ) : list of HTMLElements
 tag _ id ( str ) : parameter name , which holds the information , about
 field name this is normally " tag " , but in case of
 oai _ marc " id " ."""

implementation:
for field in fields :
    params = field . params
    # skip tags without parameters
    if tag_id not in params :
        continue
    self . controlfields [ params [ tag_id ] ] = field . getContent ( ) . strip ( )


signature:
def _parse_data_fields ( self , fields , tag_id = "tag" , sub_id = "code" ) :
    """Parse data fields .
 Args :
 fields ( list ) : of HTMLElements
 tag _ id ( str ) : parameter name , which holds the information , about
 field name this is normally " tag " , but in case of
 oai _ marc " id "
 sub _ id ( str ) : id of parameter , which holds informations about
 subfield name this is normally " code " but in case of
 oai _ marc " label " """

implementation:
for field in fields :
    params = field . params
    if tag_id not in params :
        continue
    # take care of iX / indX ( indicator ) parameters
    field_repr = OrderedDict ( [ [ self . i1_name , params . get ( self . i1_name , " " ) ] , [ self . i2_name , params . get ( self . i2_name , " " ) ] , ] )
    # process all subfields
    for subfield in field . find ( "subfield" ) :
        if sub_id not in subfield . params :
            continue
        content = MARCSubrecord ( val = subfield . getContent ( ) . strip ( ) , i1 = field_repr [ self . i1_name ] , i2 = field_repr [ self . i2_name ] , other_subfields = field_repr )
        # add or append content to list of other contents
        code = subfield . params [ sub_id ]
        if code in field_repr :
            field_repr [ code ] . append ( content )
        else :
            field_repr [ code ] = [ content ]
    tag = params [ tag_id ]
    if tag in self . datafields :
        self . datafields [ tag ] . append ( field_repr )
    else :
        self . datafields [ tag ] = [ field_repr ]


signature:
def add_ctl_field ( self , name , value ) :
    """Add new control field ` value ` with under ` name ` into control field
 dictionary : attr : ` controlfields ` ."""

implementation:
if len ( name ) != 3 :
    raise ValueError ( "name parameter have to be exactly 3 chars long!" )
self . controlfields [ name ] = value


signature:
def add_data_field ( self , name , i1 , i2 , subfields_dict ) :
    """Add new datafield into : attr : ` datafields ` and take care of OAI MARC
 differencies .
 Args :
 name ( str ) : Name of datafield .
 i1 ( char ) : Value of i1 / ind1 parameter .
 i2 ( char ) : Value of i2 / ind2 parameter .
 subfields _ dict ( dict ) : Dictionary containing subfields ( as list ) .
 ` subfields _ dict ` is expected to be in this format : :
 " field _ id " : [ " subfield data " , ] ,
 " z " : [ " X0456b " ]
 Warning :
 For your own good , use OrderedDict for ` subfields _ dict ` , or
 constructor ' s ` resort ` parameter set to ` ` True ` ` ( it is by
 default ) .
 Warning :
 ` ` field _ id ` ` can be only one character long !"""

implementation:
if i1 not in self . valid_i_chars :
    raise ValueError ( "Invalid i1 parameter '" + i1 + "'!" )
if i2 not in self . valid_i_chars :
    raise ValueError ( "Invalid i2 parameter '" + i2 + "'!" )
if len ( name ) != 3 :
    raise ValueError ( "`name` parameter have to be exactly 3 chars long!" )
if not subfields_dict :
    raise ValueError ( "`subfields_dict` have to contain something!" )
if not isinstance ( subfields_dict , dict ) :
    raise ValueError ( "`subfields_dict` parameter has to be dict instance!" )
# check local keys , convert strings to MARCSubrecord instances
subrecords = [ ]
for key , val in subfields_dict . items ( ) :
    if len ( key ) > 1 :
        raise KeyError ( "`subfields_dict` can be only one character long!" )
    # convert other values to lists
    if not isinstance ( val , list ) :
        val = [ val ]
    subfields = map ( lambda x : MARCSubrecord ( x , i1 , i2 , None ) , val )
    subfields_dict [ key ] = subfields
    subrecords . extend ( subfields )
# save i / ind values
subfields_dict [ self . i1_name ] = i1
subfields_dict [ self . i2_name ] = i2
# append dict , or add new dict into self . datafields
if name in self . datafields :
    self . datafields [ name ] . append ( subfields_dict )
else :
    self . datafields [ name ] = [ subfields_dict ]
# to each subrecord add reference to list of all subfields in this
# datafield
other_subfields = self . datafields [ name ]
for record in subrecords :
    record . other_subfields = other_subfields


signature:
def get_i_name ( self , num , is_oai = None ) :
    """This method is used mainly internally , but it can be handy if you work
 with with raw MARC XML object and not using getters .
 Args :
 num ( int ) : Which indicator you need ( 1/2 ) .
 is _ oai ( bool / None ) : If None , : attr : ` . oai _ marc ` is
 used .
 Returns :
 str : current name of ` ` i1 ` ` / ` ` ind1 ` ` parameter based on : attr : ` oai _ marc ` property ."""

implementation:
if num not in ( 1 , 2 ) :
    raise ValueError ( "`num` parameter have to be 1 or 2!" )
if is_oai is None :
    is_oai = self . oai_marc
i_name = "ind" if not is_oai else "i"
return i_name + str ( num )


signature:
def get_ctl_field ( self , controlfield , alt = None ) :
    """Method wrapper over : attr : ` . controlfields ` dictionary .
 Args :
 controlfield ( str ) : Name of the controlfield .
 alt ( object , default None ) : Alternative value of the ` controlfield `
 when ` controlfield ` couldn ' t be found .
 Returns :
 str : record from given ` controlfield `"""

implementation:
if not alt :
    return self . controlfields [ controlfield ]
return self . controlfields . get ( controlfield , alt )


signature:
def getDataRecords ( self , datafield , subfield , throw_exceptions = True ) :
    """. . deprecated : :
 Use : func : ` get _ subfields ` instead ."""

implementation: return self . get_subfields ( datafield = datafield , subfield = subfield , exception = throw_exceptions )


signature:
def get_subfields ( self , datafield , subfield , i1 = None , i2 = None , exception = False ) :
    """Return content of given ` subfield ` in ` datafield ` .
 Args :
 datafield ( str ) : Section name ( for example " 001 " , " 100 " , " 700 " ) .
 subfield ( str ) : Subfield name ( for example " a " , " 1 " , etc . . ) .
 i1 ( str , default None ) : Optional i1 / ind1 parameter value , which
 will be used for search .
 i2 ( str , default None ) : Optional i2 / ind2 parameter value , which
 will be used for search .
 exception ( bool ) : If ` ` True ` ` , : exc : ` ~ exceptions . KeyError ` is
 raised when method couldn ' t found given ` datafield ` /
 ` subfield ` . If ` ` False ` ` , blank array ` ` [ ] ` ` is returned .
 Returns :
 list : of : class : ` . MARCSubrecord ` .
 Raises :
 KeyError : If the subfield or datafield couldn ' t be found .
 Note :
 MARCSubrecord is practically same thing as string , but has defined
 : meth : ` . MARCSubrecord . i1 ` and : attr : ` . MARCSubrecord . i2 `
 methods .
 You may need to be able to get this , because MARC XML depends on
 i / ind parameters from time to time ( names of authors for example ) ."""

implementation:
if len ( datafield ) != 3 :
    raise ValueError ( "`datafield` parameter have to be exactly 3 chars long!" )
if len ( subfield ) != 1 :
    raise ValueError ( "Bad subfield specification - subfield have to be 1 char long!" )
# if datafield not found , return or raise exception
if datafield not in self . datafields :
    if exception :
        raise KeyError ( datafield + " is not in datafields!" )
    return [ ]
# look for subfield defined by ` subfield ` , ` i1 ` and ` i2 ` parameters
output = [ ]
for datafield in self . datafields [ datafield ] :
    if subfield not in datafield :
        continue
    # records are not returned just like plain string , but like
    # MARCSubrecord , because you will need ind1 / ind2 values
    for sfield in datafield [ subfield ] :
        if i1 and sfield . i1 != i1 :
            continue
        if i2 and sfield . i2 != i2 :
            continue
        output . append ( sfield )
if not output and exception :
    raise KeyError ( subfield + " couldn't be found in subfields!" )
return output


signature:
def timeit_block ( unit = 's' , label = "" ) :
    """测试代码块耗时
 : param unit : 时间单位 , 有 ' s ' , ' m ' , ' h ' 可选 ( seconds , minutes , hours )
 : param label : 代码块标签"""

implementation:
start = time . time ( )
try :
    yield
finally :
    _format ( unit , time . time ( ) - start , label )


signature:
def timeit ( unit = 's' ) :
    """测试函数耗时
 : param unit : 时间单位 , 有 ' s ' , ' m ' , ' h ' 可选 ( seconds , minutes , hours )"""

implementation:
def wrapper ( func ) :
    @ wraps ( func )
    def inner ( * args , ** kwargs ) :
        start = time . time ( )
        _result = func ( * args , ** kwargs )
        _format ( unit , time . time ( ) - start , func . __name__ + '()' )
        return _result
    return inner
return wrapper


signature:
def _print ( stats , limit , label ) :
    """控制输出量"""

implementation:
print ( "TraceMalloc for {}" . format ( label ) )
for index , stat in enumerate ( stats ) :
    if index < limit :
        print ( stat )
    else :
        break


signature:
def memoryit ( group_by = 'lineno' , limit = 10 ) :
    """追踪函数内存消耗情况
 : param group _ by : 统计分组 , 有 ' filename ' , ' lineno ' , ' traceback ' 可选
 : param limit : 限制输出行数"""

implementation:
def wrapper ( func ) :
    @ wraps ( func )
    def inner ( * args , ** kwargs ) :
        tracemalloc . start ( )
        _start = tracemalloc . take_snapshot ( )
        _result = func ( * args , ** kwargs )
        _end = tracemalloc . take_snapshot ( )
        stats = _end . compare_to ( _start , group_by )
        _print ( stats , limit , func . __name__ + '()' )
        return _result
    return inner
return wrapper


signature:
def memoryit_block ( group_by = 'lineno' , limit = 10 , label = 'code block' ) :
    """追踪代码块内存消耗情况
 : param group _ by : 统计分组 , 有 ' filename ' , ' lineno ' , ' traceback ' 可选
 : param limit : 限制输出行数
 : param label : 代码块标签"""

implementation:
tracemalloc . start ( )
_start = tracemalloc . take_snapshot ( )
try :
    yield
finally :
    _end = tracemalloc . take_snapshot ( )
    stats = _end . compare_to ( _start , group_by )
    _print ( stats , limit , label )


signature:
def _get_params ( target , param , dof ) :
    '''Get the given param from each of the DOFs for a joint .'''

implementation: return [ target . getParam ( getattr ( ode , 'Param{}{}' . format ( param , s ) ) ) for s in [ '' , '2' , '3' ] [ : dof ] ]


signature:
def _set_params ( target , param , values , dof ) :
    '''Set the given param for each of the DOFs for a joint .'''

implementation:
if not isinstance ( values , ( list , tuple , np . ndarray ) ) :
    values = [ values ] * dof
assert dof == len ( values )
for s , value in zip ( [ '' , '2' , '3' ] [ : dof ] , values ) :
    target . setParam ( getattr ( ode , 'Param{}{}' . format ( param , s ) ) , value )


signature:
def make_quaternion ( theta , * axis ) :
    '''Given an angle and an axis , create a quaternion .'''

implementation:
x , y , z = axis
r = np . sqrt ( x * x + y * y + z * z )
st = np . sin ( theta / 2. )
ct = np . cos ( theta / 2. )
return [ x * st / r , y * st / r , z * st / r , ct ]


signature:
def center_of_mass ( bodies ) :
    '''Given a set of bodies , compute their center of mass in world coordinates .'''

implementation:
x = np . zeros ( 3. )
t = 0.
for b in bodies :
    m = b . mass
    x += b . body_to_world ( m . c ) * m . mass
    t += m . mass
return x / t


signature:
def state ( self ) :
    '''The state of this body includes :
 - name of the body ( str )
 - position ( 3 - tuple )
 - quaternion ( 4 - tuple )
 - linear velocity ( 3 - tuple )
 - angular velocity ( 3 - tuple )'''

implementation: return BodyState ( self . name , tuple ( self . position ) , tuple ( self . quaternion ) , tuple ( self . linear_velocity ) , tuple ( self . angular_velocity ) )


signature:
def state ( self , state ) :
    '''Set the state of this body .
 Parameters
 state : BodyState tuple
 The desired state of the body .'''

implementation:
assert self . name == state . name , 'state name "{}" != body name "{}"' . format ( state . name , self . name )
self . position = state . position
self . quaternion = state . quaternion
self . linear_velocity = state . linear_velocity
self . angular_velocity = state . angular_velocity


signature:
def rotation ( self , rotation ) :
    '''Set the rotation of this body using a rotation matrix .
 Parameters
 rotation : sequence of 9 floats
 The desired rotation matrix for this body .'''

implementation:
if isinstance ( rotation , np . ndarray ) :
    rotation = rotation . ravel ( )
self . ode_body . setRotation ( tuple ( rotation ) )


signature:
def is_kinematic ( self , is_kinematic ) :
    '''Set the kinematic / dynamic attribute for this body .
 In pagoda , kinematic bodies have infinite mass and do interact with
 other bodies via collisions .
 Parameters
 is _ kinematic : bool
 If True , this body will be set to kinematic . If False , it will be
 set to dynamic .'''

implementation:
if is_kinematic :
    self . ode_body . setKinematic ( )
else :
    self . ode_body . setDynamic ( )


signature:
def body_to_world ( self , position ) :
    '''Convert a body - relative offset to world coordinates .
 Parameters
 position : 3 - tuple of float
 A tuple giving body - relative offsets .
 Returns
 position : 3 - tuple of float
 A tuple giving the world coordinates of the given offset .'''

implementation: return np . array ( self . ode_body . getRelPointPos ( tuple ( position ) ) )


signature:
def world_to_body ( self , position ) :
    '''Convert a point in world coordinates to a body - relative offset .
 Parameters
 position : 3 - tuple of float
 A world coordinates position .
 Returns
 offset : 3 - tuple of float
 A tuple giving the body - relative offset of the given position .'''

implementation: return np . array ( self . ode_body . getPosRelPoint ( tuple ( position ) ) )


signature:
def relative_offset_to_world ( self , offset ) :
    '''Convert a relative body offset to world coordinates .
 Parameters
 offset : 3 - tuple of float
 The offset of the desired point , given as a relative fraction of the
 size of this body . For example , offset ( 0 , 0 , 0 ) is the center of
 the body , while ( 0.5 , - 0.2 , 0.1 ) describes a point halfway from the
 center towards the maximum x - extent of the body , 20 % of the way from
 the center towards the minimum y - extent , and 10 % of the way from the
 center towards the maximum z - extent .
 Returns
 position : 3 - tuple of float
 A position in world coordinates of the given body offset .'''

implementation: return np . array ( self . body_to_world ( offset * self . dimensions / 2 ) )


signature:
def add_force ( self , force , relative = False , position = None , relative_position = None ) :
    '''Add a force to this body .
 Parameters
 force : 3 - tuple of float
 A vector giving the forces along each world or body coordinate axis .
 relative : bool , optional
 If False , the force values are assumed to be given in the world
 coordinate frame . If True , they are assumed to be given in the
 body - relative coordinate frame . Defaults to False .
 position : 3 - tuple of float , optional
 If given , apply the force at this location in world coordinates .
 Defaults to the current position of the body .
 relative _ position : 3 - tuple of float , optional
 If given , apply the force at this relative location on the body . If
 given , this method ignores the ` ` position ` ` parameter .'''

implementation:
b = self . ode_body
if relative_position is not None :
    op = b . addRelForceAtRelPos if relative else b . addForceAtRelPos
    op ( force , relative_position )
elif position is not None :
    op = b . addRelForceAtPos if relative else b . addForceAtPos
    op ( force , position )
else :
    op = b . addRelForce if relative else b . addForce
    op ( force )


signature:
def add_torque ( self , torque , relative = False ) :
    '''Add a torque to this body .
 Parameters
 force : 3 - tuple of float
 A vector giving the torque along each world or body coordinate axis .
 relative : bool , optional
 If False , the torque values are assumed to be given in the world
 coordinate frame . If True , they are assumed to be given in the
 body - relative coordinate frame . Defaults to False .'''

implementation:
op = self . ode_body . addRelTorque if relative else self . ode_body . addTorque
op ( torque )


signature:
def join_to ( self , joint , other_body = None , ** kwargs ) :
    '''Connect this body to another one using a joint .
 This method creates a joint to fasten this body to the other one . See
 : func : ` World . join ` .
 Parameters
 joint : str
 The type of joint to use when connecting these bodies .
 other _ body : : class : ` Body ` or str , optional
 The other body to join with this one . If not given , connects this
 body to the world .'''

implementation: self . world . join ( joint , self , other_body , ** kwargs )


signature:
def connect_to ( self , joint , other_body , offset = ( 0 , 0 , 0 ) , other_offset = ( 0 , 0 , 0 ) , ** kwargs ) :
    '''Move another body next to this one and join them together .
 This method will move the ` ` other _ body ` ` so that the anchor points for
 the joint coincide . It then creates a joint to fasten the two bodies
 together . See : func : ` World . move _ next _ to ` and : func : ` World . join ` .
 Parameters
 joint : str
 The type of joint to use when connecting these bodies .
 other _ body : : class : ` Body ` or str
 The other body to join with this one .
 offset : 3 - tuple of float , optional
 The body - relative offset where the anchor for the joint should be
 placed . Defaults to ( 0 , 0 , 0 ) . See : func : ` World . move _ next _ to ` for a
 description of how offsets are specified .
 other _ offset : 3 - tuple of float , optional
 The offset on the second body where the joint anchor should be
 placed . Defaults to ( 0 , 0 , 0 ) . Like ` ` offset ` ` , this is given as an
 offset relative to the size and shape of ` ` other _ body ` ` .'''

implementation:
anchor = self . world . move_next_to ( self , other_body , offset , other_offset )
self . world . join ( joint , self , other_body , anchor = anchor , ** kwargs )


signature:
def positions ( self ) :
    '''List of positions for linear degrees of freedom .'''

implementation: return [ self . ode_obj . getPosition ( i ) for i in range ( self . LDOF ) ]


signature:
def position_rates ( self ) :
    '''List of position rates for linear degrees of freedom .'''

implementation: return [ self . ode_obj . getPositionRate ( i ) for i in range ( self . LDOF ) ]


signature:
def angles ( self ) :
    '''List of angles for rotational degrees of freedom .'''

implementation: return [ self . ode_obj . getAngle ( i ) for i in range ( self . ADOF ) ]


signature:
def angle_rates ( self ) :
    '''List of angle rates for rotational degrees of freedom .'''

implementation: return [ self . ode_obj . getAngleRate ( i ) for i in range ( self . ADOF ) ]


signature:
def axes ( self ) :
    '''List of axes for this object ' s degrees of freedom .'''

implementation: return [ np . array ( self . ode_obj . getAxis ( i ) ) for i in range ( self . ADOF or self . LDOF ) ]


signature:
def axes ( self , axes ) :
    '''Set the axes for this object ' s degrees of freedom .
 Parameters
 axes : list of axes specifications
 A list of axis values to set . This list must have the same number of
 elements as the degrees of freedom of the underlying ODE object .
 Each element can be
 ( a ) None , which has no effect on the corresponding axis , or
 ( b ) three floats specifying the axis to set .'''

implementation:
assert self . ADOF == len ( axes ) or self . LDOF == len ( axes )
for i , axis in enumerate ( axes ) :
    if axis is not None :
        self . ode_obj . setAxis ( i , 0 , axis )


signature:
def lo_stops ( self , lo_stops ) :
    '''Set the lo stop values for this object ' s degrees of freedom .
 Parameters
 lo _ stops : float or sequence of float
 A lo stop value to set on all degrees of freedom , or a list
 containing one such value for each degree of freedom . For rotational
 degrees of freedom , these values must be in radians .'''

implementation: _set_params ( self . ode_obj , 'LoStop' , lo_stops , self . ADOF + self . LDOF )


signature:
def hi_stops ( self , hi_stops ) :
    '''Set the hi stop values for this object ' s degrees of freedom .
 Parameters
 hi _ stops : float or sequence of float
 A hi stop value to set on all degrees of freedom , or a list
 containing one such value for each degree of freedom . For rotational
 degrees of freedom , these values must be in radians .'''

implementation: _set_params ( self . ode_obj , 'HiStop' , hi_stops , self . ADOF + self . LDOF )


signature:
def velocities ( self , velocities ) :
    '''Set the target velocities for this object ' s degrees of freedom .
 Parameters
 velocities : float or sequence of float
 A target velocity value to set on all degrees of freedom , or a list
 containing one such value for each degree of freedom . For rotational
 degrees of freedom , these values must be in radians / second .'''

implementation: _set_params ( self . ode_obj , 'Vel' , velocities , self . ADOF + self . LDOF )


signature:
def max_forces ( self , max_forces ) :
    '''Set the maximum forces for this object ' s degrees of freedom .
 Parameters
 max _ forces : float or sequence of float
 A maximum force value to set on all degrees of freedom , or a list
 containing one such value for each degree of freedom .'''

implementation: _set_params ( self . ode_obj , 'FMax' , max_forces , self . ADOF + self . LDOF )


signature:
def erps ( self , erps ) :
    '''Set the ERP values for this object ' s degrees of freedom .
 Parameters
 erps : float or sequence of float
 An ERP value to set on all degrees of freedom , or a list
 containing one such value for each degree of freedom .'''

implementation: _set_params ( self . ode_obj , 'ERP' , erps , self . ADOF + self . LDOF )


signature:
def cfms ( self , cfms ) :
    '''Set the CFM values for this object ' s degrees of freedom .
 Parameters
 cfms : float or sequence of float
 A CFM value to set on all degrees of freedom , or a list
 containing one such value for each degree of freedom .'''

implementation: _set_params ( self . ode_obj , 'CFM' , cfms , self . ADOF + self . LDOF )


signature:
def stop_cfms ( self , stop_cfms ) :
    '''Set the CFM values for this object ' s DOF limits .
 Parameters
 stop _ cfms : float or sequence of float
 A CFM value to set on all degrees of freedom limits , or a list
 containing one such value for each degree of freedom limit .'''

implementation: _set_params ( self . ode_obj , 'StopCFM' , stop_cfms , self . ADOF + self . LDOF )


signature:
def stop_erps ( self , stop_erps ) :
    '''Set the ERP values for this object ' s DOF limits .
 Parameters
 stop _ erps : float or sequence of float
 An ERP value to set on all degrees of freedom limits , or a list
 containing one such value for each degree of freedom limit .'''

implementation: _set_params ( self . ode_obj , 'StopERP' , stop_erps , self . ADOF + self . LDOF )


signature:
def axes ( self , axes ) :
    '''Set the axes for this object ' s degrees of freedom .
 Parameters
 axes : list of axis parameters
 A list of axis values to set . This list must have the same number of
 elements as the degrees of freedom of the underlying ODE object .
 Each element can be
 ( a ) None , which has no effect on the corresponding axis , or
 ( b ) three floats specifying the axis to set , or
 ( c ) a dictionary with an " axis " key specifying the axis to set and
 an optional " rel " key ( defaults to 0 ) specifying the relative
 body to set the axis on .'''

implementation:
assert len ( axes ) == self . ADOF
for i , ax in enumerate ( axes ) :
    if ax is None :
        continue
    if not isinstance ( ax , dict ) :
        ax = dict ( axis = ax )
    self . ode_obj . setAxis ( i , ax . get ( 'rel' , 0 ) , ax [ 'axis' ] )


signature:
def axes ( self , axes ) :
    '''Set the linear axis of displacement for this joint .
 Parameters
 axes : list containing one 3 - tuple of floats
 A list of the axes for this joint . For a slider joint , which has one
 degree of freedom , this must contain one 3 - tuple specifying the X ,
 Y , and Z axis for the joint .'''

implementation:
self . lmotor . axes = [ axes [ 0 ] ]
self . ode_obj . setAxis ( tuple ( axes [ 0 ] ) )


signature:
def axes ( self , axes ) :
    '''Set the angular axis of rotation for this joint .
 Parameters
 axes : list containing one 3 - tuple of floats
 A list of the axes for this joint . For a hinge joint , which has one
 degree of freedom , this must contain one 3 - tuple specifying the X ,
 Y , and Z axis for the joint .'''

implementation:
self . amotor . axes = [ axes [ 0 ] ]
self . ode_obj . setAxis ( tuple ( axes [ 0 ] ) )


signature:
def axes ( self ) :
    '''A list of axes of rotation for this joint .'''

implementation: return [ np . array ( self . ode_obj . getAxis1 ( ) ) , np . array ( self . ode_obj . getAxis2 ( ) ) ]


signature:
def create_body ( self , shape , name = None , ** kwargs ) :
    '''Create a new body .
 Parameters
 shape : str
 The " shape " of the body to be created . This should name a type of
 body object , e . g . , " box " or " cap " .
 name : str , optional
 The name to use for this body . If not given , a default name will be
 constructed of the form " { shape } { # of objects in the world } " .
 Returns
 body : : class : ` Body `
 The created body object .'''

implementation:
shape = shape . lower ( )
if name is None :
    for i in range ( 1 + len ( self . _bodies ) ) :
        name = '{}{}' . format ( shape , i )
        if name not in self . _bodies :
            break
self . _bodies [ name ] = Body . build ( shape , name , self , ** kwargs )
return self . _bodies [ name ]


signature:
def join ( self , shape , body_a , body_b = None , name = None , ** kwargs ) :
    '''Create a new joint that connects two bodies together .
 Parameters
 shape : str
 The " shape " of the joint to use for joining together two bodies .
 This should name a type of joint , such as " ball " or " piston " .
 body _ a : str or : class : ` Body `
 The first body to join together with this joint . If a string is
 given , it will be used as the name of a body to look up in the
 world .
 body _ b : str or : class : ` Body ` , optional
 If given , identifies the second body to join together with
 ` ` body _ a ` ` . If not given , ` ` body _ a ` ` is joined to the world .
 name : str , optional
 If given , use this name for the created joint . If not given , a name
 will be constructed of the form
 " { body _ a . name } ^ { shape } ^ { body _ b . name } " .
 Returns
 joint : : class : ` Joint `
 The joint object that was created .'''

implementation:
ba = self . get_body ( body_a )
bb = self . get_body ( body_b )
shape = shape . lower ( )
if name is None :
    name = '{}^{}^{}' . format ( ba . name , shape , bb . name if bb else '' )
self . _joints [ name ] = Joint . build ( shape , name , self , body_a = ba , body_b = bb , ** kwargs )
return self . _joints [ name ]


signature:
def move_next_to ( self , body_a , body_b , offset_a , offset_b ) :
    '''Move one body to be near another one .
 After moving , the location described by ` ` offset _ a ` ` on ` ` body _ a ` ` will
 be coincident with the location described by ` ` offset _ b ` ` on ` ` body _ b ` ` .
 Parameters
 body _ a : str or : class : ` Body `
 The body to use as a reference for moving the other body . If this is
 a string , it is treated as the name of a body to look up in the
 world .
 body _ b : str or : class : ` Body `
 The body to move next to ` ` body _ a ` ` . If this is a string , it is
 treated as the name of a body to look up in the world .
 offset _ a : 3 - tuple of float
 The offset of the anchor point , given as a relative fraction of the
 size of ` ` body _ a ` ` . See : func : ` Body . relative _ offset _ to _ world ` .
 offset _ b : 3 - tuple of float
 The offset of the anchor point , given as a relative fraction of the
 size of ` ` body _ b ` ` .
 Returns
 anchor : 3 - tuple of float
 The location of the shared point , which is often useful to use as a
 joint anchor .'''

implementation:
ba = self . get_body ( body_a )
bb = self . get_body ( body_b )
if ba is None :
    return bb . relative_offset_to_world ( offset_b )
if bb is None :
    return ba . relative_offset_to_world ( offset_a )
anchor = ba . relative_offset_to_world ( offset_a )
offset = bb . relative_offset_to_world ( offset_b )
bb . position = bb . position + anchor - offset
return anchor


signature:
def set_body_states ( self , states ) :
    '''Set the states of some bodies in the world .
 Parameters
 states : sequence of states
 A complete state tuple for one or more bodies in the world . See
 : func : ` get _ body _ states ` .'''

implementation:
for state in states :
    self . get_body ( state . name ) . state = state


signature:
def step ( self , substeps = 2 ) :
    '''Step the world forward by one frame .
 Parameters
 substeps : int , optional
 Split the step into this many sub - steps . This helps to prevent the
 time delta for an update from being too large .'''

implementation:
self . frame_no += 1
dt = self . dt / substeps
for _ in range ( substeps ) :
    self . ode_contactgroup . empty ( )
    self . ode_space . collide ( None , self . on_collision )
    self . ode_world . step ( dt )


signature:
def on_key_press ( self , key , modifiers , keymap ) :
    '''Handle an otherwise unhandled keypress event ( from a GUI ) .'''

implementation:
if key == keymap . ENTER :
    self . reset ( )
    return True


signature:
def are_connected ( self , body_a , body_b ) :
    '''Determine whether the given bodies are currently connected .
 Parameters
 body _ a : str or : class : ` Body `
 One body to test for connectedness . If this is a string , it is
 treated as the name of a body to look up .
 body _ b : str or : class : ` Body `
 One body to test for connectedness . If this is a string , it is
 treated as the name of a body to look up .
 Returns
 connected : bool
 Return True iff the two bodies are connected .'''

implementation: return bool ( ode . areConnected ( self . get_body ( body_a ) . ode_body , self . get_body ( body_b ) . ode_body ) )


signature:
def on_collision ( self , args , geom_a , geom_b ) :
    '''Callback function for the collide ( ) method .
 Parameters
 args : None
 Arguments passed when the callback was registered . Not used .
 geom _ a : ODE geometry
 The geometry object of one of the bodies that has collided .
 geom _ b : ODE geometry
 The geometry object of one of the bodies that has collided .'''

implementation:
body_a = geom_a . getBody ( )
body_b = geom_b . getBody ( )
if ode . areConnected ( body_a , body_b ) or ( body_a and body_a . isKinematic ( ) ) or ( body_b and body_b . isKinematic ( ) ) :
    return
for c in ode . collide ( geom_a , geom_b ) :
    c . setBounce ( self . elasticity )
    c . setMu ( self . friction )
    ode . ContactJoint ( self . ode_world , self . ode_contactgroup , c ) . attach ( geom_a . getBody ( ) , geom_b . getBody ( ) )


signature:
def record_iterator ( xml ) :
    """Iterate over all ` ` < record > ` ` tags in ` xml ` .
 Args :
 xml ( str / file ) : Input string with XML . UTF - 8 is prefered encoding ,
 unicode should be ok .
 Yields :
 MARCXMLRecord : For each corresponding ` ` < record > ` ` ."""

implementation:
# handle file - like objects
if hasattr ( xml , "read" ) :
    xml = xml . read ( )
dom = None
try :
    dom = dhtmlparser . parseString ( xml )
except UnicodeError :
    dom = dhtmlparser . parseString ( xml . encode ( "utf-8" ) )
for record_xml in dom . findB ( "record" ) :
    yield MARCXMLRecord ( record_xml )


signature:
def profileit ( field = 'cumulative' ) :
    """测试函数运行消耗情况
 : param field : 输出内容排序方式 。
 可选参数为 " stdname " , " calls " , " time " , " cumulative " """

implementation:
def wrapper ( func ) :
    @ wraps ( func )
    def inner ( * args , ** kwargs ) :
        pro = Profile ( )
        pro . runcall ( func , * args , ** kwargs )
        stats = Stats ( pro )
        stats . strip_dirs ( )
        stats . sort_stats ( field )
        print ( "Profile for {}()" . format ( func . __name__ ) )
        stats . print_stats ( )
        stats . print_callers ( )
    return inner
return wrapper


signature:
def parse ( source , world , jointgroup = None , density = 1000 , color = None ) :
    '''Load and parse a source file .
 Parameters
 source : file
 A file - like object that contains text information describing bodies and
 joints to add to the world .
 world : : class : ` pagoda . physics . World `
 The world to add objects and joints to .
 jointgroup : ode . JointGroup , optional
 If provided , add all joints from this parse to the given group . The
 default behavior adds joints to the world without an explicit group .
 density : float , optional
 Default density for bodies . This is overridden if the source provides a
 density or mass value for a given body .
 color : tuple of floats , optional
 Default color for bodies from this source . Defaults to None , which does
 not assign a color to parsed bodies .'''

implementation:
visitor = Visitor ( world , jointgroup , density , color )
visitor . parse ( re . sub ( r'#.*' , ' ' , source . read ( ) ) )
return visitor


signature:
def parse_asf ( source , world , jointgroup = None , density = 1000 , color = None ) :
    '''Load and parse a source file .
 Parameters
 source : file
 A file - like object that contains text information describing bodies and
 joints to add to the world .
 world : : class : ` pagoda . physics . World `
 The world to add objects and joints to .
 jointgroup : ode . JointGroup , optional
 If provided , add all joints from this parse to the given group . The
 default behavior adds joints to the world without an explicit group .
 density : float , optional
 Default density for bodies . This is overridden if the source provides a
 density or mass value for a given body .
 color : tuple of floats , optional
 Default color for bodies from this source . Defaults to None , which does
 not assign a color to parsed bodies .'''

implementation:
visitor = AsfVisitor ( world , jointgroup , density , color )
visitor . parse ( re . sub ( r'#.*' , ' ' , source . read ( ) ) )
return visitor


signature:
def parse_amc ( source ) :
    '''Parse an AMC motion capture data file .
 Parameters
 source : file
 A file - like object that contains AMC motion capture text .
 Yields
 frame : dict
 Yields a series of motion capture frames . Each frame is a dictionary
 that maps a bone name to a list of the DOF configurations for that bone .'''

implementation:
lines = 0
frames = 1
frame = { }
degrees = False
for line in source :
    lines += 1
    line = line . split ( '#' ) [ 0 ] . strip ( )
    if not line :
        continue
    if line . startswith ( ':' ) :
        if line . lower ( ) . startswith ( ':deg' ) :
            degrees = True
        continue
    if line . isdigit ( ) :
        if int ( line ) != frames :
            raise RuntimeError ( 'frame mismatch on line {}: ' 'produced {} but file claims {}' . format ( lines , frames , line ) )
        yield frame
        frames += 1
        frame = { }
        continue
    fields = line . split ( )
    frame [ fields [ 0 ] ] = list ( map ( float , fields [ 1 : ] ) )


signature:
def create_bodies ( self , translate = ( 0 , 1 , 0 ) , size = 0.1 ) :
    '''Traverse the bone hierarchy and create physics bodies .'''

implementation:
stack = [ ( 'root' , 0 , self . root [ 'position' ] + translate ) ]
while stack :
    name , depth , end = stack . pop ( )
    for child in self . hierarchy . get ( name , ( ) ) :
        stack . append ( ( child , depth + 1 , end + self . bones [ child ] . end ) )
    if name not in self . bones :
        continue
    bone = self . bones [ name ]
    body = self . world . create_body ( 'box' , name = bone . name , density = self . density , lengths = ( size , size , bone . length ) )
    body . color = self . color
    # move the center of the body to the halfway point between
    # the parent ( joint ) and child ( joint ) .
    x , y , z = end - bone . direction * bone . length / 2
    # swizzle y and z - - asf uses y as up , but we use z as up .
    body . position = x , z , y
    # compute an orthonormal ( rotation ) matrix using the ground and
    # the body . this is mind - bending but seems to work .
    u = bone . direction
    v = np . cross ( u , [ 0 , 1 , 0 ] )
    l = np . linalg . norm ( v )
    if l > 0 :
        v /= l
        rot = np . vstack ( [ np . cross ( u , v ) , v , u ] ) . T
        swizzle = [ [ 1 , 0 , 0 ] , [ 0 , 0 , 1 ] , [ 0 , - 1 , 0 ] ]
        body . rotation = np . dot ( swizzle , rot )
    self . bodies . append ( body )


signature:
def create_joints ( self ) :
    '''Traverse the bone hierarchy and create physics joints .'''

implementation:
stack = [ 'root' ]
while stack :
    parent = stack . pop ( )
    for child in self . hierarchy . get ( parent , ( ) ) :
        stack . append ( child )
    if parent not in self . bones :
        continue
    bone = self . bones [ parent ]
    body = [ b for b in self . bodies if b . name == parent ] [ 0 ]
    for child in self . hierarchy . get ( parent , ( ) ) :
        child_bone = self . bones [ child ]
        child_body = [ b for b in self . bodies if b . name == child ] [ 0 ]
        shape = ( '' , 'hinge' , 'universal' , 'ball' ) [ len ( child_bone . dof ) ]
        self . joints . append ( self . world . join ( shape , body , child_body ) )


signature:
def format_cookies ( path ) :
    """将 cookie 字符串转化为字典
 : param path : cookies 文件路径
 : return : cookies 字典"""

implementation:
with open ( path , 'r' ) as f :
    _cookies = { }
    for row in f . read ( ) . split ( ';' ) :
        k , v = row . strip ( ) . split ( '=' , 1 )
        _cookies [ k ] = v
    return _cookies


signature:
def delete_empty_dir ( directory ) :
    """删除空目录
 : param directory : 目录路径"""

implementation:
if os . path . exists ( directory ) :
    if os . path . isdir ( directory ) :
        for d in os . listdir ( directory ) :
            path = os . path . join ( directory , d )
            if os . path . isdir ( path ) :
                delete_empty_dir ( path )
    if not os . listdir ( directory ) :
        os . rmdir ( directory )
        print ( "Remove the empty directory: " + directory )
else :
    print ( "The directory is not exist!" )


signature:
def _parse_corporations ( self , datafield , subfield , roles = [ "any" ] ) :
    """Parse informations about corporations from given field identified
 by ` datafield ` parameter .
 Args :
 datafield ( str ) : MARC field ID ( " ` ` 110 ` ` " , " ` ` 610 ` ` " , etc . . )
 subfield ( str ) : MARC subfield ID with name , which is typically
 stored in " ` ` a ` ` " subfield .
 roles ( str ) : specify which roles you need . Set to ` ` [ " any " ] ` ` for
 any role , ` ` [ " dst " ] ` ` for distributors , etc . . For
 details , see
 http : / / www . loc . gov / marc / relators / relaterm . html
 Returns :
 list : : class : ` Corporation ` objects ."""

implementation:
if len ( datafield ) != 3 :
    raise ValueError ( "datafield parameter have to be exactly 3 chars long!" )
if len ( subfield ) != 1 :
    raise ValueError ( "Bad subfield specification - subield have to be 3 chars long!" )
parsed_corporations = [ ]
for corporation in self . get_subfields ( datafield , subfield ) :
    other_subfields = corporation . other_subfields
    # check if corporation have at least one of the roles specified in
    # ' roles ' parameter of function
    if "4" in other_subfields and roles != [ "any" ] :
        corp_roles = other_subfields [ "4" ]
        # list of role parameters
        relevant = any ( map ( lambda role : role in roles , corp_roles ) )
        # skip non - relevant corporations
        if not relevant :
            continue
    name = ""
    place = ""
    date = ""
    name = corporation
    if "c" in other_subfields :
        place = "," . join ( other_subfields [ "c" ] )
    if "d" in other_subfields :
        date = "," . join ( other_subfields [ "d" ] )
    parsed_corporations . append ( Corporation ( name , place , date ) )
return parsed_corporations


signature:
def _parse_persons ( self , datafield , subfield , roles = [ "aut" ] ) :
    """Parse persons from given datafield .
 Args :
 datafield ( str ) : code of datafield ( " 010 " , " 730 " , etc . . )
 subfield ( char ) : code of subfield ( " a " , " z " , " 4 " , etc . . )
 role ( list of str ) : set to [ " any " ] for any role , [ " aut " ] for
 authors , etc . . For details see
 http : / / www . loc . gov / marc / relators / relaterm . html
 Main records for persons are : " 100 " , " 600 " and " 700 " , subrecords " c " .
 Returns :
 list : Person objects ."""

implementation:
# parse authors
parsed_persons = [ ]
raw_persons = self . get_subfields ( datafield , subfield )
for person in raw_persons : # check if person have at least one of the roles specified in
# ' roles ' parameter of function
    other_subfields = person . other_subfields
    if "4" in other_subfields and roles != [ "any" ] :
        person_roles = other_subfields [ "4" ]
        # list of role parameters
        relevant = any ( map ( lambda role : role in roles , person_roles ) )
        # skip non - relevant persons
        if not relevant :
            continue
    # result of . strip ( ) is string , so ind1/2 in MARCSubrecord are lost
    ind1 = person . i1
    ind2 = person . i2
    person = person . strip ( )
    name = ""
    second_name = ""
    surname = ""
    title = ""
    # here it gets nasty - there is lot of options in ind1 / ind2
    # parameters
    if ind1 == "1" and ind2 == " " :
        if "," in person :
            surname , name = person . split ( "," , 1 )
        elif " " in person :
            surname , name = person . split ( " " , 1 )
        else :
            surname = person
        if "c" in other_subfields :
            title = "," . join ( other_subfields [ "c" ] )
    elif ind1 == "0" and ind2 == " " :
        name = person . strip ( )
        if "b" in other_subfields :
            second_name = "," . join ( other_subfields [ "b" ] )
        if "c" in other_subfields :
            surname = "," . join ( other_subfields [ "c" ] )
    elif ind1 == "1" and ind2 == "0" or ind1 == "0" and ind2 == "0" :
        name = person . strip ( )
        if "c" in other_subfields :
            title = "," . join ( other_subfields [ "c" ] )
    parsed_persons . append ( Person ( name . strip ( ) , second_name . strip ( ) , surname . strip ( ) , title . strip ( ) ) )
return parsed_persons


signature:
def get_subname ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` subname ` record is not found .
 Returns :
 str : Subname of the book or ` undefined ` if ` subname ` is not found ."""

implementation: return _undefined_pattern ( "" . join ( self . get_subfields ( "245" , "b" ) ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_price ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` price ` record is not found .
 Returns :
 str : Price of the book ( with currency ) or ` undefined ` if ` price ` is not found ."""

implementation: return _undefined_pattern ( "" . join ( self . get_subfields ( "020" , "c" ) ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_part ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` part ` record is not found .
 Returns :
 str : Which part of the book series is this record or ` undefined ` if ` part ` is not found ."""

implementation: return _undefined_pattern ( "" . join ( self . get_subfields ( "245" , "p" ) ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_part_name ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` part _ name ` record is not found .
 Returns :
 str : Name of the part of the series . or ` undefined ` if ` part _ name ` is not found ."""

implementation: return _undefined_pattern ( "" . join ( self . get_subfields ( "245" , "n" ) ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_publisher ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` publisher ` record is not found .
 Returns :
 str : Name of the publisher ( " ` ` Grada ` ` " for example ) or ` undefined ` if ` publisher ` is not found ."""

implementation:
publishers = set ( [ remove_hairs_fn ( publisher ) for publisher in self [ "260b  " ] + self [ "264b" ] ] )
return _undefined_pattern ( ", " . join ( publishers ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_pub_order ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` pub _ order ` record is not found .
 Returns :
 str : Information about order in which was the book published or ` undefined ` if ` pub _ order ` is not found ."""

implementation: return _undefined_pattern ( "" . join ( self . get_subfields ( "901" , "f" ) ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_pub_place ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` pub _ place ` record is not found .
 Returns :
 str : Name of city / country where the book was published or ` undefined ` if ` pub _ place ` is not found ."""

implementation:
places = set ( [ remove_hairs_fn ( place ) for place in self [ "260a  " ] + self [ "264a" ] ] )
return _undefined_pattern ( ", " . join ( places ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_format ( self , undefined = "" ) :
    """Args :
 undefined ( optional ) : Argument , which will be returned if the
 ` format ` record is not found .
 Returns :
 str : Dimensions of the book ( ' ` ` 23 cm ` ` ' for example ) or
 ` undefined ` if ` format ` is not found ."""

implementation: return _undefined_pattern ( "" . join ( self . get_subfields ( "300" , "c" ) ) , lambda x : x . strip ( ) == "" , undefined )


signature:
def get_authors ( self ) :
    """Returns :
 list : Authors represented as : class : ` . Person ` objects ."""

implementation:
authors = self . _parse_persons ( "100" , "a" )
authors += self . _parse_persons ( "600" , "a" )
authors += self . _parse_persons ( "700" , "a" )
authors += self . _parse_persons ( "800" , "a" )
return authors


signature:
def get_corporations ( self , roles = [ "dst" ] ) :
    """Args :
 roles ( list , optional ) : Specify which types of corporations you
 need . Set to ` ` [ " any " ] ` ` for any role , ` ` [ " dst " ] ` ` for
 distributors , etc . .
 Note :
 See http : / / www . loc . gov / marc / relators / relaterm . html for details .
 Returns :
 list : : class : ` . Corporation ` objects specified by roles parameter ."""

implementation:
corporations = self . _parse_corporations ( "110" , "a" , roles )
corporations += self . _parse_corporations ( "610" , "a" , roles )
corporations += self . _parse_corporations ( "710" , "a" , roles )
corporations += self . _parse_corporations ( "810" , "a" , roles )
return corporations


signature:
def get_ISBNs ( self ) :
    """Get list of VALID ISBN .
 Returns :
 list : List with * valid * ISBN strings ."""

implementation:
invalid_isbns = set ( self . get_invalid_ISBNs ( ) )
valid_isbns = [ self . _clean_isbn ( isbn ) for isbn in self [ "020a" ] if self . _clean_isbn ( isbn ) not in invalid_isbns ]
if valid_isbns :
    return valid_isbns
# this is used sometimes in czech national library
return [ self . _clean_isbn ( isbn ) for isbn in self [ "901i" ] ]


signature:
def get_ISSNs ( self ) :
    """Get list of VALID ISSNs ( ` ` 022a ` ` ) .
 Returns :
 list : List with * valid * ISSN strings ."""

implementation:
invalid_issns = set ( self . get_invalid_ISSNs ( ) )
return [ self . _clean_isbn ( issn ) for issn in self [ "022a" ] if self . _clean_isbn ( issn ) not in invalid_issns ]


signature:
def _filter_binding ( self , binding ) :
    """Filter binding from ISBN record . In MARC XML / OAI , the binding
 information is stored in same subrecord as ISBN .
 Example :
 ` ` < subfield code = " a " > 80-251-0225-4 ( brož . ) : < / subfield > ` ` - >
 ` ` brož . ` ` ."""

implementation:
binding = binding . strip ( ) . split ( " " , 1 ) [ - 1 ]
# isolate bind . from ISBN
binding = remove_hairs_fn ( binding )
# remove special chars from binding
return binding . split ( ":" ) [ - 1 ] . strip ( )


signature:
def get_urls ( self ) :
    """Content of field ` ` 856u42 ` ` . Typically URL pointing to producers
 homepage .
 Returns :
 list : List of URLs defined by producer ."""

implementation:
urls = self . get_subfields ( "856" , "u" , i1 = "4" , i2 = "2" )
return map ( lambda x : x . replace ( "&" , "&" ) , urls )


signature:
def get_internal_urls ( self ) :
    """URL ' s , which may point to edeposit , aleph , kramerius and so on .
 Fields ` ` 856u40 ` ` , ` ` 998a ` ` and ` ` URLu ` ` .
 Returns :
 list : List of internal URLs ."""

implementation:
internal_urls = self . get_subfields ( "856" , "u" , i1 = "4" , i2 = "0" )
internal_urls . extend ( self . get_subfields ( "998" , "a" ) )
internal_urls . extend ( self . get_subfields ( "URL" , "u" ) )
return map ( lambda x : x . replace ( "&" , "&" ) , internal_urls )


signature:
def get_pub_type ( self ) :
    """Returns :
 PublicationType : : class : ` . PublicationType ` enum * * value * * ."""

implementation:
INFO_CHAR_INDEX = 6
SECOND_INFO_CHAR_I = 18
if not len ( self . leader ) >= INFO_CHAR_INDEX + 1 :
    return PublicationType . monographic
if self . controlfields . get ( "FMT" ) == "SE" :
    return PublicationType . continuing
info_char = self . leader [ INFO_CHAR_INDEX ]
multipart_n = self . get_subfields ( "245" , "n" , exception = False )
multipart_p = self . get_subfields ( "245" , "p" , exception = False )
if info_char in "acd" :
    return PublicationType . monographic
elif info_char in "bis" :
    return PublicationType . continuing
elif info_char == "m" and ( multipart_n or multipart_p ) :
    return PublicationType . multipart_monograph
elif info_char == "m" and len ( self . leader ) >= SECOND_INFO_CHAR_I + 1 :
    if self . leader [ SECOND_INFO_CHAR_I ] == "a" :
        return PublicationType . multipart_monograph
    elif self . leader [ SECOND_INFO_CHAR_I ] == " " :
        return PublicationType . single_unit
return PublicationType . monographic


signature:
def get ( self , item , alt = None ) :
    """Standard dict - like . get ( ) method .
 Args :
 item ( str ) : See : meth : ` . _ _ getitem _ _ ` for details .
 alt ( default None ) : Alternative value , if item is not found .
 Returns :
 obj : ` item ` or ` alt ` , if item is not found ."""

implementation:
try :
    val = self [ item ]
except ValueError :
    return alt
return val if val is not None else alt


signature:
def pid ( kp = 0. , ki = 0. , kd = 0. , smooth = 0.1 ) :
    r'''Create a callable that implements a PID controller .
 A PID controller returns a control signal : math : ` u ( t ) ` given a history of
 error measurements : math : ` e ( 0 ) \ dots e ( t ) ` , using proportional ( P ) , integral
 ( I ) , and derivative ( D ) terms , according to :
 . . math : :
 u ( t ) = kp * e ( t ) + ki * \ int _ { s = 0 } ^ t e ( s ) ds + kd * \ frac { de ( s ) } { ds } ( t )
 The proportional term is just the current error , the integral term is the
 sum of all error measurements , and the derivative term is the instantaneous
 derivative of the error measurement .
 Parameters
 kp : float
 The weight associated with the proportional term of the PID controller .
 ki : float
 The weight associated with the integral term of the PID controller .
 kd : float
 The weight associated with the derivative term of the PID controller .
 smooth : float in [ 0 , 1]
 Derivative values will be smoothed with this exponential average . A
 value of 1 never incorporates new derivative information , a value of 0.5
 uses the mean of the historic and new information , and a value of 0
 discards historic information ( i . e . , the derivative in this case will be
 unsmoothed ) . The default is 0.1.
 Returns
 controller : callable ( float , float ) - > float
 Returns a function that accepts an error measurement and a delta - time
 value since the previous measurement , and returns a control signal .'''

implementation:
state = dict ( p = 0 , i = 0 , d = 0 )
def control ( error , dt = 1 ) :
    state [ 'd' ] = smooth * state [ 'd' ] + ( 1 - smooth ) * ( error - state [ 'p' ] ) / dt
    state [ 'i' ] += error * dt
    state [ 'p' ] = error
    return kp * state [ 'p' ] + ki * state [ 'i' ] + kd * state [ 'd' ]
return control


signature:
def as_flat_array ( iterables ) :
    '''Given a sequence of sequences , return a flat numpy array .
 Parameters
 iterables : sequence of sequence of number
 A sequence of tuples or lists containing numbers . Typically these come
 from something that represents each joint in a skeleton , like angle .
 Returns
 ndarray :
 An array of flattened data from each of the source iterables .'''

implementation:
arr = [ ]
for x in iterables :
    arr . extend ( x )
return np . array ( arr )


signature:
def load ( self , source , ** kwargs ) :
    '''Load a skeleton definition from a file .
 Parameters
 source : str or file
 A filename or file - like object that contains text information
 describing a skeleton . See : class : ` pagoda . parser . Parser ` for more
 information about the format of the text file .'''

implementation:
if hasattr ( source , 'endswith' ) and source . lower ( ) . endswith ( '.asf' ) :
    self . load_asf ( source , ** kwargs )
else :
    self . load_skel ( source , ** kwargs )


signature:
def load_skel ( self , source , ** kwargs ) :
    '''Load a skeleton definition from a text file .
 Parameters
 source : str or file
 A filename or file - like object that contains text information
 describing a skeleton . See : class : ` pagoda . parser . BodyParser ` for
 more information about the format of the text file .'''

implementation:
logging . info ( '%s: parsing skeleton configuration' , source )
if hasattr ( source , 'read' ) :
    p = parser . parse ( source , self . world , self . jointgroup , ** kwargs )
else :
    with open ( source ) as handle :
        p = parser . parse ( handle , self . world , self . jointgroup , ** kwargs )
self . bodies = p . bodies
self . joints = p . joints
self . set_pid_params ( kp = 0.999 / self . world . dt )


signature:
def load_asf ( self , source , ** kwargs ) :
    '''Load a skeleton definition from an ASF text file .
 Parameters
 source : str or file
 A filename or file - like object that contains text information
 describing a skeleton , in ASF format .'''

implementation:
if hasattr ( source , 'read' ) :
    p = parser . parse_asf ( source , self . world , self . jointgroup , ** kwargs )
else :
    with open ( source ) as handle :
        p = parser . parse_asf ( handle , self . world , self . jointgroup , ** kwargs )
self . bodies = p . bodies
self . joints = p . joints
self . set_pid_params ( kp = 0.999 / self . world . dt )


signature:
def set_pid_params ( self , * args , ** kwargs ) :
    '''Set PID parameters for all joints in the skeleton .
 Parameters for this method are passed directly to the ` pid ` constructor .'''

implementation:
for joint in self . joints :
    joint . target_angles = [ None ] * joint . ADOF
    joint . controllers = [ pid ( * args , ** kwargs ) for i in range ( joint . ADOF ) ]


signature:
def joint_torques ( self ) :
    '''Get a list of all current joint torques in the skeleton .'''

implementation: return as_flat_array ( getattr ( j , 'amotor' , j ) . feedback [ - 1 ] [ : j . ADOF ] for j in self . joints )


signature:
def indices_for_joint ( self , name ) :
    '''Get a list of the indices for a specific joint .
 Parameters
 name : str
 The name of the joint to look up .
 Returns
 list of int :
 A list of the index values for quantities related to the named
 joint . Often useful for getting , say , the angles for a specific
 joint in the skeleton .'''

implementation:
j = 0
for joint in self . joints :
    if joint . name == name :
        return list ( range ( j , j + joint . ADOF ) )
    j += joint . ADOF
return [ ]


signature:
def indices_for_body ( self , name , step = 3 ) :
    '''Get a list of the indices for a specific body .
 Parameters
 name : str
 The name of the body to look up .
 step : int , optional
 The number of numbers for each body . Defaults to 3 , should be set
 to 4 for body rotation ( since quaternions have 4 values ) .
 Returns
 list of int :
 A list of the index values for quantities related to the named body .'''

implementation:
for j , body in enumerate ( self . bodies ) :
    if body . name == name :
        return list ( range ( j * step , ( j + 1 ) * step ) )
return [ ]


signature:
def joint_distances ( self ) :
    '''Get the current joint separations for the skeleton .
 Returns
 distances : list of float
 A list expressing the distance between the two joint anchor points ,
 for each joint in the skeleton . These quantities describe how
 " exploded " the bodies in the skeleton are ; a value of 0 indicates
 that the constraints are perfectly satisfied for that joint .'''

implementation: return [ ( ( np . array ( j . anchor ) - j . anchor2 ) ** 2 ) . sum ( ) for j in self . joints ]


signature:
def enable_motors ( self , max_force ) :
    '''Enable the joint motors in this skeleton .
 This method sets the maximum force that can be applied by each joint to
 attain the desired target velocities . It also enables torque feedback
 for all joint motors .
 Parameters
 max _ force : float
 The maximum force that each joint is allowed to apply to attain its
 target velocity .'''

implementation:
for joint in self . joints :
    amotor = getattr ( joint , 'amotor' , joint )
    amotor . max_forces = max_force
    if max_force > 0 :
        amotor . enable_feedback ( )
    else :
        amotor . disable_feedback ( )


signature:
def set_target_angles ( self , angles ) :
    '''Move each joint toward a target angle .
 This method uses a PID controller to set a target angular velocity for
 each degree of freedom in the skeleton , based on the difference between
 the current and the target angle for the respective DOF .
 PID parameters are by default set to achieve a tiny bit less than
 complete convergence in one time step , using only the P term ( i . e . , the
 P coefficient is set to 1 - \ delta , while I and D coefficients are set
 to 0 ) . PID parameters can be updated by calling the ` set _ pid _ params `
 method .
 Parameters
 angles : list of float
 A list of the target angles for every joint in the skeleton .'''

implementation:
j = 0
for joint in self . joints :
    velocities = [ ctrl ( tgt - cur , self . world . dt ) for cur , tgt , ctrl in zip ( joint . angles , angles [ j : j + joint . ADOF ] , joint . controllers ) ]
    joint . velocities = velocities
    j += joint . ADOF


signature:
def add_torques ( self , torques ) :
    '''Add torques for each degree of freedom in the skeleton .
 Parameters
 torques : list of float
 A list of the torques to add to each degree of freedom in the
 skeleton .'''

implementation:
j = 0
for joint in self . joints :
    joint . add_torques ( list ( torques [ j : j + joint . ADOF ] ) + [ 0 ] * ( 3 - joint . ADOF ) )
    j += joint . ADOF


signature:
def labels ( self ) :
    '''Return the names of our marker labels in canonical order .'''

implementation: return sorted ( self . channels , key = lambda c : self . channels [ c ] )


signature:
def load_csv ( self , filename , start_frame = 10 , max_frames = int ( 1e300 ) ) :
    '''Load marker data from a CSV file .
 The file will be imported using Pandas , which must be installed to use
 this method . ( ` ` pip install pandas ` ` )
 The first line of the CSV file will be used for header information . The
 " time " column will be used as the index for the data frame . There must
 be columns named ' markerAB - foo - x ' , ' markerAB - foo - y ' , ' markerAB - foo - z ' , and
 ' markerAB - foo - c ' for marker ' foo ' to be included in the model .
 Parameters
 filename : str
 Name of the CSV file to load .'''

implementation:
import pandas as pd
compression = None
if filename . endswith ( '.gz' ) :
    compression = 'gzip'
df = pd . read_csv ( filename , compression = compression ) . set_index ( 'time' ) . fillna ( - 1 )
# make sure the data frame ' s time index matches our world .
assert self . world . dt == pd . Series ( df . index ) . diff ( ) . mean ( )
markers = [ ]
for c in df . columns :
    m = re . match ( r'^marker\d\d-(.*)-c$' , c )
    if m :
        markers . append ( m . group ( 1 ) )
self . channels = self . _map_labels_to_channels ( markers )
cols = [ c for c in df . columns if re . match ( r'^marker\d\d-.*-[xyzc]$' , c ) ]
self . data = df [ cols ] . values . reshape ( ( len ( df ) , len ( markers ) , 4 ) ) [ start_frame : ]
self . data [ : , : , [ 1 , 2 ] ] = self . data [ : , : , [ 2 , 1 ] ]
logging . info ( '%s: loaded marker data %s' , filename , self . data . shape )
self . process_data ( )
self . create_bodies ( )


signature:
def load_c3d ( self , filename , start_frame = 0 , max_frames = int ( 1e300 ) ) :
    '''Load marker data from a C3D file .
 The file will be imported using the c3d module , which must be installed
 to use this method . ( ` ` pip install c3d ` ` )
 Parameters
 filename : str
 Name of the C3D file to load .
 start _ frame : int , optional
 Discard the first N frames . Defaults to 0.
 max _ frames : int , optional
 Maximum number of frames to load . Defaults to loading all frames .'''

implementation:
import c3d
with open ( filename , 'rb' ) as handle :
    reader = c3d . Reader ( handle )
    logging . info ( 'world frame rate %s, marker frame rate %s' , 1 / self . world . dt , reader . point_rate )
    # set up a map from marker label to index in the data stream .
    self . channels = self . _map_labels_to_channels ( [ s . strip ( ) for s in reader . point_labels ] )
    # read the actual c3d data into a numpy array .
    data = [ ]
    for i , ( _ , frame , _ ) in enumerate ( reader . read_frames ( ) ) :
        if i >= start_frame :
            data . append ( frame [ : , [ 0 , 1 , 2 , 4 ] ] )
        if len ( data ) > max_frames :
            break
    self . data = np . array ( data )
    # scale the data to meters - - mm is a very common C3D unit .
    if reader . get ( 'POINT:UNITS' ) . string_value . strip ( ) . lower ( ) == 'mm' :
        logging . info ( 'scaling point data from mm to m' )
        self . data [ : , : , : 3 ] /= 1000.
logging . info ( '%s: loaded marker data %s' , filename , self . data . shape )
self . process_data ( )
self . create_bodies ( )


signature:
def process_data ( self ) :
    '''Process data to produce velocity and dropout information .'''

implementation:
self . visibility = self . data [ : , : , 3 ]
self . positions = self . data [ : , : , : 3 ]
self . velocities = np . zeros_like ( self . positions ) + 1000
for frame_no in range ( 1 , len ( self . data ) - 1 ) :
    prev = self . data [ frame_no - 1 ]
    next = self . data [ frame_no + 1 ]
    for c in range ( self . num_markers ) :
        if - 1 < prev [ c , 3 ] < 100 and - 1 < next [ c , 3 ] < 100 :
            self . velocities [ frame_no , c ] = ( next [ c , : 3 ] - prev [ c , : 3 ] ) / ( 2 * self . world . dt )
self . cfms = np . zeros_like ( self . visibility ) + self . DEFAULT_CFM


signature:
def create_bodies ( self ) :
    '''Create physics bodies corresponding to each marker in our data .'''

implementation:
self . bodies = { }
for label in self . channels :
    body = self . world . create_body ( 'sphere' , name = 'marker:{}' . format ( label ) , radius = 0.02 )
    body . is_kinematic = True
    body . color = 0.9 , 0.1 , 0.1 , 0.5
    self . bodies [ label ] = body


signature:
def load_attachments ( self , source , skeleton ) :
    '''Load attachment configuration from the given text source .
 The attachment configuration file has a simple format . After discarding
 Unix - style comments ( any part of a line that starts with the pound ( # )
 character ) , each line in the file is then expected to have the following
 format : :
 marker - name body - name X Y Z
 The marker name must correspond to an existing " channel " in our marker
 data . The body name must correspond to a rigid body in the skeleton . The
 X , Y , and Z coordinates specify the body - relative offsets where the
 marker should be attached : 0 corresponds to the center of the body along
 the given axis , while - 1 and 1 correspond to the minimal ( maximal ,
 respectively ) extent of the body ' s bounding box along the corresponding
 dimension .
 Parameters
 source : str or file - like
 A filename or file - like object that we can use to obtain text
 configuration that describes how markers are attached to skeleton
 bodies .
 skeleton : : class : ` pagoda . skeleton . Skeleton `
 The skeleton to attach our marker data to .'''

implementation:
self . targets = { }
self . offsets = { }
filename = source
if isinstance ( source , str ) :
    source = open ( source )
else :
    filename = '(file-{})' . format ( id ( source ) )
for i , line in enumerate ( source ) :
    tokens = line . split ( '#' ) [ 0 ] . strip ( ) . split ( )
    if not tokens :
        continue
    label = tokens . pop ( 0 )
    if label not in self . channels :
        logging . info ( '%s:%d: unknown marker %s' , filename , i , label )
        continue
    if not tokens :
        continue
    name = tokens . pop ( 0 )
    bodies = [ b for b in skeleton . bodies if b . name == name ]
    if len ( bodies ) != 1 :
        logging . info ( '%s:%d: %d skeleton bodies match %s' , filename , i , len ( bodies ) , name )
        continue
    b = self . targets [ label ] = bodies [ 0 ]
    o = self . offsets [ label ] = np . array ( list ( map ( float , tokens ) ) ) * b . dimensions / 2
    logging . info ( '%s <--> %s, offset %s' , label , b . name , o )


signature:
def attach ( self , frame_no ) :
    '''Attach marker bodies to the corresponding skeleton bodies .
 Attachments are only made for markers that are not in a dropout state in
 the given frame .
 Parameters
 frame _ no : int
 The frame of data we will use for attaching marker bodies .'''

implementation:
assert not self . joints
for label , j in self . channels . items ( ) :
    target = self . targets . get ( label )
    if target is None :
        continue
    if self . visibility [ frame_no , j ] < 0 :
        continue
    if np . linalg . norm ( self . velocities [ frame_no , j ] ) > 10 :
        continue
    joint = ode . BallJoint ( self . world . ode_world , self . jointgroup )
    joint . attach ( self . bodies [ label ] . ode_body , target . ode_body )
    joint . setAnchor1Rel ( [ 0 , 0 , 0 ] )
    joint . setAnchor2Rel ( self . offsets [ label ] )
    joint . setParam ( ode . ParamCFM , self . cfms [ frame_no , j ] )
    joint . setParam ( ode . ParamERP , self . erp )
    joint . name = label
    self . joints [ label ] = joint
self . _frame_no = frame_no


signature:
def reposition ( self , frame_no ) :
    '''Reposition markers to a specific frame of data .
 Parameters
 frame _ no : int
 The frame of data where we should reposition marker bodies . Markers
 will be positioned in the appropriate places in world coordinates .
 In addition , linear velocities of the markers will be set according
 to the data as long as there are no dropouts in neighboring frames .'''

implementation:
for label , j in self . channels . items ( ) :
    body = self . bodies [ label ]
    body . position = self . positions [ frame_no , j ]
    body . linear_velocity = self . velocities [ frame_no , j ]


signature:
def distances ( self ) :
    '''Get a list of the distances between markers and their attachments .
 Returns
 distances : ndarray of shape ( num - markers , 3)
 Array of distances for each marker joint in our attachment setup . If
 a marker does not currently have an associated joint ( e . g . because
 it is not currently visible ) this will contain NaN for that row .'''

implementation:
distances = [ ]
for label in self . labels :
    joint = self . joints . get ( label )
    distances . append ( [ np . nan , np . nan , np . nan ] if joint is None else np . array ( joint . getAnchor ( ) ) - joint . getAnchor2 ( ) )
return np . array ( distances )


signature:
def forces ( self , dx_tm1 = None ) :
    '''Return an array of the forces exerted by marker springs .
 Notes
 The forces exerted by the marker springs can be approximated by : :
 F = kp * dx
 where ` ` dx ` ` is the current array of marker distances . An even more
 accurate value is computed by approximating the velocity of the spring
 displacement : :
 F = kp * dx + kd * ( dx - dx _ tm1 ) / dt
 where ` ` dx _ tm1 ` ` is an array of distances from the previous time step .
 Parameters
 dx _ tm1 : ndarray
 An array of distances from markers to their attachment targets ,
 measured at the previous time step .
 Returns
 F : ndarray
 An array of forces that the markers are exerting on the skeleton .'''

implementation:
cfm = self . cfms [ self . _frame_no ] [ : , None ]
kp = self . erp / ( cfm * self . world . dt )
kd = ( 1 - self . erp ) / cfm
dx = self . distances ( )
F = kp * dx
if dx_tm1 is not None :
    bad = np . isnan ( dx ) | np . isnan ( dx_tm1 )
    F [ ~ bad ] += ( kd * ( dx - dx_tm1 ) / self . world . dt ) [ ~ bad ]
return F


signature:
def load_skeleton ( self , filename , pid_params = None ) :
    '''Create and configure a skeleton in our model .
 Parameters
 filename : str
 The name of a file containing skeleton configuration data .
 pid _ params : dict , optional
 If given , use this dictionary to set the PID controller
 parameters on each joint in the skeleton . See
 : func : ` pagoda . skeleton . pid ` for more information .'''

implementation:
self . skeleton = skeleton . Skeleton ( self )
self . skeleton . load ( filename , color = ( 0.3 , 0.5 , 0.9 , 0.8 ) )
if pid_params :
    self . skeleton . set_pid_params ( ** pid_params )
self . skeleton . erp = 0.1
self . skeleton . cfm = 0


signature:
def load_markers ( self , filename , attachments , max_frames = 1e100 ) :
    '''Load marker data and attachment preferences into the model .
 Parameters
 filename : str
 The name of a file containing marker data . This currently needs to
 be either a . C3D or a . CSV file . CSV files must adhere to a fairly
 strict column naming convention ; see : func : ` Markers . load _ csv ` for
 more information .
 attachments : str
 The name of a text file specifying how markers are attached to
 skeleton bodies .
 max _ frames : number , optional
 Only read in this many frames of marker data . By default , the entire
 data file is read into memory .
 Returns
 markers : : class : ` Markers `
 Returns a markers object containing loaded marker data as well as
 skeleton attachment configuration .'''

implementation:
self . markers = Markers ( self )
fn = filename . lower ( )
if fn . endswith ( '.c3d' ) :
    self . markers . load_c3d ( filename , max_frames = max_frames )
elif fn . endswith ( '.csv' ) or fn . endswith ( '.csv.gz' ) :
    self . markers . load_csv ( filename , max_frames = max_frames )
else :
    logging . fatal ( '%s: not sure how to load markers!' , filename )
self . markers . load_attachments ( attachments , self . skeleton )


signature:
def step ( self , substeps = 2 ) :
    '''Advance the physics world by one step .
 Typically this is called as part of a : class : ` pagoda . viewer . Viewer ` , but
 it can also be called manually ( or some other stepping mechanism
 entirely can be used ) .'''

implementation:
# by default we step by following our loaded marker data .
self . frame_no += 1
try :
    next ( self . follower )
except ( AttributeError , StopIteration ) as err :
    self . reset ( )


signature:
def settle_to_markers ( self , frame_no = 0 , max_distance = 0.05 , max_iters = 300 , states = None ) :
    '''Settle the skeleton to our marker data at a specific frame .
 Parameters
 frame _ no : int , optional
 Settle the skeleton to marker data at this frame . Defaults to 0.
 max _ distance : float , optional
 The settling process will stop when the mean marker distance falls
 below this threshold . Defaults to 0.1m ( 10cm ) . Setting this too
 small prevents the settling process from finishing ( it will loop
 indefinitely ) , and setting it too large prevents the skeleton from
 settling to a stable state near the markers .
 max _ iters : int , optional
 Attempt to settle markers for at most this many iterations . Defaults
 to 1000.
 states : list of body states , optional
 If given , set the bodies in our skeleton to these kinematic states
 before starting the settling process .'''

implementation:
if states is not None :
    self . skeleton . set_body_states ( states )
dist = None
for _ in range ( max_iters ) :
    for _ in self . _step_to_marker_frame ( frame_no ) :
        pass
    dist = np . nanmean ( abs ( self . markers . distances ( ) ) )
    logging . info ( 'settling to frame %d: marker distance %.3f' , frame_no , dist )
    if dist < max_distance :
        return self . skeleton . get_body_states ( )
    for b in self . skeleton . bodies :
        b . linear_velocity = 0 , 0 , 0
        b . angular_velocity = 0 , 0 , 0
return states


signature:
def follow_markers ( self , start = 0 , end = 1e100 , states = None ) :
    '''Iterate over a set of marker data , dragging its skeleton along .
 Parameters
 start : int , optional
 Start following marker data after this frame . Defaults to 0.
 end : int , optional
 Stop following marker data after this frame . Defaults to the end of
 the marker data .
 states : list of body states , optional
 If given , set the states of the skeleton bodies to these values
 before starting to follow the marker data .'''

implementation:
if states is not None :
    self . skeleton . set_body_states ( states )
for frame_no , frame in enumerate ( self . markers ) :
    if frame_no < start :
        continue
    if frame_no >= end :
        break
    for states in self . _step_to_marker_frame ( frame_no ) :
        yield states


signature:
def _step_to_marker_frame ( self , frame_no , dt = None ) :
    '''Update the simulator to a specific frame of marker data .
 This method returns a generator of body states for the skeleton ! This
 generator must be exhausted ( e . g . , by consuming this call in a for loop )
 for the simulator to work properly .
 This process involves the following steps :
 - Move the markers to their new location :
 - Detach from the skeleton
 - Update marker locations
 - Reattach to the skeleton
 - Detect ODE collisions
 - Yield the states of the bodies in the skeleton
 - Advance the ODE world one step
 Parameters
 frame _ no : int
 Step to this frame of marker data .
 dt : float , optional
 Step with this time duration . Defaults to ` ` self . dt ` ` .
 Returns
 states : sequence of state tuples
 A generator of a sequence of one body state for the skeleton . This
 generator must be exhausted for the simulation to work properly .'''

implementation:
# update the positions and velocities of the markers .
self . markers . detach ( )
self . markers . reposition ( frame_no )
self . markers . attach ( frame_no )
# detect collisions .
self . ode_space . collide ( None , self . on_collision )
# record the state of each skeleton body .
states = self . skeleton . get_body_states ( )
self . skeleton . set_body_states ( states )
# yield the current simulation state to our caller .
yield states
# update the ode world .
self . ode_world . step ( dt or self . dt )
# clear out contact joints to prepare for the next frame .
self . ode_contactgroup . empty ( )


signature:
def inverse_kinematics ( self , start = 0 , end = 1e100 , states = None , max_force = 20 ) :
    '''Follow a set of marker data , yielding kinematic joint angles .
 Parameters
 start : int , optional
 Start following marker data after this frame . Defaults to 0.
 end : int , optional
 Stop following marker data after this frame . Defaults to the end of
 the marker data .
 states : list of body states , optional
 If given , set the states of the skeleton bodies to these values
 before starting to follow the marker data .
 max _ force : float , optional
 Allow each degree of freedom in the skeleton to exert at most this
 force when attempting to maintain its equilibrium position . This
 defaults to 20N . Set this value higher to simulate a stiff skeleton
 while following marker data .
 Returns
 angles : sequence of angle frames
 Returns a generator of joint angle data for the skeleton . One set of
 joint angles will be generated for each frame of marker data between
 ` start ` and ` end ` .'''

implementation:
zeros = None
if max_force > 0 :
    self . skeleton . enable_motors ( max_force )
    zeros = np . zeros ( self . skeleton . num_dofs )
for _ in self . follow_markers ( start , end , states ) :
    if zeros is not None :
        self . skeleton . set_target_angles ( zeros )
    yield self . skeleton . joint_angles


signature:
def inverse_dynamics ( self , angles , start = 0 , end = 1e100 , states = None , max_force = 100 ) :
    '''Follow a set of angle data , yielding dynamic joint torques .
 Parameters
 angles : ndarray ( num - frames x num - dofs )
 Follow angle data provided by this array of angle values .
 start : int , optional
 Start following angle data after this frame . Defaults to the start
 of the angle data .
 end : int , optional
 Stop following angle data after this frame . Defaults to the end of
 the angle data .
 states : list of body states , optional
 If given , set the states of the skeleton bodies to these values
 before starting to follow the marker data .
 max _ force : float , optional
 Allow each degree of freedom in the skeleton to exert at most this
 force when attempting to follow the given joint angles . Defaults to
 100N . Setting this value to be large results in more accurate
 following but can cause oscillations in the PID controllers ,
 resulting in noisy torques .
 Returns
 torques : sequence of torque frames
 Returns a generator of joint torque data for the skeleton . One set
 of joint torques will be generated for each frame of angle data
 between ` start ` and ` end ` .'''

implementation:
if states is not None :
    self . skeleton . set_body_states ( states )
for frame_no , frame in enumerate ( angles ) :
    if frame_no < start :
        continue
    if frame_no >= end :
        break
    self . ode_space . collide ( None , self . on_collision )
    states = self . skeleton . get_body_states ( )
    self . skeleton . set_body_states ( states )
    # joseph ' s stability fix : step to compute torques , then reset the
    # skeleton to the start of the step , and then step using computed
    # torques . thus any numerical errors between the body states after
    # stepping using angle constraints will be removed , because we
    # will be stepping the model using the computed torques .
    self . skeleton . enable_motors ( max_force )
    self . skeleton . set_target_angles ( angles [ frame_no ] )
    self . ode_world . step ( self . dt )
    torques = self . skeleton . joint_torques
    self . skeleton . disable_motors ( )
    self . skeleton . set_body_states ( states )
    self . skeleton . add_torques ( torques )
    yield torques
    self . ode_world . step ( self . dt )
    self . ode_contactgroup . empty ( )


signature:
def forward_dynamics ( self , torques , start = 0 , states = None ) :
    '''Move the body according to a set of torque data .'''

implementation:
if states is not None :
    self . skeleton . set_body_states ( states )
for frame_no , torque in enumerate ( torques ) :
    if frame_no < start :
        continue
    if frame_no >= end :
        break
    self . ode_space . collide ( None , self . on_collision )
    self . skeleton . add_torques ( torque )
    self . ode_world . step ( self . dt )
    yield
    self . ode_contactgroup . empty ( )


signature:
def resorted ( values ) :
    """Sort values , but put numbers after alphabetically sorted words .
 This function is here to make outputs diff - compatible with Aleph .
 Example : :
 > > > sorted ( [ " b " , " 1 " , " a " ] )
 [ ' 1 ' , ' a ' , ' b ' ]
 > > > resorted ( [ " b " , " 1 " , " a " ] )
 [ ' a ' , ' b ' , ' 1 ' ]
 Args :
 values ( iterable ) : any iterable object / list / tuple / whatever .
 Returns :
 list of sorted values , but with numbers after words"""

implementation:
if not values :
    return values
values = sorted ( values )
# look for first word
first_word = next ( ( cnt for cnt , val in enumerate ( values ) if val and not val [ 0 ] . isdigit ( ) ) , None )
# if not found , just return the values
if first_word is None :
    return values
words = values [ first_word : ]
numbers = values [ : first_word ]
return words + numbers


signature:
def render ( self , dt ) :
    '''Draw all bodies in the world .'''

implementation:
for frame in self . _frozen :
    for body in frame :
        self . draw_body ( body )
for body in self . world . bodies :
    self . draw_body ( body )
if hasattr ( self . world , 'markers' ) : # draw line between anchor1 and anchor2 for marker joints .
    window . glColor4f ( 0.9 , 0.1 , 0.1 , 0.9 )
    window . glLineWidth ( 3 )
    for j in self . world . markers . joints . values ( ) :
        window . glBegin ( window . GL_LINES )
        window . glVertex3f ( * j . getAnchor ( ) )
        window . glVertex3f ( * j . getAnchor2 ( ) )
        window . glEnd ( )


signature:
def get_stream ( self , error_callback = None , live = True ) :
    """Get room stream to listen for messages .
 Kwargs :
 error _ callback ( func ) : Callback to call when an error occurred ( parameters : exception )
 live ( bool ) : If True , issue a live stream , otherwise an offline stream
 Returns :
 : class : ` Stream ` . Stream"""

implementation:
self . join ( )
return Stream ( self , error_callback = error_callback , live = live )


signature:
def get_users ( self , sort = True ) :
    """Get list of users in the room .
 Kwargs :
 sort ( bool ) : If True , sort rooms by name
 Returns :
 array . List of users"""

implementation:
self . _load ( )
if sort :
    self . users . sort ( key = operator . itemgetter ( "name" ) )
return self . users


signature:
def recent ( self , message_id = None , limit = None ) :
    """Recent messages .
 Kwargs :
 message _ id ( int ) : If specified , return messages since the specified message ID
 limit ( int ) : If specified , limit the number of messages
 Returns :
 array . Messages"""

implementation:
parameters = { }
if message_id :
    parameters [ "since_message_id" ] = message_id
if limit :
    parameters [ "limit" ] = limit
messages = self . _connection . get ( "room/%s/recent" % self . id , key = "messages" , parameters = parameters )
if messages :
    messages = [ Message ( self . _campfire , message ) for message in messages ]
return messages


signature:
def set_name ( self , name ) :
    """Set the room name .
 Args :
 name ( str ) : Name
 Returns :
 bool . Success"""

implementation:
if not self . _campfire . get_user ( ) . admin :
    return False
result = self . _connection . put ( "room/%s" % self . id , { "room" : { "name" : name } } )
if result [ "success" ] :
    self . _load ( )
return result [ "success" ]


signature:
def set_topic ( self , topic ) :
    """Set the room topic .
 Args :
 topic ( str ) : Topic
 Returns :
 bool . Success"""

implementation:
if not topic :
    topic = ''
result = self . _connection . put ( "room/%s" % self . id , { "room" : { "topic" : topic } } )
if result [ "success" ] :
    self . _load ( )
return result [ "success" ]


signature:
def speak ( self , message ) :
    """Post a message .
 Args :
 message ( : class : ` Message ` or string ) : Message
 Returns :
 bool . Success"""

implementation:
campfire = self . get_campfire ( )
if not isinstance ( message , Message ) :
    message = Message ( campfire , message )
result = self . _connection . post ( "room/%s/speak" % self . id , { "message" : message . get_data ( ) } , parse_data = True , key = "message" )
if result [ "success" ] :
    return Message ( campfire , result [ "data" ] )
return result [ "success" ]


signature:
def transcript ( self , for_date = None ) :
    """Recent messages .
 Kwargs :
 for _ date ( date ) : If specified , get the transcript for this specific date
 Returns :
 array . Messages"""

implementation:
url = "room/%s/transcript" % self . id
if for_date :
    url = "%s/%d/%d/%d" % ( url , for_date . year , for_date . month , for_date . day )
messages = self . _connection . get ( url , key = "messages" )
if messages :
    messages = [ Message ( self . _campfire , message ) for message in messages ]
return messages


signature:
def upload ( self , path , progress_callback = None , finished_callback = None , error_callback = None ) :
    """Create a new thread to upload a file ( thread should be
 then started with start ( ) to perform upload . )
 Args :
 path ( str ) : Path to file
 Kwargs :
 progress _ callback ( func ) : Callback to call as file is uploaded ( parameters : current , total )
 finished _ callback ( func ) : Callback to call when upload is finished
 error _ callback ( func ) : Callback to call when an error occurred ( parameters : exception )
 Returns :
 : class : ` Upload ` . Upload thread"""

implementation: return Upload ( self , { "upload" : path } , progress_callback = progress_callback , finished_callback = finished_callback , error_callback = error_callback )


signature:
def get_new_call ( group_name , app_name , search_path , filename , require_load , version , secure ) : # type : ( str , str , Optional [ str ] , str , bool , Optional [ str ] , bool ) - > str
    '''Build a call to use the new ` ` get _ config ` ` function from args passed to
 ` ` Config . _ _ init _ _ ` ` .'''

implementation:
new_call_kwargs = { 'group_name' : group_name , 'filename' : filename }
# type : Dict [ str , Any ]
new_call_lookup_options = { }
# type : Dict [ str , Any ]
new_call_lookup_options [ 'secure' ] = secure
if search_path :
    new_call_lookup_options [ 'search_path' ] = search_path
if require_load :
    new_call_lookup_options [ 'require_load' ] = require_load
if version :
    new_call_lookup_options [ 'version' ] = version
if new_call_lookup_options :
    new_call_kwargs [ 'lookup_options' ] = new_call_lookup_options
output = build_call_str ( 'get_config' , ( app_name , ) , new_call_kwargs )
return output


signature:
def build_call_str ( prefix , args , kwargs ) : # type : ( str , Any , Any ) - > str
    '''Build a callable Python string for a function call . The output will be
 combined similar to this template : :
 < prefix > ( < args > , < kwargs > )
 Example : :
 > > > build _ call _ str ( ' foo ' , ( 1 , 2 ) , { ' a ' : ' 10 ' } )
 " foo ( 1 , 2 , a = ' 10 ' ) "'''

implementation:
kwargs_str = ', ' . join ( [ '%s=%r' % ( key , value ) for key , value in kwargs . items ( ) ] )
args_str = ', ' . join ( [ repr ( arg ) for arg in args ] )
output = [ prefix , '(' ]
if args :
    output . append ( args_str )
if args and kwargs :
    output . append ( ', ' )
if kwargs :
    output . append ( kwargs_str )
output . append ( ')' )
return '' . join ( output )


signature:
def get_xdg_dirs ( self ) : # type : ( ) - > List [ str ]
    """Returns a list of paths specified by the XDG _ CONFIG _ DIRS environment
 variable or the appropriate default .
 The list is sorted by precedence , with the most important item coming
 * last * ( required by the existing config _ resolver logic ) ."""

implementation:
config_dirs = getenv ( 'XDG_CONFIG_DIRS' , '' )
if config_dirs :
    self . _log . debug ( 'XDG_CONFIG_DIRS is set to %r' , config_dirs )
    output = [ ]
    for path in reversed ( config_dirs . split ( ':' ) ) :
        output . append ( join ( path , self . group_name , self . app_name ) )
    return output
return [ '/etc/xdg/%s/%s' % ( self . group_name , self . app_name ) ]


signature:
def get_xdg_home ( self ) : # type : ( ) - > str
    """Returns the value specified in the XDG _ CONFIG _ HOME environment variable
 or the appropriate default ."""

implementation:
config_home = getenv ( 'XDG_CONFIG_HOME' , '' )
if config_home :
    self . _log . debug ( 'XDG_CONFIG_HOME is set to %r' , config_home )
    return expanduser ( join ( config_home , self . group_name , self . app_name ) )
return expanduser ( '~/.config/%s/%s' % ( self . group_name , self . app_name ) )


signature:
def _effective_filename ( self ) : # type : ( ) - > str
    """Returns the filename which is effectively used by the application . If
 overridden by an environment variable , it will return that filename ."""

implementation:
# same logic for the configuration filename . First , check if we were
# initialized with a filename . . .
config_filename = ''
if self . filename :
    config_filename = self . filename
# . . . next , take the value from the environment
env_filename = getenv ( self . env_filename_name )
if env_filename :
    self . _log . info ( 'Configuration filename was overridden with %r ' 'by the environment variable %s.' , env_filename , self . env_filename_name )
    config_filename = env_filename
return config_filename