signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_settings ( config_file ) :
"""Search and load a configuration file .""" | default_settings = { 'general' : { 'endpoint' : 'http://guacamole.antojitos.io/files/' , 'shortener' : 'http://t.antojitos.io/api/v1/urls' , } }
settings = configparser . ConfigParser ( )
try :
settings . read_dict ( default_settings )
except AttributeError : # using python 2.7
for section , options in default_... |
def release ( self ) :
"""Release the lock .
: returns : Returns ` ` True ` ` if the lock was released .""" | unlocked = self . database . run_script ( 'lock_release' , keys = [ self . key , self . event ] , args = [ self . _lock_id ] )
return unlocked != 0 |
def infer ( self , expl_dims , inf_dims , x ) :
"""Use the sensorimotor model to compute the expected value on inf _ dims given that the value on expl _ dims is x .
. . note : : This corresponds to a prediction if expl _ dims = self . conf . m _ dims and inf _ dims = self . conf . s _ dims and to inverse predicti... | try :
if self . n_bootstrap > 0 :
self . n_bootstrap -= 1
raise ExplautoBootstrapError
y = self . sensorimotor_model . infer ( expl_dims , inf_dims , x . flatten ( ) )
except ExplautoBootstrapError :
logger . warning ( 'Sensorimotor model not bootstrapped yet' )
y = rand_bounds ( self . ... |
def is_path_hidden ( filepath ) :
"""Determines if a given file or directory is hidden .
Parameters
filepath : str
The path to a file or directory
Returns
hidden : bool
Returns ` True ` if the file is hidden""" | name = os . path . basename ( os . path . abspath ( filepath ) )
if isinstance ( name , bytes ) :
is_dotted = name . startswith ( b'.' )
else :
is_dotted = name . startswith ( '.' )
return is_dotted or _has_hidden_attribute ( filepath ) |
def is_topology ( self , layers = None ) :
'''valid the topology''' | if layers is None :
layers = self . layers
layers_nodle = [ ]
result = [ ]
for i , layer in enumerate ( layers ) :
if layer . is_delete is False :
layers_nodle . append ( i )
while True :
flag_break = True
layers_toremove = [ ]
for layer1 in layers_nodle :
flag_arrive = True
... |
def normalize ( score , alpha = 15 ) :
"""Normalize the score to be between - 1 and 1 using an alpha that
approximates the max expected value""" | norm_score = score / math . sqrt ( ( score * score ) + alpha )
if norm_score < - 1.0 :
return - 1.0
elif norm_score > 1.0 :
return 1.0
else :
return norm_score |
def update ( cls , draft_share_invite_api_key_id , status = None , sub_status = None , expiration = None , custom_headers = None ) :
"""Update a draft share invite . When sending status CANCELLED it is
possible to cancel the draft share invite .
: type user _ id : int
: type draft _ share _ invite _ api _ key... | if custom_headers is None :
custom_headers = { }
api_client = client . ApiClient ( cls . _get_api_context ( ) )
request_map = { cls . FIELD_STATUS : status , cls . FIELD_SUB_STATUS : sub_status , cls . FIELD_EXPIRATION : expiration }
request_map_string = converter . class_to_json ( request_map )
request_map_string ... |
def _get_file_alignment_for_new_binary_file ( self , file : File ) -> int :
"""Detects alignment requirements for binary files with new nn : : util : : BinaryFileHeader .""" | if len ( file . data ) <= 0x20 :
return 0
bom = file . data [ 0xc : 0xc + 2 ]
if bom != b'\xff\xfe' and bom != b'\xfe\xff' :
return 0
be = bom == b'\xfe\xff'
file_size : int = struct . unpack_from ( _get_unpack_endian_character ( be ) + 'I' , file . data , 0x1c ) [ 0 ]
if len ( file . data ) != file_size :
... |
def ekcii ( table , cindex , lenout = _default_len_out ) :
"""Return attribute information about a column belonging to a loaded
EK table , specifying the column by table and index .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ekcii _ c . html
: param table : Name of table c... | table = stypes . stringToCharP ( table )
cindex = ctypes . c_int ( cindex )
lenout = ctypes . c_int ( lenout )
column = stypes . stringToCharP ( lenout )
attdsc = stypes . SpiceEKAttDsc ( )
libspice . ekcii_c ( table , cindex , lenout , column , ctypes . byref ( attdsc ) )
return stypes . toPythonString ( column ) , at... |
def create_with ( cls , event : str = None , observable : T . Union [ str , Observable ] = None ) -> T . Callable [ ... , "ObservableProperty" ] :
"""Creates a partial application of ObservableProperty with
event and observable preset .""" | return functools . partial ( cls , event = event , observable = observable ) |
def revise_buffer_size ( info , settings ) :
'''This function is used to revise buffer size , use byte
as its unit , instead of data item .
This is only used for nnb , not for csrc .
When settings contains user customized data type , not pure
FLOAT32 , it affects the memory consumption .''' | size_mapping = { 'FLOAT32' : 4 , 'FIXED16' : 2 , 'FIXED8' : 1 }
var_dict = settings [ 'variables' ]
buffer_index = 0
info . _variable_sizes = [ ]
info . _variable_buffer_index = collections . OrderedDict ( )
info . _variable_buffer_size = collections . OrderedDict ( )
info . _buffer_ids = { }
for n , v in enumerate ( i... |
def run ( self ) :
'''Run until there are no events to be processed .''' | # We left - append rather than emit ( right - append ) because some message
# may have been already queued for execution before the director runs .
global_event_queue . appendleft ( ( INITIATE , self , ( ) , { } ) )
while global_event_queue :
self . process_event ( global_event_queue . popleft ( ) ) |
def _create_more_application ( ) :
"""Create an ` Application ` instance that displays the " - - MORE - - " .""" | from prompt_toolkit . shortcuts import create_prompt_application
registry = Registry ( )
@ registry . add_binding ( ' ' )
@ registry . add_binding ( 'y' )
@ registry . add_binding ( 'Y' )
@ registry . add_binding ( Keys . ControlJ )
@ registry . add_binding ( Keys . ControlI ) # Tab .
def _ ( event ) :
event . cli ... |
def add_settings_parser ( subparsers , parent_parser ) :
"""Creates the args parser needed for the settings command and its
subcommands .""" | # The following parser is for the settings subsection of commands . These
# commands display information about the currently applied on - chain
# settings .
settings_parser = subparsers . add_parser ( 'settings' , help = 'Displays on-chain settings' , description = 'Displays the values of currently active on-chain ' 's... |
def _make_interpolation ( self ) :
"""creates an interpolation grid in H _ 0 , omega _ m and computes quantities in Dd and Ds _ Dds
: return :""" | H0_range = np . linspace ( 10 , 100 , 90 )
omega_m_range = np . linspace ( 0.05 , 1 , 95 )
grid2d = np . dstack ( np . meshgrid ( H0_range , omega_m_range ) ) . reshape ( - 1 , 2 )
H0_grid = grid2d [ : , 0 ]
omega_m_grid = grid2d [ : , 1 ]
Dd_grid = np . zeros_like ( H0_grid )
Ds_Dds_grid = np . zeros_like ( H0_grid )
... |
def moveToPoint ( self , xxx_todo_changeme1 ) :
"""Moves the circle to the point x , y""" | ( x , y ) = xxx_todo_changeme1
self . set_cx ( float ( self . get_cx ( ) ) + float ( x ) )
self . set_cy ( float ( self . get_cy ( ) ) + float ( y ) ) |
def make_driver ( self , driver_name = 'generic' ) :
"""Make driver factory function .""" | module_str = 'condoor.drivers.%s' % driver_name
try :
__import__ ( module_str )
module = sys . modules [ module_str ]
driver_class = getattr ( module , 'Driver' )
except ImportError as e : # pylint : disable = invalid - name
print ( "driver name: {}" . format ( driver_name ) )
self . chain . connect... |
def retino_colors ( vcolorfn , * args , ** kwargs ) :
'See eccen _ colors , angle _ colors , sigma _ colors , and varea _ colors .' | if len ( args ) == 0 :
def _retino_color_pass ( * args , ** new_kwargs ) :
return retino_colors ( vcolorfn , * args , ** { k : ( new_kwargs [ k ] if k in new_kwargs else kwargs [ k ] ) for k in set ( kwargs . keys ( ) + new_kwargs . keys ( ) ) } )
return _retino_color_pass
elif len ( args ) > 1 :
ra... |
def workspace_clone ( ctx , clobber_mets , download , mets_url , workspace_dir ) :
"""Create a workspace from a METS _ URL and return the directory
METS _ URL can be a URL , an absolute path or a path relative to $ PWD .
If WORKSPACE _ DIR is not provided , creates a temporary directory .""" | workspace = ctx . resolver . workspace_from_url ( mets_url , dst_dir = os . path . abspath ( workspace_dir if workspace_dir else mkdtemp ( prefix = TMP_PREFIX ) ) , mets_basename = ctx . mets_basename , clobber_mets = clobber_mets , download = download , )
workspace . save_mets ( )
print ( workspace . directory ) |
async def Offer ( self , offers ) :
'''offers : typing . Sequence [ ~ AddApplicationOffer ]
Returns - > typing . Sequence [ ~ ErrorResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'ApplicationOffers' , request = 'Offer' , version = 2 , params = _params )
_params [ 'Offers' ] = offers
reply = await self . rpc ( msg )
return reply |
def load_from_dict ( self , data : dict , overwrite : bool = True ) :
"""Loads key / values from dicts or list into the ConfigKey .
: param data : The data object to load .
This can be a dict , or a list of key / value tuples .
: param overwrite : Should the ConfigKey overwrite data already in it ?""" | if data is None or data == { } :
return False
# Loop over items
if isinstance ( data , list ) or isinstance ( data , tuple ) : # Pick a random item from the tuple .
if len ( data [ 0 ] ) != 2 :
raise exc . LoaderException ( "Cannot load data with length {}" . format ( len ( data [ 0 ] ) ) )
items = ... |
def qsub ( command , queue = None , cwd = True , name = None , deps = [ ] , stdout = '' , stderr = '' , env = [ ] , array = None , context = 'grid' , hostname = None , memfree = None , hvmem = None , gpumem = None , pe_opt = None , io_big = False ) :
"""Submits a shell job to a given grid queue
Keyword parameters... | scmd = [ 'qsub' ]
import six
if isinstance ( queue , six . string_types ) and queue not in ( 'all.q' , 'default' ) :
scmd += [ '-l' , queue ]
if memfree :
scmd += [ '-l' , 'mem_free=%s' % memfree ]
if hvmem :
scmd += [ '-l' , 'h_vmem=%s' % hvmem ]
if gpumem :
scmd += [ '-l' , 'gpumem=%s' % gpumem ]
if i... |
def object_exists_in_project ( obj_id , proj_id ) :
''': param obj _ id : object ID
: type obj _ id : str
: param proj _ id : project ID
: type proj _ id : str
Returns True if the specified data object can be found in the specified
project .''' | if obj_id is None :
raise ValueError ( "Expected obj_id to be a string" )
if proj_id is None :
raise ValueError ( "Expected proj_id to be a string" )
if not is_container_id ( proj_id ) :
raise ValueError ( 'Expected %r to be a container ID' % ( proj_id , ) )
return try_call ( dxpy . DXHTTPRequest , '/' + ob... |
def get_voms_proxy_user ( ) :
"""Returns the owner of the voms proxy .""" | out = _voms_proxy_info ( [ "--identity" ] ) [ 1 ] . strip ( )
try :
return re . match ( r".*\/CN\=([^\/]+).*" , out . strip ( ) ) . group ( 1 )
except :
raise Exception ( "no valid identity found in voms proxy: {}" . format ( out ) ) |
def fix_config ( self , options ) :
"""Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary .
: param options : the options to fix
: type options : dict
: return : the ( potentially ) fixed options
: rtype : dict""" | options = super ( PRC , self ) . fix_config ( options )
opt = "class_index"
if opt not in options :
options [ opt ] = [ 0 ]
if opt not in self . help :
self . help [ opt ] = "The list of 0-based class-label indices to display (list)."
opt = "key_loc"
if opt not in options :
options [ opt ] = "lower center"
... |
def spline_matrix2d ( x , y , px , py , mask = None ) :
'''For boundary constraints , the first two and last two spline pieces are constrained
to be part of the same cubic curve .''' | V = np . kron ( spline_matrix ( x , px ) , spline_matrix ( y , py ) )
lenV = len ( V )
if mask is not None :
indices = np . nonzero ( mask . T . flatten ( ) )
if len ( indices ) > 1 :
indices = np . nonzero ( mask . T . flatten ( ) ) [ 1 ] [ 0 ]
newV = V . T [ indices ]
V = newV . T
V = V . ... |
def flatten_dict ( root , parents = None , sep = '.' ) :
'''Args :
root ( dict ) : Nested dictionary ( e . g . , JSON object ) .
parents ( list ) : List of ancestor keys .
Returns
list
List of ` ` ( key , value ) ` ` tuples , where ` ` key ` ` corresponds to the
ancestor keys of the respective value joi... | if parents is None :
parents = [ ]
result = [ ]
for i , ( k , v ) in enumerate ( root . iteritems ( ) ) :
parents_i = parents + [ k ]
key_i = sep . join ( parents_i )
if isinstance ( v , dict ) :
value_i = flatten_dict ( v , parents = parents_i , sep = sep )
result . extend ( value_i )
... |
def broadcastPush ( self , pushMessage ) :
"""广播消息方法 ( fromuserid 和 message为null即为不落地的push ) 方法
@ param pushMessage : json数据
@ return code : 返回码 , 200 为正常 。
@ return errorMessage : 错误信息 。""" | desc = { "name" : "CodeSuccessReslut" , "desc" : " http 成功返回结果" , "fields" : [ { "name" : "code" , "type" : "Integer" , "desc" : "返回码,200 为正常。" } , { "name" : "errorMessage" , "type" : "String" , "desc" : "错误信息。" } ] }
r = self . call_api ( method = ( 'API' , 'POST' , 'application/json' ) , action = '/push.json' , para... |
def aot_blpop ( self ) : # pylint : disable = R1710
"""Subscribe to AOT action channel .""" | if self . tcex . default_args . tc_playbook_db_type == 'Redis' :
res = None
try :
self . tcex . log . info ( 'Blocking for AOT message.' )
msg_data = self . db . blpop ( self . tcex . default_args . tc_action_channel , timeout = self . tcex . default_args . tc_terminate_seconds , )
if ms... |
def return_data ( self , data , format = None ) :
"""Format and return data appropriate to the requested API format .
data : The data retured by the api request""" | if format is None :
format = self . format
if format == "json" :
formatted_data = json . loads ( data )
else :
formatted_data = data
return formatted_data |
def extract_datetime ( cls , datetime_str ) :
"""Tries to extract a ` datetime ` object from the given string , including
time information .
Raises ` DateTimeFormatterException ` if the extraction fails .""" | if not datetime_str :
raise DateTimeFormatterException ( 'datetime_str must a valid string' )
try :
return cls . _extract_timestamp ( datetime_str , cls . DATETIME_FORMAT )
except ( TypeError , ValueError ) :
raise DateTimeFormatterException ( 'Invalid datetime string {}.' . format ( datetime_str ) ) |
def send_group_text ( self , sender , receiver , content ) :
"""发送群聊文本消息
: param sender : 发送人
: param receiver : 会话 ID
: param content : 消息内容
: return : 返回的 JSON 数据包""" | return self . send_text ( sender , 'group' , receiver , content ) |
def _process_intersects_filter_directive ( filter_operation_info , location , context , parameters ) :
"""Return a Filter basic block that checks if the directive arg and the field intersect .
Args :
filter _ operation _ info : FilterOperationInfo object , containing the directive and field info
of the field ... | filtered_field_type = filter_operation_info . field_type
filtered_field_name = filter_operation_info . field_name
argument_inferred_type = strip_non_null_from_type ( filtered_field_type )
if not isinstance ( argument_inferred_type , GraphQLList ) :
raise GraphQLCompilationError ( u'Cannot apply "intersects" to non-... |
def _set_description ( self , v , load = False ) :
"""Setter method for description , mapped from YANG variable / interface / ethernet / description ( string )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ description is considered as a private
method . Backends loo... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'1 .. 63' ] } ) , is_leaf = True , yang_name = "description" , rest_name = "description" , parent = self , path_helper = self . _path_helper , ext... |
def verifyExpanded ( self , samplerate ) :
"""Checks the expanded parameters for invalidating conditions
: param samplerate : generation samplerate ( Hz ) , passed on to component verification
: type samplerate : int
: returns : str - - error message , if any , 0 otherwise""" | results = self . expandFunction ( self . verifyComponents , args = ( samplerate , ) )
msg = [ x for x in results if x ]
if len ( msg ) > 0 :
return msg [ 0 ]
else :
return 0 |
def validate_type_registry ( option , value ) :
"""Validate the type _ registry option .""" | if value is not None and not isinstance ( value , TypeRegistry ) :
raise TypeError ( "%s must be an instance of %s" % ( option , TypeRegistry ) )
return value |
def get_netconf_client_capabilities_output_session_host_ip ( 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" )
host_ip = ET . SubElement ( session , ... |
def _init_minimizer ( self , minimizer , ** minimizer_options ) :
"""Takes a : class : ` ~ symfit . core . minimizers . BaseMinimizer ` and instantiates
it , passing the jacobian and constraints as appropriate for the
minimizer .
: param minimizer : : class : ` ~ symfit . core . minimizers . BaseMinimizer ` t... | if isinstance ( minimizer , BaseMinimizer ) :
return minimizer
if issubclass ( minimizer , BasinHopping ) :
minimizer_options [ 'local_minimizer' ] = self . _init_minimizer ( self . _determine_minimizer ( ) )
if issubclass ( minimizer , GradientMinimizer ) : # If an analytical version of the Jacobian exists we ... |
def execute ( self ) :
"""migrate storage""" | repo = repository . PickleRepository ( self . params . storage_path )
clusters = [ i [ : - 7 ] for i in os . listdir ( self . params . storage_path ) if i . endswith ( '.pickle' ) ]
if self . params . cluster :
clusters = [ x for x in clusters if x in self . params . cluster ]
if not clusters :
print ( "No clus... |
def download ( self , output = "" , outputFile = "" , silent = True ) :
"""Downloads the image of the comic onto your computer .
Arguments :
output : the output directory where comics will be downloaded to . The
default argument for ' output is the empty string ; if the empty
string is passed , it defaults ... | image = urllib . urlopen ( self . imageLink ) . read ( )
# Process optional input to work out where the dowload will go and what it ' ll be called
if output != "" :
output = os . path . abspath ( os . path . expanduser ( output ) )
if output == "" or not os . path . exists ( output ) :
output = os . path . expa... |
def init_app ( self , app ) :
"""Configures the specified Flask app to enforce SSL .""" | app . config . setdefault ( 'SSLIFY_AGE' , self . defaults [ 'age' ] )
app . config . setdefault ( 'SSLIFY_SUBDOMAINS' , self . defaults [ 'subdomains' ] )
app . config . setdefault ( 'SSLIFY_PERMANENT' , self . defaults [ 'permanent' ] )
app . config . setdefault ( 'SSLIFY_SKIPS' , self . defaults [ 'skips' ] )
app . ... |
def complex_data ( data , edata = None , draw = True , ** kwargs ) :
"""Plots the imaginary vs real for complex data .
Parameters
data
Array of complex data
edata = None
Array of complex error bars
draw = True
Draw the plot after it ' s assembled ?
See spinmob . plot . xy . data ( ) for additional o... | _pylab . ioff ( )
# generate the data the easy way
try :
rdata = _n . real ( data )
idata = _n . imag ( data )
if edata is None :
erdata = None
eidata = None
else :
erdata = _n . real ( edata )
eidata = _n . imag ( edata )
# generate the data the hard way .
except :
r... |
def ledger ( self , start = None , end = None ) :
"""Returns a list of entries for this account .
Ledger returns a sequence of LedgerEntry ' s matching the criteria
in chronological order . The returned sequence can be boolean - tested
( ie . test that nothing was returned ) .
If ' start ' is given , only e... | DEBIT_IN_DB = self . _DEBIT_IN_DB ( )
flip = 1
if self . _positive_credit ( ) :
flip *= - 1
qs = self . _entries_range ( start = start , end = end )
qs = qs . order_by ( "transaction__t_stamp" , "transaction__tid" )
balance = Decimal ( "0.00" )
if start :
balance = self . balance ( start )
if not qs :
retur... |
def paginate_stream_index ( self , bucket , index , startkey , endkey = None , max_results = 1000 , return_terms = None , continuation = None , timeout = None , term_regex = None ) :
"""Iterates over a streaming paginated index query . This is equivalent to
calling : meth : ` stream _ index ` and then successivel... | # TODO FUTURE : implement " retry on connection closed "
# as in stream _ mapred
page = self . stream_index ( bucket , index , startkey , endkey = endkey , max_results = max_results , return_terms = return_terms , continuation = continuation , timeout = timeout , term_regex = term_regex )
yield page
while page . has_ne... |
def render_text ( path , cp ) :
"""Render a file as text .""" | # define filename and slug from path
filename = os . path . basename ( path )
slug = filename . replace ( '.' , '_' )
# initializations
content = None
# read file as a string
with codecs . open ( path , 'r' , encoding = 'utf-8' , errors = 'replace' ) as fp :
content = fp . read ( )
# replace all the escaped charact... |
def _rebuild_groups ( self ) :
"""Recreates the groups master list based on the groups hierarchy ( order matters here ,
since the parser uses order to determine lineage ) .""" | self . groups = [ ]
def collapse_group ( group ) :
for subgroup in group . children :
self . groups . append ( subgroup )
collapse_group ( subgroup )
collapse_group ( self . root ) |
def set_cpuid_leaf ( self , idx , idx_sub , val_eax , val_ebx , val_ecx , val_edx ) :
"""Sets the virtual CPU cpuid information for the specified leaf . Note that these values
are not passed unmodified . VirtualBox clears features that it doesn ' t support .
Currently supported index values for cpuid :
Standa... | if not isinstance ( idx , baseinteger ) :
raise TypeError ( "idx can only be an instance of type baseinteger" )
if not isinstance ( idx_sub , baseinteger ) :
raise TypeError ( "idx_sub can only be an instance of type baseinteger" )
if not isinstance ( val_eax , baseinteger ) :
raise TypeError ( "val_eax can... |
def disable_wrapper ( cls , disable , new_class ) :
"""Wrap the disable method to call pre and post disable signals and update
module status""" | def _wrapped ( self , * args , ** kwargs ) :
if not self . enabled :
raise AssertionError ( 'Module %s is already disabled' % self . verbose_name )
logger . info ( "Disabling %s module" % self . verbose_name )
pre_disable . send ( sender = self )
res = disable ( self , * args , ** kwargs )
#... |
def sweep ( crypto , private_key , to_address , fee = None , password = None , ** modes ) :
"""Move all funds by private key to another address .""" | from moneywagon . tx import Transaction
tx = Transaction ( crypto , verbose = modes . get ( 'verbose' , False ) )
tx . add_inputs ( private_key = private_key , password = password , ** modes )
tx . change_address = to_address
tx . fee ( fee )
return tx . push ( ) |
def run_fba ( model , rxn_id , direction = "max" , single_value = True ) :
"""Return the solution of an FBA to a set objective function .
Parameters
model : cobra . Model
The metabolic model under investigation .
rxn _ id : string
A string containing the reaction ID of the desired FBA objective .
direct... | model . objective = model . reactions . get_by_id ( rxn_id )
model . objective_direction = direction
if single_value :
try :
return model . slim_optimize ( )
except Infeasible :
return np . nan
else :
try :
solution = model . optimize ( )
return solution
except Infeasible... |
def create_namespaced_persistent_volume_claim ( self , namespace , body , ** kwargs ) : # noqa : E501
"""create _ namespaced _ persistent _ volume _ claim # noqa : E501
create a PersistentVolumeClaim # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request ,... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_namespaced_persistent_volume_claim_with_http_info ( namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . create_namespaced_persistent_volume_claim_with_http_info ( namespace , body , ** kwargs ... |
def find_agent ( self , desc ) :
'''Gives medium class of the agent if the agency hosts it .''' | agent_id = ( desc . doc_id if IDocument . providedBy ( desc ) else desc )
self . log ( "I'm trying to find the agent with id: %s" , agent_id )
result = first ( x for x in self . _agents if x . _descriptor . doc_id == agent_id )
return defer . succeed ( result ) |
def prepare_delete_monarchy ( self , node , position = None , save = True ) :
"""Prepares a given : class : ` CTENode ` ` node ` for deletion , by executing
the : const : ` DELETE _ METHOD _ MONARCHY ` semantics . Descendant nodes ,
if present , will be moved ; in this case the optional ` position ` can
be a ... | # We are going to iterate all children , even though the first child is
# treated in a special way , because the query iterator may be custom , so
# we will avoid using slicing children [ 0 ] and children [ 1 : ] .
first = None
for child in node . children . all ( ) :
if first is None :
first = child
... |
def sample ( cls , dataset , samples = [ ] ) :
"""Samples the gridded data into dataset of samples .""" | ndims = dataset . ndims
dimensions = dataset . dimensions ( label = 'name' )
arrays = [ dataset . data [ vdim . name ] for vdim in dataset . vdims ]
data = defaultdict ( list )
for sample in samples :
if np . isscalar ( sample ) :
sample = [ sample ]
if len ( sample ) != ndims :
sample = [ sampl... |
def _generate_soma ( self ) :
'''soma''' | radius = self . _obj . soma . radius
return _square_segment ( radius , ( 0. , - radius ) ) |
def _update ( dashboard , profile ) :
'''Update a specific dashboard .''' | payload = { 'dashboard' : dashboard , 'overwrite' : True }
request_url = "{0}/api/dashboards/db" . format ( profile . get ( 'grafana_url' ) )
response = requests . post ( request_url , headers = { "Authorization" : "Bearer {0}" . format ( profile . get ( 'grafana_token' ) ) } , json = payload )
return response . json (... |
def ensure_index ( self , key_or_list , cache_for = 300 , ** kwargs ) :
"""* * DEPRECATED * * - Ensures that an index exists on this collection .
. . versionchanged : : 3.0
* * DEPRECATED * *""" | warnings . warn ( "ensure_index is deprecated. Use create_index instead." , DeprecationWarning , stacklevel = 2 )
# The types supported by datetime . timedelta .
if not ( isinstance ( cache_for , integer_types ) or isinstance ( cache_for , float ) ) :
raise TypeError ( "cache_for must be an integer or float." )
if ... |
def replace_strings_in_list ( array_of_strigs , replace_with_strings ) :
"A value in replace _ with _ strings can be either single string or list of strings" | potentially_nested_list = [ replace_with_strings . get ( s ) or s for s in array_of_strigs ]
return list ( flatten ( potentially_nested_list ) ) |
def plot ( histogram : HistogramBase , kind : Optional [ str ] = None , backend : Optional [ str ] = None , ** kwargs ) :
"""Universal plotting function .
All keyword arguments are passed to the plotting methods .
Parameters
kind : Type of the plot ( like " scatter " , " line " , . . . ) , similar to pandas""... | backend_name , backend = _get_backend ( backend )
if kind is None :
kinds = [ t for t in backend . types if histogram . ndim in backend . dims [ t ] ]
if not kinds :
raise RuntimeError ( "No plot type is supported for {0}" . format ( histogram . __class__ . __name__ ) )
kind = kinds [ 0 ]
if kind in... |
def set_volume ( self , percent , update_group = True ) :
"""Set client volume percent .""" | if percent not in range ( 0 , 101 ) :
raise ValueError ( 'Volume percent out of range' )
new_volume = self . _client [ 'config' ] [ 'volume' ]
new_volume [ 'percent' ] = percent
self . _client [ 'config' ] [ 'volume' ] [ 'percent' ] = percent
yield from self . _server . client_volume ( self . identifier , new_volum... |
def __send_smtp_email ( self , recipients , subject , html_body , text_body ) :
"""Send an email using SMTP
Args :
recipients ( ` list ` of ` str ` ) : List of recipient email addresses
subject ( str ) : Subject of the email
html _ body ( str ) : HTML body of the email
text _ body ( str ) : Text body of t... | smtp = smtplib . SMTP ( dbconfig . get ( 'smtp_server' , NS_EMAIL , 'localhost' ) , dbconfig . get ( 'smtp_port' , NS_EMAIL , 25 ) )
source_arn = dbconfig . get ( 'source_arn' , NS_EMAIL )
return_arn = dbconfig . get ( 'return_path_arn' , NS_EMAIL )
from_arn = dbconfig . get ( 'from_arn' , NS_EMAIL )
msg = MIMEMultipar... |
def create_followup ( self , post , content , anonymous = False ) :
"""Create a follow - up on a post ` post ` .
It seems like if the post has ` < p > ` tags , then it ' s treated as HTML ,
but is treated as text otherwise . You ' ll want to provide ` content `
accordingly .
: type post : dict | str | int
... | try :
cid = post [ "id" ]
except KeyError :
cid = post
params = { "cid" : cid , "type" : "followup" , # For followups , the content is actually put into the subject .
"subject" : content , "content" : "" , "anonymous" : "yes" if anonymous else "no" , }
return self . _rpc . content_create ( params ) |
def unget_service ( self , reference ) : # type : ( ServiceReference ) - > bool
"""Disables a reference to the service
: return : True if the bundle was using this reference , else False""" | # Lose the dependency
return self . __framework . _registry . unget_service ( self . __bundle , reference ) |
def get_raw ( tree ) :
"""Get the exact words in lowercase in the tree object .
Args :
tree ( Tree ) : Parsed tree structure
Returns :
Resulting string of tree ` ` ( Ex : " The red car " ) ` `""" | if isinstance ( tree , Tree ) :
words = [ ]
for child in tree :
words . append ( get_raw ( child ) )
return ' ' . join ( words )
else :
return tree |
def _cleanRecursive ( self , subSelf ) :
"""Delete all NestedOrderedDict that haven ' t any entries .""" | for key , item in list ( subSelf . items ( ) ) :
if self . isNestedDict ( item ) :
if not item :
subSelf . pop ( key )
else :
self . _cleanRecursive ( item ) |
def connectRelay ( self ) :
"""Builds the target protocol and connects it to the relay transport .""" | self . protocol = self . connector . buildProtocol ( None )
self . connected = True
self . protocol . makeConnection ( self ) |
def app_create ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / apps # create - app" | api_path = "/api/v2/apps.json"
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def GetFileSystemTypeIndicators ( cls , path_spec , resolver_context = None ) :
"""Determines if a file contains a supported file system types .
Args :
path _ spec ( PathSpec ) : path specification .
resolver _ context ( Optional [ Context ] ) : resolver context , where None
represents the built - in contex... | if ( cls . _file_system_remainder_list is None or cls . _file_system_store is None ) :
specification_store , remainder_list = cls . _GetSpecificationStore ( definitions . FORMAT_CATEGORY_FILE_SYSTEM )
cls . _file_system_remainder_list = remainder_list
cls . _file_system_store = specification_store
if cls . ... |
def logn2 ( n , p ) :
"""Best p - bit lower and upper bounds for log ( 2 ) / log ( n ) , as Fractions .""" | with precision ( p ) :
extra = 10
while True :
with precision ( p + extra ) : # use extra precision for intermediate step
log2upper = log2 ( n , RoundTowardPositive )
log2lower = log2 ( n , RoundTowardNegative )
lower = div ( 1 , log2upper , RoundTowardNegative )
... |
def make_symlink ( source , link_path ) :
"""Create a symlink at ` link _ path ` referring to ` source ` .""" | if not supports_symlinks ( ) :
dbt . exceptions . system_error ( 'create a symbolic link' )
return os . symlink ( source , link_path ) |
def load_sequences_to_strains ( self , joblib = False , cores = 1 , force_rerun = False ) :
"""Wrapper function for _ load _ sequences _ to _ strain""" | log . info ( 'Loading sequences to strain GEM-PROs...' )
if joblib :
result = DictList ( Parallel ( n_jobs = cores ) ( delayed ( self . _load_sequences_to_strain ) ( s , force_rerun ) for s in self . strain_ids ) )
else :
result = [ ]
for s in tqdm ( self . strain_ids ) :
result . append ( self . _l... |
def __execute_ret ( command , host = None , admin_username = None , admin_password = None , module = None ) :
'''Execute rac commands''' | if module :
if module == 'ALL' :
modswitch = '-a '
else :
modswitch = '-m {0}' . format ( module )
else :
modswitch = ''
if not host : # This is a local call
cmd = __salt__ [ 'cmd.run_all' ] ( 'racadm {0} {1}' . format ( command , modswitch ) )
else :
cmd = __salt__ [ 'cmd.run_all' ]... |
def floor_func ( self , addr ) :
"""Return the function who has the greatest address that is less than or equal to ` addr ` .
: param int addr : The address to query .
: return : A Function instance , or None if there is no other function before ` addr ` .
: rtype : Function or None""" | try :
prev_addr = self . _function_map . floor_addr ( addr )
return self . _function_map [ prev_addr ]
except KeyError :
return None |
def _copy_module ( self , conn , tmp , module_name , module_args , inject ) :
'''transfer a module over SFTP , does not run it''' | if module_name . startswith ( "/" ) :
raise errors . AnsibleFileNotFound ( "%s is not a module" % module_name )
# Search module path ( s ) for named module .
in_path = utils . plugins . module_finder . find_plugin ( module_name )
if in_path is None :
raise errors . AnsibleFileNotFound ( "module %s not found in ... |
def decode_preflist ( self , item ) :
"""Decodes a preflist response
: param preflist : a bucket / key preflist
: type preflist : list of
riak . pb . riak _ kv _ pb2 . RpbBucketKeyPreflistItem
: rtype dict""" | result = { 'partition' : item . partition , 'node' : bytes_to_str ( item . node ) , 'primary' : item . primary }
return result |
def user_describe ( object_id , input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / user - xxxx / describe API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Users # API - method % 3A - % 2Fuser - xxxx % 2Fdescribe""" | return DXHTTPRequest ( '/%s/describe' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def fix_bad_headers ( self ) :
"""Fix up bad headers that cause problems for the wrapped WCS
module .
Subclass can override this method to fix up issues with the
header for problem FITS files .""" | # WCSLIB doesn ' t like " nonstandard " units
unit = self . header . get ( 'CUNIT1' , 'deg' )
if unit . upper ( ) == 'DEGREE' : # self . header . update ( ' CUNIT1 ' , ' deg ' )
self . header [ 'CUNIT1' ] = 'deg'
unit = self . header . get ( 'CUNIT2' , 'deg' )
if unit . upper ( ) == 'DEGREE' : # self . header . upd... |
def pop_all ( self ) :
"""NON - BLOCKING POP ALL IN QUEUE , IF ANY""" | with self . lock :
output = list ( self . queue )
self . queue . clear ( )
return output |
def blksize ( path ) :
"""Get optimal file system buffer size ( in bytes ) for I / O calls .""" | diskfreespace = win32file . GetDiskFreeSpace
dirname = os . path . dirname ( fullpath ( path ) )
try :
cluster_sectors , sector_size = diskfreespace ( dirname ) [ : 2 ]
size = cluster_sectors * sector_size
except win32file . error as e :
if e . winerror != winerror . ERROR_NOT_READY :
raise
slee... |
def map_uniprot_resnum_to_pdb ( uniprot_resnum , chain_id , sifts_file ) :
"""Map a UniProt residue number to its corresponding PDB residue number .
This function requires that the SIFTS file be downloaded ,
and also a chain ID ( as different chains may have different mappings ) .
Args :
uniprot _ resnum ( ... | # Load the xml with lxml
parser = etree . XMLParser ( ns_clean = True )
tree = etree . parse ( sifts_file , parser )
root = tree . getroot ( )
my_pdb_resnum = None
# TODO : " Engineered _ Mutation is also a possible annotation , need to figure out what to do with that
my_pdb_annotation = False
# Find the right chain ( ... |
def download_from_files ( files , output_path , width ) :
"""Download files from a given file list .""" | files_to_download = get_files_from_arguments ( files , width )
download_files_if_not_in_manifest ( files_to_download , output_path ) |
def create_authorization ( self , scopes = github . GithubObject . NotSet , note = github . GithubObject . NotSet , note_url = github . GithubObject . NotSet , client_id = github . GithubObject . NotSet , client_secret = github . GithubObject . NotSet , onetime_password = None ) :
""": calls : ` POST / authorizatio... | assert scopes is github . GithubObject . NotSet or all ( isinstance ( element , ( str , unicode ) ) for element in scopes ) , scopes
assert note is github . GithubObject . NotSet or isinstance ( note , ( str , unicode ) ) , note
assert note_url is github . GithubObject . NotSet or isinstance ( note_url , ( str , unicod... |
def validate_unwrap ( self , value ) :
'''Check that ` ` value ` ` is valid for unwrapping with ` ` ComputedField . computed _ type ` `''' | try :
self . computed_type . validate_unwrap ( value )
except BadValueException as bve :
self . _fail_validation ( value , 'Bad value for computed field' , cause = bve ) |
def string ( self , units : typing . Optional [ str ] = None ) -> str :
"""Return a string representation of the pressure , using the given units .""" | if not units :
_units : str = self . _units
else :
if not units . upper ( ) in CustomPressure . legal_units :
raise UnitsError ( "unrecognized pressure unit: '" + units + "'" )
_units = units . upper ( )
val = self . value ( units )
if _units == "MB" :
return "%.0f mb" % val
if _units == "HPA" :... |
def from_http_response ( response ) :
"""Create a : class : ` GoogleAPICallError ` from a : class : ` requests . Response ` .
Args :
response ( requests . Response ) : The HTTP response .
Returns :
GoogleAPICallError : An instance of the appropriate subclass of
: class : ` GoogleAPICallError ` , with the ... | try :
payload = response . json ( )
except ValueError :
payload = { "error" : { "message" : response . text or "unknown error" } }
error_message = payload . get ( "error" , { } ) . get ( "message" , "unknown error" )
errors = payload . get ( "error" , { } ) . get ( "errors" , ( ) )
message = "{method} {url}: {e... |
def find_packages ( path ) :
"""Find all java files matching the " * Package . java " pattern within
the given enaml package directory relative to the java source path .""" | matches = [ ]
root = join ( path , 'src' , 'main' , 'java' )
for folder , dirnames , filenames in os . walk ( root ) :
for filename in fnmatch . filter ( filenames , '*Package.java' ) : # : Open and make sure it ' s an EnamlPackage somewhere
with open ( join ( folder , filename ) ) as f :
if "im... |
def recover ( self , key , value ) :
"""Get the deserialized value for a given key , and the serialized version .""" | if key not in self . _dtypes :
self . read_types ( )
if key not in self . _dtypes :
raise ValueError ( "Unknown datatype for {} and {}" . format ( key , value ) )
return self . _dtypes [ key ] [ 2 ] ( value ) |
def read_config ( cls , configparser ) :
"""Read configuration file options .""" | config = dict ( )
config [ cls . _filename_re_key ] = configparser . get ( cls . __name__ , cls . _filename_re_key ) if configparser . has_option ( cls . __name__ , cls . _filename_re_key ) else None
return config |
def write_file ( self , * args , ** kwargs ) :
"""Write a file into this directory
This method takes the same arguments as : meth : ` . FileDataAPI . write _ file `
with the exception of the ` ` path ` ` argument which is not needed here .""" | return self . _fdapi . write_file ( self . get_path ( ) , * args , ** kwargs ) |
def _windows_get_window_size ( ) :
"""Return ( width , height ) of available window area on Windows .
(0 , 0 ) if no console is allocated .""" | sbi = CONSOLE_SCREEN_BUFFER_INFO ( )
ret = windll . kernel32 . GetConsoleScreenBufferInfo ( console_handle , byref ( sbi ) )
if ret == 0 :
return ( 0 , 0 )
return ( sbi . srWindow . Right - sbi . srWindow . Left + 1 , sbi . srWindow . Bottom - sbi . srWindow . Top + 1 ) |
def brancher ( # noqa : E302
self , branches = None , all_branches = False , tags = None , all_tags = False ) :
"""Generator that iterates over specified revisions .
Args :
branches ( list ) : a list of branches to iterate over .
all _ branches ( bool ) : iterate over all available branches .
tags ( list ) ... | if not any ( [ branches , all_branches , tags , all_tags ] ) :
yield ""
return
saved_tree = self . tree
revs = [ ]
scm = self . scm
if self . scm . is_dirty ( ) :
from dvc . scm . tree import WorkingTree
self . tree = WorkingTree ( self . root_dir )
yield "Working Tree"
if all_branches :
branche... |
def get_vnetwork_portgroups_output_vnetwork_pgs_datacenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_portgroups = ET . Element ( "get_vnetwork_portgroups" )
config = get_vnetwork_portgroups
output = ET . SubElement ( get_vnetwork_portgroups , "output" )
vnetwork_pgs = ET . SubElement ( output , "vnetwork-pgs" )
datacenter = ET . SubElement ( vnetwork_pgs , "datacenter" )... |
def subtract_ranges ( r1s , r2s , already_sorted = False ) :
"""Subtract multiple ranges from a list of ranges
: param r1s : range list 1
: param r2s : range list 2
: param already _ sorted : default ( False )
: type r1s : GenomicRange [ ]
: type r2s : GenomicRange [ ]
: return : new range r1s minus r2s... | from seqtools . stream import MultiLocusStream
if not already_sorted :
r1s = merge_ranges ( r1s )
r2s = merge_ranges ( r2s )
outputs = [ ]
mls = MultiLocusStream ( [ BedArrayStream ( r1s ) , BedArrayStream ( r2s ) ] )
tot1 = 0
tot2 = 0
for loc in mls : # [ beds1 , beds2 ] = loc . get _ payload ( )
v = loc .... |
def findnode ( obj , path = '' ) :
"""Returns a Node pointing to obj .
If obj is a ctypes - derived class , an UnboundNode is returned . If obj is
an instance of such a class , then a BoundNode will be returned .
If the optional path is provided , it is a string to look up searching
down the original source... | if isclass ( obj ) :
node = _createunbound ( obj )
else :
node = _createbound ( obj )
# And walk it down .
pathparts = re . split ( r'\]?(?:[[.]|$)' , path )
for part in pathparts :
if not part :
continue
try :
idx = int ( part )
node = node [ idx ]
except ValueError :
... |
def produce_pca_explorer ( corpus , category , word2vec_model = None , projection_model = None , embeddings = None , projection = None , term_acceptance_re = re . compile ( '[a-z]{3,}' ) , x_dim = 0 , y_dim = 1 , scaler = scale , show_axes = False , show_dimensions_on_tooltip = True , ** kwargs ) :
"""Parameters
... | if projection is None :
embeddings_resolover = EmbeddingsResolver ( corpus )
if embeddings is not None :
embeddings_resolover . set_embeddings ( embeddings )
else :
embeddings_resolover . set_embeddings_model ( word2vec_model , term_acceptance_re )
corpus , projection = embeddings_resolo... |
def upix_to_pix ( upix ) :
"""Get the nside from a unique pixel number .""" | nside = np . power ( 2 , np . floor ( np . log2 ( upix / 4 ) ) / 2 ) . astype ( int )
pix = upix - 4 * np . power ( nside , 2 )
return pix , nside |
def restore ( self , res_id , backup_snap = None ) :
"""Restores a snapshot .
: param res _ id : the LUN number of primary LUN or snapshot mount point to
be restored .
: param backup _ snap : the name of a backup snapshot to be created before
restoring .""" | name = self . _get_name ( )
out = self . _cli . restore_snap ( name , res_id , backup_snap )
ex . raise_if_err ( out , 'failed to restore snap {}.' . format ( name ) , default = ex . VNXSnapError ) |
def delete_many ( cls , documents ) :
"""Delete multiple documents""" | # Ensure all documents have been converted to frames
frames = cls . _ensure_frames ( documents )
all_count = len ( documents )
assert len ( [ f for f in frames if '_id' in f . _document ] ) == all_count , "Can't delete documents without `_id`s"
# Send delete signal
signal ( 'delete' ) . send ( cls , frames = frames )
#... |
def settings_view_for_block ( block_wrapper , settings_view_factory ) :
"""Returns the settings view for an arbitrary block .
Args :
block _ wrapper ( BlockWrapper ) : The block for which a settings
view is to be returned
settings _ view _ factory ( SettingsViewFactory ) : The settings
view factory used t... | state_root_hash = block_wrapper . state_root_hash if block_wrapper is not None else None
return settings_view_factory . create_settings_view ( state_root_hash ) |
def create_v4_signature ( self , request_params ) :
'''Create URI and signature headers based on AWS V4 signing process .
Refer to https : / / docs . aws . amazon . com / AlexaWebInfoService / latest / ApiReferenceArticle . html for request params .
: param request _ params : dictionary of request parameters
... | method = 'GET'
service = 'awis'
host = 'awis.us-west-1.amazonaws.com'
region = 'us-west-1'
endpoint = 'https://awis.amazonaws.com/api'
request_parameters = urlencode ( [ ( key , request_params [ key ] ) for key in sorted ( request_params . keys ( ) ) ] )
# Key derivation functions . See :
# http : / / docs . aws . amaz... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.