signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def transform ( self , y ) :
"""Transform features per specified math function .
: param y :
: return :""" | if isinstance ( y , pd . DataFrame ) :
x = y . ix [ : , 0 ]
y = y . ix [ : , 1 ]
else :
x = y [ : , 0 ]
y = y [ : , 1 ]
if self . transform_type == 'add' :
return pd . DataFrame ( np . add ( x , y ) )
elif self . transform_type == 'sub' :
return pd . DataFrame ( np . subtract ( x , y ) )
elif se... |
def get_full_delta_pal ( PTRMS , PTRM_Checks , NRM , y_err , y_mean , b , start , end , y_segment ) :
"""input : PTRMS , PTRM _ Checks , NRM , y _ err , y _ mean , b , start , end , y _ segment
runs full sequence necessary to get delta _ pal""" | # print " - - - - - "
# print " calling get _ full _ delta _ pal in lib "
# return 0
PTRMS_cart , checks , TRM_1 = get_delta_pal_vectors ( PTRMS , PTRM_Checks , NRM )
# print " PTRMS _ Cart " , PTRMS _ cart
diffs , C = get_diffs ( PTRMS_cart , checks , PTRMS , PTRM_Checks )
# print " C " , C
TRM_star , x_star = get_TRM... |
def skew_y ( self , y ) :
"""Skew element along the y - axis by the given angle .
Parameters
y : float
y - axis skew angle in degrees""" | self . root . set ( "transform" , "%s skewY(%f)" % ( self . root . get ( "transform" ) or '' , y ) )
return self |
def liftover_cpra ( self , chromosome , position , verbose = False ) :
"""Given chromosome , position in 1 - based co - ordinates ,
This will use pyliftover to liftover a CPRA , will return a ( c , p ) tuple or raise NonUniqueLiftover if no unique
and strand maintaining liftover is possible
: param chromosome... | chromosome = str ( chromosome )
position = int ( position )
# Perform the liftover lookup , shift the position by 1 as pyliftover deals in 0 - based co - ords
new = self . liftover . convert_coordinate ( chromosome , position - 1 )
# This has to be here as new will be NoneType when the chromosome doesn ' t exist in the... |
def create_from_tuple ( cls , tube , the_tuple ) :
"""Create task from tuple .
Returns ` Task ` instance .""" | if the_tuple is None :
return
if not the_tuple . rowcount :
raise Queue . ZeroTupleException ( "Error creating task" )
row = the_tuple [ 0 ]
return cls ( tube , task_id = row [ 0 ] , state = row [ 1 ] , data = row [ 2 ] ) |
def _make_request ( self , opener , request , timeout = None ) :
"""Make the API call and return the response . This is separated into
it ' s own function , so we can mock it easily for testing .
: param opener :
: type opener :
: param request : url payload to request
: type request : urllib . Request ob... | timeout = timeout or self . timeout
try :
return opener . open ( request , timeout = timeout )
except HTTPError as err :
exc = handle_error ( err )
exc . __cause__ = None
raise exc |
def _index_fs ( self ) :
"""Returns a deque object full of local file system items .
: returns : ` ` deque ` `""" | indexed_objects = self . _return_deque ( )
directory = self . job_args . get ( 'directory' )
if directory :
indexed_objects = self . _return_deque ( deque = indexed_objects , item = self . _drectory_local_files ( directory = directory ) )
object_names = self . job_args . get ( 'object' )
if object_names :
index... |
def _resources ( p ) :
"""Callback func to display provider resources""" | if p . resources :
click . echo ( "," . join ( p . resources ) )
else :
click . echo ( f"Provider '{p.name}' does not have resource helpers" ) |
def lost_passwd ( self , data ) :
"""Send a reset link to user to recover its password""" | error = False
msg = ""
# Check input format
email_re = re . compile ( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot - atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted - string
r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$' , re . I... |
def load_yaml_file ( file_path : str ) :
"""Load a YAML file from path""" | with codecs . open ( file_path , 'r' ) as f :
return yaml . safe_load ( f ) |
def _write_init_models ( self , filenames ) :
"""Write init file
Args :
filenames ( dict ) : dict of filename and classes""" | self . write ( destination = self . output_directory , filename = "__init__.py" , template_name = "__init_model__.py.tpl" , filenames = self . _prepare_filenames ( filenames ) , class_prefix = self . _class_prefix , product_accronym = self . _product_accronym , header = self . header_content ) |
def set_cookie ( self , name , value , secret = None , digestmod = hashlib . sha256 , ** options ) :
"""Create a new cookie or replace an old one . If the ` secret ` parameter is
set , create a ` Signed Cookie ` ( described below ) .
: param name : the name of the cookie .
: param value : the value of the coo... | if not self . _cookies :
self . _cookies = SimpleCookie ( )
# To add " SameSite " cookie support .
Morsel . _reserved [ 'same-site' ] = 'SameSite'
if secret :
if not isinstance ( value , basestring ) :
depr ( 0 , 13 , "Pickling of arbitrary objects into cookies is " "deprecated." , "Only store strings i... |
def holiday_day ( self , value = None ) :
"""Corresponds to IDD Field ` holiday _ day `
Args :
value ( str ) : value for IDD Field ` holiday _ day `
if ` value ` is None it will not be checked against the
specification and is assumed to be a missing value
Raises :
ValueError : if ` value ` is not a vali... | if value is not None :
try :
value = str ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type str ' 'for field `holiday_day`' . format ( value ) )
if ',' in value :
raise ValueError ( 'value should not contain a comma ' 'for field `holiday_day`' )
self . _hol... |
def new_metric ( name , class_ , * args , ** kwargs ) :
"""Create a new metric of the given class .
Raise DuplicateMetricError if the given name has been already registered before
Internal function - use " new _ < type > instead " """ | with LOCK :
try :
item = REGISTRY [ name ]
except KeyError :
item = REGISTRY [ name ] = class_ ( * args , ** kwargs )
return item
raise DuplicateMetricError ( "Metric {} already exists of type {}" . format ( name , type ( item ) . __name__ ) ) |
def get_custom_view_details ( name , auth , url ) :
"""function requires no input and returns a list of dictionaries of custom views from an HPE IMC . Optional name
argument will return only the specified view .
: param name : str containing the name of the desired custom view
: param auth : requests auth obj... | view_id = get_custom_views ( auth , url , name = name ) [ 0 ] [ 'symbolId' ]
get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str ( view_id )
f_url = url + get_custom_view_details_url
r = requests . get ( f_url , auth = auth , headers = HEADERS )
# creates the URL using the payload variable as the content... |
def _parse_dates ( self , prop = DATES ) :
"""Creates and returns a Date Types data structure parsed from the metadata""" | return parse_dates ( self . _xml_tree , self . _data_structures [ prop ] ) |
def _get_session ( self ) :
"""Create session as needed .
. . note : :
Caller is responsible for cleaning up the session after
all partitions have been processed .""" | if self . _session is None :
session = self . _session = self . _database . session ( )
session . create ( )
return self . _session |
def attempt_connection ( self ) :
"""Establish a multicast connection - uses 2 sockets ( one for sending , the other for receiving )""" | self . socket = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP )
self . socket . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_TTL , 2 )
self . receiver_socket = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP )
self . receiver_socket . setsock... |
def _next_lowest_integer ( group_keys ) :
"""returns the lowest available integer in a set of dict keys""" | try : # TODO Replace with max default value when dropping compatibility with Python < 3.4
largest_int = max ( [ int ( val ) for val in group_keys if _is_int ( val ) ] )
except :
largest_int = 0
return largest_int + 1 |
def ConfigSectionMap ( Config , section ) :
"""Read a specific section from a ConfigParser ( ) object and return
a dict ( ) of all key - value pairs in that section""" | cfg = { }
options = Config . options ( section )
for option in options :
try :
cfg [ option ] = Config . get ( section , option )
if cfg [ option ] == - 1 :
logging . debug ( "skip: {0}" . format ( option ) )
except :
logging . debug ( "exception on {0}!" . format ( option ) ... |
def me ( access_code : str ) -> tuple :
"""Connect to a google account and get all personal info ( profile and the primary email ) .""" | auth_info = login ( access_code )
headers = HEADERS . copy ( )
headers [ "Authorization" ] = "Bearer {}" . format ( auth_info . access_token )
user = get_user_profile ( headers = headers )
# emails = get _ user _ emails ( headers = headers )
# primary _ email = next ( filter ( lambda x : x . is _ primary , emails ) )
#... |
def merge_dicts ( * args ) :
r"""add / concatenate / union / join / merge / combine dictionaries
Copies the first dictionary given and then repeatedly calls update using
the rest of the dicts given in args . Duplicate keys will receive the last
value specified the list of dictionaries .
Returns :
dict : m... | iter_ = iter ( args )
mergedict_ = six . next ( iter_ ) . copy ( )
for dict_ in iter_ :
mergedict_ . update ( dict_ )
return mergedict_ |
def write ( self , outfile ) :
"""Write the livetime cube to a FITS file .""" | hdu_pri = fits . PrimaryHDU ( )
hdu_exp = self . _create_exp_hdu ( self . data )
hdu_exp . name = 'EXPOSURE'
hdu_exp_wt = self . _create_exp_hdu ( self . _data_wt )
hdu_exp_wt . name = 'WEIGHTED_EXPOSURE'
cols = [ Column ( name = 'CTHETA_MIN' , dtype = 'f4' , data = self . costh_edges [ : - 1 ] [ : : - 1 ] ) , Column (... |
def edit ( self , name , mark = False ) :
"""Edit this file or directory
: param str name : new name for this entry
: param bool mark : whether to bookmark this entry""" | self . api . edit ( self , name , mark ) |
def getRequiredNodes ( self ) :
"""Returns a dict from node shape to number of nodes required to run the packed jobs .""" | return { nodeShape : len ( self . nodeReservations [ nodeShape ] ) for nodeShape in self . nodeShapes } |
def check_requirements ( dist , attr , value ) :
"""Verify that install _ requires is a valid requirements list""" | try :
list ( pkg_resources . parse_requirements ( value ) )
except ( TypeError , ValueError ) :
raise DistutilsSetupError ( "%r must be a string or list of strings " "containing valid project/version requirement specifiers" % ( attr , ) ) |
def commit_input_confirmed ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
commit = ET . Element ( "commit" )
config = commit
input = ET . SubElement ( commit , "input" )
confirmed = ET . SubElement ( input , "confirmed" )
callback = kwargs . pop ( 'callback' , self . _callback )
return callback ( config ) |
def _get_baremetal_switch_info ( self , link_info ) :
"""Get switch _ info dictionary from context .""" | try :
switch_info = link_info [ 'switch_info' ]
if not isinstance ( switch_info , dict ) :
switch_info = jsonutils . loads ( switch_info )
except Exception as e :
LOG . error ( "switch_info can't be decoded: %(exp)s" , { "exp" : e } )
switch_info = { }
return switch_info |
def setup_logging ( ) :
"""Sets up the internal logging mechanism , i . e . , it creates the : py : attr : ` console _ handler ` , sets
its formatting , and mounts on on the main ` ` " law " ` ` logger . It also sets the levels of all
loggers that are given in the law config .""" | global console_handler
# make sure logging is setup only once
if console_handler :
return
# set the handler of the law root logger
console_handler = logging . StreamHandler ( )
console_handler . setFormatter ( LogFormatter ( ) )
logging . getLogger ( "law" ) . addHandler ( console_handler )
# set levels for all log... |
def _AssTuple ( self , t ) :
"""Tuple on left hand side of an expression .""" | # _ write each elements , separated by a comma .
for element in t . nodes [ : - 1 ] :
self . _dispatch ( element )
self . _write ( ", " )
# Handle the last one without writing comma
last_element = t . nodes [ - 1 ]
self . _dispatch ( last_element ) |
def _warn_about_problematic_credentials ( credentials ) :
"""Determines if the credentials are problematic .
Credentials from the Cloud SDK that are associated with Cloud SDK ' s project
are problematic because they may not have APIs enabled and have limited
quota . If this is the case , warn about it .""" | from google . auth import _cloud_sdk
if credentials . client_id == _cloud_sdk . CLOUD_SDK_CLIENT_ID :
warnings . warn ( _CLOUD_SDK_CREDENTIALS_WARNING ) |
def dump ( d , fmt = 'json' , stream = None ) :
"""Serialize structured data into a stream in JSON , YAML , or LHA format .
If stream is None , return the produced string instead .
Parameters :
- fmt : should be ' json ' ( default ) , ' yaml ' , or ' lha '
- stream : if None , return string""" | if fmt == 'json' :
return _dump_json ( d , stream = stream )
elif fmt == 'yaml' :
return yaml . dump ( d , stream )
elif fmt == 'lha' :
s = _dump_lha ( d )
if stream is None :
return s
else :
return stream . write ( s ) |
def update ( self , labels , preds , masks = None ) : # pylint : disable = arguments - differ
"""Updates the internal evaluation result .
Parameters
labels : list of ` NDArray `
The labels of the data with class indices as values , one per sample .
preds : list of ` NDArray `
Prediction values for samples... | labels , preds = check_label_shapes ( labels , preds , True )
masks = [ None ] * len ( labels ) if masks is None else masks
for label , pred_label , mask in zip ( labels , preds , masks ) :
if pred_label . shape != label . shape : # TODO ( haibin ) topk does not support fp16 . Issue tracked at :
# https : / / g... |
def gene_panel ( self , ax , feature ) :
"""Plots gene models on an Axes .
Queries the database
: param ax : matplotlib . Axes object
: param feature : pybedtools . Interval""" | from gffutils . contrib . plotting import Gene
extent = [ feature . start , feature . stop ]
nearby_genes = self . db . region ( ( feature . chrom , feature . start , feature . stop ) , featuretype = 'gene' )
ybase = 0
ngenes = 0
for nearby_gene in nearby_genes :
ngenes += 1
extent . extend ( [ nearby_gene . st... |
def add_ClientData ( self ) :
"""The user may type in :
GET / HTTP / 1.1 \r \n Host : testserver . com \r \n \r \n
Special characters are handled so that it becomes a valid HTTP request .""" | if not self . data_to_send :
data = six . moves . input ( ) . replace ( '\\r' , '\r' ) . replace ( '\\n' , '\n' ) . encode ( )
# noqa : E501
else :
data = self . data_to_send . pop ( )
if data == b"quit" :
return
if self . linebreak :
data += b"\n"
self . add_record ( )
self . add_msg ( TLSApplicati... |
def download_mission ( ) :
"""Downloads the current mission and returns it in a list .
It is used in save _ mission ( ) to get the file information to save .""" | print ( " Download mission from vehicle" )
missionlist = [ ]
cmds = vehicle . commands
cmds . download ( )
cmds . wait_ready ( )
for cmd in cmds :
missionlist . append ( cmd )
return missionlist |
def _handleDecodeHextileSubrectsColoured ( self , block , bg , color , subrects , x , y , width , height , tx , ty , tw , th ) :
"""subrects with their own color""" | sz = self . bypp + 2
pos = 0
end = len ( block )
while pos < end :
pos2 = pos + self . bypp
color = block [ pos : pos2 ]
xy = ord ( block [ pos2 ] )
wh = ord ( block [ pos2 + 1 ] )
sx = xy >> 4
sy = xy & 0xf
sw = ( wh >> 4 ) + 1
sh = ( wh & 0xf ) + 1
self . fillRectangle ( tx + sx , ... |
def bbox_str ( bbox , pad = 4 , sep = ', ' ) :
r"""makes a string from an integer bounding box""" | if bbox is None :
return 'None'
fmtstr = sep . join ( [ '%' + six . text_type ( pad ) + 'd' ] * 4 )
return '(' + fmtstr % tuple ( bbox ) + ')' |
def xoscmounts ( host_mount ) :
"""Cross OS compatible mount dirs""" | callback_lower_drive_letter = lambda pat : pat . group ( 1 ) . lower ( )
host_mount = re . sub ( r"^([a-zA-Z])\:" , callback_lower_drive_letter , host_mount )
host_mount = re . sub ( r"^([a-z])" , "//\\1" , host_mount )
host_mount = re . sub ( r"\\" , "/" , host_mount )
return host_mount |
def steps ( self , start , end ) :
"""Get the maximum number of steps the driver needs for a transition .
: param start : The start value as uniform pwm value ( 0.0-1.0 ) .
: param end : The end value as uniform pwm value ( 0.0-1.0 ) .
: return : The maximum number of steps .""" | if not 0 <= start <= 1 :
raise ValueError ( 'Values must be between 0 and 1.' )
if not 0 <= end <= 1 :
raise ValueError ( 'Values must be between 0 and 1.' )
raw_start = self . _to_single_raw_pwm ( start )
raw_end = self . _to_single_raw_pwm ( end )
return abs ( raw_start - raw_end ) |
def event_listeners ( self ) :
"""List of registered event listeners .""" | return ( self . __command_listeners [ : ] , self . __server_heartbeat_listeners [ : ] , self . __server_listeners [ : ] , self . __topology_listeners [ : ] ) |
def RegisterPlugin ( self , report_plugin_cls ) :
"""Registers a report plugin for use in the GRR UI .""" | name = report_plugin_cls . __name__
if name in self . plugins :
raise RuntimeError ( "Can't register two report plugins with the same " "name. In particular, can't register the same " "report plugin twice: %r" % name )
self . plugins [ name ] = report_plugin_cls |
def has_encrypt_cert_in_metadata ( self , sp_entity_id ) :
"""Verifies if the metadata contains encryption certificates .
: param sp _ entity _ id : Entity ID for the calling service provider .
: return : True if encrypt cert exists in metadata , otherwise False .""" | if sp_entity_id is not None :
_certs = self . metadata . certs ( sp_entity_id , "any" , "encryption" )
if len ( _certs ) > 0 :
return True
return False |
def _set_ospf ( self , v , load = False ) :
"""Setter method for ospf , mapped from YANG variable / rbridge _ id / ipv6 / router / ospf ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ospf is considered as a private
method . Backends looking to populate this ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "vrf" , ospf . ospf , yang_name = "ospf" , rest_name = "ospf" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'vrf' , extensions = { u'tailf-comm... |
def Orth ( docs , drop = 0.0 ) :
"""Get word forms .""" | ids = numpy . zeros ( ( sum ( len ( doc ) for doc in docs ) , ) , dtype = "i" )
i = 0
for doc in docs :
for token in doc :
ids [ i ] = token . orth
i += 1
return ids , None |
def get_organism_permissions ( self , group ) :
"""Get the group ' s organism permissions
: type group : str
: param group : group name
: rtype : list
: return : a list containing organism permissions ( if any )""" | data = { 'name' : group , }
response = _fix_group ( self . post ( 'getOrganismPermissionsForGroup' , data ) )
return response |
def get_authority ( config , metrics , rrset_channel , ** kwargs ) :
"""Get a GCEAuthority client .
A factory function that validates configuration and creates a
proper GCEAuthority .
Args :
config ( dict ) : GCEAuthority related configuration .
metrics ( obj ) : : interface : ` IMetricRelay ` implementat... | builder = authority . GCEAuthorityBuilder ( config , metrics , rrset_channel , ** kwargs )
return builder . build_authority ( ) |
def is_image_loaded ( webdriver , webelement ) :
'''Check if an image ( in an image tag ) is loaded .
Note : This call will not work against background images . Only Images in < img > tags .
Args :
webelement ( WebElement ) - WebDriver web element to validate .''' | script = ( u ( "return arguments[0].complete && type of arguments[0].naturalWidth != \"undefined\" " ) + u ( "&& arguments[0].naturalWidth > 0" ) )
try :
return webdriver . execute_script ( script , webelement )
except :
return False |
def format ( self ) :
"""The | ChartFormat | object providing access to the shape formatting
properties of this data point , such as line and fill .""" | dPt = self . _ser . get_or_add_dPt_for_point ( self . _idx )
return ChartFormat ( dPt ) |
def _extractall ( self , path = "." , members = None ) :
"""Extract all members from the archive to the current working
directory and set owner , modification time and permissions on
directories afterwards . ` path ' specifies a different directory
to extract to . ` members ' is optional and must be a subset ... | import copy
import operator
from tarfile import ExtractError
directories = [ ]
if members is None :
members = self
for tarinfo in members :
if tarinfo . isdir ( ) :
directories . append ( tarinfo )
tarinfo = copy . copy ( tarinfo )
tarinfo . mode = 448
self . extract ( tarinfo , path... |
def search ( self , text ) :
"""Find text in log file from current position
returns a tuple containing :
absolute position ,
position in result buffer ,
result buffer ( the actual file contents )""" | key = hash ( text )
searcher = self . _searchers . get ( key )
if not searcher :
searcher = ReverseFileSearcher ( self . filename , text )
self . _searchers [ key ] = searcher
position = searcher . find ( )
if position < 0 : # reset the searcher to start from the tail again .
searcher . reset ( )
return... |
def url ( value , allow_empty = False , allow_special_ips = False , ** kwargs ) :
"""Validate that ` ` value ` ` is a valid URL .
. . note : :
URL validation is . . . complicated . The methodology that we have
adopted here is * generally * compliant with
` RFC 1738 < https : / / tools . ietf . org / html / ... | is_recursive = kwargs . pop ( 'is_recursive' , False )
if not value and not allow_empty :
raise errors . EmptyValueError ( 'value (%s) was empty' % value )
elif not value :
return None
if not isinstance ( value , basestring ) :
raise errors . CannotCoerceError ( 'value must be a valid string, ' 'was %s' % t... |
def _insert ( self , namespace , stream , events , configuration ) :
"""` namespace ` acts as db for different streams
` stream ` is the name of a stream and ` events ` is a list of events to
insert .""" | index = self . index_manager . get_index ( namespace )
start_dts_to_add = set ( )
def actions ( ) :
for _id , event in events :
dt = kronos_time_to_datetime ( uuid_to_kronos_time ( _id ) )
start_dts_to_add . add ( _round_datetime_down ( dt ) )
event [ '_index' ] = index
event [ '_typ... |
def check_data ( self ) :
"""Check that definitions file is present , and that faces file is readable .""" | assert os . path . exists ( self . data_fp )
if gis :
with fiona . drivers ( ) :
with fiona . open ( self . faces_fp ) as src :
assert src . meta
gpkg_hash = json . load ( open ( self . data_fp ) ) [ 'metadata' ] [ 'sha256' ]
assert gpkg_hash == sha256 ( self . faces_fp ) |
def lrem ( self , key , count , value ) :
"""Removes the first count occurrences of elements equal to value
from the list stored at key .
: raises TypeError : if count is not int""" | if not isinstance ( count , int ) :
raise TypeError ( "count argument must be int" )
return self . execute ( b'LREM' , key , count , value ) |
def _cim_qualifier ( key , value ) :
"""Return a CIMQualifier object , from dict item input ( key + value ) , after
performing some checks .
If the input value is a CIMQualifier object , it is returned .
Otherwise , a new CIMQualifier object is created from the input value , and
returned .""" | if key is None :
raise ValueError ( "Qualifier name must not be None" )
if isinstance ( value , CIMQualifier ) :
if value . name . lower ( ) != key . lower ( ) :
raise ValueError ( _format ( "CIMQualifier.name must be dictionary key {0!A}, but " "is {1!A}" , key , value . name ) )
qual = value
else ... |
def _get_collection ( self , collection_uri , request_headers = None ) :
"""Generator function that returns collection members .""" | # get the collection
status , headers , thecollection = self . _rest_get ( collection_uri )
if status != 200 :
msg = self . _get_extended_error ( thecollection )
raise exception . IloError ( msg )
while status < 300 : # verify expected type
# Don ' t limit to version 0 here as we will rev to 1.0 at some
# point... |
def repr ( self , changed_widgets = None ) :
"""It is used to automatically represent the object to HTML format
packs all the attributes , children and so on .
Args :
changed _ widgets ( dict ) : A dictionary containing a collection of tags that have to be updated .
The tag that have to be updated is the ke... | if changed_widgets is None :
changed_widgets = { }
local_changed_widgets = { }
self . _set_updated ( )
return '' . join ( ( '<' , self . type , '>\n' , self . innerHTML ( local_changed_widgets ) , '\n</' , self . type , '>' ) ) |
def _load_hdf5 ( self , filename , parent_level = "CellpyData" ) :
"""Load a cellpy - file .
Args :
filename ( str ) : Name of the cellpy file .
parent _ level ( str ) ( optional ) : name of the parent level
( defaults to " CellpyData " )
Returns :
loaded datasets ( DataSet - object )""" | if not os . path . isfile ( filename ) :
self . logger . info ( f"file does not exist: {filename}" )
raise IOError
store = pd . HDFStore ( filename )
# required _ keys = [ ' dfdata ' , ' dfsummary ' , ' fidtable ' , ' info ' ]
required_keys = [ 'dfdata' , 'dfsummary' , 'info' ]
required_keys = [ "/" + parent_le... |
def _attend_process ( self , proc , sleeptime ) :
"""Waits on a process for a given time to see if it finishes , returns True
if it ' s still running after the given time or False as soon as it
returns .
: param psutil . Popen proc : Process object opened by psutil . Popen ( )
: param float sleeptime : Time... | # print ( " attend : { } " . format ( proc . pid ) )
try :
proc . wait ( timeout = sleeptime )
except psutil . TimeoutExpired :
return True
return False |
def teachers_round ( x ) :
'''Do rounding such that . 5 always rounds to 1 , and not bankers rounding .
This is for compatibility with matlab functions , and ease of testing .''' | if ( ( x > 0 ) and ( x % 1 >= 0.5 ) ) or ( ( x < 0 ) and ( x % 1 > 0.5 ) ) :
return int ( np . ceil ( x ) )
else :
return int ( np . floor ( x ) ) |
def dump_tracing_state ( self , context ) :
"""A debug tool to dump all threads tracing state""" | _logger . x_debug ( "Dumping all threads Tracing state: (%s)" % context )
_logger . x_debug ( " self.tracing_enabled=%s" % self . tracing_enabled )
_logger . x_debug ( " self.execution_started=%s" % self . execution_started )
_logger . x_debug ( " self.status=%s" % self . status )
_logger . x_debug ( " self... |
async def ensureKeyPair ( self , * args , ** kwargs ) :
"""Ensure a KeyPair for a given worker type exists
Idempotently ensure that a keypair of a given name exists
This method takes input : ` ` v1 / create - key - pair . json # ` `
This method is ` ` experimental ` `""" | return await self . _makeApiCall ( self . funcinfo [ "ensureKeyPair" ] , * args , ** kwargs ) |
def markdown_media_css ( ) :
"""Add css requirements to HTML .
: returns : Editor template context .""" | return dict ( CSS_SET = posixpath . join ( settings . MARKDOWN_SET_PATH , settings . MARKDOWN_SET_NAME , 'style.css' ) , CSS_SKIN = posixpath . join ( 'django_markdown' , 'skins' , settings . MARKDOWN_EDITOR_SKIN , 'style.css' ) ) |
def remove_client ( self , client_identifier ) :
"""Remove a client .""" | new_clients = self . clients
new_clients . remove ( client_identifier )
yield from self . _server . group_clients ( self . identifier , new_clients )
_LOGGER . info ( 'removed %s from %s' , client_identifier , self . identifier )
self . _server . client ( client_identifier ) . callback ( )
self . callback ( ) |
def check_aux_coordinates ( self , ds ) :
'''Chapter 5 paragraph 3
The dimensions of an auxiliary coordinate variable must be a subset of
the dimensions of the variable with which the coordinate is associated ,
with two exceptions . First , string - valued coordinates ( Section 6.1,
" Labels " ) have a dime... | ret_val = [ ]
geophysical_variables = self . _find_geophysical_vars ( ds )
for name in geophysical_variables :
variable = ds . variables [ name ]
coordinates = getattr ( variable , 'coordinates' , None )
# We use a set so we can assert
dim_set = set ( variable . dimensions )
# No auxiliary coordinat... |
def make_object_graph ( obj , fpath = 'sample_graph.png' ) :
"""memoryprofile with objgraph
Examples :
# import objgraph
# objgraph . show _ most _ common _ types ( )
# objgraph . show _ growth ( )
# memtrack . report ( )
# memtrack . report ( )
# objgraph . show _ growth ( )
# import gc
# gc . co... | import objgraph
objgraph . show_most_common_types ( )
# print ( objgraph . by _ type ( ' ndarray ' ) )
# objgraph . find _ backref _ chain (
# random . choice ( objgraph . by _ type ( ' ndarray ' ) ) ,
# objgraph . is _ proper _ module )
objgraph . show_refs ( [ obj ] , filename = 'ref_graph.png' )
objgraph . show_back... |
def PureDotProductAttention ( dropout = 0.0 , mode = 'train' ) :
"""Pure single - headed self - attention .
Args :
dropout : float : dropout rate
mode : str : ' train ' or ' eval '
Returns :
Pure single - headed attention layer . ( No Dense transforms on input . )""" | def init_fun ( _ , input_shapes ) : # pylint : disable = invalid - name
q_shape , _ , v_shape , _ = input_shapes
output_shape = q_shape [ : - 1 ] + ( v_shape [ - 1 ] , )
return output_shape , ( )
def apply_fun ( params , inputs , ** kwargs ) : # pylint : disable = invalid - name
del params
q , k , v... |
def extract_literal_bool ( templatevar ) :
"""See if a template FilterExpression holds a literal boolean value .
: type templatevar : django . template . FilterExpression
: rtype : bool | None""" | # FilterExpression contains another ' var ' that either contains a Variable or SafeData object .
if hasattr ( templatevar , 'var' ) :
templatevar = templatevar . var
if isinstance ( templatevar , SafeData ) : # Literal in FilterExpression , can return .
return is_true ( templatevar )
else : # Variab... |
def gelu ( x ) :
"""Gaussian Error Linear Unit .
This is a smoother version of the RELU .
Original paper : https : / / arxiv . org / abs / 1606.08415
Args :
x : float Tensor to perform activation .
Returns :
x with the GELU activation applied .""" | cdf = 0.5 * ( 1.0 + tf . tanh ( ( np . sqrt ( 2 / np . pi ) * ( x + 0.044715 * tf . pow ( x , 3 ) ) ) ) )
return x * cdf |
def get_ranked_players ( ) :
"""Get the list of the first 100 ranked players .""" | rankings_page = requests . get ( RANKINGS_URL )
root = etree . HTML ( rankings_page . text )
player_rows = root . xpath ( '//div[@id="ranked"]//tr' )
for row in player_rows [ 1 : ] :
player_row = row . xpath ( 'td[@class!="country"]//text()' )
yield _Player ( name = player_row [ 1 ] , country = row [ 1 ] [ 0 ] ... |
def withdraw_ong ( self , claimer : Account , b58_recv_address : str , amount : int , payer : Account , gas_limit : int , gas_price : int ) -> str :
"""This interface is used to withdraw a amount of ong and transfer them to receive address .
: param claimer : the owner of ong that remained to claim .
: param b5... | if claimer is None :
raise SDKException ( ErrorCode . param_err ( 'the claimer should not be None.' ) )
if payer is None :
raise SDKException ( ErrorCode . param_err ( 'the payer should not be None.' ) )
if amount <= 0 :
raise SDKException ( ErrorCode . other_error ( 'the amount should be greater than than ... |
def visit_Import ( self , node ) :
"""Check if imported module exists in MODULES .""" | for alias in node . names :
current_module = MODULES
# Recursive check for submodules
for path in alias . name . split ( '.' ) :
if path not in current_module :
raise PythranSyntaxError ( "Module '{0}' unknown." . format ( alias . name ) , node )
else :
current_module... |
def get_dataset ( self , key , info ) :
"""Load a dataset .""" | logger . debug ( 'Reading in get_dataset %s.' , key . name )
radiances = self [ 'Rad' ]
if key . calibration == 'reflectance' :
logger . debug ( "Calibrating to reflectances" )
res = self . _vis_calibrate ( radiances )
elif key . calibration == 'brightness_temperature' :
logger . debug ( "Calibrating to bri... |
def values ( self ) :
"""Return the list of values .""" | def collect ( d ) :
if d is None or d . get ( 'FIRST' ) is None :
return [ ]
vals = [ d [ 'FIRST' ] ]
vals . extend ( collect ( d . get ( 'REST' ) ) )
return vals
return collect ( self ) |
def load_mplstyle ( ) :
"""Try to load conf . plot . mplstyle matplotlib style .""" | plt = importlib . import_module ( 'matplotlib.pyplot' )
if conf . plot . mplstyle :
for style in conf . plot . mplstyle . split ( ) :
stfile = config . CONFIG_DIR / ( style + '.mplstyle' )
if stfile . is_file ( ) :
style = str ( stfile )
try :
plt . style . use ( styl... |
def from_file ( cls , f ) :
"""Read configuration from a file - like object .""" | ret = cls ( )
section = None
setting = None
for lineno , line in enumerate ( f . readlines ( ) ) :
line = line . lstrip ( )
if setting is None :
if _strip_comments ( line ) . strip ( ) == "" :
continue
if line [ 0 ] == "[" :
line = _strip_comments ( line ) . rstrip ( )
... |
def on_install ( self , editor ) :
"""Extends : meth : ` spyder . api . EditorExtension . on _ install ` method to set the
editor instance as the parent widget .
. . warning : : Don ' t forget to call * * super * * if you override this
method !
: param editor : editor instance
: type editor : spyder . plu... | EditorExtension . on_install ( self , editor )
self . setParent ( editor )
self . setPalette ( QApplication . instance ( ) . palette ( ) )
self . setFont ( QApplication . instance ( ) . font ( ) )
self . editor . panels . refresh ( )
self . _background_brush = QBrush ( QColor ( self . palette ( ) . window ( ) . color (... |
async def register ( self , node , * , check = None , service = None , write_token = None ) :
"""Registers a new node , service or check
Parameters :
node ( Object ) : Node definition
check ( Object ) : Check definition
service ( Object or ObjectID ) : Service
write _ token ( ObjectID ) : Token ID
Retur... | node_id , node = prepare_node ( node )
service_id , service = prepare_service ( service )
_ , check = prepare_check ( check )
if check and node_id :
check [ "Node" ] = node_id
if check and service_id :
check [ "ServiceID" ] = service_id
token = extract_attr ( write_token , keys = [ "ID" ] )
entry = node
if serv... |
def save ( self , ** kwargs ) :
"""Overrides models . Model . save .
- Generates slug .
- Saves image file .""" | if not self . width or not self . height :
self . width , self . height = self . image . width , self . image . height
# prefill the slug with the ID , it requires double save
if not self . id :
img = self . image
# store dummy values first . . .
w , h = self . width , self . height
self . image = '... |
def as_string ( self , name = None ) :
"""Declares a stream converting each tuple on this stream
into a string using ` str ( tuple ) ` .
The stream is typed as a : py : const : ` string stream < streamsx . topology . schema . CommonSchema . String > ` .
If this stream is already typed as a string stream then ... | sas = self . _change_schema ( streamsx . topology . schema . CommonSchema . String , 'as_string' , name ) . _layout ( 'AsString' )
sas . oport . operator . sl = _SourceLocation ( _source_info ( ) , 'as_string' )
return sas |
def get_name ( self ) :
"""Returns name of the container
: return : str""" | self . name = self . name or graceful_get ( self . inspect ( refresh = False ) , "Name" )
return self . name |
def change_breakpoint_state ( self , bp_number , enabled , condition = None ) :
"""Change breakpoint status or ` condition ` expression .
: param bp _ number : number of breakpoint to change
: return : None or an error message ( string )""" | if not ( 0 <= bp_number < len ( IKBreakpoint . breakpoints_by_number ) ) :
return "Found no breakpoint numbered: %s" % bp_number
bp = IKBreakpoint . breakpoints_by_number [ bp_number ]
if not bp :
return "Found no breakpoint numbered %s" % bp_number
_logger . b_debug ( " change_breakpoint_state(bp_number=%s,... |
def subshell ( shell_cls , * commands , ** kwargs ) :
"""Decorate a function to conditionally launch a _ ShellBase subshell .
Arguments :
shell _ cls : A subclass of _ ShellBase to be launched .
commands : Names of command that should trigger this function object .
kwargs : The keyword arguments for the com... | def decorated_func ( f ) :
def inner_func ( self , cmd , args ) :
retval = f ( self , cmd , args )
# Do not launch the subshell if the return value is None .
if not retval :
return
# Pass the context ( see the doc string ) to the subshell if the
# return value is ... |
def get_variable_definitions ( self , block_addr ) :
"""Get variables that are defined at the specified block .
: param int block _ addr : Address of the block .
: return : A set of variables .""" | if block_addr in self . _outstates :
return self . _outstates [ block_addr ] . variables
return set ( ) |
def get_userids_for_address ( self , address : Address ) -> Set [ str ] :
"""Return all known user ids for the given ` ` address ` ` .""" | if not self . is_address_known ( address ) :
return set ( )
return self . _address_to_userids [ address ] |
def _filesystems ( config = '/etc/filesystems' , leading_key = True ) :
'''Return the contents of the filesystems in an OrderedDict
config
File containing filesystem infomation
leading _ key
True return dictionary keyed by ' name ' and value as dictionary with other keys , values ( name excluded )
Ordered... | ret = OrderedDict ( )
lines = [ ]
parsing_block = False
if not os . path . isfile ( config ) or 'AIX' not in __grains__ [ 'kernel' ] :
return ret
# read in block of filesystems , block starts with ' / ' till empty line
with salt . utils . files . fopen ( config ) as ifile :
for line in ifile :
line = sa... |
def d2Ibr_dV2 ( Ybr , V , lam ) :
"""Computes 2nd derivatives of complex branch current w . r . t . voltage .""" | nb = len ( V )
diaginvVm = spdiag ( div ( matrix ( 1.0 , ( nb , 1 ) ) , abs ( V ) ) )
Haa = spdiag ( mul ( - ( Ybr . T * lam ) , V ) )
Hva = - 1j * Haa * diaginvVm
Hav = Hva
Hvv = spmatrix ( [ ] , [ ] , [ ] , ( nb , nb ) )
return Haa , Hav , Hva , Hvv |
def _parseLoadConfigDirectory ( self , rva , size , magic = consts . PE32 ) :
"""Parses IMAGE _ LOAD _ CONFIG _ DIRECTORY .
@ type rva : int
@ param rva : The RVA where the IMAGE _ LOAD _ CONFIG _ DIRECTORY starts .
@ type size : int
@ param size : The size of the IMAGE _ LOAD _ CONFIG _ DIRECTORY .
@ typ... | # print " RVA : % x - SIZE : % x " % ( rva , size )
# I ' ve found some issues when parsing the IMAGE _ LOAD _ CONFIG _ DIRECTORY in some DLLs .
# There is an inconsistency with the size of the struct between MSDN docs and VS .
# sizeof ( IMAGE _ LOAD _ CONFIG _ DIRECTORY ) should be 0x40 , in fact , that ' s the size ... |
def arctic_url ( context , link , * args , ** kwargs ) :
"""Resolves links into urls with optional
arguments set in self . urls . please check get _ urls method in View .
We could tie this to check _ url _ access ( ) to check for permissions ,
including object - level .""" | def reverse_mutable_url_args ( url_args ) :
mutated_url_args = [ ]
for arg in url_args : # listview item , and argument is a string
if "item" in context and type ( arg ) == str : # try to get attribute of this object
try :
arg = getattr ( context [ "v" ] , arg . split ( "." )... |
def _is_empty_cache_record ( self , rec ) :
"""Return True if the specified cache record has no data , False otherwise .
: param rec : cache record returned by : py : meth : ` ~ . _ cache _ get `
: type rec : dict
: return : True if record is empty , False otherwise
: rtype : bool""" | # these are taken from DataQuery . query _ one _ table ( )
for k in [ 'by_version' , 'by_file_type' , 'by_installer' , 'by_implementation' , 'by_system' , 'by_distro' , 'by_country' ] :
if k in rec and len ( rec [ k ] ) > 0 :
return False
return True |
def _SetCompleted ( self ) :
"""Atomically marks the breakpoint as completed .
Returns :
True if the breakpoint wasn ' t marked already completed or False if the
breakpoint was already completed .""" | with self . _lock :
if self . _completed :
return False
self . _completed = True
return True |
def get_tops ( self ) :
'''Gather the top files''' | tops = DefaultOrderedDict ( list )
include = DefaultOrderedDict ( list )
done = DefaultOrderedDict ( list )
found = 0
# did we find any contents in the top files ?
# Gather initial top files
merging_strategy = self . opts [ 'top_file_merging_strategy' ]
if merging_strategy == 'same' and not self . opts [ 'saltenv' ] :
... |
def list_node ( self , tab_level = - 1 ) :
"""Lists the current Node and its children .
Usage : :
> > > node _ a = AbstractCompositeNode ( " MyNodeA " )
> > > node _ b = AbstractCompositeNode ( " MyNodeB " , node _ a )
> > > node _ c = AbstractCompositeNode ( " MyNodeC " , node _ a )
> > > print node _ a ... | output = ""
tab_level += 1
for i in range ( tab_level ) :
output += "\t"
output += "|----'{0}'\n" . format ( self . name )
for child in self . __children :
output += child . list_node ( tab_level )
tab_level -= 1
return output |
def catch_exceptions ( * exceptions ) :
"""Catch all exceptions provided as arguments , and raise CloudApiException instead .""" | def wrap ( fn ) :
@ functools . wraps ( fn )
def wrapped_f ( * args , ** kwargs ) :
try :
return fn ( * args , ** kwargs )
except exceptions :
t , value , traceback = sys . exc_info ( )
# If any resource does not exist , return None instead of raising
... |
def get ( self , name ) :
'''Return a secondary property value from the Node .
Args :
name ( str ) : The name of a secondary property .
Returns :
( obj ) : The secondary property value or None .''' | if name . startswith ( '#' ) :
return self . tags . get ( name [ 1 : ] )
return self . props . get ( name ) |
def word_tokenize ( text : str , custom_dict : Trie = None , engine : str = "newmm" , keep_whitespace : bool = True , ) -> List [ str ] :
""": param str text : text to be tokenized
: param str engine : tokenizer to be used
: param dict custom _ dict : a dictionary trie
: param bool keep _ whitespace : True to... | if not text or not isinstance ( text , str ) :
return [ ]
segments = [ ]
if engine == "newmm" or engine == "onecut" :
from . newmm import segment
segments = segment ( text , custom_dict )
elif engine == "longest" :
from . longest import segment
segments = segment ( text , custom_dict )
elif engine =... |
def load_config ( self , config_path = None ) :
"""Load application configuration from a file and merge it with the default
configuration .
If the ` ` FEDORA _ MESSAGING _ CONF ` ` environment variable is set to a
filesystem path , the configuration will be loaded from that location .
Otherwise , the path d... | self . loaded = True
config = copy . deepcopy ( DEFAULTS )
if config_path is None :
if "FEDORA_MESSAGING_CONF" in os . environ :
config_path = os . environ [ "FEDORA_MESSAGING_CONF" ]
else :
config_path = "/etc/fedora-messaging/config.toml"
if os . path . exists ( config_path ) :
_log . info... |
def get_account_tokens ( address , hostport = None , proxy = None ) :
"""Get the types of tokens that an address owns
Returns a list of token types""" | assert proxy or hostport , 'Need proxy or hostport'
if proxy is None :
proxy = connect_hostport ( hostport )
tokens_schema = { 'type' : 'object' , 'properties' : { 'token_types' : { 'type' : 'array' , 'pattern' : '^(.+){1,19}' , } , } , 'required' : [ 'token_types' , ] }
schema = json_response_schema ( tokens_schem... |
def download_and_verify ( path , source_url , sha256 ) :
"""Download a file to a given path from a given URL , if it does not exist .
After downloading it , verify it integrity by checking the SHA - 256 hash .
Parameters
path : str
The ( destination ) path of the file on the local filesystem
source _ url ... | if os . path . exists ( path ) : # Already exists ?
# Nothing to do , except print the SHA - 256 if necessary
if sha256 is None :
print ( 'The SHA-256 of {} is "{}"' . format ( path , compute_sha256 ( path ) ) )
return path
# Compute the path of the unverified file
unverified_path = path + '.unverified'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.