signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def rolling_fltr ( dem , f = np . nanmedian , size = 3 , circular = True , origmask = False ) :
"""General rolling filter ( default operator is median filter )
Can input any function f
Efficient for smaller arrays , correclty handles NaN , fills gaps""" | print ( "Applying rolling filter: %s with size %s" % ( f . __name__ , size ) )
dem = malib . checkma ( dem )
# Convert to float32 so we can fill with nan
dem = dem . astype ( np . float32 )
newshp = ( dem . size , size * size )
# Force a step size of 1
t = malib . sliding_window_padded ( dem . filled ( np . nan ) , ( s... |
def termpt ( method , ilusrc , target , et , fixref , abcorr , corloc , obsrvr , refvec , rolstp , ncuts , schstp , soltol , maxn ) :
"""Find terminator points on a target body . The caller specifies
half - planes , bounded by the illumination source center - target center
vector , in which to search for termin... | method = stypes . stringToCharP ( method )
ilusrc = stypes . stringToCharP ( ilusrc )
target = stypes . stringToCharP ( target )
et = ctypes . c_double ( et )
fixref = stypes . stringToCharP ( fixref )
abcorr = stypes . stringToCharP ( abcorr )
corloc = stypes . stringToCharP ( corloc )
obsrvr = stypes . stringToCharP ... |
def create ( cls , tx_signers , recipients , metadata = None , asset = None ) :
"""A simple way to generate a ` CREATE ` transaction .
Note :
This method currently supports the following Cryptoconditions
use cases :
- Ed25519
- ThresholdSha256
Additionally , it provides support for the following Bigchai... | ( inputs , outputs ) = cls . validate_create ( tx_signers , recipients , asset , metadata )
return cls ( cls . CREATE , { 'data' : asset } , inputs , outputs , metadata ) |
def get_default_config ( self ) :
"""Return the default config for the handler""" | config = super ( NullHandler , self ) . get_default_config ( )
config . update ( { } )
return config |
def _CamelCaseToSnakeCase ( path_name ) :
"""Converts a field name from camelCase to snake _ case .""" | result = [ ]
for c in path_name :
if c == '_' :
raise ParseError ( 'Fail to parse FieldMask: Path name ' '{0} must not contain "_"s.' . format ( path_name ) )
if c . isupper ( ) :
result += '_'
result += c . lower ( )
else :
result += c
return '' . join ( result ) |
def data_labels ( self ) :
"""| DataLabels | instance providing properties and methods on the
collection of data labels associated with this plot .""" | dLbls = self . _element . dLbls
if dLbls is None :
raise ValueError ( 'plot has no data labels, set has_data_labels = True first' )
return DataLabels ( dLbls ) |
def image_recognition ( image , cloud = None , batch = False , api_key = None , version = None , ** kwargs ) :
"""Given an input image , returns a dictionary of image classifications with associated scores
* Input can be either grayscale or rgb color and should either be a numpy array or nested list format .
* ... | image = data_preprocess ( image , batch = batch , size = 144 , min_axis = True )
url_params = { "batch" : batch , "api_key" : api_key , "version" : version }
return api_handler ( image , cloud = cloud , api = "imagerecognition" , url_params = url_params , ** kwargs ) |
def register_layout ( self , name , layout ) :
"""Registers given layout .
: param name : Layout name .
: type name : unicode
: param layout : Layout object .
: type layout : Layout
: return : Method success .
: rtype : bool""" | if name in self :
raise umbra . exceptions . LayoutRegistrationError ( "{0} | '{1}' layout is already registered!" . format ( self . __class__ . __name__ , name ) )
self . __layouts [ name ] = layout
return True |
def _get_xy_tree ( xy , degree ) :
"""Evaluates the entire tree of 2d mononomials .
The return value is a list of arrays , where ` out [ k ] ` hosts the ` 2 * k + 1 `
values of the ` k ` th level of the tree
(0 , 0)
(1 , 0 ) ( 0 , 1)
(2 , 0 ) ( 1 , 1 ) ( 0 , 2)""" | x , y = xy
tree = [ numpy . array ( [ numpy . ones ( x . shape , dtype = int ) ] ) ]
for d in range ( degree ) :
tree . append ( numpy . concatenate ( [ tree [ - 1 ] * x , [ tree [ - 1 ] [ - 1 ] * y ] ] ) )
return tree |
def purge ( self , queue , virtual_host = '/' ) :
"""Purge a Queue .
: param str queue : Queue name
: param str virtual _ host : Virtual host name
: raises ApiError : Raises if the remote server encountered an error .
: raises ApiConnectionError : Raises if there was a connectivity issue .
: rtype : None"... | virtual_host = quote ( virtual_host , '' )
return self . http_client . delete ( API_QUEUE_PURGE % ( virtual_host , queue ) ) |
def payment_end ( self , account , wallet ) :
"""End a payment session . Marks the account as available for use in a
payment session .
: param account : Account to mark available
: type account : str
: param wallet : Wallet to end payment session for
: type wallet : str
: raises : : py : exc : ` nano . ... | account = self . _process_value ( account , 'account' )
wallet = self . _process_value ( wallet , 'wallet' )
payload = { "account" : account , "wallet" : wallet }
resp = self . call ( 'payment_end' , payload )
return resp == { } |
def leading_particle ( df ) :
"""Grab leading particle ( neutrino , most energetic bundle muon ) .
Note : selecting the most energetic mc particle does not always select
the neutrino ! In some sub - percent cases , the post - interaction
secondaries can have more energy than the incoming neutrino !
aanet co... | leading = df . groupby ( 'event_id' , as_index = False ) . first ( )
unique = leading . type . unique ( )
if len ( unique ) == 1 and unique [ 0 ] == 0 :
leading = most_energetic ( df )
return leading |
def save_group ( store , * args , ** kwargs ) :
"""Convenience function to save several NumPy arrays to the local file system , following a
similar API to the NumPy savez ( ) / savez _ compressed ( ) functions .
Parameters
store : MutableMapping or string
Store or path to directory in file system or name of... | if len ( args ) == 0 and len ( kwargs ) == 0 :
raise ValueError ( 'at least one array must be provided' )
# handle polymorphic store arg
may_need_closing = isinstance ( store , str )
store = normalize_store_arg ( store , clobber = True )
try :
grp = _create_group ( store , overwrite = True )
for i , arr in ... |
def MarkdownColumn ( name , deferred = False , group = None , ** kwargs ) :
"""Create a composite column that autogenerates HTML from Markdown text ,
storing data in db columns named with ` ` _ html ` ` and ` ` _ text ` ` prefixes .""" | return composite ( MarkdownComposite , Column ( name + '_text' , UnicodeText , ** kwargs ) , Column ( name + '_html' , UnicodeText , ** kwargs ) , deferred = deferred , group = group or name ) |
def _valid_lsid ( self ) :
"""Performs some basic ( non - comprehensive ) LSID validation
: return :""" | if not isinstance ( self . lsid , str ) :
raise TypeError ( "lsid is not a string, string expected: " + str ( self . lsid ) )
if self . lsid . count ( ':' ) != 4 :
raise ValueError ( "lsid contains incorrect number of colons, 4 expected: " + str ( self . lsid ) )
if self . lsid . split ( ':' ) [ 0 ] . lower ( )... |
def p_field_optional2_2 ( self , p ) :
"""field : name arguments selection _ set""" | p [ 0 ] = Field ( name = p [ 1 ] , arguments = p [ 2 ] , selections = p [ 3 ] ) |
def check_base_suggested_attributes ( self , dataset ) :
'''Check the global suggested attributes for 2.0 templates . These go an extra step besides
just checking that they exist .
: param netCDF4 . Dataset dataset : An open netCDF dataset
: creator _ type = " " ; / / . . . . . SUGGESTED - Specifies type of c... | suggested_ctx = TestCtx ( BaseCheck . LOW , 'Suggested global attributes' )
# Do any of the variables define platform ?
platform_name = getattr ( dataset , 'platform' , '' )
suggested_ctx . assert_true ( platform_name != '' , 'platform should exist and point to a term in :platform_vocabulary.' )
cdm_data_type = getattr... |
def saveVirtualOutputs ( self , outdict ) :
"""Assign in - memory versions of generated products for this
` ` imageObject ` ` based on dictionary ' outdict ' .""" | if not self . inmemory :
return
for outname in outdict :
self . virtualOutputs [ outname ] = outdict [ outname ] |
def has_event ( self , event , cameo_code ) :
"""Test whether there is an " event2 " or " event3 " entry for the given cameo code
Args :
event :
cameo _ code :
Returns :""" | if self . has_cameo_code ( cameo_code ) :
entry = self . mapping . get ( cameo_code )
if entry :
return entry [ self . event_name [ event ] ]
return False |
def _get_deleted_fs ( name , blade ) :
'''Private function to check
if a file systeem has already been deleted''' | try :
_fs = _get_fs ( name , blade )
if _fs and _fs . destroyed :
return _fs
except rest . ApiException :
return None |
async def run_with_interrupt ( task , * events , loop = None ) :
"""Awaits a task while allowing it to be interrupted by one or more
` asyncio . Event ` s .
If the task finishes without the events becoming set , the results of the
task will be returned . If the event become set , the task will be cancelled
... | loop = loop or asyncio . get_event_loop ( )
task = asyncio . ensure_future ( task , loop = loop )
event_tasks = [ loop . create_task ( event . wait ( ) ) for event in events ]
done , pending = await asyncio . wait ( [ task ] + event_tasks , loop = loop , return_when = asyncio . FIRST_COMPLETED )
for f in pending :
... |
def sayHelloAsync ( self , name = "Not given" , message = "nothing" ) :
"""Implementation of IHello . sayHelloAsync .
This method will be executed via some thread , and the remote caller
will not block .
This method should return either a String result ( since the return type
of IHello . sayHelloAsync is Co... | print ( "Python.sayHelloAsync called by: {0} " "with message: '{1}'" . format ( name , message ) )
return ( "PythonAsync says: Howdy {0} " "that's a nice runtime you got there" . format ( name ) ) |
def edit_labels_on_gce_role ( self , name , add = None , remove = None , mount_point = DEFAULT_MOUNT_POINT ) :
"""Edit labels for an existing GCE role in the backend .
This allows you to add or remove labels ( keys , values , or both ) from the list of keys on the role .
Supported methods :
POST : / auth / { ... | params = { 'add' : add , 'remove' : remove , }
api_path = '/v1/auth/{mount_point}/role/{name}/labels' . format ( mount_point = mount_point , name = name , )
return self . _adapter . post ( url = api_path , json = params , ) |
def undefine ( self ) :
"""Undefine the Generic .
Python equivalent of the CLIPS undefgeneric command .
The object becomes unusable after this method has been called .""" | if lib . EnvUndefgeneric ( self . _env , self . _gnc ) != 1 :
raise CLIPSError ( self . _env )
self . _env = None |
def blockAllSignals ( self , state ) :
"""Fully blocks all signals - tree , header signals .
: param state | < bool >""" | self . blockSignals ( state )
self . header ( ) . blockSignals ( state ) |
def set_sound_mode ( self , sound_mode ) :
"""Set sound _ mode of device .
Valid values depend on the device and should be taken from
" sound _ mode _ list " .
Return " True " on success and " False " on fail .""" | if sound_mode == ALL_ZONE_STEREO :
if self . _set_all_zone_stereo ( True ) :
self . _sound_mode_raw = ALL_ZONE_STEREO
return True
else :
return False
if self . _sound_mode_raw == ALL_ZONE_STEREO :
if not self . _set_all_zone_stereo ( False ) :
return False
# For selection of ... |
def retry ( * dargs , ** dkw ) :
"""Decorator function that instantiates the Retrying object
@ param * dargs : positional arguments passed to Retrying object
@ param * * dkw : keyword arguments passed to the Retrying object""" | # support both @ retry and @ retry ( ) as valid syntax
if len ( dargs ) == 1 and callable ( dargs [ 0 ] ) :
def wrap_simple ( f ) :
@ six . wraps ( f )
def wrapped_f ( * args , ** kw ) :
return Retrying ( ) . call ( f , * args , ** kw )
return wrapped_f
return wrap_simple ( d... |
def _submit_task_with_template ( self , task_ids ) :
'''Submit tasks by interpolating a shell script defined in job _ template''' | runtime = self . config
runtime . update ( { 'workdir' : os . getcwd ( ) , 'cur_dir' : os . getcwd ( ) , # for backward compatibility
'verbosity' : env . verbosity , 'sig_mode' : env . config . get ( 'sig_mode' , 'default' ) , 'run_mode' : env . config . get ( 'run_mode' , 'run' ) , 'home_dir' : os . path . expanduser ... |
def remove_entry ( self , jid , * , timeout = None ) :
"""Request removal of the roster entry identified by the given bare
` jid ` . If the entry currently has any subscription state , the server
will send the corresponding unsubscribing presence stanzas .
` timeout ` is the maximum time in seconds to wait fo... | yield from self . client . send ( stanza . IQ ( structs . IQType . SET , payload = roster_xso . Query ( items = [ roster_xso . Item ( jid = jid , subscription = "remove" ) ] ) ) , timeout = timeout ) |
def compile ( self , script , bare = False ) :
'''compile a CoffeeScript code to a JavaScript code .
if bare is True , then compile the JavaScript without the top - level
function safety wrapper ( like the coffee command ) .''' | if not hasattr ( self , '_context' ) :
self . _context = self . _runtime . compile ( self . _compiler_script )
return self . _context . call ( "CoffeeScript.compile" , script , { 'bare' : bare } ) |
def reorient_image ( image , axis1 , axis2 = None , doreflection = False , doscale = 0 , txfn = None ) :
"""Align image along a specified axis
ANTsR function : ` reorientImage `
Arguments
image : ANTsImage
image to reorient
axis1 : list / tuple of integers
vector of size dim , might need to play w / axi... | inpixeltype = image . pixeltype
if image . pixeltype != 'float' :
image = image . clone ( 'float' )
axis_was_none = False
if axis2 is None :
axis_was_none = True
axis2 = [ 0 ] * image . dimension
axis1 = np . array ( axis1 )
axis2 = np . array ( axis2 )
axis1 = axis1 / np . sqrt ( np . sum ( axis1 * axis1 )... |
def stop_Note ( self , note , channel = 1 ) :
"""Stop a note on a channel .
If Note . channel is set , it will take presedence over the channel
argument given here .""" | if hasattr ( note , 'channel' ) :
channel = note . channel
self . stop_event ( int ( note ) + 12 , int ( channel ) )
self . notify_listeners ( self . MSG_STOP_INT , { 'channel' : int ( channel ) , 'note' : int ( note ) + 12 } )
self . notify_listeners ( self . MSG_STOP_NOTE , { 'channel' : int ( channel ) , 'note' ... |
def _select_options ( pat ) :
"""returns a list of keys matching ` pat `
if pat = = " all " , returns all registered options""" | # short - circuit for exact key
if pat in _registered_options :
return [ pat ]
# else look through all of them
keys = sorted ( _registered_options . keys ( ) )
if pat == 'all' : # reserved key
return keys
return [ k for k in keys if re . search ( pat , k , re . I ) ] |
def interpret ( self , infile ) :
"""Process a file of rest and return list of dicts""" | data = [ ]
for record in self . generate_records ( infile ) :
data . append ( record )
return data |
def compare ( s1 , s2 , ** kwargs ) :
"""Compares two strings and returns their similarity .
: param s1 : first string
: param s2 : second string
: param kwargs : additional keyword arguments passed to _ _ init _ _ .
: return : similarity between 0.0 and 1.0.
> > > from ngram import NGram
> > > NGram . ... | if s1 is None or s2 is None :
if s1 == s2 :
return 1.0
return 0.0
try :
return NGram ( [ s1 ] , ** kwargs ) . search ( s2 ) [ 0 ] [ 1 ]
except IndexError :
return 0.0 |
def walk_regularity_symmetry ( self , data_frame ) :
"""This method extracts the step and stride regularity and also walk symmetry .
: param data _ frame : The data frame . It should have x , y , and z columns .
: type data _ frame : pandas . DataFrame
: return step _ regularity : Regularity of steps on [ x ,... | def _symmetry ( v ) :
maxtab , _ = peakdet ( v , self . delta )
return maxtab [ 1 ] [ 1 ] , maxtab [ 2 ] [ 1 ]
step_regularity_x , stride_regularity_x = _symmetry ( autocorrelation ( data_frame . x ) )
step_regularity_y , stride_regularity_y = _symmetry ( autocorrelation ( data_frame . y ) )
step_regularity_z ,... |
def is_address_executable_and_writeable ( self , address ) :
"""Determines if an address belongs to a commited , writeable and
executable page . The page may or may not have additional permissions .
Looking for writeable and executable pages is important when
exploiting a software vulnerability .
@ note : R... | try :
mbi = self . mquery ( address )
except WindowsError :
e = sys . exc_info ( ) [ 1 ]
if e . winerror == win32 . ERROR_INVALID_PARAMETER :
return False
raise
return mbi . is_executable_and_writeable ( ) |
def get_asset_tarball ( asset_name , src_dir , dest_project , dest_folder , json_out ) :
"""If the src _ dir contains a " resources " directory its contents are archived and
the archived file is uploaded to the platform""" | if os . path . isdir ( os . path . join ( src_dir , "resources" ) ) :
temp_dir = tempfile . mkdtemp ( )
try :
resource_file = os . path . join ( temp_dir , asset_name + "_resources.tar.gz" )
cmd = [ "tar" , "-czf" , resource_file , "-C" , os . path . join ( src_dir , "resources" ) , "." ]
... |
def _button_delete_clicked ( self ) :
"""Save the selected cmap .""" | name = str ( self . _combobox_cmaps . currentText ( ) )
self . delete_colormap ( name )
self . _combobox_cmaps . setEditText ( "" )
self . _load_cmap_list ( ) |
def read_secret ( path , key = None ) :
'''Return the value of key at path in vault , or entire secret
Jinja Example :
. . code - block : : jinja
my - secret : { { salt [ ' vault ' ] . read _ secret ( ' secret / my / secret ' , ' some - key ' ) } }
. . code - block : : jinja
{ % set supersecret = salt [ '... | log . debug ( 'Reading Vault secret for %s at %s' , __grains__ [ 'id' ] , path )
try :
url = 'v1/{0}' . format ( path )
response = __utils__ [ 'vault.make_request' ] ( 'GET' , url )
if response . status_code != 200 :
response . raise_for_status ( )
data = response . json ( ) [ 'data' ]
if ke... |
def binary_operation_math ( self , rule , left , right , ** kwargs ) :
"""Implementation of : py : func : ` pynspect . traversers . RuleTreeTraverser . binary _ operation _ math ` interface .""" | return self . evaluate_binop_math ( rule . operation , left , right , ** kwargs ) |
def clean ( self , config = True , catalog = False , check = False ) :
"""Remove the generated SExtractor files ( if any ) .
If config is True , remove generated configuration files .
If catalog is True , remove the output catalog .
If check is True , remove output check image .""" | try :
if ( config ) :
os . unlink ( self . config [ 'FILTER_NAME' ] )
os . unlink ( self . config [ 'PARAMETERS_NAME' ] )
os . unlink ( self . config [ 'STARNNW_NAME' ] )
os . unlink ( self . config [ 'CONFIG_FILE' ] )
if ( catalog ) :
os . unlink ( self . config [ 'CATAL... |
def _prepare_init_params_from_job_description ( cls , job_details ) :
"""Convert the transform job description to init params that can be handled by the class constructor
Args :
job _ details ( dict ) : the returned job details from a describe _ transform _ job API call .
Returns :
dict : The transformed in... | init_params = dict ( )
init_params [ 'model_name' ] = job_details [ 'ModelName' ]
init_params [ 'instance_count' ] = job_details [ 'TransformResources' ] [ 'InstanceCount' ]
init_params [ 'instance_type' ] = job_details [ 'TransformResources' ] [ 'InstanceType' ]
init_params [ 'volume_kms_key' ] = job_details [ 'Transf... |
def is_progressive ( image ) :
"""Check to see if an image is progressive .""" | if not isinstance ( image , Image . Image ) : # Can only check PIL images for progressive encoding .
return False
return ( 'progressive' in image . info ) or ( 'progression' in image . info ) |
def reject ( self ) :
"""Handle ESC key""" | if self . controller . is_running :
self . info ( self . tr ( "Stopping.." ) )
self . controller . is_running = False |
def evaluation_termination ( population , num_generations , num_evaluations , args ) :
"""Return True if the number of function evaluations meets or exceeds a maximum .
This function compares the number of function evaluations that have been
generated with a specified maximum . It returns True if the maximum is... | max_evaluations = args . setdefault ( 'max_evaluations' , len ( population ) )
return num_evaluations >= max_evaluations |
def to_json ( self ) :
"""Convert the Design Day to a dictionary .""" | return { 'location' : self . location . to_json ( ) , 'design_days' : [ des_d . to_json ( ) for des_d in self . design_days ] } |
def map_texture_to_surface ( texture , surface ) :
"""Returns values on a surface for points on a texture .
Args :
texture ( texture ) : the texture to trace over the surface
surface ( surface ) : the surface to trace along
Returns :
an array of surface heights for each point in the
texture . Line separ... | texture_x , texture_y = texture
surface_h , surface_w = surface . shape
surface_x = np . clip ( np . int32 ( surface_w * texture_x - 1e-9 ) , 0 , surface_w - 1 )
surface_y = np . clip ( np . int32 ( surface_h * texture_y - 1e-9 ) , 0 , surface_h - 1 )
surface_z = surface [ surface_y , surface_x ]
return surface_z |
def get_arg_names ( target ) -> typing . List [ str ] :
"""Gets the list of named arguments for the target function
: param target :
Function for which the argument names will be retrieved""" | code = getattr ( target , '__code__' )
if code is None :
return [ ]
arg_count = code . co_argcount
kwarg_count = code . co_kwonlyargcount
args_index = get_args_index ( target )
kwargs_index = get_kwargs_index ( target )
arg_names = list ( code . co_varnames [ : arg_count ] )
if args_index != - 1 :
arg_names . a... |
def _validate ( self , writing = False ) :
"""Verify that the box obeys the specifications .""" | # channel type and association must be specified .
if not ( ( len ( self . index ) == len ( self . channel_type ) ) and ( len ( self . channel_type ) == len ( self . association ) ) ) :
msg = ( "The length of the index ({index}), channel_type " "({channel_type}), and association ({association}) inputs " "must be th... |
def go_to_marker ( self , row , col , table_type ) :
"""Move to point in time marked by the marker .
Parameters
row : QtCore . int
column : QtCore . int
table _ type : str
' dataset ' table or ' annot ' table , it works on either""" | if table_type == 'dataset' :
marker_time = self . idx_marker . property ( 'start' ) [ row ]
marker_end_time = self . idx_marker . property ( 'end' ) [ row ]
else :
marker_time = self . idx_annot_list . property ( 'start' ) [ row ]
marker_end_time = self . idx_annot_list . property ( 'end' ) [ row ]
wind... |
def all_subnets_shorter_prefix ( ip_net , cidr , include_default = False ) :
"""Function to return every subnet a ip can belong to with a shorter prefix
Args :
ip _ net : Unicast or Multicast IP address or subnet in the following format 192.168.1.1 , 239.1.1.1
cidr : CIDR value of 0 to 32
include _ default ... | subnets_list = list ( )
if include_default :
while int ( cidr ) >= 0 :
try :
subnets_list . append ( '%s/%s' % ( whole_subnet_maker ( ip_net , cidr ) , cidr ) )
except Exception as e :
LOGGER . critical ( 'Function all_subnets_shorter_prefix {item}' . format ( item = e ) )
... |
def close ( self , reason = None ) :
"""Stop consuming messages and perform an orderly shutdown .
If ` ` reason ` ` is None , then this is considered a regular close .""" | with self . _closing :
if self . _closed :
return
self . _websocket . close ( )
self . _consumer . join ( )
self . _consumer = None
self . _websocket = None
self . _closed = True
for cb in self . _close_callbacks :
cb ( self , reason ) |
def get_gemeente_by_id ( self , id ) :
'''Retrieve a ` gemeente ` by the crab id .
: param integer id : The CRAB id of the gemeente .
: rtype : : class : ` Gemeente `''' | def creator ( ) :
res = crab_gateway_request ( self . client , 'GetGemeenteByGemeenteId' , id )
if res == None :
raise GatewayResourceNotFoundException ( )
return Gemeente ( res . GemeenteId , res . GemeenteNaam , res . NisGemeenteCode , Gewest ( res . GewestId ) , res . TaalCode , ( res . CenterX ,... |
def _daemon ( self , please_stop , only_coverage_revisions = False ) :
'''Runs continuously to prefill the temporal and
annotations table with the coverage revisions * .
* A coverage revision is a revision which has had
code coverage run on it .
: param please _ stop : Used to stop the daemon
: return : N... | while not please_stop : # Get all known files and their latest revisions on the frontier
files_n_revs = self . conn . get ( "SELECT file, revision FROM latestFileMod" )
# Split these files into groups of revisions to make it
# easier to update them . If we group them together , we
# may end up updating ... |
def listen_now_dismissed_items ( self ) :
"""Get a listing of items dismissed from Listen Now tab .""" | response = self . _call ( mc_calls . ListenNowGetDismissedItems )
dismissed_items = response . body . get ( 'items' , [ ] )
return dismissed_items |
def annotation_wrapper ( annotation , doc = None ) :
"""Defines an annotation , which can be applied to attributes in a database model .""" | def decorator ( attr ) :
__cache__ . setdefault ( attr , [ ] ) . append ( annotation )
# Also mark the annotation on the object itself . This will
# fail if the object has a restrictive _ _ slots _ _ , but it ' s
# required for some objects like Column because SQLAlchemy copies
# them in subclasses ... |
def deposit ( self , beneficiary : Address , total_deposit : TokenAmount , block_identifier : BlockSpecification , ) -> None :
"""Deposit provided amount into the user - deposit contract
to the beneficiary ' s account .""" | token_address = self . token_address ( block_identifier )
token = Token ( jsonrpc_client = self . client , token_address = token_address , contract_manager = self . contract_manager , )
log_details = { 'beneficiary' : pex ( beneficiary ) , 'contract' : pex ( self . address ) , 'total_deposit' : total_deposit , }
checki... |
def Restore ( cls , state ) :
"""Unserialize this object .""" | target = SlotIdentifier . FromString ( state . get ( 'target' ) )
data = base64 . b64decode ( state . get ( 'data' ) )
var_id = state . get ( 'var_id' )
valid = state . get ( 'valid' )
return ConfigEntry ( target , var_id , data , valid ) |
def startproject ( project_name ) :
"""build a full status project""" | # the destination path
dst_path = os . path . join ( os . getcwd ( ) , project_name )
start_init_info ( dst_path )
# create dst path
_mkdir_p ( dst_path )
# create project tree
os . chdir ( dst_path )
# create files
init_code ( 'manage.py' , _manage_admin_code )
init_code ( 'requirement.txt' , _requirement_admin_code )... |
def Validate ( self ) :
"""Check the method is well constructed .""" | if not self . check_id :
raise DefinitionError ( "Check has missing check_id value" )
cls_name = self . check_id
if not self . method :
raise DefinitionError ( "Check %s has no methods" % cls_name )
ValidateMultiple ( self . method , "Check %s has invalid method definitions" % cls_name ) |
def upload_file ( self , path = None , stream = None , name = None , ** kwargs ) :
"""Uploads file to WeedFS
I takes either path or stream and name and upload it
to WeedFS server .
Returns fid of the uploaded file .
: param string path :
: param string stream :
: param string name :
: rtype : string o... | params = "&" . join ( [ "%s=%s" % ( k , v ) for k , v in kwargs . items ( ) ] )
url = "http://{master_addr}:{master_port}/dir/assign{params}" . format ( master_addr = self . master_addr , master_port = self . master_port , params = "?" + params if params else '' )
data = json . loads ( self . conn . get_data ( url ) )
... |
def transpose ( self , * dims ) -> 'DataArray' :
"""Return a new DataArray object with transposed dimensions .
Parameters
* dims : str , optional
By default , reverse the dimensions . Otherwise , reorder the
dimensions to this order .
Returns
transposed : DataArray
The returned DataArray ' s array is ... | variable = self . variable . transpose ( * dims )
return self . _replace ( variable ) |
def _fetch_atari_metrics ( base_env ) :
"""Atari games have multiple logical episodes , one per life .
However for metrics reporting we count full episodes all lives included .""" | unwrapped = base_env . get_unwrapped ( )
if not unwrapped :
return None
atari_out = [ ]
for u in unwrapped :
monitor = get_wrapper_by_cls ( u , MonitorEnv )
if not monitor :
return None
for eps_rew , eps_len in monitor . next_episode_results ( ) :
atari_out . append ( RolloutMetrics ( ep... |
def record_state ( serv_name , state , conn = None ) :
"""MAKE A DOCSTRING
: param serv _ name : < str > service name of plugin instance
: param state : < dictionary > plugin state
: param conn : < rethinkdb . DefaultConnection >
: return :""" | serv_filter = { SERVICE_KEY : serv_name }
updated = { PLUGIN_STATE_KEY : state }
return RPC . filter ( serv_filter ) . update ( updated ) . run ( conn ) |
def register ( cls ) :
"""Register a given model in the registry""" | registry_entry = RegistryEntry ( category = cls . category , namespace = cls . namespace , name = cls . name , cls = cls )
if registry_entry not in registry and not exists_in_registry ( cls . category , cls . namespace , cls . name ) :
registry . append ( registry_entry )
else :
log . warn ( "Class {0} already ... |
def insert_sort ( node , target ) :
"""Insert node into sorted position in target tree .
Uses sort function and language from target""" | sort = target . sort
lang = target . lang
collator = Collator . createInstance ( Locale ( lang ) if lang else Locale ( ) )
for child in target . tree :
if collator . compare ( sort ( child ) or '' , sort ( node ) or '' ) > 0 :
child . addprevious ( node )
break
else :
target . tree . append ( no... |
def replace_namespaced_horizontal_pod_autoscaler ( self , name , namespace , body , ** kwargs ) :
"""replace the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . replace _ name... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_horizontal_pod_autoscaler_with_http_info ( name , namespace , body , ** kwargs )
else :
( data ) = self . replace_namespaced_horizontal_pod_autoscaler_with_http_info ( name , namespace , body , ** kwarg... |
def run ( cmd , * , args = '' , timeout = 600 ) :
"""Execute a process
: param cmd ( str ) : name of the executable
: param args ( str , optional ) : arbitrary arguments
: param timeout ( int , optional ) : Execution timeout
: raises OSError : if the execution of cmd fails""" | # type checks
utils . chkstr ( cmd , 'cmd' )
utils . chkstr ( args , 'args' )
# execute the command
r = envoy . run ( "{cmd} {args}" . format ( cmd = cmd , args = args ) , timeout = timeout )
# log stdout
log . msg_debug ( "{cmd} > {stdout}" . format ( cmd = cmd , stdout = r . std_out . strip ( ) ) )
# In this way , we... |
def i2m ( self , pkt , i ) :
"""" Internal " ( IP as bytes , mask as int ) to " machine "
representation .""" | mask , ip = i
ip = socket . inet_aton ( ip )
return struct . pack ( ">B" , mask ) + ip [ : self . mask2iplen ( mask ) ] |
def auth_add_creds ( self , username , password , pwtype = 'plain' ) :
"""Add a valid set of credentials to be accepted for authentication .
Calling this function will automatically enable requiring
authentication . Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the ... | if not isinstance ( password , ( bytes , str ) ) :
raise TypeError ( "auth_add_creds() argument 2 must be bytes or str, not {0}" . format ( type ( password ) . __name__ ) )
pwtype = pwtype . lower ( )
if not pwtype in ( 'plain' , 'md5' , 'sha1' , 'sha256' , 'sha384' , 'sha512' ) :
raise ValueError ( 'invalid pa... |
def _find_entry_call ( self , frames ) :
"""attempts to auto - discover the correct frame""" | back_i = 0
pout_path = self . _get_src_file ( self . modname )
for frame_i , frame in enumerate ( frames ) :
if frame [ 1 ] == pout_path :
back_i = frame_i
return Call ( frames [ back_i ] ) |
def get_list_qtype ( array ) :
'''Finds out a corresponding qtype for a specified ` QList ` / ` numpy . ndarray `
instance .
: Parameters :
- ` array ` ( ` QList ` or ` numpy . ndarray ` ) - array to be checked
: returns : ` integer ` - qtype matching the specified array object''' | if not isinstance ( array , numpy . ndarray ) :
raise ValueError ( 'array parameter is expected to be of type: numpy.ndarray, got: %s' % type ( array ) )
if isinstance ( array , QList ) :
return - abs ( array . meta . qtype )
qtype = None
if str ( array . dtype ) in ( '|S1' , '<U1' , '>U1' , '|U1' ) :
qtype... |
def loglike ( self , y , f ) :
r"""Poisson log likelihood .
Parameters
y : ndarray
array of integer targets
f : ndarray
latent function from the GLM prior ( : math : ` \ mathbf { f } =
\ boldsymbol \ Phi \ mathbf { w } ` )
Returns
logp : ndarray
the log likelihood of each y given each f under this... | y , f = np . broadcast_arrays ( y , f )
if self . tranfcn == 'exp' :
g = np . exp ( f )
logg = f
else :
g = softplus ( f )
logg = np . log ( g )
return y * logg - g - gammaln ( y + 1 ) |
def iteritems ( self , key_type = None , return_all_keys = False ) :
"""Returns an iterator over the dictionary ' s ( key , value ) pairs .
@ param key _ type if specified , iterator will be returning only ( key , value ) pairs for this type of key .
Otherwise ( if not specified ) ( ( keys , . . . ) , value )
... | if key_type is None :
for item in self . items_dict . items ( ) :
yield item
return
used_keys = set ( )
key = str ( key_type )
if key in self . __dict__ :
for key , keys in self . __dict__ [ key ] . items ( ) :
if keys in used_keys :
continue
used_keys . add ( keys )
... |
def search ( self , q , search_handler = None , ** kwargs ) :
"""Performs a search and returns the results .
Requires a ` ` q ` ` for a string version of the query to run .
Optionally accepts ` ` * * kwargs ` ` for additional options to be passed
through the Solr URL .
Returns ` ` self . results _ cls ` ` c... | params = { 'q' : q }
params . update ( kwargs )
response = self . _select ( params , handler = search_handler )
decoded = self . decoder . decode ( response )
self . log . debug ( "Found '%s' search results." , # cover both cases : there is no response key or value is None
( decoded . get ( 'response' , { } ) or { } ) ... |
def access_token ( self ) :
"""Stores always valid OAuth2 access token .
Note :
Accessing this property may result in HTTP request .
Returns :
str""" | if ( self . _access_token is None or self . expiration_time <= int ( time . time ( ) ) ) :
resp = self . make_access_request ( )
self . _access_token = resp . json ( ) [ 'access_token' ]
return self . _access_token |
def parse_pylint_output ( output ) :
"""Parses pylint output , counting number of errors , conventions , etc
: param output : output list generated by run _ pylint ( )
: return :""" | stripped_output = [ x [ 0 ] for x in output ]
counter = Counter ( stripped_output )
return counter |
def pk_field ( self ) :
'''Name of the primary key field as retrieved from rethinkdb table
metadata , ' id ' by default . Should not be overridden . Override
` table _ create ` if you want to use a nonstandard field as the primary
key .''' | if not self . _pk :
try :
pk = self . rr . db ( 'rethinkdb' ) . table ( 'table_config' ) . filter ( { 'db' : self . rr . dbname , 'name' : self . table } ) . get_field ( 'primary_key' ) [ 0 ] . run ( )
self . _pk = pk
except Exception as e :
raise Exception ( 'problem determining primary... |
def cache_meta ( request , cache_key , start_index = 0 ) :
"""Inspect request for objects in _ ultracache and set appropriate entries
in Django ' s cache .""" | path = request . get_full_path ( )
# todo : cache headers on the request since they never change during the
# request .
# Reduce headers to the subset as defined by the settings
headers = OrderedDict ( )
for k , v in sorted ( request . META . items ( ) ) :
if ( k == "HTTP_COOKIE" ) and CONSIDER_COOKIES :
co... |
def initialize_simulation ( components : List , input_config : Mapping = None , plugin_config : Mapping = None ) -> InteractiveContext :
"""Construct a simulation from a list of components , component
configuration , and a plugin configuration .
The simulation context returned by this method still needs to be s... | config = build_simulation_configuration ( )
config . update ( input_config )
plugin_manager = PluginManager ( plugin_config )
return InteractiveContext ( config , components , plugin_manager ) |
def _ParseLayerConfigJSON ( self , parser_mediator , file_object ) :
"""Extracts events from a Docker filesystem layer configuration file .
The path of each filesystem layer config file is :
DOCKER _ DIR / graph / < layer _ id > / json
Args :
parser _ mediator ( ParserMediator ) : mediates interactions betw... | file_content = file_object . read ( )
file_content = codecs . decode ( file_content , self . _ENCODING )
json_dict = json . loads ( file_content )
if 'docker_version' not in json_dict :
raise errors . UnableToParseFile ( 'not a valid Docker layer configuration file, missing ' '\'docker_version\' key.' )
if 'created... |
def combine_slices ( self , slices , tensor_shape , device = None ) :
"""Turns a set of slices into a single tensor .
Args :
slices : list of tf . Tensor with length self . size .
tensor _ shape : Shape .
device : optional str . If absent , we use the devices of the slices .
Returns :
tf . Tensor .""" | if tensor_shape . ndims == 0 :
return slices [ 0 ]
ret = slices [ : ]
tensor_layout = self . tensor_layout ( tensor_shape )
for mesh_dim , tensor_axis in zip ( self . shape , tensor_layout . mesh_axis_to_tensor_axis ( self . ndims ) ) :
slice_size = len ( ret ) // mesh_dim . size
if tensor_axis is None :
... |
def determine_actions ( self , request , view ) :
"""For generic class based views we return information about
the fields that are accepted for ' PUT ' and ' POST ' methods .""" | actions = { }
for method in { 'PUT' , 'POST' } & set ( view . allowed_methods ) :
view . request = clone_request ( request , method )
try : # Test global permissions
if hasattr ( view , 'check_permissions' ) :
view . check_permissions ( view . request )
# Test object permissions
... |
def make_pairs_for_model ( model_num = 0 ) :
"""Create a list of pairs of model nums ; play every model nearby , then
every other model after that , then every fifth , etc .
Returns a list like [ [ N , N - 1 ] , [ N , N - 2 ] , . . . , [ N , N - 12 ] , . . . , [ N , N - 50 ] ]""" | if model_num == 0 :
return
pairs = [ ]
mm_fib = lambda n : int ( ( np . matrix ( [ [ 2 , 1 ] , [ 1 , 1 ] ] ) ** ( n // 2 ) ) [ 0 , ( n + 1 ) % 2 ] )
for i in range ( 2 , 14 ) : # Max is 233
if mm_fib ( i ) >= model_num :
break
pairs += [ [ model_num , model_num - mm_fib ( i ) ] ]
return pairs |
def update_userpass_password ( self , username , password , mount_point = 'userpass' ) :
"""POST / auth / < mount point > / users / < username > / password
: param username :
: type username :
: param password :
: type password :
: param mount _ point :
: type mount _ point :
: return :
: rtype :""" | params = { 'password' : password }
return self . _adapter . post ( '/v1/auth/{}/users/{}/password' . format ( mount_point , username ) , json = params ) |
def dump ( self ) :
"""Prints the project attributes .""" | id = self . get ( "id" )
if not id :
id = "(none)"
else :
id = id [ 0 ]
parent = self . get ( "parent" )
if not parent :
parent = "(none)"
else :
parent = parent [ 0 ]
print "'%s'" % id
print "Parent project:%s" , parent
print "Requirements:%s" , self . get ( "requirements" )
print "Default build:%s" , ... |
def count ( self , ** kwargs ) :
"""Counts the number of non - NaN objects for each column or row .
Return :
A new QueryCompiler object containing counts of non - NaN objects from each
column or row .""" | if self . _is_transposed :
kwargs [ "axis" ] = kwargs . get ( "axis" , 0 ) ^ 1
return self . transpose ( ) . count ( ** kwargs )
axis = kwargs . get ( "axis" , 0 )
map_func = self . _build_mapreduce_func ( pandas . DataFrame . count , ** kwargs )
reduce_func = self . _build_mapreduce_func ( pandas . DataFrame .... |
def insertSite ( self , businput ) :
"""Input dictionary has to have the following keys :
site _ name
it builds the correct dictionary for dao input and executes the dao""" | conn = self . dbi . connection ( )
tran = conn . begin ( )
try :
siteobj = { # FIXME : unused ?
"site_name" : businput [ "site_name" ] }
businput [ "site_id" ] = self . sm . increment ( conn , "SEQ_SI" , tran )
self . sitein . execute ( conn , businput , tran )
tran . commit ( )
except Exception as ... |
def label ( self , t ) :
"""Get the label of the song at a given time in seconds""" | if self . labels is None :
return None
prev_label = None
for l in self . labels :
if l . time > t :
break
prev_label = l
if prev_label is None :
return None
return prev_label . name |
def download_encrypted_file ( job , input_args , name ) :
"""Downloads encrypted files from S3 via header injection
input _ args : dict Input dictionary defined in main ( )
name : str Symbolic name associated with file""" | work_dir = job . fileStore . getLocalTempDir ( )
key_path = input_args [ 'ssec' ]
file_path = os . path . join ( work_dir , name )
url = input_args [ name ]
with open ( key_path , 'r' ) as f :
key = f . read ( )
if len ( key ) != 32 :
raise RuntimeError ( 'Invalid Key! Must be 32 bytes: {}' . format ( key ) )
k... |
def _authenticate ( self ) :
'''Authenticate with the master , this method breaks the functional
paradigm , it will update the master information from a fresh sign
in , signing in can occur as often as needed to keep up with the
revolving master AES key .
: rtype : Crypticle
: returns : A crypticle used f... | acceptance_wait_time = self . opts [ 'acceptance_wait_time' ]
acceptance_wait_time_max = self . opts [ 'acceptance_wait_time_max' ]
if not acceptance_wait_time_max :
acceptance_wait_time_max = acceptance_wait_time
creds = None
channel = salt . transport . client . AsyncReqChannel . factory ( self . opts , crypt = '... |
def write_block_data ( self , i2c_addr , register , data , force = None ) :
"""Write a block of byte data to a given register .
: param i2c _ addr : i2c address
: type i2c _ addr : int
: param register : Start register
: type register : int
: param data : List of bytes
: type data : list
: param force... | length = len ( data )
if length > I2C_SMBUS_BLOCK_MAX :
raise ValueError ( "Data length cannot exceed %d bytes" % I2C_SMBUS_BLOCK_MAX )
self . _set_address ( i2c_addr , force = force )
msg = i2c_smbus_ioctl_data . create ( read_write = I2C_SMBUS_WRITE , command = register , size = I2C_SMBUS_BLOCK_DATA )
msg . data ... |
def asn1_generaltime_to_seconds ( timestr ) :
"""The given string has one of the following formats
YYYYMMDDhhmmssZ
YYYYMMDDhhmmss + hhmm
YYYYMMDDhhmmss - hhmm
@ return : a datetime object or None on error""" | res = None
timeformat = "%Y%m%d%H%M%S"
try :
res = datetime . strptime ( timestr , timeformat + 'Z' )
except ValueError :
try :
res = datetime . strptime ( timestr , timeformat + '%z' )
except ValueError :
pass
return res |
def set_multiple ( self , ** kwargs ) :
"""Configure multiple app key / value pairs""" | quiet = False
if not kwargs :
return
cmd = [ "heroku" , "config:set" ]
for k in sorted ( kwargs ) :
cmd . append ( "{}={}" . format ( k , quote ( str ( kwargs [ k ] ) ) ) )
if self . _is_sensitive_key ( k ) :
quiet = True
cmd . extend ( [ "--app" , self . name ] )
if quiet :
self . _run_quiet ( ... |
def _reindex_output ( self , result ) :
"""If we have categorical groupers , then we want to make sure that
we have a fully reindex - output to the levels . These may have not
participated in the groupings ( e . g . may have all been
nan groups ) ;
This can re - expand the output space""" | # we need to re - expand the output space to accomodate all values
# whether observed or not in the cartesian product of our groupes
groupings = self . grouper . groupings
if groupings is None :
return result
elif len ( groupings ) == 1 :
return result
# if we only care about the observed values
# we are done
e... |
def close_all_files ( self ) :
"""Close all open files ( so that we can open more ) .""" | while len ( self . open_file_infos ) > 0 :
file_info = self . open_file_infos . pop ( 0 )
file_info . file_handle . close ( )
file_info . file_handle = None
self . closed_file_infos . append ( file_info )
self . can_open_more_files = True |
def should_see_id ( self , element_id ) :
"""Assert an element with the given ` ` id ` ` is visible .""" | elements = ElementSelector ( world . browser , 'id("%s")' % element_id , filter_displayed = True , )
if not elements :
raise AssertionError ( "Expected element with given id." ) |
async def _drop_databases ( cls ) -> None :
"""Tries to drop all databases provided in config passed to ` ` . init ( ) ` ` method .
Normally should be used only for testing purposes .""" | if not cls . _inited :
raise ConfigurationError ( "You have to call .init() first before deleting schemas" )
for connection in cls . _connections . values ( ) :
await connection . close ( )
await connection . db_delete ( )
cls . _connections = { }
await cls . _reset_apps ( ) |
def get_ancestors ( self ) :
""": returns : A queryset containing the current node object ' s ancestors ,
starting by the root node and descending to the parent .""" | if self . is_root ( ) :
return get_result_class ( self . __class__ ) . objects . none ( )
paths = [ self . path [ 0 : pos ] for pos in range ( 0 , len ( self . path ) , self . steplen ) [ 1 : ] ]
return get_result_class ( self . __class__ ) . objects . filter ( path__in = paths ) . order_by ( 'depth' ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.