signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def check_install_json ( self ) :
"""Check all install . json files for valid schema .""" | if self . install_json_schema is None :
return
contents = os . listdir ( self . app_path )
if self . args . install_json is not None :
contents = [ self . args . install_json ]
for install_json in sorted ( contents ) : # skip files that are not install . json files
if 'install.json' not in install_json :
... |
def _multi_string_put_transform ( cls , item , ** kwargs ) :
'''transform for a REG _ MULTI _ SZ to properly handle " Not Defined "''' | if isinstance ( item , list ) :
return item
elif isinstance ( item , six . string_types ) :
if item . lower ( ) == 'not defined' :
return None
else :
return item . split ( ',' )
else :
return 'Invalid Value' |
def print_factoids ( input_dict , environment_dict ) :
"""< Purpose >
Used to print seash factoids when user uses ' show factoids '
command .
< Arguments >
input _ dict : Input dictionary generated by seash _ dictionary . parse _ command ( ) .
environment _ dict : Dictionary describing the current seash e... | # User will insert an argument regarding how many factoids should be printed .
# We have to find what is user argument .
# User can type any positive number or he can type ' all ' to see all factoids .
dict_mark = input_dict
try :
command = dict_mark . keys ( ) [ 0 ]
while dict_mark [ command ] [ 'name' ] != 'a... |
def potentialStaeckel ( u , v , pot , delta ) :
"""NAME :
potentialStaeckel
PURPOSE :
return the potential
INPUT :
u - confocal u
v - confocal v
pot - potential
delta - focus
OUTPUT :
Phi ( u , v )
HISTORY :
2012-11-29 - Written - Bovy ( IAS )""" | R , z = bovy_coords . uv_to_Rz ( u , v , delta = delta )
return _evaluatePotentials ( pot , R , z ) |
def set_tags ( self , tags = "" ) :
"""* Set the tags for this taskpaper object *
* * Key Arguments : * *
- ` ` tags ` ` - - a tag string to set
* * Usage : * *
. . code - block : : python
aTask . set _ tags ( " @ due @ mac " )""" | self . refresh
tagList = [ ]
regex = re . compile ( r'@[^@]*' , re . S )
matchList = regex . findall ( tags )
for m in matchList :
tagList . append ( m . strip ( ) . replace ( "@" , "" ) )
self . refresh
oldContent = self . to_string ( indentLevel = 1 )
self . tags = tagList
newContent = self . to_string ( indentLe... |
def _compile_arithmetic_expression ( self , expr : Expression , scope : Dict [ str , TensorFluent ] , batch_size : Optional [ int ] = None , noise : Optional [ List [ tf . Tensor ] ] = None ) -> TensorFluent :
'''Compile an arithmetic expression ` expr ` into a TensorFluent
in the given ` scope ` with optional ba... | etype = expr . etype
args = expr . args
if len ( args ) == 1 :
etype2op = { '+' : lambda x : x , '-' : lambda x : - x }
if etype [ 1 ] not in etype2op :
raise ValueError ( 'Invalid binary arithmetic expression:\n{}' . format ( expr ) )
op = etype2op [ etype [ 1 ] ]
x = self . _compile_expression... |
def generate_token ( ) :
"""Generate a new random security token .
> > > len ( generate _ token ( ) ) = = 50
True
Returns :
string""" | length = 50
stringset = string . ascii_letters + string . digits
token = '' . join ( [ stringset [ i % len ( stringset ) ] for i in [ ord ( x ) for x in os . urandom ( length ) ] ] )
return token |
def fetch ( ) :
"""Fetches the latest exchange rate info from the European Central Bank . These
rates need to be used for displaying invoices since some countries require
local currency be quoted . Also useful to store the GBP rate of the VAT
collected at time of purchase to prevent fluctuations in exchange r... | response = urlopen ( 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' )
_ , params = cgi . parse_header ( response . headers [ 'Content-Type' ] )
if 'charset' in params :
encoding = params [ 'charset' ]
else :
encoding = 'utf-8'
return_xml = response . read ( ) . decode ( encoding )
# Example ret... |
def cylinder ( target , throat_length = 'throat.length' , throat_diameter = 'throat.diameter' ) :
r"""Calculate throat volume assuing a cylindrical shape
Parameters
target : OpenPNM Object
The object which this model is associated with . This controls the
length of the calculated array , and also provides a... | leng = target [ throat_length ]
diam = target [ throat_diameter ]
value = _sp . pi / 4 * leng * diam ** 2
return value |
def write_mappings ( self , i ) :
'''Intended to take a ToilWDL _ instance ( i ) and prints the final task dict ,
and workflow dict .
Does not work by default with toil since Toil actively suppresses stdout
during the run .
: param i : A class object instance with the following dict variables :
self . tas... | from collections import OrderedDict
class Formatter ( object ) :
def __init__ ( self ) :
self . types = { }
self . htchar = '\t'
self . lfchar = '\n'
self . indent = 0
self . set_formater ( object , self . __class__ . format_object )
self . set_formater ( dict , self ... |
def process_vhwa_command ( self , command , enm_cmd , from_guest ) :
"""Posts a Video HW Acceleration Command to the frame buffer for processing .
The commands used for 2D video acceleration ( DDraw surface creation / destroying , blitting , scaling , color conversion , overlaying , etc . )
are posted from ques... | if not isinstance ( command , basestring ) :
raise TypeError ( "command can only be an instance of type basestring" )
if not isinstance ( enm_cmd , baseinteger ) :
raise TypeError ( "enm_cmd can only be an instance of type baseinteger" )
if not isinstance ( from_guest , bool ) :
raise TypeError ( "from_gues... |
def add_event_handler ( self , full_usage_id , handler_function , event_kind = HID_EVT_ALL , aux_data = None ) :
"""Add event handler for usage value / button changes ,
returns True if the handler function was updated""" | report_id = self . find_input_usage ( full_usage_id )
if report_id != None : # allow first zero to trigger changes and releases events
self . __input_report_templates [ report_id ] [ full_usage_id ] . __value = None
if report_id == None or not handler_function : # do not add handler
return False
assert ( isinst... |
def _transmit ( self , envelopes ) :
"""Transmit the data envelopes to the ingestion service .
Return a negative value for partial success or non - retryable failure .
Return 0 if all envelopes have been successfully ingested .
Return the next retry time in seconds for retryable failure .
This function shou... | if not envelopes :
return 0
# TODO : prevent requests being tracked
blacklist_hostnames = execution_context . get_opencensus_attr ( 'blacklist_hostnames' , )
execution_context . set_opencensus_attr ( 'blacklist_hostnames' , [ 'dc.services.visualstudio.com' ] , )
try :
response = requests . post ( url = self . o... |
def people ( text , cloud = None , batch = None , api_key = None , version = 2 , ** kwargs ) :
"""Given input text , returns references to specific persons found in the text
Example usage :
. . code - block : : python
> > > text = " London Underground ' s boss Mike Brown warned that the strike . . . "
> > >... | url_params = { "batch" : batch , "api_key" : api_key , "version" : version }
return api_handler ( text , cloud = cloud , api = "people" , url_params = url_params , ** kwargs ) |
def create_document ( self , parent , collection_id , document_id , document , mask = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Creates a new document .
Example :
> > > from google . cloud import firestor... | # Wrap the transport method to add retry and timeout logic .
if "create_document" not in self . _inner_api_calls :
self . _inner_api_calls [ "create_document" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . create_document , default_retry = self . _method_configs [ "CreateDocument" ] . ... |
def append_vobject ( self , vtodo , project = None ) :
"""Add a task from vObject to Taskwarrior
vtodo - - the iCalendar to add
project - - the project to add ( see get _ filesnames ( ) as well )""" | if project :
project = basename ( project )
return self . to_task ( vtodo . vtodo , project ) |
def is_among ( value , * possibilities ) :
"""Ensure that the method that has been used for the request is one
of the expected ones ( e . g . , GET or POST ) .""" | for possibility in possibilities :
if value == possibility :
return True
raise Exception ( 'A different request value was encountered than expected: {0}' . format ( value ) ) |
def get_pegasus_to_nice_fn ( * args , ** kwargs ) :
"""Returns a coordinate translation function from the 4 - term pegasus _ index
coordinates to the 5 - term " nice " coordinates .
Details on the returned function , pegasus _ to _ nice ( u , w , k , z )
Inputs are 4 - tuples of ints , return is a 5 - tuple o... | if args or kwargs :
warnings . warn ( "Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore" )
def p2n0 ( u , w , k , z ) :
return ( 0 , w - 1 if u else z , z if u else w , u , k - 4 if u else k - 4 )
def p2n1 ( u , w , k , z ) :
return ( 1 , w - 1 if u else z , z if u else w ,... |
def out_format ( data , out , opts = None , ** kwargs ) :
'''Return the formatted outputter string for the passed data''' | return try_printout ( data , out , opts , ** kwargs ) |
def from_dict ( data , ctx ) :
"""Instantiate a new InstrumentCommission from a dict ( generally from
loading a JSON response ) . The data used to instantiate the
InstrumentCommission is a shallow copy of the dict passed in , with any
complex child types instantiated appropriately .""" | data = data . copy ( )
if data . get ( 'commission' ) is not None :
data [ 'commission' ] = ctx . convert_decimal_number ( data . get ( 'commission' ) )
if data . get ( 'unitsTraded' ) is not None :
data [ 'unitsTraded' ] = ctx . convert_decimal_number ( data . get ( 'unitsTraded' ) )
if data . get ( 'minimumCo... |
def get_routers ( self , context , router_ids = None , hd_ids = None ) :
"""Make a remote process call to retrieve the sync data for routers .
: param context : session context
: param router _ ids : list of routers to fetch
: param hd _ ids : hosting device ids , only routers assigned to these
hosting devi... | cctxt = self . client . prepare ( version = '1.1' )
return cctxt . call ( context , 'cfg_sync_routers' , host = self . host , router_ids = router_ids , hosting_device_ids = hd_ids ) |
def pre_upgrade_checks ( self , upgrades ) :
"""Run upgrade pre - checks prior to applying upgrades .
Pre - checks should
in general be fast to execute . Pre - checks may the use the wait _ for _ user
function , to query the user for confirmation , but should respect the
- - yes - i - know option to run una... | errors = [ ]
for check in self . global_pre_upgrade :
self . _setup_log_prefix ( plugin_id = check . __name__ )
try :
check ( )
except RuntimeError as e :
errors . append ( ( check . __name__ , e . args ) )
for u in upgrades :
self . _setup_log_prefix ( plugin_id = u . name )
try :
... |
def play ( ) :
"""Open the matched movie with a media player .""" | with sqlite3 . connect ( ARGS . database ) as connection :
connection . text_factory = str
cursor = connection . cursor ( )
if ARGS . pattern :
if not ARGS . strict :
ARGS . pattern = '%{0}%' . format ( ARGS . pattern )
cursor . execute ( 'SELECT * FROM Movies WHERE Name LIKE (?)... |
def on_network_adapter_change ( self , network_adapter , change_adapter ) :
"""Triggered when settings of a network adapter of the
associated virtual machine have changed .
in network _ adapter of type : class : ` INetworkAdapter `
in change _ adapter of type bool
raises : class : ` VBoxErrorInvalidVmState ... | if not isinstance ( network_adapter , INetworkAdapter ) :
raise TypeError ( "network_adapter can only be an instance of type INetworkAdapter" )
if not isinstance ( change_adapter , bool ) :
raise TypeError ( "change_adapter can only be an instance of type bool" )
self . _call ( "onNetworkAdapterChange" , in_p =... |
def _get_axis_bounds ( self , dim , bunch ) :
"""Return the min / max of an axis .""" | if dim in self . attributes : # Attribute : specified lim , or compute the min / max .
vmin , vmax = bunch [ 'lim' ]
assert vmin is not None
assert vmax is not None
return vmin , vmax
# PC dimensions : use the common scaling .
return ( - 1. / self . scaling , + 1. / self . scaling ) |
def _prepare_atoms ( topology , compute_cycles = False ) :
"""Compute cycles and add white - / blacklists to atoms .""" | atom1 = next ( topology . atoms ( ) )
has_whitelists = hasattr ( atom1 , 'whitelist' )
has_cycles = hasattr ( atom1 , 'cycles' )
compute_cycles = compute_cycles and not has_cycles
if compute_cycles or not has_whitelists :
for atom in topology . atoms ( ) :
if compute_cycles :
atom . cycles = set... |
def from_global_driver ( self ) :
"""Connect to the global driver .""" | address , _ = _read_driver ( )
if address is None :
raise DriverNotRunningError ( "No driver currently running" )
security = Security . from_default ( )
return Client ( address = address , security = security ) |
def upd_pos ( self , * args ) :
"""Ask the foundation where I should be , based on what deck I ' m
for .""" | self . pos = self . parent . _get_foundation_pos ( self . deck ) |
def get_auto_correlation_time ( chain , max_lag = None ) :
r"""Compute the auto correlation time up to the given lag for the given chain ( 1d vector ) .
This will halt when the maximum lag : math : ` m ` is reached or when the sum of two consecutive lags for any
odd lag is lower or equal to zero .
The auto co... | max_lag = max_lag or min ( len ( chain ) // 3 , 1000 )
normalized_chain = chain - np . mean ( chain , dtype = np . float64 )
previous_accoeff = 0
auto_corr_sum = 0
for lag in range ( 1 , max_lag ) :
auto_correlation_coeff = np . mean ( normalized_chain [ : len ( chain ) - lag ] * normalized_chain [ lag : ] , dtype ... |
def is_artifact_optional ( chain , task_id , path ) :
"""Tells whether an artifact is flagged as optional or not .
Args :
chain ( ChainOfTrust ) : the chain of trust object
task _ id ( str ) : the id of the aforementioned task
Returns :
bool : True if artifact is optional""" | upstream_artifacts = chain . task [ 'payload' ] . get ( 'upstreamArtifacts' , [ ] )
optional_artifacts_per_task_id = get_optional_artifacts_per_task_id ( upstream_artifacts )
return path in optional_artifacts_per_task_id . get ( task_id , [ ] ) |
def get_url ( self , url_or_dict ) :
"""Returns the reversed url given a string or dict and prints errors if MENU _ DEBUG is enabled""" | if isinstance ( url_or_dict , basestring ) :
url_or_dict = { 'viewname' : url_or_dict }
try :
return reverse ( ** url_or_dict )
except NoReverseMatch :
if MENU_DEBUG :
print >> stderr , 'Unable to reverse URL with kwargs %s' % url_or_dict |
def get_choices ( self ) :
"""stub""" | # ideally would return a displayText object in text . . . except for legacy
# use cases like OEA , it expects a text string .
choices = [ ]
# for current _ choice in self . my _ osid _ object . object _ map [ ' choices ' ] :
for current_choice in self . my_osid_object . _my_map [ 'choices' ] :
filtered_choice = { '... |
def sample_rate ( self , value ) :
"""The sample _ rate property .
Args :
value ( float ) . the property value .""" | if value == self . _defaults [ 'sampleRate' ] and 'sampleRate' in self . _values :
del self . _values [ 'sampleRate' ]
else :
self . _values [ 'sampleRate' ] = value |
def get_allowed_reset_keys_values ( self ) :
"""Get the allowed values for resetting the system .
: returns : A set with the allowed values .""" | reset_keys_action = self . _get_reset_keys_action_element ( )
if not reset_keys_action . allowed_values :
LOG . warning ( 'Could not figure out the allowed values for the ' 'reset keys in secure boot %s' , self . path )
return set ( mappings . SECUREBOOT_RESET_KEYS_MAP_REV )
return set ( [ mappings . SECUREBOOT... |
def editpropset ( self ) :
''': foo = 10''' | self . ignore ( whitespace )
if not self . nextstr ( ':' ) :
self . _raiseSyntaxExpects ( ':' )
relp = self . relprop ( )
self . ignore ( whitespace )
self . nextmust ( '=' )
self . ignore ( whitespace )
valu = self . valu ( )
return s_ast . EditPropSet ( kids = ( relp , valu ) ) |
def load_identity ( config = Config ( ) ) :
"""Load the default identity from the configuration . If there is no default
identity , a KeyError is raised .""" | return Identity ( name = config . get ( 'user' , 'name' ) , email_ = config . get ( 'user' , 'email' ) , ** config . get_section ( 'smtp' ) ) |
def get_pem_entries ( glob_path ) :
'''Returns a dict containing PEM entries in files matching a glob
glob _ path :
A path to certificates to be read and returned .
CLI Example :
. . code - block : : bash
salt ' * ' x509 . get _ pem _ entries " / etc / pki / * . crt "''' | ret = { }
for path in glob . glob ( glob_path ) :
if os . path . isfile ( path ) :
try :
ret [ path ] = get_pem_entry ( text = path )
except ValueError as err :
log . debug ( 'Unable to get PEM entries from %s: %s' , path , err )
return ret |
def session_state_view ( request , template_name , ** kwargs ) :
'Example view that exhibits the use of sessions to store state' | session = request . session
demo_count = session . get ( 'django_plotly_dash' , { } )
ind_use = demo_count . get ( 'ind_use' , 0 )
ind_use += 1
demo_count [ 'ind_use' ] = ind_use
context = { 'ind_use' : ind_use }
session [ 'django_plotly_dash' ] = demo_count
return render ( request , template_name = template_name , con... |
def has_any_roles ( self , * roles ) :
"""Check if user has any of the roles requested
: param roles : tuple of roles string
: return : bool""" | roles = map ( utils . slugify , list ( roles ) )
return True if AuthUserRole . query ( ) . join ( AuthUser ) . filter ( AuthUserRole . name . in_ ( roles ) ) . filter ( AuthUser . id == self . id ) . count ( ) else False |
def ComplementaryColor ( self , mode = 'ryb' ) :
'''Create a new instance which is the complementary color of this one .
Parameters :
: mode :
Select which color wheel to use for the generation ( ryb / rgb ) .
Returns :
A grapefruit . Color instance .
> > > Color . NewFromHsl ( 30 , 1 , 0.5 ) . Compleme... | h , s , l = self . __hsl
if mode == 'ryb' :
h = Color . RgbToRyb ( h )
h = ( h + 180 ) % 360
if mode == 'ryb' :
h = Color . RybToRgb ( h )
return Color ( ( h , s , l ) , 'hsl' , self . __a , self . __wref ) |
def build ( self ) :
"""Finalise the graph , after adding all input files to it .""" | assert not self . final , 'Trying to mutate a final graph.'
# Replace each strongly connected component with a single node ` NodeSet `
for scc in sorted ( nx . kosaraju_strongly_connected_components ( self . graph ) , key = len , reverse = True ) :
if len ( scc ) == 1 :
break
self . shrink_to_node ( Nod... |
def reaction_charge ( reaction , compound_charge ) :
"""Calculate the overall charge for the specified reaction .
Args :
reaction : : class : ` psamm . reaction . Reaction ` .
compound _ charge : a map from each compound to charge values .""" | charge_sum = 0.0
for compound , value in reaction . compounds :
charge = compound_charge . get ( compound . name , float ( 'nan' ) )
charge_sum += charge * float ( value )
return charge_sum |
def is_leaf ( obj ) :
'''the below is for nested - dict
any type is not dict will be treated as a leaf
empty dict will be treated as a leaf
from edict . edict import *
is _ leaf ( 1)
is _ leaf ( { 1:2 } )
is _ leaf ( { } )''' | if ( is_dict ( obj ) ) :
length = obj . __len__ ( )
if ( length == 0 ) :
return ( True )
else :
return ( False )
else :
return ( True ) |
def authorize ( self , username , arguments = [ ] , authen_type = TAC_PLUS_AUTHEN_TYPE_ASCII , priv_lvl = TAC_PLUS_PRIV_LVL_MIN , rem_addr = TAC_PLUS_VIRTUAL_REM_ADDR , port = TAC_PLUS_VIRTUAL_PORT ) :
"""Authorize with a TACACS + server .
: param username :
: param arguments : The authorization arguments
: p... | with self . closing ( ) :
packet = self . send ( TACACSAuthorizationStart ( username , TAC_PLUS_AUTHEN_METH_TACACSPLUS , priv_lvl , authen_type , arguments , rem_addr = rem_addr , port = port ) , TAC_PLUS_AUTHOR )
reply = TACACSAuthorizationReply . unpacked ( packet . body )
logger . debug ( '\n' . join ( [... |
def outbox ( self ) :
""": class : ` Outbox feed < pypump . models . feed . Outbox > ` with all
: class : ` activities < pypump . models . activity . Activity > ` sent by the person .
Example :
> > > for activity in pump . me . outbox [ : 2 ] :
. . . print ( activity )
pypumptest2 unliked a comment in rep... | if self . _outbox is None :
self . _outbox = Outbox ( self . links [ 'activity-outbox' ] , pypump = self . _pump )
return self . _outbox |
def plot_di_mean_bingham ( bingham_dictionary , fignum = 1 , color = 'k' , marker = 'o' , markersize = 20 , label = '' , legend = 'no' ) :
"""see plot _ di _ mean _ ellipse""" | plot_di_mean_ellipse ( bingham_dictionary , fignum = fignum , color = color , marker = marker , markersize = markersize , label = label , legend = legend ) |
def show_clock_output_clock_time_rbridge_id_out ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_clock = ET . Element ( "show_clock" )
config = show_clock
output = ET . SubElement ( show_clock , "output" )
clock_time = ET . SubElement ( output , "clock-time" )
rbridge_id_out = ET . SubElement ( clock_time , "rbridge-id-out" )
rbridge_id_out . text = kwargs . pop ( 'rbridge_i... |
def connect ( * args , ** kwargs ) :
"""Connect to a device , and return its object
Args :
platform : string one of < android | ios | windows >
Returns :
None
Raises :
SyntaxError , EnvironmentError""" | connect_url = _connect_url ( * args )
platform = kwargs . pop ( 'platform' , _detect_platform ( connect_url ) )
cls = None
if platform == 'android' :
os . environ [ 'JSONRPC_TIMEOUT' ] = "60"
# default is 90s which is too long .
devcls = __import__ ( 'atx.drivers.android' )
cls = devcls . drivers . andr... |
def sg_input ( shape = None , dtype = sg_floatx , name = None ) :
r"""Creates a placeholder .
Args :
shape : A tuple / list of integers . If an integers is given , it will turn to a list .
dtype : A data type . Default is float32.
name : A name for the placeholder .
Returns :
A wrapped placeholder ` Ten... | if shape is None :
return tf . placeholder ( dtype , shape = None , name = name )
else :
if not isinstance ( shape , ( list , tuple ) ) :
shape = [ shape ]
return tf . placeholder ( dtype , shape = [ None ] + list ( shape ) , name = name ) |
def quantization_error ( self , X , batch_size = 1 ) :
"""Calculate the quantization error .
Find the the minimum euclidean distance between the units and
some input .
Parameters
X : numpy array .
The input data .
batch _ size : int
The batch size to use for processing .
Returns
error : numpy arra... | dist = self . transform ( X , batch_size )
res = dist . __getattribute__ ( self . valfunc ) ( 1 )
return res |
def get_reconciler ( config , metrics , rrset_channel , changes_channel , ** kw ) :
"""Get a GDNSReconciler client .
A factory function that validates configuration , creates an auth
and : class : ` GDNSClient ` instance , and returns a GDNSReconciler
provider .
Args :
config ( dict ) : Google Cloud Pub /... | builder = reconciler . GDNSReconcilerBuilder ( config , metrics , rrset_channel , changes_channel , ** kw )
return builder . build_reconciler ( ) |
def construct_asset_path ( self , asset_path , css_path , output_filename , variant = None ) :
"""Return a rewritten asset URL for a stylesheet""" | public_path = self . absolute_path ( asset_path , os . path . dirname ( css_path ) . replace ( '\\' , '/' ) )
if self . embeddable ( public_path , variant ) :
return "__EMBED__%s" % public_path
if not posixpath . isabs ( asset_path ) :
asset_path = self . relative_path ( public_path , output_filename )
return a... |
def _validate_data ( self ) :
"""Verifies that the data points contained in the class are valid .""" | msg = "Error! Expected {} timestamps, found {}." . format ( len ( self . _data_points ) , len ( self . _timestamps ) )
if len ( self . _data_points ) != len ( self . _timestamps ) :
raise MonsoonError ( msg ) |
def format ( self , record ) :
"""Formats a log record and serializes to json""" | message_dict = { }
if isinstance ( record . msg , dict ) :
message_dict = record . msg
record . message = None
else :
record . message = record . getMessage ( )
# only format time if needed
if "asctime" in self . _required_fields :
record . asctime = self . formatTime ( record , self . datefmt )
# Displ... |
def main ( ) :
"""Wrapper for Assoc Parsing""" | parser = argparse . ArgumentParser ( description = 'Wrapper for obographs assocmodel library' """
By default, ontologies and assocs are cached locally and synced from a remote sparql endpoint
""" , formatter_class = argpar... |
def get_key ( key = None , keyfile = None ) :
"""returns a key given either its value , a path to it on the filesystem
or as last resort it checks the environment variable CRYPTOYAML _ SECRET""" | if key is None :
if keyfile is None :
key = environ . get ( 'CRYPTOYAML_SECRET' )
if key is None :
raise MissingKeyException ( '''You must either provide a key value,''' ''' a path to a key or its value via the environment variable ''' ''' CRYPTOYAML_SECRET''' )
else :
... |
def processConfig ( self , worker_config ) :
"""Update the pool configuration with a worker configuration .""" | self . config [ 'headless' ] |= worker_config . get ( "headless" , False )
if self . config [ 'headless' ] : # Launch discovery process
if not self . discovery_thread :
self . discovery_thread = discovery . Advertise ( port = "," . join ( str ( a ) for a in self . getPorts ( ) ) , ) |
def get_tails ( chains ) :
"""Args :
An ordered collection of block generators .
Returns
A dictionary of lists of blocks for all chains where :
1 . The first block in all the lists has the same block number
2 . Each list has all blocks from the common block to the current
block in increasing order
3 .... | def get_num_of_oldest ( blocks ) :
return blocks [ 0 ] . num
# Get the first block from every chain
tails = { }
bad_chains = [ ]
for i , chain in chains . items ( ) :
try :
tails [ i ] = [ next ( chain ) ]
except StopIteration :
bad_chains . append ( i )
# Find the minimum block number betwe... |
def decode_texts ( self , encoded_texts , unknown_token = "<UNK>" , inplace = True ) :
"""Decodes the texts using internal vocabulary . The list structure is maintained .
Args :
encoded _ texts : The list of texts to decode .
unknown _ token : The placeholder value for unknown token . ( Default value : " < UN... | if len ( self . _token2idx ) == 0 :
raise ValueError ( "You need to build vocabulary using `build_vocab` before using `decode_texts`" )
if not isinstance ( encoded_texts , list ) : # assume it ' s a numpy array
encoded_texts = encoded_texts . tolist ( )
if not inplace :
encoded_texts = deepcopy ( encoded_te... |
def parse_fragment_definition ( lexer : Lexer ) -> FragmentDefinitionNode :
"""FragmentDefinition""" | start = lexer . token
expect_keyword ( lexer , "fragment" )
# Experimental support for defining variables within fragments changes the grammar
# of FragmentDefinition
if lexer . experimental_fragment_variables :
return FragmentDefinitionNode ( name = parse_fragment_name ( lexer ) , variable_definitions = parse_vari... |
def _build_logging_config ( level , apps_list , verbose , filename = None ) :
"""Return a copy of the DEFAULT _ LOGGING config with installed application
loggers at the given log level . The ' default ' handler is kept as a
console / stream writer unless a filename is passed in , which swaps the stream
handle... | config = copy . deepcopy ( DEFAULT_LOGGING )
# Swap out default stream handler for a file handler , if
# a filename is given
if filename :
config [ 'handlers' ] [ 'default' ] . update ( { 'class' : 'logging.handlers.WatchedFileHandler' , 'filename' : filename , } )
if verbose :
config [ 'handlers' ] [ 'default'... |
def calc_link ( self , src_id , src_port , src_port_name , destination ) :
"""Add a link item for processing later
: param int src _ id : Source node ID
: param int src _ port : Source port ID
: param str src _ port _ name : Source port name
: param dict destination : Destination""" | if destination [ 'device' ] == 'NIO' :
destination [ 'port' ] = destination [ 'port' ] . lower ( )
link = { 'source_node_id' : src_id , 'source_port_id' : src_port , 'source_port_name' : src_port_name , 'source_dev' : self . node [ 'properties' ] [ 'name' ] , 'dest_dev' : destination [ 'device' ] , 'dest_port' : de... |
def main ( ) :
"""Main method .""" | run_config = _parse_args ( sys . argv [ 1 : ] )
gitlab_config = GitLabConfig ( run_config . url , run_config . token )
manager = ProjectVariablesManager ( gitlab_config , run_config . project )
variables = { }
# type : Dict [ str , str ]
for source in run_config . source :
variables . update ( read_variables ( sour... |
def _cmp ( self , other ) :
"""Comparator function for two : class : ` ~ pywbem . CIMQualifierDeclaration `
objects .
The comparison is based on their public attributes , in descending
precedence :
* ` name `
* ` type `
* ` value `
* ` is _ array `
* ` array _ size `
* ` scopes `
* ` overridable... | if self is other :
return 0
try :
assert isinstance ( other , CIMQualifierDeclaration )
except AssertionError :
raise TypeError ( _format ( "other must be CIMQualifierDeclaration, but is: {0}" , type ( other ) ) )
return ( cmpname ( self . name , other . name ) or cmpitem ( self . type , other . type ) or c... |
def _parse ( args ) :
"""Parse passed arguments from shell .""" | ordered = [ ]
opt_full = dict ( )
opt_abbrev = dict ( )
args = args + [ '' ]
# Avoid out of range
i = 0
while i < len ( args ) - 1 :
arg = args [ i ]
arg_next = args [ i + 1 ]
if arg . startswith ( '--' ) :
if arg_next . startswith ( '-' ) :
raise ValueError ( '{} lacks value' . format (... |
def file_cmd ( context , tags , archive , bundle_name , path ) :
"""Add a file to a bundle .""" | bundle_obj = context . obj [ 'db' ] . bundle ( bundle_name )
if bundle_obj is None :
click . echo ( click . style ( f"unknown bundle: {bundle_name}" , fg = 'red' ) )
context . abort ( )
version_obj = bundle_obj . versions [ 0 ]
new_file = context . obj [ 'db' ] . new_file ( path = str ( Path ( path ) . absolute... |
def techport ( Id ) :
'''In order to use this capability , queries can be issued to the system with the following URI
format :
GET / xml - api / id _ parameter
Parameter Required ? Value Description
id _ parameter Yes Type : String
Default : None
The id value of the TechPort record .
TechPort values r... | base_url = 'http://techport.nasa.gov/xml-api/'
if not isinstance ( Id , str ) :
raise ValueError ( "The Id arg you provided is not the type of str" )
else :
base_url += Id
return dispatch_http_get ( base_url ) |
def _deduplicate_items ( cls , items ) :
"Deduplicates assigned paths by incrementing numbering" | counter = Counter ( [ path [ : i ] for path , _ in items for i in range ( 1 , len ( path ) + 1 ) ] )
if sum ( counter . values ( ) ) == len ( counter ) :
return items
new_items = [ ]
counts = defaultdict ( lambda : 0 )
for i , ( path , item ) in enumerate ( items ) :
if counter [ path ] > 1 :
path = pat... |
def processRequest ( cls , ps , ** kw ) :
"""invokes callback that should return a ( request , response ) tuple .
representing the SOAP request and response respectively .
ps - - ParsedSoap instance representing HTTP Body .
request - - twisted . web . server . Request""" | resource = kw [ 'resource' ]
request = kw [ 'request' ]
method = getattr ( resource , 'soap_%s' % _get_element_nsuri_name ( ps . body_root ) [ - 1 ] )
try :
req_pyobj , rsp_pyobj = method ( ps , request = request )
except TypeError , ex :
log . err ( 'ERROR: service %s is broken, method MUST return request, res... |
def chi_a ( mass1 , mass2 , spin1z , spin2z ) :
"""Returns the aligned mass - weighted spin difference from mass1 , mass2,
spin1z , and spin2z .""" | return ( spin2z * mass2 - spin1z * mass1 ) / ( mass2 + mass1 ) |
def collect ( config , pconn ) :
"""All the heavy lifting done here""" | # initialize collection target
# tar files
if config . analyze_file :
logger . debug ( "Client analyzing a compress filesystem." )
target = { 'type' : 'compressed_file' , 'name' : os . path . splitext ( os . path . basename ( config . analyze_file ) ) [ 0 ] , 'location' : config . analyze_file }
# mountpoints
e... |
def KeyValue ( self , row = None ) :
"""Returns the super key value for the row .""" | if not row :
if self . _iterator : # If we are inside an iterator use current row iteration .
row = self [ self . _iterator ]
else :
row = self . row
# If no superkey then use row number .
if not self . superkey :
return [ "%s" % row . row ]
sorted_list = [ ]
for header in self . header :
... |
def get_child_family_ids ( self , family_id ) :
"""Gets the child ` ` Ids ` ` of the given family .
arg : family _ id ( osid . id . Id ) : the ` ` Id ` ` to query
return : ( osid . id . IdList ) - the children of the family
raise : NotFound - ` ` family _ id ` ` is not found
raise : NullArgument - ` ` famil... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ child _ bin _ ids
if self . _catalog_session is not None :
return self . _catalog_session . get_child_catalog_ids ( catalog_id = family_id )
return self . _hierarchy_session . get_children ( id_ = family_id ) |
def current_index ( self ) :
"""Get the currently selected index in the parent table view .""" | i = self . _parent . proxy_model . mapToSource ( self . _parent . currentIndex ( ) )
return i |
def get_tags_of_letter_per_page ( self , letter_id , per_page = 1000 , page = 1 ) :
"""Get tags of letter per page
: param letter _ id : the letter id
: param per _ page : How many objects per page . Default : 1000
: param page : Which page . Default : 1
: return : list""" | return self . _get_resource_per_page ( resource = LETTER_TAGS , per_page = per_page , page = page , params = { 'letter_id' : letter_id } , ) |
def process_fastq_plain ( fastq , ** kwargs ) :
"""Combine metrics extracted from a fastq file .""" | logging . info ( "Nanoget: Starting to collect statistics from plain fastq file." )
inputfastq = handle_compressed_input ( fastq )
return ut . reduce_memory_usage ( pd . DataFrame ( data = [ res for res in extract_from_fastq ( inputfastq ) if res ] , columns = [ "quals" , "lengths" ] ) . dropna ( ) ) |
def check_spectator ( node_method ) :
"""Decorator for : class : ` Node ` methods . Raise ` SpectatorNodeError ` .""" | from functools import wraps
@ wraps ( node_method )
def wrapper ( * args , ** kwargs ) :
node = args [ 0 ]
if node . in_spectator_mode : # raise node . SpectatorError ( " You should not call this method when the node in spectator _ mode " )
# warnings . warn ( " You should not call % s when the node in spec... |
def _at_while ( self , calculator , rule , scope , block ) :
"""Implements @ while""" | first_condition = condition = calculator . calculate ( block . argument )
while condition :
inner_rule = rule . copy ( )
inner_rule . unparsed_contents = block . unparsed_contents
if not self . should_scope_loop_in_rule ( inner_rule ) : # DEVIATION : Allow not creating a new namespace
inner_rule . n... |
def loadMsbwt ( self , dirName , logger ) :
'''This functions loads a BWT file and constructs total counts , indexes start positions , and constructs an FM index in memory
@ param dirName - the directory to load , inside should be ' < DIR > / comp _ msbwt . npy ' or it will fail''' | # open the file with our BWT in it
self . dirName = dirName
self . bwt = np . load ( self . dirName + '/comp_msbwt.npy' , 'r' )
# build auxiliary structures
self . constructTotalCounts ( logger )
self . constructIndexing ( )
self . constructFMIndex ( logger ) |
def set_published_date ( self , published_date = None ) :
"""Sets the published date .
: param published _ date : the new published date
: type published _ date : ` ` osid . calendaring . DateTime ` `
: raise : ` ` InvalidArgument ` ` - - ` ` published _ date ` ` is invalid
: raise : ` ` NoAccess ` ` - - ` ... | if published_date is None :
raise NullArgument ( )
metadata = Metadata ( ** settings . METADATA [ 'published_date' ] )
if metadata . is_read_only ( ) :
raise NoAccess ( )
if self . _is_valid_input ( published_date , metadata , array = False ) :
self . _my_map [ 'publishedDate' ] = published_date
# This ... |
def set_power ( self , sid , state ) :
"""Sets the power state of the smart power strip .""" | sid_mask = 0x01 << ( sid - 1 )
return self . set_power_mask ( sid_mask , state ) |
def cli_values ( self , argv ) :
"""Parse command - line arguments into values .
Parses arguments provided on the command - line ( or sys . argv ) . Only
returns arguments that are explicitly supplied , so we strip out
defaults and validation rules like ` required ` in this call .""" | options = [ ]
for option in self . _options :
kwargs = option . kwargs . copy ( )
# Must explicitly set default to None or ` store _ true ` and
# ` store _ false ` actions will set the value to true or false ,
# respectively .
kwargs [ 'default' ] = None
kwargs [ 'required' ] = False
options... |
def _load_11_5_4 ( self , ** kwargs ) :
"""Custom _ load method to accommodate for issue in 11.5.4,
where an existing object would return 404 HTTP response .""" | if 'uri' in self . _meta_data :
error = "There was an attempt to assign a new uri to this " "resource, the _meta_data['uri'] is %s and it should" " not be changed." % ( self . _meta_data [ 'uri' ] )
raise URICreationCollision ( error )
requests_params = self . _handle_requests_params ( kwargs )
self . _check_lo... |
async def _reconnect ( self , last_error ) :
"""Cleanly disconnects and then reconnects .""" | self . _log . debug ( 'Closing current connection...' )
await self . _connection . disconnect ( )
await helpers . _cancel ( self . _log , send_loop_handle = self . _send_loop_handle , recv_loop_handle = self . _recv_loop_handle )
# TODO See comment in ` _ start _ reconnect `
# Perhaps this should be the last thing to d... |
def _process_map_rule ( self , line ) :
"""Process the line string containing a map rule .""" | result = self . REPLACE_REGEX . match ( line )
if result is not None :
what = self . _process_first_group ( result . group ( 1 ) )
replacement = self . _process_second_group ( result . group ( 2 ) )
for char in what :
self . trans_map [ char ] = replacement
self . log ( [ u"Adding rule: repl... |
def getProperty ( self , key , defaultValue = None ) :
"""Fetch the value associated with the key ` ` key ` ` in the ` Properties `
object . If the key is not present , ` defaults ` is checked , and then
* its * ` defaults ` , etc . , until either a value for ` ` key ` ` is found or
the next ` defaults ` is `... | try :
return self [ key ]
except KeyError :
if self . defaults is not None :
return self . defaults . getProperty ( key , defaultValue )
else :
return defaultValue |
def parse_workflow_declaration ( self , wf_declaration_subAST ) :
'''Parses a WDL declaration AST subtree into a string and a python
dictionary containing its ' type ' and ' value ' .
For example :
var _ name = refIndex
var _ map = { ' type ' : File ,
' value ' : bamIndex }
: param wf _ declaration _ su... | var_map = OrderedDict ( )
var_name = self . parse_declaration_name ( wf_declaration_subAST . attr ( "name" ) )
var_type = self . parse_declaration_type ( wf_declaration_subAST . attr ( "type" ) )
var_expressn = self . parse_declaration_expressn ( wf_declaration_subAST . attr ( "expression" ) , es = '' )
var_map [ 'name... |
def _windows_platform_data ( ) :
'''Use the platform module for as much as we can .''' | # Provides :
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard . productname
# motherboard . serialnumber
# virtual
if not HAS_WMI :
return { }
w... |
def total_exchange_balances ( services = None , verbose = None , timeout = None , by_service = False ) :
"""Returns all balances for all currencies for all exchanges""" | balances = defaultdict ( lambda : 0 )
if not services :
services = [ x ( verbose = verbose , timeout = timeout ) for x in ExchangeUniverse . get_authenticated_services ( ) ]
for e in services :
try :
more_balances = e . get_total_exchange_balances ( )
if by_service :
balances [ e . _... |
def unpack ( self , source : IO ) :
"""Read the FieldTable from the file - like object ` source ` .
. . note : :
Advanced usage only . You will typically never need to call this
method as it will be called for you when loading a ClassFile .
: param source : Any file - like object providing ` read ( ) `""" | field_count = unpack ( '>H' , source . read ( 2 ) ) [ 0 ]
for _ in repeat ( None , field_count ) :
field = Field ( self . _cf )
field . unpack ( source )
self . append ( field ) |
def get_one ( self , cls = None , ** kwargs ) :
"""Returns a one case .""" | case = cls ( ) if cls else self . _CasesClass ( )
for attr , value in kwargs . iteritems ( ) :
setattr ( case , attr , value )
return case |
def Font ( name = None , source = "sys" , italic = False , bold = False , size = 20 ) :
"""Unifies loading of fonts .
: param name : name of system - font or filepath , if None is passed the default
system - font is loaded
: type name : str
: param source : " sys " for system font , or " file " to load a fi... | assert source in [ "sys" , "file" ]
if not name :
return pygame . font . SysFont ( pygame . font . get_default_font ( ) , size , bold = bold , italic = italic )
if source == "sys" :
return pygame . font . SysFont ( name , size , bold = bold , italic = italic )
else :
f = pygame . font . Font ( name , size )... |
def cat_acc ( y_true , y_pred ) :
"""Categorical accuracy""" | return np . mean ( y_true . argmax ( axis = 1 ) == y_pred . argmax ( axis = 1 ) ) |
def getDigitalMinimum ( self , chn = None ) :
"""Returns the minimum digital value of signal edfsignal .
Parameters
chn : int
channel number
Examples
> > > import pyedflib
> > > f = pyedflib . data . test _ generator ( )
> > > f . getDigitalMinimum ( 0)
-32768
> > > f . _ close ( )
> > > del f""... | if chn is not None :
if 0 <= chn < self . signals_in_file :
return self . digital_min ( chn )
else :
return 0
else :
digMin = np . zeros ( self . signals_in_file )
for i in np . arange ( self . signals_in_file ) :
digMin [ i ] = self . digital_min ( i )
return digMin |
def _parse_response_types ( argspec , attrs ) :
"""from the given parameters , return back the response type dictionaries .""" | return_type = argspec . annotations . get ( "return" ) or None
type_description = attrs . parameter_descriptions . get ( "return" , "" )
response_types = attrs . response_types . copy ( )
if return_type or len ( response_types ) == 0 :
response_types [ attrs . success_code ] = ResponseType ( type = return_type , ty... |
def run ( self ) :
"""run all configured stages""" | self . sanity_check ( )
# TODO - check for devel
# if not self . version :
# raise Exception ( " no version " )
# XXX check attr exist
if not self . release_environment :
raise Exception ( "no instance name" )
time_start = time . time ( )
cwd = os . getcwd ( )
who = getpass . getuser ( )
self . _make_outdirs ( )
ap... |
def _connect ( self ) :
"""Connects our client socket to the backend socket""" | if self is None :
return
comm ( 'connecting to 127.0.0.1:%d' , self . _port )
address = QtNetwork . QHostAddress ( '127.0.0.1' )
self . connectToHost ( address , self . _port )
if sys . platform == 'darwin' :
self . waitForConnected ( ) |
def setup_dashboard_panels_visibility_registry ( section_name ) :
"""Initializes the values for panels visibility in registry _ records . By
default , only users with LabManager or Manager roles can see the panels .
: param section _ name :
: return : An string like : " role1 , yes , role2 , no , rol3 , no " ... | registry_info = get_dashboard_registry_record ( )
role_permissions_list = [ ]
# Getting roles defined in the system
roles = [ ]
acl_users = get_tool ( "acl_users" )
roles_tree = acl_users . portal_role_manager . listRoleIds ( )
for role in roles_tree :
roles . append ( role )
# Set view permissions to each role as ... |
def create_contact ( self , attrs , members = None , folder_id = None , tags = None ) :
"""Create a contact
Does not include VCARD nor group membership yet
XML example :
< cn l = " 7 > # # ContactSpec
< a n = " lastName " > MARTIN < / a >
< a n = " firstName " > Pierre < / a >
< a n = " email " > pmarti... | cn = { }
if folder_id :
cn [ 'l' ] = str ( folder_id )
if tags :
tags = self . _return_comma_list ( tags )
cn [ 'tn' ] = tags
if members :
cn [ 'm' ] = members
attrs = [ { 'n' : k , '_content' : v } for k , v in attrs . items ( ) ]
cn [ 'a' ] = attrs
resp = self . request_single ( 'CreateContact' , { 'c... |
def _format_assertmsg ( obj ) :
"""Format the custom assertion message given .
For strings this simply replaces newlines with ' \n ~ ' so that
util . format _ explanation ( ) will preserve them instead of escaping
newlines . For other objects py . io . saferepr ( ) is used first .""" | # reprlib appears to have a bug which means that if a string
# contains a newline it gets escaped , however if an object has a
# . _ _ repr _ _ ( ) which contains newlines it does not get escaped .
# However in either case we want to preserve the newline .
if py . builtin . _istext ( obj ) or py . builtin . _isbytes ( ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.