signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _network_show ( self , name , network_lst ) :
'''Parse the returned network list''' | for net in network_lst :
if net . label == name :
return net . __dict__
return { } |
def action_verb ( self ) :
"""The host portion of the ` ppaction : / / ` URL contained in the action
attribute . For example ' customshow ' in
' ppaction : / / customshow ? id = 0 & return = true ' . Returns | None | if no action
attribute is present .""" | url = self . action
if url is None :
return None
protocol_and_host = url . split ( '?' ) [ 0 ]
host = protocol_and_host [ 11 : ]
return host |
def fetch ( self ) :
"""Fetch the data for the model from Redis and assign the values .
: param method callback : The callback method to invoke when done""" | LOGGER . debug ( 'Fetching session data: %s' , self . id )
result = yield gen . Task ( RedisSession . _redis_client . get , self . _key )
if result :
self . loads ( result )
raise gen . Return ( True )
else :
raise gen . Return ( False ) |
def get_gold_labels ( self , cand_lists , annotator = None ) :
"""Load sparse matrix of GoldLabels for each candidate _ class .
: param cand _ lists : The candidates to get gold labels for .
: type cand _ lists : List of list of candidates .
: param annotator : A specific annotator key to get labels for . Def... | return get_sparse_matrix ( self . session , GoldLabelKey , cand_lists , key = annotator ) |
def process_result ( self , new_sia , min_sia ) :
"""Check if the new SIA has smaller | big _ phi | than the standing
result .""" | if new_sia . phi == 0 :
self . done = True
# Short - circuit
return new_sia
elif new_sia < min_sia :
return new_sia
return min_sia |
def inference_tip ( infer_function , raise_on_overwrite = False ) :
"""Given an instance specific inference function , return a function to be
given to MANAGER . register _ transform to set this inference function .
: param bool raise _ on _ overwrite : Raise an ` InferenceOverwriteError `
if the inference ti... | def transform ( node , infer_function = infer_function ) :
if ( raise_on_overwrite and node . _explicit_inference is not None and node . _explicit_inference is not infer_function ) :
raise InferenceOverwriteError ( "Inference already set to {existing_inference}. " "Trying to overwrite with {new_inference} f... |
def get_ui ( self , _ ) :
"""Load the Swagger UI interface""" | if not self . _ui_cache :
content = self . load_static ( 'ui.html' )
if isinstance ( content , binary_type ) :
content = content . decode ( 'UTF-8' )
self . _ui_cache = content . replace ( u"{{SWAGGER_PATH}}" , str ( self . swagger_path ) )
return HttpResponse ( self . _ui_cache , headers = { 'Conte... |
def authenticate ( self , verify = True ) :
"""Creates an authenticated and internal oauth2 handler needed for queries to Twitter and verifies credentials if needed . If ` ` verify ` ` is true , it also checks if the user credentials are valid . The * * default * * value is * True *
: param verify : boolean varia... | self . __oauth = OAuth1 ( self . __consumer_key , client_secret = self . __consumer_secret , resource_owner_key = self . __access_token , resource_owner_secret = self . __access_token_secret )
if verify :
r = requests . get ( self . _base_url + self . _verify_url , auth = self . __oauth , proxies = { "https" : self... |
def _get_conn ( ret ) :
'''Return a mongodb connection object''' | _options = _get_options ( ret )
host = _options . get ( 'host' )
port = _options . get ( 'port' )
uri = _options . get ( 'uri' )
db_ = _options . get ( 'db' )
user = _options . get ( 'user' )
password = _options . get ( 'password' )
indexes = _options . get ( 'indexes' , False )
# at some point we should remove support... |
def expand_array ( data , scans , c_align , c_exp , scan_size = 16 , tpz_size = 16 , nties = 200 , track_offset = 0.5 , scan_offset = 0.5 ) :
"""Expand * data * according to alignment and expansion .""" | nties = np . asscalar ( nties )
tpz_size = np . asscalar ( tpz_size )
s_scan , s_track = da . meshgrid ( np . arange ( nties * tpz_size ) , np . arange ( scans * scan_size ) )
s_track = ( s_track . reshape ( scans , scan_size , nties , tpz_size ) % scan_size + track_offset ) / scan_size
s_scan = ( s_scan . reshape ( sc... |
def cardinal_groupby ( self ) :
"""Group this object on it cardinal dimension ( _ cardinal ) .
Returns :
grpby : Pandas groupby object ( grouped on _ cardinal )""" | g , t = self . _cardinal
self [ g ] = self [ g ] . astype ( t )
grpby = self . groupby ( g )
self [ g ] = self [ g ] . astype ( 'category' )
return grpby |
def build_not_found ( cls , errors = None ) :
"""Utility method to build a HTTP 404 Resource Error response""" | errors = [ errors ] if not isinstance ( errors , list ) else errors
return cls ( Status . NOT_FOUND , errors ) |
def load ( cls , file_path ) :
"""Load the object from a JSON file ( saved with : py : func : ` Concise . save ` ) .
Returns :
Concise : Loaded Concise object .""" | # convert back to numpy
data = helper . read_json ( file_path )
return Concise . from_dict ( data ) |
def create ( vm_ = None , call = None ) :
'''Create a single VM from a data dict''' | if call :
raise SaltCloudSystemExit ( 'You cannot create an instance with -a or -f.' )
try : # Check for required profile parameters before sending any API calls .
if vm_ [ 'profile' ] and config . is_profile_configured ( __opts__ , __active_provider_name__ or 'ec2' , vm_ [ 'profile' ] , vm_ = vm_ ) is False :
... |
def _is_really_comment ( tokens , index ) :
"""Return true if the token at index is really a comment .""" | if tokens [ index ] . type == TokenType . Comment :
return True
# Really a comment in disguise !
try :
if tokens [ index ] . content . lstrip ( ) [ 0 ] == "#" :
return True
except IndexError :
return False |
def get_string ( self , distance = 6 , velocity = 8 , charge = 3 ) :
"""Returns the string representation of LammpsData , essentially
the string to be written to a file .
Args :
distance ( int ) : No . of significant figures to output for
box settings ( bounds and tilt ) and atomic coordinates .
Default t... | file_template = """Generated by pymatgen.io.lammps.data.LammpsData
{stats}
{box}
{body}
"""
box = self . box . get_string ( distance )
body_dict = OrderedDict ( )
body_dict [ "Masses" ] = self . masses
types = OrderedDict ( )
types [ "atom" ] = len ( self . masses )
if self . force_field :
all_ff_kws = SECTION_K... |
def get_all ( self ) :
"""Gets all component references registered in this reference map .
: return : a list with component references .""" | components = [ ]
self . _lock . acquire ( )
try :
for reference in self . _references :
components . append ( reference . get_component ( ) )
finally :
self . _lock . release ( )
return components |
def created ( self ) :
"""Union [ datetime . datetime , None ] : Datetime at which the model was
created ( : data : ` None ` until set from the server ) .
Read - only .""" | value = self . _proto . creation_time
if value is not None and value != 0 : # value will be in milliseconds .
return google . cloud . _helpers . _datetime_from_microseconds ( 1000.0 * float ( value ) ) |
def packets_to_flows ( self ) :
"""Combine packets into flows""" | # For each packet , place it into either an existing flow or a new flow
for packet in self . input_stream : # Compute flow tuple and add the packet to the flow
flow_id = flow_utils . flow_tuple ( packet )
self . _flows [ flow_id ] . add_packet ( packet )
# Yield flows that are ready to go
for flow in li... |
def start_worker ( self ) :
"""start _ worker
Start the helper worker process to package queued messages
and send them to Splunk""" | # Start a worker thread responsible for sending logs
if not self . is_shutting_down ( shutdown_event = self . shutdown_event ) and self . sleep_interval > 0.1 :
self . processes = [ ]
self . debug_log ( 'start_worker - start multiprocessing.Process' )
p = multiprocessing . Process ( target = self . perform_... |
def get_spectre_plot ( self , sigma = 0.05 , step = 0.01 ) :
"""Get a matplotlib plot of the UV - visible xas . Transition are plotted
as vertical lines and as a sum of normal functions with sigma with . The
broadening is applied in energy and the xas is plotted as a function
of the wavelength .
Args :
si... | from pymatgen . util . plotting import pretty_plot
from matplotlib . mlab import normpdf
plt = pretty_plot ( 12 , 8 )
transitions = self . read_excitation_energies ( )
minval = min ( [ val [ 0 ] for val in transitions ] ) - 5.0 * sigma
maxval = max ( [ val [ 0 ] for val in transitions ] ) + 5.0 * sigma
npts = int ( ( m... |
def get_phonon_frequencies ( self ) :
"""calculate phonon frequencies""" | # TODO : the following is most likely not correct or suboptimal
# hence for demonstration purposes only
frequencies = [ ]
for k , v0 in self . data . iteritems ( ) :
for v1 in v0 . itervalues ( ) :
vec = map ( abs , v1 [ 'dynmat' ] [ k - 1 ] )
frequency = math . sqrt ( sum ( vec ) ) * 2. * math . pi... |
def on_message ( self , message ) :
"""Listens for a " websocket client ready " message .
Once that message is received an asynchronous job
is stated that yields messages to the client .
These messages make up salt ' s
" real time " event stream .""" | log . debug ( 'Got websocket message %s' , message )
if message == 'websocket client ready' :
if self . connected : # TBD : Add ability to run commands in this branch
log . debug ( 'Websocket already connected, returning' )
return
self . connected = True
while True :
try :
... |
def assignValue ( cfg , playerValue , otherValue ) :
"""artificially determine match results given match circumstances .
WARNING : cheating will be detected and your player will be banned from server""" | player = cfg . whoAmI ( )
result = { }
for p in cfg . players :
if p . name == player . name :
val = playerValue
else :
val = otherValue
result [ p . name ] = val
return result |
def verify_embedding ( emb , source , target , ignore_errors = ( ) ) :
"""A simple ( exception - raising ) diagnostic for minor embeddings .
See : func : ` diagnose _ embedding ` for a more detailed diagnostic / more information .
Args :
emb ( dict ) : a dictionary mapping source nodes to arrays of target nod... | for error in diagnose_embedding ( emb , source , target ) :
eclass = error [ 0 ]
if eclass not in ignore_errors :
raise eclass ( * error [ 1 : ] )
return True |
def hbp_namespace ( name : str , sha : Optional [ str ] = None ) -> str :
"""Format a namespace URL .""" | return HBP_NAMESPACE_URL . format ( sha = sha or LAST_HASH , keyword = name ) |
def SetCredentials ( self , password = None , username = None ) :
"""Sets the database credentials .
Args :
password ( Optional [ str ] ) : password to access the database .
username ( Optional [ str ] ) : username to access the database .""" | if password :
self . _password = password
if username :
self . _user = username |
def cast_number_strings_to_integers ( d ) :
"""d is a dict""" | for k , v in d . items ( ) : # print type ( v )
if determine_if_str_or_unicode ( v ) :
if v . isdigit ( ) :
d [ k ] = int ( v )
return d |
def _setup_storage_dir ( self ) :
"""Setup the storage directory path value and ensure the path exists .
: rtype : str
: raises : tinman . exceptions . ConfigurationException""" | dir_path = self . _settings . get ( config . DIRECTORY )
if dir_path is None :
dir_path = self . _default_path
if not os . path . exists ( dir_path ) :
self . _make_path ( dir_path )
else :
dir_path = path . abspath ( dir_path )
if not os . path . exists ( dir_path ) or not os . path . isdir ( d... |
def fidx ( right , left , left_fk = None ) :
"""Re - indexes a series or data frame ( right ) to align with
another ( left ) series or data frame via foreign key relationship .
The index of the right must be unique .
This is similar to misc . reindex , but allows for data frame
re - indexes and supports re ... | # ensure that we can align correctly
if not right . index . is_unique :
raise ValueError ( "The right's index must be unique!" )
# simpler case :
# if the left ( target ) is a single series then just re - index to it
if isinstance ( left_fk , str ) :
left = left [ left_fk ]
if isinstance ( left , pd . Series ) ... |
def calc_detection_voc_prec_rec ( gt_boxlists , pred_boxlists , iou_thresh = 0.5 ) : """Calculate precision and recall based on evaluation code of PASCAL VOC .
This function calculates precision and recall of
predicted bounding boxes obtained from a dataset which has : math : ` N `
images .
The code is based on... | n_pos = defaultdict ( int )
score = defaultdict ( list )
match = defaultdict ( list )
for gt_boxlist , pred_boxlist in zip ( gt_boxlists , pred_boxlists ) : pred_bbox = pred_boxlist . bbox . numpy ( )
pred_label = pred_boxlist . get_field ( "labels" ) . numpy ( )
pred_score = pred_boxlist . get_field ( "scores" ) . num... |
def available_backends ( self , hub = None , group = None , project = None , access_token = None , user_id = None ) :
"""Get the backends available to use in the QX Platform""" | if access_token :
self . req . credential . set_token ( access_token )
if user_id :
self . req . credential . set_user_id ( user_id )
if not self . check_credentials ( ) :
raise CredentialsError ( 'credentials invalid' )
else :
url = get_backend_url ( self . config , hub , group , project )
ret = se... |
def put ( self , item , block = True , timeout = None , chill = True ) :
"""Put an item into the queue .
If optional args ' block ' is true and ' timeout ' is None ( the default ) ,
block if necessary until a free slot is available . If ' timeout ' is
a non - negative number , it blocks at most ' timeout ' se... | with self . not_full :
if self . maxsize > 0 :
if not block :
if self . _qsize ( ) >= self . maxsize :
raise compat . queue . Full
elif timeout is None :
while self . _qsize ( ) >= self . maxsize :
self . not_full . wait ( )
elif timeou... |
def _calc_q_statistic ( x , h , nt ) :
"""Calculate Portmanteau statistics up to a lag of h .""" | t , m , n = x . shape
# covariance matrix of x
c0 = acm ( x , 0 )
# LU factorization of covariance matrix
c0f = sp . linalg . lu_factor ( c0 , overwrite_a = False , check_finite = True )
q = np . zeros ( ( 3 , h + 1 ) )
for l in range ( 1 , h + 1 ) :
cl = acm ( x , l )
# calculate tr ( cl ' * c0 ^ - 1 * cl * c0... |
def _setup_fun_config ( self , fun_conf ) :
'''Setup function configuration .
: param conf :
: return :''' | conf = copy . deepcopy ( self . config )
conf [ 'file_client' ] = 'local'
conf [ 'fun' ] = ''
conf [ 'arg' ] = [ ]
conf [ 'kwarg' ] = { }
conf [ 'cache_jobs' ] = False
conf [ 'print_metadata' ] = False
conf . update ( fun_conf )
conf [ 'fun' ] = conf [ 'fun' ] . split ( ':' ) [ - 1 ]
# Discard typing prefix
return conf |
def get_parameter ( self , name , default = None ) :
'''Returns the named parameter if present , or the value of ` default ` ,
otherwise .''' | if hasattr ( self , name ) :
item = getattr ( self , name )
if isinstance ( item , Parameter ) :
return item
return default |
def show_homecoming ( request ) :
"""Show homecoming ribbon / scores""" | return { 'show_homecoming' : settings . HOCO_START_DATE < datetime . date . today ( ) and datetime . date . today ( ) < settings . HOCO_END_DATE } |
def QA_util_to_json_from_pandas ( data ) :
"""需要对于datetime 和date 进行转换 , 以免直接被变成了时间戳""" | if 'datetime' in data . columns :
data . datetime = data . datetime . apply ( str )
if 'date' in data . columns :
data . date = data . date . apply ( str )
return json . loads ( data . to_json ( orient = 'records' ) ) |
def _clean_annotations ( annotations_dict : AnnotationsHint ) -> AnnotationsDict :
"""Fix the formatting of annotation dict .""" | return { key : ( values if isinstance ( values , dict ) else { v : True for v in values } if isinstance ( values , set ) else { values : True } ) for key , values in annotations_dict . items ( ) } |
def get_canonical_names ( packages ) :
"""Canonicalize a list of packages and return a set of canonical names""" | from . vendor . packaging . utils import canonicalize_name
if not isinstance ( packages , Sequence ) :
if not isinstance ( packages , six . string_types ) :
return packages
packages = [ packages ]
return set ( [ canonicalize_name ( pkg ) for pkg in packages if pkg ] ) |
def is_open ( location = None , attr = None ) :
"""Returns False if the location is closed , or the OpeningHours object
to show the location is currently open .""" | obj = utils . is_open ( location )
if obj is False :
return False
if attr is not None :
return getattr ( obj , attr )
return obj |
def save ( self ) :
"""Generate a random username before falling back to parent signup form""" | while True :
username = sha1 ( str ( random . random ( ) ) . encode ( 'utf-8' ) ) . hexdigest ( ) [ : 5 ]
try :
get_user_model ( ) . objects . get ( username__iexact = username )
except get_user_model ( ) . DoesNotExist :
break
self . cleaned_data [ 'username' ] = username
return super ( Sig... |
def name ( cls , func ) :
"""Return auto generated file name .""" | cls . count = cls . count + 1
fpath = '{}_{}{}' . format ( cls . count , func . __name__ , cls . suffix )
if cls . directory :
fpath = os . path . join ( cls . directory , fpath )
return fpath |
def cprint ( text , color = None , on_color = None , attrs = None , ** kwargs ) :
"""Print colorize text .
It accepts arguments of print function .""" | try :
print ( ( colored ( text , color , on_color , attrs ) ) , ** kwargs )
except TypeError : # flush is not supported by py2.7
kwargs . pop ( "flush" , None )
print ( ( colored ( text , color , on_color , attrs ) ) , ** kwargs ) |
def set_burst ( self , freq , amplitude , period , output_state = True ) :
"""Sets the func generator to burst mode with external trigerring .""" | ncyc = int ( period * freq )
commands = [ 'FUNC SIN' , 'BURS:STAT ON' , 'BURS:MODE TRIG' , # external trigger
'TRIG:SOUR EXT' , 'TRIG:SLOP POS' , 'FREQ {0}' . format ( freq ) , 'VOLT {0}' . format ( amplitude ) , 'VOLT:OFFS 0' , 'BURS:NCYC {0}' . format ( ncyc ) ]
if output_state is True :
commands . append ( 'OUTP... |
def get_multiple_data ( ) :
"""Get data from all the platforms listed in makerlabs .""" | # Get data from all the mapped platforms
all_labs = { }
all_labs [ "diybio_org" ] = diybio_org . get_labs ( format = "dict" )
all_labs [ "fablabs_io" ] = fablabs_io . get_labs ( format = "dict" )
all_labs [ "makeinitaly_foundation" ] = makeinitaly_foundation . get_labs ( format = "dict" )
all_labs [ "hackaday_io" ] = h... |
def _get_satellite_tile ( self , x_tile , y_tile , z_tile ) :
"""Load up a single satellite image tile .""" | cache_file = "mapscache/{}.{}.{}.jpg" . format ( z_tile , x_tile , y_tile )
if cache_file not in self . _tiles :
if not os . path . isfile ( cache_file ) :
url = _IMAGE_URL . format ( z_tile , x_tile , y_tile , _KEY )
data = requests . get ( url ) . content
with open ( cache_file , 'wb' ) as... |
def split_command_line ( command_line ) :
'''This splits a command line into a list of arguments . It splits arguments
on spaces , but handles embedded quotes , doublequotes , and escaped
characters . It ' s impossible to do this with a regular expression , so I
wrote a little state machine to parse the comma... | arg_list = [ ]
arg = ''
# Constants to name the states we can be in .
state_basic = 0
state_esc = 1
state_singlequote = 2
state_doublequote = 3
# The state when consuming whitespace between commands .
state_whitespace = 4
state = state_basic
for c in command_line :
if state == state_basic or state == state_whitespa... |
def user_recent ( self ) :
'''User used recently .''' | kwd = { 'pager' : '' , 'title' : '' }
self . render ( 'user/info_list/user_recent.html' , kwd = kwd , user_name = self . get_current_user ( ) , userinfo = self . userinfo ) |
def rpc_get_zonefile_inventory ( self , offset , length , ** con_info ) :
"""Get an inventory bit vector for the zonefiles in the
given bit range ( i . e . offset and length are in bytes )
Returns at most 64k of inventory ( or 524288 bits )
Return { ' status ' : True , ' inv ' : . . . } on success , where ' i... | conf = get_blockstack_opts ( )
if not is_atlas_enabled ( conf ) :
return { 'error' : 'Not an atlas node' , 'http_status' : 400 }
if not check_offset ( offset ) :
return { 'error' : 'invalid offset' , 'http_status' : 400 }
if not check_count ( length , 524288 ) :
return { 'error' : 'invalid length' , 'http_s... |
def path ( self ) :
'''return relative path of tile image''' | ( x , y ) = self . tile
return os . path . join ( '%u' % self . zoom , '%u' % y , '%u.img' % x ) |
def r2_score ( y_true , y_pred ) :
"""R2 for Bayesian regression models . Only valid for linear models .
Parameters
y _ true : : array - like of shape = ( n _ samples ) or ( n _ samples , n _ outputs )
Ground truth ( correct ) target values .
y _ pred : array - like of shape = ( n _ samples ) or ( n _ sampl... | if y_pred . ndim == 1 :
var_y_est = np . var ( y_pred )
var_e = np . var ( y_true - y_pred )
else :
var_y_est = np . var ( y_pred . mean ( 0 ) )
var_e = np . var ( y_true - y_pred , 0 )
r_squared = var_y_est / ( var_y_est + var_e )
return pd . Series ( [ np . mean ( r_squared ) , np . std ( r_squared ) ... |
def _future_completed ( future ) :
"""Helper for run _ in _ executor ( )""" | exc = future . exception ( )
if exc :
log . debug ( "Failed to run task on executor" , exc_info = exc ) |
def is_safe_to_wait ( lock_expiration : BlockExpiration , reveal_timeout : BlockTimeout , block_number : BlockNumber , ) -> SuccessOrError :
"""True if waiting is safe , i . e . there are more than enough blocks to safely
unlock on chain .""" | # reveal timeout will not ever be larger than the lock _ expiration otherwise
# the expected block _ number is negative
assert block_number > 0
assert reveal_timeout > 0
assert lock_expiration > reveal_timeout
lock_timeout = lock_expiration - block_number
# A node may wait for a new balance proof while there are reveal... |
def start_output ( self ) :
"""Write start of checking info .""" | super ( HtmlLogger , self ) . start_output ( )
header = { "encoding" : self . get_charset_encoding ( ) , "title" : configuration . App , "body" : self . colorbackground , "link" : self . colorlink , "vlink" : self . colorlink , "alink" : self . colorlink , "url" : self . colorurl , "error" : self . colorerror , "valid"... |
def pull ( directory : str ) -> Commit :
"""Pulls the subrepo that has been cloned into the given directory .
: param directory : the directory containing the subrepo
: return : the commit the subrepo is on""" | if not os . path . exists ( directory ) :
raise ValueError ( f"No subrepo found in \"{directory}\"" )
try :
result = run ( [ GIT_COMMAND , _GIT_SUBREPO_COMMAND , _GIT_SUBREPO_PULL_COMMAND , _GIT_SUBREPO_VERBOSE_FLAG , get_directory_relative_to_git_root ( directory ) ] , execution_directory = get_git_root_direct... |
def default_type_resolver ( value : Any , info : GraphQLResolveInfo , abstract_type : GraphQLAbstractType ) -> AwaitableOrValue [ Optional [ Union [ GraphQLObjectType , str ] ] ] :
"""Default type resolver function .
If a resolve _ type function is not given , then a default resolve behavior is used
which attem... | # First , look for ` _ _ typename ` .
type_name = ( value . get ( "__typename" ) if isinstance ( value , dict ) # need to de - mangle the attribute assumed to be " private " in Python
else getattr ( value , f"_{value.__class__.__name__}__typename" , None ) )
if isinstance ( type_name , str ) :
return type_name
# Ot... |
def CleanName ( name ) :
"""Perform generic name cleaning .""" | name = re . sub ( '[^_A-Za-z0-9]' , '_' , name )
if name [ 0 ] . isdigit ( ) :
name = '_%s' % name
while keyword . iskeyword ( name ) :
name = '%s_' % name
# If we end up with _ _ as a prefix , we ' ll run afoul of python
# field renaming , so we manually correct for it .
if name . startswith ( '__' ) :
nam... |
def reparentClassLike ( self ) :
'''Helper method for : func : ` ~ exhale . graph . ExhaleRoot . reparentAll ` . Iterates over the
` ` self . class _ like ` ` list and adds each object as a child to a namespace if the
class , or struct is a member of that namespace . Many classes / structs will be
reparented ... | removals = [ ]
for cl in self . class_like :
parts = cl . name . split ( "::" )
if len ( parts ) > 1 :
parent_name = "::" . join ( parts [ : - 1 ] )
for parent_cl in self . class_like :
if parent_cl . name == parent_name :
parent_cl . children . append ( cl )
... |
def plot_shapes ( df_shapes , shape_i_columns , axis = None , autoxlim = True , autoylim = True , ** kwargs ) :
'''Plot shapes from table / data - frame where each row corresponds to a vertex of
a shape . Shape vertices are grouped by ` shape _ i _ columns ` .
For example , consider the following dataframe :
... | if axis is None :
fig , axis = plt . subplots ( )
props = itertools . cycle ( mpl . rcParams [ 'axes.prop_cycle' ] )
color = kwargs . pop ( 'fc' , None )
# Cycle through default colors to set face color , unless face color was set
# explicitly .
patches = [ Polygon ( df_shape_i [ [ 'x' , 'y' ] ] . values , fc = pro... |
def __sender ( self ) :
"""Send - loop .""" | # If we ' re ignoring the quit , the connections will have to be closed
# by the server .
while ( self . __ignore_quit is True or self . __nice_quit_ev . is_set ( ) is False ) and self . __force_quit_ev . is_set ( ) is False : # TODO ( dustin ) : The quit - signals aren ' t being properly set after a producer
# stop .
... |
def setupuv ( rc ) :
"""Horn Schunck legacy OpenCV function requires we use these old - fashioned cv matrices , not numpy array""" | if cv is not None :
( r , c ) = rc
u = cv . CreateMat ( r , c , cv . CV_32FC1 )
v = cv . CreateMat ( r , c , cv . CV_32FC1 )
return ( u , v )
else :
return [ None ] * 2 |
def specify_data_set ( self , x_input , y_input , sort_data = False ) :
"""Fully define data by lists of x values and y values .
This will sort them by increasing x but remember how to unsort them for providing results .
Parameters
x _ input : iterable
list of floats that represent x
y _ input : iterable ... | if sort_data :
xy = sorted ( zip ( x_input , y_input ) )
x , y = zip ( * xy )
x_input_list = list ( x_input )
self . _original_index_of_xvalue = [ x_input_list . index ( xi ) for xi in x ]
if len ( set ( self . _original_index_of_xvalue ) ) != len ( x ) :
raise RuntimeError ( 'There are some... |
def get_slope_and_intercept_from_pdcm ( dcmdata ) :
"""Get scale and intercept from pydicom file object .
: param dcmdata :
: return :""" | if hasattr ( dcmdata , "RescaleSlope" ) and hasattr ( dcmdata , "RescaleIntercept" ) :
rescale_slope = dcmdata . RescaleSlope
rescale_intercept = dcmdata . RescaleIntercept
slope , inter = get_slope_and_intercept_from_strings ( rescale_slope , rescale_intercept )
else :
slope = 1
inter = 0
return sl... |
def group_multiecho ( bold_sess ) :
"""Multiplexes multi - echo EPIs into arrays . Dual - echo is a special
case of multi - echo , which is treated as single - echo data .
> > > bold _ sess = [ " sub - 01 _ task - rest _ echo - 1 _ run - 01 _ bold . nii . gz " ,
. . . " sub - 01 _ task - rest _ echo - 2 _ run... | from itertools import groupby
def _grp_echos ( x ) :
if '_echo-' not in x :
return x
echo = re . search ( "_echo-\\d*" , x ) . group ( 0 )
return x . replace ( echo , "_echo-?" )
ses_uids = [ ]
for _ , bold in groupby ( bold_sess , key = _grp_echos ) :
bold = list ( bold )
# If single - or d... |
def filtered ( self , efilter ) :
'''Applies a filter to the search''' | if not self . params :
self . params = { 'filter' : efilter }
return self
if not self . params . has_key ( 'filter' ) :
self . params [ 'filter' ] = efilter
return self
self . params [ 'filter' ] . update ( efilter )
return self |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : QueueContext for this QueueInstance
: rtype : twilio . rest . api . v2010 . account . queue . QueueContext""" | if self . _context is None :
self . _context = QueueContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def _get_baseline_from_tag ( config , tag ) :
'''Returns the last created baseline snapshot marked with ` tag `''' | last_snapshot = None
for snapshot in __salt__ [ 'snapper.list_snapshots' ] ( config ) :
if tag == snapshot [ 'userdata' ] . get ( "baseline_tag" ) :
if not last_snapshot or last_snapshot [ 'timestamp' ] < snapshot [ 'timestamp' ] :
last_snapshot = snapshot
return last_snapshot |
def df ( unit = 'GB' ) :
'''A wrapper for the df shell command .''' | details = { }
headers = [ 'Filesystem' , 'Type' , 'Size' , 'Used' , 'Available' , 'Capacity' , 'MountedOn' ]
n = len ( headers )
unit = df_conversions [ unit ]
p = subprocess . Popen ( args = [ 'df' , '-TP' ] , stdout = subprocess . PIPE )
# - P prevents line wrapping on long filesystem names
stdout , stderr = p . comm... |
def _mount_overlay ( self , identifier ) :
"""OverlayFS mount backend .""" | cid = self . _identifier_as_cid ( identifier )
cinfo = self . client . inspect_container ( cid )
ld , ud , wd = '' , '' , ''
try :
ld = cinfo [ 'GraphDriver' ] [ 'Data' ] [ 'lowerDir' ]
ud = cinfo [ 'GraphDriver' ] [ 'Data' ] [ 'upperDir' ]
wd = cinfo [ 'GraphDriver' ] [ 'Data' ] [ 'workDir' ]
except :
... |
def makeinit ( mod_dpath , exclude_modnames = [ ] , use_star = False ) :
r"""Args :
mod _ dpath ( str ) :
exclude _ modnames ( list ) : ( Defaults to [ ] )
use _ star ( bool ) : ( Defaults to False )
Returns :
str : init _ codeblock
CommandLine :
python - m utool . util _ autogen makeinit - - modname ... | from utool . _internal import util_importer
import utool as ut
module_name = ut . get_modname_from_modpath ( mod_dpath )
IMPORT_TUPLES = util_importer . make_import_tuples ( mod_dpath , exclude_modnames = exclude_modnames )
initstr = util_importer . make_initstr ( module_name , IMPORT_TUPLES )
regen_command = 'cd %s\n'... |
def _pop_letters ( char_list ) :
"""Pop consecutive letters from the front of a list and return them
Pops any and all consecutive letters from the start of the provided
character list and returns them as a list of characters . Operates
on ( and possibly alters ) the passed list
: param list char _ list : a ... | logger . debug ( '_pop_letters(%s)' , char_list )
letters = [ ]
while len ( char_list ) != 0 and char_list [ 0 ] . isalpha ( ) :
letters . append ( char_list . pop ( 0 ) )
logger . debug ( 'got letters: %s' , letters )
logger . debug ( 'updated char list: %s' , char_list )
return letters |
def compute_time_at_sun_angle ( day , latitude , angle ) :
"""Compute the floating point time difference between mid - day and an angle .
All the prayers are defined as certain angles from mid - day ( Zuhr ) .
This formula is taken from praytimes . org / calculation
: param day : The day to which to compute f... | positive_angle_rad = radians ( abs ( angle ) )
angle_sign = abs ( angle ) / angle
latitude_rad = radians ( latitude )
declination = radians ( sun_declination ( day ) )
numerator = - sin ( positive_angle_rad ) - sin ( latitude_rad ) * sin ( declination )
denominator = cos ( latitude_rad ) * cos ( declination )
time_diff... |
def start ( cls , callback , provider = 'gps' , min_time = 1000 , min_distance = 0 ) :
"""Convenience method that checks and requests permission if necessary
and if successful calls the callback with a populated ` Location `
instance on updates .
Note you must have the permissions in your manifest or requests... | app = AndroidApplication . instance ( )
f = app . create_future ( )
def on_success ( lm ) : # : When we have finally have permission
lm . onLocationChanged . connect ( callback )
# : Save a reference to our listener
# : because we may want to stop updates
listener = LocationManager . LocationListener ( ... |
def version ( ) :
"""Wrapper for opj _ version library routine .""" | OPENJPEG . opj_version . restype = ctypes . c_char_p
library_version = OPENJPEG . opj_version ( )
if sys . hexversion >= 0x03000000 :
return library_version . decode ( 'utf-8' )
else :
return library_version |
def _needs_ref_WCS ( reglist ) :
"""Check if the region list contains shapes in image - like coordinates""" | from pyregion . wcs_helper import image_like_coordformats
for r in reglist :
if r . coord_format in image_like_coordformats :
return True
return False |
def shot_save ( self , ) :
"""Save the current shot
: returns : None
: rtype : None
: raises : None""" | if not self . cur_shot :
return
desc = self . shot_desc_pte . toPlainText ( )
start = self . shot_start_sb . value ( )
end = self . shot_end_sb . value ( )
handle = self . shot_handle_sb . value ( )
self . cur_shot . description = desc
self . cur_shot . startframe = start
self . cur_shot . endframe = end
self . cur... |
def set_logger_dir ( dirname , action = None ) :
"""Set the directory for global logging .
Args :
dirname ( str ) : log directory
action ( str ) : an action of [ " k " , " d " , " q " ] to be performed
when the directory exists . Will ask user by default .
" d " : delete the directory . Note that the dele... | global LOG_DIR , _FILE_HANDLER
if _FILE_HANDLER : # unload and close the old file handler , so that we may safely delete the logger directory
_logger . removeHandler ( _FILE_HANDLER )
del _FILE_HANDLER
def dir_nonempty ( dirname ) : # If directory exists and nonempty ( ignore hidden files ) , prompt for action
... |
def to_volume ( self ) :
"""Return a 3D volume of the data""" | if hasattr ( self . header . definitions , "Lattice" ) :
X , Y , Z = self . header . definitions . Lattice
else :
raise ValueError ( "Unable to determine data size" )
volume = self . decoded_data . reshape ( Z , Y , X )
return volume |
def _read_object ( self , path ) :
'''read in object from file at ` path `''' | if not os . path . exists ( path ) :
return None
if os . path . isdir ( path ) :
raise RuntimeError ( '%s is a directory, not a file.' % path )
with open ( path ) as f :
file_contents = f . read ( )
return file_contents |
def dumps ( data , ac_parser = None , ** options ) :
"""Return string representation of ' data ' in forced type format .
: param data : Config data object to dump
: param ac _ parser : Forced parser type or ID or parser object
: param options : see : func : ` dump `
: return : Backend - specific string repr... | psr = find ( None , forced_type = ac_parser )
return psr . dumps ( data , ** options ) |
def agent_service_maintenance ( consul_url = None , token = None , serviceid = None , ** kwargs ) :
'''Used to place a service into maintenance mode .
: param consul _ url : The Consul server URL .
: param serviceid : A name of the service .
: param enable : Whether the service should be enabled or disabled .... | ret = { }
query_params = { }
if not consul_url :
consul_url = _get_config ( )
if not consul_url :
log . error ( 'No Consul URL found.' )
ret [ 'message' ] = 'No Consul URL found.'
ret [ 'res' ] = False
return ret
if not serviceid :
raise SaltInvocationError ( 'Required argume... |
def get_instance ( self , payload ) :
"""Build an instance of StyleSheetInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . autopilot . v1 . assistant . style _ sheet . StyleSheetInstance
: rtype : twilio . rest . autopilot . v1 . assistant . style _ sheet . StyleSheetIns... | return StyleSheetInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , ) |
def write ( self , attr_name , prefix = None ) :
'''Write attribute ' s value to a file .
: param str attr _ name :
Attribute ' s name to be logged
: param str prefix :
Optional . Attribute ' s name that is prefixed to logging message ,
defaults to ` ` None ` ` .
: returns : message written to file
: ... | if self . _folder is None :
return
separator = "\t"
attr = getattr ( self . obj , attr_name )
if hasattr ( attr , '__iter__' ) :
msg = separator . join ( [ str ( e ) for e in attr ] )
else :
msg = str ( attr )
if prefix is not None :
msg = "{}\t{}" . format ( getattr ( self . obj , prefix ) , msg )
path... |
def write_extra_resources ( self , compile_context ) :
"""Override write _ extra _ resources to produce plugin and annotation processor files .""" | target = compile_context . target
if isinstance ( target , ScalacPlugin ) :
self . _write_scalac_plugin_info ( compile_context . classes_dir . path , target )
elif isinstance ( target , JavacPlugin ) :
self . _write_javac_plugin_info ( compile_context . classes_dir . path , target )
elif isinstance ( target , A... |
def second_phase ( invec , indices , N1 , N2 ) :
"""This is the second phase of the FFT decomposition that actually performs
the pruning . It is an explicit calculation for the subset of points . Note
that there seem to be some numerical accumulation issues at various values
of N1 and N2.
Parameters
invec... | invec = numpy . array ( invec . data , copy = False )
NI = len ( indices )
# pylint : disable = unused - variable
N1 = int ( N1 )
N2 = int ( N2 )
out = numpy . zeros ( len ( indices ) , dtype = numpy . complex64 )
code = """
float pi = 3.14159265359;
for(int i=0; i<NI; i++){
std::complex<dou... |
def set_params ( self , ** params ) :
"""Set the parameters of this estimator .
Returns
self""" | valid_params = self . get_params ( )
for key , value in params . items ( ) :
if key not in valid_params :
raise ValueError ( "Invalid parameter %s for estimator %s. " "Check the list of available parameters " "with `estimator.get_params().keys()`." % ( key , self . __class__ . __name__ ) )
setattr ( sel... |
def _fontsize ( self , key , label = 'fontsize' , common = True ) :
"""Converts integer fontsizes to a string specifying
fontsize in pt .""" | size = super ( BokehPlot , self ) . _fontsize ( key , label , common )
return { k : v if isinstance ( v , basestring ) else '%spt' % v for k , v in size . items ( ) } |
def sync_remote_to_local ( force = "no" ) :
"""Replace your remote db with your local
Example :
sync _ remote _ to _ local : force = yes""" | assert "local_wp_dir" in env , "Missing local_wp_dir in env"
if force != "yes" :
message = "This will replace your local database with your " "remote, are you sure [y/n]"
answer = prompt ( message , "y" )
if answer != "y" :
logger . info ( "Sync stopped" )
return
init_tasks ( )
# Bootstrap f... |
def mock ( self , tst_name , tst_type ) :
"""Mock appearance / disappearance to force changes in interface , via setting local cache .
: param tst _ name :
: param tst _ type :
: return :""" | print ( " -> Mock {tst_name} appear" . format ( ** locals ( ) ) )
# Service appears
self . available [ tst_name ] = tst_type
yield
# Service disappear
self . available . pop ( tst_name )
print ( " -> Mock {tst_name} disappear" . format ( ** locals ( ) ) ) |
def total_msg_sent ( self ) :
"""Returns total number of UPDATE , NOTIFICATION and ROUTE _ REFRESH
message sent to this peer .""" | return ( self . get_count ( PeerCounterNames . SENT_REFRESH ) + self . get_count ( PeerCounterNames . SENT_UPDATES ) ) |
def set_word_at_rva ( self , rva , word ) :
"""Set the word value at the file offset corresponding to the given RVA .""" | return self . set_bytes_at_rva ( rva , self . get_data_from_word ( word ) ) |
def _extract_traceback ( start ) :
"""SNAGGED FROM traceback . py
RETURN list OF dicts DESCRIBING THE STACK TRACE""" | tb = sys . exc_info ( ) [ 2 ]
for i in range ( start ) :
tb = tb . tb_next
return _parse_traceback ( tb ) |
def run ( self , service_id , ** kwargs ) :
"""Retrieve a status from remote service . Set the up / down state and log .""" | log = self . get_logger ( ** kwargs )
log . info ( "Loading Service for healthcheck" )
try :
service = Service . objects . get ( id = service_id )
log . info ( "Getting health for <%s>" % ( service . name ) )
status = self . get_health ( service . url , service . token )
try :
result = status . ... |
def calc_results ( request , calc_id ) :
"""Get a summarized list of calculation results for a given ` ` calc _ id ` ` .
Result is a JSON array of objects containing the following attributes :
* id
* name
* type ( hazard _ curve , hazard _ map , etc . )
* url ( the exact url where the full result can be a... | # If the specified calculation doesn ' t exist OR is not yet complete ,
# throw back a 404.
try :
info = logs . dbcmd ( 'calc_info' , calc_id )
if not utils . user_has_permission ( request , info [ 'user_name' ] ) :
return HttpResponseForbidden ( )
except dbapi . NotFound :
return HttpResponseNotFou... |
def sin_3 ( a = 1 ) :
r"""Fourier sine transform pair sin _ 3 ( [ Ande75 ] _ ) .""" | def lhs ( x ) :
return x / ( a ** 2 + x ** 2 )
def rhs ( b ) :
return np . pi * np . exp ( - a * b ) / 2
return Ghosh ( 'sin' , lhs , rhs ) |
def parse ( self , line , namespace = None ) :
"""Parses a line into a dictionary of arguments , expanding meta - variables from a namespace .""" | try :
if namespace is None :
ipy = IPython . get_ipython ( )
namespace = ipy . user_ns
args = CommandParser . create_args ( line , namespace )
return self . parse_args ( args )
except Exception as e :
print ( str ( e ) )
return None |
def get_proficiency_admin_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the proficiency administration service .
: param proxy : a proxy
: type proxy : ` ` osid . proxy . Proxy ` `
: return : a ` ` ProficiencyAdminSession ` `
: rtype : ` ` osid . learning . ProficiencyAdminSessi... | if not self . supports_proficiency_admin ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . ProficiencyAdminSession ( proxy = proxy , runtime = self . _runtime )
except AttributeErro... |
def insert ( self , index , column , default_value = '' , values = None , compute_value_func = None , compute_key = None ) :
"""This will insert a new column at index and then set the value
unless compute _ value is provided
: param index : int index of where to insert the column
: param column : str of the n... | for row in self . table :
value = values . pop ( 0 ) if values else default_value
if compute_value_func is not None :
value = compute_value_func ( row if compute_key is None else row [ compute_key ] )
if index is None :
row . append ( value )
else :
row . insert ( index , value )... |
def from_attrs ( cls , desired_attrs = None , except_attrs = None , critical_attrs = None ) :
"""Get a generator of mechanisms supporting the specified attributes . See
RFC 5587 ' s : func : ` indicate _ mechs _ by _ attrs ` for more information .
Args :
desired _ attrs ( [ OID ] ) : Desired attributes
exce... | if isinstance ( desired_attrs , roids . OID ) :
desired_attrs = set ( [ desired_attrs ] )
if isinstance ( except_attrs , roids . OID ) :
except_attrs = set ( [ except_attrs ] )
if isinstance ( critical_attrs , roids . OID ) :
critical_attrs = set ( [ critical_attrs ] )
if rfc5587 is None :
raise NotImpl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.