signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _load_modeling_extent ( self ) :
"""# Get extent from GSSHA Grid in LSM coordinates
# Determine range within LSM Grid""" | # STEP 1 : Get extent from GSSHA Grid in LSM coordinates
# reproject GSSHA grid and get bounds
min_x , max_x , min_y , max_y = self . gssha_grid . bounds ( as_projection = self . xd . lsm . projection )
# set subset indices
self . _set_subset_indices ( min_y , max_y , min_x , max_x ) |
def list_all_payment_transactions ( cls , ** kwargs ) :
"""List PaymentTransactions
Return a list of PaymentTransactions
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ payment _ transactions ( async ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_payment_transactions_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_payment_transactions_with_http_info ( ** kwargs )
return data |
def keplerian_sheared_field_locations ( ax , kbos , date , ras , decs , names , elongation = False , plot = False ) :
"""Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field .
: param ras :
: param decs :
: param plot :
: param ax :
: param kbos... | seps = { 'dra' : 0. , 'ddec' : 0. }
for kbo in kbos :
ra = kbo . ra
dec = kbo . dec
kbo . compute ( date )
seps [ 'dra' ] += kbo . ra - ra
seps [ 'ddec' ] += kbo . dec - dec
seps [ 'dra' ] /= float ( len ( kbos ) )
seps [ 'ddec' ] /= float ( len ( kbos ) )
print date , seps , len ( kbos )
for idx in... |
def build ( self , builder ) :
"""Build XML by appending to builder""" | params = dict ( ItemOID = self . oid , Mandatory = bool_to_yes_no ( self . mandatory ) )
if self . order_number is not None :
params [ "OrderNumber" ] = str ( self . order_number )
if self . key_sequence is not None :
params [ "KeySequence" ] = str ( self . key_sequence )
if self . imputation_method_oid is not ... |
def push_progress ( self , status , object_id , progress ) :
"""Prints progress information .
: param status : Status text .
: type status : unicode
: param object _ id : Object that the progress is reported on .
: type object _ id : unicode
: param progress : Progress bar .
: type progress : unicode""" | fastprint ( progress_fmt ( status , object_id , progress ) , end = '\n' ) |
def memory_warning ( config , context ) :
"""Determines when memory usage is nearing it ' s max .""" | used = psutil . Process ( os . getpid ( ) ) . memory_info ( ) . rss / 1048576
limit = float ( context . memory_limit_in_mb )
p = used / limit
memory_threshold = config . get ( 'memory_warning_threshold' )
if p >= memory_threshold :
config [ 'raven_client' ] . captureMessage ( 'Memory Usage Warning' , level = 'warni... |
def build_multi_point_source_node ( multi_point_source ) :
"""Parses a point source to a Node class
: param point _ source :
MultiPoint source as instance of : class :
` openquake . hazardlib . source . point . MultiPointSource `
: returns :
Instance of : class : ` openquake . baselib . node . Node `""" | # parse geometry
pos = [ ]
for p in multi_point_source . mesh :
pos . append ( p . x )
pos . append ( p . y )
mesh_node = Node ( 'gml:posList' , text = pos )
upper_depth_node = Node ( "upperSeismoDepth" , text = multi_point_source . upper_seismogenic_depth )
lower_depth_node = Node ( "lowerSeismoDepth" , text =... |
def create_diskgroup ( service_instance , vsan_disk_mgmt_system , host_ref , cache_disk , capacity_disks ) :
'''Creates a disk group
service _ instance
Service instance to the host or vCenter
vsan _ disk _ mgmt _ system
vim . VimClusterVsanVcDiskManagemenetSystem representing the vSan disk
management syst... | hostname = salt . utils . vmware . get_managed_object_name ( host_ref )
cache_disk_id = cache_disk . canonicalName
log . debug ( 'Creating a new disk group with cache disk \'%s\' on host \'%s\'' , cache_disk_id , hostname )
log . trace ( 'capacity_disk_ids = %s' , [ c . canonicalName for c in capacity_disks ] )
spec = ... |
def write_gif_to_file ( self , fp , images , durations , loops , xys , disposes ) :
"""write _ gif _ to _ file ( fp , images , durations , loops , xys , disposes )
Given a set of images writes the bytes to the specified stream .""" | # Obtain palette for all images and count each occurance
palettes , occur = [ ] , [ ]
for im in images :
palettes . append ( getheader ( im ) [ 1 ] )
for palette in palettes :
occur . append ( palettes . count ( palette ) )
# Select most - used palette as the global one ( or first in case no max )
print palette... |
def is_stalemate ( self ) -> bool :
"""Checks if the current position is a stalemate .""" | if self . is_check ( ) :
return False
if self . is_variant_end ( ) :
return False
return not any ( self . generate_legal_moves ( ) ) |
def ISIs ( self , time_dimension = 0 , units = None , min_t = None , max_t = None ) :
"""returns the Inter Spike Intervals
` time _ dimension ` : which dimension contains the spike times ( by default the first )
` units ` , ` min _ t ` , ` max _ t ` : define the units of the output and the range of spikes that ... | units = self . _default_units ( units )
converted_dimension , st = self . spike_times . get_converted ( time_dimension , units )
if min_t is None :
min_t = converted_dimension . min
if max_t is None :
max_t = converted_dimension . max
return np . diff ( sorted ( st [ ( st > min_t ) * ( st < max_t ) ] ) ) |
def _parse_residue ( self , residue ) :
"""Extracts Residue Name , Number , Chain , Model , Atoms .
I / O : xml object < response > / dictionary""" | # Filter Element Nodes
childs = [ child for child in residue . childNodes if child . nodeType == child . ELEMENT_NODE ]
# Parse info out
resi = int ( childs [ 0 ] . firstChild . data . strip ( ) )
resn = childs [ 1 ] . firstChild . data . strip ( )
icode = childs [ 3 ] . firstChild . data
chain = childs [ 4 ] . firstCh... |
def makeMarkovApproxToNormalByMonteCarlo ( x_grid , mu , sigma , N_draws = 10000 ) :
'''Creates an approximation to a normal distribution with mean mu and standard
deviation sigma , by Monte Carlo .
Returns a stochastic vector called p _ vec , corresponding
to values in x _ grid . If a RV is distributed x ~ N... | # Take random draws from the desired normal distribution
random_draws = np . random . normal ( loc = mu , scale = sigma , size = N_draws )
# Compute the distance between the draws and points in x _ grid
distance = np . abs ( x_grid [ : , np . newaxis ] - random_draws [ np . newaxis , : ] )
# Find the indices of the poi... |
def logs ( id , url , follow , sleep_duration = 1 ) :
"""View the logs of a job .
To follow along a job in real time , use the - - follow flag""" | instance_log_id = get_log_id ( id )
if url :
log_url = "{}/api/v1/resources/{}?content=true" . format ( floyd . floyd_host , instance_log_id )
floyd_logger . info ( log_url )
return
if follow :
floyd_logger . info ( "Launching job ..." )
follow_logs ( instance_log_id , sleep_duration )
else :
lo... |
def _map_purchase_request_to_func ( self , purchase_request_type ) :
"""Provides appropriate parameters to the on _ purchase functions .""" | if purchase_request_type in self . _intent_view_funcs :
view_func = self . _intent_view_funcs [ purchase_request_type ]
else :
raise NotImplementedError ( 'Request type "{}" not found and no default view specified.' . format ( purchase_request_type ) )
argspec = inspect . getargspec ( view_func )
arg_names = ar... |
def _mic_required ( target_info ) :
"""Checks the MsvAvFlags field of the supplied TargetInfo structure to determine in the MIC flags is set
: param target _ info : The TargetInfo structure to check
: return : a boolean value indicating that the MIC flag is set""" | if target_info is not None and target_info [ TargetInfo . NTLMSSP_AV_FLAGS ] is not None :
flags = struct . unpack ( '<I' , target_info [ TargetInfo . NTLMSSP_AV_FLAGS ] [ 1 ] ) [ 0 ]
return bool ( flags & 0x00000002 ) |
def help_center_article_translation_create ( self , article_id , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / translations # create - translation" | api_path = "/api/v2/help_center/articles/{article_id}/translations.json"
api_path = api_path . format ( article_id = article_id )
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def charts_get ( self , ** kwargs ) :
"""Charts
Returns a list of Charts , ordered by creation date ( newest first ) . A Chart is chosen by Pollster editors . One example is \" Obama job approval - Democrats \" . It is always based upon a single Question . Users should strongly consider basing their analysis on Q... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . charts_get_with_http_info ( ** kwargs )
else :
( data ) = self . charts_get_with_http_info ( ** kwargs )
return data |
def validate_abi ( abi ) :
"""Helper function for validating an ABI""" | if not is_list_like ( abi ) :
raise ValueError ( "'abi' is not a list" )
if not all ( is_dict ( e ) for e in abi ) :
raise ValueError ( "'abi' is not a list of dictionaries" )
functions = filter_by_type ( 'function' , abi )
selectors = groupby ( compose ( encode_hex , function_abi_to_4byte_selector ) , function... |
def _validate_for_numeric_unaryop ( self , op , opstr ) :
"""Validate if we can perform a numeric unary operation .""" | if not self . _is_numeric_dtype :
raise TypeError ( "cannot evaluate a numeric op " "{opstr} for type: {typ}" . format ( opstr = opstr , typ = type ( self ) . __name__ ) ) |
def _filter_gte ( self , term , field_name , field_type , is_not ) :
"""Private method that returns a xapian . Query that searches for any term
that is greater than ` term ` in a specified ` field ` .""" | vrp = XHValueRangeProcessor ( self . backend )
pos , begin , end = vrp ( '%s:%s' % ( field_name , _term_to_xapian_value ( term , field_type ) ) , '*' )
if is_not :
return xapian . Query ( xapian . Query . OP_AND_NOT , self . _all_query ( ) , xapian . Query ( xapian . Query . OP_VALUE_RANGE , pos , begin , end ) )
r... |
def load_modules ( self , args ) :
"""Wrapper to load : plugins and export modules .""" | # Init the plugins dict
# Active plugins dictionnary
self . _plugins = collections . defaultdict ( dict )
# Load the plugins
self . load_plugins ( args = args )
# Init the export modules dict
# Active exporters dictionnary
self . _exports = collections . defaultdict ( dict )
# All available exporters dictionnary
self .... |
def do_setup ( self , arg , arguments ) :
"""Usage :
setup init [ - - force ]
Copies a cmd3 . yaml file into ~ / . cloudmesh / cmd3 . yaml""" | if arguments [ "init" ] :
Console . ok ( "Initialize cmd3.yaml file" )
from cmd3 . yaml_setup import create_cmd3_yaml_file
force = arguments [ "--force" ]
create_cmd3_yaml_file ( force = force ) |
def find_relations ( chunked ) :
"""The input is a list of [ token , tag , chunk ] - items .
The output is a list of [ token , tag , chunk , relation ] - items .
A noun phrase preceding a verb phrase is perceived as sentence subject .
A noun phrase following a verb phrase is perceived as sentence object .""" | tag = lambda token : token [ 2 ] . split ( "-" ) [ - 1 ]
# B - NP = > NP
# Group successive tokens with the same chunk - tag .
chunks = [ ]
for token in chunked :
if len ( chunks ) == 0 or token [ 2 ] . startswith ( "B-" ) or tag ( token ) != tag ( chunks [ - 1 ] [ - 1 ] ) :
chunks . append ( [ ] )
chun... |
def create_tuple ( input_list , input_string ) :
"""Function to construct a new tuple using a list and a string .
Args :
input _ list : A list of strings .
input _ string : A string .
Returns :
A tuple combining the elements of the input list and the input string .
Examples :
> > > create _ tuple ( [ ... | result_tuple = tuple ( input_list + [ input_string ] )
return result_tuple |
def manage ( self , dateTimeString ) :
"""Return a Python datetime object based on the dateTimeString
This will handle date times in the following formats :
YYYY / MM / DD HH : MM : SS
2014/11/05 21:47:28
2014/11/5 21:47:28
11/05/2014
11/5/2014
11/05/2014 16:28:00
11/05/2014 16:28
11/5/2014 16:28:... | dateTime = None
dateTimeString = dateTimeString . replace ( '-' , '/' )
_date_time_split = dateTimeString . split ( ' ' )
# [0 ] = date , [ 1 ] = time ( if exists )
_date = _date_time_split [ 0 ]
_time = '00:00:00'
# default
if len ( _date_time_split ) > 1 :
_time = _date_time_split [ 1 ]
if dateTimeString . find (... |
def config ( self ) :
"""Implements Munin Plugin Graph Configuration .
Prints out configuration for graphs .
Use as is . Not required to be overwritten in child classes . The plugin
will work correctly as long as the Munin Graph objects have been
populated .""" | for parent_name in self . _graphNames :
graph = self . _graphDict [ parent_name ]
if self . isMultigraph :
print "multigraph %s" % self . _getMultigraphID ( parent_name )
print self . _formatConfig ( graph . getConfig ( ) )
print
if ( self . isMultigraph and self . _nestedGraphs and self . _subg... |
def _query_k ( k , i , P , oracle , query , trn , state_cache , dist_cache , smooth = False , D = None , weight = 0.5 ) :
"""A helper function for query - matching function ` s iteration over observations .
Args :
k - index of the candidate path
i - index of the frames of the observations
P - the path matri... | _trn = trn ( oracle , P [ i - 1 ] [ k ] )
t = list ( itertools . chain . from_iterable ( [ oracle . latent [ oracle . data [ j ] ] for j in _trn ] ) )
_trn_unseen = [ _t for _t in _trn if _t not in state_cache ]
state_cache . extend ( _trn_unseen )
if _trn_unseen :
t_unseen = list ( itertools . chain . from_iterabl... |
def handle_options ( ) :
'''Handle options .''' | parser = OptionParser ( )
parser . set_defaults ( cmaglin = False )
parser . set_defaults ( single = False )
parser . set_defaults ( alpha_cov = False )
parser . add_option ( '-x' , '--xmin' , dest = 'xmin' , help = 'Minium X range' , type = 'float' , )
parser . add_option ( '-X' , '--xmax' , dest = 'xmax' , help = 'Ma... |
def startup ( request ) :
"""This view provides initial data to the client , such as available skills and causes""" | with translation . override ( translation . get_language_from_request ( request ) ) :
skills = serializers . SkillSerializer ( models . Skill . objects . all ( ) , many = True )
causes = serializers . CauseSerializer ( models . Cause . objects . all ( ) , many = True )
cities = serializers . GoogleAddressCi... |
def bInit ( self , vrModel , vrDiffuseTexture ) :
"Purpose : Allocates and populates the GL resources for a render model" | # create and bind a VAO to hold state for this model
self . m_glVertArray = glGenVertexArrays ( 1 )
glBindVertexArray ( self . m_glVertArray )
# Populate a vertex buffer
self . m_glVertBuffer = glGenBuffers ( 1 )
glBindBuffer ( GL_ARRAY_BUFFER , self . m_glVertBuffer )
glBufferData ( GL_ARRAY_BUFFER , sizeof ( openvr .... |
def _get_command_args ( self , command , args ) :
'''Work out the command arguments for a given command''' | command_args = { }
command_argument_names = command . __code__ . co_varnames [ : command . __code__ . co_argcount ]
for varname in command_argument_names :
if varname == 'args' :
command_args [ 'args' ] = args
elif varname in self . provide_args :
command_args [ varname ] = self . provide_args [... |
def _ProcessPathSpec ( self , extraction_worker , parser_mediator , path_spec ) :
"""Processes a path specification .
Args :
extraction _ worker ( worker . ExtractionWorker ) : extraction worker .
parser _ mediator ( ParserMediator ) : parser mediator .
path _ spec ( dfvfs . PathSpec ) : path specification ... | self . _current_display_name = parser_mediator . GetDisplayNameForPathSpec ( path_spec )
try :
extraction_worker . ProcessPathSpec ( parser_mediator , path_spec )
except dfvfs_errors . CacheFullError : # TODO : signal engine of failure .
self . _abort = True
logger . error ( ( 'ABORT: detected cache full er... |
def urlencode2 ( query , doseq = 0 , safe = "" , querydelimiter = "&" ) :
"""Encode a sequence of two - element tuples or dictionary into a URL query string .
If any values in the query arg are sequences and doseq is true , each
sequence element is converted to a separate parameter .
If the query arg is a seq... | if hasattr ( query , "items" ) : # mapping objects
query = query . items ( )
else : # it ' s a bother at times that strings and string - like objects are
# sequences . . .
try : # non - sequence items should not work with len ( )
# non - empty strings will fail this
if len ( query ) and not isinstan... |
def cmd_output_sysid ( self , args ) :
'''add new output for a specific MAVLink sysID''' | sysid = int ( args [ 0 ] )
device = args [ 1 ]
print ( "Adding output %s for sysid %u" % ( device , sysid ) )
try :
conn = mavutil . mavlink_connection ( device , input = False , source_system = self . settings . source_system )
conn . mav . srcComponent = self . settings . source_component
except Exception :
... |
def do_jump ( self , arg ) :
"""j ( ump ) lineno
Set the next line that will be executed . Only available in
the bottom - most frame . This lets you jump back and execute
code again , or jump forward to skip code that you don ' t want
to run .
It should be noted that not all jumps are allowed - - for
in... | if self . curindex + 1 != len ( self . stack ) :
self . error ( 'You can only jump within the bottom frame' )
return
try :
arg = int ( arg )
except ValueError :
self . error ( "The 'jump' command requires a line number" )
else :
try : # Do the jump , fix up our copy of the stack , and display the
... |
def root_parent ( self , category = None ) :
"""Returns the topmost parent of the current category .""" | return next ( filter ( lambda c : c . is_root , self . hierarchy ( ) ) ) |
async def send_animation ( self , chat_id : typing . Union [ base . Integer , base . String ] , animation : typing . Union [ base . InputFile , base . String ] , duration : typing . Union [ base . Integer , None ] = None , width : typing . Union [ base . Integer , None ] = None , height : typing . Union [ base . Intege... | reply_markup = prepare_arg ( reply_markup )
payload = generate_payload ( ** locals ( ) , exclude = [ "animation" , "thumb" ] )
files = { }
prepare_file ( payload , files , 'animation' , animation )
prepare_attachment ( payload , files , 'thumb' , thumb )
result = await self . request ( api . Methods . SEND_ANIMATION , ... |
def system_monitor_mail_interface_enable ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
system_monitor_mail = ET . SubElement ( config , "system-monitor-mail" , xmlns = "urn:brocade.com:mgmt:brocade-system-monitor" )
interface = ET . SubElement ( system_monitor_mail , "interface" )
enable = ET . SubElement ( interface , "enable" )
callback = kwargs . pop ( 'callback' , s... |
def alltoall_pointtwise ( xs , devices , split_axis , concat_axis ) :
"""MPI alltoall operation .
Implementation of alltoall using pointwise communication .
Args :
xs : a list of n tf . Tensors
devices : a list of n strings
split _ axis : an integer
concat _ axis : an integer
Returns :
a list of n T... | n = len ( xs )
if n == 1 :
return xs
# [ target , source ]
parts = mtf . transpose_list_of_lists ( mtf . parallel ( devices , tf . split , xs , [ n ] * n , axis = [ split_axis ] * n ) )
return mtf . parallel ( devices , tf . concat , parts , axis = [ concat_axis ] * n ) |
def euclidean3d ( v1 , v2 ) :
"""Faster implementation of euclidean distance for the 3D case .""" | if not len ( v1 ) == 3 and len ( v2 ) == 3 :
print ( "Vectors are not in 3D space. Returning None." )
return None
return np . sqrt ( ( v1 [ 0 ] - v2 [ 0 ] ) ** 2 + ( v1 [ 1 ] - v2 [ 1 ] ) ** 2 + ( v1 [ 2 ] - v2 [ 2 ] ) ** 2 ) |
def paxos_instance ( self ) :
"""Returns instance of PaxosInstance ( protocol implementation ) .""" | # Construct instance with the constant attributes .
instance = PaxosInstance ( self . network_uid , self . quorum_size )
# Set the variable attributes from the aggregate .
for name in self . paxos_variables :
value = getattr ( self , name , None )
if value is not None :
if isinstance ( value , ( set , l... |
def _notification_stmt ( self , stmt : Statement , sctx : SchemaContext ) -> None :
"""Handle notification statement .""" | self . _handle_child ( NotificationNode ( ) , stmt , sctx ) |
def get_error ( self ) :
"""Retrieve error data .""" | col_offset = - 1
if self . node is not None :
try :
col_offset = self . node . col_offset
except AttributeError :
pass
try :
exc_name = self . exc . __name__
except AttributeError :
exc_name = str ( self . exc )
if exc_name in ( None , 'None' ) :
exc_name = 'UnknownError'
out = [ " ... |
def s3_upload ( source , destination , profile_name = None ) :
"""Copy a file from a local source to an S3 destination .
Parameters
source : str
destination : str
Path starting with s3 : / / , e . g . ' s3 : / / bucket - name / key / foo . bar '
profile _ name : str , optional
AWS profile""" | session = boto3 . Session ( profile_name = profile_name )
s3 = session . resource ( 's3' )
bucket_name , key = _s3_path_split ( destination )
with open ( source , 'rb' ) as data :
s3 . Bucket ( bucket_name ) . put_object ( Key = key , Body = data ) |
def patch_jwt_settings ( ) :
"""Patch rest _ framework _ jwt authentication settings from allauth""" | defaults = api_settings . defaults
defaults [ 'JWT_PAYLOAD_GET_USER_ID_HANDLER' ] = ( __name__ + '.get_user_id_from_payload_handler' )
if 'allauth.socialaccount' not in settings . INSTALLED_APPS :
return
from allauth . socialaccount . models import SocialApp
try :
app = SocialApp . objects . get ( provider = 'h... |
def get_all_users ( ** kwargs ) :
"""Get the username & ID of all users .
Use the the filter if it has been provided
The filter has to be a list of values""" | users_qry = db . DBSession . query ( User )
filter_type = kwargs . get ( 'filter_type' )
filter_value = kwargs . get ( 'filter_value' )
if filter_type is not None : # Filtering the search of users
if filter_type == "id" :
if isinstance ( filter_value , str ) : # Trying to read a csv string
log .... |
def change_capacity_percent ( self , group_name , scaling_adjustment ) :
"""http : / / docs . aws . amazon . com / AutoScaling / latest / DeveloperGuide / as - scale - based - on - demand . html
If PercentChangeInCapacity returns a value between 0 and 1,
Auto Scaling will round it off to 1 . If the PercentChang... | group = self . autoscaling_groups [ group_name ]
percent_change = 1 + ( scaling_adjustment / 100.0 )
desired_capacity = group . desired_capacity * percent_change
if group . desired_capacity < desired_capacity < group . desired_capacity + 1 :
desired_capacity = group . desired_capacity + 1
else :
desired_capacit... |
def _init ( self , parser ) :
"""Initialize / Build the ` ` argparse . ArgumentParser ` ` and subparsers .
This internal version of ` ` init ` ` is used to ensure that all
subcommands have a properly initialized parser .
Args
parser : argparse . ArgumentParser
The parser for this command .""" | assert isinstance ( parser , argparse . ArgumentParser )
self . _init_parser ( parser )
self . _attach_arguments ( )
self . _attach_subcommands ( )
self . initialized = True |
def parse ( cls , data : bytes ) -> 'MessageContent' :
"""Parse the bytestring into message content .
Args :
data : The bytestring to parse .""" | lines = cls . _find_lines ( data )
view = memoryview ( data )
return cls . _parse ( data , view , lines ) |
def fit ( self , choosers , alternatives , current_choice ) :
"""Fit and save model parameters based on given data .
Parameters
choosers : pandas . DataFrame
Table describing the agents making choices , e . g . households .
alternatives : pandas . DataFrame
Table describing the things from which agents ar... | logger . debug ( 'start: fit LCM model {}' . format ( self . name ) )
if not isinstance ( current_choice , pd . Series ) :
current_choice = choosers [ current_choice ]
choosers , alternatives = self . apply_fit_filters ( choosers , alternatives )
if self . estimation_sample_size :
choosers = choosers . loc [ np... |
def start_discovery ( add_callback = None , remove_callback = None ) :
"""Start discovering chromecasts on the network .
This method will start discovering chromecasts on a separate thread . When
a chromecast is discovered , the callback will be called with the
discovered chromecast ' s zeroconf name . This i... | listener = CastListener ( add_callback , remove_callback )
service_browser = False
try :
service_browser = zeroconf . ServiceBrowser ( zeroconf . Zeroconf ( ) , "_googlecast._tcp.local." , listener )
except ( zeroconf . BadTypeInNameException , NotImplementedError , OSError , socket . error , zeroconf . NonUniqueNa... |
def subvolume_show ( path ) :
'''Show information of a given subvolume
path
Mount point for the filesystem
CLI Example :
. . code - block : : bash
salt ' * ' btrfs . subvolume _ show / var / volumes / tmp''' | cmd = [ 'btrfs' , 'subvolume' , 'show' , path ]
res = __salt__ [ 'cmd.run_all' ] ( cmd )
salt . utils . fsutils . _verify_run ( res )
result = { }
table = { }
# The real name is the first line , later there is a table of
# values separated with colon .
stdout = res [ 'stdout' ] . splitlines ( )
key = stdout . pop ( 0 )... |
def p0 ( self ) :
"""A dictionary of the initial position of the walkers .
This is set by using ` ` set _ p0 ` ` . If not set yet , a ` ` ValueError ` ` is
raised when the attribute is accessed .""" | if self . _p0 is None :
raise ValueError ( "initial positions not set; run set_p0" )
# convert to dict
p0 = { param : self . _p0 [ ... , k ] for ( k , param ) in enumerate ( self . sampling_params ) }
return p0 |
def wordify ( self ) :
"""Constructs string of all documents .
: return : document representation of the dataset , one line per document
: rtype : str""" | string_documents = [ ]
for klass , document in zip ( self . resulting_classes , self . resulting_documents ) :
string_documents . append ( "!" + str ( klass ) + " " + '' . join ( document ) )
return '\n' . join ( string_documents ) |
def _set_infra ( self , v , load = False ) :
"""Setter method for infra , mapped from YANG variable / show / infra ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ infra is considered as a private
method . Backends looking to populate this variable should... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = infra . infra , is_container = 'container' , presence = False , yang_name = "infra" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions =... |
def brightness ( self , x , y , radius , medv , data ) :
"""Return the brightness value found in a region ( radius ) pixels away
from ( x , y ) in ( data ) .""" | x0 , y0 , arr = self . cut_region ( x , y , radius , data )
arr2 = np . sort ( arr . flat )
idx = int ( len ( arr2 ) * 0.8 )
res = arr2 [ idx ] - medv
return float ( res ) |
def decode ( cls , bytes , cmddict ) :
"""Decodes a sequence command from an array of bytes , according to the
given command dictionary , and returns a new SeqCmd .""" | attrs = SeqCmdAttrs . decode ( bytes [ 0 : 1 ] )
delay = SeqDelay . decode ( bytes [ 1 : 4 ] )
cmd = cmddict . decode ( bytes [ 4 : ] )
return cls ( cmd , delay , attrs ) |
def encode_single ( typ , arg ) : # pylint : disable = too - many - return - statements , too - many - branches , too - many - statements , too - many - locals
"""Encode ` arg ` as ` typ ` .
` arg ` will be encoded in a best effort manner , were necessary the function
will try to correctly define the underlying... | base , sub , _ = typ
if base == 'uint' :
sub = int ( sub )
if not ( 0 < sub <= 256 and sub % 8 == 0 ) :
raise ValueError ( 'invalid unsigned integer bit length {}' . format ( sub ) )
try :
i = decint ( arg , signed = False )
except EncodingError : # arg is larger than 2 * * 256
r... |
def anonymize ( remote_addr ) :
"""Anonymize IPv4 and IPv6 : param remote _ addr : to / 24 ( zero ' d )
and / 48 ( zero ' d ) .""" | if not isinstance ( remote_addr , text_type ) and isinstance ( remote_addr , str ) :
remote_addr = remote_addr . decode ( 'ascii' , 'ignore' )
try :
ipv4 = ipaddress . IPv4Address ( remote_addr )
return u'' . join ( ipv4 . exploded . rsplit ( '.' , 1 ) [ 0 ] ) + '.' + '0'
except ipaddress . AddressValueErro... |
def load_text_data ( dataset , directory , centre = True ) :
"""Load in a data set of marker points from the Ohio State University C3D motion capture files ( http : / / accad . osu . edu / research / mocap / mocap _ data . htm ) .""" | points , point_names = parse_text ( os . path . join ( directory , dataset + '.txt' ) ) [ 0 : 2 ]
# Remove markers where there is a NaN
present_index = [ i for i in range ( points [ 0 ] . shape [ 1 ] ) if not ( np . any ( np . isnan ( points [ 0 ] [ : , i ] ) ) or np . any ( np . isnan ( points [ 0 ] [ : , i ] ) ) or n... |
def enable_disable_on_bot_select_deselect ( self ) :
"""Disables the botconfig groupbox and minus buttons when no bot is selected
: return :""" | if not self . blue_listwidget . selectedItems ( ) and not self . orange_listwidget . selectedItems ( ) :
self . bot_config_groupbox . setDisabled ( True )
self . blue_minus_toolbutton . setDisabled ( True )
self . orange_minus_toolbutton . setDisabled ( True )
else :
self . bot_config_groupbox . setDisa... |
def add_var_arg ( self , arg ) :
"""Add a variable ( or macro ) argument to the condor job . The argument is
added to the submit file and a different value of the argument can be set
for each node in the DAG .
@ param arg : name of option to add .""" | self . __args . append ( arg )
self . __job . add_var_arg ( self . __arg_index )
self . __arg_index += 1 |
def newsnr_sgveto ( snr , bchisq , sgchisq ) :
"""Combined SNR derived from NewSNR and Sine - Gaussian Chisq""" | nsnr = numpy . array ( newsnr ( snr , bchisq ) , ndmin = 1 )
sgchisq = numpy . array ( sgchisq , ndmin = 1 )
t = numpy . array ( sgchisq > 4 , ndmin = 1 )
if len ( t ) :
nsnr [ t ] = nsnr [ t ] / ( sgchisq [ t ] / 4.0 ) ** 0.5
# If snr input is float , return a float . Otherwise return numpy array .
if hasattr ( sn... |
def check_integrity ( models ) :
'''Apply validation and integrity checks to a collection of Bokeh models .
Args :
models ( seq [ Model ] ) : a collection of Models to test
Returns :
None
This function will emit log warning and error messages for all error or
warning conditions that are detected . For e... | messages = dict ( error = [ ] , warning = [ ] )
for model in models :
validators = [ ]
for name in dir ( model ) :
if not name . startswith ( "_check" ) :
continue
obj = getattr ( model , name )
if getattr ( obj , "validator_type" , None ) :
validators . append ( ... |
def preprocess ( * _unused , ** processors ) :
"""Decorator that applies pre - processors to the arguments of a function before
calling the function .
Parameters
* * processors : dict
Map from argument name - > processor function .
A processor function takes three arguments : ( func , argname , argvalue )... | if _unused :
raise TypeError ( "preprocess() doesn't accept positional arguments" )
def _decorator ( f ) :
args , varargs , varkw , defaults = argspec = getargspec ( f )
if defaults is None :
defaults = ( )
no_defaults = ( NO_DEFAULT , ) * ( len ( args ) - len ( defaults ) )
args_defaults = ... |
def ensure_ndarray ( A , shape = None , uniform = None , ndim = None , size = None , dtype = None , kind = None ) :
r"""Ensures A is an ndarray and does an assert _ array with the given parameters
Returns
A : ndarray
If A is already an ndarray , it is just returned . Otherwise this is an independent copy as a... | if not isinstance ( A , np . ndarray ) :
try :
A = np . array ( A )
except :
raise AssertionError ( 'Given argument cannot be converted to an ndarray:\n' + str ( A ) )
assert_array ( A , shape = shape , uniform = uniform , ndim = ndim , size = size , dtype = dtype , kind = kind )
return A |
async def send_http_response ( writer , http_code : int , headers : List [ Tuple [ str , str ] ] , content : bytes , http_status : str = None ) -> None :
"""generate http response payload and send to writer""" | # generate response payload
if not http_status :
http_status = STATUS_CODES . get ( http_code , 'Unknown' )
response : bytes = f'HTTP/1.1 {http_code} {http_status}\r\n' . encode ( )
for k , v in headers :
response += f'{k}: {v}\r\n' . encode ( )
response += b'\r\n'
response += content
# send payload
writer . wr... |
def _download_images ( label_path : PathOrStr , img_tuples : list , max_workers : int = defaults . cpus , timeout : int = 4 ) -> FilePathList :
"""Downloads images in ` img _ tuples ` to ` label _ path ` .
If the directory doesn ' t exist , it ' ll be created automatically .
Uses ` parallel ` to speed things up... | os . makedirs ( Path ( label_path ) , exist_ok = True )
parallel ( partial ( _download_single_image , label_path , timeout = timeout ) , img_tuples , max_workers = max_workers )
return get_image_files ( label_path ) |
def update_network ( self , network , name ) :
'''Updates a network''' | net_id = self . _find_network_id ( network )
return self . network_conn . update_network ( network = net_id , body = { 'network' : { 'name' : name } } ) |
def scan_processes_fast ( self ) :
"""Populates the snapshot with running processes .
Only the PID is retrieved for each process .
Dead processes are removed .
Threads and modules of living processes are ignored .
Tipically you don ' t need to call this method directly , if unsure use
L { scan } instead .... | # Get the new and old list of pids
new_pids = set ( win32 . EnumProcesses ( ) )
old_pids = set ( compat . iterkeys ( self . __processDict ) )
# Ignore our own pid
our_pid = win32 . GetCurrentProcessId ( )
if our_pid in new_pids :
new_pids . remove ( our_pid )
if our_pid in old_pids :
old_pids . remove ( our_pid... |
def default ( value ) :
"""Default encoder for JSON""" | if isinstance ( value , Decimal ) :
primative = float ( value )
if int ( primative ) == primative :
return int ( primative )
else :
return primative
elif isinstance ( value , set ) :
return list ( value )
elif isinstance ( value , Binary ) :
return b64encode ( value . value )
raise T... |
def modify_cache_parameter_group ( name , region = None , key = None , keyid = None , profile = None , ** args ) :
'''Update a cache parameter group in place .
Note that due to a design limitation in AWS , this function is not atomic - - a maximum of 20
params may be modified in one underlying boto call . This ... | args = dict ( [ ( k , v ) for k , v in args . items ( ) if not k . startswith ( '_' ) ] )
try :
Params = args [ 'ParameterNameValues' ]
except ValueError as e :
raise SaltInvocationError ( 'Invalid `ParameterNameValues` structure passed.' )
while Params :
args . update ( { 'ParameterNameValues' : Params [ :... |
def update_ip_info ( self , since_days = 10 , save = False , force = False ) :
"""Update the IP info .
Args :
since _ days ( int ) : if checked less than this number of days ago ,
don ' t check again ( default to 10 days ) .
save ( bool ) : whether to save anyway or not .
force ( bool ) : whether to updat... | # If ip already checked
try :
last_check = IPInfoCheck . objects . get ( ip_address = self . client_ip_address )
# If checked less than since _ days ago , don ' t check again
since_last = datetime . date . today ( ) - last_check . date
if since_last <= datetime . timedelta ( days = since_days ) :
... |
def getRemoteObject ( self , busName , objectPath , interfaces = None , replaceKnownInterfaces = False ) :
"""Creates a L { objects . RemoteDBusObject } instance to represent the
specified DBus object . If explicit interfaces are not supplied , DBus
object introspection will be used to obtain them automatically... | return self . objHandler . getRemoteObject ( busName , objectPath , interfaces , replaceKnownInterfaces , ) |
def stop ( self ) :
"""Close websocket connection .""" | self . state = STATE_STOPPED
if self . transport :
self . transport . close ( ) |
def classname ( ob ) :
"""Get the object ' s class ' s name as package . module . Class""" | import inspect
if inspect . isclass ( ob ) :
return '.' . join ( [ ob . __module__ , ob . __name__ ] )
else :
return '.' . join ( [ ob . __class__ . __module__ , ob . __class__ . __name__ ] ) |
def ___replace_adjective_maybe ( sentence , counts ) :
"""Lets find and replace all instances of # ADJECTIVE _ MAYBE
: param _ sentence :
: param counts :""" | random_decision = random . randint ( 0 , 1 )
if sentence is not None :
while sentence . find ( '#ADJECTIVE_MAYBE' ) != - 1 :
if random_decision % 2 == 0 :
sentence = sentence . replace ( '#ADJECTIVE_MAYBE' , ' ' + str ( __get_adjective ( counts ) ) , 1 )
elif random_decision % 2 != 0 :
... |
async def raw_command ( self , service : str , method : str , params : Any ) :
"""Call an arbitrary method with given parameters .
This is useful for debugging and trying out commands before
implementing them properly .
: param service : Service , use list ( self . services ) to get a list of availables .
:... | _LOGGER . info ( "Calling %s.%s(%s)" , service , method , params )
return await self . services [ service ] [ method ] ( params ) |
def _pre_md5_skip_on_check ( self , lpath , rfile ) : # type : ( Downloader , pathlib . Path ,
# blobxfer . models . azure . StorageEntity ) - > None
"""Perform pre MD5 skip on check
: param Downloader self : this
: param pathlib . Path lpath : local path
: param blobxfer . models . azure . StorageEntity rfil... | md5 = blobxfer . models . metadata . get_md5_from_metadata ( rfile )
key = blobxfer . operations . download . Downloader . create_unique_transfer_operation_id ( rfile )
with self . _md5_meta_lock :
self . _md5_map [ key ] = rfile
slpath = str ( lpath )
# temporarily create a download descriptor view for vectored io... |
def generate_pipeline_code ( pipeline_tree , operators ) :
"""Generate code specific to the construction of the sklearn Pipeline .
Parameters
pipeline _ tree : list
List of operators in the current optimized pipeline
Returns
Source code for the sklearn pipeline""" | steps = _process_operator ( pipeline_tree , operators )
pipeline_text = "make_pipeline(\n{STEPS}\n)" . format ( STEPS = _indent ( ",\n" . join ( steps ) , 4 ) )
return pipeline_text |
def create ( self , model_name ) :
"""Create a model .
Args :
model _ name : the short name of the model , such as " iris " .
Returns :
If successful , returns informaiton of the model , such as
{ u ' regions ' : [ u ' us - central1 ' ] , u ' name ' : u ' projects / myproject / models / mymodel ' }
Rais... | body = { 'name' : model_name }
parent = 'projects/' + self . _project_id
# Model creation is instant . If anything goes wrong , Exception will be thrown .
return self . _api . projects ( ) . models ( ) . create ( body = body , parent = parent ) . execute ( ) |
def update_fixed_order ( self ) :
"after pruning fixed order needs update to match new nnodes / ntips ." | # set tips order if fixing for multi - tree plotting ( default None )
fixed_order = self . ttree . _fixed_order
self . ttree_fixed_order = None
self . ttree_fixed_idx = list ( range ( self . ttree . ntips ) )
# check if fixed _ order changed :
if fixed_order :
fixed_order = [ i for i in fixed_order if i in self . t... |
def __view_to_selected_graphics ( self , data_and_metadata : DataAndMetadata . DataAndMetadata ) -> None :
"""Change the view to encompass the selected graphic intervals .""" | all_graphics = self . __graphics
graphics = [ graphic for graphic_index , graphic in enumerate ( all_graphics ) if self . __graphic_selection . contains ( graphic_index ) ]
intervals = list ( )
for graphic in graphics :
if isinstance ( graphic , Graphics . IntervalGraphic ) :
intervals . append ( graphic . ... |
def overall_CEN_calc ( classes , TP , TOP , P , CEN_dict , modified = False ) :
"""Calculate Overall _ CEN ( Overall confusion entropy ) .
: param classes : classes
: type classes : list
: param TP : true positive dict for all classes
: type TP : dict
: param TOP : test outcome positive
: type TOP : dic... | try :
result = 0
for i in classes :
result += ( convex_combination ( classes , TP , TOP , P , i , modified ) * CEN_dict [ i ] )
return result
except Exception :
return "None" |
def update_stats ( self , stats , value , _type , sample_rate = 1 ) :
"""Pipeline function that formats data , samples it and passes to send ( )
> > > client = StatsdClient ( )
> > > client . update _ stats ( ' example . update _ stats ' , 73 , " c " , 0.9)""" | stats = self . format ( stats , value , _type , self . prefix )
self . send ( self . sample ( stats , sample_rate ) , self . addr ) |
def as_array ( self , include_missing = False , weighted = True , include_transforms_for_dims = None , prune = False , ) :
"""Return ` ndarray ` representing cube values .
Returns the tabular representation of the crunch cube . The returned
array has the same number of dimensions as the cube . E . g . for
a c... | array = self . _as_array ( include_missing = include_missing , weighted = weighted , include_transforms_for_dims = include_transforms_for_dims , )
# - - - prune array if pruning was requested - - -
if prune :
array = self . _prune_body ( array , transforms = include_transforms_for_dims )
return self . _drop_mr_cat_... |
def _interfaces_ifconfig ( out ) :
"""Uses ifconfig to return a dictionary of interfaces with various information
about each ( up / down state , ip address , netmask , and hwaddr )""" | ret = dict ( )
piface = re . compile ( r'^([^\s:]+)' )
pmac = re . compile ( '.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)' )
pip = re . compile ( r'.*?(?:inet addr:|inet )(.*?)\s' )
pip6 = re . compile ( '.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)' )
pmask = re . compile ( r'.*?(?:Mask:|netmask )(?:((?:0x)... |
def _dicts_to_columns ( dicts ) :
"""Given a List of Dictionaries with uniform keys , returns a single Dictionary
with keys holding a List of values matching the key in the original List .
[ { ' name ' : ' Field Museum ' , ' location ' : ' Chicago ' } ,
{ ' name ' : ' Epcot ' , ' location ' : ' Orlando ' } ] ... | keys = dicts [ 0 ] . keys ( )
result = dict ( ( k , [ ] ) for k in keys )
for d in dicts :
for k , v in d . items ( ) :
result [ k ] += [ v ]
return result |
def resolve_dns ( opts , fallback = True ) :
'''Resolves the master _ ip and master _ uri options''' | ret = { }
check_dns = True
if ( opts . get ( 'file_client' , 'remote' ) == 'local' and not opts . get ( 'use_master_when_local' , False ) ) :
check_dns = False
# Since salt . log is imported below , salt . utils . network needs to be imported here as well
import salt . utils . network
if check_dns is True :
try... |
def _ReadFileEntries ( self , file_object ) :
"""Reads the file entries from the cpio archive .
Args :
file _ object ( FileIO ) : file - like object .""" | self . _file_entries = { }
file_offset = 0
while file_offset < self . _file_size or self . _file_size == 0 :
file_entry = self . _ReadFileEntry ( file_object , file_offset )
file_offset += file_entry . size
if file_entry . path == 'TRAILER!!!' :
break
if file_entry . path in self . _file_entries... |
def cmd ( send , msg , args ) :
"""Converts text into NATO form .
Syntax : { command } < text >""" | if not msg :
send ( "NATO what?" )
return
nato = gen_nato ( msg )
if len ( nato ) > 100 :
send ( "Your NATO is too long. Have you considered letters?" )
else :
send ( nato ) |
def export_olx ( self , tarball , root_path ) :
"""if sequestered , only export the assets""" | def append_asset_to_soup_and_export ( asset_ ) :
if isinstance ( asset_ , Item ) :
try :
unique_url = asset_ . export_olx ( tarball , root_path )
except AttributeError :
pass
else :
unique_name = get_file_name_without_extension ( unique_url )
a... |
def get_error ( time , x , sets , err_type = 'block' , tool = 'gmx analyze' ) :
"""To estimate error using block averaging method
. . warning : :
To calculate errors by using ` ` error = ' acf ' ` ` or ` ` error = ' block ' ` ` ,
GROMACS tool ` ` g _ analyze ` ` or ` ` gmx analyze ` ` should be present in ` `... | for i in range ( sets ) :
if ( len ( time ) != len ( x [ i ] ) ) :
raise ValueError ( '\nError: number of frame in time {0} mismatched with {1} of x[{2}]!!\n' . format ( len ( time ) , len ( x [ i ] ) , i ) )
if not ( ( err_type == 'block' ) or ( err_type == 'acf' ) ) :
print ( '\nWarning: Method {0} is... |
def _qr_code ( self , instance ) :
"""return generate html code with " otpauth : / / . . . " link and QR - code""" | request = self . request
# FIXME
try :
user = instance . user
except ObjectDoesNotExist :
return _ ( "Please save first!" )
current_site = get_current_site ( request )
username = user . username
secret = six . text_type ( base64 . b32encode ( instance . bin_key ) , encoding = "ASCII" )
key_uri = ( "otpauth://to... |
def _relative_uris ( self , uri_list ) :
"""if uris in list are relative , re - relate them to our basedir""" | return [ u for u in ( self . _relative ( uri ) for uri in uri_list ) if u ] |
def make_data ( n , prob ) :
"""make _ data : prepare data for a random graph
Parameters :
- n : number of vertices
- prob : probability of existence of an edge , for each pair of vertices
Returns a tuple with a list of vertices and a list edges .""" | V = range ( 1 , n + 1 )
E = [ ( i , j ) for i in V for j in V if i < j and random . random ( ) < prob ]
return V , E |
def count_seven_in_multiples ( n : int ) -> int :
"""Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
Args :
n ( int ) : The upper limit to consider for the count .
Returns :
int : The count of number ' 7 ' in the desired range .
Examples :
> > > co... | count = 0
for number in range ( n ) :
if number % 11 == 0 or number % 13 == 0 :
count += str ( number ) . count ( "7" )
return count |
def prepare ( self , variables ) :
"""Initialize all steps in this recipe using their parameters .
Args :
variables ( dict ) : A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each step .
Returns :
list of RecipeActionObject like instances : The ... | initializedsteps = [ ]
if variables is None :
variables = dict ( )
for step , params , _resources , _files in self . steps :
new_params = _complete_parameters ( params , variables )
initializedsteps . append ( step ( new_params ) )
return initializedsteps |
def distance ( lons1 , lats1 , depths1 , lons2 , lats2 , depths2 ) :
"""Calculate a distance between two points ( or collections of points )
considering points ' depth .
Calls : func : ` geodetic _ distance ` , finds the " vertical " distance between
points by subtracting one depth from another and combine bo... | hdist = geodetic_distance ( lons1 , lats1 , lons2 , lats2 )
vdist = depths1 - depths2
return numpy . sqrt ( hdist ** 2 + vdist ** 2 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.