signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def find_or_upsert ( self , constructor , props , * , comp = None , return_status = False ) :
"""This finds or upserts a model with an auto primary key , and is a bit more flexible than
find _ or _ create .
First it looks for the model matching either comp , or props if comp is None .
If not found , it will t... | model = self . find_model ( constructor , comp or props )
status = _UPSERT_STATUS_FOUND
if model is None :
model = constructor ( ** props )
status = _UPSERT_STATUS_CREATED
self . insert_model ( model , upsert = Upsert ( Upsert . DO_NOTHING ) )
if model . is_new :
model = self . find_model ( cons... |
def _get_or_insert_async ( * args , ** kwds ) :
"""Transactionally retrieves an existing entity or creates a new one .
This is the asynchronous version of Model . _ get _ or _ insert ( ) .""" | # NOTE : The signature is really weird here because we want to support
# models with properties named e . g . ' cls ' or ' name ' .
from . import tasklets
cls , name = args
# These must always be positional .
get_arg = cls . __get_arg
app = get_arg ( kwds , 'app' )
namespace = get_arg ( kwds , 'namespace' )
parent = ge... |
def toxml ( self ) :
"""Exports this object into a LEMS XML object""" | # Probably name should be removed altogether until its usage is decided , see
# https : / / github . com / LEMS / LEMS / issues / 4
# ' ' ' ( ' name = " { 0 } " ' . format ( self . name ) if self . name else ' ' ) + \ ' ' '
return '<Unit' + ( ' symbol = "{0}"' . format ( self . symbol ) if self . symbol else '' ) + ( '... |
def fixed_interval_scheduler ( interval ) :
"""A scheduler that ticks at fixed intervals of " interval " seconds""" | start = time . time ( )
next_tick = start
while True :
next_tick += interval
yield next_tick |
def get_term_and_background_counts ( self ) :
'''Returns
A pd . DataFrame consisting of unigram term counts of words occurring
in the TermDocumentMatrix and their corresponding background corpus
counts . The dataframe has two columns , corpus and background .
> > > corpus . get _ unigram _ corpus ( ) . get ... | background_df = self . _get_background_unigram_frequencies ( )
corpus_freq_df = self . get_term_count_df ( )
corpus_unigram_freq = self . _get_corpus_unigram_freq ( corpus_freq_df )
df = corpus_unigram_freq . join ( background_df , how = 'outer' ) . fillna ( 0 )
del df . index . name
return df |
def Refresh ( self , autoRelogin = False , dumpXml = YesOrNo . FALSE ) :
"""Sends the aaaRefresh query to the UCS to refresh the connection ( to prevent session expiration ) .""" | self . _Stop_refresh_timer ( )
response = self . AaaRefresh ( self . _username , self . _password , dumpXml )
if ( response . errorCode != 0 ) :
self . _cookie = None
if ( autoRelogin ) :
return self . Login ( self . _name , self . _username , self . _password , self . _noSsl , self . _port , dumpXml , ... |
def import_submodules ( module ) :
"""Import all submodules and make them available in a dict .""" | submodules = { }
for loader , name , ispkg in pkgutil . iter_modules ( module . __path__ , module . __name__ + '.' ) :
try :
submodule = import_module ( name )
except ImportError as e : # FIXME : Make the errors non - fatal ( do we want that ? ) .
logging . warning ( "Error importing %s" , name ... |
def check ( self ) :
"""Check for validity .
: raises ValueError :
- if not all lines are as long as the : attr : ` number of needles
< AYABInterface . machines . Machine . number _ of _ needles > `
- if the contents of the rows are not : attr : ` needle positions
< AYABInterface . machines . Machine . ne... | # TODO : This violates the law of demeter .
# The architecture should be changed that this check is either
# performed by the machine or by the unity of machine and
# carriage .
expected_positions = self . _machine . needle_positions
expected_row_length = self . _machine . number_of_needles
for row_index , row in enume... |
def hasPublicNet ( self , system_name ) :
"""Return true if some system has a public network .""" | nets_id = [ net . id for net in self . networks if net . isPublic ( ) ]
system = self . get_system_by_name ( system_name )
if system :
i = 0
while True :
f = system . getFeature ( "net_interface.%d.connection" % i )
if not f :
break
if f . value in nets_id :
retur... |
def parse_sql ( self , asql ) :
"""Executes all sql statements from asql .
Args :
library ( library . Library ) :
asql ( str ) : ambry sql query - see https : / / github . com / CivicKnowledge / ambry / issues / 140 for details .""" | import sqlparse
statements = sqlparse . parse ( sqlparse . format ( asql , strip_comments = True ) )
parsed_statements = [ ]
for statement in statements :
statement_str = statement . to_unicode ( ) . strip ( )
for preprocessor in self . _backend . sql_processors ( ) :
statement_str = preprocessor ( stat... |
def zeroize_crypto_domain ( self , crypto_adapter , crypto_domain_index ) :
"""Zeroize a single crypto domain on a crypto adapter .
Zeroizing a crypto domain clears the cryptographic keys and
non - compliance mode settings in the crypto domain .
The crypto domain must be attached to this partition in " contro... | body = { 'crypto-adapter-uri' : crypto_adapter . uri , 'domain-index' : crypto_domain_index }
self . manager . session . post ( self . uri + '/operations/zeroize-crypto-domain' , body ) |
def patches ( self , basemap , simplify = None , predicate = None , args_f = None , ** kwargs ) :
"""Return geodata as a list of Matplotlib patches
: param basemap : A mpl _ toolkits . basemap . Basemap
: param simplify : Integer or None . Simplify the geometry to a tolerance , in the units of the geometry .
... | from descartes import PolygonPatch
from shapely . wkt import loads
from shapely . ops import transform
if not predicate :
predicate = lambda row : True
def map_xform ( x , y , z = None ) :
return basemap ( x , y )
def make_patch ( shape , row ) :
args = dict ( kwargs . items ( ) )
if args_f :
ar... |
def bind_bottom_up ( lower , upper , __fval = None , ** fval ) :
"""Bind 2 layers for dissection .
The upper layer will be chosen for dissection on top of the lower layer , if
ALL the passed arguments are validated . If multiple calls are made with the same # noqa : E501
layers , the last one will be used as ... | if __fval is not None :
fval . update ( __fval )
lower . payload_guess = lower . payload_guess [ : ]
lower . payload_guess . append ( ( fval , upper ) ) |
def get_page ( self , url ) :
"""Get a page of items from API""" | if url :
data = self . feed . _request ( url , offset = self . _offset , since = self . _since , before = self . _before )
# set values to False to avoid using them for next request
self . _before = False if self . _before is not None else None
self . _since = False if self . _since is not None else Non... |
def _ros_read_images ( self , stream_buffer , number , staleness_limit = 10. ) :
"""Reads images from a stream buffer
Parameters
stream _ buffer : string
absolute path to the image buffer service
number : int
The number of frames to get . Must be less than the image buffer service ' s
current buffer siz... | rospy . wait_for_service ( stream_buffer , timeout = self . timeout )
ros_image_buffer = rospy . ServiceProxy ( stream_buffer , ImageBuffer )
ret = ros_image_buffer ( number , 1 )
if not staleness_limit == None :
if ret . timestamps [ - 1 ] > staleness_limit :
raise RuntimeError ( "Got data {0} seconds old,... |
def get_conditions ( self ) :
"""get conditions through which the pod has passed
: return : list of PodCondition enum or empty list""" | # filter just values that are true ( means that pod has that condition right now )
return [ PodCondition . get_from_string ( c . type ) for c in self . get_status ( ) . conditions if c . status == 'True' ] |
def draw_png ( self , image , h_zoom , v_zoom , current_y ) :
"""Draw this waveform to PNG .
: param image : the image to draw onto
: param int h _ zoom : the horizontal zoom
: param int v _ zoom : the vertical zoom
: param int current _ y : the current y offset , in modules
: type image : : class : ` PIL... | draw = ImageDraw . Draw ( image )
mws = self . rconf . mws
rate = self . audio_file . audio_sample_rate
samples = self . audio_file . audio_samples
duration = self . audio_file . audio_length
current_y_px = current_y * v_zoom
half_waveform_px = ( self . height // 2 ) * v_zoom
zero_y_px = current_y_px + half_waveform_px... |
def day_events_card ( date ) :
"""Displays Events that happened on the supplied date .
` date ` is a date object .""" | d = date . strftime ( app_settings . DATE_FORMAT )
card_title = 'Events on {}' . format ( d )
return { 'card_title' : card_title , 'event_list' : day_events ( date = date ) , } |
def parse_request ( api_secret , reqbody , dec_func = False ) :
"""> > > parse _ request ( " 123456 " , ' { " nonce " : 1451122677 , " msg " : " helllo " , " code " : 0 , " sign " : " DB30F4D1112C20DFA736F65458F89C64 " } ' )
< Storage { u ' nonce ' : 1451122677 , u ' msg ' : u ' helllo ' , u ' code ' : 0 , u ' si... | try :
if type ( reqbody ) == type ( dict ) :
return self . parse_form_request ( reqbody )
if callable ( dec_func ) :
req_msg = json . loads ( dec_func ( reqbody ) )
else :
req_msg = json . loads ( reqbody )
except Exception as err :
raise ParseError ( u"parse params error" )
if n... |
def NS ( s , o ) :
"""Nash Sutcliffe efficiency coefficient
input :
s : simulated
o : observed
output :
ns : Nash Sutcliffe efficient coefficient""" | # s , o = filter _ nan ( s , o )
return 1 - np . sum ( ( s - o ) ** 2 ) / np . sum ( ( o - np . mean ( o ) ) ** 2 ) |
def add_to_cache ( cls , remote_info , container ) : # pylint : disable = g - bad - name
"""Adds a ResourceContainer to a cache tying it to a protorpc method .
Args :
remote _ info : Instance of protorpc . remote . _ RemoteMethodInfo corresponding
to a method .
container : An instance of ResourceContainer .... | if not isinstance ( container , cls ) :
raise TypeError ( '%r not an instance of %r, could not be added to cache.' % ( container , cls ) )
if remote_info in cls . __remote_info_cache :
raise KeyError ( 'Cache has collision but should not.' )
cls . __remote_info_cache [ remote_info ] = container |
def keywords ( s , top = 10 , ** kwargs ) :
"""Returns a sorted list of keywords in the given string .""" | return parser . find_keywords ( s , top = top , frequency = parser . frequency ) |
def extract_backup_bundle ( self , resource , timeout = - 1 ) :
"""Extracts the existing backup bundle on the appliance and creates all the artifacts .
Args :
resource ( dict ) : Deployment Group to extract .
timeout :
Timeout in seconds . Waits for task completion by default . The timeout does not abort th... | return self . _client . update ( resource , uri = self . BACKUP_ARCHIVE_PATH , timeout = timeout ) |
def create ( backbone : ModelFactory , vmin : float , vmax : float , atoms : int , input_block : typing . Optional [ ModelFactory ] = None ) :
"""Vel factory function""" | if input_block is None :
input_block = IdentityFactory ( )
return QDistributionalModelFactory ( input_block = input_block , backbone = backbone , vmin = vmin , vmax = vmax , atoms = atoms ) |
def periodic ( period , drain_timeout = _DEFAULT_DRAIN , reset_timeout = _DEFAULT_RESET , max_consecutive_attempts = _DEFAULT_ATTEMPTS ) :
"""Create a periodic consistent region configuration .
The IBM Streams runtime will trigger a drain and checkpoint
the region periodically at the time interval specified by ... | return ConsistentRegionConfig ( trigger = ConsistentRegionConfig . Trigger . PERIODIC , period = period , drain_timeout = drain_timeout , reset_timeout = reset_timeout , max_consecutive_attempts = max_consecutive_attempts ) |
def contour ( f , vertexlabels = None , ** kwargs ) :
'''Contour line plot on a 2D triangle of a function evaluated at
barycentric 2 - simplex points .
: param f : Function to evaluate on N x 3 ndarray of coordinates
: type f : ` ` ufunc ` `
: param vertexlabels : Labels for corners of plot in the order
`... | return _contour ( f , vertexlabels , contourfunc = plt . tricontour , ** kwargs ) |
def _fill ( self ) :
"""Advance the iterator without returning the old head .""" | try :
self . _head = self . _iterable . next ( )
except StopIteration :
self . _head = None |
def create_char ( self , location , pattern ) :
"""Fill one of the first 8 CGRAM locations with custom characters .
The location parameter should be between 0 and 7 and pattern should
provide an array of 8 bytes containing the pattern . E . g . you can easyly
design your custom character at http : / / www . q... | # only position 0 . . 7 are allowed
location &= 0x7
self . write8 ( LCD_SETCGRAMADDR | ( location << 3 ) )
for i in range ( 8 ) :
self . write8 ( pattern [ i ] , char_mode = True ) |
def _PrintVSSStoreIdentifiersOverview ( self , volume_system , volume_identifiers ) :
"""Prints an overview of VSS store identifiers .
Args :
volume _ system ( dfvfs . VShadowVolumeSystem ) : volume system .
volume _ identifiers ( list [ str ] ) : allowed volume identifiers .
Raises :
SourceScannerError :... | header = 'The following Volume Shadow Snapshots (VSS) were found:\n'
self . _output_writer . Write ( header )
column_names = [ 'Identifier' , 'Creation Time' ]
table_view = views . CLITabularTableView ( column_names = column_names )
for volume_identifier in volume_identifiers :
volume = volume_system . GetVolumeByI... |
def compute_profit ( cost_price , selling_price ) :
"""Calculate profit from a transaction . If the transaction results in a loss , return None .
Examples :
compute _ profit ( 1500 , 1200 ) - > 300
compute _ profit ( 100 , 200 ) - > None
compute _ profit ( 2000 , 5000 ) - > None
Args :
cost _ price ( in... | if cost_price > selling_price :
profit = cost_price - selling_price
return profit
else :
return None |
def harpoon_spec ( self ) :
"""Spec for harpoon options""" | formatted_string = formatted ( string_spec ( ) , MergedOptionStringFormatter , expected_type = six . string_types )
formatted_boolean = formatted ( boolean ( ) , MergedOptionStringFormatter , expected_type = bool )
return create_spec ( Harpoon , config = optional_spec ( file_spec ( ) ) , tag = optional_spec ( string_sp... |
def set_simple_fault_geometry ( w , src ) :
"""Set simple fault trace coordinates as shapefile geometry .
: parameter w :
Writer
: parameter src :
source""" | assert "simpleFaultSource" in src . tag
geometry_node = src . nodes [ get_taglist ( src ) . index ( "simpleFaultGeometry" ) ]
fault_attrs = parse_simple_fault_geometry ( geometry_node )
w . line ( parts = [ fault_attrs [ "trace" ] . tolist ( ) ] ) |
def PCA_components ( x ) :
"""Principal Component Analysis helper to check out eigenvalues of components .
* * Args : * *
* ` x ` : input matrix ( 2d array ) , every row represents new sample
* * Returns : * *
* ` components ` : sorted array of principal components eigenvalues""" | # validate inputs
try :
x = np . array ( x )
except :
raise ValueError ( 'Impossible to convert x to a numpy array.' )
# eigen values and eigen vectors of data covariance matrix
eigen_values , eigen_vectors = np . linalg . eig ( np . cov ( x . T ) )
# sort eigen vectors according biggest eigen value
eigen_order... |
def _generate_linear_range ( start , end , periods ) :
"""Generate an equally - spaced sequence of cftime . datetime objects between
and including two dates ( whose length equals the number of periods ) .""" | import cftime
total_seconds = ( end - start ) . total_seconds ( )
values = np . linspace ( 0. , total_seconds , periods , endpoint = True )
units = 'seconds since {}' . format ( format_cftime_datetime ( start ) )
calendar = start . calendar
return cftime . num2date ( values , units = units , calendar = calendar , only_... |
def send_result_email ( self , sender = None ) :
"""Sends an email to admins indicating this Pipeline has completed .
For developer convenience . Automatically called from finalized for root
Pipelines that do not override the default action .
Args :
sender : ( optional ) Override the sender ' s email addres... | status = 'successful'
if self . was_aborted :
status = 'aborted'
app_id = os . environ [ 'APPLICATION_ID' ]
shard_index = app_id . find ( '~' )
if shard_index != - 1 :
app_id = app_id [ shard_index + 1 : ]
param_dict = { 'status' : status , 'app_id' : app_id , 'class_path' : self . _class_path , 'pipeline_id' :... |
def get_int ( config , key , default ) :
"""A helper to retrieve an integer value from a given dictionary
containing string values . If the requested value is not present
in the dictionary , or if it cannot be converted to an integer , a
default value will be returned instead .
: param config : The dictiona... | try :
return int ( config [ key ] )
except ( KeyError , ValueError ) :
return default |
def _get_crc32 ( self , filename ) :
"""Calculates and compares the CRC32 and returns the raw buffer .
The CRC32 is added to ` files _ crc32 ` dictionary , if not present .
: param filename : filename inside the zipfile
: rtype : bytes""" | buffer = self . zip . read ( filename )
if filename not in self . files_crc32 :
self . files_crc32 [ filename ] = crc32 ( buffer )
if self . files_crc32 [ filename ] != self . zip . getinfo ( filename ) . CRC :
log . error ( "File '{}' has different CRC32 after unpacking! " "Declared: {:08x}, Calculated... |
def counter ( self ) :
"""Rolling counter that ensures same - machine and same - time
cuids don ' t collide .""" | self . _counter += 1
if self . _counter >= DISCRETE_VALUES :
self . _counter = 0
return self . _counter |
def clized_default_shorts ( p1 , p2 , first_option = 'default_value' , second_option = 5 , third_option = [ 4 , 3 ] , last_option = False ) :
"""Help docstring""" | print ( '%s %s %s %s %s %s' % ( p1 , p2 , first_option , second_option , third_option , last_option ) ) |
def get_schedule_by_regid_and_term ( regid , term , non_time_schedule_instructors = True , per_section_prefetch_callback = None , transcriptable_course = "" , ** kwargs ) :
"""Returns a uw _ sws . models . ClassSchedule object
for the regid and term passed in .""" | if "include_instructor_not_on_time_schedule" in kwargs :
include = kwargs [ "include_instructor_not_on_time_schedule" ]
non_time_schedule_instructors = include
params = [ ( 'reg_id' , regid ) , ]
if transcriptable_course != "" :
params . append ( ( "transcriptable_course" , transcriptable_course , ) )
param... |
def get_variant_genotypes ( self , variant ) :
"""Get the genotypes from a well formed variant instance .
Args :
marker ( Variant ) : A Variant instance .
Returns :
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes .""" | # The chromosome to search for ( if a general one is set , that ' s the one
# we need to search for )
chrom = variant . chrom . name
if self . chrom is not None and chrom == self . chrom :
chrom = "NA"
# Getting the results
results = [ ]
iterator = self . _bgen . iter_variants_in_region ( CHROM_STR_DECODE . get ( c... |
def answer_shipping_query ( token , shipping_query_id , ok , shipping_options = None , error_message = None ) :
"""If you sent an invoice requesting a shipping address and the parameter is _ flexible was specified , the Bot API will send an Update with a shipping _ query field to the bot . Use this method to reply ... | method_url = 'answerShippingQuery'
payload = { 'shipping_query_id' : shipping_query_id , 'ok' : ok }
if shipping_options :
payload [ 'shipping_options' ] = _convert_list_json_serializable ( shipping_options )
if error_message :
payload [ 'error_message' ] = error_message
return _make_request ( token , method_ur... |
def GetParentFileEntry ( self ) :
"""Retrieves the parent file entry .
Returns :
CPIOFileEntry : parent file entry or None if not available .""" | location = getattr ( self . path_spec , 'location' , None )
if location is None :
return None
parent_location = self . _file_system . DirnamePath ( location )
if parent_location is None :
return None
if parent_location == '' :
parent_location = self . _file_system . PATH_SEPARATOR
is_root = True
is_... |
def raw_data_engine ( ** kwargs ) :
"""engine to extract raw data""" | logger . debug ( "cycles_engine" )
raise NotImplementedError
experiments = kwargs [ "experiments" ]
farms = [ ]
barn = "raw_dir"
for experiment in experiments :
farms . append ( [ ] )
return farms , barn |
def decode ( self , file_name ) :
"""Parses the filename , creating a FileTag from it .
It will try both the old and the new conventions , if the filename does
not conform any of them , then an empty FileTag will be returned .
: param file _ name : filename to parse
: return : a FileTag instance""" | try :
file_tag = self . _filename_decoder_new . decode ( file_name )
except :
try :
file_tag = self . _filename_decoder_old . decode ( file_name )
except :
file_tag = FileTag ( 0 , 0 , '' , '' , '' )
return file_tag |
def L_plate_ET ( q_plant , W_chan ) :
"""Return the length of the plates in the entrance tank .
Parameters
q _ plant : float
Plant flow rate
W _ chan : float
Width of channel
Returns
float
Examples
> > > from aguaclara . play import *
> > > L _ plate _ ET ( 20 * u . L / u . s , 2 * u . m )
0.0... | L_plate = ( q_plant / ( num_plates_ET ( q_plant , W_chan ) * W_chan * design . ent_tank . CAPTURE_BOD_VEL . magnitude * np . cos ( design . ent_tank . PLATE_ANGLE . to ( u . rad ) . magnitude ) ) )
- ( design . ent_tank . PLATE_S . magnitude * np . tan ( design . ent_tank . PLATE_ANGLE . to ( u . rad ) . magnitude ) )
... |
def distance ( p_a , p_b ) :
"""Euclidean distance , between two points
Args :
p _ a ( : obj : ` Point ` )
p _ b ( : obj : ` Point ` )
Returns :
float : distance , in degrees""" | return sqrt ( ( p_a . lat - p_b . lat ) ** 2 + ( p_a . lon - p_b . lon ) ** 2 ) |
def dist ( appname = '' , version = '' ) :
'''makes a tarball for redistributing the sources''' | import tarfile
if not appname :
appname = Utils . g_module . APPNAME
if not version :
version = Utils . g_module . VERSION
tmp_folder = appname + '-' + version
if g_gz in [ 'gz' , 'bz2' ] :
arch_name = tmp_folder + '.tar.' + g_gz
else :
arch_name = tmp_folder + '.' + 'zip'
try :
shutil . rmtree ( tm... |
def get_country ( self ) :
"""Returns the name of the country of the user .""" | doc = self . _request ( self . ws_prefix + ".getInfo" , True )
country = _extract ( doc , "country" )
if country is None or country == "None" :
return None
else :
return Country ( country , self . network ) |
def basis ( self ) :
"""Compute basis rather than storing it .""" | precision_adj = self . dt / 100
return np . arange ( self . start , self . stop - precision_adj , self . dt ) |
def to_op ( self ) :
"""Extracts the modification operation from the set .
: rtype : dict , None""" | if not self . _adds and not self . _removes :
return None
changes = { }
if self . _adds :
changes [ 'adds' ] = list ( self . _adds )
if self . _removes :
changes [ 'removes' ] = list ( self . _removes )
return changes |
def get_vmpolicy_macaddr_output_vmpolicy_macaddr_dvpg_nn ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vmpolicy_macaddr = ET . Element ( "get_vmpolicy_macaddr" )
config = get_vmpolicy_macaddr
output = ET . SubElement ( get_vmpolicy_macaddr , "output" )
vmpolicy_macaddr = ET . SubElement ( output , "vmpolicy-macaddr" )
dvpg_nn = ET . SubElement ( vmpolicy_macaddr , "dvpg-nn" )
dvpg_... |
def rescale ( img , size , mode = None ) :
"""Rescale an image to given size , crop if mode specified
* img : a PIL image object
* size : a 2 - tuple of ( width , height ) ; at least one must be specified
* mode : CROP _ TL keep the top left part , CROP _ BR the bottom right part""" | assert size [ 0 ] or size [ 1 ] , "Must provide a width or a height"
size = list ( size )
crop = size [ 0 ] and size [ 1 ]
if not size [ 0 ] :
size [ 0 ] = int ( img . size [ 0 ] * size [ 1 ] / float ( img . size [ 1 ] ) )
if not size [ 1 ] :
size [ 1 ] = int ( img . size [ 1 ] * size [ 0 ] / float ( img . size... |
def enabled ( job_label , runas = None ) :
'''Return True if the named service is enabled , false otherwise
CLI Example :
. . code - block : : bash
salt ' * ' service . enabled < service label >''' | overrides_data = dict ( plistlib . readPlist ( '/var/db/launchd.db/com.apple.launchd/overrides.plist' ) )
if overrides_data . get ( job_label , False ) :
if overrides_data [ job_label ] [ 'Disabled' ] :
return False
else :
return True
else :
return False |
def get_dictionary_representation_of_object_attributes ( obj , omit_null_fields = False ) :
"""Returns a dictionary of object ' s attributes , ignoring methods
@ param obj : The object to represent as dict
@ param omit _ null _ fields : If true , will not include fields in the dictionary that are null
@ retur... | obj_dictionary = obj . __dict__
obj_dictionary_temp = obj_dictionary . copy ( )
for k , v in obj_dictionary . iteritems ( ) :
if omit_null_fields :
if v is None :
obj_dictionary_temp . pop ( k , None )
if k . startswith ( '_' ) :
obj_dictionary_temp . pop ( k , None )
return obj_dict... |
def handle_option_error ( func ) :
"""Decorator that calls given method / function and handles any RuleOptionError gracefully by converting it to a
LintConfigError .""" | def wrapped ( * args ) :
try :
return func ( * args )
except options . RuleOptionError as e :
raise LintConfigError ( ustr ( e ) )
return wrapped |
def run ( self , host = None , port = None , debug = None , ** options ) :
"""Start the AgoraApp expecting the provided config to have at least REDIS and PORT fields .""" | tasks = options . get ( 'tasks' , [ ] )
for task in tasks :
if task is not None and hasattr ( task , '__call__' ) :
_batch_tasks . append ( task )
thread = Thread ( target = self . batch_work )
thread . start ( )
try :
super ( AgoraApp , self ) . run ( host = '0.0.0.0' , port = self . config [ 'PORT' ] ... |
def _reset_kvstore ( self ) :
"""Reset kvstore .""" | if self . _kvstore and 'dist' in self . _kvstore . type :
raise RuntimeError ( "Cannot reset distributed KVStore." )
self . _kv_initialized = False
self . _kvstore = None
self . _distributed = None
self . _update_on_kvstore = None
self . _params_to_init = [ param for param in self . _params ] |
def find_credentials ( ) :
'''Cycle through all the possible credentials and return the first one that
works''' | usernames = [ __pillar__ [ 'proxy' ] . get ( 'admin_username' , 'root' ) ]
if 'fallback_admin_username' in __pillar__ . get ( 'proxy' ) :
usernames . append ( __pillar__ [ 'proxy' ] . get ( 'fallback_admin_username' ) )
for user in usernames :
for pwd in __pillar__ [ 'proxy' ] [ 'passwords' ] :
r = __sa... |
def _action_enabled ( self , event , action ) :
"""Check if an action for a notification is enabled .""" | event_actions = self . _aconfig . get ( event )
if event_actions is None :
return True
if event_actions is False :
return False
return action in event_actions |
def get_exitcode_reactor ( ) :
"""This is only neccesary until a fix like the one outlined here is
implemented for Twisted :
http : / / twistedmatrix . com / trac / ticket / 2182""" | from twisted . internet . main import installReactor
from twisted . internet . selectreactor import SelectReactor
class ExitCodeReactor ( SelectReactor ) :
def stop ( self , exitStatus = 0 ) :
super ( ExitCodeReactor , self ) . stop ( )
self . exitStatus = exitStatus
def run ( self , * args , **... |
def walk_links ( directory , prefix = '' , linkbase = None ) :
"""Return all links contained in directory ( or any sub directory ) .""" | links = { }
try :
for child in os . listdir ( directory ) :
fullname = os . path . join ( directory , child )
if os . path . islink ( fullname ) :
link_path = os . path . normpath ( os . path . join ( directory , os . readlink ( fullname ) ) )
if linkbase :
li... |
def _gte ( field , value , document ) :
"""Returns True if the value of a document field is greater than or
equal to a given value""" | try :
return document . get ( field , None ) >= value
except TypeError : # pragma : no cover Python < 3.0
return False |
def json_integrity ( baseline , suspect ) :
"""Summary :
Validates baseline dict against suspect dict to ensure contain USERNAME
k , v parameters .
Args :
baseline ( dict ) : baseline json structure
suspect ( dict ) : json object validated against baseline structure
Returns :
Success ( matches baselin... | try :
for k , v in baseline . items ( ) :
for ks , vs in suspect . items ( ) :
keys_baseline = set ( v . keys ( ) )
keys_suspect = set ( vs . keys ( ) )
intersect_keys = keys_baseline . intersection ( keys_suspect )
added = keys_baseline - keys_suspect
... |
def get_app ( config ) :
"""Init the webdav app""" | mongo_client = MongoClient ( host = config . get ( 'mongo_opt' , { } ) . get ( 'host' , 'localhost' ) )
database = mongo_client [ config . get ( 'mongo_opt' , { } ) . get ( 'database' , 'INGInious' ) ]
# Create the FS provider
if "tasks_directory" not in config :
raise RuntimeError ( "WebDav access is only supporte... |
def get_current_scene_node ( ) :
"""Return the name of the jb _ sceneNode , that describes the current scene or None if there is no scene node .
: returns : the full name of the node or none , if there is no scene node
: rtype : str | None
: raises : None""" | c = cmds . namespaceInfo ( ':' , listOnlyDependencyNodes = True , absoluteName = True , dagPath = True )
l = cmds . ls ( c , type = 'jb_sceneNode' , absoluteName = True )
if not l :
return
else :
for n in sorted ( l ) :
if not cmds . listConnections ( "%s.reftrack" % n , d = False ) :
return... |
def get_package_versions ( package ) :
"""Get the package version information ( = SetuptoolsVersion ) which is
comparable .
note : we use the pip list _ command implementation for this
: param package : name of the package
: return : installed version , latest available version""" | list_command = ListCommand ( )
options , args = list_command . parse_args ( [ ] )
packages = [ get_dist ( package ) ]
dists = list_command . iter_packages_latest_infos ( packages , options )
try :
dist = next ( dists )
return dist . parsed_version , dist . latest_version
except StopIteration :
return None ,... |
def cluster_meet ( self , ip , port ) :
"""Force a node cluster to handshake with another node .""" | fut = self . execute ( b'CLUSTER' , b'MEET' , ip , port )
return wait_ok ( fut ) |
def channel_angle ( im , chanapproxangle = None , * , isshiftdftedge = False , truesize = None ) :
"""Extract the channel angle from the rfft
Parameters :
im : 2d array
The channel image
chanapproxangle : number , optional
If not None , an approximation of the result
isshiftdftedge : boolean , default F... | im = np . asarray ( im )
# Compute edge
if not isshiftdftedge :
im = edge ( im )
return reg . orientation_angle ( im , isshiftdft = isshiftdftedge , approxangle = chanapproxangle , truesize = truesize ) |
def outgoing ( cls , hostport , process_name = None , serve_hostport = None , handler = None , tchannel = None ) :
"""Initiate a new connection to the given host .
: param hostport :
String in the form ` ` $ host : $ port ` ` specifying the target host
: param process _ name :
Process name of the entity mak... | host , port = hostport . rsplit ( ":" , 1 )
process_name = process_name or "%s[%s]" % ( sys . argv [ 0 ] , os . getpid ( ) )
serve_hostport = serve_hostport or "0.0.0.0:0"
# TODO : change this to tornado . tcpclient . TCPClient to do async DNS
# lookups .
stream = tornado . iostream . IOStream ( socket . socket ( socke... |
def ValidateToken ( token , targets ) :
"""Does basic token validation .
Args :
token : User ' s credentials as access _ control . ACLToken .
targets : List of targets that were meant to be accessed by the token . This
is used for logging purposes only .
Returns :
True if token is valid .
Raises :
a... | def GetSubjectForError ( ) :
if len ( targets ) == 1 :
return list ( targets ) [ 0 ]
else :
return None
# All accesses need a token .
if not token :
raise access_control . UnauthorizedAccess ( "Must give an authorization token for %s" % targets , subject = GetSubjectForError ( ) )
# Token mu... |
def _makeDefaultLiveForm ( self , ( defaults , identifier ) ) :
"""Make a liveform suitable for editing the set of default values C { defaults } .
@ type defaults : C { dict }
@ param defaults : Mapping of parameter names to values .
@ rtype : L { repeatedLiveFormWrapper }""" | parameters = [ self . _cloneDefaultedParameter ( p , defaults [ p . name ] ) for p in self . parameters ]
return self . _makeALiveForm ( parameters , identifier ) |
def apply ( self , doc ) :
"""Generate MentionTables from a Document by parsing all of its Tables .
: param doc : The ` ` Document ` ` to parse .
: type doc : ` ` Document ` `
: raises TypeError : If the input doc is not of type ` ` Document ` ` .""" | if not isinstance ( doc , Document ) :
raise TypeError ( "Input Contexts to MentionTables.apply() must be of type Document" )
for table in doc . tables :
yield TemporaryTableMention ( table ) |
def relabel_atoms ( self , start = 1 ) :
"""Relabels all Atoms in numerical order , offset by the start parameter .
Parameters
start : int , optional
Defines an offset for the labelling .""" | counter = start
for atom in self . get_atoms ( ligands = True ) :
atom . id = counter
counter += 1
return |
def evaluate_clf ( clf , X , y , k = None , test_size = 0.5 , scoring = "f1_weighted" , feature_names = None ) :
"""Evalate the classifier on the FULL training dataset
This takes care of fitting on train / test splits""" | X_train , X_test , y_train , y_true = cross_validation . train_test_split ( X , y , test_size = test_size )
clf . fit ( X_train , y_train )
y_pred = clf . predict ( X_test )
print ( "Accuracy Score: %f" % metrics . accuracy_score ( y_true , y_pred ) )
print ( )
print ( "Classification report" )
print ( metrics . classi... |
def _estimate_additive_constant ( matrix ) :
"""CMDS Additive Constant : correction for non - Euclidean distances .
Procedure taken from R function cmdscale .
The additive constant is given by the largest eigenvalue ( real part )
of this 2x2 block matrix -
| 0 | 2 * dbc | NB : dbc function ( m : matrix ) : ... | topleft = np . zeros ( matrix . shape )
topright = 2 * double_centre ( matrix )
bottomleft = - np . eye ( matrix . shape [ 0 ] )
bottomright = - 4 * double_centre ( matrix , square_input = False )
Z = np . vstack ( [ np . hstack ( [ topleft , topright ] ) , np . hstack ( [ bottomleft , bottomright ] ) ] )
return max ( ... |
def get_outputs ( self ) :
"""Get outputs of this job .
Should only call if status is SUCCESS .
Yields :
Iterators , one for each shard . Each iterator is
from the argument of map _ job . output _ writer . commit _ output .""" | assert self . SUCCESS == self . get_status ( )
ss = model . ShardState . find_all_by_mapreduce_state ( self . _state )
for s in ss :
yield iter ( s . writer_state . get ( "outs" , [ ] ) ) |
def unpack_close ( self ) :
"""Unpack a close message into a status code and a reason . If no payload
is given , the code is None and the reason is an empty string .""" | if self . payload :
code = struct . unpack ( '!H' , str ( self . payload [ : 2 ] ) ) [ 0 ]
reason = str ( self . payload [ 2 : ] )
else :
code = None
reason = ''
return code , reason |
def build_set_raw ( id = None , name = None , tempbuild = False , timestamp_alignment = False , force = False , rebuild_mode = common . REBUILD_MODES_DEFAULT , ** kwargs ) :
"""Start a build of the given BuildConfigurationSet""" | logging . debug ( "temp_build: " + str ( tempbuild ) )
logging . debug ( "timestamp_alignment: " + str ( timestamp_alignment ) )
logging . debug ( "force: " + str ( force ) )
if tempbuild is False and timestamp_alignment is True :
logging . error ( "You can only activate timestamp alignment with the temporary build... |
def mark_locations ( h , section , locs , markspec = 'or' , ** kwargs ) :
"""Marks one or more locations on along a section . Could be used to
mark the location of a recording or electrical stimulation .
Args :
h = hocObject to interface with neuron
section = reference to section
locs = float between 0 an... | # get list of cartesian coordinates specifying section path
xyz = get_section_path ( h , section )
( r , theta , phi ) = sequential_spherical ( xyz )
rcum = np . append ( 0 , np . cumsum ( r ) )
# convert locs into lengths from the beginning of the path
if type ( locs ) is float or type ( locs ) is np . float64 :
l... |
def checkIfAvailable ( self , dateTime = timezone . now ( ) ) :
'''Available slots are available , but also tentative slots that have been held as tentative
past their expiration date''' | return ( self . startTime >= dateTime + timedelta ( days = getConstant ( 'privateLessons__closeBookingDays' ) ) and self . startTime <= dateTime + timedelta ( days = getConstant ( 'privateLessons__openBookingDays' ) ) and not self . eventRegistration and ( self . status == self . SlotStatus . available or ( self . stat... |
def add_image_info_cb ( self , viewer , channel , image_info ) :
"""Almost the same as add _ image _ cb ( ) , except that the image
may not be loaded in memory .""" | chname = channel . name
name = image_info . name
self . logger . debug ( "name=%s" % ( name ) )
# Updates of any extant information
try :
image = channel . get_loaded_image ( name )
except KeyError : # images that are not yet loaded will show " N / A " for keywords
image = None
self . add_image_cb ( viewer , ch... |
def prior ( self , m , H ) :
"""Set prior
Set prior values
Inputs :
mean of the prior
precision matrix of the prior
Hiddens :
ln _ H _ : log ( det ( H ) ) / 2
calculate this once to use everytime log prior is called
Hm : < H , m >
calculate this once to use everytime proposal is called""" | if self . _prior == True :
raise Warning ( "prior information is already set" )
else :
self . _prior = True
# mean
self . _m = np . reshape ( np . array ( m ) , ( - 1 , 1 ) )
try :
assert np . size ( self . _m ) == self . _n
except :
raise TypeError ( "mean has to be an array of size n" )
# precision
se... |
def _x_flow_ok ( self , active ) :
"""Confirm a flow method
Confirms to the peer that a flow command was received and
processed .
PARAMETERS :
active : boolean
current flow setting
Confirms the setting of the processed flow method :
True means the peer will start sending or continue
to send content ... | args = AMQPWriter ( )
args . write_bit ( active )
self . _send_method ( ( 20 , 21 ) , args ) |
def fill_hist ( hist , array , weights = None , return_indices = False ) :
"""Fill a ROOT histogram with a NumPy array .
Parameters
hist : ROOT TH1 , TH2 , or TH3
The ROOT histogram to fill .
array : numpy array of shape [ n _ samples , n _ dimensions ]
The values to fill the histogram with . The number o... | import ROOT
array = np . asarray ( array , dtype = np . double )
if weights is not None :
weights = np . asarray ( weights , dtype = np . double )
if weights . shape [ 0 ] != array . shape [ 0 ] :
raise ValueError ( "array and weights must have the same length" )
if weights . ndim != 1 :
rai... |
def match ( string , patterns ) :
"""Given a string return true if it matches the supplied list of
patterns .
Parameters
string : str
The string to be matched .
patterns : None or [ pattern , . . . ]
The series of regular expressions to attempt to match .""" | if patterns is None :
return True
else :
return any ( re . match ( pattern , string ) for pattern in patterns ) |
def process_input ( self , character ) :
"""A subclassable method for dealing with input characters .""" | func = None
try :
func = getattr ( self , "handle_%s" % chr ( character ) , None )
except :
pass
if func :
func ( ) |
def harmonize ( self , harmonics_dict ) :
"""Returns a " harmonized " table lookup instance by using a " harmonics "
dictionary with { partial : amplitude } terms , where all " partial " keys have
to be integers .""" | data = sum ( cycle ( self . table [ : : partial + 1 ] ) * amplitude for partial , amplitude in iteritems ( harmonics_dict ) )
return TableLookup ( data . take ( len ( self ) ) , cycles = self . cycles ) |
def dict_expand ( o ) :
"""Expand keys in a dict with ' . ' in them into
sub - dictionaries , e . g .
{ ' a . b . c ' : ' foo ' } = = > { ' a ' : { ' b ' : { ' c ' : ' foo ' } } }""" | r = { }
for k , v in o . items ( ) :
if isinstance ( k , str ) :
k = k . replace ( '$' , '_' )
if "." in k :
sub_r , keys = r , k . split ( '.' )
# create sub - dicts until last part of key
for k2 in keys [ : - 1 ] :
sub_r [ k2 ] = { }
sub_r = sub_r [ k2 ]... |
def gatk_snp_cutoff ( in_file , data ) :
"""Perform cutoff - based soft filtering on GATK SNPs using best - practice recommendations .
We have a more lenient mapping quality ( MQ ) filter compared to GATK defaults .
The recommended filter ( MQ < 40 ) is too stringent , so we adjust to 30:
http : / / imgur . c... | filters = [ "MQRankSum < -12.5" , "ReadPosRankSum < -8.0" ]
# GATK Haplotype caller ( v2.2 ) appears to have much larger HaplotypeScores
# resulting in excessive filtering , so avoid this metric
variantcaller = utils . get_in ( data , ( "config" , "algorithm" , "variantcaller" ) )
if variantcaller not in [ "gatk-haplot... |
def try_date ( obj ) -> Optional [ datetime . date ] :
"""Attempts to convert an object into a date .
If the date format is known , it ' s recommended to use the corresponding function
This is meant to be used in constructors .
Parameters
obj : : class : ` str ` , : class : ` datetime . datetime ` , : class... | if obj is None :
return None
if isinstance ( obj , datetime . datetime ) :
return obj . date ( )
if isinstance ( obj , datetime . date ) :
return obj
res = parse_tibia_date ( obj )
if res is not None :
return res
res = parse_tibia_full_date ( obj )
if res is not None :
return res
res = parse_tibiada... |
def rnoncentral_t ( mu , lam , nu , size = None ) :
"""Non - central Student ' s t random variates .""" | tau = rgamma ( nu / 2. , nu / ( 2. * lam ) , size )
return rnormal ( mu , tau ) |
def install ( plugin_package , plugins_directory , server_url = DEFAULT_SERVER_URL ) :
'''Parameters
plugin _ package : str
Name of plugin package hosted on MicroDrop plugin index . Version
constraints are also supported ( e . g . , ` ` " foo " , " foo = = 1.0 " ,
" foo > = 1.0 " ` ` , etc . ) See ` version... | import pip_helpers
if path ( plugin_package ) . isfile ( ) :
plugin_is_file = True
with open ( plugin_package , 'rb' ) as plugin_file : # Plugin package is a file .
plugin_file_metadata = extract_metadata ( plugin_file )
name = plugin_file_metadata [ 'package_name' ]
version = plugin_file_metada... |
def allocate ( self ) :
"""Initializes libvirt resources .""" | disk_path = self . provider_image
self . _hypervisor = libvirt . open ( self . configuration . get ( 'hypervisor' , 'vbox:///session' ) )
self . _domain = domain_create ( self . _hypervisor , self . identifier , self . configuration [ 'domain' ] , disk_path ) |
def clear_cache ( ) :
'''Completely clear svnfs cache''' | fsb_cachedir = os . path . join ( __opts__ [ 'cachedir' ] , 'svnfs' )
list_cachedir = os . path . join ( __opts__ [ 'cachedir' ] , 'file_lists/svnfs' )
errors = [ ]
for rdir in ( fsb_cachedir , list_cachedir ) :
if os . path . exists ( rdir ) :
try :
shutil . rmtree ( rdir )
except OSErr... |
def autogen_envconfigs ( config , envs ) :
"""Make the envconfigs for undeclared envs .
This is a stripped - down version of parseini . _ _ init _ _ made for making
an envconfig .""" | prefix = 'tox' if config . toxinipath . basename == 'setup.cfg' else None
reader = tox . config . SectionReader ( "tox" , config . _cfg , prefix = prefix )
distshare_default = "{homedir}/.tox/distshare"
reader . addsubstitutions ( toxinidir = config . toxinidir , homedir = config . homedir )
reader . addsubstitutions (... |
def simplify_basic ( drawing , process = False , ** kwargs ) :
"""Merge colinear segments and fit circles .
Parameters
drawing : Path2D object , will not be modified .
Returns
simplified : Path2D with circles .""" | if any ( i . __class__ . __name__ != 'Line' for i in drawing . entities ) :
log . debug ( 'Path contains non- linear entities, skipping' )
return drawing
# we are going to do a bookkeeping to avoid having
# to recompute literally everything when simplification is ran
cache = copy . deepcopy ( drawing . _cache )... |
def from_timeseries ( cls , timeSeries ) :
"""Create a new Matrix instance from a TimeSeries or MultiDimensionalTimeSeries
: param TimeSeries timeSeries : The TimeSeries , which should be used to
create a new Matrix .
: return : A Matrix with the values of the timeSeries . Each row of
the Matrix represents ... | width = 1
if isinstance ( timeSeries , MultiDimensionalTimeSeries ) :
width = timeSeries . dimension_count ( )
matrixData = [ [ ] for dummy in xrange ( width ) ]
for entry in timeSeries :
for col in xrange ( 1 , len ( entry ) ) :
matrixData [ col - 1 ] . append ( entry [ col ] )
if not matrixData [ 0 ] ... |
def get_element_profile ( self , element , comp , comp_tol = 1e-5 ) :
"""Provides the element evolution data for a composition .
For example , can be used to analyze Li conversion voltages by varying
uLi and looking at the phases formed . Also can be used to analyze O2
evolution by varying uO2.
Args :
ele... | element = get_el_sp ( element )
element = Element ( element . symbol )
if element not in self . elements :
raise ValueError ( "get_transition_chempots can only be called with" " elements in the phase diagram." )
gccomp = Composition ( { el : amt for el , amt in comp . items ( ) if el != element } )
elref = self . e... |
def close ( self ) :
'''Close the application and all installed plugins .''' | for plugin in self . plugins :
if hasattr ( plugin , 'close' ) :
plugin . close ( )
self . stopped = True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.