signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _resolve_view_params ( self , request , defaults , * args , ** kwargs ) :
"""Resolves view params with least ammount of resistance .
Firstly check for params on urls passed args , then on class init args or members ,
and lastly on class get methods .""" | params = copy . copy ( defaults )
params . update ( self . params )
params . update ( kwargs )
resolved_params = { }
extra_context = { }
for key in params : # grab from provided params .
value = params [ key ]
# otherwise grab from existing params
if value == None :
value = self . params [ key ] if ... |
def format_filename ( filename , shorten = False ) :
"""Formats a filename for user display . The main purpose of this
function is to ensure that the filename can be displayed at all . This
will decode the filename to unicode if necessary in a way that it will
not fail . Optionally , it can shorten the filena... | if shorten :
filename = os . path . basename ( filename )
return filename_to_ui ( filename ) |
def readCovarianceMatrixFile ( cfile , readCov = True , readEig = True ) :
"""reading in similarity matrix
cfile File containing the covariance matrix . The corresponding ID file must be specified in cfile . id )""" | covFile = cfile + '.cov'
evalFile = cfile + '.cov.eval'
evecFile = cfile + '.cov.evec'
RV = { }
if readCov :
assert os . path . exists ( covFile ) , '%s is missing.' % covFile
RV [ 'K' ] = SP . loadtxt ( covFile )
if readEig :
assert os . path . exists ( evalFile ) , '%s is missing.' % evalFile
assert o... |
def _cmp_by_origin ( path1 , path2 ) :
"""Select the best path based on origin attribute .
IGP is preferred over EGP ; EGP is preferred over Incomplete .
If both paths have same origin , we return None .""" | def get_origin_pref ( origin ) :
if origin . value == BGP_ATTR_ORIGIN_IGP :
return 3
elif origin . value == BGP_ATTR_ORIGIN_EGP :
return 2
elif origin . value == BGP_ATTR_ORIGIN_INCOMPLETE :
return 1
else :
LOG . error ( 'Invalid origin value encountered %s.' , origin )
... |
def getShocks ( self ) :
'''Finds the effective permanent and transitory shocks this period by combining the aggregate
and idiosyncratic shocks of each type .
Parameters
None
Returns
None''' | IndShockConsumerType . getShocks ( self )
# Update idiosyncratic shocks
self . TranShkNow = self . TranShkNow * self . TranShkAggNow * self . wRteNow
self . PermShkNow = self . PermShkNow * self . PermShkAggNow |
async def unicode_type ( self , elem ) :
"""Unicode type
: param elem :
: return :""" | if self . writing :
return await x . dump_unicode ( self . iobj , elem )
else :
return await x . load_unicode ( self . iobj ) |
def _client_data ( self , client ) :
"""Returns a dict that represents the client specified
Keys : obj , id , url , name""" | data = { }
if client :
data [ 'obj' ] = client
data [ 'id' ] = client . id
data [ 'url' ] = client . absolute_url ( )
data [ 'name' ] = to_utf8 ( client . getName ( ) )
return data |
def GetEntries ( self , parser_mediator , match = None , ** unused_kwargs ) :
"""Extract device information from the iPod plist .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
match ( Optional [ dict [ str : object ] ] ... | devices = match . get ( 'Devices' , { } )
for device_identifier , device_information in iter ( devices . items ( ) ) :
datetime_value = device_information . get ( 'Connected' , None )
if not datetime_value :
continue
event_data = IPodPlistEventData ( )
event_data . device_id = device_identifier
... |
def _iter ( self ) :
"""Generate ( name , est , weight ) tuples excluding None transformers""" | get_weight = ( self . transformer_weights or { } ) . get
return ( ( name , trans , get_weight ( name ) ) for name , trans in self . transformer_list if trans is not None ) |
def MaxPool ( a , k , strides , padding , data_format ) :
"""Maximum pooling op .""" | if data_format . decode ( "ascii" ) == "NCHW" :
a = np . rollaxis ( a , 1 , - 1 ) ,
patches = _pool_patches ( a , k , strides , padding . decode ( "ascii" ) )
pool = np . amax ( patches , axis = tuple ( range ( - len ( k ) , 0 ) ) )
if data_format . decode ( "ascii" ) == "NCHW" :
pool = np . rollaxis ( pool , -... |
def snapshot_status ( repository = None , snapshot = None , ignore_unavailable = False , hosts = None , profile = None ) :
'''. . versionadded : : 2017.7.0
Obtain status of all currently running snapshots .
repository
Particular repository to look for snapshots
snapshot
Snapshot name
ignore _ unavailabl... | es = _get_instance ( hosts , profile )
try :
return es . snapshot . status ( repository = repository , snapshot = snapshot , ignore_unavailable = ignore_unavailable )
except elasticsearch . TransportError as e :
raise CommandExecutionError ( "Cannot obtain snapshot status, server returned code {0} with message ... |
def authenticateRequest ( self , service_request , username , password , ** kwargs ) :
"""Processes an authentication request . If no authenticator is supplied ,
then authentication succeeds .
@ return : Returns a C { bool } based on the result of authorization . A
value of C { False } will stop processing th... | authenticator = self . getAuthenticator ( service_request )
if authenticator is None :
return True
args = ( username , password )
if hasattr ( authenticator , '_pyamf_expose_request' ) :
http_request = kwargs . get ( 'http_request' , None )
args = ( http_request , ) + args
return authenticator ( * args ) ==... |
async def push_transaction_async ( self ) :
"""Increment async transaction depth .""" | await self . connect_async ( loop = self . loop )
depth = self . transaction_depth_async ( )
if not depth :
conn = await self . _async_conn . acquire ( )
self . _task_data . set ( 'conn' , conn )
self . _task_data . set ( 'depth' , depth + 1 ) |
def get_output_jsonpath ( self , sub_output = None ) :
"""Attempt to build a JSONPath filter for this ExtractorProcessor
that captures how to get at the outputs of the wrapped Extractor""" | output_jsonpath_field = self . get_output_jsonpath_field ( sub_output )
metadata = self . extractor . get_metadata ( )
metadata [ 'source' ] = str ( self . input_fields )
extractor_filter = ""
is_first = True
for key , value in metadata . iteritems ( ) :
if is_first :
is_first = False
else :
ext... |
def to_abivars ( self ) :
"""Returns a dictionary with the abinit variables""" | return { # Spectral function
"nomegasf" : self . nomegasf , "domegasf" : self . domegasf , "spmeth" : self . spmeth , # Frequency mesh for the polarizability
"nfreqre" : self . nfreqre , "freqremax" : self . freqremax , "nfreqim" : self . nfreqim , "freqremin" : self . freqremin , } |
def open_external_editor ( filename = None , sql = None ) :
"""Open external editor , wait for the user to type in their query , return
the query .
: return : list with one tuple , query as first element .""" | message = None
filename = filename . strip ( ) . split ( ' ' , 1 ) [ 0 ] if filename else None
sql = sql or ''
MARKER = '# Type your query above this line.\n'
# Populate the editor buffer with the partial sql ( if available ) and a
# placeholder comment .
query = click . edit ( u'{sql}\n\n{marker}' . format ( sql = sql... |
def add_method ( obj , func , name = None ) :
"""Adds an instance method to an object .""" | if name is None :
name = func . __name__
if sys . version_info < ( 3 , ) :
method = types . MethodType ( func , obj , obj . __class__ )
else :
method = types . MethodType ( func , obj )
setattr ( obj , name , method ) |
def make_setup_state ( self , app : 'Quart' , first_registration : bool , * , url_prefix : Optional [ str ] = None , ) -> 'BlueprintSetupState' :
"""Return a blueprint setup state instance .
Arguments :
first _ registration : True if this is the first registration
of this blueprint on the app .
url _ prefix... | return BlueprintSetupState ( self , app , first_registration , url_prefix = url_prefix ) |
def Reinit ( self , pid , auto_symfile_loading = True ) :
"""Reinitializes the object with a new pid .
Since all modes might need access to this object at any time , this object
needs to be long - lived . To make this clear in the API , this shorthand is
supplied .
Args :
pid : the pid of the target proce... | self . ShutDownGdb ( )
self . __init__ ( pid , auto_symfile_loading , architecture = self . arch ) |
def create_userena_profile ( self , user ) :
"""Creates an : class : ` UserenaSignup ` instance for this user .
: param user :
Django : class : ` User ` instance .
: return : The newly created : class : ` UserenaSignup ` instance .""" | if isinstance ( user . username , text_type ) :
user . username = smart_text ( user . username )
salt , activation_key = generate_sha1 ( user . username )
try :
profile = self . get ( user = user )
except self . model . DoesNotExist :
profile = self . create ( user = user , activation_key = activation_key )... |
def hdr ( data , filename ) :
"""write ENVI header files
Parameters
data : str or dict
the file or dictionary to get the info from
filename : str
the HDR file to write
Returns""" | hdrobj = data if isinstance ( data , HDRobject ) else HDRobject ( data )
hdrobj . write ( filename ) |
def get_bucket ( self , hash_name , bucket_key ) :
"""Returns bucket content as list of tuples ( vector , data ) .""" | results = [ ]
for row in self . _get_bucket_rows ( hash_name , bucket_key ) :
val_dict = pickle . loads ( row )
# Depending on type ( sparse or not ) reconstruct vector
if 'sparse' in val_dict : # Fill these for COO creation
row = [ ]
col = [ ]
data = [ ]
# For each non - zer... |
def get_contingency_tables ( self ) :
"""Create an Array of ContingencyTable objects for each probability threshold .
Returns :
Array of ContingencyTable objects""" | return np . array ( [ ContingencyTable ( * ct ) for ct in self . contingency_tables . values ] ) |
def lookup ( id = None , artist_amg_id = None , upc = None , country = 'US' , media = 'all' , entity = None , attribute = None , limit = 50 ) :
"""Returns the result of the lookup of the specified id , artist _ amg _ id or upc in an array of result _ item ( s )
: param id : String . iTunes ID of the artist , albu... | # If none of the basic lookup arguments are provided , raise a ValueError
if id is None and artist_amg_id is None and upc is None :
raise ValueError ( lookup_no_ids )
lookup_url = _url_lookup_builder ( id , artist_amg_id , upc , country , media , entity , attribute , limit )
r = requests . get ( lookup_url )
try :
... |
def namer ( cls , imageUrl , pageUrl ) :
"""Image file name is UNIX time stamp & something for most of the comics . . .""" | start = ''
tsmatch = compile ( r'/(\d+)-' ) . search ( imageUrl )
if tsmatch :
start = datetime . utcfromtimestamp ( int ( tsmatch . group ( 1 ) ) ) . strftime ( "%Y-%m-%d" )
else : # There were only chapter 1 , page 4 and 5 not matching when writing
# this . . .
start = '2015-04-11x'
return start + "-" + pageU... |
def create_ca_signed_cert ( ca_name , CN , days = 365 , cacert_path = None , ca_filename = None , cert_path = None , cert_filename = None , digest = 'sha256' , cert_type = None , type_ext = False , replace = False ) :
'''Create a Certificate ( CERT ) signed by a named Certificate Authority ( CA )
If the certifica... | ret = { }
set_ca_path ( cacert_path )
if not ca_filename :
ca_filename = '{0}_ca_cert' . format ( ca_name )
if not cert_path :
cert_path = '{0}/{1}/certs' . format ( cert_base_path ( ) , ca_name )
if type_ext :
if not cert_type :
log . error ( 'type_ext = True but cert_type is unset. ' 'Certificate ... |
def replace_series_data ( self , chartSpace ) :
"""Rewrite the series data under * chartSpace * using the chart data
contents . All series - level formatting is left undisturbed . If
the chart data contains fewer series than * chartSpace * , the extra
series in * chartSpace * are deleted . If * chart _ data *... | plotArea , date_1904 = chartSpace . plotArea , chartSpace . date_1904
chart_data = self . _chart_data
self . _adjust_ser_count ( plotArea , len ( chart_data ) )
for ser , series_data in zip ( plotArea . sers , chart_data ) :
self . _rewrite_ser_data ( ser , series_data , date_1904 ) |
def shared_memory ( attrs = None , where = None ) :
'''Return shared _ memory information from osquery
CLI Example :
. . code - block : : bash
salt ' * ' osquery . shared _ memory''' | if __grains__ [ 'os_family' ] in [ 'RedHat' , 'Debian' ] :
return _osquery_cmd ( table = 'shared_memory' , attrs = attrs , where = where )
return { 'result' : False , 'comment' : 'Only available on Red Hat or Debian based systems.' } |
def handle_features ( self , device_features ) :
"""Handles features of the device""" | self . device_features = device_features
if device_features and 'zone' in device_features :
for zone in device_features [ 'zone' ] :
zone_id = zone . get ( 'id' )
if zone_id in self . zones :
_LOGGER . debug ( "handle_features: %s" , zone_id )
input_list = zone . get ( 'input... |
def cellsim ( self , cellindex , return_just_cell = False ) :
"""Do the actual simulations of LFP , using synaptic spike times from
network simulation .
Parameters
cellindex : int
cell index between 0 and population size - 1.
return _ just _ cell : bool
If True , return only the ` LFPy . Cell ` object
... | tic = time ( )
cell = LFPy . Cell ( ** self . cellParams )
cell . set_pos ( ** self . pop_soma_pos [ cellindex ] )
cell . set_rotation ( ** self . rotations [ cellindex ] )
if return_just_cell : # with several cells , NEURON can only hold one cell at the time
allsecnames = [ ]
allsec = [ ]
for sec in cell .... |
def validate_categories ( categories ) :
"""Take an iterable of source categories and raise ValueError if some
of them are invalid .""" | if not set ( categories ) <= Source . categories :
invalid = list ( set ( categories ) - Source . categories )
raise ValueError ( 'Invalid categories: %s' % invalid ) |
def set_chain_info ( self , chain_id , chain_name , num_groups ) :
"""Set the chain information .
: param chain _ id : the asym chain id from mmCIF
: param chain _ name : the auth chain id from mmCIF
: param num _ groups : the number of groups this chain has""" | self . chain_id_list . append ( chain_id )
self . chain_name_list . append ( chain_name )
self . groups_per_chain . append ( num_groups ) |
def load ( filename , loader = None , implicit_tuple = True , env = { } , schema = None ) :
"""Load and evaluate a GCL expression from a file .""" | with open ( filename , 'r' ) as f :
return loads ( f . read ( ) , filename = filename , loader = loader , implicit_tuple = implicit_tuple , env = env , schema = schema ) |
def file_adapter ( file_or_path ) :
"""Context manager that works similar to ` ` open ( file _ path ) ` ` but also accepts already openned file - like objects .""" | if is_file ( file_or_path ) :
file_obj = file_or_path
else :
file_obj = open ( file_or_path , 'rb' )
yield file_obj
file_obj . close ( ) |
def set_idlemax ( self , idlemax ) :
"""Sets CPU idle max value
: param idlemax : idle max value ( integer )""" | is_running = yield from self . is_running ( )
if is_running : # router is running
yield from self . _hypervisor . send ( 'vm set_idle_max "{name}" 0 {idlemax}' . format ( name = self . _name , idlemax = idlemax ) )
log . info ( 'Router "{name}" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}' . format (... |
def _rspiral ( width , height ) :
"""Reversed spiral generator .
Parameters
width : ` int `
Spiral width .
height : ` int `
Spiral height .
Returns
` generator ` of ( ` int ` , ` int ` )
Points .""" | x0 = 0
y0 = 0
x1 = width - 1
y1 = height - 1
while x0 < x1 and y0 < y1 :
for x in range ( x0 , x1 ) :
yield x , y0
for y in range ( y0 , y1 ) :
yield x1 , y
for x in range ( x1 , x0 , - 1 ) :
yield x , y1
for y in range ( y1 , y0 , - 1 ) :
yield x0 , y
x0 += 1
y0 ... |
def export_json ( self , filename ) :
"""Export graph in JSON form to the given file .""" | json_graph = self . to_json ( )
with open ( filename , 'wb' ) as f :
f . write ( json_graph . encode ( 'utf-8' ) ) |
def state ( self , context ) :
"""Get instance state .
: param resort . engine . execution . Context context :
Current execution context .
: rtype :
str
: return :
Instance state name .""" | state = None
for line in self . read ( context , [ "status" , context . resolve ( self . __name ) ] ) :
if line [ 2 ] == "state" :
state = line [ 3 ] . strip ( )
return state |
def visitStringFacet ( self , ctx : ShExDocParser . StringFacetContext ) :
"""stringFacet : stringLength INTEGER | REGEXP REGEXP _ FLAGS
stringLength : KW _ LENGTH | KW _ MINLENGTH | KW _ MAXLENGTH""" | if ctx . stringLength ( ) :
slen = jsg . Integer ( ctx . INTEGER ( ) . getText ( ) )
if ctx . stringLength ( ) . KW_LENGTH ( ) :
self . nodeconstraint . length = slen
elif ctx . stringLength ( ) . KW_MINLENGTH ( ) :
self . nodeconstraint . minlength = slen
else :
self . nodeconst... |
def plot_iso ( axis , step , var ) :
"""Plot isocontours of scalar field .
Args :
axis ( : class : ` matplotlib . axes . Axes ` ) : the axis handler of an
existing matplotlib figure where the isocontours should
be plotted .
step ( : class : ` ~ stagpy . stagyydata . _ Step ` ) : a step of a StagyyData
i... | xmesh , ymesh , fld = get_meshes_fld ( step , var )
if conf . field . shift :
fld = np . roll ( fld , conf . field . shift , axis = 0 )
axis . contour ( xmesh , ymesh , fld , linewidths = 1 ) |
def update_line ( self , trace , xdata , ydata , side = 'left' , draw = False , update_limits = True ) :
"""update a single trace , for faster redraw""" | x = self . conf . get_mpl_line ( trace )
x . set_data ( xdata , ydata )
datarange = [ xdata . min ( ) , xdata . max ( ) , ydata . min ( ) , ydata . max ( ) ]
self . conf . set_trace_datarange ( datarange , trace = trace )
axes = self . axes
if side == 'right' :
axes = self . get_right_axes ( )
if update_limits :
... |
def FlipAllowed ( self ) :
"""Raise an error if the not keyword is used where it is not allowed .""" | if not hasattr ( self , 'flipped' ) :
raise errors . ParseError ( 'Not defined.' )
if not self . flipped :
return
if self . current_expression . operator :
if not self . current_expression . operator . lower ( ) in ( 'is' , 'contains' , 'inset' , 'equals' ) :
raise errors . ParseError ( 'Keyword \'n... |
def dcs_modules ( ) :
"""Get names of DCS modules , depending on execution environment . If being packaged with PyInstaller ,
modules aren ' t discoverable dynamically by scanning source directory because ` FrozenImporter ` doesn ' t
implement ` iter _ modules ` method . But it is still possible to find all pot... | dcs_dirname = os . path . dirname ( __file__ )
module_prefix = __package__ + '.'
if getattr ( sys , 'frozen' , False ) :
importer = pkgutil . get_importer ( dcs_dirname )
return [ module for module in list ( importer . toc ) if module . startswith ( module_prefix ) and module . count ( '.' ) == 2 ]
else :
r... |
def find_video_by_id ( self , video_id ) :
"""doc : http : / / open . youku . com / docs / doc ? id = 44""" | url = 'https://openapi.youku.com/v2/videos/show_basic.json'
params = { 'client_id' : self . client_id , 'video_id' : video_id }
r = requests . get ( url , params = params )
check_error ( r )
return r . json ( ) |
def generate ( data , format = "auto" ) :
"""Converts input chemical formats to json and optimizes structure .
Args :
data : A string or file representing a chemical
format : The format of the ` data ` variable ( default is ' auto ' )
The ` format ` can be any value specified by Open Babel
( http : / / op... | # Support both files and strings and attempt to infer file type
try :
with open ( data ) as in_file :
if format == 'auto' :
format = data . split ( '.' ) [ - 1 ]
data = in_file . read ( )
except :
if format == 'auto' :
format = 'smi'
return format_converter . convert ( data ,... |
def sgn ( x ) :
"""Return the sign of x .
Return a positive integer if x > 0 , 0 if x = = 0 , and a negative integer if
x < 0 . Raise ValueError if x is a NaN .
This function is equivalent to cmp ( x , 0 ) , but more efficient .""" | x = BigFloat . _implicit_convert ( x )
if is_nan ( x ) :
raise ValueError ( "Cannot take sign of a NaN." )
return mpfr . mpfr_sgn ( x ) |
def save_pip ( self , out_dir ) :
"""Saves the current working set of pip packages to requirements . txt""" | try :
import pkg_resources
installed_packages = [ d for d in iter ( pkg_resources . working_set ) ]
installed_packages_list = sorted ( [ "%s==%s" % ( i . key , i . version ) for i in installed_packages ] )
with open ( os . path . join ( out_dir , 'requirements.txt' ) , 'w' ) as f :
f . write ( "... |
def setup ( self ) :
"""Defers loading until needed .
Compares the existing mapping for each language with the current codebase .
If they differ , it automatically updates the index .""" | # Get the existing mapping & cache it . We ' ll compare it
# during the ` ` update ` ` & if it doesn ' t match , we ' ll put the new
# mapping .
for language in self . languages :
self . index_name = self . _index_name_for_language ( language )
try :
self . existing_mapping [ language ] = self . conn . ... |
def get_bit_values ( number , size = 32 ) :
"""Get bit values as a list for a given number
> > > get _ bit _ values ( 1 ) = = [ 0 ] * 31 + [ 1]
True
> > > get _ bit _ values ( 0xDEADBEEF )
[1 , 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 0 , 1 , \
1 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 1 ... | number += 2 ** size
return list ( map ( int , bin ( number ) [ - size : ] ) ) |
def enabled_checker ( func ) :
"""Access decorator which checks if a RPC method is enabled by our configuration""" | @ wraps ( func )
def wrap ( self , * args , ** kwargs ) :
if self . allowed_methods and isinstance ( self . allowed_methods , list ) and func . __name__ not in self . allowed_methods :
raise Exception ( "Method {} is disabled" . format ( func . __name__ ) )
return func ( self , * args , ** kwargs )
retu... |
def sample ( self , idx ) :
"""return a tuple of ( s , r , a , o ) ,
where s is of shape self . _ output _ shape , which is
[ H , W , ( hist _ len + 1 ) * channel ] if input is ( H , W , channel )""" | idx = ( self . _curr_pos + idx ) % self . _curr_size
k = self . history_len + 1
if idx + k <= self . _curr_size :
state = self . state [ idx : idx + k ]
reward = self . reward [ idx : idx + k ]
action = self . action [ idx : idx + k ]
isOver = self . isOver [ idx : idx + k ]
else :
end = idx + k - s... |
def _clear_ignore ( endpoint_props ) :
'''Both _ clear _ dict and _ ignore _ keys in a single iteration .''' | return dict ( ( prop_name , prop_val ) for prop_name , prop_val in six . iteritems ( endpoint_props ) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) |
def save_dot ( self , fd ) :
"""Saves a representation of the case in the Graphviz DOT language .""" | from pylon . io import DotWriter
DotWriter ( self ) . write ( fd ) |
def __register_class ( self , parsed_config ) :
"""Register the class implementing this config , so we only add it once .
Args :
parsed _ config : The JSON object with the API configuration being added .
Raises :
ApiConfigurationError : If the class has already been registered .""" | methods = parsed_config . get ( 'methods' )
if not methods :
return
# Determine the name of the class that implements this configuration .
service_classes = set ( )
for method in methods . itervalues ( ) :
rosy_method = method . get ( 'rosyMethod' )
if rosy_method and '.' in rosy_method :
method_cla... |
async def send ( self , message : Union [ Data , Iterable [ Data ] , AsyncIterable [ Data ] ] ) -> None :
"""This coroutine sends a message .
It sends a string ( : class : ` str ` ) as a text frame and a bytes - like
object ( : class : ` bytes ` , : class : ` bytearray ` , or : class : ` memoryview ` )
as a b... | await self . ensure_open ( )
# Unfragmented message - - this case must be handled first because
# strings and bytes - like objects are iterable .
if isinstance ( message , ( str , bytes , bytearray , memoryview ) ) :
opcode , data = prepare_data ( message )
await self . write_frame ( True , opcode , data )
# Fr... |
def validate_argmax_with_skipna ( skipna , args , kwargs ) :
"""If ' Series . argmax ' is called via the ' numpy ' library ,
the third parameter in its signature is ' out ' , which
takes either an ndarray or ' None ' , so check if the
' skipna ' parameter is either an instance of ndarray or
is None , since ... | skipna , args = process_skipna ( skipna , args )
validate_argmax ( args , kwargs )
return skipna |
def update ( self , name , modifiers , dtype , kind ) :
"""Updates the attributes for the function instance , handles name changes
in the parent module as well .""" | self . update_name ( name )
self . modifiers = modifiers
self . dtype = dtype
self . kind = kind
self . update_dtype ( ) |
def setup_environment ( chip , args_file = None ) :
"""Setup the SCons environment for compiling arm cortex code .
This will return an env that has all of the correct settings and create a
command line arguments file for GCC that contains all of the required
flags . The use of a command line argument file pas... | config = ConfigManager ( )
# Make sure we never get MSVC settings for windows since that has the wrong command line flags for gcc
if platform . system ( ) == 'Windows' :
env = Environment ( tools = [ 'mingw' ] , ENV = os . environ )
else :
env = Environment ( tools = [ 'default' ] , ENV = os . environ )
env [ '... |
def pretty_date ( the_datetime ) :
"""Attempt to return a human - readable time delta string .""" | # Source modified from
# http : / / stackoverflow . com / a / 5164027/176978
diff = datetime . utcnow ( ) - the_datetime
if diff . days > 7 or diff . days < 0 :
return the_datetime . strftime ( '%A %B %d, %Y' )
elif diff . days == 1 :
return '1 day ago'
elif diff . days > 1 :
return '{0} days ago' . format ... |
def _parse_dict ( features , new_names ) :
"""Helping function of ` _ parse _ features ` that parses a list .""" | feature_collection = OrderedDict ( )
for feature_type , feature_names in features . items ( ) :
try :
feature_type = FeatureType ( feature_type )
except ValueError :
ValueError ( 'Failed to parse {}, keys of the dictionary have to be instances ' 'of {}' . format ( features , FeatureType . __name... |
def unicodify ( filename ) :
"""Make sure filename is Unicode .
Because the tarfile module on Python 2 doesn ' t return Unicode .""" | if isinstance ( filename , bytes ) :
return filename . decode ( locale . getpreferredencoding ( ) )
else :
return filename |
def _rm_name_match ( s1 , s2 ) :
"""determine whether two sequence names from a repeatmasker alignment match .
: return : True if they are the same string , or if one forms a substring of the
other , else False""" | m_len = min ( len ( s1 ) , len ( s2 ) )
return s1 [ : m_len ] == s2 [ : m_len ] |
def from_string ( cls , alg_str ) :
"""Creates a location from a two character string consisting of
the file then rank written in algebraic notation .
Examples : e4 , b5 , a7
: type : alg _ str : str
: rtype : Location""" | try :
return cls ( int ( alg_str [ 1 ] ) - 1 , ord ( alg_str [ 0 ] ) - 97 )
except ValueError as e :
raise ValueError ( "Location.from_string {} invalid: {}" . format ( alg_str , e ) ) |
def merge ( filehandle_1 , filehandle_2 , output_filehandle ) :
"""Merges together two files maintaining sorted order .""" | line2 = filehandle_2 . readline ( )
for line1 in filehandle_1 . readlines ( ) :
while line2 != '' and line2 <= line1 :
output_filehandle . write ( line2 )
line2 = filehandle_2 . readline ( )
output_filehandle . write ( line1 )
while line2 != '' :
output_filehandle . write ( line2 )
line2... |
def parse_expmethodresponse ( self , tup_tree ) : # pylint : disable = unused - argument
"""This function not implemented .""" | raise CIMXMLParseError ( _format ( "Internal Error: Parsing support for element {0!A} is not " "implemented" , name ( tup_tree ) ) , conn_id = self . conn_id ) |
def p_statement ( self , p ) :
"""statement : OPTION _ AND _ VALUE""" | p [ 0 ] = [ 'statement' , p [ 1 ] [ 0 ] , p [ 1 ] [ 1 ] ]
if self . options . get ( 'lowercasenames' ) :
p [ 0 ] [ 1 ] = p [ 0 ] [ 1 ] . lower ( )
if ( not self . options . get ( 'nostripvalues' ) and not hasattr ( p [ 0 ] [ 2 ] , 'is_single_quoted' ) and not hasattr ( p [ 0 ] [ 2 ] , 'is_double_quoted' ) ) :
p... |
def create_new_example ( self , foo = '' , a = '' , b = '' ) :
"""Entity object factory .""" | return create_new_example ( foo = foo , a = a , b = b ) |
def _merge_adjacent_rows ( self , rows ) :
"""Resolves adjacent and overlapping rows . Overlapping rows are resolved as follows :
* The interval with the most recent begin date prevails for the overlapping period .
* If the begin dates are the same the interval with the most recent end date prevails .
* If th... | ret = list ( )
prev_row = None
for row in rows :
if prev_row :
relation = Allen . relation ( prev_row [ self . _key_start_date ] , prev_row [ self . _key_end_date ] , row [ self . _key_start_date ] , row [ self . _key_end_date ] )
if relation is None : # row holds an invalid interval ( prev _ row al... |
def findCfgFileForPkg ( pkgName , theExt , pkgObj = None , taskName = None ) :
"""Locate the configuration files for / from / within a given python package .
pkgName is a string python package name . This is used unless pkgObj
is given , in which case pkgName is taken from pkgObj . _ _ name _ _ .
theExt is ei... | # arg check
ext = theExt
if ext [ 0 ] != '.' :
ext = '.' + theExt
# Do the import , if needed
pkgsToTry = { }
if pkgObj :
pkgsToTry [ pkgObj . __name__ ] = pkgObj
else : # First try something simple like a regular or dotted import
try :
fl = [ ]
if pkgName . find ( '.' ) > 0 :
fl... |
def gradient ( self , wrt ) :
"""Gets the autodiff of current symbol .
This function can only be used if current symbol is a loss function .
. . note : : This function is currently not implemented .
Parameters
wrt : Array of String
keyword arguments of the symbol that the gradients are taken .
Returns
... | handle = SymbolHandle ( )
c_wrt = c_str_array ( wrt )
check_call ( _LIB . MXSymbolGrad ( self . handle , mx_uint ( len ( wrt ) ) , c_wrt , ctypes . byref ( handle ) ) )
return Symbol ( handle ) |
def _parse_properties ( response , result_class ) :
'''Extracts out resource properties and metadata information .
Ignores the standard http headers .''' | if response is None or response . headers is None :
return None
props = result_class ( )
for key , value in response . headers :
info = GET_PROPERTIES_ATTRIBUTE_MAP . get ( key )
if info :
if info [ 0 ] is None :
setattr ( props , info [ 1 ] , info [ 2 ] ( value ) )
else :
... |
def get_modifications ( self ) :
"""Extract Modification INDRA Statements .""" | # Find all event frames that are a type of protein modification
qstr = "$.events.frames[(@.type is 'protein-modification')]"
res = self . tree . execute ( qstr )
if res is None :
return
# Extract each of the results when possible
for r in res : # The subtype of the modification
modification_type = r . get ( 'su... |
def is_strict_subclass ( value , klass ) :
"""Check that ` value ` is a subclass of ` klass ` but that it is not actually
` klass ` . Unlike issubclass ( ) , does not raise an exception if ` value ` is
not a type .""" | return ( isinstance ( value , type ) and issubclass ( value , klass ) and value is not klass ) |
def show_system_monitor_output_switch_status_switch_state ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_system_monitor = ET . Element ( "show_system_monitor" )
config = show_system_monitor
output = ET . SubElement ( show_system_monitor , "output" )
switch_status = ET . SubElement ( output , "switch-status" )
switch_state = ET . SubElement ( switch_status , "switch-state" )
switch_s... |
def on_pumprequest ( self , event ) :
"""Activates or deactivates a connected pump .
: param event :""" | self . log ( "Updating pump status: " , event . controlvalue )
self . _set_digital_pin ( self . _pump_channel , event . controlvalue ) |
def cleanup_service ( self , factory , svc_registration ) : # type : ( Any , ServiceRegistration ) - > bool
"""If this bundle used that factory , releases the reference ; else does
nothing
: param factory : The service factory
: param svc _ registration : The ServiceRegistration object
: return : True if th... | svc_ref = svc_registration . get_reference ( )
try : # " service " for factories , " services " for prototypes
services , _ = self . __factored . pop ( svc_ref )
except KeyError :
return False
else :
if svc_ref . is_prototype ( ) and services :
for service in services :
try :
... |
def unpack_archive ( filename , extract_dir , progress_filter = default_filter , drivers = None ) :
"""Unpack ` filename ` to ` extract _ dir ` , or raise ` ` UnrecognizedFormat ` `
` progress _ filter ` is a function taking two arguments : a source path
internal to the archive ( ' / ' - separated ) , and a fil... | for driver in drivers or extraction_drivers :
try :
driver ( filename , extract_dir , progress_filter )
except UnrecognizedFormat :
continue
else :
return
else :
raise UnrecognizedFormat ( "Not a recognized archive type: %s" % filename ) |
def loads ( s , model ) :
"""Deserialize PENMAN graphs from a string
Args :
s ( str ) : serialized PENMAN graphs
model : Xmrs subclass instantiated from decoded triples
Returns :
a list of objects ( of class * model * )""" | graphs = penman . loads ( s , cls = XMRSCodec )
xs = [ model . from_triples ( g . triples ( ) ) for g in graphs ]
return xs |
def _stage_user_code_in_s3 ( self ) :
"""Upload the user training script to s3 and return the location .
Returns : s3 uri""" | local_mode = self . output_path . startswith ( 'file://' )
if self . code_location is None and local_mode :
code_bucket = self . sagemaker_session . default_bucket ( )
code_s3_prefix = '{}/source' . format ( self . _current_job_name )
kms_key = None
elif self . code_location is None :
code_bucket , _ = ... |
def parse_sysctl ( text ) :
'''Parse sysctl output .''' | lines = text . splitlines ( )
results = { }
for line in lines :
key , _ , value = line . decode ( 'ascii' ) . partition ( ': ' )
if key == 'hw.memsize' :
value = int ( value )
elif key == 'vm.swapusage' :
values = value . split ( ) [ 2 : : 3 ]
# every third token
su_unit = va... |
def predict_cdf ( self , X , quantile , nsamples = 200 , likelihood_args = ( ) ) :
r"""Predictive cumulative density function of a Bayesian GLM .
Parameters
X : ndarray
( N * , d ) array query input dataset ( N * samples , D dimensions ) .
quantile : float
The predictive probability , : math : ` p ( y ^ *... | # Get latent function samples
N = X . shape [ 0 ]
ps = np . empty ( ( N , nsamples ) )
fsamples = self . _sample_func ( X , nsamples )
# Push samples though likelihood cdf
cdfarg = tuple ( chain ( atleast_list ( self . like_hypers_ ) , likelihood_args ) )
for i , f in enumerate ( fsamples ) :
ps [ : , i ] = self . ... |
def upload_and_update ( path , token , cleanup ) :
"""The egg that the provided path points to will be uploaded to Databricks .
All jobs which use the same major version of the library will be updated
to use the new version , and all version of this library in the production
folder with the same major version... | config = _load_config ( CFG_FILE )
token = _resolve_input ( token , 'token' , 'token' , config )
folder = _resolve_input ( None , 'folder' , 'prod_folder' , config )
update_databricks ( logger , path , token , folder , update_jobs = True , cleanup = cleanup ) |
def process_result ( transmute_func , context , result , exc , content_type ) :
"""process a result :
transmute _ func : the transmute _ func function that returned the response .
context : the transmute _ context to use .
result : the return value of the function , which will be serialized and
returned bac... | if isinstance ( result , Response ) :
response = result
else :
response = Response ( result = result , code = transmute_func . success_code , success = True )
if exc :
if isinstance ( exc , APIException ) :
response . result = str ( exc )
response . success = False
response . code = ... |
def transpose ( self ) :
"""transpose operation of self
Returns
Matrix : Matrix
transpose of self""" | if not self . isdiagonal :
return type ( self ) ( x = self . __x . copy ( ) . transpose ( ) , row_names = self . col_names , col_names = self . row_names , autoalign = self . autoalign )
else :
return type ( self ) ( x = self . __x . copy ( ) , row_names = self . row_names , col_names = self . col_names , isdia... |
def quality_to_apply ( self ) :
"""Value of quality parameter to use in processing request .
Simple substitution of ' native ' or ' default ' if no quality
parameter is specified .""" | if ( self . request . quality is None ) :
if ( self . api_version <= '1.1' ) :
return ( 'native' )
else :
return ( 'default' )
return ( self . request . quality ) |
def _convert ( s , re_pattern , syllable_function , add_apostrophes = False , remove_apostrophes = False , separate_syllables = False ) :
"""Convert a string ' s syllables to a different transcription system .""" | original = s
new = ''
while original :
match = re . search ( re_pattern , original , re . IGNORECASE | re . UNICODE )
if match is None and original : # There are no more matches , but the given string isn ' t fully
# processed yet .
new += original
break
match_start , match_end = match .... |
def from_settings_product ( cls , environments , babblings , interest_models , sensorimotor_models , evaluate_at , testcases = None , same_testcases = False ) :
"""Creates a ExperimentPool with the product of all the given settings .
: param environments : e . g . [ ( ' simple _ arm ' , ' default ' ) , ( ' simple... | l = itertools . product ( environments , babblings , interest_models , sensorimotor_models )
settings = [ make_settings ( env , bab , im , sm , env_conf , im_conf , sm_conf ) for ( ( env , env_conf ) , bab , ( im , im_conf ) , ( sm , sm_conf ) ) in l ]
return cls ( settings , evaluate_at , testcases , same_testcases ) |
def handle_hooks ( stage , hooks , provider , context ) :
"""Used to handle pre / post _ build hooks .
These are pieces of code that we want to run before / after the builder
builds the stacks .
Args :
stage ( string ) : The current stage ( pre _ run , post _ run , etc ) .
hooks ( list ) : A list of : cla... | if not hooks :
logger . debug ( "No %s hooks defined." , stage )
return
hook_paths = [ ]
for i , h in enumerate ( hooks ) :
try :
hook_paths . append ( h . path )
except KeyError :
raise ValueError ( "%s hook #%d missing path." % ( stage , i ) )
logger . info ( "Executing %s hooks: %s" ,... |
def sdot ( U , V ) :
'''Computes the tensorproduct reducing last dimensoin of U with first dimension of V .
For matrices , it is equal to regular matrix product .''' | nu = U . ndim
# nv = V . ndim
return np . tensordot ( U , V , axes = ( nu - 1 , 0 ) ) |
def track_field ( field ) :
"""Returns whether the given field should be tracked by Auditlog .
Untracked fields are many - to - many relations and relations to the Auditlog LogEntry model .
: param field : The field to check .
: type field : Field
: return : Whether the given field should be tracked .
: r... | from auditlog . models import LogEntry
# Do not track many to many relations
if field . many_to_many :
return False
# Do not track relations to LogEntry
if getattr ( field , 'remote_field' , None ) is not None and field . remote_field . model == LogEntry :
return False
# 1.8 check
elif getattr ( field , 'rel' ,... |
def pw_score_jaccard ( self , s1 : ClassId , s2 : ClassId ) -> SimScore :
"""Calculate jaccard index of inferred associations of two subjects
| ancs ( s1 ) / \ ancs ( s2 ) |
| ancs ( s1 ) \ / ancs ( s2 ) |""" | am = self . assocmodel
a1 = am . inferred_types ( s1 )
a2 = am . inferred_types ( s2 )
num_union = len ( a1 | a2 )
if num_union == 0 :
return 0.0
return len ( a1 & a2 ) / num_union |
def copy_version_to_package ( path ) :
"""Copy the single source of truth version number into the package as well .""" | init_file = os . path . join ( path , "__init__.py" )
with open ( init_file , "r" ) as original_file :
lines = original_file . readlines ( )
with open ( init_file , "w" ) as new_file :
for line in lines :
if "__version__" not in line :
new_file . write ( line )
else :
new... |
def set_vflip ( self , val ) :
"""Flip all the images in the animation list vertically .""" | self . __vertical_flip = val
for image in self . images :
image . v_flip = val |
def getOutEdges ( self , vertex , rawResults = False ) :
"""An alias for getEdges ( ) that returns only the out Edges""" | return self . getEdges ( vertex , inEdges = False , outEdges = True , rawResults = rawResults ) |
def percentiles ( a , pcts , axis = None ) :
"""Like scoreatpercentile but can take and return array of percentiles .
Parameters
a : array
data
pcts : sequence of percentile values
percentile or percentiles to find score at
axis : int or None
if not None , computes scores over this axis
Returns
sc... | scores = [ ]
try :
n = len ( pcts )
except TypeError :
pcts = [ pcts ]
n = 0
for i , p in enumerate ( pcts ) :
if axis is None :
score = stats . scoreatpercentile ( a . ravel ( ) , p )
else :
score = N . apply_along_axis ( stats . scoreatpercentile , axis , a , p )
scores . appen... |
def decode_chain_list ( in_bytes ) :
"""Convert a list of bytes to a list of strings . Each string is of length mmtf . CHAIN _ LEN
: param in _ bytes : the input bytes
: return the decoded list of strings""" | bstrings = numpy . frombuffer ( in_bytes , numpy . dtype ( 'S' + str ( mmtf . utils . constants . CHAIN_LEN ) ) )
return [ s . decode ( "ascii" ) . strip ( mmtf . utils . constants . NULL_BYTE ) for s in bstrings ] |
def get_feature_names ( host_name , client_name , client_pass ) :
"""Get the names of all features in a PServer client .
Inputs : - host _ name : A string containing the address of the machine where the PServer instance is hosted .
- client _ name : The PServer client name .
- client _ pass : The PServer clie... | # Construct request .
request = construct_request ( model_type = "pers" , client_name = client_name , client_pass = client_pass , command = "getftrdef" , values = "ftr=*" )
# Send request .
request_result = send_request ( host_name , request )
# Extract a python list from xml object .
feature_names = list ( )
append_fe... |
def DEFAULT_RENAMER ( L , Names = None ) :
"""Renames overlapping column names of numpy ndarrays with structured dtypes
Rename the columns by using a simple convention :
* If ` L ` is a list , it will append the number in the list to the key
associated with the array .
* If ` L ` is a dictionary , the algor... | if isinstance ( L , dict ) :
Names = L . keys ( )
LL = L . values ( )
else :
if Names == None :
Names = range ( len ( L ) )
else :
assert len ( Names ) == len ( L )
LL = L
commons = Commons ( [ l . dtype . names for l in LL ] )
D = { }
for ( i , l ) in zip ( Names , LL ) :
d = { ... |
def get_perm_name ( cls , action , full = True ) :
"""Return the name of the permission for a given model and action .
By default it returns the full permission name ` app _ label . perm _ codename ` . If ` full = False ` , it returns only the
` perm _ codename ` .""" | codename = "{}_{}" . format ( action , cls . __name__ . lower ( ) )
if full :
return "{}.{}" . format ( cls . _meta . app_label , codename )
return codename |
def RGB_to_XYZ ( cobj , target_illuminant = None , * args , ** kwargs ) :
"""RGB to XYZ conversion . Expects 0-255 RGB values .
Based off of : http : / / www . brucelindbloom . com / index . html ? Eqn _ RGB _ to _ XYZ . html""" | # Will contain linearized RGB channels ( removed the gamma func ) .
linear_channels = { }
if isinstance ( cobj , sRGBColor ) :
for channel in [ 'r' , 'g' , 'b' ] :
V = getattr ( cobj , 'rgb_' + channel )
if V <= 0.04045 :
linear_channels [ channel ] = V / 12.92
else :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.