signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def origin ( self , origin ) :
"""Set the origin . Pass a length three tuple of floats""" | ox , oy , oz = origin [ 0 ] , origin [ 1 ] , origin [ 2 ]
self . SetOrigin ( ox , oy , oz )
self . Modified ( ) |
def printable_name ( column , path = None ) :
"""Provided for debug output when rendering conditions .
User . name [ 3 ] [ " foo " ] [ 0 ] [ " bar " ] - > name [ 3 ] . foo [ 0 ] . bar""" | pieces = [ column . name ]
path = path or path_of ( column )
for segment in path :
if isinstance ( segment , str ) :
pieces . append ( segment )
else :
pieces [ - 1 ] += "[{}]" . format ( segment )
return "." . join ( pieces ) |
def get_tunnel_info_input_filter_type_filter_by_sip_src_ip ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_tunnel_info = ET . Element ( "get_tunnel_info" )
config = get_tunnel_info
input = ET . SubElement ( get_tunnel_info , "input" )
filter_type = ET . SubElement ( input , "filter-type" )
filter_by_sip = ET . SubElement ( filter_type , "filter-by-sip" )
src_ip = ET . SubElement ( filt... |
def _vmomentsurfaceIntegrand ( vz , vR , vT , R , z , df , sigmaR1 , gamma , sigmaz1 , n , m , o ) : # pragma : no cover because this is too slow ; a warning is shown
"""Internal function that is the integrand for the vmomentsurface mass integration""" | return vR ** n * vT ** m * vz ** o * df ( R , vR * sigmaR1 , vT * sigmaR1 * gamma , z , vz * sigmaz1 , use_physical = False ) |
def write_to_fitsfile ( self , fitsfile , clobber = True ) :
"""Write this mapping to a FITS file , to avoid having to recompute it""" | from fermipy . skymap import Map
hpx_header = self . _hpx . make_header ( )
index_map = Map ( self . ipixs , self . wcs )
mult_map = Map ( self . mult_val , self . wcs )
prim_hdu = index_map . create_primary_hdu ( )
mult_hdu = index_map . create_image_hdu ( )
for key in [ 'COORDSYS' , 'ORDERING' , 'PIXTYPE' , 'ORDERING... |
def match_lists ( pos1 , pos2 , tolerance = MATCH_TOLERANCE , spherical = False ) :
"""Given two sets of x / y positions match the lists , uniquely .
: rtype : numpy . ma , numpy . ma
: param pos1 : list of x / y positions .
: param pos2 : list of x / y positions .
: param tolerance : float distance , in pi... | assert isinstance ( pos1 , numpy . ndarray )
assert isinstance ( pos2 , numpy . ndarray )
# build some arrays to hold the index of things that matched between lists .
npts2 = npts1 = 0
if len ( pos1 ) > 0 :
npts1 = len ( pos1 [ : , 0 ] )
pos1_idx_array = numpy . arange ( npts1 , dtype = numpy . int16 )
if len ( pos... |
def extern_store_f64 ( self , context_handle , f64 ) :
"""Given a context and double , return a new Handle to represent the double .""" | c = self . _ffi . from_handle ( context_handle )
return c . to_value ( f64 ) |
def get_queryset ( self ) :
"""Get QuerySet from cached widget .""" | kwargs = { model_field_name : self . request . GET . get ( form_field_name ) for form_field_name , model_field_name in self . widget . dependent_fields . items ( ) if form_field_name in self . request . GET and self . request . GET . get ( form_field_name , '' ) != '' }
return self . widget . filter_queryset ( self . r... |
def derive_queryset ( self , ** kwargs ) :
"""Derives our queryset .""" | # get our parent queryset
queryset = super ( SmartListView , self ) . get_queryset ( ** kwargs )
# apply any filtering
search_fields = self . derive_search_fields ( )
search_query = self . request . GET . get ( 'search' )
if search_fields and search_query :
term_queries = [ ]
for term in search_query . split ( ... |
def parse_package_ref ( self , ref ) :
"""Return tuple of architecture , package _ name , version , id""" | if not ref :
return None
parsed = re . match ( '(.*)\ (.*)\ (.*)\ (.*)' , ref )
return parsed . groups ( ) |
def print_prediction ( self , ptup , precision = 2 ) :
"""Print a summary of a predicted position .
The argument * ptup * is a tuple returned by : meth : ` predict ` . It is
printed to : data : ` sys . stdout ` in a reasonable format that uses Unicode
characters .""" | from . import ellipses
bestra , bestdec , maj , min , pa = ptup
f = ellipses . sigmascale ( 1 )
maj *= R2A
min *= R2A
pa *= R2D
print_ ( 'position =' , fmtradec ( bestra , bestdec , precision = precision ) )
print_ ( 'err(1σ) = %.*f" × %.*f" @ %.0f°' % ( precision , maj * f , precision , min * f , pa ) ) |
def has_node ( self , n , t = None ) :
"""Return True if the graph , at time t , contains the node n .
Parameters
n : node
t : snapshot id ( default None )
If None return the presence of the node in the flattened graph .
Examples
> > > G = dn . DynGraph ( ) # or DiGraph , MultiGraph , MultiDiGraph , etc... | if t is None :
try :
return n in self . _node
except TypeError :
return False
else :
deg = list ( self . degree ( [ n ] , t ) . values ( ) )
if len ( deg ) > 0 :
return deg [ 0 ] > 0
else :
return False |
def get_files ( path , ext = [ ] , include = True ) :
"""遍历提供的文件夹的所有子文件夹 , 饭后生成器对象 。
: param str path : 待处理的文件夹 。
: param list ext : 扩展名列表 。
: param bool include : 若值为 True , 代表 ext 提供的是包含列表 ;
否则是排除列表 。
: returns : 一个生成器对象 。""" | has_ext = len ( ext ) > 0
for p , d , fs in os . walk ( path ) :
for f in fs :
if has_ext :
in_ext = False
for name in ext :
if f . endswith ( name ) :
in_ext = True
break
if ( include and in_ext ) or ( not include a... |
def get ( self , sid ) :
"""Constructs a PhoneNumberContext
: param sid : The unique string that identifies the resource
: returns : twilio . rest . proxy . v1 . service . phone _ number . PhoneNumberContext
: rtype : twilio . rest . proxy . v1 . service . phone _ number . PhoneNumberContext""" | return PhoneNumberContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = sid , ) |
def add_dataset_to_collection ( dataset_id , collection_id , ** kwargs ) :
"""Add a single dataset to a dataset collection .""" | collection_i = _get_collection ( collection_id )
collection_item = _get_collection_item ( collection_id , dataset_id )
if collection_item is not None :
raise HydraError ( "Dataset Collection %s already contains dataset %s" , collection_id , dataset_id )
new_item = DatasetCollectionItem ( )
new_item . dataset_id = d... |
def recall ( result , reference ) :
"""Recall .
Parameters
result : array _ like
Input data containing objects . Can be any type but will be converted
into binary : background where 0 , object everywhere else .
reference : array _ like
Input data containing objects . Can be any type but will be converte... | result = numpy . atleast_1d ( result . astype ( numpy . bool ) )
reference = numpy . atleast_1d ( reference . astype ( numpy . bool ) )
tp = numpy . count_nonzero ( result & reference )
fn = numpy . count_nonzero ( ~ result & reference )
try :
recall = tp / float ( tp + fn )
except ZeroDivisionError :
recall = ... |
def copy ( self , new_name = None ) :
"""Returns a deep copy of the system
Parameters
new _ name : str , optional
Set a new meta name parameter .
Default : < old _ name > _ copy""" | _tmp = copy . deepcopy ( self )
if not new_name :
new_name = self . name + '_copy'
if str ( type ( self ) ) == "<class 'pymrio.core.mriosystem.IOSystem'>" :
_tmp . meta . note ( 'IOSystem copy {new} based on {old}' . format ( new = new_name , old = self . meta . name ) )
_tmp . meta . change_meta ( 'name' ,... |
def _query ( self , sql , * args ) :
"""Executes the specified ` sql ` query and returns the cursor""" | if not self . _con :
logger . debug ( ( "Open MBTiles file '%s'" ) % self . filename )
self . _con = sqlite3 . connect ( self . filename )
self . _cur = self . _con . cursor ( )
sql = ' ' . join ( sql . split ( ) )
logger . debug ( ( "Execute query '%s' %s" ) % ( sql , args ) )
try :
self . _cur . execu... |
def register_request ( self , valid_responses ) :
"""Register a RPC request .
: param list valid _ responses : List of possible Responses that
we should be waiting for .
: return :""" | uuid = str ( uuid4 ( ) )
self . _response [ uuid ] = [ ]
for action in valid_responses :
self . _request [ action ] = uuid
return uuid |
def init ( track_log_handler ) :
"""( Re ) initialize track ' s file handler for track package logger .
Adds a stdout - printing handler automatically .""" | logger = logging . getLogger ( __package__ )
# TODO ( just document prominently )
# assume only one trial can run at once right now
# multi - concurrent - trial support will require complex filter logic
# based on the currently - running trial ( maybe we shouldn ' t allow multiple
# trials on different python threads ,... |
def new ( path = '.' , template = None ) :
"""Creates a new project""" | path = abspath ( path . rstrip ( sep ) )
template = template or DEFAULT_TEMPLATE_URL
render_skeleton ( template , path , include_this = [ '.gitignore' ] , filter_this = [ '~*' , '*.py[co]' , '__pycache__' , '__pycache__/*' , '.git' , '.git/*' , '.hg' , '.hg/*' , '.svn' , '.svn/*' , ] )
print ( HELP_MSG % ( path , ) ) |
def _get_parents ( folds , linenum ) :
"""Get the parents at a given linenum .
If parents is empty , then the linenum belongs to the module .
Parameters
folds : list of : class : ` FoldScopeHelper `
linenum : int
The line number to get parents for . Typically this would be the
cursor position .
Return... | # Note : this might be able to be sped up by finding some kind of
# abort - early condition .
parents = [ ]
for fold in folds :
start , end = fold . range
if linenum >= start and linenum <= end :
parents . append ( fold )
else :
continue
return parents |
def _properties_from_dict ( d , key_name = 'key' ) :
'''Transforms dictionary into pipeline object properties .
The output format conforms to boto ' s specification .
Example input :
' a ' : ' 1 ' ,
' ref ' : ' 2'
Example output :
' key ' : ' a ' ,
' stringValue ' : ' 1 ' ,
' key ' : ' b ' ,
' ref... | fields = [ ]
for key , value in six . iteritems ( d ) :
if isinstance ( value , dict ) :
fields . append ( { key_name : key , 'refValue' : value [ 'ref' ] , } )
else :
fields . append ( { key_name : key , 'stringValue' : value , } )
return fields |
def _getStore ( self ) :
"""Get the Store used for FTS .
If it does not exist , it is created and initialised .""" | storeDir = self . store . newDirectory ( self . indexDirectory )
if not storeDir . exists ( ) :
store = Store ( storeDir )
self . _initStore ( store )
return store
else :
return Store ( storeDir ) |
def hist ( self , xdata , disp = True , ** kwargs ) :
'''Graphs a histogram .
xdata : List of values to bin . Can optionally include a header , see testGraph _ barAndHist . py in https : / / github . com / Dfenestrator / GooPyCharts for an example .
disp : for displaying plots immediately . Set to True by defau... | # combine data into proper format
data = [ self . xlabel ] + xdata
# Include other options , supplied by * * kwargs
other = ''
for option in kwargs :
other += option + ': ' + kwargs [ option ] + ',\n'
# input argument format to template is in dictionary format ( see template for where variables are inserted )
argDi... |
def get_entry_point ( key , value ) :
"""Check if registered entry point is available for a given name and
load it . Otherwise , return None .
key ( unicode ) : Entry point name .
value ( unicode ) : Name of entry point to load .
RETURNS : The loaded entry point or None .""" | for entry_point in pkg_resources . iter_entry_points ( key ) :
if entry_point . name == value :
return entry_point . load ( ) |
def cmd_ip2asn ( ip ) :
"""Use Team Cymru ip2asn service to get information about a public IPv4 / IPv6.
Reference : https : / / www . team - cymru . com / IP - ASN - mapping . html
$ habu . ip2asn 8.8.8.8
" asn " : " 15169 " ,
" net " : " 8.8.8.0/24 " ,
" cc " : " US " ,
" rir " : " ARIN " ,
" asname ... | try :
ipaddress . ip_address ( ip )
except ValueError :
logging . error ( 'Invalid IP address' )
sys . exit ( 1 )
data = ip2asn ( ip )
print ( json . dumps ( data , indent = 4 ) ) |
def has ( self , querypart_name , value = None ) :
"""Returns ` ` True ` ` if ` ` querypart _ name ` ` with ` ` value ` ` is set . For example
you can check if you already used condition by ` ` sql . has ( ' where ' ) ` ` .
If you want to check for more information , for example if that condition
also contain... | if super ( ) . has ( querypart_name , value ) :
return True
if not value :
return super ( ) . has ( 'select_options' , querypart_name )
return False |
def validate ( self , bug : Bug , verbose : bool = True ) -> bool :
"""Checks that a given bug successfully builds , and that it produces an
expected set of test suite outcomes .
Parameters :
verbose : toggles verbosity of output . If set to ` True ` , the
outcomes of each test will be printed to the standa... | # attempt to rebuild - - don ' t worry , Docker ' s layer caching prevents us
# from actually having to rebuild everything from scratch : - )
try :
self . build ( bug , force = True , quiet = True )
except docker . errors . BuildError :
print ( "failed to build bug: {}" . format ( self . identifier ) )
retu... |
def do_edit ( self , line ) :
"""edit FILE
Copies the file locally , launches an editor to edit the file .
When the editor exits , if the file was modified then its copied
back .
You can specify the editor used with the - - editor command line
option when you start rshell , or by using the VISUAL or EDITO... | if len ( line ) == 0 :
print_err ( "Must provide a filename" )
return
filename = resolve_path ( line )
dev , dev_filename = get_dev_and_path ( filename )
mode = auto ( get_mode , filename )
if mode_exists ( mode ) and mode_isdir ( mode ) :
print_err ( "Unable to edit directory '{}'" . format ( filename ) )
... |
def DeregisterAnalyzer ( cls , analyzer_class ) :
"""Deregisters a analyzer class .
The analyzer classes are identified based on their lower case name .
Args :
analyzer _ class ( type ) : class object of the analyzer .
Raises :
KeyError : if analyzer class is not set for the corresponding name .""" | analyzer_name = analyzer_class . NAME . lower ( )
if analyzer_name not in cls . _analyzer_classes :
raise KeyError ( 'analyzer class not set for name: {0:s}' . format ( analyzer_class . NAME ) )
del cls . _analyzer_classes [ analyzer_name ] |
def is_list_sorted ( lst ) :
"""This function checks if a given list is sorted in ascending order or not .
> > > is _ list _ sorted ( [ 1 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 17 ] )
True
> > > is _ list _ sorted ( [ 1 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 20 , 17 ] )
False
> > > is _ list _ sorted ( [ 1 , 2 ,... | return all ( lst [ i ] <= lst [ i + 1 ] for i in range ( len ( lst ) - 1 ) ) |
def en010 ( self , value = None ) :
"""Corresponds to IDD Field ` en010 `
mean coincident dry - bulb temperature to
Enthalpy corresponding to 1.0 % annual cumulative frequency of occurrence
Args :
value ( float ) : value for IDD Field ` en010 `
Unit : kJ / kg
if ` value ` is None it will not be checked ... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `en010`' . format ( value ) )
self . _en010 = value |
def connected_components_subgraphs ( self , copy = True ) :
"""Iterates over connected components in current : class : ` BreakpointGraph ` object , and yields new instances of : class : ` BreakpointGraph ` with respective information deep - copied by default ( week reference is possible of specified in method call ... | for component in nx . connected_components ( self . bg ) :
component = self . bg . subgraph ( component )
if copy :
component . copy ( )
yield BreakpointGraph ( component ) |
def delete_lines ( self , lines ) :
"""Delete all lines with given line numbers .
Args :
lines ( list ) : List of integers corresponding to line numbers to delete""" | for k , i in enumerate ( lines ) :
del self [ i - k ] |
def validate_input ( self , input_string , validators ) :
"""Validate the given input string against the specified list of validators .
: param input _ string : the input string to verify .
: param validators : the list of validators .
: raises InvalidValidator if the list of validators does not provide a val... | validation_result = True
if isinstance ( validators , BaseValidator ) :
validators = [ validators ]
elif validators is None :
validators = [ ]
if isinstance ( validators , list ) :
validation_results = [ ]
for validator in validators :
if isinstance ( validator , BaseValidator ) :
va... |
def two_qubit_randomized_benchmarking ( sampler : sim . Sampler , first_qubit : devices . GridQubit , second_qubit : devices . GridQubit , * , num_clifford_range : Sequence [ int ] = range ( 5 , 50 , 5 ) , num_circuits : int = 20 , repetitions : int = 1000 ) -> RandomizedBenchMarkResult :
"""Clifford - based random... | cliffords = _single_qubit_cliffords ( )
cfd_matrices = _two_qubit_clifford_matrices ( first_qubit , second_qubit , cliffords )
gnd_probs = [ ]
for num_cfds in num_clifford_range :
gnd_probs_l = [ ]
for _ in range ( num_circuits ) :
circuit = _random_two_q_clifford ( first_qubit , second_qubit , num_cfds... |
def get_stdlib_modules ( ) :
"""Returns a list containing the names of all the modules available in the
standard library .
Based on the function get _ root _ modules from the IPython project .
Present in IPython . core . completerlib in v0.13.1
Copyright ( C ) 2010-2011 The IPython Development Team .
Dist... | modules = list ( sys . builtin_module_names )
for path in sys . path [ 1 : ] :
if 'site-packages' not in path :
modules += module_list ( path )
modules = set ( modules )
if '__init__' in modules :
modules . remove ( '__init__' )
modules = list ( modules )
return modules |
def redo ( self , channel , image ) :
"""Called from the reference viewer shell when a new image has
been added to a channel .""" | chname = channel . name
# Only update our GUI if the activity is in the focused
# channel
if self . active == chname :
imname = image . get ( 'name' , 'NONAME' )
self . set_info ( "A new image '%s' has been added to channel %s" % ( imname , chname ) )
return True |
def create_name_and_type ( self , name : str , descriptor : str ) -> NameAndType :
"""Creates a new : class : ` ConstantNameAndType ` , adding it to the pool and
returning it .
: param name : The name of the class .
: param descriptor : The descriptor for ` name ` .""" | self . append ( ( 12 , self . create_utf8 ( name ) . index , self . create_utf8 ( descriptor ) . index ) )
return self . get ( self . raw_count - 1 ) |
def delete_attachment ( request , link_field = None , uri = None ) :
"""Delete existing file and link .""" | if link_field is None :
link_field = "record_uri"
if uri is None :
uri = record_uri ( request )
# Remove file .
filters = [ Filter ( link_field , uri , core_utils . COMPARISON . EQ ) ]
storage = request . registry . storage
file_links , _ = storage . get_all ( "" , FILE_LINKS , filters = filters )
for link in f... |
def connect ( self , dests = [ ] , name = None , id = '' , props = { } ) :
'''Connect this port to other ports .
After the connection has been made , a delayed reparse of the
connections for this and the destination port will be triggered .
@ param dests A list of the destination Port objects . Must be provid... | with self . _mutex :
if self . porttype == 'DataInPort' or self . porttype == 'DataOutPort' :
for prop in props :
if prop in self . properties :
if props [ prop ] not in [ x . strip ( ) for x in self . properties [ prop ] . split ( ',' ) ] and 'any' not in self . properties [ pro... |
def _decorate_fun ( self , fun ) :
"""Decorate function fun""" | msg = "Function %s is deprecated" % fun . __name__
if self . extra :
msg += "; %s" % self . extra
def wrapped ( * args , ** kwargs ) :
warnings . warn ( msg , category = DeprecationWarning )
return fun ( * args , ** kwargs )
wrapped . __name__ = fun . __name__
wrapped . __dict__ = fun . __dict__
wrapped . _... |
def rate_sp ( self ) :
"""Sets the rate _ sp at which the servo travels from 0 to 100.0 % ( half of the full
range of the servo ) . Units are in milliseconds . Example : Setting the rate _ sp
to 1000 means that it will take a 180 degree servo 2 second to move from 0
to 180 degrees . Note : Some servo controll... | self . _rate_sp , value = self . get_attr_int ( self . _rate_sp , 'rate_sp' )
return value |
def LoadConfig ( config_obj , config_file = None , config_fd = None , secondary_configs = None , contexts = None , reset = False , parser = ConfigFileParser ) :
"""Initialize a ConfigManager with the specified options .
Args :
config _ obj : The ConfigManager object to use and update . If None , one will be
c... | if config_obj is None or reset : # Create a new config object .
config_obj = _CONFIG . MakeNewConfig ( )
# Initialize the config with a filename or file like object .
if config_file is not None :
config_obj . Initialize ( filename = config_file , must_exist = True , parser = parser )
elif config_fd is not None ... |
def get_connected_service_details ( self , project_id , name ) :
"""GetConnectedServiceDetails .
[ Preview API ]
: param str project _ id :
: param str name :
: rtype : : class : ` < WebApiConnectedServiceDetails > < azure . devops . v5_0 . core . models . WebApiConnectedServiceDetails > `""" | route_values = { }
if project_id is not None :
route_values [ 'projectId' ] = self . _serialize . url ( 'project_id' , project_id , 'str' )
if name is not None :
route_values [ 'name' ] = self . _serialize . url ( 'name' , name , 'str' )
response = self . _send ( http_method = 'GET' , location_id = 'b4f70219-e1... |
def tag ( s , tokenize = True , encoding = "utf-8" , ** kwargs ) :
"""Returns a list of ( token , tag ) - tuples from the given string .""" | tags = [ ]
for sentence in parse ( s , tokenize , True , False , False , False , encoding , ** kwargs ) . split ( ) :
for token in sentence :
tags . append ( ( token [ 0 ] , token [ 1 ] ) )
return tags |
def _dumps ( self , obj ) :
"""If : prop : serialized is True , @ obj will be serialized
using : prop : serializer""" | if not self . serialized :
return obj
return self . serializer . dumps ( obj ) |
def _set_value ( value ) :
'''A function to detect if user is trying to pass a dictionary or list . parse it and return a
dictionary list or a string''' | # don ' t continue if already an acceptable data - type
if isinstance ( value , bool ) or isinstance ( value , dict ) or isinstance ( value , list ) :
return value
# check if json
if value . startswith ( 'j{' ) and value . endswith ( '}j' ) :
value = value . replace ( 'j{' , '{' )
value = value . replace ( ... |
def dropEvent ( self , event ) :
"""Listens for query ' s being dragged and dropped onto this tree .
: param event | < QDropEvent >""" | # overload the current filtering options
data = event . mimeData ( )
if data . hasFormat ( 'application/x-orb-table' ) and data . hasFormat ( 'application/x-orb-query' ) :
tableName = self . tableTypeName ( )
if nativestring ( data . data ( 'application/x-orb-table' ) ) == tableName :
data = nativestrin... |
def start ( widget , processEvents = True , style = None , movie = None ) :
"""Starts a loader widget on the inputed widget .
: param widget | < QWidget >
: return < XLoaderWidget >""" | if style is None :
style = os . environ . get ( 'PROJEXUI_LOADER_STYLE' , 'gray' )
# there is a bug with the way the loader is handled in a splitter ,
# so bypass it
parent = widget . parent ( )
while isinstance ( parent , QSplitter ) :
parent = parent . parent ( )
# retrieve the loader widget
loader = getattr ... |
def assemble_oligos ( dna_list , reference = None ) :
'''Given a list of DNA sequences , assemble into a single construct .
: param dna _ list : List of DNA sequences - they must be single - stranded .
: type dna _ list : coral . DNA list
: param reference : Expected sequence - once assembly completed , this ... | # FIXME : this protocol currently only supports 5 ' ends on the assembly
# Find all matches for every oligo . If more than 2 per side , error .
# Self - oligo is included in case the 3 ' end is self - complementary .
# 1 ) Find all unique 3 ' binders ( and non - binders ) .
match_3 = [ bind_unique ( seq , dna_list , ri... |
def least_common_multiple ( num1 , num2 ) :
"""Calculate the least common multiple ( LCM ) of two positive numbers .
Examples :
least _ common _ multiple ( 4 , 6 ) - > 12
least _ common _ multiple ( 15 , 17 ) - > 255
least _ common _ multiple ( 2 , 6 ) - > 6
: param num1 : An integer
: param num2 : An i... | max_num = max ( num1 , num2 )
while True :
if max_num % num1 == 0 and max_num % num2 == 0 :
lcm = max_num
break
max_num += 1
return lcm |
def write ( self , path ) :
'''Write assembly oligos and ( if applicable ) primers to csv .
: param path : path to csv file , including . csv extension .
: type path : str''' | with open ( path , 'wb' ) as oligo_file :
oligo_writer = csv . writer ( oligo_file , delimiter = ',' , quoting = csv . QUOTE_MINIMAL )
oligo_writer . writerow ( [ 'name' , 'oligo' , 'notes' ] )
for i , oligo in enumerate ( self . oligos ) :
name = 'oligo {}' . format ( i + 1 )
oligo_len = le... |
def session_login ( self , user = None , passwd = None ) :
"""Performs a session login by posting the auth information
to the _ session endpoint .
: param str user : Username used to connect to server .
: param str auth _ token : Authentication token used to connect to server .""" | self . change_credentials ( user = user , auth_token = passwd ) |
def copy ( self , target , timeout = 500 ) :
"""Copy or download this file to a new local file""" | if self . metadata and 'encoding' in self . metadata :
with io . open ( target , 'w' , encoding = self . metadata [ 'encoding' ] ) as f :
for line in self :
f . write ( line )
else :
with io . open ( target , 'wb' ) as f :
for line in self :
if sys . version < '3' and isi... |
def by_type ( self , chamber , type , congress = CURRENT_CONGRESS ) :
"Return votes by type : missed , party , lone no , perfect" | check_chamber ( chamber )
path = "{congress}/{chamber}/votes/{type}.json" . format ( congress = congress , chamber = chamber , type = type )
return self . fetch ( path ) |
def _set_defaults ( self , v , load = False ) :
"""Setter method for defaults , mapped from YANG variable / show / defaults ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ defaults is considered as a private
method . Backends looking to populate this var... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = defaults . defaults , is_container = 'container' , presence = False , yang_name = "defaults" , rest_name = "defaults" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def __undo_filter_sub ( self , scanline ) :
"""Undo sub filter .""" | ai = 0
# Loops starts at index fu .
for i in range ( self . fu , len ( scanline ) ) :
x = scanline [ i ]
a = scanline [ ai ]
# result
scanline [ i ] = ( x + a ) & 0xff
# result
ai += 1 |
def all_logging_disabled ( highest_level = logging . CRITICAL ) :
"""Disable all logging temporarily .
A context manager that will prevent any logging messages triggered during the body from being processed .
Args :
highest _ level : the maximum logging level that is being blocked""" | previous_level = logging . root . manager . disable
logging . disable ( highest_level )
try :
yield
finally :
logging . disable ( previous_level ) |
def importSignedCertificate ( self , alias , certFile ) :
"""This operation imports a certificate authority ( CA ) signed SSL
certificate into the key store .""" | params = { "f" : "json" }
files = { "file" : certFile }
url = self . _url + "/sslCertificates/{cert}/importSignedCertificate" . format ( cert = alias )
return self . _post ( url = url , files = files , param_dict = params , proxy_port = self . _proxy_port , proxy_url = self . _proxy_url ) |
def pause ( self ) :
"""Pause the animation .""" | if not self . _pause_level :
self . _paused_time = self . _clock ( ) + self . _offset
self . _paused_frame = self . current_frame
self . _pause_level += 1 |
def set_project ( self , project ) :
"""Set the project selection to the given project
: param project : the project to select
: type project : : class : ` djadapter . models . Project `
: returns : None
: rtype : None
: raises : ValueError""" | prjroot = self . prjbrws . model . root
prjitems = prjroot . childItems
for row , item in enumerate ( prjitems ) :
prj = item . internal_data ( )
if prj == project :
prjindex = self . prjbrws . model . index ( row , 0 )
break
else :
raise ValueError ( "Could not select the given taskfile. No... |
def _set_exception ( self ) :
"""Called by a Job object to tell that an exception occured
during the processing of the function . The object will become
ready but not successful . The collector ' s notify _ ready ( )
method will be called , but NOT the callback method""" | assert not self . ready ( )
self . _data = sys . exc_info ( )
self . _success = False
self . _event . set ( )
if self . _collector is not None :
self . _collector . notify_ready ( self ) |
def unselect_all ( self ) :
"""Clearing the selected _ item also clears the focused _ item .""" | items = self . _get_selected_items ( )
with self . _suppress_selection_events ( ) :
self . _selection . clear ( )
self . queue_draw_item ( * items )
self . emit ( 'selection-changed' , self . _get_selected_items ( ) ) |
def get_log_entries ( self ) :
"""Gets all log entries .
In plenary mode , the returned list contains all known entries or
an error results . Otherwise , the returned list may contain only
those entries that are accessible through this session .
return : ( osid . logging . LogEntryList ) - a list of log ent... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'logging' , collection = 'LogEntry' , runtime = self . _runtime )
result = collection . find ( self . _view_filter ( ) ) . sort ( '_i... |
def get_topic_for_path ( channel , chan_path_tuple ) :
"""Given channel ( dict ) that contains a hierary of TopicNode dicts , we use the
walk the path given in ` chan _ path _ tuple ` to find the corresponding TopicNode .""" | assert chan_path_tuple [ 0 ] == channel [ 'dirname' ] , 'Wrong channeldir'
chan_path_list = list ( chan_path_tuple )
chan_path_list . pop ( 0 )
# skip the channel name
if len ( chan_path_list ) == 0 :
return channel
current = channel
for subtopic in chan_path_list :
current = list ( filter ( lambda d : 'dirname... |
def _update_atomtypes ( unatomtyped_topology , res_name , prototype ) :
"""Update atomtypes in residues in a topology using a prototype topology .
Atomtypes are updated when residues in each topology have matching names .
Parameters
unatomtyped _ topology : openmm . app . Topology
Topology lacking atomtypes... | for res in unatomtyped_topology . residues ( ) :
if res . name == res_name :
for old_atom , new_atom_id in zip ( [ atom for atom in res . atoms ( ) ] , [ atom . id for atom in prototype . atoms ( ) ] ) :
old_atom . id = new_atom_id |
def crawl_legend ( self , ax , legend ) :
"""Recursively look through objects in legend children""" | legendElements = list ( utils . iter_all_children ( legend . _legend_box , skipContainers = True ) )
legendElements . append ( legend . legendPatch )
for child in legendElements : # force a large zorder so it appears on top
child . set_zorder ( 1E6 + child . get_zorder ( ) )
try : # What kind of object . . .
... |
def delete_entities ( namespace , workspace , json_body ) :
"""Delete entities in a workspace .
Note : This action is not reversible . Be careful !
Args :
namespace ( str ) : project to which workspace belongs
workspace ( str ) : Workspace name
json _ body :
" entityType " : " string " ,
" entityName ... | uri = "workspaces/{0}/{1}/entities/delete" . format ( namespace , workspace )
return __post ( uri , json = json_body ) |
def ungrab_server ( self , onerror = None ) :
"""Release the server if it was previously grabbed by this client .""" | request . UngrabServer ( display = self . display , onerror = onerror ) |
def region ( self , start = 0 , end = None ) :
'''Returns a region of ` ` Sequence . sequence ` ` , in FASTA format .
If called without kwargs , the entire sequence will be returned .
Args :
start ( int ) : Start position of the region to be returned . Default
is 0.
end ( int ) : End position of the regio... | if end is None :
end = len ( self . sequence )
return '>{}\n{}' . format ( self . id , self . sequence [ start : end ] ) |
def close ( self ) :
"""Shut down the socket connection , client and controller""" | self . _sock = None
self . _controller = None
if hasattr ( self , "_port" ) and self . _port :
portpicker . return_port ( self . _port )
self . _port = None |
def passwordLogin ( self , username ) :
"""Generate a new challenge for the given username .""" | self . challenge = secureRandom ( 16 )
self . username = username
return { 'challenge' : self . challenge } |
def display_name ( self ) :
"""Find the most appropriate display name for a user : look for a " display _ name " , then
a " real _ name " , and finally fall back to the always - present " name " .""" | for k in self . _NAME_KEYS :
if self . _raw . get ( k ) :
return self . _raw [ k ]
if "profile" in self . _raw and self . _raw [ "profile" ] . get ( k ) :
return self . _raw [ "profile" ] [ k ]
return self . _raw [ "name" ] |
def build_model_from_txt ( self , fname ) :
"""Construct the model and perform regressions based on data in a txt file .
Parameters
fname : str
The name of the file to load .""" | x_values , y_values = read_column_data_from_txt ( fname )
self . build_model_from_xy ( x_values , y_values ) |
def as_dict ( self ) :
"""Return the dependencies as a dictionary .
Returns :
dict : dictionary of dependencies .""" | return { 'name' : str ( self ) , 'modules' : [ m . as_dict ( ) for m in self . modules ] , 'packages' : [ p . as_dict ( ) for p in self . packages ] } |
def sql ( self ) :
"""If you access this attribute , we will build an SQLite database
out of the FASTA file and you will be able access everything in an
indexed fashion , and use the blaze library via sql . frame""" | from fasta . indexed import DatabaseFASTA , fasta_to_sql
db = DatabaseFASTA ( self . prefix_path + ".db" )
if not db . exists :
fasta_to_sql ( self . path , db . path )
return db |
def update ( self , data , overwrite = None , overwrite_sections = True , overwrite_options = True ) :
"""Updates the currently stored configuration with new * data * , given as a dictionary . When
* overwrite _ sections * is * False * , sections in * data * that are already present in the current
config are sk... | if overwrite is not None :
overwrite_sections = overwrite
overwrite_options = overwrite
for section , _data in six . iteritems ( data ) :
if not self . has_section ( section ) :
self . add_section ( section )
elif not overwrite_sections :
continue
for option , value in six . iteritem... |
def get_field_names ( self ) :
"""Return the field names to get values for""" | col_model = self . request . get ( "colModel" , None )
if not col_model :
return [ "UID" , ]
names = [ ]
col_model = json . loads ( _u ( col_model ) )
if isinstance ( col_model , ( list , tuple ) ) :
names = map ( lambda c : c . get ( "columnName" , "" ) . strip ( ) , col_model )
# UID is used by reference widg... |
def _calculate ( self , field ) :
'''If the offset is unknown , return 0''' | base_offset = 0
if self . base_field is not None :
base_offset = self . base_field . offset
target_offset = self . _field . offset
if ( target_offset is None ) or ( base_offset is None ) :
return 0
return target_offset - base_offset |
def run_operation ( jboss_config , operation , fail_on_error = True , retries = 1 ) :
'''Execute an operation against jboss instance through the CLI interface .
jboss _ config
Configuration dictionary with properties specified above .
operation
An operation to execute against jboss instance
fail _ on _ er... | cli_command_result = __call_cli ( jboss_config , operation , retries )
if cli_command_result [ 'retcode' ] == 0 :
if _is_cli_output ( cli_command_result [ 'stdout' ] ) :
cli_result = _parse ( cli_command_result [ 'stdout' ] )
cli_result [ 'success' ] = cli_result [ 'outcome' ] == 'success'
else ... |
def round_to_specified_time ( self , a_datetime , hour , minute , second , mode = "lower" ) :
"""Round the given datetime to specified hour , minute and second .
: param mode : if ' lower ' , floor to . if ' upper ' , ceiling to .
* * 中文文档 * *
将给定时间对齐到最近的一个指定了小时 , 分钟 , 秒的时间上 。""" | mode = mode . lower ( )
new_datetime = datetime ( a_datetime . year , a_datetime . month , a_datetime . day , hour , minute , second )
if mode == "lower" :
if new_datetime <= a_datetime :
return new_datetime
else :
return timewrapper . add_days ( new_datetime , - 1 )
elif mode == "upper" :
i... |
def _find_feature_type ( self , feature_name , eopatch ) :
"""Iterates over allowed feature types of given EOPatch and tries to find a feature type for which there
exists a feature with given name
: return : A feature type or ` None ` if such feature type does not exist
: rtype : FeatureType or None""" | for feature_type in self . allowed_feature_types :
if feature_type . has_dict ( ) and feature_name in eopatch [ feature_type ] :
return feature_type
return None |
def hugoniot_p ( rho , rho0 , c0 , s ) :
"""calculate pressure along a Hugoniot
: param rho : density in g / cm ^ 3
: param rho0 : density at 1 bar in g / cm ^ 3
: param c0 : velocity at 1 bar in km / s
: param s : slope of the velocity change
: return : pressure in GPa""" | eta = 1. - ( rho0 / rho )
Ph = rho0 * c0 * c0 * eta / np . power ( ( 1. - s * eta ) , 2. )
return Ph |
def handle ( self , * controller_args , ** controller_kwargs ) :
"""handles the request and returns the response
This should set any response information directly onto self . response
this method has the same signature as the request handling methods
( eg , GET , POST ) so subclasses can override this method ... | req = self . request
res = self . response
res . set_header ( 'Content-Type' , "{};charset={}" . format ( self . content_type , self . encoding ) )
encoding = req . accept_encoding
res . encoding = encoding if encoding else self . encoding
res_method_name = ""
controller_methods = self . find_methods ( )
# controller _... |
def filter ( self , u ) :
"""Filter the valid identities for this matcher .
: param u : unique identity which stores the identities to filter
: returns : a list of identities valid to work with this matcher .
: raises ValueError : when the unique identity is not an instance
of UniqueIdentity class""" | if not isinstance ( u , UniqueIdentity ) :
raise ValueError ( "<u> is not an instance of UniqueIdentity" )
filtered = [ ]
for id_ in u . identities :
email = None
name = None
if self . sources and id_ . source . lower ( ) not in self . sources :
continue
if self . _check_blacklist ( id_ ) :
... |
def _dequeue_update ( self , change ) :
"""Only update when all changes are done""" | self . _update_count -= 1
if self . _update_count != 0 :
return
self . update_shape ( change ) |
def ignored_double_corner ( intersection , tangent_s , tangent_t , edge_nodes1 , edge_nodes2 ) :
"""Check if an intersection is an " ignored " double corner .
. . note : :
This is a helper used only by : func : ` ignored _ corner ` , which in turn is
only used by : func : ` classify _ intersection ` .
Helpe... | # Compute the other edge for the ` ` s ` ` surface .
prev_index = ( intersection . index_first - 1 ) % 3
prev_edge = edge_nodes1 [ prev_index ]
alt_tangent_s = _curve_helpers . evaluate_hodograph ( 1.0 , prev_edge )
# First check if ` ` tangent _ t ` ` is interior to the ` ` s ` ` surface .
cross_prod1 = _helpers . cro... |
def humanize_hours ( total_hours , frmt = '{hours:02d}:{minutes:02d}:{seconds:02d}' , negative_frmt = None ) :
"""Given time in hours , return a string representing the time .""" | seconds = int ( float ( total_hours ) * 3600 )
return humanize_seconds ( seconds , frmt , negative_frmt ) |
def path ( self , * paths , ** kwargs ) :
"""Create new Path based on self . root and provided paths .
: param paths : List of sub paths
: param kwargs : required = False
: rtype : Path""" | return self . __class__ ( self . __root__ , * paths , ** kwargs ) |
def nz ( value , none_value , strict = True ) :
'''This function is named after an old VBA function . It returns a default
value if the passed in value is None . If strict is False it will
treat an empty string as None as well .
example :
x = None
nz ( x , " hello " )
- - > " hello "
nz ( x , " " )
... | if not DEBUG :
debug = False
else :
debug = False
if debug :
print ( "START nz frameworkutilities.py ----------------------\n" )
if value is None and strict :
return_val = none_value
elif strict and value is not None :
return_val = value
elif not strict and not is_not_null ( value ) :
return_val... |
def plot_gender ( data , options ) :
"""Plots the gender .
: param data : the data to plot .
: param options : the options .
: type data : numpy . recarray
: type options : argparse . Namespace
Plots the summarized intensities of the markers on the Y chromosomes in
function of the markers on the X chrom... | if data is None : # there is a problem . . .
msg = ( "no data: specify either '--bfile' and '--intensities', or " "'--summarized-intensities'" )
raise ProgramError ( msg )
import matplotlib as mpl
if options . format != "X11" and mpl . get_backend ( ) != "agg" :
mpl . use ( "Agg" )
import matplotlib . pyplo... |
def splay_health ( health_target ) :
"""Set Health Check path , port , and protocol .
Args :
health _ target ( str ) : The health target . ie ` ` HTTP : 80 ` `
Returns :
HealthCheck : A * * collections . namedtuple * * class with * path * , * port * ,
* proto * , and * target * attributes .""" | HealthCheck = collections . namedtuple ( 'HealthCheck' , [ 'path' , 'port' , 'proto' , 'target' ] )
proto , health_port_path = health_target . split ( ':' )
port , * health_path = health_port_path . split ( '/' )
if proto == 'TCP' :
path = ''
elif not health_path :
path = '/healthcheck'
else :
path = '/{0}'... |
def flow_tuple ( data ) :
"""Tuple for flow ( src , dst , sport , dport , proto )""" | src = net_utils . inet_to_str ( data [ 'packet' ] . get ( 'src' ) ) if data [ 'packet' ] . get ( 'src' ) else None
dst = net_utils . inet_to_str ( data [ 'packet' ] . get ( 'dst' ) ) if data [ 'packet' ] . get ( 'dst' ) else None
sport = data [ 'transport' ] . get ( 'sport' ) if data . get ( 'transport' ) else None
dpo... |
def folderitem ( self , obj , item , index ) :
"""Service triggered each time an item is iterated in folderitems .
The use of this service prevents the extra - loops in child objects .
: obj : the instance of the class to be foldered
: item : dict containing the properties of the object to be used by
the te... | DueDate = obj . getDueDate
item [ "getDateReceived" ] = self . ulocalized_time ( obj . getDateReceived )
item [ "getDueDate" ] = self . ulocalized_time ( DueDate )
if DueDate and DueDate < DateTime ( ) :
item [ "after" ] [ "DueDate" ] = get_image ( "late.png" , title = t ( _ ( "Late Analysis" ) ) )
# Add Priority c... |
def _get_authorization_headers ( self ) -> dict :
"""Constructs and returns the Authorization header for the client app .
Args :
None
Returns :
header dict for communicating with the authorization endpoints""" | auth = base64 . encodestring ( ( self . client_id + ':' + self . client_secret ) . encode ( 'latin-1' ) ) . decode ( 'latin-1' )
auth = auth . replace ( '\n' , '' ) . replace ( ' ' , '' )
auth = 'Basic {}' . format ( auth )
headers = { 'Authorization' : auth }
return headers |
def get_json_event_start ( event_buffer ) :
"""get the event start of an event that is different ( in time ) from the
adjoining event , in XML format""" | event_start_pattern = '{"_cd":"'
time_key_pattern = '"_time":"'
time_end_pattern = '"'
event_end_pattern = '"},\n'
event_end_pattern2 = '"}[]'
# old json output format bug
event_start = event_buffer . find ( event_start_pattern )
event_end = event_buffer . find ( event_end_pattern , event_start ) + len ( event_end_patt... |
def subtract_timedelta ( self , delta ) :
"""Remove timedelta duration from the instance .
: param delta : The timedelta instance
: type delta : datetime . timedelta
: rtype : Time""" | if delta . days :
raise TypeError ( "Cannot subtract timedelta with days to Time." )
return self . subtract ( seconds = delta . seconds , microseconds = delta . microseconds ) |
def get_pattern_mat ( oracle , pattern ) :
"""Output a matrix containing patterns in rows from a vmo .
: param oracle : input vmo object
: param pattern : pattern extracted from oracle
: return : a numpy matrix that could be used to visualize the pattern extracted .""" | pattern_mat = np . zeros ( ( len ( pattern ) , oracle . n_states - 1 ) )
for i , p in enumerate ( pattern ) :
length = p [ 1 ]
for s in p [ 0 ] :
pattern_mat [ i ] [ s - length : s - 1 ] = 1
return pattern_mat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.