signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def update_and_get_audited ( self , id , ** kwargs ) :
"""Updates an existing Build Configuration and returns BuildConfigurationAudited entity
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . update_and_get_audited_with_http_info ( id , ** kwargs )
else :
( data ) = self . update_and_get_audited_with_http_info ( id , ** kwargs )
return data |
def additions_mount ( ) :
'''Mount VirtualBox Guest Additions CD to the temp directory .
To connect VirtualBox Guest Additions via VirtualBox graphical interface
press ' Host + D ' ( ' Host ' is usually ' Right Ctrl ' ) .
CLI Example :
. . code - block : : bash
salt ' * ' vbox _ guest . additions _ mount ... | mount_point = tempfile . mkdtemp ( )
ret = __salt__ [ 'mount.mount' ] ( mount_point , '/dev/cdrom' )
if ret is True :
return mount_point
else :
raise OSError ( ret ) |
def parse_mode ( mode , default_bitdepth = None ) :
"""Parse PIL - style mode and return tuple ( grayscale , alpha , bitdeph )""" | # few special cases
if mode == 'P' : # Don ' t know what is pallette
raise Error ( 'Unknown colour mode:' + mode )
elif mode == '1' : # Logical
return ( True , False , 1 )
elif mode == 'I' : # Integer
return ( True , False , 16 )
# here we go
if mode . startswith ( 'L' ) :
grayscale = True
mode = mo... |
def _modeldesc_from_dict ( self , d ) :
"""Return a string representation of a patsy ModelDesc object""" | lhs_termlist = [ Term ( [ LookupFactor ( d [ 'lhs_termlist' ] [ 0 ] ) ] ) ]
rhs_termlist = [ ]
for name in d [ 'rhs_termlist' ] :
if name == '' :
rhs_termlist . append ( Term ( [ ] ) )
else :
rhs_termlist . append ( Term ( [ LookupFactor ( name ) ] ) )
md = ModelDesc ( lhs_termlist , rhs_termlis... |
def trim_docstring ( docstring ) :
"""Taken from http : / / www . python . org / dev / peps / pep - 0257/""" | if not docstring :
return ''
# Convert tabs to spaces ( following the normal Python rules )
# and split into a list of lines :
lines = docstring . expandtabs ( ) . splitlines ( )
# Determine minimum indentation ( first line doesn ' t count ) :
indent = maxsize
for line in lines [ 1 : ] :
stripped = line . lstri... |
def sorted_keywords_by_order ( keywords , order ) :
"""Sort keywords based on defined order .
: param keywords : Keyword to be sorted .
: type keywords : dict
: param order : Ordered list of key .
: type order : list
: return : Ordered dictionary based on order list .
: rtype : OrderedDict""" | # we need to delete item with no value
for key , value in list ( keywords . items ( ) ) :
if value is None :
del keywords [ key ]
ordered_keywords = OrderedDict ( )
for key in order :
if key in list ( keywords . keys ( ) ) :
ordered_keywords [ key ] = keywords . get ( key )
for keyword in keywor... |
def get_ascii ( self , show_internal = True , compact = False , attributes = None ) :
"""Returns a string containing an ascii drawing of the tree .
Parameters :
show _ internal :
include internal edge names .
compact :
use exactly one line per tip .
attributes :
A list of node attributes to shown in t... | ( lines , mid ) = self . _asciiArt ( show_internal = show_internal , compact = compact , attributes = attributes )
return '\n' + '\n' . join ( lines ) |
def generate ( self , rprs = None , mass = None , radius = None , n = 2e4 , fp_specific = 0.01 , u1 = None , u2 = None , starmodel = None , Teff = None , logg = None , rbin_width = 0.3 , MAfn = None , lhoodcachefile = None ) :
"""Generates Population
All arguments defined in ` ` _ _ init _ _ ` ` .""" | n = int ( n )
if starmodel is None :
if type ( mass ) is type ( ( 1 , ) ) :
mass = dists . Gaussian_Distribution ( * mass )
if isinstance ( mass , dists . Distribution ) :
mdist = mass
mass = mdist . rvs ( 1e5 )
if type ( radius ) is type ( ( 1 , ) ) :
radius = dists . Gaussi... |
def one_banner ( slug ) :
"""Служит для отображения одного случайного баннера из указанного баннерного места
Пример использования : :
{ % one _ banner ' place _ slug ' % }
: param slug : символьный код баннерного места
: return :""" | place = BannerPlace . objects . published ( ) . get ( slug = slug )
banner = place . banner_set . published ( ) . order_by ( '?' ) . first ( )
renderer = get_renderer ( banner )
return renderer ( banner ) |
def Contains ( self , value ) :
"""Sets the type of the WHERE clause as " contains " .
Args :
value : The value to be used in the WHERE condition .
Returns :
The query builder that this WHERE builder links to .""" | self . _awql = self . _CreateSingleValueCondition ( value , 'CONTAINS' )
return self . _query_builder |
def integrate_gamma ( v , v0 , gamma0 , q0 , q1 , theta0 ) :
"""internal function to calculate Debye temperature
: param v : unit - cell volume in A ^ 3
: param v0 : unit - cell volume in A ^ 3 at 1 bar
: param gamma0 : Gruneisen parameter at 1 bar
: param q0 : logarithmic derivative of Gruneisen parameter ... | def f_integrand ( v ) :
gamma = gamma0 * np . exp ( q0 / q1 * ( ( v / v0 ) ** q1 - 1. ) )
return gamma / v
theta_term = quad ( f_integrand , v0 , v ) [ 0 ]
return theta_term |
def htmlReadDoc ( cur , URL , encoding , options ) :
"""parse an XML in - memory document and build a tree .""" | ret = libxml2mod . htmlReadDoc ( cur , URL , encoding , options )
if ret is None :
raise treeError ( 'htmlReadDoc() failed' )
return xmlDoc ( _obj = ret ) |
def serialize_to_string ( self , name , datas ) :
"""Serialize given datas to a string .
Simply return the value from required variable ` ` value ` ` .
Arguments :
name ( string ) : Name only used inside possible exception message .
datas ( dict ) : Datas to serialize .
Returns :
string : Value .""" | value = datas . get ( 'value' , None )
if value is None :
msg = ( "String reference '{}' lacks of required 'value' variable " "or is empty" )
raise SerializerError ( msg . format ( name ) )
return value |
def hosts_to_endpoints ( hosts , port = 2181 ) :
"""return a list of ( host , port ) tuples from a given host [ : port ] , . . . str""" | endpoints = [ ]
for host in hosts . split ( "," ) :
endpoints . append ( tuple ( host . rsplit ( ":" , 1 ) ) if ":" in host else ( host , port ) )
return endpoints |
def load ( modname , verbose = False , failfast = False ) :
"""Loads all modules with name ' modname ' from all installed apps .
If verbose is True , debug information will be printed to stdout .
If failfast is True , import errors will not be surpressed .""" | for app in settings . INSTALLED_APPS :
get_module ( app , modname , verbose , failfast ) |
def toList ( self ) :
"""Returns time as signed list .""" | slist = angle . toList ( self . value )
# Keep hours in 0 . . 23
slist [ 1 ] = slist [ 1 ] % 24
return slist |
def set_settings ( self , releases = None , default_release = None ) :
"""set path to storage""" | super ( ReplicaSets , self ) . set_settings ( releases , default_release )
Servers ( ) . set_settings ( releases , default_release ) |
def run_command ( local_root , command , env_var = True , pipeto = None , retry = 0 , environ = None ) :
"""Run a command and return the output .
: raise CalledProcessError : Command exits non - zero .
: param str local _ root : Local path to git root directory .
: param iter command : Command to run .
: pa... | log = logging . getLogger ( __name__ )
# Setup env .
env = os . environ . copy ( )
if environ :
env . update ( environ )
if env_var and not IS_WINDOWS :
env [ 'GIT_DIR' ] = os . path . join ( local_root , '.git' )
else :
env . pop ( 'GIT_DIR' , None )
# Run command .
with open ( os . devnull ) as null :
... |
def __version_capture_slp ( self , pkg_id , version_binary , version_display , display_name ) :
'''This returns the version and where the version string came from , based on instructions
under ` ` version _ capture ` ` , if ` ` version _ capture ` ` is missing , it defaults to
value of display - version .
Arg... | if self . __pkg_obj and hasattr ( self . __pkg_obj , 'version_capture' ) :
version_str , src , version_user_str = self . __pkg_obj . version_capture ( pkg_id , version_binary , version_display , display_name )
if src != 'use-default' and version_str and src :
return version_str , src , version_user_str
... |
def _send_textmetrics ( metrics ) :
'''Format metrics for the carbon plaintext protocol''' | data = [ ' ' . join ( map ( six . text_type , metric ) ) for metric in metrics ] + [ '' ]
return '\n' . join ( data ) |
def _resize_image_if_necessary ( image_fobj , target_pixels = None ) :
"""Resize an image to have ( roughly ) the given number of target pixels .
Args :
image _ fobj : File object containing the original image .
target _ pixels : If given , number of pixels that the image must have .
Returns :
A file obje... | if target_pixels is None :
return image_fobj
cv2 = tfds . core . lazy_imports . cv2
# Decode image using OpenCV2.
image = cv2 . imdecode ( np . fromstring ( image_fobj . read ( ) , dtype = np . uint8 ) , flags = 3 )
# Get image height and width .
height , width , _ = image . shape
actual_pixels = height * width
if ... |
def user_set_avatar ( self , action = None , quick_key = None , url = None ) :
"""user / set _ avatar
http : / / www . mediafire . com / developers / core _ api / 1.3 / user / # set _ avatar""" | return self . request ( "user/set_avatar" , QueryParams ( { "action" : action , "quick_key" : quick_key , "url" : url } ) ) |
def remote_call ( request , cls , method , args , kw ) :
'''Command for executing remote calls on a remote object''' | actor = request . actor
name = 'remote_%s' % cls . __name__
if not hasattr ( actor , name ) :
object = cls ( actor )
setattr ( actor , name , object )
else :
object = getattr ( actor , name )
method_name = '%s%s' % ( PREFIX , method )
return getattr ( object , method_name ) ( request , * args , ** kw ) |
def safe_encode ( s ) :
"""Safely decodes a binary string to unicode""" | if isinstance ( s , unicode ) :
return s . encode ( defenc )
elif isinstance ( s , bytes ) :
return s
elif s is not None :
raise TypeError ( 'Expected bytes or text, but got %r' % ( s , ) ) |
def get_series_episodes ( self , series_id , page = 1 ) :
"""Retrieves all episodes for a particular series given its TheTVDB id . It retrieves a maximum of 100 results per
page .
: param series _ id : The TheTVDB id of the series .
: param page : The page number . If none is provided , 1 is used by default .... | raw_response = requests_util . run_request ( 'get' , self . API_BASE_URL + '/series/%d/episodes?page=%d' % ( series_id , page ) , headers = self . __get_header_with_auth ( ) )
return self . parse_raw_response ( raw_response ) |
def shutdown ( self , ssc = None , grace_secs = 0 , timeout = 259200 ) :
"""Stops the distributed TensorFlow cluster .
For InputMode . SPARK , this will be executed AFTER the ` TFCluster . train ( ) ` or ` TFCluster . inference ( ) ` method completes .
For InputMode . TENSORFLOW , this will be executed IMMEDIAT... | logging . info ( "Stopping TensorFlow nodes" )
# identify ps / workers
ps_list , worker_list , eval_list = [ ] , [ ] , [ ]
for node in self . cluster_info :
( ps_list if node [ 'job_name' ] == 'ps' else eval_list if node [ 'job_name' ] == 'evaluator' else worker_list ) . append ( node )
# setup execution timeout
if... |
def upload_bam_to_s3 ( job , ids , input_args , sample ) :
"""Uploads output BAM from sample to S3
Input1 : Toil Job instance
Input2 : jobstore id dictionary
Input3 : Input arguments dictionary
Input4 : Sample tuple - - contains uuid and urls for the sample""" | uuid , urls = sample
key_path = input_args [ 'ssec' ]
work_dir = job . fileStore . getLocalTempDir ( )
# Parse s3 _ dir to get bucket and s3 path
s3_dir = input_args [ 's3_dir' ]
bucket_name = s3_dir . lstrip ( '/' ) . split ( '/' ) [ 0 ]
bucket_dir = '/' . join ( s3_dir . lstrip ( '/' ) . split ( '/' ) [ 1 : ] )
base_... |
def auth_app_id ( self , app_id , user_id , mount_point = 'app-id' , use_token = True ) :
"""POST / auth / < mount point > / login
: param app _ id :
: type app _ id :
: param user _ id :
: type user _ id :
: param mount _ point :
: type mount _ point :
: param use _ token :
: type use _ token :
:... | params = { 'app_id' : app_id , 'user_id' : user_id , }
return self . login ( '/v1/auth/{0}/login' . format ( mount_point ) , json = params , use_token = use_token ) |
def densities_close ( rho0 : Density , rho1 : Density , tolerance : float = TOLERANCE ) -> bool :
"""Returns True if densities are almost identical .
Closeness is measured with the metric Fubini - Study angle .""" | return vectors_close ( rho0 . vec , rho1 . vec , tolerance ) |
def _set_cfm_detail ( self , v , load = False ) :
"""Setter method for cfm _ detail , mapped from YANG variable / cfm _ state / cfm _ detail ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ cfm _ detail is considered as a private
method . Backends looking... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = cfm_detail . cfm_detail , is_container = 'container' , presence = False , yang_name = "cfm-detail" , rest_name = "cfm-detail" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa... |
def find_op_code_sequence ( pattern : list , instruction_list : list ) -> Generator :
"""Returns all indices in instruction _ list that point to instruction
sequences following a pattern .
: param pattern : The pattern to look for , e . g . [ [ " PUSH1 " , " PUSH2 " ] , [ " EQ " ] ] where [ " PUSH1 " , " EQ " ]... | for i in range ( 0 , len ( instruction_list ) - len ( pattern ) + 1 ) :
if is_sequence_match ( pattern , instruction_list , i ) :
yield i |
def process_settings ( pelicanobj ) :
"""Sets user specified settings ( see README for more details )""" | # Default settings
inline_settings = { }
inline_settings [ 'config' ] = { '[]' : ( '' , 'pelican-inline' ) }
# Get the user specified settings
try :
settings = pelicanobj . settings [ 'MD_INLINE' ]
except :
settings = None
# If settings have been specified , add them to the config
if isinstance ( settings , dic... |
def queryset ( self , request , ** kwargs ) :
"""Returns the queryset ( along with ordering ) to be used when retrieving object ( s ) .""" | qs = self . model . _default_manager . all ( )
if self . ordering :
qs = qs . order_by ( * self . ordering )
return qs |
def add_response_log_fields ( self , log_fields : LogFields , start_time : datetime , err : Exception ) :
"""Add log fields related to a response to the provided log fields
: param log _ fields : log fields instnace to which to add the fields
: param start _ time : start time of the request
: param err : exce... | code = "Unknown" if err is not None else "OK"
duration = ( datetime . utcnow ( ) - start_time ) . total_seconds ( ) * 1000
log_fields . add_fields ( { "grpc.start_time" : start_time . isoformat ( ) + "Z" , "grpc.code" : code , "duration" : "{duration}ms" . format ( duration = duration ) , } ) |
def kernel ( self ) :
"""Returns the current kernel .
: return : the kernel or None if none found
: rtype : Kernel""" | result = javabridge . static_call ( "weka/classifiers/KernelHelper" , "getKernel" , "(Ljava/lang/Object;)Lweka/classifiers/functions/supportVector/Kernel;" , self . jobject )
if result is None :
return None
else :
return Kernel ( jobject = result ) |
def parseJuiceHeaders ( lines ) :
"""Create a JuiceBox from a list of header lines .
@ param lines : a list of lines .""" | b = JuiceBox ( )
bodylen = 0
key = None
for L in lines :
if L [ 0 ] == ' ' : # continuation
assert key is not None
b [ key ] += '\r\n' + L [ 1 : ]
continue
parts = L . split ( ': ' , 1 )
if len ( parts ) != 2 :
raise MalformedJuiceBox ( "Wrong number of parts: %r" % ( L , ) )... |
def fm_discriminator ( Signal ) :
"""Calculates the digital FM discriminator from a real - valued time signal .
Parameters
Signal : array - like
A real - valued time signal
Returns
fmDiscriminator : array - like
The digital FM discriminator of the argument signal""" | S_analytic = _hilbert ( Signal )
S_analytic_star = _GetComplexConjugateArray ( S_analytic )
S_analytic_hat = S_analytic [ 1 : ] * S_analytic_star [ : - 1 ]
R , I = _GetRealImagArray ( S_analytic_hat )
fmDiscriminator = _np . arctan2 ( I , R )
return fmDiscriminator |
def date_range ( data ) :
"""Returns the minimum activity start time and the maximum activity end time
from the active entities response . These dates are modified in the following
way . The hours ( and minutes and so on ) are removed from the start and end
times and a * day * is added to the end time . These... | start = min ( [ parse ( d [ 'activity_start_time' ] ) for d in data ] )
end = max ( [ parse ( d [ 'activity_end_time' ] ) for d in data ] )
start = remove_hours ( start )
end = remove_hours ( end ) + timedelta ( days = 1 )
return start , end |
def unzip_recursive ( zip_file_name ) :
"""Unzip file with all recursive zip files inside and delete zip files after that .
: param zip _ file _ name : file name of zip file
: return : list of archive members by name .""" | logger . debug ( "unzipping " + zip_file_name )
fnlist = unzip_one ( zip_file_name )
for fn in fnlist :
if zipfile . is_zipfile ( fn ) :
local_fnlist = unzip_recursive ( fn )
fnlist . extend ( local_fnlist )
return fnlist |
def _call_pyfftw ( self , x , out , ** kwargs ) :
"""Implement ` ` self ( x [ , out , * * kwargs ] ) ` ` for pyfftw back - end .
Parameters
x : ` numpy . ndarray `
Array representing the function to be transformed
out : ` numpy . ndarray `
Array to which the output is written
planning _ effort : { ' est... | # We pop some kwargs options here so that we always use the ones
# given during init or implicitly assumed .
kwargs . pop ( 'axes' , None )
kwargs . pop ( 'halfcomplex' , None )
kwargs . pop ( 'normalise_idft' , None )
# We use ` False `
# Pre - processing before calculating the sums , in - place for C2C and R2C
if sel... |
def set_limits ( self , min_ = None , max_ = None ) :
"""Sets limits for this config value
If the resulting integer is outside those limits , an exception will be raised
: param min _ : minima
: param max _ : maxima""" | self . _min , self . _max = min_ , max_ |
def expr_labelfunc ( leaf_renderer = str , fallback = str ) :
"""Factory for function ` ` labelfunc ( expr , is _ leaf ) ` `
It has the following behavior :
* If ` ` is _ leaf ` ` is True , return ` ` leaf _ renderer ( expr ) ` ` .
* Otherwise ,
- if ` expr ` is an Expression , return a custom string simila... | def _labelfunc ( expr , is_leaf ) :
if is_leaf :
label = leaf_renderer ( expr )
elif isinstance ( expr , Expression ) :
if len ( expr . kwargs ) == 0 :
label = expr . __class__ . __name__
else :
label = "%s(..., %s)" % ( expr . __class__ . __name__ , ", " . join (... |
def journal_event ( events ) :
"""Group multiple events into a single one .""" | reasons = set ( chain . from_iterable ( e . reasons for e in events ) )
attributes = set ( chain . from_iterable ( e . file_attributes for e in events ) )
return JrnlEvent ( events [ 0 ] . file_reference_number , events [ 0 ] . parent_file_reference_number , events [ 0 ] . file_name , events [ 0 ] . timestamp , list ( ... |
def _parse ( self ) :
"""The function for parsing the JSON response to the vars dictionary .""" | try :
self . vars [ 'status' ] = self . json [ 'status' ]
except ( KeyError , ValueError , TypeError ) :
pass
for v in [ 'remarks' , 'notices' ] :
try :
self . vars [ v ] = self . summarize_notices ( self . json [ v ] )
except ( KeyError , ValueError , TypeError ) :
pass
try :
self .... |
def get ( cls , bucket_id ) :
"""Get a bucket object ( excluding deleted ) .
: param bucket _ id : Bucket identifier .
: returns : Bucket instance .""" | return cls . query . filter_by ( id = bucket_id , deleted = False ) . one_or_none ( ) |
def download_url ( url : str , dest : str , overwrite : bool = False , pbar : ProgressBar = None , show_progress = True , chunk_size = 1024 * 1024 , timeout = 4 , retries = 5 ) -> None :
"Download ` url ` to ` dest ` unless it exists and not ` overwrite ` ." | if os . path . exists ( dest ) and not overwrite :
return
s = requests . Session ( )
s . mount ( 'http://' , requests . adapters . HTTPAdapter ( max_retries = retries ) )
u = s . get ( url , stream = True , timeout = timeout )
try :
file_size = int ( u . headers [ "Content-Length" ] )
except :
show_progress... |
def stop ( self , message : str = None , silent : bool = False ) :
"""Stops the execution of the project at the current step immediately
without raising an error . Use this to abort running the project in
situations where some critical branching action should prevent the
project from continuing to run .
: p... | me = self . get_internal_project ( )
if not me or not me . current_step :
return
if not silent :
render_stop_display ( me . current_step , message )
raise UserAbortError ( halt = True ) |
def _init_kvstore ( self ) :
"""Create kvstore .""" | config = self . _kvstore_params
# configure kvstore , update _ on _ kvstore and self . _ distributed on three cases :
if self . _contains_sparse_weight : # If weight is sparse , kvstore must be present and the weight must be updated on kvstore .
# The training loop is the following :
# - row _ sparse _ pull ( sparse _ ... |
def _get_acronyms ( acronyms ) :
"""Return a formatted list of acronyms .""" | acronyms_str = { }
if acronyms :
for acronym , expansions in iteritems ( acronyms ) :
expansions_str = ", " . join ( [ "%s (%d)" % expansion for expansion in expansions ] )
acronyms_str [ acronym ] = expansions_str
return [ { 'acronym' : str ( key ) , 'expansion' : value . encode ( 'utf8' ) } for ke... |
def _filter_closest ( self , lat , lon , stations ) :
"""Helper to filter the closest station to a given location .""" | current_location = ( lat , lon )
closest = None
closest_distance = None
for station in stations :
station_loc = ( station . latitude , station . longitude )
station_distance = distance . distance ( current_location , station_loc ) . km
if not closest or station_distance < closest_distance :
closest ... |
def append_sources_from ( self , other ) :
"""Merge the source alias lists of two CatDicts .""" | # Get aliases lists from this ` CatDict ` and other
self_aliases = self [ self . _KEYS . SOURCE ] . split ( ',' )
other_aliases = other [ self . _KEYS . SOURCE ] . split ( ',' )
# Store alias to ` self `
self [ self . _KEYS . SOURCE ] = uniq_cdl ( self_aliases + other_aliases )
return |
def _contextkey ( jail = None , chroot = None , root = None , prefix = 'pkg.list_pkgs' ) :
'''As this module is designed to manipulate packages in jails and chroots , use
the passed jail / chroot to ensure that a key in the _ _ context _ _ dict that is
unique to that jail / chroot is used .''' | if jail :
return six . text_type ( prefix ) + '.jail_{0}' . format ( jail )
elif chroot :
return six . text_type ( prefix ) + '.chroot_{0}' . format ( chroot )
elif root :
return six . text_type ( prefix ) + '.root_{0}' . format ( root )
return prefix |
def _find_guids ( guid_string ) :
'''Return the set of GUIDs found in guid _ string
: param str guid _ string :
String containing zero or more GUIDs . Each GUID may or may not be
enclosed in { }
Example data ( this string contains two distinct GUIDs ) :
PARENT _ SNAPSHOT _ ID SNAPSHOT _ ID
{ a5b8999f - ... | guids = [ ]
for found_guid in re . finditer ( GUID_REGEX , guid_string ) :
if found_guid . groups ( ) :
guids . append ( found_guid . group ( 0 ) . strip ( '{}' ) )
return sorted ( list ( set ( guids ) ) ) |
def bootstrap_tree_from_alignment ( aln , seed = None , num_trees = None , params = None ) :
"""Returns a tree from Alignment object aln with bootstrap support values .
aln : an cogent . core . alignment . Alignment object , or data that can be used
to build one .
seed : an interger , seed value to use
num ... | # Create instance of controllor , enable bootstrap , disable alignment , tree
app = Clustalw ( InputHandler = '_input_as_multiline_string' , params = params , WorkingDir = '/tmp' )
app . Parameters [ '-align' ] . off ( )
app . Parameters [ '-tree' ] . off ( )
if app . Parameters [ '-bootstrap' ] . isOff ( ) :
if nu... |
def config ( redirect_url = None , custom_init = '' , custom_options = '' , ** kwargs ) :
"""Initialize dropzone configuration .
. . versionadded : : 1.4.4
: param redirect _ url : The URL to redirect when upload complete .
: param custom _ init : Custom javascript code in ` ` init : function ( ) { } ` ` .
... | if custom_init and not custom_init . strip ( ) . endswith ( ';' ) :
custom_init += ';'
if custom_options and not custom_options . strip ( ) . endswith ( ',' ) :
custom_options += ','
upload_multiple = kwargs . get ( 'upload_multiple' , current_app . config [ 'DROPZONE_UPLOAD_MULTIPLE' ] )
parallel_uploads = kwa... |
def selection_val ( traj_exp , adj_mat ) :
'''Function returns an ndarray of ratios calculated by dividing the summed neighborhood variances by the global variance
: param traj _ exp : ndarray representing gene expression
: param adj _ mat : ndarray representing the calculated adjacency matrix
: return val : ... | r = traj_exp . shape [ 0 ]
# keep track of the rows
c = traj_exp . shape [ 1 ]
# keep track of the columns
k = np . sum ( adj_mat [ 0 ] > 0 , dtype = float )
# k calculation based off of adjacency matrix
dev = np . zeros_like ( traj_exp , dtype = float )
# initialize matrix to store dev _ ij values
val = np . zeros ( t... |
def kitchen_create ( backend , parent , kitchen ) :
"""Create a new kitchen""" | click . secho ( '%s - Creating kitchen %s from parent kitchen %s' % ( get_datetime ( ) , kitchen , parent ) , fg = 'green' )
master = 'master'
if kitchen . lower ( ) != master . lower ( ) :
check_and_print ( DKCloudCommandRunner . create_kitchen ( backend . dki , parent , kitchen ) )
else :
raise click . ClickE... |
def _sprite_map_name ( map ) :
"""Returns the name of a sprite map The name is derived from the folder than
contains the sprites .""" | map = StringValue ( map ) . value
sprite_map = sprite_maps . get ( map )
if not sprite_map :
log . error ( "No sprite map found: %s" , map )
if sprite_map :
return StringValue ( sprite_map [ '*n*' ] )
return StringValue ( None ) |
def setShowAddButton ( self , state ) :
"""Sets whether or not the add button is visible .
: param state | < bool >""" | self . _showAddButton = state
self . _addButton . setVisible ( state ) |
def get_zt ( self , output = 'eigs' , doping_levels = True , relaxation_time = 1e-14 , kl = 1.0 ) :
"""Gives the ZT coefficient ( S ^ 2 * cond * T / thermal cond ) in either a full
3x3 tensor form ,
as 3 eigenvalues , or as the average value ( trace / 3.0 ) If
doping _ levels = True , the results are given at... | result = None
result_doping = None
if doping_levels :
result_doping = { doping : { t : [ ] for t in self . _seebeck_doping [ doping ] } for doping in self . _seebeck_doping }
for doping in result_doping :
for t in result_doping [ doping ] :
for i in range ( len ( self . doping [ doping ] ) )... |
def async_saves ( cls ) :
"""Returns a context manager to allow asynchronously creating subjects .
Using this context manager will create a pool of threads which will
create multiple subjects at once and upload any local files
simultaneously .
The recommended way to use this is with the ` with ` statement :... | cls . _local . save_exec = ThreadPoolExecutor ( max_workers = ASYNC_SAVE_THREADS )
return cls . _local . save_exec |
def check_feature ( self , feature , readwrite ) :
"""Check if the * feature * is supported in the handler and
raise an exception otherwise .
* * Parameters * *
feature : str
Identifier for a certain feature .
readwrite : " read " or " write "
Check if the feature is available for reading or writing .""... | if readwrite == "read" :
features = self . can_read
if readwrite == "write" :
features = self . can_write
if feature not in features :
matches = difflib . get_close_matches ( feature , features )
raise FeatureNotAvailable ( "Feature %s not present in %s. Close matches: %s" % ( feature , str ( type ( sel... |
def register ( self , target ) :
"""Registers url _ rules on the blueprint""" | for rule , options in self . url_rules :
target . add_url_rule ( rule , self . name , self . dispatch_request , ** options ) |
def _prior_headerfooter ( self ) :
"""| _ Footer | proxy on prior sectPr element or None if this is first section .""" | preceding_sectPr = self . _sectPr . preceding_sectPr
return ( None if preceding_sectPr is None else _Footer ( preceding_sectPr , self . _document_part , self . _hdrftr_index ) ) |
def _handle_response ( self , response ) :
"""Logs dropped chunks and updates dynamic settings""" | if isinstance ( response , Exception ) :
logging . error ( "dropped chunk %s" % response )
elif response . json ( ) . get ( "limits" ) :
parsed = response . json ( )
self . _api . dynamic_settings . update ( parsed [ "limits" ] ) |
def breakRankTies ( self , oldsym , newsym ) :
"""break Ties to form a new list with the same integer ordering
from high to low
Example
old = [ 4 , 2 , 4 , 7 , 8 ] ( Two ties , 4 and 4)
new = [ 60 , 2 61,90,99]
res = [ 4 , 0 , 3 , 1 , 2]
* * This tie is broken in this case""" | stableSort = map ( None , oldsym , newsym , range ( len ( oldsym ) ) )
stableSort . sort ( )
lastOld , lastNew = None , None
x = - 1
for old , new , index in stableSort :
if old != lastOld :
x += 1
# the last old value was changed , so update both
lastOld = old
lastNew = new
elif... |
def _set_periodic_transmission_machine_state ( self , v , load = False ) :
"""Setter method for periodic _ transmission _ machine _ state , mapped from YANG variable / brocade _ lag _ rpc / get _ portchannel _ info _ by _ intf / output / lacp / periodic _ transmission _ machine _ state ( enumeration )
If this var... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'fast-periodic' : { 'value' : 4 } , u'unknown' : { 'value' : 1 } , u'no-periodic' : { 'value' : 3 } , u'slow-periodic' : { 'valu... |
def _maybe_warn_for_unseparable_batches ( self , output_key : str ) :
"""This method warns once if a user implements a model which returns a dictionary with
values which we are unable to split back up into elements of the batch . This is controlled
by a class attribute ` ` _ warn _ for _ unseperable _ batches `... | if output_key not in self . _warn_for_unseparable_batches :
logger . warning ( f"Encountered the {output_key} key in the model's return dictionary which " "couldn't be split by the batch size. Key will be ignored." )
# We only want to warn once for this key ,
# so we set this to false so we don ' t warn aga... |
def get_netconf_client_capabilities_output_session_vendor ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_netconf_client_capabilities = ET . Element ( "get_netconf_client_capabilities" )
config = get_netconf_client_capabilities
output = ET . SubElement ( get_netconf_client_capabilities , "output" )
session = ET . SubElement ( output , "session" )
vendor = ET . SubElement ( session , "... |
def trusted_permission ( f ) :
"""Access only by D1 infrastructure .""" | @ functools . wraps ( f )
def wrapper ( request , * args , ** kwargs ) :
trusted ( request )
return f ( request , * args , ** kwargs )
return wrapper |
def loader ( self , file_name , bad_steps = None , ** kwargs ) :
"""Loads data from biologics . mpr files .
Args :
file _ name ( str ) : path to . res file .
bad _ steps ( list of tuples ) : ( c , s ) tuples of steps s
( in cycle c ) to skip loading .
Returns :
new _ tests ( list of data objects )""" | new_tests = [ ]
if not os . path . isfile ( file_name ) :
self . logger . info ( "Missing file_\n %s" % file_name )
return None
filesize = os . path . getsize ( file_name )
hfilesize = humanize_bytes ( filesize )
txt = "Filesize: %i (%s)" % ( filesize , hfilesize )
self . logger . debug ( txt )
# creating tem... |
def digest ( self , elimseq = False , notrunc = False ) :
"""Obtain the fuzzy hash .
This operation does not change the state at all . It reports the hash
for the concatenation of the data previously fed using update ( ) .
: return : The fuzzy hash
: rtype : String
: raises InternalError : If lib returns ... | if self . _state == ffi . NULL :
raise InternalError ( "State object is NULL" )
flags = ( binding . lib . FUZZY_FLAG_ELIMSEQ if elimseq else 0 ) | ( binding . lib . FUZZY_FLAG_NOTRUNC if notrunc else 0 )
result = ffi . new ( "char[]" , binding . lib . FUZZY_MAX_RESULT )
if binding . lib . fuzzy_digest ( self . _sta... |
def parseDiskStatLine ( L ) :
"""Parse a single line from C { / proc / diskstats } into a two - tuple of the name of
the device to which it corresponds ( ie ' hda ' ) and an instance of the
appropriate record type ( either L { partitionstat } or L { diskstat } ) .""" | parts = L . split ( )
device = parts [ 2 ]
if len ( parts ) == 7 :
factory = partitionstat
else :
factory = diskstat
return device , factory ( * map ( int , parts [ 3 : ] ) ) |
def exists ( name , region , user = None , opts = False ) :
'''Ensure the SQS queue exists .
name
Name of the SQS queue .
region
Region to create the queue
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line''' | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
does_exist = __salt__ [ 'aws_sqs.queue_exists' ] ( name , region , opts , user )
if not does_exist :
if __opts__ [ 'test' ] :
ret [ 'result' ] = None
ret [ 'comment' ] = 'AWS SQS queue {0} is set to be created' . format ( n... |
def cached_unless_authenticated ( timeout = 50 , key_prefix = 'default' ) :
"""Cache anonymous traffic .""" | def caching ( f ) :
@ wraps ( f )
def wrapper ( * args , ** kwargs ) :
cache_fun = current_cache . cached ( timeout = timeout , key_prefix = key_prefix , unless = lambda : current_cache_ext . is_authenticated_callback ( ) )
return cache_fun ( f ) ( * args , ** kwargs )
return wrapper
return ... |
def _ppf ( self , q , dist , cache ) :
"""Point percentile function .""" | return - evaluation . evaluate_inverse ( dist , 1 - q , cache = cache ) |
def stream ( self , device = values . unset , sim = values . unset , status = values . unset , direction = values . unset , limit = None , page_size = None ) :
"""Streams CommandInstance records from the API as a generator stream .
This operation lazily loads records as efficiently as possible until the limit
i... | limits = self . _version . read_limits ( limit , page_size )
page = self . page ( device = device , sim = sim , status = status , direction = direction , page_size = limits [ 'page_size' ] , )
return self . _version . stream ( page , limits [ 'limit' ] , limits [ 'page_limit' ] ) |
def search_tree ( self , name ) : # noqa : D302
r"""Search tree for all nodes with a specific name .
: param name : Node name to search for
: type name : : ref : ` NodeName `
: raises : RuntimeError ( Argument \ ` name \ ` is not valid )
For example :
> > > from _ _ future _ _ import print _ function
> ... | if self . _validate_node_name ( name ) :
raise RuntimeError ( "Argument `name` is not valid" )
return self . _search_tree ( name ) |
def make_stack ( env , stage , segment ) :
"""For each transform segment , create the code in the try / except block with the
assignements for pipes in the segment""" | import string
import random
from ambry . valuetype import ValueType
column = segment [ 'column' ]
def make_line ( column , t ) :
preamble = [ ]
line_t = "v = {} # {}"
if isinstance ( t , type ) and issubclass ( t , ValueType ) : # A valuetype class , from the datatype column .
try :
cc ,... |
def create_asset ( self , ** kwargs ) :
"""Creates an instance of the Asset Service .""" | asset = predix . admin . asset . Asset ( ** kwargs )
asset . create ( )
client_id = self . get_client_id ( )
if client_id :
asset . grant_client ( client_id )
asset . add_to_manifest ( self )
return asset |
def setup ( logdir = 'log' ) :
"""Set up dual logging to console and to logfile .
When this function is called , it first creates the given directory . It then
creates a logfile and passes all log messages to come to it . The logfile
name encodes the date and time when it was created , for example
"20181115... | # Create the root logger .
logger = logging . getLogger ( )
logger . setLevel ( logging . DEBUG )
# Validate the given directory .
logdir = os . path . normpath ( logdir )
# Create a folder for the logfiles .
if not os . path . exists ( logdir ) :
os . makedirs ( logdir )
# Construct the logfile name .
t = datetime... |
def _CheckForOutOfOrderStepAndMaybePurge ( self , event ) :
"""Check for out - of - order event . step and discard expired events for tags .
Check if the event is out of order relative to the global most recent step .
If it is , purge outdated summaries for tags that the event contains .
Args :
event : The ... | if event . step < self . most_recent_step and event . HasField ( 'summary' ) :
self . _Purge ( event , by_tags = True ) |
def is_valid ( self ) :
"""Is the current entity valid .
Returns
valid : bool
Is the current entity well formed""" | valid = np . any ( ( self . points - self . points [ 0 ] ) != 0 )
return valid |
def remove ( self , name , strategy = Strategy . promote ) :
"""Remove a node from the graph . Returns the set of nodes that were
removed .
If the node doesn ' t exist , an exception will be raised .
name : The name of the node to remove .
strategy : ( Optional , Strategy . promote ) What to do with childre... | removed = set ( )
stack = [ name ]
while stack :
current = stack . pop ( )
node = self . _nodes . pop ( current )
if strategy == Strategy . remove :
for child_name in node . children :
child_node = self . _nodes [ child_name ]
child_node . parents . remove ( current )
... |
def parse_formula ( model_formula , parent_data , unscramble = False ) :
"""Recursively parse a model formula by breaking it into additive atoms
and tracking grouping symbol depth .
Parameters
model _ formula : str
Expression for the model formula , e . g .
' ( a + b ) ^ ^ 2 + dd1 ( c + ( d + e ) ^ 3 ) + ... | variables = { }
data = { }
expr_delimiter = 0
grouping_depth = 0
model_formula = _expand_shorthand ( model_formula , parent_data . columns )
for i , char in enumerate ( model_formula ) :
if char == '(' :
grouping_depth += 1
elif char == ')' :
grouping_depth -= 1
elif grouping_depth == 0 and ... |
def unify_ips ( ) :
"""Unifies the currently saved IPs .
Unification is based on last IP segment .
So if there are is e . g . 192.168.128.121 and 192.168.128.122 tthey will be merged to 192.168.128.121.
This is a little aggressive but the spammers are aggressive , too .
: return : number of merged ips
: r... | processed_ips = 0
ips = { }
# query for the IPs , also includes the starred IPs
for ip in IP . objects . raw ( 'select distinct a.id, a.seg_0, a.seg_1, a.seg_2 ' 'from ip_assembler_ip a, ip_assembler_ip b ' 'where a.seg_0 = b.seg_0 and a.seg_1 = b.seg_1 and a.seg_2 = b.seg_2 and a.seg_3 != b.seg_3 ' 'order by a.seg_0, ... |
def _get_lottery_detail_by_id ( self , id ) :
"""相应彩种历史信息生成
百度详细信息页有两种结构 , 需要分开处理""" | header = '编号 期号 开奖日期 开奖号码' . split ( )
pt = PrettyTable ( )
pt . _set_field_names ( header )
url = QUERY_DETAIL_URL . format ( id = id )
import requests
content = requests . get ( url ) . text
d = pq ( content )
if d ( 'table.historylist' ) : # 输出彩种
info = d ( 'div.historyHd1 h2' ) . text ( )
print ( info )
... |
def targeted_left_multiply ( left_matrix : np . ndarray , right_target : np . ndarray , target_axes : Sequence [ int ] , out : Optional [ np . ndarray ] = None ) -> np . ndarray :
"""Left - multiplies the given axes of the target tensor by the given matrix .
Note that the matrix must have a compatible tensor stru... | k = len ( target_axes )
d = len ( right_target . shape )
work_indices = tuple ( range ( k ) )
data_indices = tuple ( range ( k , k + d ) )
used_data_indices = tuple ( data_indices [ q ] for q in target_axes )
input_indices = work_indices + used_data_indices
output_indices = list ( data_indices )
for w , t in zip ( work... |
def model_yaml ( self , ** kwargs ) :
"""return the name of a model yaml file""" | kwargs_copy = self . base_dict . copy ( )
kwargs_copy . update ( ** kwargs )
self . _replace_none ( kwargs_copy )
localpath = NameFactory . model_yaml_format . format ( ** kwargs_copy )
if kwargs . get ( 'fullpath' , False ) :
return self . fullpath ( localpath = localpath )
return localpath |
def convert_Text_to_mrf ( text ) :
'''Converts from Text object into pre - syntactic mrf format , given as a list of
lines , as in the output of etmrf .
* ) If the input Text has already been morphologically analysed , uses the existing
analysis ;
* ) If the input has not been analysed , performs the analys... | from estnltk . text import Text
if not isinstance ( text , Text ) :
raise Exception ( ' Expected estnltk\'s Text as an input argument! ' )
if not text . is_tagged ( ANALYSIS ) : # If morphological analysis has not been performed yet , set the right arguments and
# perform the analysis
kwargs = text . get_kwargs... |
def frange ( start , stop , step , digits_to_round = 3 ) :
"""Works like range for doubles
: param start : starting value
: param stop : ending value
: param step : the increment _ value
: param digits _ to _ round : the digits to which to round ( makes floating - point numbers much easier to work with )
... | while start < stop :
yield round ( start , digits_to_round )
start += step |
def create_cookie ( name , value , domain , httponly = None , ** kwargs ) :
"""Creates ` cookielib . Cookie ` instance""" | if domain == 'localhost' :
domain = ''
config = dict ( name = name , value = value , version = 0 , port = None , domain = domain , path = '/' , secure = False , expires = None , discard = True , comment = None , comment_url = None , rfc2109 = False , rest = { 'HttpOnly' : httponly } , )
for key in kwargs :
if k... |
def available_options ( self ) :
"""Return options that can be used given
the current cmd line
rtype : command . Option generator""" | for option in list ( self . cmd . options . values ( ) ) :
if ( option . is_multiple or option not in list ( self . used_options ) ) :
yield option |
def format_style ( number : int ) -> str :
"""Return an escape code for a style , by number .
This handles invalid style numbers .""" | if str ( number ) not in _stylenums :
raise InvalidStyle ( number )
return codeformat ( number ) |
def _copy ( self , other , copy_func ) :
"""Copies the contents of another OctetBitString object to itself
: param object :
Another instance of the same class
: param copy _ func :
An reference of copy . copy ( ) or copy . deepcopy ( ) to use when copying
lists , dicts and objects""" | super ( OctetBitString , self ) . _copy ( other , copy_func )
self . _bytes = other . _bytes |
def get_indexer_nd ( index , labels , method = None , tolerance = None ) :
"""Call pd . Index . get _ indexer ( labels ) .""" | kwargs = _index_method_kwargs ( method , tolerance )
flat_labels = np . ravel ( labels )
flat_indexer = index . get_indexer ( flat_labels , ** kwargs )
indexer = flat_indexer . reshape ( labels . shape )
return indexer |
def icons ( self , left = None ) :
"""Return the ICONS with left variable * left * , or all ICONS .
Args :
left : the left variable of the ICONS to return ; if ` None ` ,
return all ICONS""" | if left is not None :
return self . _icons [ left ]
else :
return list ( chain . from_iterable ( self . _icons . values ( ) ) ) |
def _maybe_append_formatted_extension ( numobj , metadata , num_format , number ) :
"""Appends the formatted extension of a phone number to formatted number ,
if the phone number had an extension specified .""" | if numobj . extension :
if num_format == PhoneNumberFormat . RFC3966 :
return number + _RFC3966_EXTN_PREFIX + numobj . extension
else :
if metadata . preferred_extn_prefix is not None :
return number + metadata . preferred_extn_prefix + numobj . extension
else :
r... |
def disasters_sim ( early_mean = early_mean , late_mean = late_mean , switchpoint = switchpoint ) :
"""Coal mining disasters sampled from the posterior predictive distribution""" | return concatenate ( ( pm . rpoisson ( early_mean , size = switchpoint ) , pm . rpoisson ( late_mean , size = n - switchpoint ) ) ) |
def pytwis_clt ( ) :
"""The main routine of this command - line tool .""" | epilog = '''After launching `pytwis_clt.py`, you will be able to use the following commands:
* Register a new user:
127.0.0.1:6379> register {username} {password}
* Log into a user:
127.0.0.1:6379> login {username} {password}
* Log out of a user:
127.0.0.1:6379> logout
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.