signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _threaded_callback ( callback , * args ) :
"""Internal wrapper to start a callback in threaded mode . Using the
daemon mode to not block the main thread from exiting .""" | t = Thread ( target = callback , args = args )
t . daemon = True
t . start ( ) |
def generate_filename ( self , requirement ) :
"""Generate a distribution archive filename for a package .
: param requirement : A : class : ` . Requirement ` object .
: returns : The filename of the distribution archive ( a string )
including a single leading directory component to indicate
the cache forma... | return FILENAME_PATTERN % ( self . config . cache_format_revision , requirement . name , requirement . version , get_python_version ( ) ) |
def protect ( allow_browser_login = False ) :
"""Use this decorator to enable granular security permissions
to your API methods ( BaseApi and child classes ) .
Permissions will be associated to a role , and roles are associated to users .
allow _ browser _ login will accept signed cookies obtained from the no... | def _protect ( f ) :
if hasattr ( f , '_permission_name' ) :
permission_str = f . _permission_name
else :
permission_str = f . __name__
def wraps ( self , * args , ** kwargs ) :
permission_str = "{}{}" . format ( PERMISSION_PREFIX , f . _permission_name )
class_permission_nam... |
def get_db_prep_value ( self , value , connection , prepared = False ) :
"""Prepare a value for DB interaction .
Returns :
- list ( bytes ) if not prepared
- list ( str ) if prepared""" | if prepared :
return value
if value is None :
return [ ]
values = value if self . multi_valued_field else [ value ]
prepared_values = [ self . get_prep_value ( v ) for v in values ]
# Remove duplicates .
# https : / / tools . ietf . org / html / rfc4511 # section - 4.1.7 :
# " The set of attribute values is uno... |
def enough_input ( layer , post_processor_input ) :
"""Check if the input from impact _ fields in enough .
: param layer : The vector layer to use for post processing .
: type layer : QgsVectorLayer
: param post _ processor _ input : Collection of post processor input
requirements .
: type post _ processo... | impact_fields = list ( layer . keywords [ 'inasafe_fields' ] . keys ( ) )
for input_key , input_values in list ( post_processor_input . items ( ) ) :
input_values = ( input_values if isinstance ( input_values , list ) else [ input_values ] )
msg = None
for input_value in input_values :
is_constant_i... |
def _g_1 ( self ) :
"""omega1 < omega < omega2""" | # return 3 * self . _ n _ 1 ( ) / ( self . _ omega - self . _ vertices _ omegas [ 0 ] )
return ( 3 * self . _f ( 1 , 0 ) * self . _f ( 2 , 0 ) / ( self . _vertices_omegas [ 3 ] - self . _vertices_omegas [ 0 ] ) ) |
def _get_title ( self , directory , filename ) :
"""Loads image title if any""" | # = = = = = LOAD TITLE = = = = =
fullfile = os . path . join ( directory , filename + '.title' )
try :
logger . debug ( 'trying to open [%s]' % ( fullfile ) )
_title = ( open ( fullfile ) . readline ( ) . strip ( ) )
logger . debug ( "_updatemeta: %s - title is '%s'" , filename , _title )
except :
_titl... |
def _create_json ( self ) :
"""JSON Documentation : https : / / www . jfrog . com / confluence / display / RTF / Security + Configuration + JSON""" | data_json = { 'name' : self . name , 'email' : self . email , 'password' : self . password , 'admin' : self . admin , "profileUpdatable" : self . profileUpdatable , "internalPasswordDisabled" : self . internalPasswordDisabled , "groups" : self . _groups , }
return data_json |
def create ( self , using = None , ** kwargs ) :
"""Creates the index in elasticsearch .
Any additional keyword arguments will be passed to
` ` Elasticsearch . indices . create ` ` unchanged .""" | self . _get_connection ( using ) . indices . create ( index = self . _name , body = self . to_dict ( ) , ** kwargs ) |
def get_column ( self , X , column ) :
"""Return a column of the given matrix .
Args :
X : ` numpy . ndarray ` or ` pandas . DataFrame ` .
column : ` int ` or ` str ` .
Returns :
np . ndarray : Selected column .""" | if isinstance ( X , pd . DataFrame ) :
return X [ column ] . values
return X [ : , column ] |
def aliases_categories ( chr ) :
"""Retrieves the script block alias and unicode category for a unicode character .
> > > categories . aliases _ categories ( ' A ' )
( ' LATIN ' , ' L ' )
> > > categories . aliases _ categories ( ' τ ' )
( ' GREEK ' , ' L ' )
> > > categories . aliases _ categories ( ' - ... | l = 0
r = len ( categories_data [ 'code_points_ranges' ] ) - 1
c = ord ( chr )
# binary search
while r >= l :
m = ( l + r ) // 2
if c < categories_data [ 'code_points_ranges' ] [ m ] [ 0 ] :
r = m - 1
elif c > categories_data [ 'code_points_ranges' ] [ m ] [ 1 ] :
l = m + 1
else :
... |
def _parse_query_key ( self , key , val , is_escaped ) :
"""Strips query modifier from key and call ' s the appropriate value modifier .
Args :
key ( str ) : Query key
val : Query value
Returns :
Parsed query key and value .""" | if key . endswith ( '__contains' ) :
key = key [ : - 10 ]
val = self . _parse_query_modifier ( 'contains' , val , is_escaped )
elif key . endswith ( '__range' ) :
key = key [ : - 7 ]
val = self . _parse_query_modifier ( 'range' , val , is_escaped )
elif key . endswith ( '__startswith' ) :
key = key ... |
def to_triple ( self , ast_obj = None , fmt = "medium" ) :
"""Convert AST object to BEL triple
Args :
fmt ( str ) : short , medium , long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format... | if not ast_obj :
ast_obj = self
if self . bel_subject and self . bel_relation and self . bel_object :
if self . bel_relation . startswith ( "has" ) :
bel_relation = self . bel_relation
elif fmt == "short" :
bel_relation = self . spec [ "relations" ] [ "to_short" ] . get ( self . bel_relation... |
def get_killer ( args ) :
"""Returns a KillerBase instance subclassed based on the OS .""" | if POSIX :
log . debug ( 'Platform: POSIX' )
from killer . killer_posix import KillerPosix
return KillerPosix ( config_path = args . config , debug = args . debug )
elif WINDOWS :
log . debug ( 'Platform: Windows' )
from killer . killer_windows import KillerWindows
return KillerWindows ( config_... |
def OnInit ( self ) :
"""Initialize by creating the split window with the tree""" | project = compass . CompassProjectParser ( sys . argv [ 1 ] ) . parse ( )
frame = MyFrame ( None , - 1 , 'wxCompass' , project )
frame . Show ( True )
self . SetTopWindow ( frame )
return True |
def GetDatabaseAccount ( self , url_connection = None ) :
"""Gets database account info .
: return :
The Database Account .
: rtype :
documents . DatabaseAccount""" | if url_connection is None :
url_connection = self . url_connection
initial_headers = dict ( self . default_headers )
headers = base . GetHeaders ( self , initial_headers , 'get' , '' , # path
'' , # id
'' , # type
{ } )
request = request_object . _RequestObject ( 'databaseaccount' , documents . _OperationType . Rea... |
def p_genvardecl ( self , p ) :
'genvardecl : GENVAR genvarlist SEMICOLON' | p [ 0 ] = Decl ( p [ 2 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def reduce_activities ( self ) :
"""Rewrite the activity types referenced in Statements for consistency .
Activity types are reduced to the most specific form whenever possible .
For instance , if ' kinase ' is the only specific activity type known
for the BaseAgent of BRAF , its generic ' activity ' forms ar... | for stmt in self . statements :
agents = stmt . agent_list ( )
for agent in agents :
if agent is not None and agent . activity is not None :
agent_base = self . _get_base ( agent )
act_red = agent_base . get_activity_reduction ( agent . activity . activity_type )
if a... |
def get_courses_metadata ( self ) :
"""Gets the metadata for the courses .
return : ( osid . Metadata ) - metadata for the courses
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . learning . ActivityForm . get _ assets _ metadata _ template
metadata = dict ( self . _mdata [ 'courses' ] )
metadata . update ( { 'existing_courses_values' : self . _my_map [ 'courseIds' ] } )
return Metadata ( ** metadata ) |
def create ( self , create_missing = None ) :
"""Manually fetch a complete set of attributes for this entity .
For more information , see ` Bugzilla # 1449749
< https : / / bugzilla . redhat . com / show _ bug . cgi ? id = 1449749 > ` _ .""" | return Host ( self . _server_config , id = self . create_json ( create_missing ) [ 'id' ] , ) . read ( ) |
def _mark_target ( type , item ) :
"""Wrap given item as input or output target that should be added to task .
Wrapper object will be handled specially in : paramref : ` create _ cmd _ task . parts ` .
: param type : Target type .
Allowed values :
- ' input '
- ' output '
: param item : Item to mark as ... | # If given type is not valid
if type not in ( 'input' , 'output' ) : # Get error message
msg = 'Error (7D74X): Type is not valid: {0}' . format ( type )
# Raise error
raise ValueError ( msg )
# If given type is valid .
# Store given item
orig_item = item
# If given path is list
if isinstance ( item , list )... |
def _readline_echo ( self , char , echo ) :
"""Echo a recieved character , move cursor etc . . .""" | if self . _readline_do_echo ( echo ) :
self . write ( char ) |
def stop ( args ) :
"""% prog stop
Stop EC2 instance .""" | p = OptionParser ( stop . __doc__ )
p . add_option ( "--profile" , default = "mvrad-datasci-role" , help = "Profile name" )
opts , args = p . parse_args ( args )
if len ( args ) != 0 :
sys . exit ( not p . print_help ( ) )
role ( [ "htang" ] )
session = boto3 . Session ( profile_name = opts . profile )
client = ses... |
def filename_for_track ( track ) :
""": return : A safe filename for the given track""" | artist = track . user [ 'permalink' ]
title = track . title
return '{}-{}.mp3' . format ( artist , title ) . lower ( ) . replace ( ' ' , '_' ) . replace ( '/' , '_' ) |
def get_m2m_popup_field ( cls , * args , ** kwargs ) :
"""generate m2m field related to class wait popup crud""" | kwargs [ 'popup_name' ] = cls . get_class_verbose_name ( )
kwargs [ 'permissions_required' ] = cls . permissions_required
if cls . template_name_m2m is not None :
kwargs [ 'template_name' ] = cls . template_name_m2m
return ManyToManyWidget ( '{}_popup_create' . format ( cls . get_class_name ( ) ) , * args , ** kwar... |
def database ( self , name = None ) :
"""Connect to a database called ` name ` .
Parameters
name : str , optional
The name of the database to connect to . If ` ` None ` ` , return
the database named ` ` self . current _ database ` ` .
Returns
db : MySQLDatabase
An : class : ` ibis . sql . mysql . clie... | if name == self . current_database or ( name is None and name != self . current_database ) :
return self . database_class ( self . current_database , self )
else :
url = self . con . url
client_class = type ( self )
new_client = client_class ( host = url . host , user = url . username , port = url . por... |
def logout ( self , subject ) :
"""Logs out the specified Subject from the system .
Note that most application developers should not call this method unless
they have a good reason for doing so . The preferred way to logout a
Subject is to call ` ` Subject . logout ( ) ` ` , not by calling ` ` SecurityManager... | if ( subject is None ) :
msg = "Subject argument cannot be None."
raise ValueError ( msg )
self . before_logout ( subject )
identifiers = copy . copy ( subject . identifiers )
# copy is new to yosai
if ( identifiers ) :
msg = ( "Logging out subject with primary identifier {0}" . format ( identifiers . prima... |
def _mprotate ( ang , lny , pool , order ) :
"""Uses multiprocessing to wrap around _ rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores .
The function calls _ rotate which accesses the ` mprotate _ dict ` .
Data is rotated in - place .
Parameters
ang : float
rotation angle in degrees
ln... | targ_args = list ( )
slsize = np . int ( np . floor ( lny / ncores ) )
for t in range ( ncores ) :
ymin = t * slsize
ymax = ( t + 1 ) * slsize
if t == ncores - 1 :
ymax = lny
targ_args . append ( ( ymin , ymax , ang , order ) )
pool . map ( _rotate , targ_args ) |
def remove_private_obfuscation ( self ) :
"""removes the python obfuscation of class privates so they can be executed as
they appear in class source . Useful when playing with IPython .""" | classname = self . __class__ . __name__
attrlist = [ attr for attr in dir ( self ) if attr . startswith ( '_' + classname + '__' ) ]
for attr in attrlist :
method = getattr ( self , attr )
truename = attr . replace ( '_' + classname + '__' , '__' )
setattr ( self , truename , method ) |
def before_save ( file_or_dir ) :
"""make sure that the dedicated path exists ( create if not exist )
: param file _ or _ dir :
: return : None""" | dir_name = os . path . dirname ( os . path . abspath ( file_or_dir ) )
if not os . path . exists ( dir_name ) :
os . makedirs ( dir_name ) |
def load ( self ) :
"""Extract tabular data as | TableData | instances from a MediaWiki file .
| load _ source _ desc _ file |
: return :
Loaded table data iterator .
| load _ table _ name _ desc |
Format specifier Value after the replacement
` ` % ( filename ) s ` ` | filename _ desc |
` ` % ( key ) ... | self . _validate ( )
self . _logger . logging_load ( )
self . encoding = get_file_encoding ( self . source , self . encoding )
with io . open ( self . source , "r" , encoding = self . encoding ) as fp :
formatter = MediaWikiTableFormatter ( fp . read ( ) )
formatter . accept ( self )
return formatter . to_table_dat... |
def GetStopsInBoundingBox ( self , north , east , south , west , n ) :
"""Return a sample of up to n stops in a bounding box""" | stop_list = [ ]
for s in self . stops . values ( ) :
if ( s . stop_lat <= north and s . stop_lat >= south and s . stop_lon <= east and s . stop_lon >= west ) :
stop_list . append ( s )
if len ( stop_list ) == n :
break
return stop_list |
def estimate_hessian ( objective_func , parameters , lower_bounds = None , upper_bounds = None , step_ratio = 2 , nmr_steps = 5 , max_step_sizes = None , data = None , cl_runtime_info = None ) :
"""Estimate and return the upper triangular elements of the Hessian of the given function at the given parameters .
Thi... | if len ( parameters . shape ) == 1 :
parameters = parameters [ None , : ]
nmr_voxels = parameters . shape [ 0 ]
nmr_params = parameters . shape [ 1 ]
nmr_derivatives = nmr_params * ( nmr_params + 1 ) // 2
initial_step = _get_initial_step ( parameters , lower_bounds , upper_bounds , max_step_sizes )
kernel_data = { ... |
def generate_strings ( project_base_dir , localization_bundle_path , tmp_directory , exclude_dirs , include_strings_file , special_ui_components_prefix ) :
"""Calls the builtin ' genstrings ' command with JTLocalizedString as the string to search for ,
and adds strings extracted from UI elements internationalized... | localization_directory = os . path . join ( localization_bundle_path , DEFAULT_LANGUAGE_DIRECTORY_NAME )
if not os . path . exists ( localization_directory ) :
os . makedirs ( localization_directory )
localization_file = os . path . join ( localization_directory , LOCALIZATION_FILENAME )
# Creating the same directo... |
def build_stereographic_projection ( center ) :
"""Compute * x * and * y * coordinates at which to plot the positions .""" | # TODO : Computing the center should really be done using
# optimization , as in :
# https : / / math . stackexchange . com / questions / 409217/
p = center . position . au
u = p / length_of ( p )
c = u . mean ( axis = 1 )
c = c / length_of ( c )
x_c , y_c , z_c = c
def project ( position ) :
p = position . positio... |
def activated ( self , include_extras = True , extra_dists = [ ] ) :
"""A context manager which activates the virtualenv .
: param list extra _ dists : Paths added to the context after the virtualenv is activated .
This context manager sets the following environment variables :
* ` PYTHONUSERBASE `
* ` VIRT... | original_path = sys . path
original_prefix = sys . prefix
original_user_base = os . environ . get ( "PYTHONUSERBASE" , None )
original_venv = os . environ . get ( "VIRTUAL_ENV" , None )
parent_path = vistir . compat . Path ( __file__ ) . absolute ( ) . parent . parent . as_posix ( )
prefix = self . prefix . as_posix ( ... |
def plot_correlation_heatmap ( self ) :
"""Return HTML for correlation heatmap""" | data = None
corr_type = None
correlation_type = getattr ( config , 'rna_seqc' , { } ) . get ( 'default_correlation' , 'spearman' )
if self . rna_seqc_spearman is not None and correlation_type != 'pearson' :
data = self . rna_seqc_spearman
corr_type = 'Spearman'
elif self . rna_seqc_pearson is not None :
dat... |
def action_getattr ( ) :
"""Creates a getter that will drop the current value
and retrieve the action ' s attribute with the context key as name .""" | def action_getattr ( _value , context , ** _params ) :
value = getattr ( context [ "action" ] , context [ "key" ] )
return _attr ( value )
return action_getattr |
def compliance_violation ( self , column = None , value = None , ** kwargs ) :
"""A compliance schedule violation reflects the non - achievement of a
given compliance schedule event including the type of violation and ty
pe of resolution .
> > > PCS ( ) . compliance _ violation ( ' cs _ rnc _ detect _ date ' ... | return self . _resolve_call ( 'PCS_CMPL_SCHD_VIOL' , column , value , ** kwargs ) |
def eth_getBlockByNumber ( self , block = BLOCK_TAG_LATEST , tx_objects = True ) :
"""https : / / github . com / ethereum / wiki / wiki / JSON - RPC # eth _ getblockbynumber
: param block : Block tag or number ( optional )
: type block : int or BLOCK _ TAGS
: param tx _ objects : Return txs full object ( opti... | block = validate_block ( block )
result = yield from self . rpc_call ( 'eth_getBlockByNumber' , [ block , tx_objects ] )
# TODO : Update result response
return result |
def point_rotate ( pt , ax , theta ) :
"""Rotate a 3 - D point around a 3 - D axis through the origin .
Handedness is a counter - clockwise rotation when viewing the rotation
axis as pointing at the observer . Thus , in a right - handed x - y - z frame ,
a 90deg rotation of ( 1,0,0 ) around the z - axis ( 0,0... | # Imports
import numpy as np
# Ensure pt is reducible to 3 - D vector .
pt = make_nd_vec ( pt , nd = 3 , t = np . float64 , norm = False )
# Calculate the rotation
rot_pt = np . dot ( mtx_rot ( ax , theta , reps = 1 ) , pt )
# Should be ready to return
return rot_pt |
def _balance ( self , ) :
"""calc unbalanced charges and radicals for skin atoms""" | meta = h . meta
for n in ( skin_reagent . keys ( ) | skin_product . keys ( ) ) :
lost = skin_reagent [ n ]
cycle_lost = cycle ( lost )
new = skin_product [ n ]
cycle_new = cycle ( new )
atom = h . _node [ n ]
dr = atom . p_radical - atom . radical
# radical balancing
if dr > 0 : # radica... |
def set_dchans ( self , dchans = None , method = 'set' ) :
"""Set ( or update ) the dchans dict
dchans is a dict of np . ndarrays of len ( ) = self . nch containing
channel - specific information
Use the kwarg ' method ' to set / update the dict""" | assert method in [ 'set' , 'update' ]
dchans = self . _checkformat_inputs_dchans ( dchans = dchans )
if method == 'set' :
self . _dchans = dchans
else :
self . _dchans . update ( dchans ) |
def check_input ( self , obj ) :
"""Performs checks on the input object . Raises an exception if unsupported .
: param obj : the object to check
: type obj : object""" | if isinstance ( obj , str ) :
return
if isinstance ( obj , unicode ) :
return
raise Exception ( "Unsupported class: " + self . _input . __class__ . __name__ ) |
def set_default_loader ( loader ) :
"""Set defaulr loader instance
Parameters
loader : instance or string
An instance or registered name of loader class .
The specified loader instance will be used when user did not specified
: attr : ` loader ` in : func : ` maidenhair . functions . load ` function .
S... | if isinstance ( loader , basestring ) :
loader = registry . find ( loader ) ( )
if not isinstance ( loader , BaseLoader ) :
loader = loader ( )
global _loader
_loader = loader |
def exchange_to_margin ( self , symbol , currency , amount , _async = False ) :
"""现货账户划入至借贷账户
: param amount :
: param currency :
: param symbol :
: return :""" | params = { 'symbol' : symbol , 'currency' : currency , 'amount' : amount }
path = '/v1/dw/transfer-in/margin'
return api_key_post ( params , path , _async = _async ) |
def set_cores_massive ( self , filename = 'core_masses_massive.txt' ) :
'''Uesse function cores in nugridse . py''' | core_info = [ ]
minis = [ ]
for i in range ( len ( self . runs_H5_surf ) ) :
sefiles = se ( self . runs_H5_out [ i ] )
mini = sefiles . get ( 'mini' )
minis . append ( mini )
incycle = int ( sefiles . se . cycles [ - 1 ] )
core_info . append ( sefiles . cores ( incycle = incycle ) )
print_info = ''
... |
def plotDataframe ( table , title , plotPath ) :
"""Plot Panda dataframe .
: param table : Panda dataframe returned by : func : ` analyzeWeightPruning `
: type table : : class : ` pandas . DataFrame `
: param title : Plot title
: type title : str
: param plotPath : Plot full path
: type plotPath : str""... | plt . figure ( )
axes = table . T . plot ( subplots = True , sharex = True , grid = True , legend = True , title = title , figsize = ( 8 , 11 ) )
# Use fixed scale for " accuracy "
accuracy = next ( ax for ax in axes if ax . lines [ 0 ] . get_label ( ) == 'accuracy' )
accuracy . set_ylim ( 0.0 , 1.0 )
plt . savefig ( p... |
def compare_user ( passed_user = None , user_list = None ) :
"""Check if supplied User instance exists in supplied Users list and , if so , return the differences .
args :
passed _ user ( User ) : the user instance to check for differences
user _ list ( Users ) : the Users instance containing a list of Users ... | # Check if user exists
returned = user_list . describe_users ( users_filter = dict ( name = passed_user . name ) )
replace_keys = False
# User exists , so compare attributes
comparison_result = dict ( )
if passed_user . uid and ( not returned [ 0 ] . uid == passed_user . uid ) :
comparison_result [ 'uid_action' ] =... |
def crosstab ( self , col1 , col2 ) :
"""Computes a pair - wise frequency table of the given columns . Also known as a contingency
table . The number of distinct values for each column should be less than 1e4 . At most 1e6
non - zero pair frequencies will be returned .
The first column of each row will be the... | if not isinstance ( col1 , basestring ) :
raise ValueError ( "col1 should be a string." )
if not isinstance ( col2 , basestring ) :
raise ValueError ( "col2 should be a string." )
return DataFrame ( self . _jdf . stat ( ) . crosstab ( col1 , col2 ) , self . sql_ctx ) |
def process_input ( netIn , allowedformats , outputformat = 'G' ) :
"""Takes input network and checks what the input is .
Parameters
netIn : array , dict , or TemporalNetwork
Network ( graphlet , contact or object )
allowedformats : str
Which format of network objects that are allowed . Options : ' C ' , ... | inputtype = checkInput ( netIn )
# Convert TN to G representation
if inputtype == 'TN' and 'TN' in allowedformats and outputformat != 'TN' :
G = netIn . df_to_array ( )
netInfo = { 'nettype' : netIn . nettype , 'netshape' : netIn . netshape }
elif inputtype == 'TN' and 'TN' in allowedformats and outputformat ==... |
def get_user_info ( self , request ) :
"""Implement custom getter .""" | if not current_user . is_authenticated :
return { }
user_info = { 'id' : current_user . get_id ( ) , }
if 'SENTRY_USER_ATTRS' in current_app . config :
for attr in current_app . config [ 'SENTRY_USER_ATTRS' ] :
if hasattr ( current_user , attr ) :
user_info [ attr ] = getattr ( current_user ... |
def _ReadBooleanDataTypeDefinition ( self , definitions_registry , definition_values , definition_name , is_member = False ) :
"""Reads a boolean data type definition .
Args :
definitions _ registry ( DataTypeDefinitionsRegistry ) : data type definitions
registry .
definition _ values ( dict [ str , object ... | return self . _ReadFixedSizeDataTypeDefinition ( definitions_registry , definition_values , data_types . BooleanDefinition , definition_name , self . _SUPPORTED_ATTRIBUTES_BOOLEAN , is_member = is_member , supported_size_values = ( 1 , 2 , 4 ) ) |
def next_trials ( self ) :
"""Provides Trial objects to be queued into the TrialRunner .
Returns :
trials ( list ) : Returns a list of trials .""" | trials = list ( self . _trial_generator )
if self . _shuffle :
random . shuffle ( trials )
self . _finished = True
return trials |
def make_tag ( cls , tag_name ) :
"""Make a Tag object from a tag name . Registers it with the content manager
if possible .""" | if cls . cm :
return cls . cm . make_tag ( tag_name )
return Tag ( tag_name . strip ( ) ) |
def revisit ( self , node , include_self = True ) :
"""Revisit a node in the future . As a result , the successors to this node will be revisited as well .
: param node : The node to revisit in the future .
: return : None""" | successors = self . successors ( node )
# , skip _ reached _ fixedpoint = True )
if include_self :
self . _sorted_nodes . add ( node )
for succ in successors :
self . _sorted_nodes . add ( succ )
# reorder it
self . _sorted_nodes = OrderedSet ( sorted ( self . _sorted_nodes , key = lambda n : self . _node_to_in... |
def _get_sorted_go2nt ( self , go2nt , sortby ) :
"""Return sorted list of tuples .""" | if sortby is True :
_fnc = self . get_fncsortnt ( )
return sorted ( go2nt . items ( ) , key = lambda t : _fnc ( t [ 1 ] ) )
if sortby :
return sorted ( go2nt . items ( ) , key = lambda t : sortby ( t [ 1 ] ) )
return go2nt . items ( ) |
def mkstemp ( * args , ** kwargs ) :
"""Context manager similar to tempfile . NamedTemporaryFile except the file is not deleted on close , and only the filepath
is returned
. . warnings : : Unlike tempfile . mkstemp , this is not secure""" | fd , filename = tempfile . mkstemp ( * args , ** kwargs )
os . close ( fd )
try :
yield filename
finally :
os . remove ( filename ) |
def _repeat_1d ( x , K , out ) :
'''Repeats each element of a vector many times and repeats the whole
result many times
Parameters
x : ndarray ( ndim = 1)
vector to be repeated
K : scalar ( int )
number of times each element of x is repeated ( inner iterations )
out : ndarray ( ndim = 1)
placeholder... | N = x . shape [ 0 ]
L = out . shape [ 0 ] // ( K * N )
# number of outer iterations
# K # number of inner iterations
# the result out should enumerate in C - order the elements
# of a 3 - dimensional array T of dimensions ( K , N , L )
# such that for all k , n , l , we have T [ k , n , l ] = = x [ n ]
for n in range (... |
def division_name ( self ) :
"""The type designation for the county or county equivalent , such as ' County ' , ' Parish ' or ' Borough '""" | try :
return next ( e for e in self . type_names_re . search ( self . name ) . groups ( ) if e is not None )
except AttributeError : # The search will fail for ' District of Columbia '
return '' |
def hist_calls ( fn ) :
"""Decorator to check the distribution of return values of a function .""" | @ functools . wraps ( fn )
def wrapper ( * args , ** kwargs ) :
_histogram = histogram ( "%s_calls" % pyformance . registry . get_qualname ( fn ) )
rtn = fn ( * args , ** kwargs )
if type ( rtn ) in ( int , float ) :
_histogram . add ( rtn )
return rtn
return wrapper |
def exec_stmt_handle ( self , tokens ) :
"""Process Python - 3 - style exec statements .""" | internal_assert ( 1 <= len ( tokens ) <= 3 , "invalid exec statement tokens" , tokens )
if self . target . startswith ( "2" ) :
out = "exec " + tokens [ 0 ]
if len ( tokens ) > 1 :
out += " in " + ", " . join ( tokens [ 1 : ] )
return out
else :
return "exec(" + ", " . join ( tokens ) + ")" |
def save_to_mat_file ( self , parameter_space , result_parsing_function , filename , runs ) :
"""Return the results relative to the desired parameter space in the form
of a . mat file .
Args :
parameter _ space ( dict ) : dictionary containing
parameter / list - of - values pairs .
result _ parsing _ func... | # Make sure all values are lists
for key in parameter_space :
if not isinstance ( parameter_space [ key ] , list ) :
parameter_space [ key ] = [ parameter_space [ key ] ]
# Add a dimension label for each non - singular dimension
dimension_labels = [ { key : str ( parameter_space [ key ] ) } for key in param... |
def prepare_request_body ( self , username , password , body = '' , scope = None , include_client_id = False , ** kwargs ) :
"""Add the resource owner password and username to the request body .
The client makes a request to the token endpoint by adding the
following parameters using the " application / x - www... | kwargs [ 'client_id' ] = self . client_id
kwargs [ 'include_client_id' ] = include_client_id
return prepare_token_request ( self . grant_type , body = body , username = username , password = password , scope = scope , ** kwargs ) |
def set_advanced_configs ( vm_name , datacenter , advanced_configs , service_instance = None ) :
'''Appends extra config parameters to a virtual machine advanced config list
vm _ name
Virtual machine name
datacenter
Datacenter name where the virtual machine is available
advanced _ configs
Dictionary wit... | current_config = get_vm_config ( vm_name , datacenter = datacenter , objects = True , service_instance = service_instance )
diffs = compare_vm_configs ( { 'name' : vm_name , 'advanced_configs' : advanced_configs } , current_config )
datacenter_ref = salt . utils . vmware . get_datacenter ( service_instance , datacenter... |
def get_settings ( self , * args , ** kwargs ) :
"""Return the settings for this wiki page .
Includes permission level , names of editors , and whether
the page is listed on / wiki / pages .
Additional parameters are passed into
: meth : ` ~ praw . _ _ init _ _ . BaseReddit . request _ json `""" | url = self . reddit_session . config [ 'wiki_page_settings' ]
url = url . format ( subreddit = six . text_type ( self . subreddit ) , page = self . page )
return self . reddit_session . request_json ( url , * args , ** kwargs ) [ 'data' ] |
def write_length_and_key ( fp , value ) :
"""Helper to write descriptor key .""" | written = write_fmt ( fp , 'I' , 0 if value in _TERMS else len ( value ) )
written += write_bytes ( fp , value )
return written |
def build ( self , builder ) :
"""Build XML by appending to builder""" | builder . start ( "SourceID" , { } )
builder . data ( self . source_id )
builder . end ( "SourceID" ) |
def get_compatible_systems ( self , id_or_uri ) :
"""Retrieves a collection of all storage systems that is applicable to this storage volume template .
Args :
id _ or _ uri :
Can be either the power device id or the uri
Returns :
list : Storage systems .""" | uri = self . _client . build_uri ( id_or_uri ) + "/compatible-systems"
return self . _client . get ( uri ) |
def israw ( self , ** kwargs ) :
"""Returns True if the PTY should operate in raw mode .
If the container was not started with tty = True , this will return False .""" | if self . raw is None :
info = self . _container_info ( )
self . raw = self . stdout . isatty ( ) and info [ 'Config' ] [ 'Tty' ]
return self . raw |
def generate_shared_public_key ( my_private_key , their_public_pair , generator ) :
"""Two parties each generate a private key and share their public key with the
other party over an insecure channel . The shared public key can be generated by
either side , but not by eavesdroppers . You can then use the entrop... | p = generator . Point ( * their_public_pair )
return my_private_key * p |
def update ( self , img , value_dict ) :
"""Accepts an image reference ( object or ID ) and dictionary of key / value
pairs , where the key is an attribute of the image , and the value is the
desired new value for that image .
NOTE : There is a bug in Glance where the ' add ' operation returns a 409
if the ... | img = self . get ( img )
uri = "/%s/%s" % ( self . uri_base , utils . get_id ( img ) )
body = [ ]
for key , val in value_dict . items ( ) :
op = "replace" if key in img . __dict__ else "add"
body . append ( { "op" : op , "path" : "/%s" % key , "value" : val } )
headers = { "Content-Type" : "application/openstac... |
def copy_and_patch_libzmq ( ZMQ , libzmq ) :
"""copy libzmq into source dir , and patch it if necessary .
This command is necessary prior to running a bdist on Linux or OS X .""" | if sys . platform . startswith ( 'win' ) :
return
# copy libzmq into zmq for bdist
local = localpath ( 'zmq' , libzmq )
if not ZMQ and not os . path . exists ( local ) :
fatal ( "Please specify zmq prefix via `setup.py configure --zmq=/path/to/zmq` " "or copy libzmq into zmq/ manually prior to running bdist." )... |
def search ( self ) :
"""* trigger the conesearch *
* * Return : * *
- ` ` matchIndies ` ` - - the indicies of the input transient sources ( syncs with ` ` uniqueMatchDicts ` ` )
- ` ` uniqueMatchDicts ` ` - - the crossmatch results
* * Usage : * *
See class docstring for usage examples
. . todo : :
-... | self . log . debug ( 'starting the ``search`` method' )
# ACCOUNT FOR TYPE OF SEARCH
sqlWhere = False
magnitudeLimitFilter = self . magnitudeLimitFilter
disCols = [ "zColName" , "distanceColName" , "semiMajorColName" ]
sqlWhere = ""
if self . physicalSearch == True :
for d in disCols :
colName = self . colM... |
def _staging_step ( self , basename ) :
"""Checks the size of audio file , splits it if it ' s needed to manage api
limit and then moves to ` staged ` directory while appending ` * ` to
the end of the filename for self . split _ audio _ by _ duration to replace
it by a number .
Parameters
basename : str
... | name = '' . join ( basename . split ( '.' ) [ : - 1 ] )
if self . get_mode ( ) == "ibm" : # Checks the file size . It ' s better to use 95 % of the allocated
# size per file since the upper limit is not always respected .
total_size = os . path . getsize ( "{}/filtered/{}.wav" . format ( self . src_dir , name ) )
... |
def default_peek ( python_type , exposes ) :
"""Autoserializer factory .
Works best in Python 3.
Arguments :
python _ type ( type ) : type constructor .
exposes ( iterable ) : sequence of attributes .
Returns :
callable : deserializer ( ` peek ` routine ) .""" | with_args = False
make = python_type
try :
make ( )
except ( SystemExit , KeyboardInterrupt ) :
raise
except :
make = lambda : python_type . __new__ ( python_type )
try :
make ( )
except ( SystemExit , KeyboardInterrupt ) :
raise
except :
make = lambda args : python_type ... |
async def parse_get_revoc_reg_delta_response ( get_revoc_reg_delta_response : str ) -> ( str , str , int ) :
"""Parse a GET _ REVOC _ REG _ DELTA response to get Revocation Registry Delta in the format compatible with Anoncreds API .
: param get _ revoc _ reg _ delta _ response : response of GET _ REVOC _ REG _ D... | logger = logging . getLogger ( __name__ )
logger . debug ( "parse_get_revoc_reg_delta_response: >>> get_revoc_reg_delta_response: %r" , get_revoc_reg_delta_response )
if not hasattr ( parse_get_revoc_reg_delta_response , "cb" ) :
logger . debug ( "parse_get_revoc_reg_delta_response: Creating callback" )
parse_g... |
def count_lines ( fname , mode = 'rU' ) :
'''Count the number of lines in a file
Only faster way would be to utilize multiple processor cores to perform parallel reads .
http : / / stackoverflow . com / q / 845058/623735''' | with open ( fname , mode ) as f :
for i , l in enumerate ( f ) :
pass
return i + 1 |
def export_assets ( self , parent , output_config , read_time = None , asset_types = None , content_type = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Exports assets with time and resource types to a given Clou... | # Wrap the transport method to add retry and timeout logic .
if "export_assets" not in self . _inner_api_calls :
self . _inner_api_calls [ "export_assets" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . export_assets , default_retry = self . _method_configs [ "ExportAssets" ] . retry , ... |
def create_raid ( self , raid_config ) :
"""Create the raid configuration on the hardware .
: param raid _ config : A dictionary containing target raid configuration
data . This data stucture should be as follows :
raid _ config = { ' logical _ disks ' : [ { ' raid _ level ' : 1,
' size _ gb ' : 100 , ' phy... | manager . validate ( raid_config )
logical_drives = raid_config [ 'logical_disks' ]
redfish_logical_disk = [ ]
for ld in logical_drives :
ld_attr = { "Raid" : "Raid" + ld [ "raid_level" ] }
ld_attr [ "CapacityGiB" ] = - 1 if ld [ "size_gb" ] == "MAX" else int ( ld [ "size_gb" ] )
if 'physical_disks' in ld :... |
def match_pattern ( self , pat , word ) :
"""Implements fixed - width pattern matching .
Matches just in case pattern is the same length ( in segments ) as the
word and each of the segments in the pattern is a featural subset of the
corresponding segment in the word . Matches return the corresponding list
o... | segs = self . word_fts ( word )
if len ( pat ) != len ( segs ) :
return None
else :
if all ( [ set ( p ) <= s for ( p , s ) in zip ( pat , segs ) ] ) :
return segs |
def get_all_fix_names ( fixer_pkg , remove_prefix = True ) :
"""Return a sorted list of all available fix names in the given package .""" | pkg = __import__ ( fixer_pkg , [ ] , [ ] , [ "*" ] )
fixer_dir = os . path . dirname ( pkg . __file__ )
fix_names = [ ]
for name in sorted ( os . listdir ( fixer_dir ) ) :
if name . startswith ( "fix_" ) and name . endswith ( ".py" ) :
if remove_prefix :
name = name [ 4 : ]
fix_names . a... |
def _shrink ( self , needed , running ) :
"""Shrink the process pool from the number currently running to
the needed number . The processes will be sent a SIGTERM at first
and if that doesn ' t clear the process , a SIGKILL . Errors will
be logged but otherwise ignored .""" | log = self . _params . get ( 'log' , self . _discard )
log . info ( "%d process%s running, reducing to %d process%s" , running , ses ( running , 'es' ) , needed , ses ( needed , 'es' ) )
now = time . time ( )
signalled = 0
for proc in self . _proc_state [ needed : ] :
if proc . pid is None :
continue
if... |
def handle_exception ( error ) :
"""Simple method for handling exceptions raised by ` PyBankID ` .
: param flask _ pybankid . FlaskPyBankIDError error : The exception to handle .
: return : The exception represented as a dictionary .
: rtype : dict""" | response = jsonify ( error . to_dict ( ) )
response . status_code = error . status_code
return response |
def unroll_angles ( A , sign ) :
"""Unrolls the angles , A , so they increase continuously""" | n = np . array ( [ 0 , 0 , 0 ] )
P = np . zeros ( np . shape ( A ) )
P [ 0 ] = A [ 0 ]
for i in range ( 1 , len ( A ) ) :
n = n + ( ( A [ i ] - A [ i - 1 ] + 0.5 * sign * np . pi ) * sign < 0 ) * np . ones ( 3 ) * 2. * np . pi
P [ i ] = A [ i ] + sign * n
return P |
def get_glitter_app ( self , glitter_app_name ) :
"""Retrieve the Glitter App config for a specific Glitter App .""" | if not self . discovered :
self . discover_glitter_apps ( )
try :
glitter_app = self . glitter_apps [ glitter_app_name ]
return glitter_app
except KeyError :
return None |
def dice_check ( self , n , d , target , comparator = '<=' ) :
"""Roll ` ` n ` ` dice with ` ` d ` ` sides , sum them , and return whether they
are < = ` ` target ` ` .
If ` ` comparator ` ` is provided , use it instead of < = . You may
use a string like ' < ' or ' > = ' .""" | from operator import gt , lt , ge , le , eq , ne
comps = { '>' : gt , '<' : lt , '>=' : ge , '<=' : le , '=' : eq , '==' : eq , '!=' : ne }
try :
comparator = comps . get ( comparator , comparator )
except TypeError :
pass
return comparator ( sum ( self . dice ( n , d ) ) , target ) |
def render_dictionary ( data , headers = None ) :
"""Return a dictionary list formatted as a HTML table .
Args :
data : the dictionary list
headers : the keys in the dictionary to use as table columns , in order .""" | return IPython . core . display . HTML ( _html . HtmlBuilder . render_table ( data , headers ) ) |
def _collect_valid_settings ( meta , clsdict ) :
"""Return a sequence containing the enumeration values that are valid
assignment values . Return - only values are excluded .""" | enum_members = clsdict [ '__members__' ]
valid_settings = [ ]
for member in enum_members :
valid_settings . extend ( member . valid_settings )
clsdict [ '_valid_settings' ] = valid_settings |
def solveConsRepAgentMarkov ( solution_next , MrkvArray , DiscFac , CRRA , IncomeDstn , CapShare , DeprFac , PermGroFac , aXtraGrid ) :
'''Solve one period of the simple representative agent consumption - saving model .
This version supports a discrete Markov process .
Parameters
solution _ next : ConsumerSol... | # Define basic objects
StateCount = MrkvArray . shape [ 0 ]
aNrmNow = aXtraGrid
aNrmCount = aNrmNow . size
EndOfPrdvP_cond = np . zeros ( ( StateCount , aNrmCount ) ) + np . nan
# Loop over * next period * states , calculating conditional EndOfPrdvP
for j in range ( StateCount ) : # Define next - period - state conditi... |
def monitor ( args ) :
'''Retrieve status of jobs submitted from a given workspace , as a list
of TSV lines sorted by descending order of job submission date''' | r = fapi . list_submissions ( args . project , args . workspace )
fapi . _check_response_code ( r , 200 )
statuses = sorted ( r . json ( ) , key = lambda k : k [ 'submissionDate' ] , reverse = True )
header = '\t' . join ( list ( statuses [ 0 ] . keys ( ) ) )
expander = lambda v : '{0}' . format ( v )
def expander ( th... |
def get_times ( self ) :
"""Return a list of occurrance times of the events
: return : list of times""" | if not self . n :
return list ( )
ret = list ( )
for item in self . _event_times :
ret += list ( self . __dict__ [ item ] )
return ret + list ( matrix ( ret ) - 1e-6 ) |
def upgrade_tools_all ( call = None ) :
'''To upgrade VMware Tools on all virtual machines present in
the specified provider
. . note : :
If the virtual machine is running Windows OS , this function
will attempt to suppress the automatic reboot caused by a
VMware Tools upgrade .
CLI Example :
. . code... | if call != 'function' :
raise SaltCloudSystemExit ( 'The upgrade_tools_all function must be called with ' '-f or --function.' )
ret = { }
vm_properties = [ "name" ]
vm_list = salt . utils . vmware . get_mors_with_properties ( _get_si ( ) , vim . VirtualMachine , vm_properties )
for vm in vm_list :
ret [ vm [ 'n... |
def update_visited ( self ) :
"""Updates exploration map visited status""" | assert isinstance ( self . player . cshape . center , eu . Vector2 )
pos = self . player . cshape . center
# Helper function
def set_visited ( layer , cell ) :
if cell and not cell . properties . get ( 'visited' ) and cell . tile and cell . tile . id > 0 :
cell . properties [ 'visited' ] = True
self... |
def authorize ( * args , ** kwargs ) :
"""View for rendering authorization request .""" | if request . method == 'GET' :
client = Client . query . filter_by ( client_id = kwargs . get ( 'client_id' ) ) . first ( )
if not client :
abort ( 404 )
scopes = current_oauth2server . scopes
ctx = dict ( client = client , oauth_request = kwargs . get ( 'request' ) , scopes = [ scopes [ x ] for... |
def __get_keys ( self ) :
"""Return the keys associated with this node by adding its key and then adding parent keys recursively .""" | keys = list ( )
tree_node = self
while tree_node is not None and tree_node . key is not None :
keys . insert ( 0 , tree_node . key )
tree_node = tree_node . parent
return keys |
def getKwdArgs ( self , flatten = False ) :
"""Return a dict of all normal dict parameters - that is , all
parameters NOT marked with " pos = N " in the . cfgspc file . This will
also exclude all hidden parameters ( metadata , rules , etc ) .""" | # Start with a full deep - copy . What complicates this method is the
# idea of sub - sections . This dict can have dicts as values , and so on .
dcopy = self . dict ( )
# ConfigObj docs say this is a deep - copy
# First go through the dict removing all positional args
for idx , scope , name in self . _posArgs :
th... |
def _handle_order_args ( self , rison_args ) :
"""Help function to handle rison order
arguments
: param rison _ args :
: return :""" | order_column = rison_args . get ( API_ORDER_COLUMN_RIS_KEY , "" )
order_direction = rison_args . get ( API_ORDER_DIRECTION_RIS_KEY , "" )
if not order_column and self . base_order :
order_column , order_direction = self . base_order
if order_column not in self . order_columns :
return "" , ""
return order_colum... |
def merge ( self , another ) :
"""Merges another validation result graph into itself""" | if isinstance ( another , Result ) :
another = another . errors
self . errors = self . merge_errors ( self . errors , another ) |
def gauge ( self , name ) :
"""Returns an existing or creates and returns a new gauge
: param name : name of the gauge
: return : the gauge object""" | with self . _lock :
if name not in self . _gauges :
if self . _registry . _ignore_patterns and any ( pattern . match ( name ) for pattern in self . _registry . _ignore_patterns ) :
gauge = noop_metric
else :
gauge = Gauge ( name )
self . _gauges [ name ] = gauge
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.