signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def addRegion ( self , name , text , row , column ) :
"""Adds a new region for this zone at the given row and column .
: param name | < str >
text | < str >
row | < int >
column | < int >""" | region = XDropZoneRegion ( self )
region . setObjectName ( name )
region . setText ( text )
region . hide ( )
self . layout ( ) . addWidget ( region , row , column )
return region |
def _get_child_mock ( self , ** kws ) :
"""Create a new FileLikeMock instance .
The new mock will inherit the parent ' s side _ effect and read _ data
attributes .""" | kws . update ( { '_new_parent' : self , 'side_effect' : self . _mock_side_effect , 'read_data' : self . __read_data , } )
return FileLikeMock ( ** kws ) |
def find_if_x_retbool_else_retbool ( node ) :
"""Finds simplifiable if condition""" | return ( isinstance ( node , ast . If ) and isinstance ( node . body [ 0 ] , ast . Return ) and h . is_boolean ( node . body [ 0 ] . value ) and h . has_else ( node ) and isinstance ( node . orelse [ 0 ] , ast . Return ) and h . is_boolean ( node . orelse [ 0 ] . value ) ) |
def GetLogdirSubdirectories ( path ) :
"""Obtains all subdirectories with events files .
The order of the subdirectories returned is unspecified . The internal logic
that determines order varies by scenario .
Args :
path : The path to a directory under which to find subdirectories .
Returns :
A tuple of... | if not tf . io . gfile . exists ( path ) : # No directory to traverse .
return ( )
if not tf . io . gfile . isdir ( path ) :
raise ValueError ( 'GetLogdirSubdirectories: path exists and is not a ' 'directory, %s' % path )
if IsCloudPath ( path ) : # Glob - ing for files can be significantly faster than recursiv... |
def get_or_create ( cls , ** kwargs ) :
'''Creates an object or returns the object if exists
credit to Kevin @ StackOverflow
from : http : / / stackoverflow . com / questions / 2546207 / does - sqlalchemy - have - an - equivalent - of - djangos - get - or - create''' | session = Session ( )
instance = session . query ( cls ) . filter_by ( ** kwargs ) . first ( )
session . close ( )
if not instance :
self = cls ( ** kwargs )
self . save ( )
else :
self = instance
return self |
def space ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) :
"""Press white space key n times .
* * 中文文档 * *
按空格键 n 次 。""" | self . delay ( pre_dl )
self . k . tap_key ( self . k . space_key , n )
self . delay ( post_dl ) |
def withExactArgs ( self , * args , ** kwargs ) : # pylint : disable = invalid - name
"""Inspected function should be called with full of specified arguments
Args : any
Return : self""" | def check ( ) : # pylint : disable = missing - docstring
return super ( SinonExpectation , self ) . calledWithExactly ( * args , ** kwargs )
self . valid_list . append ( check )
return self |
def _get_env ( self ) :
"""this returns an environment dictionary we want to use to run the command
this will also create a fake pgpass file in order to make it possible for
the script to be passwordless""" | if hasattr ( self , 'env' ) :
return self . env
# create a temporary pgpass file
pgpass = self . _get_file ( )
# format : http : / / www . postgresql . org / docs / 9.2 / static / libpq - pgpass . html
pgpass . write ( '*:*:*:{}:{}\n' . format ( self . username , self . password ) . encode ( "utf-8" ) )
pgpass . cl... |
def authenticate ( self , code : str ) -> 'Preston' :
"""Authenticates using the code from the EVE SSO .
A new Preston object is returned ; this object is not modified .
The intended usage is :
auth = preston . authenticate ( ' some _ code _ here ' )
Args :
code : SSO code
Returns :
new Preston , auth... | headers = self . _get_authorization_headers ( )
data = { 'grant_type' : 'authorization_code' , 'code' : code }
r = self . session . post ( self . TOKEN_URL , headers = headers , data = data )
if not r . status_code == 200 :
raise Exception ( f'Could not authenticate, got repsonse code {r.status_code}' )
new_kwargs ... |
def get_witnesses ( self , name = '*' ) :
"""Returns a generator supplying ` WitnessText ` objects for each work
in the corpus .
: rtype : ` generator ` of ` WitnessText `""" | for filepath in glob . glob ( os . path . join ( self . _path , name , '*.txt' ) ) :
if os . path . isfile ( filepath ) :
name = os . path . split ( os . path . split ( filepath ) [ 0 ] ) [ 1 ]
siglum = os . path . splitext ( os . path . basename ( filepath ) ) [ 0 ]
yield self . get_witness... |
def get_user ( self , name ) :
"""Get user from kubeconfig .""" | users = self . data [ 'users' ]
for user in users :
if user [ 'name' ] == name :
return user
raise KubeConfError ( "user name not found." ) |
def new_credentials ( ) :
"""Generate a new identifier and seed for authentication .
Use the returned values in the following way :
* The identifier shall be passed as username to SRPAuthHandler . step1
* Seed shall be passed to SRPAuthHandler constructor""" | identifier = binascii . b2a_hex ( os . urandom ( 8 ) ) . decode ( ) . upper ( )
seed = binascii . b2a_hex ( os . urandom ( 32 ) )
# Corresponds to private key
return identifier , seed |
def serialize_basic ( self , data , data_type , ** kwargs ) :
"""Serialize basic builting data type .
Serializes objects to str , int , float or bool .
Possible kwargs :
- is _ xml bool : If set , adapt basic serializers without the need for basic _ types _ serializers
- basic _ types _ serializers dict [ s... | custom_serializer = self . _get_custom_serializers ( data_type , ** kwargs )
if custom_serializer :
return custom_serializer ( data )
if data_type == 'str' :
return self . serialize_unicode ( data )
return eval ( data_type ) ( data ) |
def DecoratorMixin ( decorator ) :
"""Converts a decorator written for a function view into a mixin for a
class - based view .
LoginRequiredMixin = DecoratorMixin ( login _ required )
class MyView ( LoginRequiredMixin ) :
pass
class SomeView ( DecoratorMixin ( some _ decorator ) ,
DecoratorMixin ( somet... | class Mixin ( object ) :
__doc__ = decorator . __doc__
@ classmethod
def as_view ( cls , * args , ** kwargs ) :
view = super ( Mixin , cls ) . as_view ( * args , ** kwargs )
return decorator ( view )
Mixin . __name__ = str ( 'DecoratorMixin(%s)' % decorator . __name__ )
return Mixin |
def _init_metadata ( self ) :
"""stub""" | self . _files_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'files' ) , 'element_label' : 'Files' , 'instructions' : 'enter a file id with optional label' , 'required' : False , 'read_only' : False , 'linked' : False , 'array' : False , 'default_obj... |
def before_request ( ) :
"""Checks to ensure that the session is valid and validates the users CSRF token is present
Returns :
` None `""" | if not request . path . startswith ( '/saml' ) and not request . path . startswith ( '/auth' ) : # Validate the session has the items we need
if 'accounts' not in session :
logger . debug ( 'Missing \'accounts\' from session object, sending user to login page' )
return BaseView . make_unauth_respons... |
def _is_allowed_signal ( self , signal ) :
"""Check if a signal is valid .
Raise an exception if the signal is not allowed .
Parameters
signal : str
a signal .""" | if signal not in self . _allowed_signals :
raise Exception ( "Signal '{0}' is not allowed for '{1}'." . format ( signal , type ( self ) ) ) |
def prepare ( self ) :
"""Prepares this graphic item to be displayed .""" | text = self . property ( 'caption' )
if text :
capw = int ( self . property ( 'caption_width' , 0 ) )
item = self . addText ( text , capw ) |
def handle_delete ( self ) :
"""Handle a graduated user being deleted .""" | from intranet . apps . eighth . models import EighthScheduledActivity
EighthScheduledActivity . objects . filter ( eighthsignup_set__user = self ) . update ( archived_member_count = F ( 'archived_member_count' ) + 1 ) |
def parse ( self , string , parent ) :
"""Parses all the value code elements from the specified string .""" | result = { }
for member in self . RE_MEMBERS . finditer ( string ) :
mems = self . _process_member ( member , parent , string )
# The regex match could contain multiple members that were defined
# on the same line in the code file .
for onemem in mems :
result [ onemem . name . lower ( ) ] = one... |
def cressman_point ( sq_dist , values , radius ) :
r"""Generate a Cressman interpolation value for a point .
The calculated value is based on the given distances and search radius .
Parameters
sq _ dist : ( N , ) ndarray
Squared distance between observations and grid point
values : ( N , ) ndarray
Obser... | weights = tools . cressman_weights ( sq_dist , radius )
total_weights = np . sum ( weights )
return sum ( v * ( w / total_weights ) for ( w , v ) in zip ( weights , values ) ) |
def get_list_by_name ( self , display_name ) :
"""Returns a sharepoint list based on the display name of the list""" | if not display_name :
raise ValueError ( 'Must provide a valid list display name' )
url = self . build_url ( self . _endpoints . get ( 'get_list_by_name' ) . format ( display_name = display_name ) )
response = self . con . get ( url )
if not response :
return [ ]
data = response . json ( )
return self . list_co... |
def read_flags_from_files ( self , argv , force_gnu = True ) :
"""Processes command line args , but also allow args to be read from file .
Args :
argv : [ str ] , a list of strings , usually sys . argv [ 1 : ] , which may contain
one or more flagfile directives of the form - - flagfile = " . / filename " .
... | rest_of_args = argv
new_argv = [ ]
while rest_of_args :
current_arg = rest_of_args [ 0 ]
rest_of_args = rest_of_args [ 1 : ]
if self . _is_flag_file_directive ( current_arg ) : # This handles the case of - ( - ) flagfile foo . In this case the
# next arg really is part of this one .
if current_a... |
def _R2deriv ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ R2deriv
PURPOSE :
evaluate the second radial derivative for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the second radial derivative
HISTORY :
2011-10-09 - Wri... | r2 = R ** 2. + z ** 2.
r = nu . sqrt ( r2 )
return ( 1. / r2 * ( 1. - R ** 2. / r2 * ( 3. * self . _a2 + 2. * r2 ) / ( self . _a2 + r2 ) ) + self . _a / r2 / r * ( 3. * R ** 2. / r2 - 1. ) * nu . arctan ( r / self . _a ) ) / self . _a |
def make_lastbeat ( peer_uid , app_id ) :
"""Prepares the last beat UDP packet ( when the peer is going away )
Format : Little endian
* Kind of beat ( 1 byte )
* Peer UID length ( 2 bytes )
* Peer UID ( variable , UTF - 8)
* Application ID length ( 2 bytes )
* Application ID ( variable , UTF - 8)
: pa... | packet = struct . pack ( "<BB" , PACKET_FORMAT_VERSION , PACKET_TYPE_LASTBEAT )
for string in ( peer_uid , app_id ) :
string_bytes = to_bytes ( string )
packet += struct . pack ( "<H" , len ( string_bytes ) )
packet += string_bytes
return packet |
def pure_murmur2 ( byte_array , seed = 0x9747b28c ) :
"""Pure - python Murmur2 implementation .
Based on java client , see org . apache . kafka . common . utils . Utils . murmur2
https : / / github . com / apache / kafka / blob / 0.8.2 / clients / src / main / java / org / apache / kafka / common / utils / Util... | # Ensure byte _ array arg is a bytearray
if not isinstance ( byte_array , bytearray ) :
raise TypeError ( "Type: %r of 'byte_array' arg must be 'bytearray'" , type ( byte_array ) )
length = len ( byte_array )
# ' m ' and ' r ' are mixing constants generated offline .
# They ' re not really ' magic ' , they just hap... |
async def skiplast ( source , n ) :
"""Forward an asynchronous sequence , skipping the last ` ` n ` ` elements .
If ` ` n ` ` is negative , no elements are skipped .
Note : it is required to reach the ` ` n + 1 ` ` th element of the source
before the first element is generated .""" | queue = collections . deque ( maxlen = n if n > 0 else 0 )
async with streamcontext ( source ) as streamer :
async for item in streamer :
if n <= 0 :
yield item
continue
if len ( queue ) == n :
yield queue [ 0 ]
queue . append ( item ) |
def parse_tx_op_return ( tx ) :
"""Given a transaction , locate its OP _ RETURN and parse
out its opcode and payload .
Return ( opcode , payload ) on success
Return ( None , None ) if there is no OP _ RETURN , or if it ' s not a blockchain ID operation .""" | # find OP _ RETURN output
op_return = None
outputs = tx [ 'vout' ]
for out in outputs :
script_key = out [ 'scriptPubKey' ] [ 'hex' ]
if int ( script_key [ 0 : 2 ] , 16 ) == virtualchain . OPCODE_VALUES [ 'OP_RETURN' ] :
op_return = script_key . decode ( 'hex' )
break
if op_return is None :
... |
def get_filters ( self , filter_id = None , params = None ) :
""": arg filter _ id : The ID of the filter to fetch
: arg from _ : skips a number of filters
: arg size : specifies a max number of filters to get""" | return self . transport . perform_request ( "GET" , _make_path ( "_ml" , "filters" , filter_id ) , params = params ) |
async def query ( self , stmt , * args ) :
"""Query for a list of results .
Typical usage : :
results = await self . query ( . . . )
Or : :
for row in await self . query ( . . . )""" | with ( await self . application . db . cursor ( ) ) as cur :
await cur . execute ( stmt , args )
return [ self . row_to_obj ( row , cur ) for row in await cur . fetchall ( ) ] |
def repeat_masker_alignment_iterator ( fn , index_friendly = True , verbose = False ) :
"""Iterator for repeat masker alignment files ; yields multiple alignment objects .
Iterate over a file / stream of full repeat alignments in the repeatmasker
format . Briefly , this format is as follows : each record ( alig... | # step 1 - - build our iterator for the stream . .
try :
fh = open ( fn )
except ( TypeError ) :
fh = fn
iterable = fh
if index_friendly :
iterable = iter ( fh . readline , '' )
# build progress indicator , if we want one and we ' re able to
if verbose :
try :
m_fn = ": " + fh . name
except ... |
def all_in ( self , name ) -> iter :
"""Yield all ( power ) nodes contained in given ( power ) node""" | for elem in self . inclusions [ name ] :
yield elem
yield from self . all_in ( elem ) |
def c2l ( c ) :
"char [ 4 ] to unsigned long" | l = U32 ( c [ 0 ] )
l = l | ( U32 ( c [ 1 ] ) << 8 )
l = l | ( U32 ( c [ 2 ] ) << 16 )
l = l | ( U32 ( c [ 3 ] ) << 24 )
return l |
def main ( ) :
"""NAME
squish . py
DESCRIPTION
takes dec / inc data and " squishes " with specified flattening factor , flt
using formula tan ( Io ) = flt * tan ( If )
INPUT
declination inclination
OUTPUT
" squished " declincation inclination
SYNTAX
squish . py [ command line options ] [ < filen... | ofile = ""
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-F' in sys . argv :
ind = sys . argv . index ( '-F' )
ofile = sys . argv [ ind + 1 ]
out = open ( ofile , 'w' )
if '-flt' in sys . argv :
ind = sys . argv . index ( '-flt' )
flt = float ( sys . argv [ ind + 1 ] )
... |
def decode ( obj ) :
"""Decoder for deserializing numpy data types .""" | typ = obj . get ( 'typ' )
if typ is None :
return obj
elif typ == 'timestamp' :
freq = obj [ 'freq' ] if 'freq' in obj else obj [ 'offset' ]
return Timestamp ( obj [ 'value' ] , tz = obj [ 'tz' ] , freq = freq )
elif typ == 'nat' :
return NaT
elif typ == 'period' :
return Period ( ordinal = obj [ 'o... |
def get_attributes ( self ) :
"""Gets the Attributes from the AttributeStatement element .
EncryptedAttributes are not supported""" | attributes = { }
attribute_nodes = self . __query_assertion ( '/saml:AttributeStatement/saml:Attribute' )
for attribute_node in attribute_nodes :
attr_name = attribute_node . get ( 'Name' )
if attr_name in attributes . keys ( ) :
raise OneLogin_Saml2_ValidationError ( 'Found an Attribute element with du... |
def get_pt ( self , viewer , points , pt , canvas_radius = None ) :
"""Takes an array of points ` points ` and a target point ` pt ` .
Returns the first index of the point that is within the
radius of the target point . If none of the points are within
the radius , returns None .""" | if canvas_radius is None :
canvas_radius = self . cap_radius
if hasattr ( self , 'rot_deg' ) : # rotate point back to cartesian alignment for test
ctr_pt = self . get_center_pt ( )
pt = trcalc . rotate_coord ( pt , [ - self . rot_deg ] , ctr_pt )
res = self . within_radius ( viewer , points , pt , canvas_ra... |
async def get_model ( self , model ) :
"""Get a model by name or UUID .
: param str model : Model name or UUID
: returns Model : Connected Model instance .""" | uuids = await self . model_uuids ( )
if model in uuids :
uuid = uuids [ model ]
else :
uuid = model
from juju . model import Model
model = Model ( )
kwargs = self . connection ( ) . connect_params ( )
kwargs [ 'uuid' ] = uuid
await model . _connect_direct ( ** kwargs )
return model |
def patch_namespaced_pod_template ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ pod _ template # noqa : E501
partially update the specified PodTemplate # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_namespaced_pod_template_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_pod_template_with_http_info ( name , namespace , body , ** kwargs )
# no... |
def plot_connectivity_topos ( layout = 'diagonal' , topo = None , topomaps = None , fig = None ) :
"""Place topo plots in a figure suitable for connectivity visualization .
. . note : : Parameter ` topo ` is modified by the function by calling : func : ` ~ eegtopo . topoplot . Topoplot . set _ map ` .
Parameter... | m = len ( topomaps )
if fig is None :
fig = new_figure ( )
if layout == 'diagonal' :
for i in range ( m ) :
ax = fig . add_subplot ( m , m , i * ( 1 + m ) + 1 )
plot_topo ( ax , topo , topomaps [ i ] )
ax . set_yticks ( [ ] )
ax . set_xticks ( [ ] )
ax . set_frame_on ( Fa... |
def extract_images ( self , imageQuery , imageCount = 100 , destinationFolder = './' , threadCount = 4 ) :
"""Searches across Google Image Search with the specified image query and
downloads the specified count of images
Arguments :
imageQuery { [ str ] } - - [ Image Search Query ]
Keyword Arguments :
ima... | # Initialize the chrome driver
self . _initialize_chrome_driver ( )
# Initialize the image download parameters
self . _imageQuery = imageQuery
self . _imageCount = imageCount
self . _destinationFolder = destinationFolder
self . _threadCount = threadCount
self . _get_image_urls ( )
self . _create_storage_folder ( )
self... |
def _create_postgresql_pygresql ( self , ** kwargs ) :
""": rtype : Engine""" | return self . _ce ( self . _ccs ( self . DialectAndDriver . psql_pygresql ) , ** kwargs ) |
def prototype_adjacency ( self , n_block_features , alpha ) :
"""Build a new graph .
Doc for " . create ( n _ features , alpha ) "
Parameters
n _ features : int
alpha : float ( 0,1)
The complexity / sparsity factor .
This is ( 1 - alpha _ 0 ) in sklearn . datasets . make _ sparse _ spd _ matrix
where ... | return make_sparse_spd_matrix ( n_block_features , alpha = np . abs ( 1.0 - alpha ) , smallest_coef = self . spd_low , largest_coef = self . spd_high , random_state = self . prng , ) |
def shelter_get ( self , ** kwargs ) :
"""shelter . get wrapper . Given a shelter ID , retrieve its details in
dict form .
: rtype : dict
: returns : The shelter ' s details .""" | root = self . _do_api_call ( "shelter.get" , kwargs )
shelter = root . find ( "shelter" )
for field in shelter :
record = { }
for field in shelter :
record [ field . tag ] = field . text
return record |
def publish_predictions_to_core ( self ) :
"""publish _ predictions _ to _ core""" | status = FAILED
msg = "not started"
try :
msg = "generating request"
log . info ( msg )
# noqa https : / / stackoverflow . com / questions / 29815129 / pandas - dataframe - to - list - of - dictionaries
publish_req = generate_ai_request ( predict_rows = self . df . fillna ( ANTINEX_MISSING_VALUE ) . to_... |
def recover ( self , state ) :
"recompute the actual value , then compare it against the truth" | newval = self . f . recover ( state )
return self . errtype ( self . value , newval ) |
def _reverse ( self ) :
"""Reverse all bits in - place .""" | # Reverse the contents of each byte
n = [ BYTE_REVERSAL_DICT [ b ] for b in self . _datastore . rawbytes ]
# Then reverse the order of the bytes
n . reverse ( )
# The new offset is the number of bits that were unused at the end .
newoffset = 8 - ( self . _offset + self . len ) % 8
if newoffset == 8 :
newoffset = 0
... |
def logger_usage ( client , to_delete ) :
"""Logger usage .""" | LOG_NAME = "logger_usage_%d" % ( _millis ( ) )
# [ START logger _ create ]
logger = client . logger ( LOG_NAME )
# [ END logger _ create ]
to_delete . append ( logger )
# [ START logger _ log _ text ]
logger . log_text ( "A simple entry" )
# API call
# [ END logger _ log _ text ]
# [ START logger _ log _ struct ]
logge... |
def circle_plot ( netIn , ax , nodelabels = None , linestyle = 'k-' , nodesize = 1000 , cmap = 'Set2' ) :
r'''Function draws " circle plot " and exports axis handles
Parameters
netIn : temporal network input ( graphlet or contact )
ax : matplotlib ax handles .
nodelabels : list
nodes labels . List of stri... | # Get input type ( C or G )
inputType = checkInput ( netIn , conMat = 1 )
if nodelabels is None :
nodelabels = [ ]
# Convert C representation to G
if inputType == 'M' :
shape = np . shape ( netIn )
edg = np . where ( np . abs ( netIn ) > 0 )
contacts = [ tuple ( [ edg [ 0 ] [ i ] , edg [ 1 ] [ i ] ] ) f... |
def _get_dtype ( arr_or_dtype ) :
"""Get the dtype instance associated with an array
or dtype object .
Parameters
arr _ or _ dtype : array - like
The array - like or dtype object whose dtype we want to extract .
Returns
obj _ dtype : The extract dtype instance from the
passed in array or dtype object ... | if arr_or_dtype is None :
raise TypeError ( "Cannot deduce dtype from null object" )
# fastpath
elif isinstance ( arr_or_dtype , np . dtype ) :
return arr_or_dtype
elif isinstance ( arr_or_dtype , type ) :
return np . dtype ( arr_or_dtype )
# if we have an array - like
elif hasattr ( arr_or_dtype , 'dtype' ... |
def parse_args_and_kwargs ( self , cmdline ) :
'''cmdline : list
returns tuple of : args ( list ) , kwargs ( dict )''' | # Parse args and kwargs
args = [ ]
kwargs = { }
if len ( cmdline ) > 1 :
for item in cmdline [ 1 : ] :
if '=' in item :
( key , value ) = item . split ( '=' , 1 )
kwargs [ key ] = value
else :
args . append ( item )
return ( args , kwargs ) |
def _get_page_elements ( self ) :
"""Return page elements and page objects of this page object
: returns : list of page elements and page objects""" | page_elements = [ ]
for attribute , value in list ( self . __dict__ . items ( ) ) + list ( self . __class__ . __dict__ . items ( ) ) :
if attribute != 'parent' and isinstance ( value , CommonObject ) :
page_elements . append ( value )
return page_elements |
async def incoming ( self ) :
"""Returns the next incoming message .""" | msg = await self . _queue . get ( )
self . _queue . task_done ( )
return msg |
def create_colspec ( self , columns , overflow_default = None ) :
"""Produce a full format columns spec dictionary . The overrides spec
can be a partial columns spec as described in the _ _ init _ _ method ' s
depiction of the . columns attribute .""" | spec = [ { "width" : None , "minwidth" : self . column_minwidth , "padding" : self . column_padding , "align" : self . column_align , "overflow" : self . overflow or overflow_default } for x in range ( columns ) ]
if self . columns_def :
for dst , src in zip ( spec , self . columns_def ) :
if hasattr ( src ... |
def info ( self , url , limit = None ) :
"""GETs " info " about ` ` url ` ` . See https : / / github . com / reddit / reddit / wiki / API % 3A - info . json .
URL : ` ` http : / / www . reddit . com / api / info / ? url = < url > ` `
: param url : url
: param limit : max number of links to get""" | return self . _limit_get ( 'api' , 'info' , params = dict ( url = url ) , limit = limit ) |
def get_visible_scopes ( self ) :
"""Get list of non - internal scopes for token .
: returns : A list of scopes .""" | return [ k for k , s in current_oauth2server . scope_choices ( ) if k in self . scopes ] |
def expand ( self , name = None , target = None , ** kwargs ) :
""": param string name : The name for this alias .
: param string target : The address of the destination target .""" | if name is None :
raise TargetDefinitionException ( '{}:?' . format ( self . _parse_context . rel_path , name ) , 'The alias() must have a name!' )
if target is None :
raise TargetDefinitionException ( '{}:{}' . format ( self . _parse_context . rel_path , name ) , 'The alias() must have a "target" parameter.' )... |
def translate_request ( request ) :
"""This function takes the arguments passed to the request handler and
uses them to generate a WSGI compatible environ dictionary .""" | message = request . _message
payload = request . _payload
uri_parts = urlsplit ( message . path )
environ = { 'wsgi.input' : payload , 'wsgi.errors' : sys . stderr , 'wsgi.version' : ( 1 , 0 ) , 'wsgi.async' : True , 'wsgi.multithread' : False , 'wsgi.multiprocess' : False , 'wsgi.run_once' : False , 'SERVER_SOFTWARE' ... |
def make_alias ( self , entry ) :
"""Make this variable an alias of another one""" | entry . add_alias ( self )
self . alias = entry
self . scope = entry . scope
# Local aliases can be " global " ( static )
self . byref = entry . byref
self . offset = entry . offset
self . addr = entry . addr |
def match_url ( self , path , method = 'GET' ) :
"""Find a callback bound to a path and a specific HTTP method .
Return ( callback , param ) tuple or ( None , { } ) .
method : HEAD falls back to GET . HEAD and GET fall back to ALL .""" | path = path . strip ( ) . lstrip ( '/' )
handler , param = self . routes . match ( method + ';' + path )
if handler :
return handler , param
if method == 'HEAD' :
handler , param = self . routes . match ( 'GET;' + path )
if handler :
return handler , param
handler , param = self . routes . match ( '... |
def to_zarr ( dataset , store = None , mode = 'w-' , synchronizer = None , group = None , encoding = None , compute = True , consolidated = False ) :
"""This function creates an appropriate datastore for writing a dataset to
a zarr ztore
See ` Dataset . to _ zarr ` for full API docs .""" | if isinstance ( store , Path ) :
store = str ( store )
if encoding is None :
encoding = { }
# validate Dataset keys , DataArray names , and attr keys / values
_validate_dataset_names ( dataset )
_validate_attrs ( dataset )
zstore = backends . ZarrStore . open_group ( store = store , mode = mode , synchronizer =... |
def _print_refs ( self , fobj , refs , total , level = 1 , minsize = 0 , minpct = 0.1 ) :
"""Print individual referents recursively .""" | lrefs = list ( refs )
lrefs . sort ( key = lambda x : x . size )
lrefs . reverse ( )
if level == 1 :
fobj . write ( '<table>\n' )
for ref in lrefs :
if ref . size > minsize and ( ref . size * 100.0 / total ) > minpct :
data = dict ( level = level , name = trunc ( str ( ref . name ) , 128 ) , size = pp (... |
def compute_empirical ( cls , X ) :
"""Compute empirical distribution .""" | z_left = [ ]
z_right = [ ]
L = [ ]
R = [ ]
U , V = cls . split_matrix ( X )
N = len ( U )
base = np . linspace ( EPSILON , 1.0 - EPSILON , COMPUTE_EMPIRICAL_STEPS )
# See https : / / github . com / DAI - Lab / Copulas / issues / 45
for k in range ( COMPUTE_EMPIRICAL_STEPS ) :
left = sum ( np . logical_and ( U <= ba... |
def pt_change_axis ( pt = ( 0.0 , 0.0 ) , flip = [ False , False ] , offset = [ 0.0 , 0.0 ] ) :
'''Return given point with axes flipped and offset , converting points between cartesian axis layouts .
For example , SVG Y - axis increases top to bottom but DXF is bottom to top .''' | assert isinstance ( pt , tuple )
l_pt = len ( pt )
assert l_pt > 1
for i in pt :
assert isinstance ( i , float )
assert isinstance ( flip , list )
l_fl = len ( flip )
assert l_fl == l_pt
for i in flip :
assert isinstance ( i , bool )
assert isinstance ( offset , list )
l_of = len ( offset )
assert l_of == l_pt
... |
def from_file ( cls , vert , frag , ** kwargs ) :
"""Reads the shader programs , given the vert and frag filenames
Arguments :
- vert ( str ) : The filename of the vertex shader program ( ex : ' vertshader . vert ' )
- frag ( str ) : The filename of the fragment shader program ( ex : ' fragshader . frag ' )
... | vert_program = open ( vert ) . read ( )
frag_program = open ( frag ) . read ( )
return cls ( vert = vert_program , frag = frag_program , ** kwargs ) |
def correct_rytov_output ( radius , sphere_index , medium_index , radius_sampling ) :
r"""Error - correction of refractive index and radius for Rytov
This method corrects the fitting results for ` radius `
: math : ` r _ \ text { Ryt } ` and ` sphere _ index ` : math : ` n _ \ text { Ryt } `
obtained using : ... | params = get_params ( radius_sampling )
x = sphere_index / medium_index - 1
radius_sc = radius * ( params [ "ra" ] * x ** 2 + params [ "rb" ] * x + params [ "rc" ] )
sphere_index_sc = sphere_index + medium_index * ( params [ "na" ] * x ** 2 + params [ "nb" ] * x )
return radius_sc , sphere_index_sc |
def paintEvent ( self , event ) :
"""Pains the messages and the visible area on the panel .
: param event : paint event infos""" | if self . isVisible ( ) : # fill background
self . _background_brush = QtGui . QBrush ( self . editor . background )
painter = QtGui . QPainter ( self )
painter . fillRect ( event . rect ( ) , self . _background_brush )
self . _draw_messages ( painter )
self . _draw_visible_area ( painter ) |
def make_request ( ins , method , url , stripe_account = None , params = None , headers = None , ** kwargs ) :
"""Return a deferred or handle error .
For overriding in various classes .""" | if txstripe . api_key is None :
raise error . AuthenticationError ( 'No API key provided. (HINT: set your API key using ' '"stripe.api_key = <API-KEY>"). You can generate API keys ' 'from the Stripe web interface. See https://stripe.com/api ' 'for details, or email support@stripe.com if you have any ' 'questions.'... |
def _fill_scope_refs ( name , scope ) :
"""Put referenced name in ' ref ' dictionary of a scope .
Walks up the scope tree and adds the name to ' ref ' of every scope
up in the tree until a scope that defines referenced name is reached .""" | symbol = scope . resolve ( name )
if symbol is None :
return
orig_scope = symbol . scope
scope . refs [ name ] = orig_scope
while scope is not orig_scope :
scope = scope . get_enclosing_scope ( )
scope . refs [ name ] = orig_scope |
def _set_on_startup ( self , v , load = False ) :
"""Setter method for on _ startup , mapped from YANG variable / rbridge _ id / router / ospf / max _ metric / router _ lsa / on _ startup ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ on _ startup is cons... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = on_startup . on_startup , is_container = 'container' , presence = False , yang_name = "on-startup" , rest_name = "on-startup" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa... |
def gen_enum_completions ( self , arg_name ) :
"""generates dynamic enumeration completions""" | try : # if enum completion
for choice in self . cmdtab [ self . current_command ] . arguments [ arg_name ] . choices :
if self . validate_completion ( choice ) :
yield Completion ( choice , - len ( self . unfinished_word ) )
except TypeError : # there is no choices option
pass |
def convert ( model , feature_names , target ) :
"""Convert a boosted tree model to protobuf format .
Parameters
decision _ tree : GradientBoostingClassifier
A trained scikit - learn tree model .
feature _ names : [ str ]
Name of the input columns .
target : str
Name of the output column .
Returns
... | if not ( _HAS_SKLEARN ) :
raise RuntimeError ( 'scikit-learn not found. scikit-learn conversion API is disabled.' )
_sklearn_util . check_expected_type ( model , _ensemble . GradientBoostingClassifier )
def is_gbr_model ( m ) :
if len ( m . estimators_ ) == 0 :
return False
if hasattr ( m , 'estimat... |
def _sqlalchemy_on_connection_close ( self ) :
"""Rollsback and closes the active session , since the client disconnected before the request
could be completed .""" | if hasattr ( self , "_db_conns" ) :
try :
for db_conn in self . _db_conns . values ( ) :
db_conn . rollback ( )
except :
tornado . log . app_log . warning ( "Error occurred during database transaction cleanup: %s" , str ( sys . exc_info ( ) [ 0 ] ) )
raise
finally :
... |
def _findlinestarts ( code ) :
"""Find the offsets in a byte code which are start of lines in the source
Generate pairs offset , lineno as described in Python / compile . c
This is a modified version of dis . findlinestarts , which allows multiplelinestarts
with the same line number""" | lineno = code . co_firstlineno
addr = 0
for byte_incr , line_incr in zip ( code . co_lnotab [ 0 : : 2 ] , code . co_lnotab [ 1 : : 2 ] ) :
if byte_incr :
yield addr , lineno
addr += byte_incr
lineno += line_incr
yield addr , lineno |
def codeblock ( self , text , lang = "" ) :
"""* convert plain - text to MMD fenced codeblock *
* * Key Arguments : * *
- ` ` text ` ` - - the text to convert to MMD fenced codeblock
- ` ` lang ` ` - - the code language for syntax highlighting . Default * ' ' *
* * Return : * *
- ` ` text ` ` - - the MMD ... | reRemoveNewline = re . compile ( r'^(\s*\n)?([^\n].*?)\s*$' , re . S )
m = reRemoveNewline . match ( text )
text = m . group ( 2 )
return "\n```%(lang)s\n%(text)s\n```\n" % locals ( ) |
def get_course_id ( self , course_uuid ) :
"""Get course id based on uuid .
Args :
uuid ( str ) : course uuid , i . e . / project / mitxdemosite
Raises :
PyLmodUnexpectedData : No course data was returned .
requests . RequestException : Exception connection error
Returns :
int : numeric course id""" | course_data = self . get ( 'courseguide/course?uuid={uuid}' . format ( uuid = course_uuid or self . course_id ) , params = None )
try :
return course_data [ 'response' ] [ 'docs' ] [ 0 ] [ 'id' ]
except KeyError :
failure_message = ( 'KeyError in get_course_id - ' 'got {0}' . format ( course_data ) )
log . ... |
def cli ( env ) :
"""List Subject IDs for ticket creation .""" | ticket_mgr = SoftLayer . TicketManager ( env . client )
table = formatting . Table ( [ 'id' , 'subject' ] )
for subject in ticket_mgr . list_subjects ( ) :
table . add_row ( [ subject [ 'id' ] , subject [ 'name' ] ] )
env . fout ( table ) |
def create_on_task ( self , task , params = { } , ** options ) :
"""Adds a comment to a task . The comment will be authored by the
currently authenticated user , and timestamped when the server receives
the request .
Returns the full record for the new story added to the task .
Parameters
task : { Id } Gl... | path = "/tasks/%s/stories" % ( task )
return self . client . post ( path , params , ** options ) |
def fresh ( req_headers : HEADER_TYPE , res_headers : HEADER_TYPE ) -> bool :
"""根据 req _ headers , res _ headers 判断改消息是否为 304""" | modified_since = cast ( Optional [ str ] , req_headers . get ( 'if-modified-since' ) , )
none_match = cast ( Optional [ str ] , req_headers . get ( 'if-none-match' ) , )
if not modified_since and not none_match :
return False
cache_control = req_headers . get ( 'cache-control' )
if cache_control is not None :
i... |
def __ensure_provisioning_writes ( table_name , table_key , gsi_name , gsi_key , num_consec_write_checks ) :
"""Ensure that provisioning of writes is correct
: type table _ name : str
: param table _ name : Name of the DynamoDB table
: type table _ key : str
: param table _ key : Table configuration option ... | if not get_gsi_option ( table_key , gsi_key , 'enable_writes_autoscaling' ) :
logger . info ( '{0} - GSI: {1} - ' 'Autoscaling of writes has been disabled' . format ( table_name , gsi_name ) )
return False , dynamodb . get_provisioned_gsi_write_units ( table_name , gsi_name ) , 0
update_needed = False
try :
... |
def register_sig ( self , builder_name : str , sig : list , docstring : str , cachable : bool = True , attempts = 1 ) :
"""Register a builder signature & docstring for ` builder _ name ` .
The input for the builder signature is a list of " sig - spec " s
representing the builder function arguments .
Each sig ... | if self . sig is not None :
raise KeyError ( '{} already registered a signature!' . format ( builder_name ) )
self . sig = OrderedDict ( name = ArgSpec ( PropType . TargetName , Empty ) )
self . docstring = docstring
kwargs_section = False
for arg_spec in listify ( sig ) :
arg_name , sig_spec = evaluate_arg_spe... |
def users_list ( self , permission_set = None , role = None , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / users # list - users" | api_path = "/api/v2/users.json"
api_query = { }
if "query" in kwargs . keys ( ) :
api_query . update ( kwargs [ "query" ] )
del kwargs [ "query" ]
if permission_set :
api_query . update ( { "permission_set" : permission_set , } )
if role :
api_query . update ( { "role" : role , } )
return self . call ( ... |
def process_settings ( self , settings ) :
"""A lazy way of feeding Dharma with configuration settings .""" | logging . debug ( "Using configuration from: %s" , settings . name )
exec ( compile ( settings . read ( ) , settings . name , 'exec' ) , globals ( ) , locals ( ) ) |
def as_dict ( self ) :
"""Serializes the object necessary data in a dictionary .
: returns : Serialized data in a dictionary .
: rtype : dict""" | result_dict = super ( Group , self ) . as_dict ( )
statuses = list ( )
version = None
titles = list ( )
descriptions = list ( )
platforms = list ( )
groups = list ( )
rules = list ( )
for child in self . children :
if isinstance ( child , Version ) :
version = child . as_dict ( )
elif isinstance ( child... |
def estimate ( self , X , ** params ) :
"""Estimates the model given the data X
Parameters
X : object
A reference to the data from which the model will be estimated
params : dict
New estimation parameter values . The parameters must that have been
announced in the _ _ init _ _ method of this estimator .... | # set params
if params :
self . set_params ( ** params )
self . _model = self . _estimate ( X )
# ensure _ estimate returned something
assert self . _model is not None
self . _estimated = True
return self |
def load_mozlz4 ( self , path ) :
"""Load a Mozilla LZ4 file from the user profile .
Mozilla LZ4 is regular LZ4 with a custom string prefix .""" | with open ( self . profile_path ( path , must_exist = True ) , 'rb' ) as f :
if f . read ( 8 ) != b'mozLz40\0' :
raise NotMozLz4Error ( 'Not Mozilla LZ4 format.' )
data = lz4 . block . decompress ( f . read ( ) )
return data |
def parse_arguments ( argv ) :
"""Parse command line arguments .
Args :
argv : list of command line arguments , includeing programe name .
Returns :
An argparse Namespace object .
Raises :
ValueError : for bad parameters""" | parser = argparse . ArgumentParser ( description = 'Runs Preprocessing on structured data.' )
parser . add_argument ( '--output-dir' , type = str , required = True , help = 'Google Cloud Storage which to place outputs.' )
parser . add_argument ( '--schema-file' , type = str , required = False , help = ( 'BigQuery json ... |
def parse_line ( self , line , lineno ) :
"""Parse a single line of the log""" | match = self . RE_TINDERBOXPRINT . match ( line ) if line else None
if match :
line = match . group ( 'line' )
for regexp_item in self . TINDERBOX_REGEXP_TUPLE :
match = regexp_item [ 're' ] . match ( line )
if match :
artifact = match . groupdict ( )
# handle duplicate f... |
def delete_notes ( self , noteids ) :
"""Delete a note or notes
: param noteids : The noteids to delete""" | if self . standard_grant_type is not "authorization_code" :
raise DeviantartError ( "Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint." )
response = self . _req ( '/notes/delete' , post_data = { 'noteids[]' : noteids } )
return response |
def delete_project ( self , id ) :
"""Delete a project from the Gitlab server
Gitlab currently returns a Boolean True if the deleted and as such we return an
empty Dictionary
: param id : The ID of the project or NAMESPACE / PROJECT _ NAME
: return : Dictionary
: raise : HttpError : If invalid response re... | url = '/projects/{id}' . format ( id = id )
response = self . delete ( url )
if response is True :
return { }
else :
return response |
def findNestedClassLike ( self , lst ) :
'''Recursive helper function for finding nested classes and structs . If this node
is a class or struct , it is appended to ` ` lst ` ` . Each node also calls each of
its child ` ` findNestedClassLike ` ` with the same list .
: Parameters :
` ` lst ` ` ( list )
The... | if self . kind == "class" or self . kind == "struct" :
lst . append ( self )
for c in self . children :
c . findNestedClassLike ( lst ) |
def rule_match ( component , cmd ) :
'''see if one rule component matches''' | if component == cmd :
return True
expanded = rule_expand ( component , cmd )
if cmd in expanded :
return True
return False |
def _init_cfg_interfaces ( self , cb , intf_list = None , all_intf = True ) :
"""Configure the interfaces during init time .""" | if not all_intf :
self . intf_list = intf_list
else :
self . intf_list = sys_utils . get_all_run_phy_intf ( )
self . cb = cb
self . intf_attr = { }
self . cfg_lldp_interface_list ( self . intf_list ) |
def get_enabled ( ) :
'''Return a list of service that are enabled on boot
CLI Example :
. . code - block : : bash
salt ' * ' service . get _ enabled''' | prefix = '/etc/rc[S{0}].d/S' . format ( _get_runlevel ( ) )
ret = set ( )
lines = glob . glob ( '{0}*' . format ( prefix ) )
for line in lines :
ret . add ( re . split ( prefix + r'\d+' , line ) [ 1 ] )
return sorted ( ret ) |
def mode ( self , values , weights = None ) :
"""compute the mode within each group .
Parameters
values : array _ like , [ keys , . . . ]
values to compute the mode of per group
weights : array _ like , [ keys ] , float , optional
optional weight associated with each entry in values
Returns
unique : n... | if weights is None :
unique , weights = npi . count ( ( self . index . sorted_group_rank_per_key , values ) )
else :
unique , weights = npi . group_by ( ( self . index . sorted_group_rank_per_key , values ) ) . sum ( weights )
x , bin = npi . group_by ( unique [ 0 ] ) . argmax ( weights )
return x , unique [ 1 ... |
async def createcsrf ( self , csrfarg = '_csrf' ) :
"""Create a anti - CSRF token in the session""" | await self . sessionstart ( )
if not csrfarg in self . session . vars :
self . session . vars [ csrfarg ] = uuid . uuid4 ( ) . hex |
def _offset_for ( self , param ) :
"""Return the offset of the param inside this parameterized object .
This does not need to account for shaped parameters , as it
basically just sums up the parameter sizes which come before param .""" | if param . has_parent ( ) :
p = param . _parent_ . _get_original ( param )
if p in self . parameters :
return reduce ( lambda a , b : a + b . size , self . parameters [ : p . _parent_index_ ] , 0 )
return self . _offset_for ( param . _parent_ ) + param . _parent_ . _offset_for ( param )
return 0 |
def track_dependency ( self , name , data , type = None , target = None , duration = None , success = None , result_code = None , properties = None , measurements = None , dependency_id = None ) :
"""Sends a single dependency telemetry that was captured for the application .
Args :
name ( str ) . the name of th... | dependency_data = channel . contracts . RemoteDependencyData ( )
dependency_data . id = dependency_id or str ( uuid . uuid4 ( ) )
dependency_data . name = name
dependency_data . data = data
dependency_data . type = type
dependency_data . target = target
dependency_data . duration = self . __ms_to_duration ( duration )
... |
def _delete ( self , pos , idx ) :
"""Delete the item at the given ( pos , idx ) .
Combines lists that are less than half the load level .
Updates the index when the sublist length is more than half the load
level . This requires decrementing the nodes in a traversal from the leaf
node to the root . For an ... | _maxes , _lists , _keys , _index = self . _maxes , self . _lists , self . _keys , self . _index
keys_pos = _keys [ pos ]
lists_pos = _lists [ pos ]
del keys_pos [ idx ]
del lists_pos [ idx ]
self . _len -= 1
len_keys_pos = len ( keys_pos )
if len_keys_pos > self . _half :
_maxes [ pos ] = keys_pos [ - 1 ]
if le... |
def diffheaders ( t1 , t2 ) :
"""Return the difference between the headers of the two tables as a pair of
sets . E . g . : :
> > > import petl as etl
> > > table1 = [ [ ' foo ' , ' bar ' , ' baz ' ] ,
. . . [ ' a ' , 1 , . 3 ] ]
> > > table2 = [ [ ' baz ' , ' bar ' , ' quux ' ] ,
. . . [ ' a ' , 1 , . 3... | t1h = set ( header ( t1 ) )
t2h = set ( header ( t2 ) )
return t2h - t1h , t1h - t2h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.