signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def b_getma ( b ) :
"""Get masked array from input GDAL Band
Parameters
b : gdal . Band
Input GDAL Band
Returns
np . ma . array
Masked array containing raster values""" | b_ndv = get_ndv_b ( b )
# bma = np . ma . masked _ equal ( b . ReadAsArray ( ) , b _ ndv )
# This is more appropriate for float , handles precision issues
bma = np . ma . masked_values ( b . ReadAsArray ( ) , b_ndv )
return bma |
def _sync_to_group ( self , device ) :
'''Sync the device to the cluster group
: param device : bigip object - - device to sync to group''' | config_sync_cmd = 'config-sync to-group %s' % self . name
device . tm . cm . exec_cmd ( 'run' , utilCmdArgs = config_sync_cmd ) |
def _binary_arithemtic ( self , left , binary , right ) :
"""Parameters
operand : Column object , integer or float
Value on which to apply operator to this column
binary : char
binary arithmetic operator ( - , + , * , / , ^ , % )
Returns
self
Notes
Returning self will allow the next object to use th... | if isinstance ( right , ( int , float ) ) :
right = right
elif isinstance ( right , Column ) :
right = right . execution_name
else :
raise AttributeError ( "{} can only be used " . format ( binary ) + "with integer, float or column" )
if isinstance ( left , ( int , float ) ) :
left = left
elif isinstanc... |
def lstm_state_tuples ( num_nodes , name ) :
"""Convenience so that the names of the vars are defined in the same file .""" | if not isinstance ( num_nodes , tf . compat . integral_types ) :
raise ValueError ( 'num_nodes must be an integer: %s' % num_nodes )
return [ ( STATE_NAME % name + '_0' , tf . float32 , num_nodes ) , ( STATE_NAME % name + '_1' , tf . float32 , num_nodes ) ] |
def _copy_context_into_mutable ( context ) :
"""Copy a properly formatted context into a mutable data structure .""" | def make_mutable ( val ) :
if isinstance ( val , Mapping ) :
return dict ( val )
else :
return val
if not isinstance ( context , ( str , Mapping ) ) :
try :
return [ make_mutable ( val ) for val in context ]
except TypeError :
pass
return make_mutable ( context ) |
def execute_runner_async ( runner , workunit_factory = None , workunit_name = None , workunit_labels = None , workunit_log_config = None ) :
"""Executes the given java runner asynchronously .
We can ' t use ' with ' here because the workunit _ generator ' s _ _ exit _ _ function
must be called after the process... | if not isinstance ( runner , Executor . Runner ) :
raise ValueError ( 'The runner argument must be a java Executor.Runner instance, ' 'given {} of type {}' . format ( runner , type ( runner ) ) )
if workunit_factory is None :
return SubprocessProcessHandler ( runner . spawn ( ) )
else :
workunit_labels = [ ... |
def create_user ( name , username , email , password , token_manager = None , app_url = defaults . APP_URL ) :
"""create a new user with the specified name , username email and password""" | headers = token_manager . get_access_token_headers ( )
auth_url = environment . get_auth_url ( app_url = app_url )
url = "%s/api/v1/accounts" % auth_url
payload = { 'name' : name , 'username' : username , 'email' : email , 'password' : password }
response = requests . post ( url , data = json . dumps ( payload ) , head... |
def set_customjs_callback ( self , js_callback , handle ) :
"""Generates a CustomJS callback by generating the required JS
code and gathering all plotting handles and installs it on
the requested callback handle .""" | if self . on_events :
for event in self . on_events :
handle . js_on_event ( event , js_callback )
if self . on_changes :
for change in self . on_changes :
handle . js_on_change ( change , js_callback )
elif hasattr ( handle , 'callback' ) :
handle . callback = js_callback |
def nack ( self , id , transaction = None , receipt = None ) :
"""Let the server know that a message was not consumed .
: param str id : the unique id of the message to nack
: param str transaction : include this nack in a named transaction""" | assert id is not None , "'id' is required"
headers = { HDR_ID : id }
if transaction :
headers [ HDR_TRANSACTION ] = transaction
if receipt :
headers [ HDR_RECEIPT ] = receipt
self . send_frame ( CMD_NACK , headers ) |
def check_float_param ( self , param , low , high , name ) :
"""Check if the value of the given parameter is in the given range
and a float .
Designed for testing parameters like ` mu ` and ` eps ` .
To pass this function the variable ` param ` must be able to be converted
into a float with a value between ... | try :
param = float ( param )
except :
raise ValueError ( 'Parameter {} is not float or similar' . format ( name ) )
if low != None or high != None :
if not low <= param <= high :
raise ValueError ( 'Parameter {} is not in range <{}, {}>' . format ( name , low , high ) )
return param |
def detect_circle ( nodes ) :
"""Wrapper for recursive _ detect _ circle function""" | # Verify nodes and traveled types
if not isinstance ( nodes , dict ) :
raise TypeError ( '"nodes" must be a dictionary' )
dependencies = set ( nodes . keys ( ) )
traveled = [ ]
heads = _detect_circle ( nodes , dependencies , traveled )
return DependencyTree ( heads ) |
def task_detail ( job_id = None , task_name = None ) :
"""Show a detailed description of a specific task .""" | jobs = get_jobs ( )
job = [ job for job in jobs if str ( job [ 'job_id' ] ) == job_id ] [ 0 ]
return render_template ( 'task_detail.html' , job = job , task_name = task_name , task = [ task for task in job [ 'tasks' ] if task [ 'name' ] == task_name ] [ 0 ] ) |
def get_users ( self , condensed = False ) :
'''Grabs all users in the slack team
This should should only be used for getting list of all users . Do not
use it for searching users . Use get _ user _ info instead .
Args :
condensed ( bool ) : if true triggers list condensing functionality
Returns :
dict ... | user_list = self . slack_client . api_call ( 'users.list' )
if not user_list . get ( 'ok' ) :
return None
if condensed :
users = [ { 'id' : item . get ( 'id' ) , 'name' : item . get ( 'name' ) , 'display_name' : item . get ( 'profile' ) . get ( 'display_name' ) } for item in user_list . get ( 'members' ) ]
... |
def set_marktype_cb ( self , w , index ) :
"""Set type of marking .""" | self . marktype = self . _mark_options [ index ]
# Mark size is not used for point
if self . marktype != 'point' :
self . w . mark_size . set_enabled ( True )
else :
self . w . mark_size . set_enabled ( False ) |
def fig_voight_painting ( h , index = None , palette = 'colorblind' , height_factor = 0.01 , fig = None ) :
"""Make a figure of shared haplotype prefixes for both left and right
flanks , centred on some variant of choice .
Parameters
h : array _ like , int , shape ( n _ variants , n _ haplotypes )
Haplotype... | import matplotlib . pyplot as plt
from matplotlib . gridspec import GridSpec
import seaborn as sns
# check inputs
h = asarray_ndim ( h , 2 )
if index is None : # use midpoint
index = h . shape [ 0 ] // 2
# divide data into two flanks
hl = h [ : index + 1 ] [ : : - 1 ]
hr = h [ index : ]
# paint both flanks
pl , il ... |
def hash ( cls , path , digest = None , hasher = sha1 ) :
"""Return the digest of a single file in a memory - efficient manner .""" | if digest is None :
digest = hasher ( )
with open ( path , 'rb' ) as fh :
cls . update_hash ( fh , digest )
return digest . hexdigest ( ) |
def serial_udb_extra_f8_send ( self , sue_HEIGHT_TARGET_MAX , sue_HEIGHT_TARGET_MIN , sue_ALT_HOLD_THROTTLE_MIN , sue_ALT_HOLD_THROTTLE_MAX , sue_ALT_HOLD_PITCH_MIN , sue_ALT_HOLD_PITCH_MAX , sue_ALT_HOLD_PITCH_HIGH , force_mavlink1 = False ) :
'''Backwards compatible version of SERIAL _ UDB _ EXTRA F8 : format
s... | return self . send ( self . serial_udb_extra_f8_encode ( sue_HEIGHT_TARGET_MAX , sue_HEIGHT_TARGET_MIN , sue_ALT_HOLD_THROTTLE_MIN , sue_ALT_HOLD_THROTTLE_MAX , sue_ALT_HOLD_PITCH_MIN , sue_ALT_HOLD_PITCH_MAX , sue_ALT_HOLD_PITCH_HIGH ) , force_mavlink1 = force_mavlink1 ) |
def grep_projects ( tofind_list , user_profile = None , verbose = True , new = False , ** kwargs ) :
r"""Greps the projects defined in the current UserProfile
Args :
tofind _ list ( list ) :
user _ profile ( None ) : ( default = None )
Kwargs :
user _ profile
CommandLine :
python - m utool - - tf grep... | import utool as ut
user_profile = ensure_user_profile ( user_profile )
print ( 'user_profile = {!r}' . format ( user_profile ) )
kwargs = kwargs . copy ( )
colored = kwargs . pop ( 'colored' , True )
grepkw = { }
grepkw [ 'greater_exclude_dirs' ] = user_profile . project_exclude_dirs
grepkw [ 'exclude_dirs' ] = user_pr... |
def RunMetadata ( self , tag ) :
"""Given a tag , return the associated session . run ( ) metadata .
Args :
tag : A string tag associated with the event .
Raises :
ValueError : If the tag is not found .
Returns :
The metadata in form of ` RunMetadata ` proto .""" | if tag not in self . _tagged_metadata :
raise ValueError ( 'There is no run metadata with this tag name' )
run_metadata = config_pb2 . RunMetadata ( )
run_metadata . ParseFromString ( self . _tagged_metadata [ tag ] )
return run_metadata |
def _get_signed_url ( self , params ) :
"""Returns a Premier account signed url . Docs on signature :
https : / / developers . google . com / maps / documentation / business / webservices / auth # digital _ signatures""" | params [ 'client' ] = self . client_id
if self . channel :
params [ 'channel' ] = self . channel
path = "?" . join ( ( self . api_path , urlencode ( params ) ) )
signature = hmac . new ( base64 . urlsafe_b64decode ( self . secret_key ) , path . encode ( 'utf-8' ) , hashlib . sha1 )
signature = base64 . urlsafe_b64e... |
def uppercase_chars ( string : any ) -> str :
"""Return all ( and only ) the uppercase chars in the given string .""" | return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] ) |
def delete ( self , * args , ** kwargs ) :
"""Executes an HTTP DELETE .
: Parameters :
- ` args ` : Non - keyword arguments
- ` kwargs ` : Keyword arguments""" | return self . session . delete ( * args , ** self . get_kwargs ( ** kwargs ) ) |
def diff_mtime_map ( map1 , map2 ) :
'''Is there a change to the mtime map ? return a boolean''' | # check if the mtimes are the same
if sorted ( map1 ) != sorted ( map2 ) :
return True
# map1 and map2 are guaranteed to have same keys ,
# so compare mtimes
for filename , mtime in six . iteritems ( map1 ) :
if map2 [ filename ] != mtime :
return True
# we made it , that means we have no changes
return... |
def success ( self , request , message , extra_tags = '' , fail_silently = False ) :
"""Add a message with the ` ` SUCCESS ` ` level .""" | add ( self . target_name , request , constants . SUCCESS , message , extra_tags = extra_tags , fail_silently = fail_silently ) |
def list ( self , ** params ) :
"""Retrieve all notes
Returns all notes available to the user , according to the parameters provided
: calls : ` ` get / notes ` `
: param dict params : ( optional ) Search options .
: return : List of dictionaries that support attriubte - style access , which represent colle... | _ , _ , notes = self . http_client . get ( "/notes" , params = params )
return notes |
def normalize ( filename ) :
"""Return an absolute path of the given file name .""" | # Default value means we do not resolve a model file .
if filename == "default" :
return filename
filename = expanduser ( filename )
if isabs ( filename ) :
return filename
else :
return join ( os . getcwd ( ) , filename ) |
def contourf_to_geojson ( contourf , geojson_filepath = None , min_angle_deg = None , ndigits = 5 , unit = '' , stroke_width = 1 , fill_opacity = .9 , geojson_properties = None , strdump = False , serialize = True ) :
"""Transform matplotlib . contourf to geojson with MultiPolygons .""" | polygon_features = [ ]
mps = [ ]
contourf_idx = 0
for coll in contourf . collections :
color = coll . get_facecolor ( )
for path in coll . get_paths ( ) :
for coord in path . to_polygons ( ) :
if min_angle_deg :
coord = keep_high_angle ( coord , min_angle_deg )
co... |
def get_matching_blocks ( self ) :
"""Similar to : py : meth : ` get _ opcodes ` , but returns only the opcodes that are
equal and returns them in a somewhat different format
( i . e . ` ` ( i , j , n ) ` ` ) .""" | opcodes = self . get_opcodes ( )
match_opcodes = filter ( lambda x : x [ 0 ] == EQUAL , opcodes )
return map ( lambda opcode : [ opcode [ 1 ] , opcode [ 3 ] , opcode [ 2 ] - opcode [ 1 ] ] , match_opcodes ) |
def get_single_node ( self ) -> yaml . Node :
"""Hook used when loading a single document .
This is the hook we use to hook yatiml into ruamel . yaml . It is called by the yaml libray when the user uses load ( ) to load a YAML document .
Returns :
A processed node representing the document .""" | node = super ( ) . get_single_node ( )
if node is not None :
node = self . __process_node ( node , type ( self ) . document_type )
return node |
def agents_me_update ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / chat / agents # update - requesting - agent" | api_path = "/api/v2/agents/me"
return self . call ( api_path , method = "PUT" , data = data , ** kwargs ) |
def create_topic ( self , topic ) :
"""Create a topic .""" | nsq . assert_valid_topic_name ( topic )
return self . _request ( 'POST' , '/topic/create' , fields = { 'topic' : topic } ) |
def starfit ( folder , multiplicities = [ 'single' ] , models = 'mist' , use_emcee = False , plot_only = False , overwrite = False , verbose = False , logger = None , starmodel_type = None , ini_file = 'star.ini' , no_plots = False , bands = None , ** kwargs ) :
"""Runs starfit routine for a given folder .""" | nstars = { 'single' : 1 , 'binary' : 2 , 'triple' : 3 }
if starmodel_type is None :
Mod = StarModel
else :
Mod = starmodel_type
ichrone = None
print ( 'Fitting {}' . format ( folder ) )
for mult in multiplicities :
print ( '{} starfit...' . format ( mult ) )
model_filename = '{}_starmodel_{}.h5' . forma... |
def _check_acl ( self , acl_no , network , netmask ) :
"""Check a ACL config exists in the running config .
: param acl _ no : access control list ( ACL ) number
: param network : network which this ACL permits
: param netmask : netmask of the network
: return :""" | exp_cfg_lines = [ 'ip access-list standard ' + str ( acl_no ) , ' permit ' + str ( network ) + ' ' + str ( netmask ) ]
ios_cfg = self . _get_running_config ( )
parse = HTParser ( ios_cfg )
acls_raw = parse . find_children ( exp_cfg_lines [ 0 ] )
if acls_raw :
if exp_cfg_lines [ 1 ] in acls_raw :
return True... |
def run_commands ( commands , # type : List [ Union [ str , List [ str ] , Dict [ str , Union [ str , List [ str ] ] ] ] ]
directory , # type : str
env = None # type : Optional [ Dict [ str , Union [ str , int ] ] ]
) : # noqa
# type : ( . . . ) - > None
"""Run list of commands .""" | if env is None :
env = os . environ . copy ( )
for step in commands :
if isinstance ( step , ( list , six . string_types ) ) :
execution_dir = directory
raw_command = step
elif step . get ( 'command' ) : # dictionary
execution_dir = os . path . join ( directory , step . get ( 'cwd' )... |
def from_radians ( cls , lat_radians , long_radians ) :
'''Return a new instance of Point from a pair of coordinates in radians .''' | return cls ( math . degrees ( lat_radians ) , math . degrees ( long_radians ) ) |
def request_minion_cachedir ( minion_id , opts = None , fingerprint = '' , pubkey = None , provider = None , base = None , ) :
'''Creates an entry in the requested / cachedir . This means that Salt Cloud has
made a request to a cloud provider to create an instance , but it has not
yet verified that the instance... | if base is None :
base = __opts__ [ 'cachedir' ]
if not fingerprint and pubkey is not None :
fingerprint = salt . utils . crypt . pem_finger ( key = pubkey , sum_type = ( opts and opts . get ( 'hash_type' ) or 'sha256' ) )
init_cachedir ( base )
data = { 'minion_id' : minion_id , 'fingerprint' : fingerprint , '... |
def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_interface_detail = ET . Element ( "get_interface_detail" )
config = get_interface_detail
input = ET . SubElement ( get_interface_detail , "input" )
request_type = ET . SubElement ( input , "request-type" )
get_next_request = ET . SubElement ( request_type , "get-next-request" )
la... |
def artifact_quality ( self , artifact_quality ) :
"""Sets the artifact _ quality of this ArtifactRest .
: param artifact _ quality : The artifact _ quality of this ArtifactRest .
: type : str""" | allowed_values = [ "NEW" , "VERIFIED" , "TESTED" , "DEPRECATED" , "BLACKLISTED" , "DELETED" , "TEMPORARY" ]
if artifact_quality not in allowed_values :
raise ValueError ( "Invalid value for `artifact_quality` ({0}), must be one of {1}" . format ( artifact_quality , allowed_values ) )
self . _artifact_quality = arti... |
def get ( url , max_backoff = 32 , verbose = False , ** kwargs ) :
"""Adding retries to requests . get with exponential backoff .
Args :
url ( str ) : The URL to fetch
max _ backoff ( int ) : The number of seconds to sleep at maximums
verbose ( bool ) : Whether to print exceptions .
Returns :
Response :... | sleep_seconds = 1
while sleep_seconds <= max_backoff :
try : # you may overwrite ` timeout ` via ` kwargs `
response = requests . get ( url , ** { ** { 'timeout' : 30 } , ** kwargs } )
# for 4xx , return instantly , no hope of success
if 400 <= response . status_code < 500 :
retu... |
def dir_is_glotk ( path ) :
"""check that the current directory is a glotk project folder""" | test_set = set ( [ "gloTK_info" , "gloTK_assemblies" , "gloTK_configs" , "gloTK_reads" , "gloTK_fastqc" , "gloTK_kmer" , "gloTK_reports" ] )
# http : / / stackoverflow . com / questions / 11968976/
files = set ( [ f for f in os . listdir ( '.' ) if os . path . isdir ( f ) ] )
intersection = test_set . intersection ( fi... |
def set_initialize_mode ( complexity = 2 ) :
"""Set initialization mode . Default is slow mode .
* * 中文文档 * *
设置WinFile类的全局变量 , 指定WinFile . initialize方法所绑定的初始化方式 。""" | if complexity == 3 :
WinFile . initialize = WinFile . level3_initialize
WinFile . init_mode = 3
elif complexity == 2 :
WinFile . initialize = WinFile . level2_initialize
WinFile . init_mode = 2
elif complexity == 1 :
WinFile . initialize = WinFile . level1_initialize
WinFile . init_mode = 1
else... |
def find_tor_binary ( globs = ( '/usr/sbin/' , '/usr/bin/' , '/Applications/TorBrowser_*.app/Contents/MacOS/' ) , system_tor = True ) :
"""Tries to find the tor executable using the shell first or in in the
paths whose glob - patterns is in the given ' globs ' - tuple .
: param globs :
A tuple of shell - styl... | # Try to find the tor executable using the shell
if system_tor :
try :
proc = subprocess . Popen ( ( 'which tor' ) , stdout = subprocess . PIPE , stderr = subprocess . PIPE , shell = True )
except OSError :
pass
else :
stdout , _ = proc . communicate ( )
if proc . poll ( ) ==... |
def get_artists ( self , limit = 50 , cacheable = True ) :
"""Returns a sequence of Album objects
if limit = = None it will return all ( may take a while )""" | seq = [ ]
for node in _collect_nodes ( limit , self , self . ws_prefix + ".getArtists" , cacheable ) :
name = _extract ( node , "name" )
playcount = _number ( _extract ( node , "playcount" ) )
tagcount = _number ( _extract ( node , "tagcount" ) )
seq . append ( LibraryItem ( Artist ( name , self . netwo... |
def return_net ( word , word_net , depth = 1 ) :
'''Creates a list of unique words that are at a provided depth from root word .
@ Args :
word : root word from which the linked words should be returned .
word _ net : word network ( dictionary of word instances ) to be refered in this process .
depth : depth... | if depth < 1 :
raise Exception ( TAG + "Degree value error.range(1,~)" )
if depth == 1 :
return list ( word_net [ word ] . frwrd_links )
elif depth > 1 :
words = word_net [ word ] . frwrd_links
res = [ ]
for w in words :
res . extend ( return_net ( w , word_net , depth = depth - 1 ) )
re... |
def disable_inheritance ( path , objectType , copy = True ) :
'''Disable inheritance on an object
Args :
path : The path to the object
objectType : The type of object ( FILE , DIRECTORY , REGISTRY )
copy : True will copy the Inherited ACEs to the DACL before disabling inheritance
Returns ( dict ) : A dict... | dc = daclConstants ( )
objectType = dc . getObjectTypeBit ( objectType )
path = dc . processPath ( path , objectType )
return _set_dacl_inheritance ( path , objectType , False , copy , None ) |
def _loadf16 ( ins ) :
"""Load a 32 bit ( 16.16 ) fixed point value from a memory address
If 2nd arg . start with ' * ' , it is always treated as
an indirect value .""" | output = _f16_oper ( ins . quad [ 2 ] )
output . append ( 'push de' )
output . append ( 'push hl' )
return output |
def check_authentication ( self , load , auth_type , key = None , show_username = False ) :
'''. . versionadded : : 2018.3.0
Go through various checks to see if the token / eauth / user can be authenticated .
Returns a dictionary containing the following keys :
- auth _ list
- username
- error
If an err... | auth_list = [ ]
username = load . get ( 'username' , 'UNKNOWN' )
ret = { 'auth_list' : auth_list , 'username' : username , 'error' : { } }
# Authenticate
if auth_type == 'token' :
token = self . authenticate_token ( load )
if not token :
ret [ 'error' ] = { 'name' : 'TokenAuthenticationError' , 'message... |
def _find_sources_with_paths ( im , target , sources , polarity ) :
"""Get the subset of source nodes with paths to the target .
Given a target , a list of sources , and a path polarity , perform a
breadth - first search upstream from the target to find paths to any of the
upstream sources .
Parameters
im... | # First , create a list of visited nodes
# Adapted from
# http : / / stackoverflow . com / questions / 8922060/
# how - to - trace - the - path - in - a - breadth - first - search
# FIXME : the sign information for the target should be associated with
# the observable itself
queue = deque ( [ [ ( target , 1 ) ] ] )
whi... |
async def enable_analog_reporting ( self , pin ) :
"""Enables analog reporting . By turning reporting on for a single pin ,
: param pin : Analog pin number . For example for A0 , the number is 0.
: returns : No return value""" | command = [ PrivateConstants . REPORT_ANALOG + pin , PrivateConstants . REPORTING_ENABLE ]
await self . _send_command ( command ) |
def get_symmetry_from_database ( hall_number ) :
"""Return symmetry operations corresponding to a Hall symbol .
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
' rotations ' and ' translations ' .
If it fails , None is retu... | _set_no_error ( )
rotations = np . zeros ( ( 192 , 3 , 3 ) , dtype = 'intc' )
translations = np . zeros ( ( 192 , 3 ) , dtype = 'double' )
num_sym = spg . symmetry_from_database ( rotations , translations , hall_number )
_set_error_message ( )
if num_sym is None :
return None
else :
return { 'rotations' : np . ... |
def process_relation ( self , relation , last_relation ) :
"""Process a relation into an INDRA statement .
Parameters
relation : MedscanRelation
The relation to process ( a CONTROL svo with normalized verb )
last _ relation : MedscanRelation
The relation immediately proceding the relation to process withi... | subj_res = self . agent_from_entity ( relation , relation . subj )
obj_res = self . agent_from_entity ( relation , relation . obj )
if subj_res is None or obj_res is None : # Don ' t extract a statement if the subject or object cannot
# be resolved
return
subj , subj_bounds = subj_res
obj , obj_bounds = obj_res
# M... |
def index_data_relations ( self ) :
'''Standard Fedora relations to be included in
: meth : ` index _ data ` output . This implementation includes all
standard relations included in the Fedora relations namespace ,
but should be extended or overridden as appropriate for custom
: class : ` ~ eulfedora . mode... | data = { }
# NOTE : hasModel relation is handled with top - level object properties above
# currently not indexing other model rels ( service bindings )
for rel in fedora_rels :
values = [ ]
for o in self . rels_ext . content . objects ( self . uriref , relsextns [ rel ] ) :
values . append ( force_text... |
def from_cap ( cls , theta , lmax , clat = None , clon = None , nmax = None , theta_degrees = True , coord_degrees = True , dj_matrix = None ) :
"""Construct spherical cap Slepian functions .
Usage
x = Slepian . from _ cap ( theta , lmax , [ clat , clon , nmax , theta _ degrees ,
coord _ degrees , dj _ matrix... | if theta_degrees :
tapers , eigenvalues , taper_order = _shtools . SHReturnTapers ( _np . radians ( theta ) , lmax )
else :
tapers , eigenvalues , taper_order = _shtools . SHReturnTapers ( theta , lmax )
return SlepianCap ( theta , tapers , eigenvalues , taper_order , clat , clon , nmax , theta_degrees , coord_... |
def success ( self ) :
"""Return boolean indicating whether a solution was found""" | self . _check_valid ( )
return self . _problem . _p . get_status ( ) == qsoptex . SolutionStatus . OPTIMAL |
def vcs_upload ( ) :
"""Uploads the project with the selected VCS tool .""" | if env . deploy_tool == "git" :
remote_path = "ssh://%s@%s%s" % ( env . user , env . host_string , env . repo_path )
if not exists ( env . repo_path ) :
run ( "mkdir -p %s" % env . repo_path )
with cd ( env . repo_path ) :
run ( "git init --bare" )
local ( "git push -f %s master"... |
def expect ( self , pattern , timeout = - 1 , searchwindowsize = - 1 , async_ = False , ** kw ) :
'''This seeks through the stream until a pattern is matched . The
pattern is overloaded and may take several types . The pattern can be a
StringType , EOF , a compiled re , or a list of any of those types .
Strin... | if 'async' in kw :
async_ = kw . pop ( 'async' )
if kw :
raise TypeError ( "Unknown keyword arguments: {}" . format ( kw ) )
compiled_pattern_list = self . compile_pattern_list ( pattern )
return self . expect_list ( compiled_pattern_list , timeout , searchwindowsize , async_ ) |
def find_good_temp_dir ( candidate_temp_dirs ) :
"""Given a list of candidate temp directories extracted from ` ` ansible . cfg ` ` ,
combine it with the Python - builtin list of candidate directories used by
: mod : ` tempfile ` , then iteratively try each until one is found that is both
writeable and execut... | paths = [ os . path . expandvars ( os . path . expanduser ( p ) ) for p in candidate_temp_dirs ]
paths . extend ( tempfile . _candidate_tempdir_list ( ) )
for path in paths :
if is_good_temp_dir ( path ) :
LOG . debug ( 'Selected temp directory: %r (from %r)' , path , paths )
return path
raise IOErr... |
def _normalize ( obj ) :
"""Normalize dicts and lists
: param obj :
: return : normalized object""" | if isinstance ( obj , list ) :
return [ _normalize ( item ) for item in obj ]
elif isinstance ( obj , dict ) :
return { k : _normalize ( v ) for k , v in obj . items ( ) if v is not None }
elif hasattr ( obj , 'to_python' ) :
return obj . to_python ( )
return obj |
def config_string_to_dict ( string , result = None ) :
"""Convert a given configuration string : :
key _ 1 = value _ 1 | key _ 2 = value _ 2 | . . . | key _ n = value _ n
into the corresponding dictionary : :
dictionary [ key _ 1 ] = value _ 1
dictionary [ key _ 2 ] = value _ 2
dictionary [ key _ n ] = va... | if string is None :
return { }
pairs = string . split ( gc . CONFIG_STRING_SEPARATOR_SYMBOL )
return pairs_to_dict ( pairs , result ) |
def parse_metric_family ( self , response ) :
"""Parse the MetricFamily from a valid requests . Response object to provide a MetricFamily object ( see [ 0 ] )
The text format uses iter _ lines ( ) generator .
The protobuf format directly parse the response . content property searching for Prometheus messages of... | if 'application/vnd.google.protobuf' in response . headers [ 'Content-Type' ] :
n = 0
buf = response . content
while n < len ( buf ) :
msg_len , new_pos = _DecodeVarint32 ( buf , n )
n = new_pos
msg_buf = buf [ n : n + msg_len ]
n += msg_len
message = metrics_pb2 . Me... |
def _copy_ancestor_docstring ( mro_list , func ) : # pylint : disable = W0613
"""Decorator to set docstring for * func * from * mro *""" | if func . __doc__ is not None :
raise RuntimeError ( 'Function already has docstring' )
# Search for docstring in superclass
for cls in mro_list :
super_fn = getattr ( cls , func . __name__ , None )
if super_fn is None :
continue
func . __doc__ = super_fn . __doc__
break
else :
raise Run... |
def get_class_weights ( y , smooth_factor = 0 ) :
"""Returns the weights for each class based on the frequencies of the samples .
Args :
y : A list of true labels ( the labels must be hashable ) .
smooth _ factor : A factor that smooths extremely uneven weights .
Returns :
A dictionary with the weight for... | from collections import Counter
counter = Counter ( y )
if smooth_factor > 0 :
p = max ( counter . values ( ) ) * smooth_factor
for k in counter . keys ( ) :
counter [ k ] += p
majority = max ( counter . values ( ) )
return { cls : float ( majority / count ) for cls , count in counter . items ( ) } |
def list_event_sources ( self ) :
"""Returns the existing event sources .
: rtype : ~ collections . Iterable [ str ]""" | # Server does not do pagination on listings of this resource .
# Return an iterator anyway for similarity with other API methods
path = '/archive/{}/events/sources' . format ( self . _instance )
response = self . _client . get_proto ( path = path )
message = archive_pb2 . EventSourceInfo ( )
message . ParseFromString (... |
def get_metric_values ( self , group_name ) :
"""Get the faked metric values for a metric group , by its metric group
name .
The result includes all metric object values added earlier for that
metric group name , using
: meth : ` ~ zhmcclient . FakedMetricsContextManager . add _ metric _ object _ values `
... | if group_name not in self . _metric_values :
raise ValueError ( "Metric values for this group name do not " "exist: {}" . format ( group_name ) )
return self . _metric_values [ group_name ] |
def Mandhane_Gregory_Aziz_regime ( m , x , rhol , rhog , mul , mug , sigma , D , full_output = False ) :
r'''Classifies the regime of a two - phase flow according to Mandhane ,
Gregory , and Azis ( 1974 ) flow map .
The flow regimes in this method are ' elongated bubble ' , ' stratified ' ,
' annular mist ' ,... | A = 0.25 * pi * D * D
Vsl = m * ( 1.0 - x ) / ( rhol * A )
Vsg = m * x / ( rhog * A )
# Convert to imperial units
Vsl , Vsg = Vsl / 0.3048 , Vsg / 0.3048
# X1 = ( rhog / 0.0808 ) * * 0.333 * ( rhol * 72.4/62.4 / sigma ) * * 0.25 * ( mug / 0.018 ) * * 0.2
# Y1 = ( rhol * 72.4/62.4 / sigma ) * * 0.25 * ( mul / 1 . ) * * ... |
def get_current_version ( repo_path ) :
"""Given a repo will return the version string , according to semantic
versioning , counting as non - backwards compatible commit any one with a
message header that matches ( case insensitive ) : :
sem - ver : . * break . *
And as features any commit with a header mat... | repo = dulwich . repo . Repo ( repo_path )
tags = get_tags ( repo )
maj_version = 0
feat_version = 0
fix_version = 0
for commit_sha , children in reversed ( get_children_per_first_parent ( repo_path ) . items ( ) ) :
commit = get_repo_object ( repo , commit_sha )
maj_version , feat_version , fix_version = get_v... |
def _update_physics ( self ) :
"""Update physics using the current value of ' quantity '
Notes
The algorithm directly writes the value of ' quantity ' into the phase .
This method was implemented relaxing one of the OpenPNM rules of
algorithms not being able to write into phases .""" | phase = self . project . phases ( ) [ self . settings [ 'phase' ] ]
physics = self . project . find_physics ( phase = phase )
for item in self . settings [ 'sources' ] : # Regenerate models with new guess
quantity = self . settings [ 'quantity' ]
# Put quantity on phase so physics finds it when regenerating
... |
def det ( L ) :
"""Determinant
Compute the determinant given a lower triangular matrix
Inputs :
lower triangular matrix
Outputs :
det _ L :
determinant of L""" | size_L = L . shape
if np . size ( L ) == 1 :
return np . array ( L )
else :
try :
assert np . all ( np . tril ( L ) == L )
except AssertionError :
print 'Error: Input is not a lower triangular matrix.'
return 0
try :
assert size_L [ 0 ] == size_L [ 1 ]
except Assertio... |
def check ( self , dsm , independence_factor = 5 , ** kwargs ) :
"""Check least common mechanism .
Args :
dsm ( : class : ` DesignStructureMatrix ` ) : the DSM to check .
independence _ factor ( int ) : if the maximum dependencies for one
module is inferior or equal to the DSM size divided by the
independ... | # leastCommonMechanismMatrix
least_common_mechanism = False
message = ''
# get the list of dependent modules for each module
data = dsm . data
categories = dsm . categories
dsm_size = dsm . size [ 0 ]
if not categories :
categories = [ 'appmodule' ] * dsm_size
dependent_module_number = [ ]
# evaluate Matrix ( data ... |
def push_pv ( self , tokens ) :
"""Creates and Generator object , populates it with data , finds its Bus
and adds it .""" | logger . debug ( "Pushing PV data: %s" % tokens )
bus = self . case . buses [ tokens [ "bus_no" ] - 1 ]
g = Generator ( bus )
g . p = tokens [ "p" ]
g . q_max = tokens [ "q_max" ]
g . q_min = tokens [ "q_min" ]
# Optional parameter
# if tokens . has _ key ( " status " ) :
# g . online = tokens [ " status " ]
self . cas... |
def check_dissociated ( self , cutoff = 1.2 ) :
"""Check if adsorbate dissociates""" | dissociated = False
if not len ( self . B ) > self . nslab + 1 : # only one adsorbate
return dissociated
adsatoms = [ atom for atom in self . B [ self . nslab : ] ]
ads0 , ads1 = set ( atom . symbol for atom in adsatoms )
bond_dist = get_ads_dist ( self . B , ads0 , ads1 )
Cradii = [ cradii [ atom . number ] for at... |
def load_mo ( self , state , page_idx ) :
"""Loads a memory object from memory .
: param page _ idx : the index into the page
: returns : a tuple of the object""" | mo = self . _storage [ page_idx - self . _page_addr ]
# print filter ( lambda x : x ! = None , self . _ storage )
if mo is None and hasattr ( self , "from_dbg" ) :
byte_val = get_debugger ( ) . get_byte ( page_idx )
mo = SimMemoryObject ( claripy . BVV ( byte_val , 8 ) , page_idx )
self . _storage [ page_id... |
def help_handler ( docpie , flag ) :
"""Default help ( ` - - help ` , ` - h ` ) handler . print help string and exit .
when help = ' short _ brief ' , flag startswith ` - - ` will print
the full ` doc ` , ` - ` for " Usage " section and " Option " section only .
when help = ' short _ brief _ notice ' , flag s... | help_type = docpie . help
helpstyle = docpie . helpstyle
if helpstyle == 'python' :
doc = Docpie . help_style_python ( docpie . doc )
elif helpstyle == 'dedent' :
doc = Docpie . help_style_dedent ( docpie . doc )
# elif help _ style = = ' raw ' :
# doc = Docpie . help _ style _ raw ( docpie . doc )
else :
d... |
def poisson_dist ( p1 , p2 ) :
"""Calculates the Poisson distance between two vectors .
p1 can be a sparse matrix , while p2 has to be a dense matrix .""" | # ugh . . .
p1_ = p1 + eps
p2_ = p2 + eps
return np . dot ( p1_ - p2_ , np . log ( p1_ / p2_ ) ) |
def getQCAnalyses ( self ) :
"""Return the Quality Control analyses .
: returns : a list of QC analyses
: rtype : List of ReferenceAnalysis / DuplicateAnalysis""" | qc_types = [ 'ReferenceAnalysis' , 'DuplicateAnalysis' ]
analyses = self . getAnalyses ( )
return [ a for a in analyses if a . portal_type in qc_types ] |
def Kdiag ( self , X ) :
"""Compute the diagonal of the covariance matrix associated to X .""" | vyt = self . variance_Yt
vyx = self . variance_Yx
lyt = 1. / ( 2 * self . lengthscale_Yt )
lyx = 1. / ( 2 * self . lengthscale_Yx )
a = self . a
b = self . b
c = self . c
# # dk ^ 2 / dtdt '
k1 = ( 2 * lyt ) * vyt * vyx
# # dk ^ 2 / dx ^ 2
k2 = ( - 2 * lyx ) * vyt * vyx
# # dk ^ 4 / dx ^ 2dx ' ^ 2
k3 = ( 4 * 3 * lyx **... |
def _update_cache ( self ) :
"""To avoid build _ schema every time , we cache
some values : they only change when a SearchIndex
changes , which typically restarts the Python .""" | fields = connections [ self . connection_alias ] . get_unified_index ( ) . all_searchfields ( )
if self . _fields != fields :
self . _fields = fields
self . _content_field_name , self . _schema = self . build_schema ( self . _fields ) |
def main ( args_list = None ) :
"""Wrapper for find _ schemes if called from command line""" | args_list = args_list or sys . argv [ 1 : ]
parser = argparse . ArgumentParser ( description = 'Discover schemes of given stanza file' )
parser . add_argument ( 'infile' , type = argparse . FileType ( 'r' ) , )
parser . add_argument ( 'outfile' , help = 'Where the result is written to. Default: stdout' , nargs = '?' , ... |
def skip ( self , count = 1 ) :
'''Skip the first count contiguous elements of the source sequence .
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception .
Note : This method uses deferred execution .
Args :
count : The number of elements to s... | if self . closed ( ) :
raise ValueError ( "Attempt to call skip() on a closed Queryable." )
count = max ( 0 , count )
if count == 0 :
return self
# Try an optimised version
if hasattr ( self . _iterable , "__getitem__" ) :
try :
stop = len ( self . _iterable )
return self . _create ( self . ... |
def get_all_parts ( self , max_parts = None , part_number_marker = None ) :
"""Return the uploaded parts of this MultiPart Upload . This is
a lower - level method that requires you to manually page through
results . To simplify this process , you can just use the
object itself as an iterator and it will autom... | self . _parts = [ ]
query_args = 'uploadId=%s' % self . id
if max_parts :
query_args += '&max-parts=%d' % max_parts
if part_number_marker :
query_args += '&part-number-marker=%s' % part_number_marker
response = self . bucket . connection . make_request ( 'GET' , self . bucket . name , self . key_name , query_ar... |
def hide_bundle_services ( self , bundle ) :
"""Hides the services of the given bundle ( removes them from lists , but
lets them be unregistered )
: param bundle : The bundle providing services
: return : The references of the hidden services""" | with self . __svc_lock :
try :
svc_refs = self . __bundle_svc . pop ( bundle )
except KeyError : # Nothing to do
return set ( )
else : # Clean the registry
specs = set ( )
for svc_ref in svc_refs :
if svc_ref . is_factory ( ) :
continue
... |
def retype ( value , index_column = None ) :
"""if the input is a ` DataFrame ` , convert it to this class .
: param index _ column : the column that will be used as index ,
default to ` date `
: param value : value to convert
: return : this extended class""" | if index_column is None :
index_column = 'date'
if isinstance ( value , pd . DataFrame ) : # use all lower case for column name
value . columns = map ( lambda c : c . lower ( ) , value . columns )
if index_column in value . columns :
value . set_index ( index_column , inplace = True )
value = St... |
def forward_algo ( self , observations ) :
"""Finds the probability of an observation sequence for given model parameters
* * Arguments * * :
: param observations : The observation sequence , where each element belongs to ' observations ' variable declared with _ _ init _ _ object .
: type observations : A li... | # Store total number of observations total _ stages = len ( observations )
total_stages = len ( observations )
# Alpha [ i ] stores the probability of reaching state ' i ' in stage ' j ' where ' j ' is the iteration number
# Inittialize Alpha
ob_ind = self . obs_map [ observations [ 0 ] ]
alpha = np . multiply ( np . t... |
def setHistogramRange ( self , mn , mx , padding = 0.1 ) :
"""Set the Y range on the histogram plot . This disables auto - scaling .""" | self . vb . enableAutoRange ( self . vb . YAxis , False )
self . vb . setYRange ( mn , mx , padding ) |
def apply_change ( self ) :
"""Applies changes to the permissions of the role .
To make a change to the permission of the role , a request
in the following format should be sent :
. . code - block : : python
' change ' :
' id ' : ' workflow2 . lane1 . task1 ' ,
' checked ' : false
The ' id ' field of ... | changes = self . input [ 'change' ]
key = self . current . task_data [ 'role_id' ]
role = RoleModel . objects . get ( key = key )
for change in changes :
permission = PermissionModel . objects . get ( code = change [ 'id' ] )
if change [ 'checked' ] is True :
role . add_permission ( permission )
els... |
def _getRightsAssignments ( user_right ) :
'''helper function to return all the user rights assignments / users''' | sids = [ ]
polHandle = win32security . LsaOpenPolicy ( None , win32security . POLICY_ALL_ACCESS )
sids = win32security . LsaEnumerateAccountsWithUserRight ( polHandle , user_right )
return sids |
def activate_backup_image ( reset = False ) :
'''Activates the firmware backup image .
CLI Example :
Args :
reset ( bool ) : Reset the CIMC device on activate .
. . code - block : : bash
salt ' * ' cimc . activate _ backup _ image
salt ' * ' cimc . activate _ backup _ image reset = True''' | dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True :
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""" . format ( r )
ret = __proxy__ [ 'cimc.set_config_modify' ] ( dn... |
def http_put ( self , path , query_data = { } , post_data = { } , files = None , ** kwargs ) :
"""Make a PUT request to the Gitlab server .
Args :
path ( str ) : Path or full URL to query ( ' / projects ' or
' http : / / whatever / v4 / api / projecs ' )
query _ data ( dict ) : Data to send as query paramet... | result = self . http_request ( 'put' , path , query_data = query_data , post_data = post_data , files = files , ** kwargs )
try :
return result . json ( )
except Exception :
raise GitlabParsingError ( error_message = "Failed to parse the server message" ) |
def list_config_files ( ) -> List [ Text ] :
"""This function returns the list of configuration files to load .
This is a callable so the configuration can be reloaded with files that
changed in between .""" | return [ os . path . join ( os . path . dirname ( __file__ ) , 'default_settings.py' ) , os . getenv ( ENVIRONMENT_VARIABLE , '' ) , ] |
def launch_protect ( job , patient_data , univ_options , tool_options ) :
"""The launchpad for ProTECT . The DAG for ProTECT can be viewed in Flowchart . txt .
: param dict patient _ data : Dict of information regarding the input sequences for the patient
: param dict univ _ options : Dict of universal options ... | # Add Patient id to univ _ options as is is passed to every major node in the DAG and can be used
# as a prefix for the logfile .
univ_options [ 'patient' ] = patient_data [ 'patient_id' ]
univ_options [ 'tumor_type' ] = patient_data [ 'tumor_type' ]
# Ascertain number of cpus to use per job
for tool in tool_options :
... |
def update_from_stats ( self , stats ) :
"""Update columns based on partition statistics""" | sd = dict ( stats )
for c in self . columns :
if c not in sd :
continue
stat = sd [ c ]
if stat . size and stat . size > c . size :
c . size = stat . size
c . lom = stat . lom |
def getParameterByValue ( self , value ) :
"""Searchs a parameter by value and returns it .""" | result = None
for parameter in self . getParameters ( ) :
valueParam = parameter . getValue ( )
if valueParam == value :
result = parameter
break
return result |
def set_provider ( self , provider_id ) :
"""Sets a provider .
arg : provider _ id ( osid . id . Id ) : the new provider
raise : InvalidArgument - ` ` provider _ id ` ` is invalid
raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
raise : NullArgument - ` ` provider _ id ` ` is ` ` null ` ... | if provider_id is None :
raise NullArgument ( 'provider_id cannot be None' )
if self . get_provider_metadata ( ) . is_read_only ( ) :
raise NoAccess ( )
if not self . my_osid_object_form . _is_valid_id ( provider_id ) :
raise InvalidArgument ( 'provider_id must be instance of Id' )
self . my_osid_object_for... |
def batch_for_sv ( samples ) :
"""Prepare a set of samples for parallel structural variant calling .
CWL input target - - groups samples into batches and structural variant
callers for parallel processing .""" | samples = cwlutils . assign_complex_to_samples ( samples )
to_process , extras , background = _batch_split_by_sv ( samples , "standard" )
out = [ cwlutils . samples_to_records ( xs ) for xs in to_process . values ( ) ] + extras
return out |
def get_object_cat1 ( con , token , cat , kwargs ) :
"""Constructs the " GET " URL . The functions is used by the get _ object method
First Category of " GET " URL construction . Again calling it first category because more
complex functions maybe added later .""" | req_str = "/" + kwargs [ 'id' ] + "?"
# / id ?
req_str += "access_token=" + token
# / id ? @ acces _ token = . . . . .
del kwargs [ 'id' ]
key = settings . get_object_cat1_param [ cat ]
# get the param name for the category ( single , multiple )
req_str += "&" + key + "="
# / id ? @ acces _ token = . . . . . key =
if k... |
def make_ultrametric ( self , strategy = 1 ) :
"""Returns a tree with branch lengths transformed so that the tree is
ultrametric . Strategies include ( 1 ) tip - align : extend tips to the length
of the fartest tip from the root ; ( 2 ) non - parametric rate - smoothing :
minimize ancestor - descendant local ... | ctree = self . _ttree . copy ( )
if strategy == 1 :
for node in ctree . treenode . traverse ( ) :
if node . is_leaf ( ) :
node . dist = node . height + 1
else :
raise NotImplementedError ( "Strategy {} not yet implemented. Seeking developers." . format ( strategy ) )
return ctree |
def make_package ( name , path , make_base = None , make_root = None , skip_existing = True , warn_on_skip = True ) :
"""Make and install a package .
Example :
> > > def make _ root ( variant , path ) :
> > > os . symlink ( " / foo _ payload / misc / python27 " , " ext " )
> > > with make _ package ( ' foo ... | maker = PackageMaker ( name )
yield maker
# post - with - block :
package = maker . get_package ( )
cwd = os . getcwd ( )
src_variants = [ ]
# skip those variants that already exist
if skip_existing :
for variant in package . iter_variants ( ) :
variant_ = variant . install ( path , dry_run = True )
... |
def clone ( self ) :
"""Return a new bitfield with the same value .
The returned value is a copy , and so is no longer linked to the
original bitfield . This is important when the original is located
at anything other than normal memory , with accesses to it either
slow or having side effects . Creating a c... | temp = self . __class__ ( )
temp . base = self . base
return temp |
def parse_arguments ( argv ) :
"""Create the argument parser""" | parser = argparse . ArgumentParser ( description = DESCRIPTION )
base_parser = argparse . ArgumentParser ( add_help = False )
parser . add_argument ( '-V' , '--version' , action = 'version' , version = 'taxit v' + version , help = 'Print the version number and exit' )
parser . add_argument ( '-v' , '--verbose' , action... |
def commit ( self , if_match = None , wait = True , timeout = None ) :
"""Apply all the changes on the current model .
: param wait : Whether to wait until the operation is completed
: param timeout : The maximum amount of time required for this
operation to be completed .
If optional : param wait : is True... | if not self . _changes :
LOG . debug ( "No changes available for %s: %s" , self . __class__ . __name__ , self . resource_id )
return
LOG . debug ( "Apply all the changes on the current %s: %s" , self . __class__ . __name__ , self . resource_id )
client = self . _get_client ( )
endpoint = self . _endpoint . form... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.