signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def filterBuilderList ( self , builderNames ) :
"""Make sure that C { builderNames } is a subset of the configured
C { self . builderNames } , returning an empty list if not . If
C { builderNames } is empty , use C { self . builderNames } .
@ returns : list of builder names to build on""" | # self . builderNames is the configured list of builders
# available for try . If the user supplies a list of builders ,
# it must be restricted to the configured list . If not , build
# on all of the configured builders .
if builderNames :
for b in builderNames :
if b not in self . builderNames :
... |
def _equivalent ( self , other ) :
"""Compare two entities of the same class , excluding keys .""" | if other . __class__ is not self . __class__ : # TODO : What about subclasses ?
raise NotImplementedError ( 'Cannot compare different model classes. ' '%s is not %s' % ( self . __class__ . __name__ , other . __class_ . __name__ ) )
if set ( self . _projection ) != set ( other . _projection ) :
return False
# It... |
def write_from_file ( library , session , filename , count ) :
"""Take data from a file and write it out synchronously .
Corresponds to viWriteFromFile function of the VISA library .
: param library : the visa library wrapped by ctypes .
: param session : Unique logical identifier to a session .
: param fil... | return_count = ViUInt32 ( )
ret = library . viWriteFromFile ( session , filename , count , return_count )
return return_count , ret |
def _auth ( profile = None ) :
'''Set up neutron credentials''' | credentials = __salt__ [ 'config.option' ] ( profile )
kwargs = { 'username' : credentials [ 'keystone.user' ] , 'password' : credentials [ 'keystone.password' ] , 'tenant_name' : credentials [ 'keystone.tenant' ] , 'auth_url' : credentials [ 'keystone.auth_url' ] , 'region_name' : credentials . get ( 'keystone.region_... |
def find_plugin ( self , name ) :
"""Find a plugin named name""" | suffix = ".py"
if not self . class_name :
suffix = ""
for i in self . _get_paths ( ) :
path = os . path . join ( i , "%s%s" % ( name , suffix ) )
if os . path . exists ( path ) :
return path
return None |
def set_property ( self , name , value , update_session = True ) :
"""Create or set the value of a property . Returns ` True ` if the property was created or updated , or ` False ` if
there were no changes to the value of the property .
Args :
name ( str ) : Name of the property to create or update
value ( ... | if type ( value ) == datetime :
value = value . isoformat ( )
else :
value = value
try :
prop = self . get_property ( name )
if prop . value == value :
return False
prop . value = value
except AttributeError :
prop = ResourceProperty ( )
prop . resource_id = self . id
prop . name... |
def set_params ( self , ** params ) :
"""Sets new values to the specified parameters .
Parameters :
params : variable sized dictionary , n key - word arguments
Example :
scaler . set _ params ( std = 0.30)
Returns :
void : void , returns nothing""" | for k , v in params . items ( ) :
vars ( self ) [ k ] = v |
def GetCpuUsedMs ( self ) :
'''Retrieves the number of milliseconds during which the virtual machine
has used the CPU . This value includes the time used by the guest
operating system and the time used by virtualization code for tasks for this
virtual machine . You can combine this value with the elapsed time... | counter = c_uint64 ( )
ret = vmGuestLib . VMGuestLib_GetCpuUsedMs ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def samples_by_indices_nomapping ( self , indices ) :
"""Gather a batch of samples by indices * without * applying any index
mapping resulting from the ( optional ) use of the ` indices ` array
passed to the constructor .
Parameters
indices : 1D - array of ints or slice
The samples to retrieve
Returns
... | batch = tuple ( [ d [ indices ] for d in self . data ] )
if self . include_indices :
if isinstance ( indices , slice ) :
indices = np . arange ( indices . start , indices . stop , indices . step )
return ( indices , ) + batch
else :
return batch |
def get_icon_url ( self , brain ) :
"""Returns the ( big ) icon URL for the given catalog brain""" | icon_url = api . get_icon ( brain , html_tag = False )
url , icon = icon_url . rsplit ( "/" , 1 )
relative_url = url . lstrip ( self . portal . absolute_url ( ) )
name , ext = os . path . splitext ( icon )
# big icons endwith _ big
if not name . endswith ( "_big" ) :
icon = "{}_big{}" . format ( name , ext )
icon_b... |
def get_activity_objective_bank_assignment_session ( self , proxy ) :
"""Gets the session for assigning activity to objective bank mappings .
: param proxy : a proxy
: type proxy : ` ` osid . proxy . Proxy ` `
: return : an ` ` ActivityObjectiveBankAssignmentSession ` `
: rtype : ` ` osid . learning . Activ... | if not self . supports_activity_objective_bank_assignment ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . ActivityObjectiveBankAssignmentSession ( proxy = proxy , runtime = self .... |
def write ( self , frames ) :
"""Write the frames to the target HDF5 file , using the format used by
` ` pd . Panel . to _ hdf ` `
Parameters
frames : iter [ ( int , DataFrame ) ] or dict [ int - > DataFrame ]
An iterable or other mapping of sid to the corresponding OHLCV
pricing data .""" | with HDFStore ( self . _path , 'w' , complevel = self . _complevel , complib = self . _complib ) as store :
panel = pd . Panel . from_dict ( dict ( frames ) )
panel . to_hdf ( store , 'updates' )
with tables . open_file ( self . _path , mode = 'r+' ) as h5file :
h5file . set_node_attr ( '/' , 'version' , 0 ... |
def colourblind ( i ) :
'''colour pallete from http : / / tableaufriction . blogspot . ro /
allegedly suitable for colour - blind folk
SJ''' | rawRGBs = [ ( 162 , 200 , 236 ) , ( 255 , 128 , 14 ) , ( 171 , 171 , 171 ) , ( 95 , 158 , 209 ) , ( 89 , 89 , 89 ) , ( 0 , 107 , 164 ) , ( 255 , 188 , 121 ) , ( 207 , 207 , 207 ) , ( 200 , 82 , 0 ) , ( 137 , 137 , 137 ) ]
scaledRGBs = [ ]
for r in rawRGBs :
scaledRGBs . append ( ( old_div ( r [ 0 ] , 255. ) , old_d... |
def _get_formatted_query ( self , fields , limit , order_by , offset ) :
"""Converts the query to a ServiceNow - interpretable format
: return :
- ServiceNow query""" | if not isinstance ( order_by , list ) :
raise InvalidUsage ( "Argument order_by should be a `list` of fields" )
if not isinstance ( fields , list ) :
raise InvalidUsage ( "Argument fields should be a `list` of fields" )
if isinstance ( self . query , QueryBuilder ) :
sysparm_query = str ( self . query )
eli... |
def to_dict ( self ) :
'''Save this target port into a dictionary .''' | d = super ( TargetPort , self ) . to_dict ( )
d [ 'portName' ] = self . port_name
return d |
def qteNextWindow ( self ) :
"""Return next window in cyclic order .
| Args |
* * * None * *
| Returns |
* * * QtmacsWindow * * : the next window in the Qtmacs internal
window list .
| Raises |
* * * None * *""" | # Get the currently active window .
win = self . qteActiveWindow ( )
if win in self . _qteWindowList : # Find the index of the window in the window list and
# cyclically move to the next element in this list to find
# the next window object .
idx = self . _qteWindowList . index ( win )
idx = ( idx + 1 ) % len (... |
def compare_nodes ( node1 , node2 , ret ) :
'''compare _ nodes
High - level api : Compare node1 and node2 and put the result in ret .
Parameters
node1 : ` Element `
A node in a model tree .
node2 : ` Element `
A node in another model tree .
ret : ` Element `
A node in self . tree .
Returns
None ... | for child in node2 . getchildren ( ) :
peer = ModelDiff . get_peer ( child . tag , node1 )
if peer is None :
ModelDiff . copy_subtree ( ret , child , 'added' )
else :
if ModelDiff . node_equal ( peer , child ) :
continue
else :
if child . attrib [ 'type' ] in ... |
def group_barh ( self , column_label , ** vargs ) :
"""Plot a horizontal bar chart for the table .
The values of the specified column are grouped and counted , and one
bar is produced for each group .
Note : This differs from ` ` barh ` ` in that there is no need to specify
bar heights ; the size of a categ... | self . group ( column_label ) . barh ( column_label , ** vargs ) |
def find_le ( array , x ) :
"""Find rightmost value less than or equal to x .
: type array : list
: param array : an iterable object that support inex
: param x : a comparable value
Example : :
> > > find _ le ( [ 0 , 1 , 2 , 3 ] , 2.0)
* * 中文文档 * *
寻找最大的小于等于x的数 。""" | i = bisect . bisect_right ( array , x )
if i :
return array [ i - 1 ]
raise ValueError |
def create_csr ( cls , name , common_name , public_key_algorithm = 'rsa' , signature_algorithm = 'rsa_sha_512' , key_length = 4096 ) :
"""Create a certificate signing request .
: param str name : name of TLS Server Credential
: param str rcommon _ name : common name for certificate . An example
would be : " C... | json = { 'name' : name , 'info' : common_name , 'public_key_algorithm' : public_key_algorithm , 'signature_algorithm' : signature_algorithm , 'key_length' : key_length , 'certificate_state' : 'initial' }
return ElementCreator ( cls , json ) |
def gen_colors ( img ) :
"""Generate a colorscheme using Colorz .""" | # pylint : disable = not - callable
raw_colors = colorz . colorz ( img , n = 6 , bold_add = 0 )
return [ util . rgb_to_hex ( [ * color [ 0 ] ] ) for color in raw_colors ] |
def _transform_row ( self , row ) :
"""Transforms a Row into Python values .
: param row :
A ` ` common _ pb2 . Row ` ` object .
: returns :
A list of values casted into the correct Python types .
: raises :
NotImplementedError""" | tmp_row = [ ]
for i , column in enumerate ( row . value ) :
if column . has_array_value :
raise NotImplementedError ( 'array types are not supported' )
elif column . scalar_value . null :
tmp_row . append ( None )
else :
field_name , rep , mutate_to , cast_from = self . _column_data_... |
def _iter_member_elms ( self ) :
"""Generate each child of the ` ` < p : spTree > ` ` element that corresponds to
a shape , in the sequence they appear in the XML .""" | for shape_elm in self . _spTree . iter_shape_elms ( ) :
if self . _is_member_elm ( shape_elm ) :
yield shape_elm |
def setVersion ( self , date_issued , version_id = None ) :
"""Legacy function . . .
should use the other set _ * for version and date
as of 2016-10-20 used in :
dipper / sources / HPOAnnotations . py 139:
dipper / sources / CTD . py 99:
dipper / sources / BioGrid . py 100:
dipper / sources / MGI . py 2... | if date_issued is not None :
self . set_date_issued ( date_issued )
elif version_id is not None :
self . set_version_by_num ( version_id )
else :
LOG . error ( "date or version not set!" )
# TODO throw error
return
if version_id is not None :
self . set_version_by_num ( version_id )
else :
L... |
def adjustHSP ( self , hsp ) :
"""Adjust the read and subject start and end offsets in an HSP .
@ param hsp : a L { dark . hsp . HSP } or L { dark . hsp . LSP } instance .""" | reduction = self . _reductionForOffset ( min ( hsp . readStartInSubject , hsp . subjectStart ) )
hsp . readEndInSubject = hsp . readEndInSubject - reduction
hsp . readStartInSubject = hsp . readStartInSubject - reduction
hsp . subjectEnd = hsp . subjectEnd - reduction
hsp . subjectStart = hsp . subjectStart - reduction |
def check_for_missed_cleanup ( ) :
"""Check for TaskAttempts that were never cleaned up""" | if get_setting ( 'PRESERVE_ALL' ) :
return
from api . models . tasks import TaskAttempt
if get_setting ( 'PRESERVE_ON_FAILURE' ) :
for task_attempt in TaskAttempt . objects . filter ( status_is_running = False ) . filter ( status_is_cleaned_up = False ) . exclude ( status_is_failed = True ) :
task_attem... |
def stop ( name , kill = False , runas = None ) :
'''Stop a VM
: param str name :
Name / ID of VM to stop
: param bool kill :
Perform a hard shutdown
: param str runas :
The user that the prlctl command will be run as
Example :
. . code - block : : bash
salt ' * ' parallels . stop macvm runas = ma... | # Construct argument list
args = [ salt . utils . data . decode ( name ) ]
if kill :
args . append ( '--kill' )
# Execute command and return output
return prlctl ( 'stop' , args , runas = runas ) |
def create_lb_cookie_stickiness_policy ( self , cookie_expiration_period , lb_name , policy_name ) :
"""Generates a stickiness policy with sticky session lifetimes controlled
by the lifetime of the browser ( user - agent ) or a specified expiration
period . This policy can only be associated only with HTTP list... | params = { 'CookieExpirationPeriod' : cookie_expiration_period , 'LoadBalancerName' : lb_name , 'PolicyName' : policy_name , }
return self . get_status ( 'CreateLBCookieStickinessPolicy' , params ) |
def mpl_to_bokeh ( properties ) :
"""Utility to process style properties converting any
matplotlib specific options to their nearest bokeh
equivalent .""" | new_properties = { }
for k , v in properties . items ( ) :
if isinstance ( v , dict ) :
new_properties [ k ] = v
elif k == 's' :
new_properties [ 'size' ] = v
elif k == 'marker' :
new_properties . update ( markers . get ( v , { 'marker' : v } ) )
elif ( k == 'color' or k . endswi... |
def setup_app ( config ) :
'''Deprecated .''' | if isinstance ( config , str ) :
data = _deserialize ( config )
elif isinstance ( config , dict ) :
data = config
else :
raise ConfigError ( 'must provide a filename or dictionary' )
db_conn_data = data . pop ( 'db' , None )
app = App ( ** data )
if not db_conn_data :
return app
for name , conn_data in ... |
def utc ( self , year , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 ) :
"""Build a ` Time ` from a UTC calendar date .
You can either specify the date as separate components , or
provide a time zone aware Python datetime . The following two
calls are equivalent ( the ` ` utc ` ` time zone objec... | if isinstance ( year , datetime ) :
dt = year
tai = _utc_datetime_to_tai ( self . leap_dates , self . leap_offsets , dt )
elif isinstance ( year , date ) :
d = year
tai = _utc_date_to_tai ( self . leap_dates , self . leap_offsets , d )
elif hasattr ( year , '__len__' ) and isinstance ( year [ 0 ] , date... |
def parse_modeline ( code ) :
"""Parse params from file ' s modeline .
: return dict : Linter params .""" | seek = MODELINE_RE . search ( code )
if seek :
return dict ( v . split ( '=' ) for v in seek . group ( 1 ) . split ( ':' ) )
return dict ( ) |
def add_supporting_evidence ( self , evidence_line , evidence_type = None , label = None ) :
"""Add supporting line of evidence node to association id
: param evidence _ line : curie or iri , evidence line
: param evidence _ type : curie or iri , evidence type if available
: return : None""" | self . graph . addTriple ( self . association , self . globaltt [ 'has_supporting_evidence_line' ] , evidence_line )
if evidence_type is not None :
self . model . addIndividualToGraph ( evidence_line , label , evidence_type )
return |
def extrema ( self , x0 , y0 , w , h ) :
"""Returns the minimum and maximum values contained in a given area .
: param x0 : Starting x index .
: param y0 : Starting y index .
: param w : Width of the area to scan .
: param h : Height of the area to scan .
: return : Tuple containing the minimum and maximu... | minimum = 9223372036854775807
maximum = 0
for y in range ( y0 , y0 + h ) :
for x in range ( x0 , x0 + w ) :
value = self [ x , y ]
if value != self . filler :
minimum = min ( minimum , value )
maximum = max ( maximum , value )
return minimum , maximum |
def pixel_coords ( latlon , ground_width = 0 , mt = None , topleft = None , width = None ) :
'''return pixel coordinates in the map image for a ( lat , lon )''' | ( lat , lon ) = ( latlon [ 0 ] , latlon [ 1 ] )
return mt . coord_to_pixel ( topleft [ 0 ] , topleft [ 1 ] , width , ground_width , lat , lon ) |
def __make_request_method ( self , teststep_dict , entry_json ) :
"""parse HAR entry request method , and make teststep method .""" | method = entry_json [ "request" ] . get ( "method" )
if not method :
logging . exception ( "method missed in request." )
sys . exit ( 1 )
teststep_dict [ "request" ] [ "method" ] = method |
def _validate_int ( name , value , limits = ( ) , strip = '%' ) :
'''Validate the named integer within the supplied limits inclusive and
strip supplied unit characters''' | comment = ''
# Must be integral
try :
if isinstance ( value , string_types ) :
value = value . strip ( ' ' + strip )
value = int ( value )
except ( TypeError , ValueError ) :
comment += '{0} must be an integer ' . format ( name )
# Must be in range
else :
if len ( limits ) == 2 :
if valu... |
def geojson ( filename , color = 'b' , linewidth = 1 , fill = False , f_tooltip = None ) :
"""Draw features described in geojson format ( http : / / geojson . org / )
: param filename : filename of the geojson file
: param color : color for the shapes . If callable , it will be invoked for each feature , passin... | from geoplotlib . layers import GeoJSONLayer
_global_config . layers . append ( GeoJSONLayer ( filename , color = color , linewidth = linewidth , fill = fill , f_tooltip = f_tooltip ) ) |
def _validate_alias_command_level ( alias , command ) :
"""Make sure that if the alias is a reserved command , the command that the alias points to
in the command tree does not conflict in levels .
e . g . ' dns ' - > ' network dns ' is valid because dns is a level 2 command and network dns starts at level 1.
... | alias_collision_table = AliasManager . build_collision_table ( [ alias ] )
# Alias is not a reserved command , so it can point to any command
if not alias_collision_table :
return
command_collision_table = AliasManager . build_collision_table ( [ command ] )
alias_collision_levels = alias_collision_table . get ( al... |
def get_variables ( self , entity = None ) :
"""Gets all variables contained in a tax and benefit system .
: param < Entity subclass > entity : If set , returns only the variable defined for the given entity .
: returns : A dictionnary , indexed by variable names .
: rtype : dict""" | if not entity :
return self . variables
else :
return { variable_name : variable for variable_name , variable in self . variables . items ( ) # TODO - because entities are copied ( see constructor ) they can ' t be compared
if variable . entity . key == entity . key } |
def _add_match ( self , match_key , match_value ) :
"""Adds a match key / value""" | if match_key is None :
raise errors . NullArgument ( )
self . _query_terms [ match_key ] = str ( match_key ) + '=' + str ( match_value ) |
def delete_param ( context , provider , ** kwargs ) : # noqa pylint : disable = unused - argument
"""Delete SSM parameter .""" | parameter_name = kwargs . get ( 'parameter_name' )
if not parameter_name :
raise ValueError ( 'Must specify `parameter_name` for delete_param ' 'hook.' )
session = get_session ( provider . region )
ssm_client = session . client ( 'ssm' )
try :
ssm_client . delete_parameter ( Name = parameter_name )
except ssm_c... |
def main ( graph , * args ) :
"""Entry point for invoking Alembic ' s ` CommandLine ` .
Alembic ' s CLI defines its own argument parsing and command invocation ; we want
to use these directly but define configuration our own way . This function takes
the behavior of ` CommandLine . main ( ) ` and reinterprets... | migrations_dir = get_migrations_dir ( graph )
cli = CommandLine ( )
options = cli . parser . parse_args ( args if args else argv [ 1 : ] )
if not hasattr ( options , "cmd" ) :
cli . parser . error ( "too few arguments" )
if options . cmd [ 0 ] . __name__ == "init" :
cli . parser . error ( "Alembic 'init' comman... |
def rpc_get_namespace_blockchain_record ( self , namespace_id , ** con_info ) :
"""Return the namespace with the given namespace _ id
Return { ' status ' : True , ' record ' : . . . } on success
Return { ' error ' : . . . } on error""" | if not check_namespace ( namespace_id ) :
return { 'error' : 'Invalid name or namespace' , 'http_status' : 400 }
db = get_db_state ( self . working_dir )
ns = db . get_namespace ( namespace_id )
if ns is None : # maybe revealed ?
ns = db . get_namespace_reveal ( namespace_id )
db . close ( )
if ns is No... |
def import_from_nhmmer_table ( hmmout_path ) :
'''Generate new results object from the output of nhmmer search''' | # nhmmer format is
# qseqid queryname hmmfrom hmmto alifrom alito envfrom envto sqlen strand evalue bitscore bias description
# 0 2 4 5 6 7 8 9 10 11 12 13 14 15
res = HMMSearchResult ( )
res . fields = [ SequenceSearchResult . QUERY_ID_FIELD , SequenceSearchResult . HMM_NAME_FIELD , SequenceSearchResult . ALIGNMENT_LE... |
def _get_axis ( self , name_or_index : AxisIdentifier ) -> int :
"""Get a zero - based index of an axis and check its existence .""" | # TODO : Add unit test
if isinstance ( name_or_index , int ) :
if name_or_index < 0 or name_or_index >= self . ndim :
raise ValueError ( "No such axis, must be from 0 to {0}" . format ( self . ndim - 1 ) )
return name_or_index
elif isinstance ( name_or_index , str ) :
if name_or_index not in self . ... |
def databoxes ( ds , xscript = 0 , yscript = 1 , eyscript = None , exscript = None , g = None , plotter = xy_data , transpose = False , ** kwargs ) :
"""Plots the listed databox objects with the specified scripts .
ds list of databoxes
xscript script for x data
yscript script for y data
eyscript script for ... | if not _fun . is_iterable ( ds ) :
ds = [ ds ]
if 'xlabel' not in kwargs :
kwargs [ 'xlabel' ] = str ( xscript )
if 'ylabel' not in kwargs :
kwargs [ 'ylabel' ] = str ( yscript )
# First make sure everything is a list of scripts ( or None ' s )
if not _fun . is_iterable ( xscript ) :
xscript = [ xscript... |
def initialize_dendrites ( self ) :
"""Initialize all the dendrites of the neuron to a set of random connections""" | # Wipe any preexisting connections by creating a new connection matrix
self . dendrites = SM32 ( )
self . dendrites . reshape ( self . dim , self . num_dendrites )
for row in range ( self . num_dendrites ) :
synapses = numpy . random . choice ( self . dim , self . dendrite_length , replace = False )
for synapse... |
def calf ( self , spec ) :
"""Typical safe usage is this , which sets everything that could be
problematic up .
Requires the filename which everything will be produced to .""" | if not isinstance ( spec , Spec ) :
raise TypeError ( 'spec must be of type Spec' )
if not spec . get ( BUILD_DIR ) :
tempdir = realpath ( mkdtemp ( ) )
spec . advise ( CLEANUP , shutil . rmtree , tempdir )
build_dir = join ( tempdir , 'build' )
mkdir ( build_dir )
spec [ BUILD_DIR ] = build_dir... |
def hash ( self ) :
"""Calculate the hash for the block header . Note that this has the bytes
in the opposite order from how the header is usually displayed ( so the
long string of 00 bytes is at the end , not the beginning ) .""" | if not hasattr ( self , "__hash" ) :
self . __hash = self . _calculate_hash ( )
return self . __hash |
def whichchain ( atom ) :
"""Returns the residue number of an PyBel or OpenBabel atom .""" | atom = atom if not isinstance ( atom , Atom ) else atom . OBAtom
# Convert to OpenBabel Atom
return atom . GetResidue ( ) . GetChain ( ) if atom . GetResidue ( ) is not None else None |
def rho2sigma ( self , rho0 , Ra , Rs ) :
"""converts 3d density into 2d projected density parameter
: param rho0:
: param Ra :
: param Rs :
: return :""" | return np . pi * rho0 * Ra * Rs / ( Rs + Ra ) |
def rm ( name ) :
"""Remove an existing project and its container .""" | path = get_existing_project_path ( name )
click . confirm ( 'Are you sure you want to delete project %s?' % name , abort = True )
container_name = get_container_name ( name )
client = docker . Client ( )
try :
client . inspect_container ( container_name )
except docker . errors . NotFound :
pass
else :
prin... |
def _stmt_location_to_agents ( stmt , location ) :
"""Apply an event location to the Agents in the corresponding Statement .
If a Statement is in a given location we represent that by requiring all
Agents in the Statement to be in that location .""" | if location is None :
return
agents = stmt . agent_list ( )
for a in agents :
if a is not None :
a . location = location |
def rate_of_return ( period_ret , base_period ) :
"""Convert returns to ' one _ period _ len ' rate of returns : that is the value the
returns would have every ' one _ period _ len ' if they had grown at a steady
rate
Parameters
period _ ret : pd . DataFrame
DataFrame containing returns values with column... | period_len = period_ret . name
conversion_factor = ( pd . Timedelta ( base_period ) / pd . Timedelta ( period_len ) )
return period_ret . add ( 1 ) . pow ( conversion_factor ) . sub ( 1 ) |
def kalman_filter ( kalman_state , old_indices , coordinates , q , r ) :
'''Return the kalman filter for the features in the new frame
kalman _ state - state from last frame
old _ indices - the index per feature in the last frame or - 1 for new
coordinates - Coordinates of the features in the new frame .
q ... | assert isinstance ( kalman_state , KalmanState )
old_indices = np . array ( old_indices )
if len ( old_indices ) == 0 :
return KalmanState ( kalman_state . observation_matrix , kalman_state . translation_matrix )
# Cull missing features in old state and collect only matching coords
matching = old_indices != - 1
new... |
def alter ( self , tbl_properties = None ) :
"""Change setting and parameters of the table .
Parameters
tbl _ properties : dict , optional
Returns
None ( for now )""" | def _run_ddl ( ** kwds ) :
stmt = ddl . AlterTable ( self . _qualified_name , ** kwds )
return self . _execute ( stmt )
return self . _alter_table_helper ( _run_ddl , tbl_properties = tbl_properties ) |
def upload_file ( request ) :
'''Upload a Zip File Containing a single file containing media .''' | if request . method == 'POST' :
form = MediaForm ( request . POST , request . FILES )
if form . is_valid ( ) :
context_dict = { }
try :
context_dict [ 'copied_files' ] = update_media_file ( request . FILES [ 'zip_file' ] )
except Exception as e :
context_dict [ 'e... |
def _drop_no_label_results ( self , results , fh ) :
"""Writes ` results ` to ` fh ` minus those results associated with the
' no ' label .
: param results : results to be manipulated
: type results : file - like object
: param fh : output destination
: type fh : file - like object""" | results . seek ( 0 )
results = Results ( results , self . _tokenizer )
results . remove_label ( self . _no_label )
results . csv ( fh ) |
def get_user_group_perms ( user_or_group , obj ) :
"""Get permissins for user groups .
Based on guardian . core . ObjectPermissionChecker .""" | user , group = get_identity ( user_or_group )
if user and not user . is_active :
return [ ] , [ ]
user_model = get_user_model ( )
ctype = ContentType . objects . get_for_model ( obj )
group_model = get_group_obj_perms_model ( obj )
group_rel_name = group_model . permission . field . related_query_name ( )
if user :... |
def record ( self , attr , value ) :
"""Add a new value to the given column for the current
epoch .""" | msg = "Call new_epoch before recording for the first time."
if not self :
raise ValueError ( msg )
self [ - 1 ] [ attr ] = value |
def deconstruct ( self ) :
"""Deconstruct operation .""" | return ( self . __class__ . __name__ , [ ] , { 'process' : self . process , 'field' : self . _raw_field , 'schema' : self . schema , 'default' : self . default , } ) |
def join_all ( self , * parts ) :
"""Join all parts with domain . Example domain : https : / / www . python . org
: param parts : Other parts , example : " / doc " , " / py27"
: return : url""" | url = util . join_all ( self . domain , * parts )
return url |
def remove_child_families ( self , family_id ) :
"""Removes all children from a family .
arg : family _ id ( osid . id . Id ) : the ` ` Id ` ` of a family
raise : NotFound - ` ` family _ id ` ` not in hierarchy
raise : NullArgument - ` ` family _ id ` ` is ` ` null ` `
raise : OperationFailed - unable to co... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . remove _ child _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . remove_child_catalogs ( catalog_id = family_id )
return self . _hierarchy_session . remove_children ( id_ = family_id ) |
def random_product ( * args , repeat = 1 ) :
"Random selection from itertools . product ( * args , * * kwds )" | pools = [ tuple ( pool ) for pool in args ] * repeat
return tuple ( random . choice ( pool ) for pool in pools ) |
def _run_vqsr ( in_file , ref_file , vrn_files , sensitivity_cutoff , filter_type , data ) :
"""Run variant quality score recalibration .""" | cutoffs = [ "100.0" , "99.99" , "99.98" , "99.97" , "99.96" , "99.95" , "99.94" , "99.93" , "99.92" , "99.91" , "99.9" , "99.8" , "99.7" , "99.6" , "99.5" , "99.0" , "98.0" , "90.0" ]
if sensitivity_cutoff not in cutoffs :
cutoffs . append ( sensitivity_cutoff )
cutoffs . sort ( )
broad_runner = broad . runner_... |
def script_post_save ( model , os_path , contents_manager , ** kwargs ) :
"""convert notebooks to Python script after save with nbconvert
replaces ` ipython notebook - - script `""" | from nbconvert . exporters . script import ScriptExporter
if model [ 'type' ] != 'notebook' :
return
global _script_exporter
if _script_exporter is None :
_script_exporter = ScriptExporter ( parent = contents_manager )
log = contents_manager . log
base , ext = os . path . splitext ( os_path )
# py _ fname = bas... |
def build ( self ) :
"""Build the full HTML source .""" | if self . is_built ( ) : # pragma : no cover
return
with _wait_signal ( self . loadFinished , 20 ) :
self . rebuild ( )
self . _built = True |
def iwslt_dataset ( directory = 'data/iwslt/' , train = False , dev = False , test = False , language_extensions = [ 'en' , 'de' ] , train_filename = '{source}-{target}/train.{source}-{target}.{lang}' , dev_filename = '{source}-{target}/IWSLT16.TED.tst2013.{source}-{target}.{lang}' , test_filename = '{source}-{target}/... | if len ( language_extensions ) != 2 :
raise ValueError ( "`language_extensions` must be two language extensions " "['en'|'de'|'it'|'ni'|'ro'] to load." )
# Format Filenames
source , target = tuple ( language_extensions )
check_files = [ s . format ( source = source , target = target ) for s in check_files ]
url = u... |
def support_false_negative_count ( m , m_hat ) :
"""Count the number of false negative support elements in
m _ hat in one triangle , not including the diagonal .""" | m_nnz , m_hat_nnz , intersection_nnz = _nonzero_intersection ( m , m_hat )
return int ( ( m_nnz - intersection_nnz ) / 2.0 ) |
def getScreenBounds ( self , screenId ) :
"""Returns the screen size of the specified monitor ( 0 being the main monitor ) .""" | screen_details = self . getScreenDetails ( )
if not isinstance ( screenId , int ) or screenId < - 1 or screenId >= len ( screen_details ) :
raise ValueError ( "Invalid screen ID" )
if screenId == - 1 : # -1 represents the entire virtual screen
return self . _getVirtualScreenRect ( )
return screen_details [ scre... |
def set_signatures ( library , errcheck = None ) :
"""Set the signatures of most visa functions in the library .
All instrumentation related functions are specified here .
: param library : the visa library wrapped by ctypes .
: type library : ctypes . WinDLL or ctypes . CDLL
: param errcheck : error checki... | # Somehow hasattr ( library , ' _ functions ' ) segfaults in cygwin ( See # 131)
if '_functions' not in dir ( library ) :
library . _functions = [ ]
library . _functions_failed = [ ]
def _applier ( restype , errcheck_ ) :
def _internal ( function_name , argtypes , required = False ) :
try :
... |
def _get_access_token ( self , code , ** params ) :
"""Fetch an access token with the provided ` code ` .""" | params . update ( { 'code' : code , 'client_id' : self . client_id , 'client_secret' : self . secret , 'redirect_uri' : self . get_callback_url ( ) , } )
logger . debug ( "Params: %s" , params )
resp , content = self . request_access_token ( params = params )
content = smart_unicode ( content )
logger . debug ( "Status... |
def labels ( self ) :
"""Retrieve or set labels assigned to this bucket .
See
https : / / cloud . google . com / storage / docs / json _ api / v1 / buckets # labels
. . note : :
The getter for this property returns a dict which is a * copy *
of the bucket ' s labels . Mutating that dict has no effect unle... | labels = self . _properties . get ( "labels" )
if labels is None :
return { }
return copy . deepcopy ( labels ) |
def guess_io_type ( obj ) :
"""Guess input or output type of ' obj ' .
: param obj : a path string , a pathlib . Path or a file / file - like object
: return : IOInfo type defined in anyconfig . globals . IOI _ TYPES
> > > apath = " / path / to / a _ conf . ext "
> > > assert guess _ io _ type ( apath ) = =... | if obj is None :
return IOI_NONE
if anyconfig . utils . is_path ( obj ) :
return IOI_PATH_STR
if anyconfig . utils . is_path_obj ( obj ) :
return IOI_PATH_OBJ
if anyconfig . utils . is_file_stream ( obj ) :
return IOI_STREAM
raise ValueError ( "Unknown I/O type object: %r" % obj ) |
def embedding_lookup ( x , means , num_blocks , block_v_size , bottleneck_kind = "dvq" , random_top_k = 1 , soft_em = False , num_samples = 1 , do_hard_gumbel_softmax = False , temperature_warmup_steps = 150000 , num_flows = 0 , approximate_gs_entropy = False , sum_over_latents = False ) :
"""Compute nearest neighb... | if bottleneck_kind == "gumbel-softmax-dvq" :
x_means_hot , neg_q_entropy = gumbel_softmax_nearest_neighbor_dvq ( x , means , block_v_size , hard = do_hard_gumbel_softmax , num_samples = num_samples , temperature_warmup_steps = temperature_warmup_steps , num_flows = num_flows , approximate_gs_entropy = approximate_g... |
def filter_taxa ( fasta_path : 'path to fasta input' , taxids : 'comma delimited list of taxon IDs' , unclassified : 'pass sequences unclassified at superkingdom level >(0)' = False , discard : 'discard specified taxa' = False , warnings : 'show warnings' = False ) :
'''Customisable filtering of tictax flavoured fa... | configure_warnings ( warnings )
records = SeqIO . parse ( fasta_path , 'fasta' )
filtered_records = tictax . filter_taxa ( records , map ( int , taxids . split ( ',' ) ) , unclassified , discard )
SeqIO . write ( filtered_records , sys . stdout , 'fasta' ) |
def get_auth_params_from_request ( request ) :
"""Extracts properties needed by novaclient call from the request object .
These will be used to memoize the calls to novaclient .""" | return ( request . user . username , request . user . token . id , request . user . tenant_id , request . user . token . project . get ( 'domain_id' ) , base . url_for ( request , 'compute' ) , base . url_for ( request , 'identity' ) ) |
def disable_distribution ( region = None , key = None , keyid = None , profile = None , ** kwargs ) :
'''Set a CloudFront distribution to be disabled .
Id
Id of the distribution to update .
region
Region to connect to .
key
Secret key to use .
keyid
Access key to use .
profile
Dict , or pillar k... | retries = 10
sleep = 6
kwargs = { k : v for k , v in kwargs . items ( ) if not k . startswith ( '_' ) }
authargs = { 'region' : region , 'key' : key , 'keyid' : keyid , 'profile' : profile }
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
Id = kwargs . get ( 'Id' )
current = get_dis... |
def __write_list_tmpl ( html_tpl ) :
'''doing for directory .''' | out_dir = os . path . join ( os . getcwd ( ) , CRUD_PATH , 'infolist' )
if os . path . exists ( out_dir ) :
pass
else :
os . mkdir ( out_dir )
# for var _ name in VAR _ NAMES :
for var_name , bl_val in SWITCH_DICS . items ( ) :
if var_name . startswith ( 'dic_' ) :
outfile = os . path . join ( out_d... |
def copyNodeList ( self ) :
"""Do a recursive copy of the node list . Use
xmlDocCopyNodeList ( ) if possible to ensure string interning .""" | ret = libxml2mod . xmlCopyNodeList ( self . _o )
if ret is None :
raise treeError ( 'xmlCopyNodeList() failed' )
__tmp = xmlNode ( _obj = ret )
return __tmp |
def mergeWCS ( default_wcs , user_pars ) :
"""Merges the user specified WCS values given as dictionary derived from
the input configObj object with the output PyWCS object computed
using distortion . output _ wcs ( ) .
The user _ pars dictionary needs to have the following set of keys : :
user _ pars = { ' ... | # Start by making a copy of the input WCS . . .
outwcs = default_wcs . deepcopy ( )
# If there are no user set parameters , just return a copy of
# the original WCS :
if all ( [ upar is None for upar in user_pars . values ( ) ] ) :
return outwcs
if _check_custom_WCS_pars ( 'ra' , 'dec' , user_pars ) :
_crval = ... |
def _tty_stdio ( cls , env ) :
"""Handles stdio redirection in the case of all stdio descriptors being the same tty .""" | # If all stdio is a tty , there ' s only one logical I / O device ( the tty device ) . This happens to
# be addressable as a file in OSX and Linux , so we take advantage of that and directly open the
# character device for output redirection - eliminating the need to directly marshall any
# interactive stdio back / for... |
def create_table ( self , table_name , schema , provisioned_throughput ) :
"""Add a new table to your account . The table name must be unique
among those associated with the account issuing the request .
This request triggers an asynchronous workflow to begin creating
the table . When the workflow is complete... | data = { 'TableName' : table_name , 'KeySchema' : schema , 'ProvisionedThroughput' : provisioned_throughput }
json_input = json . dumps ( data )
response_dict = self . make_request ( 'CreateTable' , json_input )
return response_dict |
def tag_mode ( self , tag_mode ) :
"""Sets the tag _ mode of this ChartSettings .
For the tabular view , which mode to use to determine which point tags to display # noqa : E501
: param tag _ mode : The tag _ mode of this ChartSettings . # noqa : E501
: type : str""" | allowed_values = [ "all" , "top" , "custom" ]
# noqa : E501
if tag_mode not in allowed_values :
raise ValueError ( "Invalid value for `tag_mode` ({0}), must be one of {1}" # noqa : E501
. format ( tag_mode , allowed_values ) )
self . _tag_mode = tag_mode |
def from_path ( cls , path ) :
"""Takes a path and returns a File object with the path as the PFN .""" | urlparts = urlparse . urlsplit ( path )
site = 'nonlocal'
if ( urlparts . scheme == '' or urlparts . scheme == 'file' ) :
if os . path . isfile ( urlparts . path ) :
path = os . path . abspath ( urlparts . path )
path = urlparse . urljoin ( 'file:' , urllib . pathname2url ( path ) )
site = '... |
def to_numpy_bins ( bins ) -> np . ndarray :
"""Convert physt bin format to numpy edges .
Parameters
bins : array _ like
1 - D ( n ) or 2 - D ( n , 2 ) array of edges
Returns
edges : all edges""" | bins = np . asarray ( bins )
if bins . ndim == 1 : # Already in the proper format
return bins
if not is_consecutive ( bins ) :
raise RuntimeError ( "Cannot create numpy bins from inconsecutive edges" )
return np . concatenate ( [ bins [ : 1 , 0 ] , bins [ : , 1 ] ] ) |
def request_patch ( self , * args , ** kwargs ) :
"""Maintains the existing api for Session . request .
Used by all of the higher level methods , e . g . Session . get .
The background _ callback param allows you to do some processing on the
response in the background , e . g . call resp . json ( ) so that js... | func = sup = super ( FuturesSession , self ) . request
background_callback = kwargs . pop ( 'background_callback' , None )
if background_callback :
def wrap ( * args_ , ** kwargs_ ) :
resp = sup ( * args_ , ** kwargs_ )
# Patch the closure to return the callback .
return background_callback ... |
def get_per_pixel_mean ( names = ( 'train' , 'test' , 'extra' ) ) :
"""Args :
names ( tuple [ str ] ) : names of the dataset split
Returns :
a 32x32x3 image , the mean of all images in the given datasets""" | for name in names :
assert name in [ 'train' , 'test' , 'extra' ] , name
images = [ SVHNDigit ( x ) . X for x in names ]
return np . concatenate ( tuple ( images ) ) . mean ( axis = 0 ) |
def instruction_ROL_register ( self , opcode , register ) :
"""Rotate accumulator left""" | a = register . value
r = self . ROL ( a )
# log . debug ( " $ % x ROL % s value $ % x < < 1 | Carry = $ % x " % (
# self . program _ counter ,
# register . name , a , r
register . set ( r ) |
def token_to_id ( self , token ) :
"""Get the token _ id of given token .
Args :
token ( str ) : token from vocabulary .
Returns :
int : int id of token .""" | token = self . process_token ( token )
return self . _token2id . get ( token , len ( self . _token2id ) - 1 ) |
def _findSwiplLin ( ) :
"""This function uses several heuristics to guess where SWI - Prolog is
installed in Linuxes .
: returns :
A tuple of ( path to the swipl so , path to the resource file )
: returns type :
( { str , None } , { str , None } )""" | # Maybe the exec is on path ?
( path , swiHome ) = _findSwiplFromExec ( )
if path is not None :
return ( path , swiHome )
# If it is not , use find _ library
path = _findSwiplPathFromFindLib ( )
if path is not None :
return ( path , swiHome )
# Our last try : some hardcoded paths .
paths = [ '/lib' , '/usr/lib'... |
def user_names_like ( cls , user_name , db_session = None ) :
"""fetch users with similar names using LIKE clause
: param user _ name :
: param db _ session :
: return :""" | db_session = get_db_session ( db_session )
query = db_session . query ( cls . model )
query = query . filter ( sa . func . lower ( cls . model . user_name ) . like ( ( user_name or "" ) . lower ( ) ) )
query = query . order_by ( cls . model . user_name )
# q = q . options ( sa . orm . eagerload ( ' groups ' ) )
return ... |
def remove ( self ) :
"""Removes the subscription .""" | self . logger . debug ( 'Remove subscription from server...' )
data = { 'command' : 'unsubscribe' , 'identifier' : self . _identifier_string ( ) }
self . connection . send ( data )
self . state = 'unsubscribed' |
def folderitem ( self , obj , item , index ) :
"""Service triggered each time an item is iterated in folderitems .
The use of this service prevents the extra - loops in child objects .
: obj : the instance of the class to be foldered
: item : dict containing the properties of the object to be used by
the te... | # ensure we have an object and not a brain
obj = api . get_object ( obj )
url = api . get_url ( obj )
title = api . get_title ( obj )
keyword = obj . getKeyword ( )
# get the category
if self . show_categories_enabled ( ) :
category = obj . getCategoryTitle ( )
if category not in self . categories :
sel... |
def get_task ( task_id , completed = True ) :
"""Get a task by task id where a task _ id is required .
: param task _ id : task ID
: type task _ id : str
: param completed : include completed tasks ?
: type completed : bool
: return : a task
: rtype : obj""" | tasks = get_tasks ( task_id = task_id , completed = completed )
if len ( tasks ) == 0 :
return None
assert len ( tasks ) == 1 , 'get_task should return at max 1 task for a task id'
return tasks [ 0 ] |
def event_loop ( self ) :
"""Run the event loop once .""" | if hasattr ( self . loop , '._run_once' ) :
self . loop . _thread_id = threading . get_ident ( )
try :
self . loop . _run_once ( )
finally :
self . loop . _thread_id = None
else :
self . loop . call_soon ( self . loop . stop )
self . loop . run_forever ( ) |
def add ( repo_path , dest_path ) :
'''Registers a git repository with homely so that it will run its ` HOMELY . py `
script on each invocation of ` homely update ` . ` homely add ` also immediately
executes a ` homely update ` so that the dotfiles are installed straight
away . If the git repository is hosted... | mkcfgdir ( )
try :
repo = getrepohandler ( repo_path )
except NotARepo as err :
echo ( "ERROR: {}: {}" . format ( ERR_NOT_A_REPO , err . repo_path ) )
sys . exit ( 1 )
# if the repo isn ' t on disk yet , we ' ll need to make a local clone of it
if repo . isremote :
localrepo , needpull = addfromremote (... |
def parse_file ( self , inputstring , addhash = True ) :
"""Parse file code .""" | if addhash :
use_hash = self . genhash ( False , inputstring )
else :
use_hash = None
return self . parse ( inputstring , self . file_parser , { "nl_at_eof_check" : True } , { "header" : "file" , "use_hash" : use_hash } ) |
def claim ( self , ttl , grace , count = None ) :
"""Claims up to ` count ` unclaimed messages from this queue . If count is
not specified , the default is to claim 10 messages .
The ` ttl ` parameter specifies how long the server should wait before
releasing the claim . The ttl value MUST be between 60 and 4... | if count is None :
qs = ""
else :
qs = "?limit=%s" % count
uri = "/%s%s" % ( self . uri_base , qs )
body = { "ttl" : ttl , "grace" : grace , }
resp , resp_body = self . api . method_post ( uri , body = body )
if resp . status_code == 204 : # Nothing available to claim
return None
# Get the claim ID from the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.