idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
30,300
def xml_entity_escape ( data ) : data = data . replace ( "&" , "&amp;" ) data = data . replace ( ">" , "&gt;" ) data = data . replace ( "<" , "&lt;" ) return data
replace special characters with their XML entity versions
30,301
def should_show ( options , member ) : show = options . show if show == SHOW_PUBLIC : return member . is_public ( ) elif show == SHOW_PACKAGE : return member . is_public ( ) or member . is_protected ( ) elif show == SHOW_PRIVATE : return True
whether to show a member by its access flags and the show option . There s probably a faster and smarter way to do this but eh .
30,302
def _unpack_annotation_val ( unpacker , cpool ) : tag , = unpacker . unpack_struct ( _B ) tag = chr ( tag ) if tag in 'BCDFIJSZs' : data , = unpacker . unpack_struct ( _H ) elif tag == 'e' : data = unpacker . unpack_struct ( _HH ) elif tag == 'c' : data , = unpacker . unpack_struct ( _H ) elif tag == '@' : data = JavaA...
tag data tuple of an annotation
30,303
def _pretty_annotation_val ( val , cpool ) : tag , data = val if tag in 'BCDFIJSZs' : data = "%s#%i" % ( tag , data ) elif tag == 'e' : data = "e#%i.#%i" % data elif tag == 'c' : data = "c#%i" % data elif tag == '@' : data = "@" + data . pretty_annotation ( ) elif tag == '[' : combine = list ( ) for val in data : combi...
a pretty display of a tag and data pair annotation value
30,304
def platform_from_version ( major , minor ) : v = ( major , minor ) for low , high , name in _platforms : if low <= v <= high : return name return None
returns the minimum platform version that can load the given class version indicated by major . minor or None if no known platforms match the given version
30,305
def _next_argsig ( s ) : c = s [ 0 ] if c in "BCDFIJSVZ" : result = ( c , s [ 1 : ] ) elif c == "[" : d , s = _next_argsig ( s [ 1 : ] ) result = ( c + d , s [ len ( d ) + 1 : ] ) elif c == "L" : i = s . find ( ';' ) + 1 result = ( s [ : i ] , s [ i + 1 : ] ) elif c == "(" : i = s . find ( ')' ) + 1 result = ( s [ : i ...
given a string find the next complete argument signature and return it and a new string advanced past that point
30,306
def _typeseq_iter ( s ) : s = str ( s ) while s : t , s = _next_argsig ( s ) yield t
iterate through all of the type signatures in a sequence
30,307
def _pretty_type ( s , offset = 0 ) : tc = s [ offset ] if tc == "V" : return "void" elif tc == "Z" : return "boolean" elif tc == "C" : return "char" elif tc == "B" : return "byte" elif tc == "S" : return "short" elif tc == "I" : return "int" elif tc == "J" : return "long" elif tc == "D" : return "double" elif tc == "F...
returns the pretty version of a type code
30,308
def is_class_file ( filename ) : with open ( filename , "rb" ) as fd : c = fd . read ( len ( JAVA_CLASS_MAGIC ) ) if isinstance ( c , str ) : c = map ( ord , c ) return tuple ( c ) == JAVA_CLASS_MAGIC
checks whether the given file is a Java class file by opening it and checking for the magic header
30,309
def unpack_class ( data , magic = None ) : with unpack ( data ) as up : magic = magic or up . unpack_struct ( _BBBB ) if magic != JAVA_CLASS_MAGIC : raise ClassUnpackException ( "Not a Java class file" ) o = JavaClassInfo ( ) o . unpack ( up , magic = magic ) return o
unpacks a Java class from data which can be a string a buffer or a stream supporting the read method . Returns a populated JavaClassInfo instance .
30,310
def unpack ( self , unpacker ) : ( count , ) = unpacker . unpack_struct ( _H ) items = [ ( None , None ) , ] count -= 1 hackpass = False for _i in range ( 0 , count ) : if hackpass : hackpass = False items . append ( ( None , None ) ) else : item = _unpack_const_item ( unpacker ) items . append ( item ) if item [ 0 ] i...
Unpacks the constant pool from an unpacker stream
30,311
def deref_const ( self , index ) : if not index : raise IndexError ( "Requested const 0" ) t , v = self . consts [ index ] if t in ( CONST_Utf8 , CONST_Integer , CONST_Float , CONST_Long , CONST_Double ) : return v elif t in ( CONST_Class , CONST_String , CONST_MethodType ) : return self . deref_const ( v ) elif t in (...
returns the dereferenced value from the const pool . For simple types this will be a single value indicating the constant . For more complex types such as fieldref methodref etc this will return a tuple .
30,312
def unpack ( self , unpacker ) : cval = self . cpool . deref_const ( count , ) = unpacker . unpack_struct ( _H ) for _i in range ( 0 , count ) : ( name , size ) = unpacker . unpack_struct ( _HI ) self [ cval ( name ) ] = unpacker . read ( size )
Unpack an attributes table from an unpacker stream . Modifies the structure of this instance .
30,313
def unpack ( self , unpacker , magic = None ) : magic = magic or unpacker . unpack_struct ( _BBBB ) if isinstance ( magic , ( str , buffer ) ) : magic = tuple ( ord ( m ) for m in magic ) else : magic = tuple ( magic ) if magic != JAVA_CLASS_MAGIC : raise ClassUnpackException ( "Not a Java class file" ) self . magic = ...
Unpacks a Java class from an unpacker stream . Updates the structure of this instance .
30,314
def get_field_by_name ( self , name ) : for f in self . fields : if f . get_name ( ) == name : return f return None
the field member matching name or None if no such field is found
30,315
def get_methods_by_name ( self , name ) : return ( m for m in self . methods if m . get_name ( ) == name )
generator of methods matching name . This will include any bridges present .
30,316
def get_method ( self , name , arg_types = ( ) ) : arg_types = tuple ( arg_types ) for m in self . get_methods_by_name ( name ) : if ( ( ( not m . is_bridge ( ) ) and m . get_arg_type_descriptors ( ) == arg_types ) ) : return m return None
searches for the method matching the name and having argument type descriptors matching those in arg_types .
30,317
def get_method_bridges ( self , name , arg_types = ( ) ) : for m in self . get_methods_by_name ( name ) : if ( ( m . is_bridge ( ) and m . get_arg_type_descriptors ( ) == arg_types ) ) : yield m
generator of bridge methods found that adapt the return types of a named method and having argument type descriptors matching those in arg_types .
30,318
def get_sourcefile ( self ) : buff = self . get_attribute ( "SourceFile" ) if buff is None : return None with unpack ( buff ) as up : ( ref , ) = up . unpack_struct ( _H ) return self . deref_const ( ref )
the name of thie file this class was compiled from or None if not indicated
30,319
def get_innerclasses ( self ) : buff = self . get_attribute ( "InnerClasses" ) if buff is None : return tuple ( ) with unpack ( buff ) as up : return tuple ( up . unpack_objects ( JavaInnerClassInfo , self . cpool ) )
sequence of JavaInnerClassInfo instances describing the inner classes of this class definition
30,320
def _pretty_access_flags_gen ( self ) : if self . is_public ( ) : yield "public" if self . is_final ( ) : yield "final" if self . is_abstract ( ) : yield "abstract" if self . is_interface ( ) : if self . is_annotation ( ) : yield "@interface" else : yield "interface" if self . is_enum ( ) : yield "enum"
generator of the pretty access flags
30,321
def pretty_descriptor ( self ) : f = " " . join ( self . pretty_access_flags ( ) ) if not self . is_interface ( ) : f += " class" n = self . pretty_this ( ) e = self . pretty_super ( ) i = "," . join ( self . pretty_interfaces ( ) ) if i : return "%s %s extends %s implements %s" % ( f , n , e , i ) else : return "%s %s...
get the class or interface name its accessor flags its parent class and any interfaces it implements
30,322
def _get_provides ( self , private = False ) : me = self . pretty_this ( ) yield me for field in self . fields : if private or field . is_public ( ) : yield "%s.%s" % ( me , field . pretty_identifier ( ) ) for method in self . methods : if private or method . is_public ( ) : yield "%s.%s" % ( me , method . pretty_ident...
iterator of provided classes fields methods
30,323
def _get_requires ( self ) : provided = set ( self . get_provides ( private = True ) ) cpool = self . cpool for i , t , _v in cpool . constants ( ) : if t in ( CONST_Class , CONST_Fieldref , CONST_Methodref , CONST_InterfaceMethodref ) : pv = str ( cpool . pretty_deref_const ( i ) ) if pv [ 0 ] == "[" : t = _typeseq ( ...
iterator of required classes fields methods determined my mining the constant pool for such types
30,324
def get_provides ( self , ignored = tuple ( ) , private = False ) : if private : if self . _provides_private is None : self . _provides_private = set ( self . _get_provides ( True ) ) provides = self . _provides_private else : if self . _provides is None : self . _provides = set ( self . _get_provides ( False ) ) provi...
The provided API including the class itself its fields and its methods .
30,325
def get_requires ( self , ignored = tuple ( ) ) : if self . _requires is None : self . _requires = set ( self . _get_requires ( ) ) requires = self . _requires return [ req for req in requires if not fnmatches ( req , * ignored ) ]
The required API including all external classes fields and methods that this class references
30,326
def unpack ( self , unpacker ) : ( a , b , c ) = unpacker . unpack_struct ( _HHH ) self . access_flags = a self . name_ref = b self . descriptor_ref = c self . attribs . unpack ( unpacker )
unpack the contents of this instance from the values in unpacker
30,327
def get_annotationdefault ( self ) : buff = self . get_attribute ( "AnnotationDefault" ) if buff is None : return None with unpack ( buff ) as up : ( ti , ) = up . unpack_struct ( _H ) return ti
The AnnotationDefault attribute only present upon fields in an annotaion .
30,328
def get_code ( self ) : buff = self . get_attribute ( "Code" ) if buff is None : return None with unpack ( buff ) as up : code = JavaCodeInfo ( self . cpool ) code . unpack ( up ) return code
the JavaCodeInfo of this member if it is a non - abstract method None otherwise
30,329
def get_exceptions ( self ) : buff = self . get_attribute ( "Exceptions" ) if buff is None : return ( ) with unpack ( buff ) as up : return tuple ( self . deref_const ( e [ 0 ] ) for e in up . unpack_struct_array ( _H ) )
a tuple of class names for the exception types this method may raise or None if this is not a method
30,330
def get_constantvalue ( self ) : buff = self . get_attribute ( "ConstantValue" ) if buff is None : return None with unpack ( buff ) as up : ( cval_ref , ) = up . unpack_struct ( _H ) return cval_ref
the constant pool index for this field or None if this is not a contant field
30,331
def get_arg_type_descriptors ( self ) : if not self . is_method : return tuple ( ) tp = _typeseq ( self . get_descriptor ( ) ) tp = _typeseq ( tp [ 0 ] [ 1 : - 1 ] ) return tp
The parameter type descriptor list for a method or None for a field . Type descriptors are shorthand identifiers for the builtin java types .
30,332
def pretty_arg_types ( self ) : if self . is_method : types = self . get_arg_type_descriptors ( ) return ( _pretty_type ( t ) for t in types ) else : return tuple ( )
Sequence of pretty argument types .
30,333
def pretty_descriptor ( self ) : f = " " . join ( self . pretty_access_flags ( ) ) p = self . pretty_type ( ) n = self . get_name ( ) t = "," . join ( self . pretty_exceptions ( ) ) if n == "<init>" : p = None if self . is_method : n = "%s(%s)" % ( n , "," . join ( self . pretty_arg_types ( ) ) ) if t : t = "throws " +...
assemble a long member name from access flags type argument types exceptions as applicable
30,334
def pretty_identifier ( self ) : ident = self . get_name ( ) if self . is_method : args = "," . join ( self . pretty_arg_types ( ) ) ident = "%s(%s)" % ( ident , args ) return "%s:%s" % ( ident , self . pretty_type ( ) )
The pretty version of get_identifier
30,335
def unpack ( self , unpacker ) : ( a , b , c ) = unpacker . unpack_struct ( _HHI ) self . max_stack = a self . max_locals = b self . code = unpacker . read ( c ) uobjs = unpacker . unpack_objects self . exceptions = tuple ( uobjs ( JavaExceptionInfo , self ) ) self . attribs . unpack ( unpacker )
unpacks a code block from a buffer . Updates the internal structure of this instance
30,336
def get_line_for_offset ( self , code_offset ) : prev_line = 0 for ( offset , line ) in self . get_linenumbertable ( ) : if offset < code_offset : prev_line = line elif offset == code_offset : return line else : return prev_line return prev_line
returns the line number given a code offset
30,337
def unpack ( self , unpacker ) : ( a , b , c , d ) = unpacker . unpack_struct ( _HHHH ) self . start_pc = a self . end_pc = b self . handler_pc = c self . catch_type_ref = d
unpacks an exception handler entry in an exception table . Updates the internal structure of this instance
30,338
def info ( self ) : return ( self . start_pc , self . end_pc , self . handler_pc , self . get_catch_type ( ) )
tuple of the start_pc end_pc handler_pc and catch_type_ref
30,339
def unpack ( self , unpacker ) : ( a , b , c , d ) = unpacker . unpack_struct ( _HHHH ) self . inner_info_ref = a self . outer_info_ref = b self . name_ref = c self . access_flags = d
unpack this instance with data from unpacker
30,340
def parse_sections ( data ) : if not data : return curr = None for lineno , line in enumerate ( data . splitlines ( ) ) : cleanline = line . replace ( '\x00' , '' ) if not cleanline : if curr : yield curr curr = None elif cleanline [ 0 ] == ' ' : if curr is None : raise MalformedManifest ( "bad line continuation, " " l...
yields one section at a time in the form
30,341
def digest_chunks ( chunks , algorithms = ( hashlib . md5 , hashlib . sha1 ) ) : hashes = [ algorithm ( ) for algorithm in algorithms ] for chunk in chunks : for h in hashes : h . update ( chunk ) return [ _b64encode_to_str ( h . digest ( ) ) for h in hashes ]
returns a base64 rep of the given digest algorithms from the chunks of data
30,342
def file_chunk ( filename , size = _BUFFERING ) : def chunks ( ) : with open ( filename , "rb" , _BUFFERING ) as fd : buf = fd . read ( size ) while buf : yield buf buf = fd . read ( size ) return chunks
returns a generator function which when called will emit x - sized chunks of filename s contents
30,343
def zipentry_chunk ( zipfile , name , size = _BUFFERING ) : def chunks ( ) : with zipfile . open ( name ) as fd : buf = fd . read ( size ) while buf : yield buf buf = fd . read ( size ) return chunks
returns a generator function which when called will emit x - sized chunks of the named entry in the zipfile object
30,344
def single_path_generator ( pathname ) : if isdir ( pathname ) : trim = len ( pathname ) if pathname [ - 1 ] != sep : trim += 1 for entry in directory_generator ( pathname , trim ) : yield entry else : zf = ZipFile ( pathname ) for f in zf . namelist ( ) : if f [ - 1 ] != '/' : yield f , zipentry_chunk ( zf , f ) zf . ...
emits name chunkgen pairs for the given file at pathname . If pathname is a directory will act recursively and will emit for each file in the directory tree chunkgen is a generator that can be iterated over to obtain the contents of the file in multiple parts
30,345
def cli_create ( argument_list ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "content" , help = "file or directory" ) parser . add_argument ( "-r" , "--recursive" , help = "process directories recursively" ) parser . add_argument ( "-i" , "--ignore" , nargs = "+" , action = "append" , help = "patte...
command - line call to create a manifest from a JAR file or a directory
30,346
def main ( args = sys . argv ) : if len ( args ) < 2 : return usage ( "Command expected" ) command = args [ 1 ] rest = args [ 2 : ] if "create" . startswith ( command ) : return cli_create ( rest ) elif "query" . startswith ( command ) : return cli_query ( rest ) elif "verify" . startswith ( command ) : return cli_veri...
main entry point for the manifest CLI
30,347
def load ( self , items ) : for k , vals in items : self [ k ] = "" . join ( vals )
Populate this section from an iteration of the parse_items call
30,348
def store ( self , stream , linesep = os . linesep ) : for k , v in self . items ( ) : write_key_val ( stream , k , v , linesep ) stream . write ( linesep . encode ( 'utf-8' ) )
Serialize this section and write it to a binary stream
30,349
def create_section ( self , name , overwrite = True ) : if overwrite : sect = ManifestSection ( name ) self . sub_sections [ name ] = sect else : sect = self . sub_sections . get ( name , None ) if sect is None : sect = ManifestSection ( name ) self . sub_sections [ name ] = sect return sect
create and return a new sub - section of this manifest with the given Name attribute . If a sub - section already exists with that name it will be lost unless overwrite is False in which case the existing sub - section will be returned .
30,350
def store ( self , stream , linesep = None ) : linesep = linesep or self . linesep or os . linesep ManifestSection . store ( self , stream , linesep ) for sect in sorted ( self . sub_sections . values ( ) ) : sect . store ( stream , linesep )
Serialize the Manifest to a binary stream
30,351
def clear ( self ) : for sub in self . sub_sections . values ( ) : sub . clear ( ) self . sub_sections . clear ( ) ManifestSection . clear ( self )
removes all items from this manifest and clears and removes all sub - sections
30,352
def digest_manifest ( self , manifest , java_algorithm = "SHA-256" ) : linesep = manifest . linesep or os . linesep all_key = java_algorithm + "-Digest-Manifest" main_key = java_algorithm + "-Digest-Manifest-Main-Attributes" sect_key = java_algorithm + "-Digest" digest = _get_digest ( java_algorithm ) accum = manifest ...
Create a main section checksum and sub - section checksums based off of the data from an existing manifest using an algorithm given by Java - style name .
30,353
def verify_manifest_main_checksum ( self , manifest ) : for java_digest in self . keys_with_suffix ( "-Digest-Manifest" ) : whole_mf_digest = b64_encoded_digest ( manifest . get_data ( ) , _get_digest ( java_digest ) ) if whole_mf_digest == self . get ( java_digest + "-Digest-Manifest" ) : return True return False
Verify the checksum over the manifest main section .
30,354
def verify_manifest_entry_checksums ( self , manifest , strict = True ) : failures = [ ] for s in manifest . sub_sections . values ( ) : sf_section = self . create_section ( s . primary ( ) , overwrite = False ) digests = s . keys_with_suffix ( "-Digest" ) if not digests and strict : failures . append ( s . primary ( )...
Verifies the checksums over the given manifest . If strict is True then entries which had no digests will fail verification . If strict is False then entries with no digests will not be considered failing .
30,355
def fnmatches ( entry , * pattern_list ) : for pattern in pattern_list : if pattern and fnmatch ( entry , pattern ) : return True return False
returns true if entry matches any of the glob patterns false otherwise
30,356
def copydir ( orig , dest ) : copied = list ( ) makedirsp ( dest ) for root , dirs , files in walk ( orig ) : for d in dirs : makedirsp ( join ( dest , d ) ) for f in files : root_f = join ( root , f ) dest_f = join ( dest , relpath ( root_f , orig ) ) copy ( root_f , dest_f ) copied . append ( ( root_f , dest_f ) ) re...
copies directory orig to dest . Returns a list of tuples of relative filenames which were copied from orig to dest
30,357
def _gen_from_dircmp ( dc , lpath , rpath ) : left_only = dc . left_only left_only . sort ( ) for f in left_only : fp = join ( dc . left , f ) if isdir ( fp ) : for r , _ds , fs in walk ( fp ) : r = relpath ( r , lpath ) for f in fs : yield ( LEFT , join ( r , f ) ) else : yield ( LEFT , relpath ( fp , lpath ) ) right_...
do the work of comparing the dircmp
30,358
def verify ( certificate , jar_file , sf_name = None ) : zip_file = ZipFile ( jar_file ) sf_files = [ f for f in zip_file . namelist ( ) if file_matches_sigfile ( f ) ] if len ( sf_files ) == 0 : raise JarSignatureMissingError ( "No .SF file in %s" % jar_file ) elif len ( sf_files ) > 1 : if sf_name is None : msg = "Mu...
Verifies signature of a JAR file .
30,359
def cli_create_jar ( argument_list ) : usage_message = "usage: jarutil c [OPTIONS] file.jar files..." parser = argparse . ArgumentParser ( usage = usage_message ) parser . add_argument ( "jar_file" , type = str , help = "The file to create" ) parser . add_argument ( "-m" , "--main-class" , type = str , help = "Specify ...
A subset of jar command . Creating new JARs only .
30,360
def create_signature_block ( openssl_digest , certificate , private_key , extra_certs , data ) : smime = SMIME . SMIME ( ) with BIO . openfile ( private_key ) as k , BIO . openfile ( certificate ) as c : smime . load_key_bio ( k , c ) if extra_certs is not None : stack = X509 . X509_Stack ( ) for cert in extra_certs : ...
Produces a signature block for the data .
30,361
def verify_signature_block ( certificate_file , content , signature ) : sig_bio = BIO . MemoryBuffer ( signature ) pkcs7 = SMIME . PKCS7 ( m2 . pkcs7_read_bio_der ( sig_bio . _ptr ( ) ) , 1 ) signers_cert_stack = pkcs7 . get0_signers ( X509 . X509_Stack ( ) ) trusted_cert_store = X509 . X509_Store ( ) trusted_cert_stor...
Verifies the signature over the content trusting the certificate .
30,362
def send ( self , obj_id ) : response = self . _client . session . post ( '{url}/{id}/send' . format ( url = self . endpoint_url , id = obj_id ) ) return self . process_response ( response )
Send email to the assigned lists
30,363
def send_to_contact ( self , obj_id , contact_id ) : response = self . _client . session . post ( '{url}/{id}/send/contact/{contact_id}' . format ( url = self . endpoint_url , id = obj_id , contact_id = contact_id ) ) return self . process_response ( response )
Send email to a specific contact
30,364
def get_owners ( self ) : response = self . _client . session . get ( '{url}/list/owners' . format ( url = self . endpoint_url ) ) return self . process_response ( response )
Get a list of users available as contact owners
30,365
def get_events ( self , obj_id , search = '' , include_events = None , exclude_events = None , order_by = '' , order_by_dir = 'ASC' , page = 1 ) : if include_events is None : include_events = [ ] if exclude_events is None : exclude_events = [ ] parameters = { 'search' : search , 'includeEvents' : include_events , 'excl...
Get a list of a contact s engagement events
30,366
def get_contact_notes ( self , obj_id , search = '' , start = 0 , limit = 0 , order_by = '' , order_by_dir = 'ASC' ) : parameters = { 'search' : search , 'start' : start , 'limit' : limit , 'orderBy' : order_by , 'orderByDir' : order_by_dir , } response = self . _client . session . get ( '{url}/{id}/notes' . format ( u...
Get a list of a contact s notes
30,367
def add_points ( self , obj_id , points , ** kwargs ) : response = self . _client . session . post ( '{url}/{id}/points/plus/{points}' . format ( url = self . endpoint_url , id = obj_id , points = points ) , data = kwargs ) return self . process_response ( response )
Add the points to a contact
30,368
def add_dnc ( self , obj_id , channel = 'email' , reason = MANUAL , channel_id = None , comments = 'via API' ) : data = { 'reason' : reason , 'channelId' : channel_id , 'comments' : comments } response = self . _client . session . post ( '{url}/{id}/dnc/add/{channel}' . format ( url = self . endpoint_url , id = obj_id ...
Adds Do Not Contact
30,369
def remove_dnc ( self , obj_id , channel ) : response = self . _client . session . post ( '{url}/{id}/dnc/remove/{channel}' . format ( url = self . endpoint_url , id = obj_id , channel = channel ) ) return self . process_response ( response )
Removes Do Not Contact
30,370
def get ( self , obj_id ) : response = self . _client . session . get ( '{url}/{id}' . format ( url = self . endpoint_url , id = obj_id ) ) return self . process_response ( response )
Get a single item
30,371
def get_list ( self , search = '' , start = 0 , limit = 0 , order_by = '' , order_by_dir = 'ASC' , published_only = False , minimal = False ) : parameters = { } args = [ 'search' , 'start' , 'limit' , 'minimal' ] for arg in args : if arg in locals ( ) and locals ( ) [ arg ] : parameters [ arg ] = locals ( ) [ arg ] if ...
Get a list of items
30,372
def edit ( self , obj_id , parameters , create_if_not_exists = False ) : if create_if_not_exists : response = self . _client . session . put ( '{url}/{id}/edit' . format ( url = self . endpoint_url , id = obj_id ) , data = parameters ) else : response = self . _client . session . patch ( '{url}/{id}/edit' . format ( ur...
Edit an item with option to create if it doesn t exist
30,373
def get ( self , table = '' , start = 0 , limit = 0 , order = None , where = None ) : parameters = { } args = [ 'start' , 'limit' , 'order' , 'where' ] for arg in args : if arg in locals ( ) and locals ( ) [ arg ] : parameters [ arg ] = locals ( ) [ arg ] response = self . _client . session . get ( '{url}/{table}' . fo...
Get a list of stat items
30,374
def add_contact ( self , segment_id , contact_id ) : response = self . _client . session . post ( '{url}/{segment_id}/contact/add/{contact_id}' . format ( url = self . endpoint_url , segment_id = segment_id , contact_id = contact_id ) ) return self . process_response ( response )
Add a contact to the segment
30,375
def check_permission ( self , obj_id , permissions ) : response = self . _client . session . post ( '{url}/{id}/permissioncheck' . format ( url = self . endpoint_url , id = obj_id ) , data = { 'permissions' : permissions } ) return self . process_response ( response )
Get list of permissions for a user
30,376
def delete_trigger_events ( self , trigger_id , event_ids ) : response = self . _client . session . delete ( '{url}/{trigger_id}/events/delete' . format ( url = self . endpoint_url , trigger_id = trigger_id ) , params = { 'events' : event_ids } ) return self . process_response ( response )
Remove events from a point trigger
30,377
def delete_fields ( self , form_id , field_ids ) : response = self . _client . session . delete ( '{url}/{form_id}/fields/delete' . format ( url = self . endpoint_url , form_id = form_id ) , params = { 'fields' : field_ids } ) return self . process_response ( response )
Remove fields from a form
30,378
def delete_actions ( self , form_id , action_ids ) : response = self . _client . session . delete ( '{url}/{form_id}/actions/delete' . format ( url = self . endpoint_url , form_id = form_id ) , params = { 'actions' : action_ids } ) return self . process_response ( response )
Remove actions from a form
30,379
def update_token_tempfile ( token ) : with open ( tmp , 'w' ) as f : f . write ( json . dumps ( token , indent = 4 ) )
Example of function for token update
30,380
def set_folder ( self , folder = 'assets' ) : folder = folder . replace ( '/' , '.' ) self . _endpoint = 'files/{folder}' . format ( folder = folder )
Changes the file folder to look at
30,381
def _check_cooling_parameters ( radiuscooling , scalecooling ) : if radiuscooling != "linear" and radiuscooling != "exponential" : raise Exception ( "Invalid parameter for radiuscooling: " + radiuscooling ) if scalecooling != "linear" and scalecooling != "exponential" : raise Exception ( "Invalid parameter for scalecoo...
Helper function to verify the cooling parameters of the training .
30,382
def _hexplot ( matrix , fig , colormap ) : umatrix_min = matrix . min ( ) umatrix_max = matrix . max ( ) n_rows , n_columns = matrix . shape cmap = plt . get_cmap ( colormap ) offsets = np . zeros ( ( n_columns * n_rows , 2 ) ) facecolors = [ ] for row in range ( n_rows ) : for col in range ( n_columns ) : if row % 2 =...
Internal function to plot a hexagonal map .
30,383
def load_bmus ( self , filename ) : self . bmus = np . loadtxt ( filename , comments = '%' , usecols = ( 1 , 2 ) ) if self . n_vectors != 0 and len ( self . bmus ) != self . n_vectors : raise Exception ( "The number of best matching units does not match " "the number of data instances" ) else : self . n_vectors = len (...
Load the best matching units from a file to the Somoclu object .
30,384
def load_umatrix ( self , filename ) : self . umatrix = np . loadtxt ( filename , comments = '%' ) if self . umatrix . shape != ( self . _n_rows , self . _n_columns ) : raise Exception ( "The dimensions of the U-matrix do not " "match that of the map" )
Load the umatrix from a file to the Somoclu object .
30,385
def load_codebook ( self , filename ) : self . codebook = np . loadtxt ( filename , comments = '%' ) if self . n_dim == 0 : self . n_dim = self . codebook . shape [ 1 ] if self . codebook . shape != ( self . _n_rows * self . _n_columns , self . n_dim ) : raise Exception ( "The dimensions of the codebook do not " "match...
Load the codebook from a file to the Somoclu object .
30,386
def update_data ( self , data ) : oldn_dim = self . n_dim if data . dtype != np . float32 : print ( "Warning: data was not float32. A 32-bit copy was made" ) self . _data = np . float32 ( data ) else : self . _data = data self . n_vectors , self . n_dim = data . shape if self . n_dim != oldn_dim and oldn_dim != 0 : rai...
Change the data set in the Somoclu object . It is useful when the data is updated and the training should continue on the new data .
30,387
def view_component_planes ( self , dimensions = None , figsize = None , colormap = cm . Spectral_r , colorbar = False , bestmatches = False , bestmatchcolors = None , labels = None , zoom = None , filename = None ) : if self . codebook is None : raise Exception ( "The codebook is not available. Either train a map" " or...
Observe the component planes in the codebook of the SOM .
30,388
def view_umatrix ( self , figsize = None , colormap = cm . Spectral_r , colorbar = False , bestmatches = False , bestmatchcolors = None , labels = None , zoom = None , filename = None ) : if self . umatrix is None : raise Exception ( "The U-matrix is not available. Either train a map" " or load a U-matrix from a file" ...
Plot the U - matrix of the trained map .
30,389
def view_activation_map ( self , data_vector = None , data_index = None , activation_map = None , figsize = None , colormap = cm . Spectral_r , colorbar = False , bestmatches = False , bestmatchcolors = None , labels = None , zoom = None , filename = None ) : if data_vector is None and data_index is None : raise Except...
Plot the activation map of a given data instance or a new data vector
30,390
def _check_parameters ( self ) : if self . _map_type != "planar" and self . _map_type != "toroid" : raise Exception ( "Invalid parameter for _map_type: " + self . _map_type ) if self . _grid_type != "rectangular" and self . _grid_type != "hexagonal" : raise Exception ( "Invalid parameter for _grid_type: " + self . _gri...
Internal function to verify the basic parameters of the SOM .
30,391
def _init_codebook ( self ) : codebook_size = self . _n_columns * self . _n_rows * self . n_dim if self . codebook is None : if self . _initialization == "random" : self . codebook = np . zeros ( codebook_size , dtype = np . float32 ) self . codebook [ 0 : 2 ] = [ 1000 , 2000 ] else : self . _pca_init ( ) elif self . c...
Internal function to set the codebook or to indicate it to the C ++ code that it should be randomly initialized .
30,392
def cluster ( self , algorithm = None ) : import sklearn . base if algorithm is None : import sklearn . cluster algorithm = sklearn . cluster . KMeans ( ) elif not isinstance ( algorithm , sklearn . base . ClusterMixin ) : raise Exception ( "Cannot use algorithm of type " + type ( algorithm ) ) original_shape = self . ...
Cluster the codebook . The clusters of the data instances can be assigned based on the BMUs . The method populates the class variable Somoclu . clusters . If viewing methods are called after clustering but without colors for best matching units colors will be automatically assigned based on cluster membership .
30,393
def get_surface_state ( self , data = None ) : if data is None : d = self . _data else : d = data codebookReshaped = self . codebook . reshape ( self . codebook . shape [ 0 ] * self . codebook . shape [ 1 ] , self . codebook . shape [ 2 ] ) parts = np . array_split ( d , 200 , axis = 0 ) am = np . empty ( ( 0 , ( self ...
Return the Euclidean distance between codebook and data .
30,394
def get_bmus ( self , activation_map ) : Y , X = np . unravel_index ( activation_map . argmin ( axis = 1 ) , ( self . _n_rows , self . _n_columns ) ) return np . vstack ( ( X , Y ) ) . T
Returns Best Matching Units indexes of the activation map .
30,395
def view_similarity_matrix ( self , data = None , labels = None , figsize = None , filename = None ) : if not have_heatmap : raise Exception ( "Import dependencies missing for viewing " "similarity matrix. You must have seaborn and " "scikit-learn" ) if data is None and self . activation_map is None : self . get_surfac...
Plot the similarity map according to the activation map
30,396
def find_child_element ( elm , child_local_name ) : for n in range ( len ( elm ) ) : child_elm = elm [ n ] tag = etree . QName ( child_elm ) if tag . localname == child_local_name : return child_elm return None
Find an XML child element by local tag name .
30,397
def make_service_url ( self ) : cas_service_url = self . authenticator . cas_service_url if cas_service_url is None : cas_service_url = self . request . protocol + "://" + self . request . host + self . request . uri return cas_service_url
Make the service URL CAS will use to redirect the browser back to this service .
30,398
def validate_service_ticket ( self , ticket ) : app_log = logging . getLogger ( "tornado.application" ) http_client = AsyncHTTPClient ( ) service = self . make_service_url ( ) qs_dict = dict ( service = service , ticket = ticket ) qs = urllib . parse . urlencode ( qs_dict ) cas_validate_url = self . authenticator . cas...
Validate a CAS service ticket .
30,399
def clean_exit ( signum , frame = None ) : global exiting if exiting : LOG . debug ( 'Exit in progress clean_exit received additional signal %s' % signum ) return LOG . info ( 'Received signal %s, beginning graceful shutdown.' % signum ) exiting = True wait_for_exit = False for process in processors : try : if process ...
Exit all processes attempting to finish uncommitted active work before exit . Can be called on an os signal or no zookeeper losing connection .