signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def list ( cls , state = None , page = None , per_page = None ) :
"""List existing clusters present in your account .
Kwargs :
` state ` : list only those clusters which are in this state
Returns :
List of clusters satisfying the given criteria""" | conn = Qubole . agent ( )
params = { }
if page :
params [ 'page' ] = page
if per_page :
params [ 'per_page' ] = per_page
if ( params . get ( 'page' ) or params . get ( 'per_page' ) ) and Qubole . version == 'v1.2' :
log . warn ( "Pagination is not supported with API v1.2. Fetching all clusters." )
params = ... |
def fit_model ( p , d , q , ts , includeIntercept = True , method = "css-cgd" , userInitParams = None , sc = None ) :
"""Given a time series , fit a non - seasonal ARIMA model of order ( p , d , q ) , where p represents
the autoregression terms , d represents the order of differencing , and q moving average error... | assert sc != None , "Missing SparkContext"
jvm = sc . _jvm
jmodel = jvm . com . cloudera . sparkts . models . ARIMA . fitModel ( p , d , q , _py2java ( sc , Vectors . dense ( ts ) ) , includeIntercept , method , _py2java_double_array ( sc , userInitParams ) )
return ARIMAModel ( jmodel = jmodel , sc = sc ) |
def keep_ ( self , * cols ) -> "Ds" :
"""Returns a dataswim instance with a dataframe limited
to some columns
: param cols : names of the columns
: type cols : str
: return : a dataswim instance
: rtype : Ds
: example : ` ` ds2 = ds . keep _ ( " Col 1 " , " Col 2 " ) ` `""" | try :
ds2 = self . _duplicate_ ( self . df [ list ( cols ) ] )
except Exception as e :
self . err ( e , "Can not remove colums" )
return
self . ok ( "Columns" , " ," . join ( cols ) , "kept" )
return ds2 |
def p_instance_bodylist ( self , p ) :
'instance _ bodylist : instance _ bodylist COMMA instance _ body' | p [ 0 ] = p [ 1 ] + ( p [ 3 ] , )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def extract_common_fields ( self , data ) :
"""Extract fields from a metadata query .""" | return dict ( dc = data . get ( 'dc' ) , role = data . get ( 'role' ) , account_name = data . get ( 'accountname' ) , user_id = data . get ( 'user_id' ) , login = data . get ( 'login' ) , login_url = data . get ( 'login_url' ) , api_endpoint = data . get ( 'api_endpoint' ) , ) |
def _viewset_results ( self ) :
"""Parse results from the viewset response .""" | results = [ ]
try :
response = self . _viewset_method ( self . _viewset . request , * self . _request . args , ** self . _request . kwargs )
if response . status_code == 200 :
results = response . data
if not isinstance ( results , list ) :
if isinstance ( results , dict ) : # XXX : ... |
def setCurrentDate ( self , date ) :
"""Sets the current date displayed by this calendar widget .
: return < QDate >""" | if ( date == self . _currentDate or not date . isValid ( ) ) :
return
self . _currentDate = date
self . markForRebuild ( )
parent = self . parent ( )
if ( not parent . signalsBlocked ( ) ) :
parent . currentDateChanged . emit ( date )
parent . titleChanged . emit ( self . title ( ) ) |
def _level_coords ( self ) :
"""Return a mapping of all MultiIndex levels and their corresponding
coordinate name .""" | level_coords = OrderedDict ( )
for cname , var in self . _coords . items ( ) :
if var . ndim == 1 and isinstance ( var , IndexVariable ) :
level_names = var . level_names
if level_names is not None :
dim , = var . dims
level_coords . update ( { lname : dim for lname in level_... |
def call_later ( self , delay : float , callback : Callable [ ... , None ] , * args : Any , ** kwargs : Any ) -> object :
"""Runs the ` ` callback ` ` after ` ` delay ` ` seconds have passed .
Returns an opaque handle that may be passed to ` remove _ timeout `
to cancel . Note that unlike the ` asyncio ` method... | return self . call_at ( self . time ( ) + delay , callback , * args , ** kwargs ) |
def dark_palette ( color , n_colors = 6 , reverse = False , as_cmap = False ) :
"""Make a palette that blends from a deep gray to ` color ` .
Parameters
color : matplotlib color
hex , rgb - tuple , or html color name
n _ colors : int , optional
number of colors in the palette
reverse : bool , optional
... | gray = "#222222"
colors = [ color , gray ] if reverse else [ gray , color ]
return blend_palette ( colors , n_colors , as_cmap ) |
def my_main ( context ) :
"""The starting point for your app .""" | print ( 'starting MyApp...' )
if context [ 'debug' ] :
print ( 'Context:' )
for k in context :
print ( 'Key: {}\nValue: {}' . format ( k , context [ k ] ) )
print ( 'Done!' )
return 0 |
def validate_rule_name ( self , name ) :
"""Validate rule name .
Arguments :
name ( string ) : Rule name .
Returns :
bool : ` ` True ` ` if rule name is valid .""" | if not name :
raise SerializerError ( "Rule name is empty" . format ( name ) )
if name [ 0 ] not in RULE_ALLOWED_START :
msg = "Rule name '{}' must starts with a letter"
raise SerializerError ( msg . format ( name ) )
for item in name :
if item not in RULE_ALLOWED_CHARS :
msg = ( "Invalid rule n... |
def _get_study_txt ( self , goid ) :
"""Get GO text from GOEA study .""" | if self . go2res is not None :
res = self . go2res . get ( goid , None )
if res is not None :
if self . study_items is not None :
return self . _get_item_str ( res )
else :
return self . pltvars . fmtres . format ( study_count = res . study_count ) |
def get_instance ( self , payload ) :
"""Build an instance of RoomRecordingInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . video . v1 . room . recording . RoomRecordingInstance
: rtype : twilio . rest . video . v1 . room . recording . RoomRecordingInstance""" | return RoomRecordingInstance ( self . _version , payload , room_sid = self . _solution [ 'room_sid' ] , ) |
def _parse_country_file ( self , cty_file , country_mapping_filename = None ) :
"""Parse the content of a PLIST file from country - files . com return the
parsed values in dictionaries .
Country - files . com provides Prefixes and Exceptions""" | import plistlib
cty_list = None
entities = { }
exceptions = { }
prefixes = { }
exceptions_index = { }
prefixes_index = { }
exceptions_counter = 0
prefixes_counter = 0
mapping = None
with open ( country_mapping_filename , "r" ) as f :
mapping = json . loads ( f . read ( ) , encoding = 'UTF-8' )
cty_list = plistlib .... |
def replace_simple_tags ( s , from_tag = 'italic' , to_tag = 'i' , to_open_tag = None ) :
"""Replace tags such as < italic > to < i >
This does not validate markup""" | if to_open_tag :
s = s . replace ( '<' + from_tag + '>' , to_open_tag )
elif to_tag :
s = s . replace ( '<' + from_tag + '>' , '<' + to_tag + '>' )
s = s . replace ( '<' + from_tag + '/>' , '<' + to_tag + '/>' )
else :
s = s . replace ( '<' + from_tag + '>' , '' )
s = s . replace ( '<' + from_tag + ... |
def sg_expand_dims ( tensor , opt ) :
r"""Inserts a new axis .
See tf . expand _ dims ( ) in tensorflow .
Args :
tensor : A ` Tensor ` ( automatically given by chain ) .
opt :
axis : Dimension to expand . Default is - 1.
name : If provided , it replaces current tensor ' s name .
Returns :
A ` Tensor... | opt += tf . sg_opt ( axis = - 1 )
return tf . expand_dims ( tensor , opt . axis , name = opt . name ) |
def parse ( self ) :
"""Parses a backup file header . Will be done automatically if
used together with the ' with ' statement""" | self . fp . seek ( 0 )
magic = self . fp . readline ( )
assert magic == b'ANDROID BACKUP\n'
self . version = int ( self . fp . readline ( ) . strip ( ) )
self . compression = CompressionType ( int ( self . fp . readline ( ) . strip ( ) ) )
self . encryption = EncryptionType ( self . fp . readline ( ) . strip ( ) . deco... |
def do_restart_role ( self , role ) :
"""Restart a role
Usage :
> restart _ role < role > Restarts this role""" | if not role :
return None
if not self . has_cluster ( ) :
return None
if '-' not in role :
print ( "Please enter a valid role name" )
return None
try :
service = api . get_cluster ( self . cluster ) . get_service ( role . split ( '-' ) [ 0 ] )
service . restart_roles ( role )
print ( "Restar... |
def onerror ( self , emitter , message , source , lineno , colno ) :
"""WebPage Event that occurs on webpage errors""" | super ( MyApp , self ) . onerror ( emitter , message , source , lineno , colno ) |
def get_interims_data ( self ) :
"""Returns a dictionary with the interims data""" | form = self . request . form
if 'item_data' not in form :
return { }
item_data = { }
if type ( form [ 'item_data' ] ) == list :
for i_d in form [ 'item_data' ] :
for i , d in json . loads ( i_d ) . items ( ) :
item_data [ i ] = d
return item_data
return json . loads ( form [ 'item_data' ... |
def param_fetch_one ( self , name ) :
'''initiate fetch of one parameter''' | try :
idx = int ( name )
self . mav . param_request_read_send ( self . target_system , self . target_component , "" , idx )
except Exception :
self . mav . param_request_read_send ( self . target_system , self . target_component , name , - 1 ) |
def module_is_imported ( modname , scope = None ) :
"""Checks if a module is imported within the current namespace .""" | # return early if modname is not even cached
if not module_is_in_cache ( modname ) :
return False
if scope is None : # use globals ( ) of the caller by default
scope = inspect . stack ( ) [ 1 ] [ 0 ] . f_globals
for m in scope . values ( ) :
if isinstance ( m , type ( sys ) ) and m . __name__ == modname :
... |
def _create_emitter ( self , event ) :
"""Create a method that emits an event of the same name .""" | if not hasattr ( self , event ) :
setattr ( self , event , lambda * args , ** kwargs : self . emit ( event , * args , ** kwargs ) ) |
def register_file_monitor ( filename , target = None ) :
"""Maps a specific file / directory modification event to a signal .
: param str | unicode filename : File or a directory to watch for its modification .
: param int | Signal | str | unicode target : Existing signal to raise
or Signal Target to register... | return _automate_signal ( target , func = lambda sig : uwsgi . add_file_monitor ( int ( sig ) , filename ) ) |
def default ( self , o ) :
"""JSONEncoder default method that converts NumPy arrays and quantities
objects to lists .""" | if isinstance ( o , Q_ ) :
return o . magnitude
elif isinstance ( o , np . ndarray ) :
return o . tolist ( )
else : # raise TypeError if not serializable
return super ( SimKitJSONEncoder , self ) . default ( o ) |
def main ( ) :
"""expected output :
1a2
aba
3a4""" | colorama . init ( )
print ( "aaa" )
print ( "aaa" )
print ( "aaa" )
print ( forward ( ) + up ( 2 ) + "b" + up ( ) + back ( 2 ) + "1" + forward ( ) + "2" + back ( 3 ) + down ( 2 ) + "3" + forward ( ) + "4" ) |
def run_pyspark_yarn_cluster ( env_dir , env_name , env_archive , args ) :
"""Initializes the requires spark command line options on order to start a python job with the given python environment .
Parameters
env _ dir : str
env _ name : str
env _ archive : str
args : list
Returns
This call will spawn ... | env = dict ( os . environ )
yarn_python = os . path . join ( "." , "CONDA" , env_name , "bin" , "python" )
archives = env_archive + "#CONDA"
prepend_args = [ "--master" , "yarn" , "--deploy-mode" , "cluster" , "--conf" , "spark.yarn.appMasterEnv.PYSPARK_PYTHON={}" . format ( yarn_python ) , "--archives" , archives , ]
... |
def missing_kegg_mapping ( self ) :
"""list : List of genes with no mapping to KEGG .""" | kegg_missing = [ ]
for g in self . genes :
keggs = g . protein . filter_sequences ( KEGGProp )
no_sequence_file_available = True
for k in keggs :
if k . sequence_file :
no_sequence_file_available = False
break
if no_sequence_file_available :
kegg_missing . append ... |
def DotProd ( self , other ) :
"""Returns the ( scalar ) dot product of self with other .""" | return self . x * other . x + self . y * other . y + self . z * other . z |
def get_percentage ( self ) :
"""Get the cumulative time percentage of each stopwatch ( including the current split ) .
Returns
cumulative _ elapsed _ time _ percentage : List [ float ]""" | cumulative_elapsed_time = self . get_cumulative_elapsed_time ( )
sum_elapsed_time = sum ( cumulative_elapsed_time , datetime . timedelta ( ) )
if not sum_elapsed_time :
raise ValueError ( "cannot get percentage if there is no any elapsed time" )
return [ div_timedelta ( t , sum_elapsed_time ) for t in cumulative_el... |
def get_coordination_of_site ( self , n ) :
"""Returns the number of neighbors of site n .
In graph terms , simply returns degree
of node corresponding to site n .
: param n : index of site
: return ( int ) :""" | number_of_self_loops = sum ( [ 1 for n , v in self . graph . edges ( n ) if n == v ] )
return self . graph . degree ( n ) - number_of_self_loops |
def add_monitor ( self , pattern , callback , limit = 80 ) :
"""Calls the given function whenever the given pattern matches the
buffer .
Arguments passed to the callback are the index of the match , and
the match object of the regular expression .
: type pattern : str | re . RegexObject | list ( str | re . ... | self . monitors . append ( [ to_regexs ( pattern ) , callback , 0 , limit ] ) |
def make_json_error ( error ) :
"""Handle errors by logging and""" | message = extract_error_message ( error )
status_code = extract_status_code ( error )
context = extract_context ( error )
retryable = extract_retryable ( error )
headers = extract_headers ( error )
# Flask will not log user exception ( fortunately ) , but will log an error
# for exceptions that escape out of the applic... |
def save_data ( self , trigger_id , ** data ) :
"""get the data from the service
: param trigger _ id : id of the trigger
: params data , dict
: rtype : dict""" | status = False
taiga = Taiga . objects . get ( trigger_id = trigger_id )
title = self . set_title ( data )
body = self . set_content ( data )
# add a ' story ' to the project
if taiga . project_name :
api = self . taiga_api ( )
new_project = api . projects . get_by_slug ( taiga . project_name )
userstory = ... |
def cmd ( send , msg , args ) :
"""Provides Metro Info .
Syntax : { command }""" | incidents = get_incidents ( args [ 'config' ] [ 'api' ] [ 'wmatakey' ] )
if not incidents :
send ( "No incidents found. Sure you picked the right metro system?" )
return
for t , i in incidents . items ( ) :
send ( "%s:" % get_type ( t ) )
for desc in i :
send ( desc ) |
def use_sequestered_composition_view ( self ) :
"""Pass through to provider CompositionLookupSession . use _ sequestered _ composition _ view""" | self . _containable_views [ 'composition' ] = SEQUESTERED
# self . _ get _ provider _ session ( ' composition _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_sequestered_composition_view ( )
except AttributeError :
... |
def _validate_slice ( self , start , end ) :
"""Validate start and end and return them as positive bit positions .""" | if start is None :
start = 0
elif start < 0 :
start += self . len
if end is None :
end = self . len
elif end < 0 :
end += self . len
if not 0 <= end <= self . len :
raise ValueError ( "end is not a valid position in the bitstring." )
if not 0 <= start <= self . len :
raise ValueError ( "start is... |
def add_static ( self , prefix : str , path : PathLike , * , name : Optional [ str ] = None , expect_handler : Optional [ _ExpectHandler ] = None , chunk_size : int = 256 * 1024 , show_index : bool = False , follow_symlinks : bool = False , append_version : bool = False ) -> AbstractResource :
"""Add static files v... | assert prefix . startswith ( '/' )
if prefix . endswith ( '/' ) :
prefix = prefix [ : - 1 ]
resource = StaticResource ( prefix , path , name = name , expect_handler = expect_handler , chunk_size = chunk_size , show_index = show_index , follow_symlinks = follow_symlinks , append_version = append_version )
self . reg... |
def send_offer_email ( self , offer_id , email_dict ) :
"""Sends an offer by email
If you want to send your email to more than one persons do :
' recipients ' : { ' to ' : [ ' bykof @ me . com ' , ' mbykovski @ seibert - media . net ' ] } }
: param offer _ id : the invoice id
: param email _ dict : the emai... | return self . _create_post_request ( resource = OFFERS , billomat_id = offer_id , send_data = email_dict , command = EMAIL , ) |
def mime ( self ) :
"""Produce the final MIME message .""" | author = self . author
sender = self . sender
if not author :
raise ValueError ( "You must specify an author." )
if not self . subject :
raise ValueError ( "You must specify a subject." )
if len ( self . recipients ) == 0 :
raise ValueError ( "You must specify at least one recipient." )
if not self . plain ... |
def connect ( username , password , host , heartbeats = ( 0 , 0 ) ) :
"""STOMP connect command .
username , password :
These are the needed auth details to connect to the
message server .
After sending this we will receive a CONNECTED
message which will contain our session id .""" | if len ( heartbeats ) != 2 :
raise ValueError ( 'Invalid heartbeat %r' % heartbeats )
cx , cy = heartbeats
return "CONNECT\naccept-version:1.1\nhost:%s\nheart-beat:%i,%i\nlogin:%s\npasscode:%s\n\n\x00\n" % ( host , cx , cy , username , password ) |
def _check_collections ( self ) :
"""Checks node local collection storage sizes""" | self . collection_sizes = { }
self . collection_total = 0
for col in self . db . collection_names ( include_system_collections = False ) :
self . collection_sizes [ col ] = self . db . command ( 'collstats' , col ) . get ( 'storageSize' , 0 )
self . collection_total += self . collection_sizes [ col ]
sorted_x =... |
def read_runtime_class ( self , name , ** kwargs ) :
"""read the specified RuntimeClass
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . read _ runtime _ class ( name , async _ req = True )
> > > result = thr... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . read_runtime_class_with_http_info ( name , ** kwargs )
else :
( data ) = self . read_runtime_class_with_http_info ( name , ** kwargs )
return data |
def project_role ( self , project , id ) :
"""Get a role Resource .
: param project : ID or key of the project to get the role from
: param id : ID of the role to get""" | if isinstance ( id , Number ) :
id = "%s" % id
return self . _find_for_resource ( Role , ( project , id ) ) |
def process_document ( self , doc ) :
"""Add your code for processing the document""" | descriptions = doc . select_segments ( "projects[*].description" )
projects = doc . select_segments ( "projects[*]" )
for d , p in zip ( descriptions , projects ) : # First phase of extraction
names = doc . extract ( self . name_extractor , d )
p . store ( names , "members" )
# Second phase of extraction
... |
def multiget ( client , keys , ** options ) :
"""Executes a parallel - fetch across multiple threads . Returns a list
containing : class : ` ~ riak . riak _ object . RiakObject ` or
: class : ` ~ riak . datatypes . Datatype ` instances , or 4 - tuples of
bucket - type , bucket , key , and the exception raised... | transient_pool = False
outq = Queue ( )
if 'pool' in options :
pool = options [ 'pool' ]
del options [ 'pool' ]
else :
pool = MultiGetPool ( )
transient_pool = True
try :
pool . start ( )
for bucket_type , bucket , key in keys :
task = Task ( client , outq , bucket_type , bucket , key , ... |
def _build_document_scrapers ( cls , session : AppSession ) :
'''Create the document scrapers .
Returns :
A list of document scrapers''' | html_parser = session . factory [ 'HTMLParser' ]
element_walker = session . factory . new ( 'ElementWalker' )
scrapers = [ session . factory . new ( 'HTMLScraper' , html_parser , element_walker , followed_tags = session . args . follow_tags , ignored_tags = session . args . ignore_tags , only_relative = session . args ... |
def headerData ( self , section , orientation , role = Qt . DisplayRole ) :
"""Qt Override .""" | if role == Qt . TextAlignmentRole :
if orientation == Qt . Horizontal :
return to_qvariant ( int ( Qt . AlignHCenter | Qt . AlignVCenter ) )
return to_qvariant ( int ( Qt . AlignRight | Qt . AlignVCenter ) )
if role != Qt . DisplayRole :
return to_qvariant ( )
if orientation == Qt . Horizontal :
... |
def bbt_simple_plot ( self ) :
"""Makes a simple bar plot with summed alignment counts for
each species , stacked .""" | # First , sum the different types of alignment counts
data = OrderedDict ( )
cats = OrderedDict ( )
for s_name in self . bbt_data :
data [ s_name ] = OrderedDict ( )
for org in self . bbt_data [ s_name ] :
data [ s_name ] [ org ] = self . bbt_data [ s_name ] [ org ] [ 'hits' ] - self . bbt_data [ s_name... |
def owner_profile ( self ) -> 'Profile' :
""": class : ` Profile ` instance of the Post ' s owner .""" | if not self . _owner_profile :
if 'username' in self . _node [ 'owner' ] :
owner_struct = self . _node [ 'owner' ]
else : # Sometimes , the ' owner ' structure does not contain the username , only the user ' s ID . In that case ,
# this call triggers downloading of the complete Post metadata struct ... |
def gradient ( self ) :
"""Gradient operator of the functional .""" | if self . operator is None :
return ConstantOperator ( self . vector , self . domain )
else :
if not self . operator . is_linear : # TODO : Acutally works otherwise , but needs more work
raise NotImplementedError ( '`operator` must be linear' )
# Figure out if operator is symmetric
opadjoint = s... |
def delete_templatetype ( type_id , template_i = None , ** kwargs ) :
"""Delete a template type and its typeattrs .""" | try :
tmpltype_i = db . DBSession . query ( TemplateType ) . filter ( TemplateType . id == type_id ) . one ( )
except NoResultFound :
raise ResourceNotFoundError ( "Template Type %s not found" % ( type_id , ) )
if template_i is None :
template_i = db . DBSession . query ( Template ) . filter ( Template . id... |
def naming_convention_columns ( self , convention = 'underscore' , remove_empty = True ) :
"""This will change the column names to a particular naming convention .
underscore : lower case all letters and replaces spaces with _
title : uppercase first letter and replaces _ with spaces
: param convention : str ... | converter = getattr ( self , '_%s_column' % convention , None )
assert converter is not None , 'Convention "%s" is not a valid convention' % convention
self . row_columns = [ converter ( col ) for col in self . row_columns ]
self . _columns = [ converter ( col ) for col in self . _columns ]
if remove_empty and '' in se... |
def stream_header ( self , f ) :
"""Stream the block header in the standard way to the file - like object f .""" | stream_struct ( "L##L" , f , self . version , self . previous_block_hash , self . merkle_root , self . height )
f . write ( b'\0' * 28 )
stream_struct ( "LL#S" , f , self . timestamp , self . difficulty , self . nonce , self . solution ) |
def write_desc ( self ) -> None :
"""Writes a description of the model to the exp _ dir .""" | path = os . path . join ( self . exp_dir , "model_description.txt" )
with open ( path , "w" ) as desc_f :
for key , val in self . __dict__ . items ( ) :
print ( "%s=%s" % ( key , val ) , file = desc_f )
import json
json_path = os . path . join ( self . exp_dir , "model_description.json" )
desc = { }
# type ... |
def done ( p_queue , host = None ) :
if host is not None :
return _path ( _c . FSQ_DONE , root = _path ( host , root = hosts ( p_queue ) ) )
'''Construct a path to the done dir for a queue''' | return _path ( p_queue , _c . FSQ_DONE ) |
def send ( self , message ) :
"puts a message in the outgoing queue ." | if not isinstance ( message , Message ) :
raise TypeError ( "message must be a Message" )
# end if
serial = ct . c_uint ( )
if not dbus . dbus_connection_send ( self . _dbobj , message . _dbobj , ct . byref ( serial ) ) :
raise CallFailed ( "dbus_connection_send" )
# end if
return serial . value |
def _get_system_volume ( vm_ ) :
'''Construct VM system volume list from cloud profile config''' | # Override system volume size if ' disk _ size ' is defined in cloud profile
disk_size = get_size ( vm_ ) [ 'disk' ]
if 'disk_size' in vm_ :
disk_size = vm_ [ 'disk_size' ]
# Construct the system volume
volume = Volume ( name = '{0} Storage' . format ( vm_ [ 'name' ] ) , size = disk_size , disk_type = get_disk_type... |
def remove_leading_spaces ( self , input_model ) :
"""This function is a part of the model post - processing pipeline . It
removes leading spaces from an extracted module ; depending on the
formatting of the draft / rfc text , may have multiple spaces prepended
to each line . The function also determines the ... | leading_spaces = 1024
output_model = [ ]
for mline in input_model :
line = mline [ 0 ]
if line . rstrip ( ' \r\n' ) != '' :
leading_spaces = min ( leading_spaces , len ( line ) - len ( line . lstrip ( ' ' ) ) )
output_model . append ( [ line [ leading_spaces : ] , mline [ 1 ] ] )
line_le... |
def _get_object ( data , position , obj_end , opts ) :
"""Decode a BSON subdocument to opts . document _ class or bson . dbref . DBRef .""" | obj_size = _UNPACK_INT ( data [ position : position + 4 ] ) [ 0 ]
end = position + obj_size - 1
if data [ end : position + obj_size ] != b"\x00" :
raise InvalidBSON ( "bad eoo" )
if end >= obj_end :
raise InvalidBSON ( "invalid object length" )
obj = _elements_to_dict ( data , position + 4 , end , opts , subdoc... |
def parameters ( self ) :
"""Get parameters of transform""" | libfn = utils . get_lib_fn ( 'getTransformParameters%s' % self . _libsuffix )
return np . asarray ( libfn ( self . pointer ) , order = 'F' ) |
def load ( manager , units = 80 ) :
"""Simulate loading services from a remote node
States are connecting ( red ) , loading ( yellow ) , and loaded ( green )""" | pb_connecting = manager . counter ( total = units , desc = 'Loading' , unit = 'services' , color = 'red' , bar_format = BAR_FMT )
pb_loading = pb_connecting . add_subcounter ( 'yellow' )
pb_loaded = pb_connecting . add_subcounter ( 'green' , all_fields = True )
connecting = [ ]
loading = [ ]
loaded = [ ]
count = 0
whil... |
def load_experiment ( folder , return_path = False ) :
'''load _ experiment :
reads in the config . json for a folder , returns None if not found .
: param folder : full path to experiment folder
: param return _ path : if True , don ' t load the config . json , but return it''' | fullpath = os . path . abspath ( folder )
config = "%s/config.json" % ( fullpath )
if not os . path . exists ( config ) :
bot . error ( "config.json could not be found in %s" % ( folder ) )
config = None
if return_path is False and config is not None :
config = read_json ( config )
return config |
def send_calibrate_accelerometer ( self , simple = False ) :
"""Request accelerometer calibration .
: param simple : if True , perform simple accelerometer calibration""" | calibration_command = self . message_factory . command_long_encode ( self . _handler . target_system , 0 , # target _ system , target _ component
mavutil . mavlink . MAV_CMD_PREFLIGHT_CALIBRATION , # command
0 , # confirmation
0 , # param 1 , 1 : gyro calibration , 3 : gyro temperature calibration
0 , # param 2 , 1 : m... |
def merge ( self , other , overlap = 'error' ) :
"""Merge content of other IntelHex object into current object ( self ) .
@ param other other IntelHex object .
@ param overlap action on overlap of data or starting addr :
- error : raising OverlapError ;
- ignore : ignore other data and keep current data
i... | # check args
if not isinstance ( other , IntelHex ) :
raise TypeError ( 'other should be IntelHex object' )
if other is self :
raise ValueError ( "Can't merge itself" )
if overlap not in ( 'error' , 'ignore' , 'replace' ) :
raise ValueError ( "overlap argument should be either " "'error', 'ignore' or 'repla... |
def start ( main_gui_class , ** kwargs ) :
"""This method starts the webserver with a specific App subclass .""" | debug = kwargs . pop ( 'debug' , False )
standalone = kwargs . pop ( 'standalone' , False )
logging . basicConfig ( level = logging . DEBUG if debug else logging . INFO , format = '%(name)-16s %(levelname)-8s %(message)s' )
logging . getLogger ( 'remi' ) . setLevel ( level = logging . DEBUG if debug else logging . INFO... |
def add ( self , id , obj , criteria = { } , force = False , _check_id = True ) :
"""Add a : class : ` Component < cqparts . Component > ` instance to the database .
: param id : unique id of entry , can be anything
: type id : : class : ` str `
: param obj : component to be serialized , then added to the cat... | # Verify component
if not isinstance ( obj , Component ) :
raise TypeError ( "can only add(%r), component is a %r" % ( Component , type ( obj ) ) )
# Serialize object
obj_data = obj . serialize ( )
# Add to database
q = tinydb . Query ( )
if ( force or _check_id ) and self . items . count ( q . id == id ) :
if ... |
def create_markdown_cell ( block ) :
"""Create a markdown cell from a block .""" | kwargs = { 'cell_type' : block [ 'type' ] , 'source' : block [ 'content' ] }
markdown_cell = nbbase . new_markdown_cell ( ** kwargs )
return markdown_cell |
def convert_to_string ( self , block ) :
"""Takes a list of SeqRecordExpanded objects corresponding to a gene _ code
and produces the gene _ block as string .
: param block :
: return : str .""" | if self . aminoacids :
molecule_type = "protein"
else :
molecule_type = "dna"
out = None
for seq_record in block :
if not out :
out = '&[{0}]\n' . format ( molecule_type , seq_record . gene_code )
taxon_id = '{0}_{1}_{2}' . format ( seq_record . voucher_code , seq_record . taxonomy [ 'genus' ] ,... |
def book_reservation ( self , sessionid , roomid , start , end ) :
"""Book a reservation given the session id , the room id as an integer , and the start and end time as datetimes .""" | duration = int ( ( end - start ) . seconds / 60 )
format = "%Y-%m-%dT%H:%M:%S-{}" . format ( self . get_dst_gmt_timezone ( ) )
booking_url = "{}/reserve/{}/{}/?d={}" . format ( BASE_URL , roomid , start . strftime ( format ) , duration )
resp = requests . get ( booking_url , cookies = { "sessionid" : sessionid } )
if r... |
def simple_atmo ( rgb , haze , contrast , bias ) :
"""A simple , static ( non - adaptive ) atmospheric correction function .
Parameters
haze : float
Amount of haze to adjust for . For example , 0.03
contrast : integer
Enhances the intensity differences between the lighter and darker
elements of the imag... | gamma_b = 1 - haze
gamma_g = 1 - ( haze / 3.0 )
arr = np . empty ( shape = ( 3 , rgb . shape [ 1 ] , rgb . shape [ 2 ] ) )
arr [ 0 ] = rgb [ 0 ]
arr [ 1 ] = gamma ( rgb [ 1 ] , gamma_g )
arr [ 2 ] = gamma ( rgb [ 2 ] , gamma_b )
output = rgb . copy ( )
output [ 0 : 3 ] = sigmoidal ( arr , contrast , bias )
return outpu... |
def hybrid_forward ( self , F , inputs , states , i2h_weight , h2h_weight , h2r_weight , i2h_bias , h2h_bias ) :
r"""Hybrid forward computation for Long - Short Term Memory Projected network cell
with cell clip and projection clip .
Parameters
inputs : input tensor with shape ` ( batch _ size , input _ size )... | prefix = 't%d_' % self . _counter
i2h = F . FullyConnected ( data = inputs , weight = i2h_weight , bias = i2h_bias , num_hidden = self . _hidden_size * 4 , name = prefix + 'i2h' )
h2h = F . FullyConnected ( data = states [ 0 ] , weight = h2h_weight , bias = h2h_bias , num_hidden = self . _hidden_size * 4 , name = prefi... |
def set_wv_parameters ( filter_name , grism_name ) :
"""Set wavelength calibration parameters for rectified images .
Parameters
filter _ name : str
Filter name .
grism _ name : str
Grism name .
Returns
wv _ parameters : dictionary
Python dictionary containing relevant wavelength calibration
parame... | # protections
if filter_name not in EMIR_VALID_FILTERS :
raise ValueError ( 'Unexpected filter_name:' , filter_name )
if grism_name not in EMIR_VALID_GRISMS :
raise ValueError ( 'Unexpected grism_name:' , grism_name )
# intialize output
wv_parameters = { }
# set parameters
wv_parameters [ 'crpix1_enlarged' ] = ... |
def describe_field ( field_definition ) :
"""Build descriptor for Field instance .
Args :
field _ definition : Field instance to provide descriptor for .
Returns :
Initialized FieldDescriptor instance describing the Field instance .""" | field_descriptor = FieldDescriptor ( )
field_descriptor . name = field_definition . name
field_descriptor . number = field_definition . number
field_descriptor . variant = field_definition . variant
if isinstance ( field_definition , messages . EnumField ) :
field_descriptor . type_name = field_definition . type . ... |
def remove ( self , record ) :
"""Remove a reference to the provided record""" | self . _field . validate_value ( record )
del self . _elements [ record . id ]
self . _sync_field ( ) |
def iter_items ( cls , repo , rev , paths = '' , ** kwargs ) :
"""Find all commits matching the given criteria .
: param repo : is the Repo
: param rev : revision specifier , see git - rev - parse for viable options
: param paths :
is an optional path or list of paths , if set only Commits that include the ... | if 'pretty' in kwargs :
raise ValueError ( "--pretty cannot be used as parsing expects single sha's only" )
# END handle pretty
# use - - in any case , to prevent possibility of ambiguous arguments
# see https : / / github . com / gitpython - developers / GitPython / issues / 264
args = [ '--' ]
if paths :
args... |
def update_license ( self , license_text ) :
"""Install or update the Cloudera Manager license .
@ param license _ text : the license in text form""" | content = ( '--MULTI_BOUNDARY' , 'Content-Disposition: form-data; name="license"' , '' , license_text , '--MULTI_BOUNDARY--' , '' )
resp = self . _get_resource_root ( ) . post ( 'cm/license' , data = "\r\n" . join ( content ) , contenttype = 'multipart/form-data; boundary=MULTI_BOUNDARY' )
return ApiLicense . from_json... |
def device_by_load ( wproc = 0.5 , wmem = 0.5 ) :
"""Get a list of GPU device ids ordered by increasing weighted
average of processor and memory load .""" | gl = gpu_load ( wproc = wproc , wmem = wmem )
# return np . argsort ( np . asarray ( gl ) [ : , - 1 ] ) . tolist ( )
return [ idx for idx , load in sorted ( enumerate ( [ g . weighted for g in gl ] ) , key = ( lambda x : x [ 1 ] ) ) ] |
def runCommand ( command ) :
"""Run a command .
: param command : the command to run .
: type command : list
Tries to run a command . If it fails , raise a : py : class : ` ProgramError ` . This
function uses the : py : mod : ` subprocess ` module .
. . warning : :
The variable ` ` command ` ` should be... | output = None
try :
output = subprocess . check_output ( command , stderr = subprocess . STDOUT , shell = False , )
except subprocess . CalledProcessError :
msg = "couldn't run command\n" + " " . join ( command )
raise ProgramError ( msg ) |
def merge_directories ( self , directory_digests ) :
"""Merges any number of directories .
: param directory _ digests : Tuple of DirectoryDigests .
: return : A Digest .""" | result = self . _native . lib . merge_directories ( self . _scheduler , self . _to_value ( _DirectoryDigests ( directory_digests ) ) , )
return self . _raise_or_return ( result ) |
def create_app ( config ) :
"""Create a fully configured Celery application object .
Args :
config ( Config ) : A reference to a lightflow configuration object .
Returns :
Celery : A fully configured Celery application object .""" | # configure the celery logging system with the lightflow settings
setup_logging . connect ( partial ( _initialize_logging , config ) , weak = False )
task_postrun . connect ( partial ( _cleanup_workflow , config ) , weak = False )
# patch Celery to use cloudpickle instead of pickle for serialisation
patch_celery ( )
# ... |
def getinputencoding ( stream = None ) :
"""Return preferred encoding for reading from ` ` stream ` ` .
` ` stream ` ` defaults to sys . stdin .""" | if stream is None :
stream = sys . stdin
encoding = stream . encoding
if not encoding :
encoding = getpreferredencoding ( )
return encoding |
def _get_deployment_instance_diagnostics ( awsclient , deployment_id , instance_id ) :
"""Gets you the diagnostics details for the first ' Failed ' event .
: param awsclient :
: param deployment _ id :
: param instance _ id :
return : None or ( error _ code , script _ name , message , log _ tail )""" | client_codedeploy = awsclient . get_client ( 'codedeploy' )
request = { 'deploymentId' : deployment_id , 'instanceId' : instance_id }
response = client_codedeploy . get_deployment_instance ( ** request )
# find first ' Failed ' event
for i , event in enumerate ( response [ 'instanceSummary' ] [ 'lifecycleEvents' ] ) :
... |
def cli_info ( data , title = 'Info' ) :
'''Prints an info on CLI with the title .
Useful for infos , general errors etc .
: param data :
: param title :
: return :''' | wrapper = textwrap . TextWrapper ( )
wrapper . initial_indent = ' ' * 4
wrapper . subsequent_indent = wrapper . initial_indent
return '{title}:\n\n{text}' . format ( title = title , text = wrapper . fill ( data ) ) |
def help ( ) :
"""List all targets""" | print ( "Please use '{} <target>' where <target> is one of" . format ( sys . argv [ 0 ] ) )
width = max ( len ( name ) for name in TARGETS )
for name , target in TARGETS . items ( ) :
print ( ' {name:{width}} {descr}' . format ( name = name , width = width , descr = target . __doc__ ) ) |
def copy_file_if_update_required ( source_file , target_file ) :
"""Copies source _ file to target _ file if latter one in not existing or outdated
: param source _ file : Source file of the copy operation
: param target _ file : Target file of the copy operation""" | if file_needs_update ( target_file , source_file ) :
shutil . copy ( source_file , target_file ) |
def get_vcs_details_output_vcs_details_local_switch_wwn ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vcs_details = ET . Element ( "get_vcs_details" )
config = get_vcs_details
output = ET . SubElement ( get_vcs_details , "output" )
vcs_details = ET . SubElement ( output , "vcs-details" )
local_switch_wwn = ET . SubElement ( vcs_details , "local-switch-wwn" )
local_switch_wwn . tex... |
def weld_standard_deviation ( array , weld_type ) :
"""Returns the * sample * standard deviation of the array .
Parameters
array : numpy . ndarray or WeldObject
Input array .
weld _ type : WeldType
Type of each element in the input array .
Returns
WeldObject
Representation of this computation .""" | weld_obj_var = weld_variance ( array , weld_type )
obj_id , weld_obj = create_weld_object ( weld_obj_var )
weld_obj_var_id = get_weld_obj_id ( weld_obj , weld_obj_var )
weld_template = _weld_std_code
weld_obj . weld_code = weld_template . format ( var = weld_obj_var_id )
return weld_obj |
def FDMT_iteration ( datain , maxDT , nchan0 , f_min , f_max , iteration_num , dataType ) :
"""Input :
Input - 3d array , with dimensions [ nint , N _ d0 , nbl , nchan , npol ]
f _ min , f _ max - are the base - band begin and end frequencies .
The frequencies can be entered in both MHz and GHz , units are fa... | nint , dT , nbl , nchan , npol = datain . shape
# output _ dims = list ( input _ dims )
deltaF = 2 ** ( iteration_num ) * ( f_max - f_min ) / float ( nchan0 )
dF = ( f_max - f_min ) / float ( nchan0 )
# the maximum deltaT needed to calculate at the i ' th iteration
deltaT = int ( np . ceil ( ( maxDT - 1 ) * ( 1. / f_mi... |
def echo ( * args , ** kwargs ) :
"""Write a message to a file .
Arguments :
args A list of arguments which make up the message . The last argument
is the path to the file to write to .""" | msg = args [ : - 1 ]
path = fs . path ( args [ - 1 ] )
append = kwargs . pop ( "append" , False )
if append :
with open ( path , "a" ) as file :
print ( * msg , file = file , ** kwargs )
else :
with open ( fs . path ( path ) , "w" ) as file :
print ( * msg , file = file , ** kwargs ) |
def _calc_adu ( self ) :
"""Apply DAFs if existing for the buffer .""" | res = super ( ) . _calc_adu ( )
self . ensure_one ( )
dafs_to_apply = self . env [ 'ddmrp.adjustment' ] . search ( self . _daf_to_apply_domain ( ) )
if dafs_to_apply :
daf = 1
values = dafs_to_apply . mapped ( 'value' )
for val in values :
daf *= val
prev = self . adu
self . adu *= daf
_... |
def _hexdecode ( hexstring ) :
"""Convert a hex encoded string to a byte string .
For example ' 4A ' will return ' J ' , and ' 04 ' will return ` ` ' \\ x04 ' ` ` ( which has length 1 ) .
Args :
hexstring ( str ) : Can be for example ' A3 ' or ' A3B4 ' . Must be of even length .
Allowed characters are ' 0 '... | # Note : For Python3 the appropriate would be : raise TypeError ( new _ error _ message ) from err
# but the Python2 interpreter will indicate SyntaxError .
# Thus we need to live with this warning in Python3:
# ' During handling of the above exception , another exception occurred '
_checkString ( hexstring , descripti... |
def generate_confirmation_token ( self , user ) :
"""Generates a unique confirmation token for the specified user .
: param user : The user to work with""" | data = [ str ( user . id ) , self . hash_data ( user . email ) ]
return self . security . confirm_serializer . dumps ( data ) |
def Kdiag ( self , X ) :
"""Compute the diagonal of the covariance matrix associated to X .""" | ret = np . empty ( X . shape [ 0 ] )
ret [ : ] = self . variance
return ret |
def submit_metric ( self , name , snmp_value , forced_type , tags = None ) :
'''Convert the values reported as pysnmp - Managed Objects to values and
report them to the aggregator''' | tags = [ ] if tags is None else tags
if reply_invalid ( snmp_value ) : # Metrics not present in the queried object
self . log . warning ( "No such Mib available: {}" . format ( name ) )
return
metric_name = self . normalize ( name , prefix = "snmp" )
if forced_type :
if forced_type . lower ( ) == "gauge" :
... |
def _serve_file ( self , path ) :
"""Call Paste ' s FileApp ( a WSGI application ) to serve the file
at the specified path""" | static = PkgResourcesParser ( 'pylons' , 'pylons' )
request . environ [ 'PATH_INFO' ] = '/%s' % path
return static ( request . environ , self . start_response ) |
def strip_number ( self ) :
"""The number of the strip that has changed state ,
with 0 being the first strip .
On tablets with only one strip , this method always returns 0.
For events not of type
: attr : ` ~ libinput . constant . EventType . TABLET _ PAD _ STRIP ` , this property
raises : exc : ` Attrib... | if self . type != EventType . TABLET_PAD_STRIP :
raise AttributeError ( _wrong_prop . format ( self . type ) )
return self . _libinput . libinput_event_tablet_pad_get_strip_number ( self . _handle ) |
def client_connected_callback ( self , reader , writer ) :
"""Handle connected client .""" | peer = writer . get_extra_info ( 'peername' )
clients . append ( ( reader , writer , peer ) )
log . info ( "Incoming connection from: %s:%s" , peer [ 0 ] , peer [ 1 ] )
try :
while True :
data = yield from reader . readline ( )
if not data :
break
try :
line = data . ... |
def alarm_disable ( self ) :
"""disable the alarm""" | log . debug ( "alarm => disable..." )
params = { "enabled" : False }
self . _app_exec ( "com.lametric.clock" , "clock.alarm" , params = params ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.