signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def resteem ( self , identifier ) :
'''Waits 20 seconds as that is the required
amount of time between resteems''' | for num_of_retries in range ( default . max_retry ) :
try :
self . steem_instance ( ) . resteem ( identifier , self . mainaccount )
self . msg . message ( "resteemed " + identifier )
time . sleep ( 10 )
except Exception as e :
self . util . retry ( '''COULD NOT RESTEEM
... |
def _get_state_changes ( self , limit : int = None , offset : int = None , filters : List [ Tuple [ str , Any ] ] = None , logical_and : bool = True , ) -> List [ StateChangeRecord ] :
"""Return a batch of state change records ( identifier and data )
The batch size can be tweaked with the ` limit ` and ` offset `... | cursor = self . _form_and_execute_json_query ( query = 'SELECT identifier, data FROM state_changes ' , limit = limit , offset = offset , filters = filters , logical_and = logical_and , )
result = [ StateChangeRecord ( state_change_identifier = row [ 0 ] , data = row [ 1 ] , ) for row in cursor ]
return result |
def load_tk_image ( filename ) :
"""Load in an image file and return as a tk Image .
: param filename : image filename to load
: return : tk Image object""" | if filename is None :
return None
if not os . path . isfile ( filename ) :
raise ValueError ( 'Image file {} does not exist.' . format ( filename ) )
tk_image = None
filename = os . path . normpath ( filename )
_ , ext = os . path . splitext ( filename )
try :
pil_image = PILImage . open ( filename )
tk... |
def _executor ( self , host ) :
'''handler for multiprocessing library''' | try :
exec_rc = self . _executor_internal ( host )
# if type ( exec _ rc ) ! = ReturnData and type ( exec _ rc ) ! = ansible . runner . return _ data . ReturnData :
# raise Exception ( " unexpected return type : % s " % type ( exec _ rc ) )
# redundant , right ?
if not exec_rc . comm_ok :
se... |
def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] :
"""Returns the default bucket from a list of buckets , i . e . the largest bucket .
: param buckets : List of buckets .
: return : The largest bucket in the list .""" | return max ( buckets ) |
def remove_from_role ( server_context , role , user_id = None , email = None , container_path = None ) :
"""Remove user / group from security role
: param server _ context : A LabKey server context . See utils . create _ server _ context .
: param role : ( from get _ roles ) to remove user from
: param user _... | return __make_security_role_api_request ( server_context , 'removeAssignment.api' , role , user_id = user_id , email = email , container_path = container_path ) |
def distort_image ( image , height , width , bbox , thread_id = 0 , scope = None ) :
"""Distort one image for training a network .
Distorting images provides a useful technique for augmenting the data
set during training in order to make the network invariant to aspects
of the image that do not effect the lab... | with tf . name_scope ( values = [ image , height , width , bbox ] , name = scope , default_name = 'distort_image' ) : # Each bounding box has shape [ 1 , num _ boxes , box coords ] and
# the coordinates are ordered [ ymin , xmin , ymax , xmax ] .
# Display the bounding box in the first thread only .
if not thread_i... |
def _send ( self ) :
"""Implementation of the send thread . Waits for data to be added
to the send buffer , then passes as much of the buffered data
to the socket ` ` send ( ) ` ` method as possible .""" | # Outer loop : wait for data to send
while True : # Release the send lock and wait for data , then reacquire
# the send lock
self . _send_lock . release ( )
self . _sendbuf_event . wait ( )
self . _send_lock . acquire ( )
# Inner loop : send as much data as we can
while self . _sendbuf :
sen... |
def get_settings ( self , section = None , defaults = None ) :
"""Gets a named section from the configuration source .
: param section : a : class : ` str ` representing the section you want to
retrieve from the configuration source . If ` ` None ` ` this will
fallback to the : attr : ` plaster . PlasterURL .... | # This is a partial reimplementation of
# ` ` paste . deploy . loadwsgi . ConfigLoader : get _ context ` ` which supports
# " set " and " get " options and filters out any other globals
section = self . _maybe_get_default_name ( section )
if self . filepath is None :
return { }
parser = self . _get_parser ( default... |
def handle_shell_config ( shell , vexrc , environ ) :
"""Carry out the logic of the - - shell - config option .""" | from vex import shell_config
data = shell_config . shell_config_for ( shell , vexrc , environ )
if not data :
raise exceptions . OtherShell ( "unknown shell: {0!r}" . format ( shell ) )
if hasattr ( sys . stdout , 'buffer' ) :
sys . stdout . buffer . write ( data )
else :
sys . stdout . write ( data )
retur... |
def init_tornado_workers ( self ) :
"""Prepare worker instances for all Tornado applications . Return
: class : ` list ` of the : class : ` ProcessWrapper ` instances .""" | workers = [ ]
for tornado_app in get_tornado_apps ( self . context , debug = False ) :
interface = tornado_app . settings [ 'interface' ]
if not interface . port and not interface . unix_socket :
raise ValueError ( 'Interface MUST listen either on TCP ' 'or UNIX socket or both' )
name , processes , ... |
def make_view ( robot ) :
"""为一个 BaseRoBot 生成 Bottle view 。
Usage : :
from werobot import WeRoBot
robot = WeRoBot ( token = ' token ' )
@ robot . handler
def hello ( message ) :
return ' Hello World ! '
from bottle import Bottle
from werobot . contrib . bottle import make _ view
app = Bottle ( )
... | def werobot_view ( * args , ** kwargs ) :
if not robot . check_signature ( request . query . timestamp , request . query . nonce , request . query . signature ) :
return HTTPResponse ( status = 403 , body = robot . make_error_page ( html . escape ( request . url ) ) )
if request . method == 'GET' :
... |
def get_next_base26 ( prev = None ) :
"""Increment letter - based IDs .
Generates IDs like [ ' a ' , ' b ' , . . . , ' z ' , ' aa ' , ab ' , . . . , ' az ' , ' ba ' , . . . ]
Returns :
str : Next base - 26 ID .""" | if not prev :
return 'a'
r = re . compile ( "^[a-z]*$" )
if not r . match ( prev ) :
raise ValueError ( "Invalid base26" )
if not prev . endswith ( 'z' ) :
return prev [ : - 1 ] + chr ( ord ( prev [ - 1 ] ) + 1 )
return get_next_base26 ( prev [ : - 1 ] ) + 'a' |
def grants ( self ) :
"""Returns grants for the current user""" | from linode_api4 . objects . account import UserGrants
resp = self . _client . get ( '/profile/grants' )
# use special endpoint for restricted users
grants = None
if resp is not None : # if resp is None , we ' re unrestricted and do not have grants
grants = UserGrants ( self . _client , self . username , resp )
ret... |
def widget_attrs ( self , widget ) :
"""Given a Widget instance ( * not * a Widget class ) , returns a dictionary of
any HTML attributes that should be added to the Widget , based on this
Field .""" | attrs = { }
if getattr ( self , "min_value" , None ) is not None :
attrs [ 'min' ] = self . min_value
if getattr ( self , "max_value" , None ) is not None :
attrs [ 'max' ] = self . max_value
return attrs |
def get_subscription ( self , subscription_id ) :
"""Get single subscription""" | url = self . SUBSCRIPTIONS_ID_URL % subscription_id
connection = Connection ( self . token )
connection . set_url ( self . production , url )
return connection . get_request ( ) |
def run ( self , * args ) :
"""Import data on the registry .
By default , it reads the data from the standard input . If a positional
argument is given , it will read the data from there .""" | params = self . parser . parse_args ( args )
with params . infile as infile :
try :
stream = self . __read_file ( infile )
parser = SortingHatParser ( stream )
except InvalidFormatError as e :
self . error ( str ( e ) )
return e . code
except ( IOError , TypeError , Attribute... |
def _validate_options ( cls , options ) :
"""Validate the mutually exclusive options .
Return ` True ` iff only zero or one of ` BASE _ ERROR _ SELECTION _ OPTIONS `
was selected .""" | for opt1 , opt2 in itertools . permutations ( cls . BASE_ERROR_SELECTION_OPTIONS , 2 ) :
if getattr ( options , opt1 ) and getattr ( options , opt2 ) :
log . error ( 'Cannot pass both {} and {}. They are ' 'mutually exclusive.' . format ( opt1 , opt2 ) )
return False
if options . convention and opti... |
def check_json ( code ) :
"""Yield errors .""" | try :
json . loads ( code )
except ValueError as exception :
message = '{}' . format ( exception )
line_number = 0
found = re . search ( r': line\s+([0-9]+)[^:]*$' , message )
if found :
line_number = int ( found . group ( 1 ) )
yield ( int ( line_number ) , message ) |
def command_deps_status ( self ) :
"""Print dependencies status""" | image = ""
for arg in self . args :
if arg . startswith ( "--graph=" ) :
image = arg . split ( "=" ) [ 1 ]
if len ( self . args ) == 1 and self . args [ 0 ] == "deps-status" :
DependenciesStatus ( image ) . show ( )
elif len ( self . args ) == 2 and self . args [ 0 ] == "deps-status" and image :
Dep... |
def _drawContents ( self , reason = None , initiator = None ) :
"""Draws the plot contents from the sliced array of the collected repo tree item .
The reason parameter is used to determine if the axes will be reset ( the initiator
parameter is ignored ) . See AbstractInspector . updateContents for their descrip... | self . crossPlotRow = None
# reset because the sliced array shape may change
self . crossPlotCol = None
# idem dito
gridLayout = self . graphicsLayoutWidget . ci . layout
# A QGraphicsGridLayout
if self . config . horCrossPlotCti . configValue :
gridLayout . setRowStretchFactor ( ROW_HOR_LINE , 1 )
if not self ... |
def add_nodes_to_axes ( self ) :
"""Creates a new marker for every node from idx indexes and lists of
node _ values , node _ colors , node _ sizes , node _ style , node _ labels _ style .
Pulls from node _ color and adds to a copy of the style dict for each
node to create marker .
Node _ colors has priority... | # bail out if not any visible nodes ( e . g . , none w / size > 0)
if all ( [ i == "" for i in self . node_labels ] ) :
return
# build markers for each node .
marks = [ ]
for nidx in self . ttree . get_node_values ( 'idx' , 1 , 1 ) : # select node value from deconstructed lists
nlabel = self . node_labels [ nid... |
def new ( self , bytes_to_skip ) : # type : ( int ) - > None
'''Create a new Rock Ridge Sharing Protocol record .
Parameters :
bytes _ to _ skip - The number of bytes to skip .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'SP record already initialized!' )
self . bytes_to_skip = bytes_to_skip
self . _initialized = True |
def fromAddress ( address ) :
"""This method should be used to create
an iban object from ethereum address
@ method fromAddress
@ param { String } address
@ return { Iban } the IBAN object""" | validate_address ( address )
address_as_integer = int ( address , 16 )
address_as_base36 = baseN ( address_as_integer , 36 )
padded = pad_left_hex ( address_as_base36 , 15 )
return Iban . fromBban ( padded . upper ( ) ) |
def with_metaclass ( meta , * bases ) :
"""Python 2 and 3 compatible way to do meta classes""" | class metaclass ( meta ) :
def __new__ ( cls , name , this_bases , d ) :
return meta ( name , bases , d )
return type . __new__ ( metaclass , "temporary_class" , ( ) , { } ) |
def create ( cls , currency , all_co_owner , description = None , daily_limit = None , overdraft_limit = None , alias = None , avatar_uuid = None , status = None , sub_status = None , reason = None , reason_description = None , notification_filters = None , setting = None , custom_headers = None ) :
""": type user ... | if custom_headers is None :
custom_headers = { }
request_map = { cls . FIELD_CURRENCY : currency , cls . FIELD_DESCRIPTION : description , cls . FIELD_DAILY_LIMIT : daily_limit , cls . FIELD_OVERDRAFT_LIMIT : overdraft_limit , cls . FIELD_ALIAS : alias , cls . FIELD_AVATAR_UUID : avatar_uuid , cls . FIELD_STATUS : ... |
def generate ( self ) :
"""Generate sample settings""" | otype = getattr ( self , 'GENERATE' )
if otype :
if otype == 'env' :
self . generate_env ( )
elif otype == "command" :
self . generate_command ( )
elif otype == "docker-run" :
self . generate_docker_run ( )
elif otype == "docker-compose" :
self . generate_docker_compose (... |
def cython_debug_files ( ) :
"""Cython extra debug information files""" | # Search all subdirectories of sys . path directories for a
# " cython _ debug " directory . Note that sys _ path is a variable set by
# cysignals - CSI . It may differ from sys . path if GDB is run with a
# different Python interpreter .
files = [ ]
for path in sys_path : # noqa
pattern = os . path . join ( path ,... |
def run_hooks ( self , packet ) :
"""Run any additional functions that want to process this type of packet .
These can be internal parser hooks , or external hooks that process
information""" | if packet . __class__ in self . internal_hooks :
self . internal_hooks [ packet . __class__ ] ( packet )
if packet . __class__ in self . hooks :
self . hooks [ packet . __class__ ] ( packet ) |
def transform ( data_frame , ** kwargs ) :
"""Return a transformed DataFrame .
Transform data _ frame along the given axis . By default , each row will be normalized ( axis = 0 ) .
Parameters
data _ frame : DataFrame
Data to be normalized .
axis : int , optional
0 ( default ) to normalize each row , 1 t... | norm = kwargs . get ( 'norm' , 1.0 )
axis = kwargs . get ( 'axis' , 0 )
if axis == 0 :
norm_vector = _get_norms_of_rows ( data_frame , kwargs . get ( 'method' , 'vector' ) )
else :
norm_vector = _get_norms_of_cols ( data_frame , kwargs . get ( 'method' , 'first' ) )
if 'labels' in kwargs :
if axis == 0 :
... |
def linspace ( start , stop , num , decimals = 18 ) :
"""Returns a list of evenly spaced numbers over a specified interval .
Inspired from Numpy ' s linspace function : https : / / github . com / numpy / numpy / blob / master / numpy / core / function _ base . py
: param start : starting value
: type start : ... | start = float ( start )
stop = float ( stop )
if abs ( start - stop ) <= 10e-8 :
return [ start ]
num = int ( num )
if num > 1 :
div = num - 1
delta = stop - start
return [ float ( ( "{:." + str ( decimals ) + "f}" ) . format ( ( start + ( float ( x ) * float ( delta ) / float ( div ) ) ) ) ) for x in r... |
def lerp_quat ( from_quat , to_quat , percent ) :
"""Return linear interpolation of two quaternions .""" | # Check if signs need to be reversed .
if dot_quat ( from_quat , to_quat ) < 0.0 :
to_sign = - 1
else :
to_sign = 1
# Simple linear interpolation
percent_from = 1.0 - percent
percent_to = percent
result = Quat ( percent_from * from_quat . x + to_sign * percent_to * to_quat . x , percent_from * from_quat . y + t... |
def auth_get ( user , computed = True ) :
'''List authorization for user
user : string
username
computed : boolean
merge results from ` auths ` command into data from user _ attr
CLI Example :
. . code - block : : bash
salt ' * ' rbac . auth _ get leo''' | user_auths = [ ]
# # read user _ attr file ( user : qualifier : res1 : res2 : attr )
with salt . utils . files . fopen ( '/etc/user_attr' , 'r' ) as user_attr :
for auth in user_attr :
auth = salt . utils . stringutils . to_unicode ( auth )
auth = auth . strip ( ) . split ( ':' )
# skip comm... |
def list_container_instance_groups ( access_token , subscription_id , resource_group ) :
'''List the container groups in a resource group .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) : Azure subscription id .
resource _ group ( str ) : Azure resource group... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , resource_group , '/providers/Microsoft.ContainerInstance/ContainerGroups' , '?api-version=' , CONTAINER_API ] )
return do_get ( endpoint , access_token ) |
def nic_v1 ( msg , NICs ) :
"""Calculate NIC , navigation integrity category , for ADS - B version 1
Args :
msg ( string ) : 28 bytes hexadecimal message string
NICs ( int or string ) : NIC supplement
Returns :
int or string : Horizontal Radius of Containment
int or string : Vertical Protection Limit""" | if typecode ( msg ) < 5 or typecode ( msg ) > 22 :
raise RuntimeError ( "%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg )
tc = typecode ( msg )
NIC = uncertainty . TC_NICv1_lookup [ tc ]
if isinsta... |
def satellites_list ( self , daemon_type = '' ) :
"""Get the arbiter satellite names sorted by type
Returns a list of the satellites as in :
reactionner : [
" reactionner - master "
broker : [
" broker - master "
arbiter : [
" arbiter - master "
scheduler : [
" scheduler - master - 3 " ,
" sched... | with self . app . conf_lock :
res = { }
for s_type in [ 'arbiter' , 'scheduler' , 'poller' , 'reactionner' , 'receiver' , 'broker' ] :
if daemon_type and daemon_type != s_type :
continue
satellite_list = [ ]
res [ s_type ] = satellite_list
for daemon_link in getattr (... |
def from_edgelist ( self , edges , strict = True ) :
"""Load transform data from an edge list into the current
scene graph .
Parameters
edgelist : ( n , ) tuples
( node _ a , node _ b , { key : value } )
strict : bool
If true , raise a ValueError when a
malformed edge is passed in a tuple .""" | # loop through each edge
for edge in edges : # edge contains attributes
if len ( edge ) == 3 :
self . update ( edge [ 1 ] , edge [ 0 ] , ** edge [ 2 ] )
# edge just contains nodes
elif len ( edge ) == 2 :
self . update ( edge [ 1 ] , edge [ 0 ] )
# edge is broken
elif strict :
... |
def _draw_surfaces ( self , surface , offset , surfaces ) :
"""Draw surfaces onto buffer , then redraw tiles that cover them
: param surface : destination
: param offset : offset to compensate for buffer alignment
: param surfaces : sequence of surfaces to blit""" | surface_blit = surface . blit
ox , oy = offset
left , top = self . _tile_view . topleft
hit = self . _layer_quadtree . hit
get_tile = self . data . get_tile_image
tile_layers = tuple ( self . data . visible_tile_layers )
dirty = list ( )
dirty_append = dirty . append
# TODO : check to avoid sorting overhead
# sort laye... |
def infer_newX ( self , Y_new , optimize = True ) :
"""Infer X for the new observed data * Y _ new * .
: param Y _ new : the new observed data for inference
: type Y _ new : numpy . ndarray
: param optimize : whether to optimize the location of new X ( True by default )
: type optimize : boolean
: return ... | from . . inference . latent_function_inference . inferenceX import infer_newX
return infer_newX ( self , Y_new , optimize = optimize ) |
def remote ( * args , ** kwargs ) :
"""Define a remote function or an actor class .
This can be used with no arguments to define a remote function or actor as
follows :
. . code - block : : python
@ ray . remote
def f ( ) :
return 1
@ ray . remote
class Foo ( object ) :
def method ( self ) :
ret... | worker = get_global_worker ( )
if len ( args ) == 1 and len ( kwargs ) == 0 and callable ( args [ 0 ] ) : # This is the case where the decorator is just @ ray . remote .
return make_decorator ( worker = worker ) ( args [ 0 ] )
# Parse the keyword arguments from the decorator .
error_string = ( "The @ray.remote deco... |
def get_region ( ) :
"""Gets the AWS Region ID for this system
: return : ( str ) AWS Region ID where this system lives""" | log = logging . getLogger ( mod_logger + '.get_region' )
# First get the availability zone
availability_zone = get_availability_zone ( )
if availability_zone is None :
msg = 'Unable to determine the Availability Zone for this system, cannot determine the AWS Region'
log . error ( msg )
return
# Strip of the... |
def _bind ( self , args , kwargs , partial = False ) :
"""Private method . Don ' t use directly .""" | arguments = OrderedDict ( )
parameters = iter ( self . parameters . values ( ) )
parameters_ex = ( )
arg_vals = iter ( args )
if partial : # Support for binding arguments to ' functools . partial ' objects .
# See ' functools . partial ' case in ' signature ( ) ' implementation
# for details .
for param_name , para... |
def decode_consumermetadata_response ( cls , data ) :
"""Decode bytes to a ConsumerMetadataResponse
: param bytes data : bytes to decode""" | ( correlation_id , error_code , node_id ) , cur = relative_unpack ( '>ihi' , data , 0 )
host , cur = read_short_ascii ( data , cur )
( port , ) , cur = relative_unpack ( '>i' , data , cur )
return ConsumerMetadataResponse ( error_code , node_id , nativeString ( host ) , port ) |
def configs ( max_configs = 1 , offset = None , serial = False , create_uuid = True ) :
"""Generate max configs , each one a dictionary . e . g . [ { ' x ' : 1 } ]
Will also add a config UUID , useful for tracking configs .
You can turn this off by passing create _ uuid = False .""" | global default_selector
return default_selector . configs ( max_configs , offset , serial , create_uuid ) |
async def FinishActions ( self , results ) :
'''results : typing . Sequence [ ~ ActionExecutionResult ]
Returns - > typing . Sequence [ ~ ErrorResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'Uniter' , request = 'FinishActions' , version = 5 , params = _params )
_params [ 'results' ] = results
reply = await self . rpc ( msg )
return reply |
def ExtValueMax ( mu , sigma , tag = None ) :
"""An Extreme Value Maximum random variate .
Parameters
mu : scalar
The location parameter
sigma : scalar
The scale parameter ( must be greater than zero )""" | assert sigma > 0 , 'ExtremeValueMax "sigma" must be greater than zero'
p = U ( 0 , 1 ) . _mcpts [ : ]
return UncertainFunction ( mu - sigma * np . log ( - np . log ( p ) ) , tag = tag ) |
def reload_glance ( self , target_app , slices = None ) :
"""Reloads an app ' s glance . Blocks as long as necessary .
: param target _ app : The UUID of the app for which to reload its glance .
: type target _ app : ~ uuid . UUID
: param slices : The slices with which to reload the app ' s glance .
: type ... | glance = AppGlance ( version = 1 , creation_time = time . time ( ) , slices = ( slices or [ ] ) )
SyncWrapper ( self . _blobdb . insert , BlobDatabaseID . AppGlance , target_app , glance . serialise ( ) ) . wait ( ) |
def saveSettings ( self , settings ) :
"""Saves the logging settings for this widget to the inputed settings .
: param < QtCore . QSettings >""" | lvls = [ ]
for logger , level in self . loggerLevels ( ) . items ( ) :
lvls . append ( '{0}:{1}' . format ( logger , level ) )
settings . setValue ( 'format' , wrapVariant ( self . formatText ( ) ) )
settings . setValue ( 'levels' , ',' . join ( map ( str , self . activeLevels ( ) ) ) )
settings . setValue ( 'logge... |
def get_all_dbsecurity_groups ( self , groupname = None , max_records = None , marker = None ) :
"""Get all security groups associated with your account in a region .
: type groupnames : list
: param groupnames : A list of the names of security groups to retrieve .
If not provided , all security groups will
... | params = { }
if groupname :
params [ 'DBSecurityGroupName' ] = groupname
if max_records :
params [ 'MaxRecords' ] = max_records
if marker :
params [ 'Marker' ] = marker
return self . get_list ( 'DescribeDBSecurityGroups' , params , [ ( 'DBSecurityGroup' , DBSecurityGroup ) ] ) |
def configure ( self , config ) :
"""Configures component by passing configuration parameters .
: param config : configuration parameters to be set .""" | credentials = CredentialParams . many_from_config ( config )
for credential in credentials :
self . _credentials . append ( credential ) |
def tokenise_word ( string , strict = False , replace = False , tones = False , unknown = False ) :
"""Tokenise the string into a list of tokens or raise ValueError if it cannot
be tokenised ( relatively ) unambiguously . The string should not include
whitespace , i . e . it is assumed to be a single word .
I... | string = normalise ( string )
if replace :
string = ipa . replace_substitutes ( string )
tokens = [ ]
for index , char in enumerate ( string ) :
if ipa . is_letter ( char , strict ) :
if tokens and ipa . is_tie_bar ( string [ index - 1 ] ) :
tokens [ - 1 ] += char
else :
... |
def fetcharrowbatches ( self , strings_as_dictionary = False , adaptive_integers = False ) :
"""Fetches rows in the active result set generated with ` ` execute ( ) ` ` or
` ` executemany ( ) ` ` as an iterable of arrow tables .
: param strings _ as _ dictionary : If true , fetch string columns as
dictionary ... | self . _assert_valid_result_set ( )
if _has_arrow_support ( ) :
from turbodbc_arrow_support import make_arrow_result_set
rs = make_arrow_result_set ( self . impl . get_result_set ( ) , strings_as_dictionary , adaptive_integers )
first_run = True
while True :
table = rs . fetch_next_batch ( )
... |
def from_key_bytes ( cls , algorithm , key_bytes ) :
"""Builds a ` Signer ` from an algorithm suite and a raw signing key .
: param algorithm : Algorithm on which to base signer
: type algorithm : aws _ encryption _ sdk . identifiers . Algorithm
: param bytes key _ bytes : Raw signing key
: rtype : aws _ en... | key = serialization . load_der_private_key ( data = key_bytes , password = None , backend = default_backend ( ) )
return cls ( algorithm , key ) |
def theta_str ( theta , taustr = TAUSTR , fmtstr = '{coeff:,.1f}{taustr}' ) :
r"""Format theta so it is interpretable in base 10
Args :
theta ( float ) angle in radians
taustr ( str ) : default 2pi
Returns :
str : theta _ str - the angle in tau units
Example1:
> > > # ENABLE _ DOCTEST
> > > from uto... | coeff = theta / TAU
theta_str = fmtstr . format ( coeff = coeff , taustr = taustr )
return theta_str |
def _path_polygon ( self , points ) :
"Low - level polygon - drawing routine ." | ( xmin , ymin , xmax , ymax ) = _compute_bounding_box ( points )
if invisible_p ( xmax , ymax ) :
return
self . setbb ( xmin , ymin )
self . setbb ( xmax , ymax )
self . newpath ( )
self . moveto ( xscale ( points [ 0 ] [ 0 ] ) , yscale ( points [ 0 ] [ 1 ] ) )
for point in points [ 1 : ] :
self . lineto ( xsca... |
def apply_config ( self , config ) :
"""Sets the ` discovery ` and ` meta _ cluster ` attributes , as well as the
configured + available balancer attributes from a given validated
config .""" | self . discovery = config [ "discovery" ]
self . meta_cluster = config . get ( "meta_cluster" )
for balancer_name in Balancer . get_installed_classes ( ) . keys ( ) :
if balancer_name in config :
setattr ( self , balancer_name , config [ balancer_name ] ) |
def get_by_identifier ( self , identifier ) :
"""Gets blocks by identifier
Args :
identifier ( str ) : Should be any of : username , phone _ number , email .
See : https : / / auth0 . com / docs / api / management / v2 # ! / User _ Blocks / get _ user _ blocks""" | params = { 'identifier' : identifier }
return self . client . get ( self . _url ( ) , params = params ) |
def visit ( self , node , * args , ** kwargs ) :
"""Visit a node .""" | f = self . get_visitor ( node )
if f is not None :
return f ( node , * args , ** kwargs )
return self . generic_visit ( node , * args , ** kwargs ) |
def bulk_add ( self , named_graph , add , size = DEFAULT_CHUNK_SIZE ) :
"""Add batches of statements in n - sized chunks .""" | return self . bulk_update ( named_graph , add , size ) |
def cmd ( send , * _ ) :
"""Enumerate threads .
Syntax : { command }""" | thread_names = [ ]
for x in sorted ( threading . enumerate ( ) , key = lambda k : k . name ) :
res = re . match ( r'Thread-(\d+$)' , x . name )
if res :
tid = int ( res . group ( 1 ) )
# Handle the main server thread ( permanently listed as _ worker )
if x . _target . __name__ == '_worke... |
def _read_table_file ( self , table_file ) :
"""Read an ` astropy . table . Table ` from table _ file to set up the ` JobArchive `""" | self . _table_file = table_file
if os . path . exists ( self . _table_file ) :
self . _table = Table . read ( self . _table_file , hdu = 'JOB_ARCHIVE' )
self . _table_ids = Table . read ( self . _table_file , hdu = 'FILE_IDS' )
else :
self . _table , self . _table_ids = JobDetails . make_tables ( { } )
self... |
def add_click_commands ( module , cli , command_dict , namespaced ) :
"""Loads all click commands""" | module_commands = [ item for item in getmembers ( module ) if isinstance ( item [ 1 ] , BaseCommand ) ]
options = command_dict . get ( 'config' , { } )
namespace = command_dict . get ( 'namespace' )
for name , function in module_commands :
f_options = options . get ( name , { } )
command_name = f_options . get ... |
def _local_times_from_hours_since_midnight ( times , hours ) :
"""converts hours since midnight from an array of floats to localized times""" | tz_info = times . tz
# pytz timezone info
naive_times = times . tz_localize ( None )
# naive but still localized
# normalize local , naive times to previous midnight and add the hours until
# sunrise , sunset , and transit
return pd . DatetimeIndex ( ( naive_times . normalize ( ) . astype ( np . int64 ) + ( hours * NS_... |
def _create_states ( self , states_num ) :
"""Args :
states _ num ( int ) : Number of States
Returns :
list : An initialized list""" | states = [ ]
for i in range ( 0 , states_num ) :
states . append ( i )
return states |
def update_metadata ( ctx , archive_name ) :
'''Update an archive ' s metadata''' | _generate_api ( ctx )
args , kwargs = _parse_args_and_kwargs ( ctx . args )
assert len ( args ) == 0 , 'Unrecognized arguments: "{}"' . format ( args )
var = ctx . obj . api . get_archive ( archive_name )
var . update_metadata ( metadata = kwargs ) |
def _interpolate_stream_track_aA ( self ) :
"""Build interpolations of the stream track in action - angle coordinates""" | if hasattr ( self , '_interpolatedObsTrackAA' ) :
return None
# Already did this
# Calculate 1D meanOmega on a fine grid in angle and interpolate
if not hasattr ( self , '_interpolatedThetasTrack' ) :
self . _interpolate_stream_track ( )
dmOs = numpy . array ( [ self . meanOmega ( da , oned = True , use_phy... |
def datetime_period ( base = None , hours = None , minutes = None , seconds = None ) :
"""Round a datetime object down to the start of a defined period .
The ` base ` argument may be used to find the period start for an arbitrary datetime , defaults to ` utcnow ( ) ` .""" | if base is None :
base = utcnow ( )
base -= timedelta ( hours = 0 if hours is None else ( base . hour % hours ) , minutes = ( base . minute if hours else 0 ) if minutes is None else ( base . minute % minutes ) , seconds = ( base . second if minutes or hours else 0 ) if seconds is None else ( base . second % seconds... |
def load ( filename ) :
"""Load an object that has been saved with dump .
We try to open it using the pickle protocol . As a fallback , we
use joblib . load . Joblib was the default prior to msmbuilder v3.2
Parameters
filename : string
The name of the file to load .""" | try :
with open ( filename , 'rb' ) as f :
return pickle . load ( f )
except Exception as e1 :
try :
return jl_load ( filename )
except Exception as e2 :
raise IOError ( "Unable to load {} using the pickle or joblib protocol.\n" "Pickle: {}\n" "Joblib: {}" . format ( filename , e1 , ... |
def fetch_data ( self , url ) :
'''Fetches data from specific url .
: return : The response .
: rtype : dict''' | return self . http . _post_data ( url , None , self . http . _headers_with_access_token ( ) ) |
def calc_coverage ( ref , start , end , length , nucs ) :
"""calculate coverage for positions in range start - > end""" | ref = ref [ start - 1 : end ]
bases = 0
for pos in ref :
for base , count in list ( pos . items ( ) ) :
if base in nucs :
bases += count
return float ( bases ) / float ( length ) |
def get_parent_repository_ids ( self , repository_id ) :
"""Gets the parent ` ` Ids ` ` of the given repository .
arg : repository _ id ( osid . id . Id ) : a repository ` ` Id ` `
return : ( osid . id . IdList ) - the parent ` ` Ids ` ` of the repository
raise : NotFound - ` ` repository _ id ` ` is not foun... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ parent _ bin _ ids
if self . _catalog_session is not None :
return self . _catalog_session . get_parent_catalog_ids ( catalog_id = repository_id )
return self . _hierarchy_session . get_parents ( id_ = repository_id ) |
def xpath ( self , expression ) :
"""return result for a call to lxml xpath ( )
output will be a list""" | self . __expression = expression
self . __namespaces = XPATH_NAMESPACES
return self . __doc . xpath ( self . __expression , namespaces = self . __namespaces ) |
def resolve_identifier ( self , name , expected_type = None ) :
"""Resolve an identifier to an object .
There is a single namespace for identifiers so the user also should
pass an expected type that will be checked against what the identifier
actually resolves to so that there are no surprises .
Args :
na... | name = str ( name )
if name in self . _known_identifiers :
obj = self . _known_identifiers [ name ]
if expected_type is not None and not isinstance ( obj , expected_type ) :
raise UnresolvedIdentifierError ( u"Identifier resolved to an object of an unexpected type" , name = name , expected_type = expect... |
def _check_certificate ( self ) :
"""Check for certificates options for wget""" | if ( self . file_name . startswith ( "jdk-" ) and self . repo == "sbo" and self . downder == "wget" ) :
certificate = ( ' --no-check-certificate --header="Cookie: ' 'oraclelicense=accept-securebackup-cookie"' )
self . msg . template ( 78 )
print ( "| '{0}' need to go ahead downloading" . format ( certificat... |
def __fixed_interpolation ( self , line ) :
"""Place additional points on the border at the specified distance .
By default the distance is 0.5 ( meters ) which means that the first
point will be placed 0.5 m from the starting point , the second
point will be placed at the distance of 1.0 m from the first
p... | STARTPOINT = [ line . xy [ 0 ] [ 0 ] - self . _minx , line . xy [ 1 ] [ 0 ] - self . _miny ]
ENDPOINT = [ line . xy [ 0 ] [ - 1 ] - self . _minx , line . xy [ 1 ] [ - 1 ] - self . _miny ]
count = self . _interpolation_dist
newline = [ STARTPOINT ]
while count < line . length :
point = line . interpolate ( count )
... |
def get_all_customer_gateways ( self , customer_gateway_ids = None , filters = None ) :
"""Retrieve information about your CustomerGateways . You can filter results to
return information only about those CustomerGateways that match your search
parameters . Otherwise , all CustomerGateways associated with your a... | params = { }
if customer_gateway_ids :
self . build_list_params ( params , customer_gateway_ids , 'CustomerGatewayId' )
if filters :
i = 1
for filter in filters :
params [ ( 'Filter.%d.Name' % i ) ] = filter [ 0 ]
params [ ( 'Filter.%d.Value.1' ) ] = filter [ 1 ]
i += 1
return self .... |
def items ( self ) :
"""Return a list of the ( name , value ) pairs of the enum .
These are returned in the order they were defined in the . proto file .""" | return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ] |
def cycle ( cb , pool , params , plane ) :
"""Fun function to do a palette cycling animation .
: param cb : Cursebox instance .
: type cb : cursebox . Cursebox
: param params : Current application parameters .
: type params : params . Params
: param plane : Plane containing the current Mandelbrot values .... | step = params . max_iterations // 20
if step == 0 :
step = 1
for i in range ( 0 , params . max_iterations , step ) :
params . palette_offset = i
draw_panel ( cb , pool , params , plane )
cb . refresh ( )
params . palette_offset = 0 |
def generate ( env ) :
"""Add Builders and construction variables for sun f90 compiler to an
Environment .""" | add_all_to_env ( env )
fcomp = env . Detect ( compilers ) or 'f90'
env [ 'FORTRAN' ] = fcomp
env [ 'F90' ] = fcomp
env [ 'SHFORTRAN' ] = '$FORTRAN'
env [ 'SHF90' ] = '$F90'
env [ 'SHFORTRANFLAGS' ] = SCons . Util . CLVar ( '$FORTRANFLAGS -KPIC' )
env [ 'SHF90FLAGS' ] = SCons . Util . CLVar ( '$F90FLAGS -KPIC' ) |
def to_simple_filter ( bool_or_filter ) :
"""Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter .""" | if not isinstance ( bool_or_filter , ( bool , SimpleFilter ) ) :
raise TypeError ( 'Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter )
return { True : _always , False : _never , } . get ( bool_or_filter , bool_or_filter ) |
def matrix_to_pair_dictionary ( X , row_keys = None , column_keys = None , filter_fn = None ) :
"""X : numpy . ndarray
row _ keys : dict
Dictionary mapping indices to row names . If omitted then maps each
number to its string representation , such as 1 - > " 1 " .
column _ keys : dict
If omitted and matri... | n_rows , n_cols = X . shape
if row_keys is None :
row_keys = { i : i for i in range ( n_rows ) }
if column_keys is None :
if n_rows == n_cols :
column_keys = row_keys
else :
column_keys = { j : j for j in range ( n_cols ) }
if len ( row_keys ) != n_rows :
raise ValueError ( "Need %d row ... |
def get_template ( self , template_name ) :
'''Retrieves a template object from the pattern " app _ name / template . html " .
This is one of the required methods of Django template engines .
Because DMP templates are always app - specific ( Django only searches
a global set of directories ) , the template _ ... | dmp = apps . get_app_config ( 'django_mako_plus' )
match = RE_TEMPLATE_NAME . match ( template_name )
if match is None or match . group ( 1 ) is None or match . group ( 3 ) is None :
raise TemplateDoesNotExist ( 'Invalid template_name format for a DMP template. This method requires that the template name be in app... |
def check ( ) -> Result :
"""Open and close the broker channel .""" | try : # Context to release connection
with Connection ( conf . get ( 'CELERY_BROKER_URL' ) ) as conn :
conn . connect ( )
except ConnectionRefusedError :
return Result ( message = 'Service unable to connect, "Connection was refused".' , severity = Result . ERROR )
except AccessRefused :
return Resul... |
def get_episode ( self , episode_id ) :
"""Returns the full information of the episode belonging to the Id provided .
: param episode _ id : The TheTVDB id of the episode .
: return : a python dictionary with either the result of the search or an error from TheTVDB .""" | raw_response = requests_util . run_request ( 'get' , self . API_BASE_URL + '/episodes/%d' % episode_id , headers = self . __get_header_with_auth ( ) )
return self . parse_raw_response ( raw_response ) |
def parallel ( fsms , test ) :
'''Crawl several FSMs in parallel , mapping the states of a larger meta - FSM .
To determine whether a state in the larger FSM is final , pass all of the
finality statuses ( e . g . [ True , False , False ] to ` test ` .''' | alphabet = set ( ) . union ( * [ fsm . alphabet for fsm in fsms ] )
initial = dict ( [ ( i , fsm . initial ) for ( i , fsm ) in enumerate ( fsms ) ] )
# dedicated function accepts a " superset " and returns the next " superset "
# obtained by following this transition in the new FSM
def follow ( current , symbol ) :
... |
def _get_responses ( link ) :
"""Returns an OpenApi - compliant response""" | template = link . response_schema
template . update ( { 'description' : 'Success' } )
res = { 200 : template }
res . update ( link . error_status_codes )
return res |
def check_sim_in ( self ) :
'''check for FDM packets from runsim''' | try :
pkt = self . sim_in . recv ( 17 * 8 + 4 )
except socket . error as e :
if not e . errno in [ errno . EAGAIN , errno . EWOULDBLOCK ] :
raise
return
if len ( pkt ) != 17 * 8 + 4 : # wrong size , discard it
print ( "wrong size %u" % len ( pkt ) )
return
( latitude , longitude , altitude ,... |
def page_for ( self , member , page_size = DEFAULT_PAGE_SIZE ) :
'''Determine the page where a member falls in the leaderboard .
@ param member [ String ] Member name .
@ param page _ size [ int ] Page size to be used in determining page location .
@ return the page where a member falls in the leaderboard .''... | return self . page_for_in ( self . leaderboard_name , member , page_size ) |
def delete_subscription ( self , subscription_id ) :
"""Deleting an existing subscription
: param subscription _ id : is the subscription the client wants to delete""" | self . _validate_uuid ( subscription_id )
url = "/notification/v1/subscription/{}" . format ( subscription_id )
response = NWS_DAO ( ) . deleteURL ( url , self . _write_headers ( ) )
if response . status != 204 :
raise DataFailureException ( url , response . status , response . data )
return response . status |
def get_tensor_shape ( self , tensor_name ) :
"""The tf . TensorShape of a tensor .
Args :
tensor _ name : string , the name of a tensor in the graph .
Returns :
a tf . TensorShape""" | tensor = self . _name_to_tensor ( tensor_name )
if isinstance ( tensor , mtf . Tensor ) :
return tf . TensorShape ( tensor . shape . to_integer_list )
else : # tf . Tensor
return tensor . shape |
def owner ( self ) :
"""Returns whether the lock is locked by a writer or reader .""" | if self . _writer is not None :
return self . WRITER
if self . _readers :
return self . READER
return None |
async def handle_frame ( self , frame ) :
"""Handle incoming API frame , return True if this was the expected frame .""" | if not isinstance ( frame , FrameGetVersionConfirmation ) :
return False
self . version = frame . version
self . success = True
return True |
def weld_merge_outer_join ( arrays_self , weld_types_self , arrays_other , weld_types_other , how , is_on_sorted , is_on_unique , readable_text ) :
"""Applies merge - join on the arrays returning indices from each to keep in the resulting
Parameters
arrays _ self : list of ( numpy . ndarray or WeldObject )
Co... | assert is_on_unique
weld_obj_vec_of_struct_self = weld_arrays_to_vec_of_struct ( arrays_self , weld_types_self )
weld_obj_vec_of_struct_other = weld_arrays_to_vec_of_struct ( arrays_other , weld_types_other )
weld_obj_join = _weld_merge_outer_join ( weld_obj_vec_of_struct_self , weld_obj_vec_of_struct_other , weld_type... |
def strip_pad ( hdu ) :
"""Remove the padding lines that CFHT adds to headers""" | l = hdu . header . ascardlist ( )
d = [ ]
for index in range ( len ( l ) ) :
if l [ index ] . key in __comment_keys and str ( l [ index ] ) == __cfht_padding :
d . append ( index )
d . reverse ( )
for index in d :
del l [ index ]
return ( 0 ) |
def whisper_filename ( self ) :
"""Build a file path to the Whisper database""" | source_name = self . source_id and self . source . name or ''
return get_valid_filename ( "{0}__{1}.wsp" . format ( source_name , self . name ) ) |
def convert ( input , type ) :
"""Converts input value to request type
: param input : input value
: param type : type to cast
: return : converted value""" | try :
if not input :
if type == Types . TYPE_STRING :
return ''
else :
return None
if type == Types . TYPE_STRING :
if isinstance ( input , datetime . date ) :
return input . strftime ( '%Y-%m-%d' )
else :
return input
if type =... |
def load ( self , modules ) :
"""Load Python modules and check their usability
: param modules : list of the modules that must be loaded
: return :""" | self . modules_assoc = [ ]
for module in modules :
if not module . enabled :
logger . info ( "Module %s is declared but not enabled" , module . name )
# Store in our modules list but do not try to load
# Probably someone else will load this module later . . .
self . modules [ module ... |
def parse_exception ( line ) :
'''Parse the first line of a Cartouche exception description .
Args :
line ( str ) : A single line Cartouche exception description .
Returns :
A 2 - tuple containing the exception type and the first line of the description .''' | m = RAISES_REGEX . match ( line )
if m is None :
raise CartoucheSyntaxError ( 'Cartouche: Invalid argument syntax "{line}" for Raises block' . format ( line = line ) )
return m . group ( 2 ) , m . group ( 1 ) |
def validate_services_by_name ( self , sentry_services ) :
"""Validate system service status by service name , automatically
detecting init system based on Ubuntu release codename .
: param sentry _ services : dict with sentry keys and svc list values
: returns : None if successful , Failure string message ot... | self . log . debug ( 'Checking status of system services...' )
# Point at which systemd became a thing
systemd_switch = self . ubuntu_releases . index ( 'vivid' )
for sentry_unit , services_list in six . iteritems ( sentry_services ) : # Get lsb _ release codename from unit
release , ret = self . get_ubuntu_release... |
def scantypes ( cls , value , value_type , visitor ) :
"""Like : py : meth : ` normalize . visitor . VisitorPattern . unpack ` , but
returns a getter which just returns the property , and a collection
getter which returns a set with a single item in it .""" | item_type_generator = None
if issubclass ( value_type , Collection ) :
def get_item_types ( ) :
if isinstance ( value_type . itemtype , tuple ) : # not actually supported by Collection yet , but whatever
for vt in value_type . itemtype :
yield ( vt , vt )
else :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.