signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_token_credentials ( cls , username , request ) :
"""Get api token for user with username of : username :
Used by Token - based auth as ` credentials _ callback ` kwarg .""" | try :
user = cls . get_item ( username = username )
except Exception as ex :
log . error ( str ( ex ) )
forget ( request )
else :
if user :
return user . api_key . token |
def get_bool ( _bytearray , byte_index , bool_index ) :
"""Get the boolean value from location in bytearray""" | index_value = 1 << bool_index
byte_value = _bytearray [ byte_index ]
current_value = byte_value & index_value
return current_value == index_value |
def _pfp__handle_updated ( self , watched_field ) :
"""Handle the watched field that was updated""" | self . _pfp__no_notify = True
# nested data has been changed , so rebuild the
# nested data to update the field
# TODO a global setting to determine this behavior ?
# could slow things down a bit for large nested structures
# notice the use of _ is _ here - ' is ' ! = ' = = ' . ' = = ' uses
# the _ _ eq _ _ operator , ... |
def _get_cromwell_execution_dir ( base_dir , target_glob ) :
"""Retrieve the baseline directory with cromwell output files .
Handles Cromwell restarts where there are multiple work directories and
we traverse symlinks back to the original .""" | cur_dir = glob . glob ( os . path . join ( base_dir , target_glob ) ) [ 0 ]
if os . path . exists ( os . path . join ( cur_dir , "cwl.output.json" ) ) :
return base_dir
else :
symlink_dir = os . path . dirname ( os . path . realpath ( os . path . join ( cur_dir , "script" ) ) )
ref_base = os . path . dirnam... |
def _force_read ( self , element , value , text_prefix_before , text_suffix_before , text_prefix_after , text_suffix_after , data_of ) :
"""Force the screen reader display an information of element with prefixes
or suffixes .
: param element : The reference element .
: type element : hatemile . util . html . ... | if ( text_prefix_before ) or ( text_suffix_before ) :
text_before = text_prefix_before + value + text_suffix_before
else :
text_before = ''
if ( text_prefix_after ) or ( text_suffix_after ) :
text_after = text_prefix_after + value + text_suffix_after
else :
text_after = ''
self . _force_read_simple ( el... |
def persist ( self , storageLevel ) :
"""Persists the underlying RDD with the specified storage level .""" | if not isinstance ( storageLevel , StorageLevel ) :
raise TypeError ( "`storageLevel` should be a StorageLevel, got %s" % type ( storageLevel ) )
javaStorageLevel = self . _java_matrix_wrapper . _sc . _getJavaStorageLevel ( storageLevel )
self . _java_matrix_wrapper . call ( "persist" , javaStorageLevel )
return se... |
def from_clause ( cls , clause ) :
"""Factory method""" | name = clause . getName ( )
if name == "not" :
cond = Invert ( cls . from_clause ( clause [ 1 ] ) )
elif name == "operator" :
cond = OperatorConstraint . from_clause ( clause )
elif name == "conjunction" or clause . conjunction :
cond = Conjunction . from_clause ( clause )
elif name == "function" :
cond... |
def project_remove_tags ( object_id , input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / project - xxxx / removeTags API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Projects # API - method % 3A - % 2Fproject - xxxx % 2FremoveTags""" | return DXHTTPRequest ( '/%s/removeTags' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def prepare_info ( self , ts = None ) :
"""Return all session unique ids recorded in prepare phase .
: param ts : timestamp , default to current timestamp
: return : set of session unique ids""" | sp_key = "%s:session_prepare" % self . namespace ( ts or int ( time . time ( ) ) )
return set ( s ( m ) for m in self . r . smembers ( sp_key ) ) |
def _folder_get_content_iter ( self , folder_key = None ) :
"""Iterator for api . folder _ get _ content""" | lookup_params = [ { 'content_type' : 'folders' , 'node' : 'folders' } , { 'content_type' : 'files' , 'node' : 'files' } ]
for param in lookup_params :
more_chunks = True
chunk = 0
while more_chunks :
chunk += 1
content = self . api . folder_get_content ( content_type = param [ 'content_type'... |
def mill ( self ) :
'''Processes the variables collected from agents using the function millRule ,
storing the results in attributes named in aggr _ sow .
Parameters
none
Returns
none''' | # Make a dictionary of inputs for the millRule
reap_vars_string = ''
for name in self . reap_vars :
reap_vars_string += ' \'' + name + '\' : self.' + name + ','
const_vars_string = ''
for name in self . const_vars :
const_vars_string += ' \'' + name + '\' : self.' + name + ','
mill_dict = eval ( '{' + reap_vars... |
def cutadapt ( job , inputs , r1_id , r2_id ) :
"""Filters out adapters that may be left in the RNA - seq files
: param JobFunctionWrappingJob job : passed by Toil automatically
: param Namespace inputs : Stores input arguments ( see main )
: param str r1 _ id : FileStore ID of read 1 fastq
: param str r2 _... | job . fileStore . logToMaster ( 'Running CutAdapt: {}' . format ( inputs . uuid ) )
work_dir = job . fileStore . getLocalTempDir ( )
inputs . improper_pair = None
# Retrieve files
job . fileStore . readGlobalFile ( r1_id , os . path . join ( work_dir , 'R1.fastq' ) )
job . fileStore . readGlobalFile ( r2_id , os . path... |
def name_resolve ( self , name = None , recursive = False , nocache = False , ** kwargs ) :
"""Gets the value currently published at an IPNS name .
IPNS is a PKI namespace , where names are the hashes of public keys , and
the private key enables publishing new ( signed ) values . In resolve , the
default valu... | kwargs . setdefault ( "opts" , { "recursive" : recursive , "nocache" : nocache } )
args = ( name , ) if name is not None else ( )
return self . _client . request ( '/name/resolve' , args , decoder = 'json' , ** kwargs ) |
def parse_tablature ( lines ) :
'''Parse a list of lines into a ` Tablature ` .''' | lines = [ parse_line ( l ) for l in lines ]
return Tablature ( lines = lines ) |
def serialize ( self ) :
"""Serialize to JSON document that can be accepted by the
X - Ray backend service . It uses jsonpickle to perform
serialization .""" | try :
return jsonpickle . encode ( self , unpicklable = False )
except Exception :
log . exception ( "got an exception during serialization" ) |
def _bytes_from_json ( value , field ) :
"""Base64 - decode value""" | if _not_null ( value , field ) :
return base64 . standard_b64decode ( _to_bytes ( value ) ) |
def get_rec_dtype ( self , ** keys ) :
"""Get the dtype for the specified columns
parameters
colnums : integer array
The column numbers , 0 offset
vstorage : string , optional
See docs in read _ columns""" | colnums = keys . get ( 'colnums' , None )
vstorage = keys . get ( 'vstorage' , self . _vstorage )
if colnums is None :
colnums = self . _extract_colnums ( )
descr = [ ]
isvararray = numpy . zeros ( len ( colnums ) , dtype = numpy . bool )
for i , colnum in enumerate ( colnums ) :
dt , isvar = self . get_rec_col... |
def create_key_filter ( properties : Dict [ str , list ] ) -> List [ Tuple ] :
"""Generate combinations of key , value pairs for each key in properties .
Examples
properties = { ' ent ' : [ ' geo _ rev ' , ' supply _ chain ' ] , ' own ' , ' fi ' }
> > create _ key _ filter ( properties )
- - > [ ( ' ent ' ,... | combinations = ( product ( [ k ] , v ) for k , v in properties . items ( ) )
return chain . from_iterable ( combinations ) |
def load_plugin_widgets ( self ) :
"""Pull widgets added via plugins using the ` enaml _ native _ widgets `
entry point . The entry point function must return a dictionary of
Widget declarations to add to the core api .
def install ( ) :
from charts . widgets . chart _ view import BarChart , LineChart
ret... | from enamlnative . widgets import api
for plugin in self . get_plugins ( group = 'enaml_native_widgets' ) :
get_widgets = plugin . load ( )
for name , widget in iter ( get_widgets ( ) ) : # : Update the core api with these widgets
setattr ( api , name , widget ) |
def _set_vrf ( self , v , load = False ) :
"""Setter method for vrf , mapped from YANG variable / vrf ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vrf is considered as a private
method . Backends looking to populate this variable should
do so via calling... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "vrf_name" , vrf . vrf , yang_name = "vrf" , rest_name = "vrf" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'vrf-name' , extensions = { u'tail... |
def fetch_pcr ( * args , ** kwargs ) :
"""Wrapper for fetch to automatically parse results from the PCR API .""" | # Load user ' s token from ` PCR _ AUTH _ TOKEN ` , use public token as default if missing
kwargs [ 'token' ] = os . getenv ( "PCR_AUTH_TOKEN" , "public" )
return fetch ( DOMAIN , * args , ** kwargs ) [ 'result' ] |
def process_edge_flow ( self , source , sink , i , j , algo , q ) :
'''API : process _ edge _ flow ( self , source , sink , i , j , algo , q )
Description :
Used by by max _ flow _ preflowpush ( ) method . Processes edges along
prefolow push .
Input :
source : Source node name of flow graph .
sink : Sin... | if ( self . get_node_attr ( i , 'distance' ) != self . get_node_attr ( j , 'distance' ) + 1 ) :
return False
if ( i , j ) in self . edge_attr :
edge = ( i , j )
capacity = self . get_edge_attr ( i , j , 'capacity' )
mult = 1
else :
edge = ( j , i )
capacity = 0
mult = - 1
flow = mult * self ... |
def decode ( token , certs = None , verify = True , audience = None ) :
"""Decode and verify a JWT .
Args :
token ( str ) : The encoded JWT .
certs ( Union [ str , bytes , Mapping [ str , Union [ str , bytes ] ] ] ) : The
certificate used to validate the JWT signature . If bytes or string ,
it must the th... | header , payload , signed_section , signature = _unverified_decode ( token )
if not verify :
return payload
# If certs is specified as a dictionary of key IDs to certificates , then
# use the certificate identified by the key ID in the token header .
if isinstance ( certs , collections . Mapping ) :
key_id = he... |
def use_absl_handler ( ) :
"""Uses the ABSL logging handler for logging if not yet configured .
The absl handler is already attached to root if there are no other handlers
attached when importing this module .
Otherwise , this method is called in app . run ( ) so absl handler is used .""" | absl_handler = get_absl_handler ( )
if absl_handler not in logging . root . handlers :
logging . root . addHandler ( absl_handler )
FLAGS [ 'verbosity' ] . _update_logging_levels ( ) |
def update ( d , e ) :
"""Return a copy of dict ` d ` updated with dict ` e ` .""" | res = copy . copy ( d )
res . update ( e )
return res |
def lorem ( anon , obj , field , val ) :
"""Generates a paragraph of lorem ipsum text""" | return ' ' . join ( anon . faker . sentences ( field = field ) ) |
def update_variables ( X , Z , U , prox_f , step_f , prox_g , step_g , L ) :
"""Update the primal and dual variables
Note : X , Z , U are updated inline
Returns : LX , R , S""" | if not hasattr ( prox_g , '__iter__' ) :
if prox_g is not None :
dX = step_f / step_g * L . T . dot ( L . dot ( X ) - Z + U )
X [ : ] = prox_f ( X - dX , step_f )
LX , R , S = do_the_mm ( X , step_f , Z , U , prox_g , step_g , L )
else : # fall back to simple fixed - point method for f
... |
def __response_url ( self , message_id ) :
"""URL for responding to agent requests .""" | if self . from_ . pid != 0 :
path = AGENT_RESPONSE_PATH % ( self . from_ . pid , message_id )
return "http://%s:%s/%s" % ( self . host , self . port , path ) |
def close_db_connections ( self , instance , db_key , db_name = None ) :
"""We close the db connections explicitly b / c when we don ' t they keep
locks on the db . This presents as issues such as the SQL Server Agent
being unable to stop .""" | conn_key = self . _conn_key ( instance , db_key , db_name )
if conn_key not in self . connections :
return
try :
self . connections [ conn_key ] [ 'conn' ] . close ( )
del self . connections [ conn_key ]
except Exception as e :
self . log . warning ( "Could not close adodbapi db connection\n{0}" . forma... |
def from_array ( arr , name = None ) : # type : ( np . ndarray [ Any ] , Optional [ Text ] ) - > TensorProto
"""Converts a numpy array to a tensor def .
Inputs :
arr : a numpy array .
name : ( optional ) the name of the tensor .
Returns :
tensor _ def : the converted tensor def .""" | tensor = TensorProto ( )
tensor . dims . extend ( arr . shape )
if name :
tensor . name = name
if arr . dtype == np . object : # Special care for strings .
tensor . data_type = mapping . NP_TYPE_TO_TENSOR_TYPE [ arr . dtype ]
# TODO : Introduce full string support .
# We flatten the array in case there ... |
def get_form_value ( self , form_key , object_brain_uid , default = None ) :
"""Returns a value from the request ' s form for the given uid , if any""" | if form_key not in self . request . form :
return default
uid = object_brain_uid
if not api . is_uid ( uid ) :
uid = api . get_uid ( object_brain_uid )
values = self . request . form . get ( form_key )
if isinstance ( values , list ) :
if len ( values ) == 0 :
return default
if len ( values ) > ... |
def run ( ) :
"""Compare two or more sets of GO IDs . Best done using sections .""" | obj = CompareGOsCli ( )
obj . write ( obj . kws . get ( 'xlsx' ) , obj . kws . get ( 'ofile' ) , obj . kws . get ( 'verbose' , False ) ) |
def pytype_to_deps_hpp ( t ) :
"""python - > pythonic type hpp filename .""" | if isinstance ( t , List ) :
return { 'list.hpp' } . union ( pytype_to_deps_hpp ( t . __args__ [ 0 ] ) )
elif isinstance ( t , Set ) :
return { 'set.hpp' } . union ( pytype_to_deps_hpp ( t . __args__ [ 0 ] ) )
elif isinstance ( t , Dict ) :
tkey , tvalue = t . __args__
return { 'dict.hpp' } . union ( py... |
def identifier_simple ( mesh ) :
"""Return a basic identifier for a mesh , consisting of properties
that have been hand tuned to be somewhat robust to rigid
transformations and different tesselations .
Parameters
mesh : Trimesh object
Source geometry
Returns
identifier : ( 6 , ) float
Identifying va... | # verify the cache once
mesh . _cache . verify ( )
# don ' t check hashes during identifier as we aren ' t
# changing any data values of the mesh inside block
# if we did change values in cache block things would break
with mesh . _cache : # pre - allocate identifier so indexes of values can ' t move around
# like they... |
def cli ( env , volume_id , notes ) :
"""Creates a snapshot on a given volume""" | block_manager = SoftLayer . BlockStorageManager ( env . client )
snapshot = block_manager . create_snapshot ( volume_id , notes = notes )
if 'id' in snapshot :
click . echo ( 'New snapshot created with id: %s' % snapshot [ 'id' ] )
else :
click . echo ( 'Error occurred while creating snapshot.\n' 'Ensure volume... |
def get_power_state ( self , userid ) :
"""Get power status of a z / VM instance .""" | LOG . debug ( 'Querying power stat of %s' % userid )
requestData = "PowerVM " + userid + " status"
action = "query power state of '%s'" % userid
with zvmutils . log_and_reraise_smt_request_failed ( action ) :
results = self . _request ( requestData )
with zvmutils . expect_invalid_resp_data ( results ) :
status... |
def linreg_ols_lu ( y , X ) :
"""Linear Regression , OLS , by solving linear equations and LU decomposition
Properties
* based on LAPACK ' s _ gesv what applies LU decomposition
* avoids using python ' s inverse functions
* should be stable
* no overhead or other computations
Example :
beta = linreg _... | import numpy as np
try : # solve OLS formula
return np . linalg . solve ( np . dot ( X . T , X ) , np . dot ( X . T , y ) )
except np . linalg . LinAlgError :
print ( "LinAlgError: X*X' is singular or not square." )
return None |
def quantile ( expr , prob = None , ** kw ) :
"""Percentile value .
: param expr :
: param prob : probability or list of probabilities , in [ 0 , 1]
: return :""" | prob = kw . get ( '_prob' , prob )
output_type = _stats_type ( expr )
if isinstance ( prob , ( list , set ) ) and not isinstance ( expr , GroupBy ) :
output_type = types . List ( output_type )
return _reduction ( expr , Quantile , output_type , _prob = prob ) |
def complete_sum ( self ) :
"""Return an equivalent DNF expression that includes all prime
implicants .""" | node = self . node . complete_sum ( )
if node is self . node :
return self
else :
return _expr ( node ) |
def fastrcnn_outputs ( feature , num_classes , class_agnostic_regression = False ) :
"""Args :
feature ( any shape ) :
num _ classes ( int ) : num _ category + 1
class _ agnostic _ regression ( bool ) : if True , regression to N x 1 x 4
Returns :
cls _ logits : N x num _ class classification logits
reg ... | classification = FullyConnected ( 'class' , feature , num_classes , kernel_initializer = tf . random_normal_initializer ( stddev = 0.01 ) )
num_classes_for_box = 1 if class_agnostic_regression else num_classes
box_regression = FullyConnected ( 'box' , feature , num_classes_for_box * 4 , kernel_initializer = tf . random... |
def data ( self ) :
"""Return the examples in the dataset in order , sorted , or shuffled .""" | if self . sort :
xs = sorted ( self . dataset , key = self . sort_key )
elif self . shuffle :
xs = [ self . dataset [ i ] for i in self . random_shuffler ( range ( len ( self . dataset ) ) ) ]
else :
xs = self . dataset
return xs |
def flavor_access_list ( name , projects , ** kwargs ) :
'''Grants access of the flavor to a project . Flavor must be private .
: param name : non - public flavor name
: param projects : list of projects which should have the access to the flavor
. . code - block : : yaml
nova - flavor - share :
nova . fl... | dry_run = __opts__ [ 'test' ]
ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } }
kwargs . update ( { 'filter' : { 'is_public' : False } } )
try :
flavor_list = __salt__ [ 'nova.flavor_list' ] ( ** kwargs )
flavor_id = flavor_list [ name ] [ 'id' ]
except KeyError :
raise
project_l... |
def terminate ( self , unique_id , configs = None ) :
"""Issues a kill - 15 to the specified process
: Parameter unique _ id : the name of the process""" | self . _send_signal ( unique_id , signal . SIGTERM , configs ) |
def change_scroll ( self , position ) :
"""Args :
position ( int ) : Vertical location to end scroll window
Change scroll window""" | self . stream . write ( self . hide_cursor )
self . stream . write ( self . csr ( 0 , position ) )
self . stream . write ( self . move ( position , 0 ) ) |
def focusOutEvent ( self , event ) :
"""Updates the focus in state for this edit .
: param event | < QFocusEvent >""" | super ( XLineEdit , self ) . focusOutEvent ( event )
self . _focusedIn = False |
def _route_flags ( rflags ) :
'''https : / / github . com / torvalds / linux / blob / master / include / uapi / linux / route . h
https : / / github . com / torvalds / linux / blob / master / include / uapi / linux / ipv6 _ route . h''' | flags = ''
fmap = { 0x0001 : 'U' , # RTF _ UP , route is up
0x0002 : 'G' , # RTF _ GATEWAY , use gateway
0x0004 : 'H' , # RTF _ HOST , target is a host
0x0008 : 'R' , # RET _ REINSTATE , reinstate route for dynamic routing
0x0010 : 'D' , # RTF _ DYNAMIC , dynamically installed by daemon or redirect
0x0020 : 'M' , # RTF... |
def install_cache ( expire_after = 12 * 3600 , cache_post = False ) :
"""Patches the requests library with requests _ cache .""" | allowable_methods = [ 'GET' ]
if cache_post :
allowable_methods . append ( 'POST' )
requests_cache . install_cache ( expire_after = expire_after , allowable_methods = allowable_methods ) |
def pop_all ( self ) :
"""Preserve the context stack by transferring it to a new instance""" | ret = ExitStack ( )
ret . _context_stack . append ( self . _context_stack . pop ( ) )
self . _context_stack . append ( [ ] ) |
def _parse_on_demand_syllabus ( self , course_name , page , reverse = False , unrestricted_filenames = False , subtitle_language = 'en' , video_resolution = None , download_quizzes = False , mathjax_cdn_url = None , download_notebooks = False ) :
"""Parse a Coursera on - demand course listing / syllabus page .
@ ... | dom = json . loads ( page )
class_id = dom [ 'elements' ] [ 0 ] [ 'id' ]
logging . info ( 'Parsing syllabus of on-demand course (id=%s). ' 'This may take some time, please be patient ...' , class_id )
modules = [ ]
json_modules = dom [ 'linked' ] [ 'onDemandCourseMaterialItems.v2' ]
course = CourseraOnDemand ( session ... |
def build_filename ( self , binary ) :
"""Return the proposed filename with extension for the binary .""" | template = '%(APP)s-%(VERSION)s.%(LOCALE)s.%(PLATFORM)s%(STUB)s' '.%(EXT)s'
return template % { 'APP' : self . application , 'VERSION' : self . version , 'LOCALE' : self . locale , 'PLATFORM' : self . platform , 'STUB' : '-stub' if self . is_stub_installer else '' , 'EXT' : self . extension } |
def gen_etree ( self ) :
"""convert an RST tree ( DGParentedTree - > lxml etree )""" | relations_elem = self . gen_relations ( )
header = E ( 'header' )
header . append ( relations_elem )
self . gen_body ( )
tree = E ( 'rst' )
tree . append ( header )
# The < body > contains both < segment > , as well as < group > elements .
# While the order of the elements should theoretically be irrelevant ,
# rs3 fil... |
def _run_seq ( self , size ) :
"""Send the contents of self [ ' SEQ ' ] to the chip and wait until it finishes .""" | # Write the sequence to the sequence generator ( hw driver )
self [ 'SEQ' ] . write ( size )
# write pattern to memory
self [ 'SEQ' ] . set_size ( size )
# set size
self [ 'SEQ' ] . set_repeat ( 1 )
# set repeat
for _ in range ( 1 ) :
self [ 'SEQ' ] . start ( )
# start
while not self [ 'SEQ' ] . get_done ( ... |
def participants ( self ) :
"""Access the participants
: returns : twilio . rest . api . v2010 . account . conference . participant . ParticipantList
: rtype : twilio . rest . api . v2010 . account . conference . participant . ParticipantList""" | if self . _participants is None :
self . _participants = ParticipantList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , conference_sid = self . _solution [ 'sid' ] , )
return self . _participants |
def target_power ( self ) :
"""Setting this to ` True ` will activate the power pins ( 4 and 6 ) . If
set to ` False ` the power will be deactivated .
Raises an : exc : ` IOError ` if the hardware adapter does not support
the switchable power pins .""" | ret = api . py_aa_target_power ( self . handle , TARGET_POWER_QUERY )
_raise_error_if_negative ( ret )
return ret |
def __select_nearest_ws ( jsondata , latitude , longitude ) :
"""Select the nearest weatherstation .""" | log . debug ( "__select_nearest_ws: latitude: %s, longitude: %s" , latitude , longitude )
dist = 0
dist2 = 0
loc_data = None
try :
ws_json = jsondata [ __ACTUAL ]
ws_json = ws_json [ __STATIONMEASUREMENTS ]
except ( KeyError , TypeError ) :
log . warning ( "Missing section in Buienradar xmldata (%s)." "Can ... |
def _model ( self , beta ) :
"""Creates the structure of the model
Parameters
beta : np . array
Contains untransformed starting values for latent variables
Returns
lambda : np . array
Contains the values for the conditional volatility series
Y : np . array
Contains the length - adjusted time series ... | Y = np . array ( self . data [ self . max_lag : self . data . shape [ 0 ] ] )
X = np . ones ( Y . shape [ 0 ] )
scores = np . zeros ( Y . shape [ 0 ] )
# Transform latent variables
parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] )
l... |
def has_ndarray_int_columns ( features , X ) :
"""Checks if numeric feature columns exist in ndarray""" | _ , ncols = X . shape
if not all ( d . isdigit ( ) for d in features if isinstance ( d , str ) ) or not isinstance ( X , np . ndarray ) :
return False
ndarray_columns = np . arange ( 0 , ncols )
feature_cols = np . unique ( [ int ( d ) for d in features ] )
return all ( np . in1d ( feature_cols , ndarray_columns ) ... |
def strings_equal ( s1 , s2 ) :
"""Timing - attack resistant string comparison .
Normal comparison using = = will short - circuit on the first mismatching
character . This avoids that by scanning the whole string , though we
still reveal to a timing attack whether the strings are the same
length .""" | try :
s1 = unicodedata . normalize ( 'NFKC' , str ( s1 ) )
s2 = unicodedata . normalize ( 'NFKC' , str ( s2 ) )
except :
s1 = unicodedata . normalize ( 'NFKC' , unicode ( s1 ) )
s2 = unicodedata . normalize ( 'NFKC' , unicode ( s2 ) )
return compare_digest ( s1 , s2 ) |
def notify ( self , force_notify = None , use_email = None , use_sms = None , ** kwargs ) :
"""Overridden to only call ` notify ` if model matches .""" | notified = False
instance = kwargs . get ( "instance" )
if instance . _meta . label_lower == self . model :
notified = super ( ) . notify ( force_notify = force_notify , use_email = use_email , use_sms = use_sms , ** kwargs , )
return notified |
def _process_pod_rate ( self , metric_name , metric , scraper_config ) :
"""Takes a simple metric about a pod , reports it as a rate .
If several series are found for a given pod , values are summed before submission .""" | if metric . type not in METRIC_TYPES :
self . log . error ( "Metric type %s unsupported for metric %s" % ( metric . type , metric . name ) )
return
samples = self . _sum_values_by_context ( metric , self . _get_pod_uid_if_pod_metric )
for pod_uid , sample in iteritems ( samples ) :
if '.network.' in metric_... |
def unregister_layout ( self , name ) :
"""Unregisters given layout .
: param name : Layout name .
: type name : unicode
: param layout : Layout object .
: type layout : Layout
: return : Method success .
: rtype : bool""" | if not name in self :
raise umbra . exceptions . LayoutRegistrationError ( "{0} | '{1}' layout is not registered!" . format ( self . __class__ . __name__ , name ) )
del ( self . __layouts [ name ] )
return True |
def run_loop ( self ) :
"""Main entry point for running in interactive mode .""" | self . root_command . prog = ''
history_file = self . load_history ( )
rendering . vtmlprint ( self . intro )
try :
self . loop ( )
finally :
readline . write_history_file ( history_file ) |
def GetEnabledInterfaces ( ) :
"""Gives a list of enabled interfaces . Should work on all windows versions .
Returns :
interfaces : Names of interfaces found enabled .""" | interfaces = [ ]
show_args = [ '/c' , 'netsh' , 'show' , 'interface' ]
# pylint : disable = undefined - variable
res = client_utils_common . Execute ( 'cmd' , show_args , time_limit = - 1 , bypass_whitelist = True )
pattern = re . compile ( r'\s*' )
for line in res [ 0 ] . split ( '\r\n' ) : # res [ 0 ] is stdout .
... |
def rnd_date_list_high_performance ( size , start = date ( 1970 , 1 , 1 ) , end = None , ** kwargs ) :
"""Generate mass random date .
: param size : int , number of
: param start : date similar object , int / str / date / datetime
: param end : date similar object , int / str / date / datetime , default today... | if end is None :
end = date . today ( )
start_days = to_ordinal ( parser . parse_datetime ( start ) )
end_days = to_ordinal ( parser . parse_datetime ( end ) )
_assert_correct_start_end ( start_days , end_days )
if has_np : # pragma : no cover
return [ from_ordinal ( days ) for days in np . random . randint ( s... |
def data_from_query ( self , cmd ) :
"""Callback for . execute _ command ( ) for DELETE / GET / HEAD requests""" | res = None
ckey = "%s /%s" % ( self . command , cmd )
if not isinstance ( self . _query_params , dict ) :
self . _query_params = { }
if ckey in _NCMD :
self . _cmd = _NCMD [ ckey ]
else :
for key in sorted ( _RCMD , key = len , reverse = True ) :
if not key . startswith ( "%s " % self . command ) :
... |
def require_dataset ( self , name , shape , dtype = None , exact = False , ** kwargs ) :
"""Obtain an array , creating if it doesn ' t exist . Other ` kwargs ` are
as per : func : ` zarr . hierarchy . Group . create _ dataset ` .
Parameters
name : string
Array name .
shape : int or tuple of ints
Array s... | return self . _write_op ( self . _require_dataset_nosync , name , shape = shape , dtype = dtype , exact = exact , ** kwargs ) |
def convert_to_string ( self , block ) :
"""Makes gene _ block as str from list of SeqRecordExpanded objects of a gene _ code .
Override this function if the dataset block needs to be different
due to file format .
This block will need to be split further if the dataset is FASTA or
TNT and the partitioning ... | if self . partitioning != '1st-2nd, 3rd' :
return self . make_datablock_by_gene ( block )
else :
if self . format == 'FASTA' :
return self . make_datablock_considering_codon_positions_as_fasta_format ( block )
else :
return self . make_datablock_by_gene ( block ) |
def plot_ratio_return ( self , isox , isoy , deltax = True , deltay = True ) :
'''This routine returns data isotopic data to plot from the
filtered list of data .
Parameters
isox : list
Isotopes for x axis in standard format [ ' Si - 28 ' , ' Si - 30 ' ] .
isoy : list
Same as isox but for y axis .
del... | # check availability
index_x , delta_b_x , ratio_b_x = self . check_availability ( isox )
index_y , delta_b_y , ratio_b_y = self . check_availability ( isoy )
if index_x == - 1 or index_y == - 1 :
print ( 'Following input data are not available in the database. Revise your input.' )
if index_x == - 1 :
... |
def is_Type ( tp ) :
"""Python version independent check if an object is a type .
For Python 3.7 onwards ( ? ) this is not equivalent to
` ` isinstance ( tp , type ) ` ` any more , as that call would return
` ` False ` ` for PEP 484 types .
Tested with CPython 2.7 , 3.5 , 3.6 , 3.7 and Jython 2.7.1.""" | if isinstance ( tp , type ) :
return True
try :
typing . _type_check ( tp , '' )
return True
except TypeError :
return False |
def keyPressEvent ( self , event ) :
"""Listens for the escape key to cancel out from this snapshot .
: param event | < QKeyPressEvent >""" | # reject on a cancel
if event . key ( ) == Qt . Key_Escape :
self . reject ( )
super ( XSnapshotWidget , self ) . keyPressEvent ( event ) |
def make_header ( self ) :
"""Builds and returns FITS header for this HEALPix map""" | cards = [ fits . Card ( "TELESCOP" , "GLAST" ) , fits . Card ( "INSTRUME" , "LAT" ) , fits . Card ( self . _conv . coordsys , self . _coordsys ) , fits . Card ( "PIXTYPE" , "HEALPIX" ) , fits . Card ( "ORDERING" , self . ordering ) , fits . Card ( "ORDER" , self . _order ) , fits . Card ( "NSIDE" , self . _nside ) , fi... |
def build_indexes ( connection , verbose = False ) :
"""Using the how _ to _ index annotations in the table class definitions ,
construct a set of indexes for the database at the given
connection .""" | cursor = connection . cursor ( )
for table_name in get_table_names ( connection ) : # FIXME : figure out how to do this extensibly
if table_name in TableByName :
how_to_index = TableByName [ table_name ] . how_to_index
elif table_name in lsctables . TableByName :
how_to_index = lsctables . Table... |
def decode_privkey_hex ( privkey_hex ) :
"""Decode a private key for ecdsa signature""" | if not isinstance ( privkey_hex , ( str , unicode ) ) :
raise ValueError ( "private key is not a string" )
# force uncompressed
priv = str ( privkey_hex )
if len ( priv ) > 64 :
if priv [ - 2 : ] != '01' :
raise ValueError ( "private key does not end in '01'" )
priv = priv [ : 64 ]
pk_i = int ( priv... |
def secondary_structure_summary ( dssp_df ) :
"""Summarize the secondary structure content of the DSSP dataframe for each chain .
Args :
dssp _ df : Pandas DataFrame of parsed DSSP results
Returns :
dict : Chain to secondary structure summary dictionary""" | chains = dssp_df . chain . unique ( )
infodict = { }
for chain in chains :
expoinfo = defaultdict ( int )
chain_df = dssp_df [ dssp_df . chain == chain ]
counts = chain_df . ss . value_counts ( )
total = float ( len ( chain_df ) )
for ss , count in iteritems ( counts ) :
if ss == '-' :
... |
def make_line ( self , response = None , importance = None , base = None , tag = None , features = None , namespaces = None , ) :
"""Makes and returns an example string in VW syntax .
If given , ' response ' , ' importance ' , ' base ' , and ' tag ' are used
to label the example . Features for the example come ... | if namespaces is not None :
self . add_namespaces ( namespaces )
if features is not None :
namespace = Namespace ( features = features )
self . add_namespace ( namespace )
substrings = [ ]
tokens = [ ]
if response is not None :
token = str ( response )
tokens . append ( token )
if importance is ... |
def _pad_bytes ( request_bytes ) :
""": type request _ bytes : bytes
: rtype : bytes""" | padding_length = ( _BLOCK_SIZE - len ( request_bytes ) % _BLOCK_SIZE )
padding_character = bytes ( bytearray ( [ padding_length ] ) )
return request_bytes + padding_character * padding_length |
def raise_check_result ( self ) :
"""Raise ACTIVE CHECK RESULT entry
Example : " ACTIVE HOST CHECK : server ; DOWN ; HARD ; 1 ; I don ' t know what to say . . . "
: return : None""" | if not self . __class__ . log_active_checks :
return
log_level = 'info'
if self . state == 'DOWN' :
log_level = 'error'
elif self . state == 'UNREACHABLE' :
log_level = 'warning'
brok = make_monitoring_log ( log_level , 'ACTIVE HOST CHECK: %s;%s;%d;%s' % ( self . get_name ( ) , self . state , self . attempt... |
def derive_fields ( self ) :
"""Derives our fields .""" | if self . fields is not None :
fields = list ( self . fields )
else :
form = self . form
fields = [ ]
for field in form :
fields . append ( field . name )
# this is slightly confusing but we add in readonly fields here because they will still
# need to be displayed
readonly = self . ... |
def text_search ( self , query = None , language = lang . ENGLISH , lat_lng = None , radius = 3200 , type = None , types = [ ] , location = None , pagetoken = None ) :
"""Perform a text search using the Google Places API .
Only the one of the query or pagetoken kwargs are required , the rest of the
keyword argu... | self . _request_params = { 'query' : query }
if lat_lng is not None or location is not None :
lat_lng_str = self . _generate_lat_lng_string ( lat_lng , location )
self . _request_params [ 'location' ] = lat_lng_str
self . _request_params [ 'radius' ] = radius
if type :
self . _request_params [ 'type' ] = ty... |
def get_dataset ( self , key , info ) :
"""Read data from file and return the corresponding projectables .""" | if key . name in [ 'longitude' , 'latitude' ] :
logger . debug ( 'Reading coordinate arrays.' )
if self . lons is None or self . lats is None :
self . lons , self . lats = self . get_lonlats ( )
if key . name == 'latitude' :
proj = Dataset ( self . lats , id = key , ** info )
else :
... |
def func ( self ) :
"""func : func name ( paramlist ) block""" | self . eat ( TokenTypes . FUNC )
name = Var ( self . cur_token )
self . eat ( TokenTypes . VAR )
self . eat ( TokenTypes . LPAREN )
sig = self . param_list ( )
self . eat ( TokenTypes . RPAREN )
block = self . block ( )
return FunctionDef ( name , Function ( sig , block ) ) |
def who_has ( self , subid ) :
"""Return a list of names who own subid in their id range set .""" | answer = [ ]
for name in self . __map :
if subid in self . __map [ name ] and not name in answer :
answer . append ( name )
return answer |
def current_version ( ) :
"""Get current version of directory - components .""" | filepath = os . path . abspath ( project_root / "directory_components" / "version.py" )
version_py = get_file_string ( filepath )
regex = re . compile ( Utils . get_version )
if regex . search ( version_py ) is not None :
current_version = regex . search ( version_py ) . group ( 0 )
print ( color ( "Current dir... |
def cmd ( self , args = None , interact = True ) :
"""Process command - line arguments .""" | if args is None :
parsed_args = arguments . parse_args ( )
else :
parsed_args = arguments . parse_args ( args )
self . exit_code = 0
with self . handling_exceptions ( ) :
self . use_args ( parsed_args , interact , original_args = args )
self . exit_on_error ( ) |
def get_entity ( self , etype , entity_id ) :
"""Return entity in this workspace .
Args :
etype ( str ) : Entity type
entity _ id ( str ) : Entity name / unique id""" | r = fapi . get_entity ( self . namespace , self . name , etype , entity_id , self . api_url )
fapi . _check_response_code ( r , 200 )
dresp = r . json ( )
return Entity ( etype , entity_id , dresp [ 'attributes' ] ) |
def RegisterArtifact ( self , artifact_rdfvalue , source = "datastore" , overwrite_if_exists = False , overwrite_system_artifacts = False ) :
"""Registers a new artifact .""" | artifact_name = artifact_rdfvalue . name
if artifact_name in self . _artifacts :
if not overwrite_if_exists :
details = "artifact already exists and `overwrite_if_exists` is unset"
raise rdf_artifacts . ArtifactDefinitionError ( artifact_name , details )
elif not overwrite_system_artifacts :
... |
def has_name_version ( self , name : str , version : str ) -> bool :
"""Check if there exists a network with the name / version combination in the database .""" | return self . session . query ( exists ( ) . where ( and_ ( Network . name == name , Network . version == version ) ) ) . scalar ( ) |
def create_user_id ( self , user_id , app_id , cidr_block = None , mount_point = 'app-id' , ** kwargs ) :
"""POST / auth / < mount point > / map / user - id / < user _ id >
: param user _ id :
: type user _ id :
: param app _ id :
: type app _ id :
: param cidr _ block :
: type cidr _ block :
: param ... | # user - id can be associated to more than 1 app - id ( aka policy ) . It is easier for the user to
# pass in the policies as a list so if they do , we need to convert to a , delimited string .
if isinstance ( app_id , ( list , set , tuple ) ) :
app_id = ',' . join ( app_id )
params = { 'value' : app_id }
# Only us... |
def put_file ( self , key , file ) :
"""Store into key from file on disk
Stores data from a source into key . * file * can either be a string ,
which will be interpretet as a filename , or an object with a * read ( ) *
method .
If the passed object has a * fileno ( ) * method , it may be used to speed
up ... | # FIXME : shouldn ' t we call self . _ check _ valid _ key here ?
if isinstance ( file , str ) :
return self . _put_filename ( key , file )
else :
return self . _put_file ( key , file ) |
def to_array ( self ) :
"""Serializes this AnimationMessage to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( AnimationMessage , self ) . to_array ( )
if isinstance ( self . animation , InputFile ) :
array [ 'animation' ] = self . animation . to_array ( )
# type InputFile
elif isinstance ( self . animation , str ) :
array [ 'animation' ] = u ( self . animation )
# py2 : type unicode , py3 : type... |
def compress ( self , image_path ) :
'''compress will ( properly ) compress an image''' | if os . path . exists ( image_path ) :
compressed_image = "%s.gz" % image_path
os . system ( 'gzip -c -6 %s > %s' % ( image_path , compressed_image ) )
return compressed_image
bot . exit ( "Cannot find image %s" % image_path ) |
def _populate_validated_data_with_sub_field_data ( self , validated_data ) :
"""Move field data nested in ` ModelSubSerializer ` fields back into the
overall validated data dict .""" | for fieldname , field in self . get_fields ( ) . items ( ) :
if isinstance ( field , ModelSubSerializer ) :
field_data = validated_data . pop ( fieldname , None )
if field_data :
validated_data . update ( field_data ) |
def calc_finished ( self ) :
'''Check if the lockfile is in the calculation directory .
It is removed by the script at the end regardless of the
success of the calculation . This is totally tied to
implementation and you need to implement your own scheme !''' | # print _ stack ( limit = 5)
if not self . calc_running : # print ( ' Calc running : ' , self . calc _ running )
return True
else : # The calc is marked as running check if this is still true
# We do it by external scripts . You need to write these
# scripts for your own system .
# See examples / scripts directory ... |
def load_yaml_file ( yaml_file ) :
"""Read YAML file .""" | try :
import yaml
except ImportError :
sys . exit ( "Unable to import yaml module." )
try :
with io . open ( yaml_file , "rt" , encoding = "utf-8" ) as fname :
return yaml . safe_load ( fname )
except IOError :
sys . exit ( "Unable to open YAML file: {0}" . format ( yaml_file ) ) |
def get_next_del_state ( self , state , ret ) :
"""Return the next delete state from previous state .""" | if ret :
if state == fw_const . INIT_STATE :
return state
else :
return state - 1
else :
return state |
def _is_aborted ( self , cycle , statustext , total_elements = None , freq = None ) :
"""Displays progress and returns True if abort
Parameters
cycle : Integer
\t The current operation cycle
statustext : String
\t Left text in statusbar to be displayed
total _ elements : Integer :
\t The number of ele... | if total_elements is None :
statustext += _ ( "{nele} elements processed. Press <Esc> to abort." )
else :
statustext += _ ( "{nele} of {totalele} elements processed. " "Press <Esc> to abort." )
if freq is None :
show_msg = False
freq = 1000
else :
show_msg = True
# Show progress in statusbar each fr... |
def make_typecast ( type_ , node , lineno ) :
"""Wrapper : returns a Typecast node""" | assert isinstance ( type_ , symbols . TYPE )
return symbols . TYPECAST . make_node ( type_ , node , lineno ) |
def load ( self ) :
"""read dotfile and populate self
opts will override the dotfile settings ,
make sure everything is synced in both
opts and this object""" | if self . exists ( ) :
with open ( self . dot_file , 'r' ) as handle :
self . update ( json . load ( handle ) )
if self . options [ 'context' ] is not None :
self [ 'context' ] = self . options [ 'context' ]
else :
self . options [ 'context' ] = self [ 'context' ]
if self . options [ 'defaults' ] is... |
def command ( self , command = None , timestamp = None , element = None , host = None , service = None , user = None , parameters = None ) : # pylint : disable = too - many - branches
"""Request to execute an external command
Allowed parameters are :
` command ` : mandatory parameter containing the whole comman... | if cherrypy . request . method in [ "POST" ] :
if not cherrypy . request . json :
return { '_status' : u'ERR' , '_message' : u'You must POST parameters on this endpoint.' }
if command is None :
try :
command = cherrypy . request . json . get ( 'command' , None )
timestamp = cherrypy . re... |
def get_info ( self ) :
"""Get current configuration info from ' v ' command .""" | re_info = re . compile ( r'\[.*\]' )
self . _write_cmd ( 'v' )
while True :
line = self . _serial . readline ( )
try :
line = line . encode ( ) . decode ( 'utf-8' )
except AttributeError :
line = line . decode ( 'utf-8' )
match = re_info . match ( line )
if match :
return sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.