signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def computeIndent ( self , block , char ) : """Compute indent for the block . Basic alorightm , which knows nothing about programming languages May be used by child classes"""
prevBlockText = block . previous ( ) . text ( ) # invalid block returns empty text if char == '\n' and prevBlockText . strip ( ) == '' : # continue indentation , if no text return self . _prevBlockIndent ( block ) else : # be smart return self . computeSmartIndent ( block , char )
def _get_calculatable_methods_dict ( inputs , methods ) : '''Given an iterable of input variable names and a methods dictionary , returns the subset of that methods dictionary that can be calculated and which doesn ' t calculate something we already have . Additionally it may only contain one method for any g...
# Initialize a return dictionary calculatable_methods = { } # Iterate through each potential method output for var in methods . keys ( ) : # See if we already have this output if var in inputs : continue # if we have it , we don ' t need to calculate it ! else : # Initialize a dict for this outp...
def calculate_omega_matrix ( states , Omega = 1 ) : """Calculate the matrix of transition frequencies . This function recieves a list of states and returns the corresponding omega _ ij matrix , rescaled to units of Omega . These are understood to be absolute frequencies ( as opposed angular frequencies ) ."""
N = len ( states ) omega = [ [ 2 * Pi * ( states [ i ] . nu - states [ j ] . nu ) / Omega for j in range ( N ) ] for i in range ( N ) ] return omega
def inverse_kinematics ( self , target_position , target_orientation , rest_poses = None ) : """Helper function to do inverse kinematics for a given target position and orientation in the PyBullet world frame . Args : target _ position : A tuple , list , or numpy array of size 3 for position . target _ orie...
if rest_poses is None : ik_solution = list ( p . calculateInverseKinematics ( self . ik_robot , 6 , target_position , targetOrientation = target_orientation , restPoses = [ 0 , - 1.18 , 0.00 , 2.18 , 0.00 , 0.57 , 3.3161 ] , jointDamping = [ 0.1 ] * 7 , ) ) else : ik_solution = list ( p . calculateInverseKinema...
def tags ( self ) : '''List tags ( py _ version , abi , platform ) supported by this wheel .'''
return itertools . product ( self . py_version . split ( '.' ) , self . abi . split ( '.' ) , self . platform . split ( '.' ) , )
def sigma_data ( self ) : """Read - only Property : return : Data belonging to each sigma variable as a dict with variable names as key , data as value . : rtype : collections . OrderedDict"""
sigmas = self . model . sigmas return OrderedDict ( ( sigmas [ var ] , self . data [ sigmas [ var ] ] ) for var in self . model . dependent_vars )
def remove_col_label ( self , event ) : # , include _ pmag = True ) : """check to see if column is required if it is not , delete it from grid"""
er_possible_headers = self . grid_headers [ self . grid_type ] [ 'er' ] [ 2 ] pmag_possible_headers = self . grid_headers [ self . grid_type ] [ 'pmag' ] [ 2 ] er_actual_headers = self . grid_headers [ self . grid_type ] [ 'er' ] [ 0 ] pmag_actual_headers = self . grid_headers [ self . grid_type ] [ 'pmag' ] [ 0 ] col ...
def output_mailbox ( gandi , mailbox , output_keys , justify = 16 ) : """Helper to output a mailbox information ."""
quota = 'quota' in output_keys responder = 'responder' in output_keys if quota : output_keys . pop ( output_keys . index ( 'quota' ) ) if responder : output_keys . pop ( output_keys . index ( 'responder' ) ) if 'aliases' in output_keys : mailbox [ 'aliases' ] = sorted ( mailbox [ 'aliases' ] ) output_generi...
def charge_sign ( self ) : """Charge sign text"""
if self . charge > 0 : sign = "+" elif self . charge < 0 : sign = "–" # en dash , not hyphen - minus else : return "" ab = abs ( self . charge ) if ab > 1 : return str ( ab ) + sign return sign
def send ( self , smtp = None , ** kw ) : """Sends message . : param smtp : When set , parameters from this dictionary overwrite options from config . See ` emails . Message . send ` for more information . : param kwargs : Parameters for ` emails . Message . send ` : return : Response objects from emails ba...
smtp_options = { } smtp_options . update ( self . config . smtp_options ) if smtp : smtp_options . update ( smtp ) return super ( Message , self ) . send ( smtp = smtp_options , ** kw )
def parents ( self ) : """Returns list of parents changesets ."""
return [ self . repository . get_changeset ( parent ) for parent in self . _commit . parents ]
def as_dict ( self ) : """Makes XcFunc obey the general json interface used in pymatgen for easier serialization ."""
d = { "@module" : self . __class__ . __module__ , "@class" : self . __class__ . __name__ } # print ( " in as _ dict " , type ( self . x ) , type ( self . c ) , type ( self . xc ) ) if self . x is not None : d [ "x" ] = self . x . as_dict ( ) if self . c is not None : d [ "c" ] = self . c . as_dict ( ) if self ....
def copy_abs ( self ) : """Return a copy of self with the sign bit unset . Unlike abs ( self ) , this does not make use of the context : the result has the same precision as the original ."""
result = mpfr . Mpfr_t . __new__ ( BigFloat ) mpfr . mpfr_init2 ( result , self . precision ) mpfr . mpfr_setsign ( result , self , False , ROUND_TIES_TO_EVEN ) return result
def _fire_task ( self , exclude = None ) : """Build and send the emails as a celery task ."""
connection = mail . get_connection ( fail_silently = True ) # Warning : fail _ silently swallows errors thrown by the generators , too . connection . open ( ) for m in self . _mails ( self . _users_watching ( exclude = exclude ) ) : connection . send_messages ( [ m ] )
def _coord ( self ) : """Attribute indicating the tree coordinates for this node . The tree coordinates of a node are expressed as a tuple of the indices of the node and its ancestors , for example : A grandchild node with node path ` / root . name / root . childs [ 2 ] . name / root . childs [ 2 ] . childs...
_coord = [ ] _node = self while _node . parent : _idx = _node . parent . childs . index ( _node ) _coord . insert ( 0 , _idx ) _node = _node . parent return tuple ( _coord )
def _process_tags ( self , tags ) : """Process the tags of the message : param tags : the tags string of a message : type tags : : class : ` str ` | None : returns : list of tags : rtype : : class : ` list ` of : class : ` message . Tag ` : raises : None"""
if not tags : return [ ] return [ message . Tag . from_str ( x ) for x in tags . split ( ';' ) ]
def _to_array ( self , alpha , normalization = '4pi' , csphase = 1 ) : """Return the spherical harmonic coefficients of Slepian function i as an array , where i = 0 is the best concentrated function ."""
if self . coeffs is None : coeffs = _np . copy ( self . _taper2coeffs ( alpha ) ) else : if alpha > self . nrot - 1 : raise ValueError ( 'alpha must be less than or equal to ' + 'nrot - 1. alpha = {:d}, nrot = {:d}' . format ( alpha , self . nrot ) ) coeffs = _shtools . SHVectorToCilm ( self . coeff...
def to_add_link ( self , ) : '''To add link'''
if self . check_post_role ( ) [ 'ADD' ] : pass else : return False kwd = { 'pager' : '' , 'uid' : '' , } self . render ( 'misc/link/link_add.html' , topmenu = '' , kwd = kwd , userinfo = self . userinfo , )
def bottom ( self , objects : Set [ Object ] ) -> Set [ Object ] : """Return the bottom most objects ( i . e . maximum y _ loc ) . The comparison is done separately for each box ."""
objects_per_box = self . _separate_objects_by_boxes ( objects ) return_set : Set [ Object ] = set ( ) for _ , box_objects in objects_per_box . items ( ) : max_y_loc = max ( [ obj . y_loc for obj in box_objects ] ) return_set . update ( set ( [ obj for obj in box_objects if obj . y_loc == max_y_loc ] ) ) return ...
def open ( filename ) : """Open a file in read only mode using the encoding detected by detect _ encoding ( ) ."""
buffer = _builtin_open ( filename , 'rb' ) try : encoding , lines = detect_encoding ( buffer . readline ) buffer . seek ( 0 ) text = TextIOWrapper ( buffer , encoding , line_buffering = True ) text . mode = 'r' return text except : buffer . close ( ) raise
def get_url_file_name ( url ) : """Determines the url ' s file name . : param str url : the url to extract the file name from : return str : the filename ( without the file extension ) on the server"""
url_root_ext = os . path . splitext ( url ) if len ( url_root_ext [ 1 ] ) <= MAX_FILE_EXTENSION_LENGTH : return os . path . split ( url_root_ext [ 0 ] ) [ 1 ] else : return os . path . split ( url ) [ 1 ]
def send ( data , channels = None , push_time = None , expiration_time = None , expiration_interval = None , where = None , cql = None ) : """发送推送消息 。 返回结果为此条推送对应的 _ Notification 表中的对象 , 但是如果需要使用其中的数据 , 需要调用 fetch ( ) 方法将数据同步至本地 。 : param channels : 需要推送的频道 : type channels : list or tuple : param push _ time ...
if expiration_interval and expiration_time : raise TypeError ( 'Both expiration_time and expiration_interval can\'t be set' ) params = { 'data' : data , } if client . USE_PRODUCTION == '0' : params [ 'prod' ] = 'dev' if channels : params [ 'channels' ] = channels if push_time : tzinfo = push_time . tzin...
def _convert_to_seeder_format ( dataset ) : """WA KAT dataset has different structure from Seeder . This is convertor which converts WA - KAT - > Seeder data format . Args : dataset ( dict ) : WA - KAT dataset sent from frontend . Returns : dict : Dict with converted data ."""
data = { } seed = { } _add_if_set ( data , "name" , dataset . get ( "title" ) ) _add_if_set ( data , "issn" , dataset . get ( "issn" ) ) _add_if_set ( data , "annotation" , dataset . get ( "annotation" ) ) rules = dataset . get ( "rules" , { } ) if rules : _add_if_set ( data , "frequency" , rules . get ( "frequency...
def named_relations ( self , name , neg = False ) : '''Returns list of named Relations . < name > may be string or list .'''
if self . internalLinks and not neg : if isinstance ( name , six . string_types ) : return filter ( lambda x : x . name == name , self . internalLinks ) elif isinstance ( name , list ) : return filter ( lambda x : x . name in name , self . internalLinks ) else : return None # should ...
def _run_command ( self , env ) : """Run command ( s ) and return output and urgency ."""
output = "" urgent = False # run the block / command for command in self . commands : try : process = Popen ( command , stdout = PIPE , stderr = PIPE , universal_newlines = True , env = env , shell = True , ) except Exception as e : msg = "Command '{cmd}' {error}" raise Exception ( msg ....
def unpack_node ( image_path , name = None , output_folder = None , size = None ) : '''unpackage node is intended to unpackage a node that was packaged with package _ node . The image should be a . tgz file . The general steps are to : 1 . Package the node using the package _ node function 2 . Transfer the pa...
if not image_path . endswith ( ".tgz" ) : bot . error ( "The image_path should end with .tgz. Did you create with package_node?" ) sys . exit ( 1 ) if output_folder is None : output_folder = os . path . dirname ( os . path . abspath ( image_path ) ) image_name = os . path . basename ( image_path ) if name i...
def checkCache ( fnm , strip = 0 , upx = 0 ) : """Cache prevents preprocessing binary files again and again ."""
# On darwin a cache is required anyway to keep the libaries # with relative install names . Caching on darwin does not work # since we need to modify binary headers to use relative paths # to dll depencies and starting with ' @ executable _ path ' . if ( ( not strip and not upx and not is_darwin and not is_win ) or fnm...
def _pb_timestamp_to_datetime ( timestamp_pb ) : """Convert a Timestamp protobuf to a datetime object . : type timestamp _ pb : : class : ` google . protobuf . timestamp _ pb2 . Timestamp ` : param timestamp _ pb : A Google returned timestamp protobuf . : rtype : : class : ` datetime . datetime ` : returns ...
return _EPOCH + datetime . timedelta ( seconds = timestamp_pb . seconds , microseconds = ( timestamp_pb . nanos / 1000.0 ) )
def pre_create ( sender , model ) : """Callback before creating any new model Identify the creator of the new model & set the created timestamp to now ."""
model . created = dt . utcnow ( ) model . creator = goldman . sess . login
def shell_comment ( c ) : 'Do not shell - escape raw strings in comments , but do handle line breaks .'
return ShellQuoted ( '# {c}' ) . format ( c = ShellQuoted ( ( raw_shell ( c ) if isinstance ( c , ShellQuoted ) else c ) . replace ( '\n' , '\n# ' ) ) )
def _K ( m ) : """matrix K _ m from Wiktorsson2001"""
M = m * ( m - 1 ) // 2 K = np . zeros ( ( M , m ** 2 ) , dtype = np . int64 ) row = 0 for j in range ( 1 , m ) : col = ( j - 1 ) * m + j s = m - j K [ row : ( row + s ) , col : ( col + s ) ] = np . eye ( s ) row += s return K
def tournament_game ( n , k , random_state = None ) : """Return a NormalFormGame instance of the 2 - player win - lose game , whose payoffs are either 0 or 1 , introduced by Anbalagan et al . (2013 ) . Player 0 has n actions , which constitute the set of nodes {0 , . . . , n - 1 } , while player 1 has n choos...
m = scipy . special . comb ( n , k , exact = True ) if m > np . iinfo ( np . intp ) . max : raise ValueError ( 'Maximum allowed size exceeded' ) payoff_arrays = tuple ( np . zeros ( shape ) for shape in [ ( n , m ) , ( m , n ) ] ) tourn = random_tournament_graph ( n , random_state = random_state ) indices , indptr ...
def common_install_apache2 ( self ) : """Install apache2 web server"""
try : sudo ( 'apt-get install apache2 -y' ) except Exception as e : print ( e ) print ( green ( ' * Installed Apache2 in the system.' ) ) print ( green ( ' * Done' ) ) print ( )
def get_p2p_routing_table ( self , x , y ) : """Dump the contents of a chip ' s P2P routing table . This method can be indirectly used to get a list of functioning chips . . . note : : This method only returns the entries for chips within the bounds of the system . E . g . if booted with 8x8 only entries fo...
table = { } # Get the dimensions of the system p2p_dims = self . read_struct_field ( "sv" , "p2p_dims" , x , y ) width = ( p2p_dims >> 8 ) & 0xFF height = ( p2p_dims >> 0 ) & 0xFF # Read out the P2P table data , one column at a time ( note that eight # entries are packed into each 32 - bit word ) col_words = ( ( ( heig...
def validate ( schema_text , data_text , deserializer = _default_deserializer ) : """Validate specified JSON text with specified schema . Both arguments are converted to JSON objects with : func : ` simplejson . loads ` , if present , or : func : ` json . loads ` . : param schema _ text : Text of the JSON s...
schema = Schema ( deserializer ( schema_text ) ) data = deserializer ( data_text ) return Validator . validate ( schema , data )
def exists ( self , path ) : """Check if a given path exists on the filesystem . : type path : str : param path : the path to look for : rtype : bool : return : : obj : ` True ` if ` ` path ` ` exists"""
_complain_ifclosed ( self . closed ) return self . fs . exists ( path )
def add_variables ( self , variables , cardinality , inhibitor_probability ) : """Adds variables to the NoisyOrModel . Parameters variables : list , tuple , dict ( array like ) array containing names of the variables that are to be added . cardinality : list , tuple , dict ( array like ) array containing ...
if len ( variables ) == 1 : if not isinstance ( inhibitor_probability [ 0 ] , ( list , tuple ) ) : inhibitor_probability = [ inhibitor_probability ] if len ( variables ) != len ( cardinality ) : raise ValueError ( "Size of variables and cardinality should be same" ) elif any ( cardinal != len ( prob_arr...
def rc_to_exctype ( cls , rc ) : """Map an error code to an exception : param int rc : The error code received for an operation : return : a subclass of : class : ` CouchbaseError `"""
try : return _LCB_ERRNO_MAP [ rc ] except KeyError : newcls = _mk_lcberr ( rc ) _LCB_ERRNO_MAP [ rc ] = newcls return newcls
def tlsa_rec ( rdata ) : '''Validate and parse DNS record data for TLSA record ( s ) : param rdata : DNS record data : return : dict w / fields'''
rschema = OrderedDict ( ( ( 'usage' , RFC . TLSA_USAGE ) , ( 'selector' , RFC . TLSA_SELECT ) , ( 'matching' , RFC . TLSA_MATCHING ) , ( 'pub' , str ) ) ) return _data2rec ( rschema , rdata )
def _create_all_tables ( self ) : """Creates all the required tables by calling the required functions . : return :"""
self . _create_post_table ( ) self . _create_tag_table ( ) self . _create_tag_posts_table ( ) self . _create_user_posts_table ( )
def _Region4 ( P , x ) : """Basic equation for region 4 Parameters P : float Pressure , [ MPa ] x : float Vapor quality , [ - ] Returns prop : dict Dict with calculated properties . The available properties are : * T : Saturated temperature , [ K ] * P : Saturated pressure , [ MPa ] * x : Vapo...
T = _TSat_P ( P ) if T > 623.15 : rhol = 1. / _Backward3_sat_v_P ( P , T , 0 ) P1 = _Region3 ( rhol , T ) rhov = 1. / _Backward3_sat_v_P ( P , T , 1 ) P2 = _Region3 ( rhov , T ) else : P1 = _Region1 ( T , P ) P2 = _Region2 ( T , P ) propiedades = { } propiedades [ "T" ] = T propiedades [ "P" ] =...
def p_call_expr_nobf ( self , p ) : """call _ expr _ nobf : member _ expr _ nobf arguments | call _ expr _ nobf arguments | call _ expr _ nobf LBRACKET expr RBRACKET | call _ expr _ nobf PERIOD identifier"""
if len ( p ) == 3 : p [ 0 ] = ast . FunctionCall ( p [ 1 ] , p [ 2 ] ) elif len ( p ) == 4 : p [ 0 ] = ast . DotAccessor ( p [ 1 ] , p [ 3 ] ) else : p [ 0 ] = ast . BracketAccessor ( p [ 1 ] , p [ 3 ] )
def iterate ( self , max_iter = None ) : """Note : A ZMQStreamer does not activate its stream , but allows the zmq _ worker to do that . Yields data : dict Data drawn from ` streamer ( max _ iter ) ` ."""
context = zmq . Context ( ) if six . PY2 : warnings . warn ( 'zmq_stream cannot preserve numpy array alignment ' 'in Python 2' , RuntimeWarning ) try : socket = context . socket ( zmq . PAIR ) port = socket . bind_to_random_port ( 'tcp://*' , min_port = self . min_port , max_port = self . max_port , max_tri...
def hmap_dt ( self ) : # used for CSV export """: returns : a composite dtype ( imt , poe )"""
return numpy . dtype ( [ ( '%s-%s' % ( imt , poe ) , F32 ) for imt in self . imtls for poe in self . poes ] )
def get_context_data ( self , ** kwargs ) : """Add in what fields are linkable"""
context = super ( SmartListView , self ) . get_context_data ( ** kwargs ) # our linkable fields self . link_fields = self . derive_link_fields ( context ) # stuff it all in our context context [ 'link_fields' ] = self . link_fields # our search term if any if 'search' in self . request . GET : context [ 'search' ] ...
def admin_app_list ( request ) : """Adopted from ` ` django . contrib . admin . sites . AdminSite . index ` ` . Returns a list of lists of models grouped and ordered according to ` ` yacms . conf . ADMIN _ MENU _ ORDER ` ` . Called from the ` ` admin _ dropdown _ menu ` ` template tag as well as the ` ` app _...
app_dict = { } # Model or view - - > ( group index , group title , item index , item title ) . menu_order = { } for ( group_index , group ) in enumerate ( settings . ADMIN_MENU_ORDER ) : group_title , items = group for ( item_index , item ) in enumerate ( items ) : if isinstance ( item , ( tuple , list ...
def create_filter ( request , mapped_class , geom_attr , ** kwargs ) : """Create MapFish default filter based on the request params . Arguments : request the request . mapped _ class the SQLAlchemy mapped class . geom _ attr the key of the geometry property as defined in the SQLAlchemy mapper . If y...
attr_filter = create_attr_filter ( request , mapped_class ) geom_filter = create_geom_filter ( request , mapped_class , geom_attr , ** kwargs ) if geom_filter is None and attr_filter is None : return None if geom_filter is None : return attr_filter if attr_filter is None : return geom_filter return and_ ( g...
def split ( self , sep = None , maxsplit = sys . maxsize ) : """Behaves like the built - in str . split ( ) except returns a WordList . : rtype : : class : ` WordList < WordList > `"""
return WordList ( self . _strkey ( ) . split ( sep , maxsplit ) , parent = self )
def set_max_requests_per_connection ( self , host_distance , max_requests ) : """Sets a threshold for concurrent requests per connection , above which new connections will be created to a host ( up to max connections ; see : meth : ` ~ Cluster . set _ max _ connections _ per _ host ` ) . Pertains to connectio...
if self . protocol_version >= 3 : raise UnsupportedOperation ( "Cluster.set_max_requests_per_connection() only has an effect " "when using protocol_version 1 or 2." ) if max_requests < 1 or max_requests > 127 or max_requests <= self . _min_requests_per_connection [ host_distance ] : raise ValueError ( "max_requ...
def add ( self , hostname , keytype , key ) : """Add a host key entry to the table . Any existing entry for a ` ` ( hostname , keytype ) ` ` pair will be replaced . : param str hostname : the hostname ( or IP ) to add : param str keytype : key type ( ` ` " ssh - rsa " ` ` or ` ` " ssh - dss " ` ` ) : param ...
for e in self . _entries : if ( hostname in e . hostnames ) and ( e . key . get_name ( ) == keytype ) : e . key = key return self . _entries . append ( HostKeyEntry ( [ hostname ] , key ) )
def flatten_dict_vals ( dict_ ) : """Flattens only values in a heirarchical dictionary , keys are nested ."""
if isinstance ( dict_ , dict ) : return dict ( [ ( ( key , augkey ) , augval ) for key , val in dict_ . items ( ) for augkey , augval in flatten_dict_vals ( val ) . items ( ) ] ) else : return { None : dict_ }
def request ( self , method , endpoint = None , headers = None , use_auth = True , _url = None , _kwargs = None , ** kwargs ) : """Make a request to the Canvas API and return the response . : param method : The HTTP method for the request . : type method : str : param endpoint : The endpoint to call . : typ...
full_url = _url if _url else "{}{}" . format ( self . base_url , endpoint ) if not headers : headers = { } if use_auth : auth_header = { 'Authorization' : 'Bearer {}' . format ( self . access_token ) } headers . update ( auth_header ) # Convert kwargs into list of 2 - tuples and combine with _ kwargs . _kwa...
def _load_actor_class_from_gcs ( self , driver_id , function_descriptor ) : """Load actor class from GCS ."""
key = ( b"ActorClass:" + driver_id . binary ( ) + b":" + function_descriptor . function_id . binary ( ) ) # Wait for the actor class key to have been imported by the # import thread . TODO ( rkn ) : It shouldn ' t be possible to end # up in an infinite loop here , but we should push an error to # the driver if too much...
def com_google_fonts_check_name_familyname_first_char ( ttFont ) : """Make sure family name does not begin with a digit . Font family names which start with a numeral are often not discoverable in Windows applications ."""
from fontbakery . utils import get_name_entry_strings failed = False for familyname in get_name_entry_strings ( ttFont , NameID . FONT_FAMILY_NAME ) : digits = map ( str , range ( 0 , 10 ) ) if familyname [ 0 ] in digits : yield FAIL , ( "Font family name '{}'" " begins with a digit!" ) . format ( famil...
def draw_route ( self , df_route , cr , color = None , line_width = None ) : '''Draw a line between electrodes listed in a route . Arguments - ` df _ route ` : * A ` pandas . DataFrame ` containing a column named ` electrode _ i ` . * For each row , ` electrode _ i ` corresponds to the integer index of th...
df_route_centers = ( self . canvas . df_shape_centers . ix [ df_route . electrode_i ] [ [ 'x_center' , 'y_center' ] ] ) df_endpoint_marker = ( .6 * self . get_endpoint_marker ( df_route_centers ) + df_route_centers . iloc [ - 1 ] . values ) # Save cairo context to restore after drawing route . cr . save ( ) if color is...
def write_job ( self , fh ) : """Write the DAG entry for this node ' s job to the DAG file descriptor . @ param fh : descriptor of open DAG file ."""
if isinstance ( self . job ( ) , CondorDAGManJob ) : # create an external subdag from this dag fh . write ( ' ' . join ( [ 'SUBDAG EXTERNAL' , self . __name , self . __job . get_sub_file ( ) ] ) ) if self . job ( ) . get_dag_directory ( ) : fh . write ( ' DIR ' + self . job ( ) . get_dag_directory ( ) )...
def copy_tpl ( template_file , dst , template_vars ) : """This supports jinja2 templates . Please feel encouraged to use the template framework of your choosing . jinja2 docu : http : / / jinja . pocoo . org / docs / 2.9/ : param template _ file : : param dst : : param template _ vars : dictionary contain...
create_dir ( dst ) # load template template_loader = jinja2 . FileSystemLoader ( searchpath = '/' ) template_env = jinja2 . Environment ( loader = template_loader , keep_trailing_newline = True ) template = template_env . get_template ( template_file ) # render and write to file template . stream ( template_vars ) . du...
def _add_metadata ( item , metadata , remotes , only_metadata = False ) : """Add metadata information from CSV file to current item . Retrieves metadata based on ' description ' parsed from input CSV file . Adds to object and handles special keys : - ` description ` : A new description for the item . Used to ...
for check_key in [ item [ "description" ] ] + _get_file_keys ( item ) + _get_vrn_keys ( item ) : item_md = metadata . get ( check_key ) if item_md : break if not item_md : item_md = _find_glob_metadata ( item [ "files" ] , metadata ) if remotes . get ( "region" ) : item [ "algorithm" ] [ "varian...
def handle ( self , * args , ** options ) : # NoQA """Execute the command ."""
# Load the settings self . require_settings ( args , options ) # Load your AWS credentials from ~ / . aws / credentials self . load_credentials ( ) try : # Tail the available logs all_logs = self . zappa . fetch_logs ( self . lambda_name ) self . print_logs ( all_logs ) # Keep polling , and print any new lo...
def construct_arg ( cls : Type [ T ] , # pylint : disable = inconsistent - return - statements , too - many - return - statements param_name : str , annotation : Type , default : Any , params : Params , ** extras ) -> Any : """Does the work of actually constructing an individual argument for : func : ` create _ kwa...
from allennlp . models . archival import load_archive # import here to avoid circular imports # We used ` param _ name ` as the method argument to avoid conflicts with ' name ' being a key in # ` extras ` , which isn ' t _ that _ unlikely . Now that we are inside the method , we can switch back # to using ` name ` . na...
def follow_redirects ( url ) : """Get ' s the url actual address by following forwards : param str url : the url to work on : return str : actual address of url"""
opener = urllib2 . build_opener ( urllib2 . HTTPRedirectHandler ) return opener . open ( url ) . url
def get_handler ( self , * args , ** options ) : """Returns the django . contrib . staticfiles handler ."""
handler = WSGIHandler ( ) try : from django . contrib . staticfiles . handlers import StaticFilesHandler except ImportError : return handler use_static_handler = options . get ( 'use_static_handler' , True ) insecure_serving = options . get ( 'insecure_serving' , False ) if ( settings . DEBUG and use_static_han...
def hexdump_diff_iter ( source1 , source2 , start = None , end = None , length = None , major_len = 8 , minor_len = 4 , colour = True , before = 2 , after = 2 , address_base = None ) : """Returns the differences between two byte strings in tabular hexadecimal / ASCII format . source1 The first byte string sourc...
stride = minor_len * major_len start = start if start is not None else 0 end = end if end is not None else max ( len ( source1 ) , len ( source2 ) ) start = max ( start , 0 ) end = min ( end , max ( len ( source1 ) , len ( source2 ) ) ) address_base_offset = address_base - start if address_base is not None else 0 diff_...
def message_handler ( self , * custom_filters , commands = None , regexp = None , content_types = None , state = None , run_task = None , ** kwargs ) : """Decorator for message handler Examples : Simple commands handler : . . code - block : : python3 @ dp . message _ handler ( commands = [ ' start ' , ' wel...
def decorator ( callback ) : self . register_message_handler ( callback , * custom_filters , commands = commands , regexp = regexp , content_types = content_types , state = state , run_task = run_task , ** kwargs ) return callback return decorator
def cmd_string ( name , cmd ) : # type : ( AName , ACmd ) - > ADefine """Define a string parameter coming from a shell command to be used within this YAML file . Trailing newlines will be stripped ."""
value = subprocess . check_output ( cmd , shell = True ) . rstrip ( "\n" ) return Define ( name , value )
def compute_files ( user1 , user2 , file_list , dir_pre , start_num ) : """Compute the smatch scores for a file list between two users Args : user1 : user 1 name user2 : user 2 name file _ list : file list dir _ pre : the file location prefix start _ num : the number of restarts in smatch Returns : ...
match_total = 0 test_total = 0 gold_total = 0 for fi in file_list : file1 = dir_pre + user1 + "/" + fi + ".txt" file2 = dir_pre + user2 + "/" + fi + ".txt" if not os . path . exists ( file1 ) : print ( "*********Error: " , file1 , "does not exist*********" , file = ERROR_LOG ) return - 1.00 ...
def run ( self , ) : """Start the configeditor : returns : None : rtype : None : raises : None"""
ra = SceneReleaseActions ( ) mayawin = maya_main_window ( ) self . rw = ReleaseWin ( FILETYPES [ "mayamainscene" ] , parent = mayawin ) self . rw . set_release_actions ( ra ) pm = MayaPluginManager . get ( ) genesis = pm . get_plugin ( "MayaGenesis" ) c = genesis . get_config ( ) try : f = models . TaskFile . objec...
def weights ( self ) : 'weights in the input basis ( encapsulated in an object )'
self . _check_estimated ( ) u_input = self . u return _KoopmanWeights ( u_input [ 0 : - 1 ] , u_input [ - 1 ] )
def prev ( self ) : """Fetch a set of items with IDs greater than current set ."""
if self . limit and self . limit == self . num_tweets : raise StopIteration self . index -= 1 if self . index < 0 : # There ' s no way to fetch a set of tweets directly ' above ' the # current set raise StopIteration data = self . results [ self . index ] self . max_id = self . model_results [ self . index ] . ...
def register ( cls , archive_table , engine ) : """: param archive _ table : the model for the users archive table : param engine : the database engine : param version _ col _ names : strings which correspond to columns that versioning will pivot around . These columns must have a unique constraint set on them ...
version_col_names = cls . version_columns if not version_col_names : raise LogTableCreationError ( 'Need to specify version cols in cls.version_columns' ) if cls . ignore_columns is None : cls . ignore_columns = set ( ) cls . ignore_columns . add ( 'version_id' ) version_cols = [ getattr ( cls , col_name , None...
def prt_summary_anno2ev ( self , associations , prt = sys . stdout ) : """Print annotation / evidence code summary ."""
ctr = cx . Counter ( ) for ntanno in associations : evidence_code = ntanno . Evidence_Code if 'NOT' not in ntanno . Qualifier : ctr [ evidence_code ] += 1 elif 'NOT' in ntanno . Qualifier : ctr [ "NOT {EV:3}" . format ( EV = ntanno . Evidence_Code ) ] += 1 else : raise Exception ...
def rest_equals ( self , rest_object ) : """Compare objects REST attributes"""
if not self . equals ( rest_object ) : return False return self . to_dict ( ) == rest_object . to_dict ( )
def mount_medium ( self , name , controller_port , device , medium , force ) : """Mounts a medium ( : py : class : ` IMedium ` , identified by the given UUID @ a id ) to the given storage controller ( : py : class : ` IStorageController ` , identified by @ a name ) , at the indicated port and device . The dev...
if not isinstance ( name , basestring ) : raise TypeError ( "name can only be an instance of type basestring" ) if not isinstance ( controller_port , baseinteger ) : raise TypeError ( "controller_port can only be an instance of type baseinteger" ) if not isinstance ( device , baseinteger ) : raise TypeError...
def get_json_tree_path ( self , * args , ** kwargs ) : """Return path to ricecooker json tree file . Override this method to use a custom filename , e . g . , for channel with multiple languages ."""
json_tree_path = os . path . join ( self . TREES_DATA_DIR , self . RICECOOKER_JSON_TREE ) return json_tree_path
def init ( self ) : """Performs a clone or a fetch , depending on whether the repository has been previously cloned or not ."""
if os . path . isdir ( self . path ) : self . fetch ( ) else : self . clone ( )
def position ( self , account , contract , position , avgCost ) : """position ( EWrapper self , IBString const & account , Contract contract , int position , double avgCost )"""
return _swigibpy . EWrapper_position ( self , account , contract , position , avgCost )
def np_array_datetime64_compat ( arr , * args , ** kwargs ) : """provide compat for construction of an array of strings to a np . array ( . . . , dtype = np . datetime64 ( . . ) ) tz - changes in 1.11 that make ' 2015-01-01 09:00:00Z ' show a deprecation warning , when need to pass ' 2015-01-01 09:00:00'"""
# is _ list _ like if ( hasattr ( arr , '__iter__' ) and not isinstance ( arr , ( str , bytes ) ) ) : arr = [ tz_replacer ( s ) for s in arr ] else : arr = tz_replacer ( arr ) return np . array ( arr , * args , ** kwargs )
def highlight ( self , search ) : """Add highlighting for all the fields"""
return search . highlight ( * ( f if '^' not in f else f . split ( '^' , 1 ) [ 0 ] for f in self . fields ) )
def toggleLongTouchView ( self ) : '''Toggles the long touch View operation . : return :'''
if not self . isLongTouchingView : msg = 'Long touching View' self . toast ( msg , background = Color . GREEN ) self . statusBar . set ( msg ) self . isLongTouchingView = True else : self . toast ( None ) self . statusBar . clear ( ) self . isLongTouchingView = False
def limit_chars ( function , * args , ** kwargs ) : """Truncate the string returned from a function and return the result ."""
output_chars_limit = args [ 0 ] . reddit_session . config . output_chars_limit output_string = function ( * args , ** kwargs ) if - 1 < output_chars_limit < len ( output_string ) : output_string = output_string [ : output_chars_limit - 3 ] + '...' return output_string
def paragraph_sub ( match ) : """Captures paragraphs ."""
text = re . sub ( r' \n' , r'\n<br/>\n' , match . group ( 0 ) . strip ( ) ) return '<p>{}</p>' . format ( text )
def send ( self , picture , * args ) : """Send a ' picture ' message to the socket ( or actor ) . The picture is a string that defines the type of each frame . This makes it easy to send a complex multiframe message in one call . The picture can contain any of these characters , each corresponding to one or t...
return lib . zsock_send ( self . _as_parameter_ , picture , * args )
def mutator ( arg = None ) : """Structures mutator functions by allowing handlers to be registered for different types of event . When the decorated function is called with an initial value and an event , it will call the handler that has been registered for that type of event . It works like singledispat...
domain_class = None def _mutator ( func ) : wrapped = singledispatch ( func ) @ wraps ( wrapped ) def wrapper ( initial , event ) : initial = initial or domain_class return wrapped . dispatch ( type ( event ) ) ( initial , event ) wrapper . register = wrapped . register return wrappe...
def tcp_reassembly ( packet , * , count = NotImplemented ) : """Store data for TCP reassembly ."""
if 'TCP' in packet : ip = packet [ 'IP' ] if 'IP' in packet else packet [ 'IPv6' ] tcp = packet [ 'TCP' ] data = dict ( bufid = ( ipaddress . ip_address ( ip . src ) , # source IP address ipaddress . ip_address ( ip . dst ) , # destination IP address tcp . sport , # source port tcp . dport , # d...
def get_fake_data ( * a ) : """Called whenever someone presses the " fire " button ."""
# add columns of data to the databox d [ 'x' ] = _n . linspace ( 0 , 10 , 100 ) d [ 'y' ] = _n . cos ( d [ 'x' ] ) + 0.1 * _n . random . rand ( 100 ) # update the curve c . setData ( d [ 'x' ] , d [ 'y' ] )
def at_time_validate ( ctx , param , value ) : """Callback validating the at _ time commit option . Purpose : Validates the ` at time ` option for the commit command . Only the | the following two formats are supported : ' hh : mm [ : ss ] ' or | ' yyyy - mm - dd hh : mm [ : ss ] ' ( seconds are optional ) . ...
# if they are doing commit _ at , ensure the input is formatted correctly . if value is not None : if ( re . search ( r'([0-2]\d)(:[0-5]\d){1,2}' , value ) is None and re . search ( r'\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d(:[0-5]\d)?' , value ) is None ) : raise click . BadParameter ( "A commit at time must b...
def _get_crop_target ( target_px : Union [ int , TensorImageSize ] , mult : int = None ) -> Tuple [ int , int ] : "Calc crop shape of ` target _ px ` to nearest multiple of ` mult ` ."
target_r , target_c = tis2hw ( target_px ) return _round_multiple ( target_r , mult ) , _round_multiple ( target_c , mult )
def save_all ( self ) : """Save all editors ."""
initial_index = self . currentIndex ( ) for i in range ( self . count ( ) ) : try : self . setCurrentIndex ( i ) self . save_current ( ) except AttributeError : pass self . setCurrentIndex ( initial_index )
def ld_mnist ( ) : """Load training and test data ."""
def convert_types ( image , label ) : image = tf . cast ( image , tf . float32 ) image /= 255 return image , label dataset , info = tfds . load ( 'mnist' , data_dir = 'gs://tfds-data/datasets' , with_info = True , as_supervised = True ) mnist_train , mnist_test = dataset [ 'train' ] , dataset [ 'test' ] mni...
def get_current ( self , channel ) : """channel : 1 = OP1 , 2 = OP2 , AUX is not supported"""
ret = self . ask ( "I%dO?" % channel ) if ret [ - 1 ] != "A" : print ( "ttiQl355tp.get_current() format error" , ret ) return None return float ( ret [ : - 1 ] )
def stop ( self ) : """Stop server process ."""
msg = '' if self . _process : _stop_process ( self . _process , 'Server process' ) else : msg += 'Server not started.\n' if msg : print ( msg , end = '' )
def _get_grouper ( obj , key = None , axis = 0 , level = None , sort = True , observed = False , mutated = False , validate = True ) : """create and return a BaseGrouper , which is an internal mapping of how to create the grouper indexers . This may be composed of multiple Grouping objects , indicating multip...
group_axis = obj . _get_axis ( axis ) # validate that the passed single level is compatible with the passed # axis of the object if level is not None : # TODO : These if - block and else - block are almost same . # MultiIndex instance check is removable , but it seems that there are # some processes only for non - Mult...
def _get_constraints ( self ) : """Get neighboring edges for each edge in the edges ."""
num_edges = len ( self . edges ) for k in range ( num_edges ) : for i in range ( num_edges ) : # add to constraints if i shared an edge with k if k != i and self . edges [ k ] . is_adjacent ( self . edges [ i ] ) : self . edges [ k ] . neighbors . append ( i )
def postpone ( self , record ) : """Postpone ( if required ) the given task . The real action is depended on task postpone policy : param record : record to postpone : return : None"""
maximum_records = self . maximum_records ( ) if maximum_records is not None and len ( self . __records ) >= maximum_records : record . task_dropped ( ) return task_policy = record . policy ( ) task_group_id = record . task_group_id ( ) if task_policy == WScheduleRecord . PostponePolicy . wait : self . __pos...
def update ( self , data , length = None ) : """Hashes given byte string @ param data - string to hash @ param length - if not specifed , entire string is hashed , otherwise only first length bytes"""
if self . digest_finalized : raise DigestError ( "No updates allowed" ) if not isinstance ( data , bintype ) : raise TypeError ( "A byte string is expected" ) if length is None : length = len ( data ) elif length > len ( data ) : raise ValueError ( "Specified length is greater than length of data" ) res...
def distance2_to_line ( pt , l0 , l1 ) : '''The perpendicular distance squared from a point to a line pt - point in question l0 - one point on the line l1 - another point on the line'''
pt = np . atleast_1d ( pt ) l0 = np . atleast_1d ( l0 ) l1 = np . atleast_1d ( l1 ) reshape = pt . ndim == 1 if reshape : pt . shape = l0 . shape = l1 . shape = ( 1 , pt . shape [ 0 ] ) result = ( ( ( l0 [ : , 0 ] - l1 [ : , 0 ] ) * ( l0 [ : , 1 ] - pt [ : , 1 ] ) - ( l0 [ : , 0 ] - pt [ : , 0 ] ) * ( l0 [ : , 1 ] ...
def split_css_for_ie_selector_limit ( input_file , output_file ) : """Splits a large CSS file into several smaller files , each one containing less than the IE 4096 selector limit ."""
from . modules import bless , utils if not isinstance ( input_file , str ) : raise RuntimeError ( 'CSS splitter takes only a single input file.' ) return { 'dependencies_fn' : utils . no_dependencies , 'compiler_fn' : bless . bless_css , 'input' : input_file , 'output' : output_file , 'kwargs' : { } , }
def plot_transit_model ( self , show = True , fold = None , ax = None ) : '''Plot the light curve de - trended with a join instrumental + transit model with the best fit transit model overlaid . The transit model should be specified using the : py : obj : ` transit _ model ` attribute and should be an instanc...
if self . transit_model is None : raise ValueError ( "No transit model provided!" ) if self . transit_depth is None : self . compute ( ) if fold is not None : if ( fold is True and len ( self . transit_model ) > 1 ) or ( type ( fold ) is not str ) : raise Exception ( "Kwarg `fold` should be the name...
def save ( self , commit = True , ** kwargs ) : """Saves the considered instances ."""
if self . post : for form in self . forms : form . instance . post = self . post super ( ) . save ( commit )
def find_reference_section_no_title_generic ( docbody , marker_patterns ) : """This function would generally be used when it was not possible to locate the start of a document ' s reference section by means of its title . Instead , this function will look for reference lines that have numeric markers of the f...
if not docbody : return None ref_start_line = ref_line_marker = None # try to find first reference line in the reference section : found_ref_sect = False for reversed_index , line in enumerate ( reversed ( docbody ) ) : mark_match = regex_match_list ( line . strip ( ) , marker_patterns ) if mark_match and m...