signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def next_lookup ( self , symbol ) :
"""Returns the next TerminalSymbols produced by the input symbol within this grammar definition""" | result = [ ]
if symbol == self . initialsymbol :
result . append ( EndSymbol ( ) )
for production in self . productions :
if symbol in production . rightside :
nextindex = production . rightside . index ( symbol ) + 1
while nextindex < len ( production . rightside ) :
nextsymbol = pr... |
def __parse_namespace ( self ) :
"""Parse the namespace from various sources""" | if self . manifest . has_option ( 'config' , 'namespace' ) :
return self . manifest . get ( 'config' , 'namespace' )
elif self . manifest . has_option ( 'config' , 'source' ) :
return NAMESPACE_REGEX . search ( self . manifest . get ( 'config' , 'source' ) ) . groups ( ) [ 0 ]
else :
logger . warn ( 'Could ... |
def set_width ( self , width ) :
"""Set Screen Width""" | if width > 0 and width <= self . server . server_info . get ( "screen_width" ) :
self . width = width
self . server . request ( "screen_set %s wid %i" % ( self . ref , self . width ) ) |
def create_one ( self , commit = True ) :
'''Create and return one model instance . If * commit * is ` ` False ` ` the
instance will not be saved and many to many relations will not be
processed .
Subclasses that override ` ` create _ one ` ` can specify arbitrary keyword
arguments . They will be passed thr... | tries = self . tries
instance = self . model ( )
process = instance . _meta . fields
while process and tries > 0 :
for field in process :
self . process_field ( instance , field )
process = self . check_constraints ( instance )
tries -= 1
if tries == 0 :
raise CreateInstanceError ( u'Cannot solv... |
def global_horizontal_radiation ( self , value = 9999.0 ) :
"""Corresponds to IDD Field ` global _ horizontal _ radiation `
Args :
value ( float ) : value for IDD Field ` global _ horizontal _ radiation `
Unit : Wh / m2
value > = 0.0
Missing value : 9999.0
if ` value ` is None it will not be checked aga... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `global_horizontal_radiation`' . format ( value ) )
if value < 0.0 :
raise ValueError ( 'value need to be greater or equal 0.0 ' 'for field `glo... |
def load ( self , label ) :
"""Load obj with give label from hidden state directory""" | objloc = '{0}/{1}' . format ( self . statedir , label )
try :
obj = pickle . load ( open ( objloc , 'r' ) )
except ( KeyError , IndexError , EOFError ) :
obj = open ( objloc , 'r' ) . read ( )
try :
obj = float ( obj )
except ValueError :
pass
except IOError :
obj = None
return obj |
def pip_execute ( * args , ** kwargs ) :
"""Overriden pip _ execute ( ) to stop sys . path being changed .
The act of importing main from the pip module seems to cause add wheels
from the / usr / share / python - wheels which are installed by various tools .
This function ensures that sys . path remains the s... | try :
_path = sys . path
try :
from pip import main as _pip_execute
except ImportError :
apt_update ( )
if six . PY2 :
apt_install ( 'python-pip' )
else :
apt_install ( 'python3-pip' )
from pip import main as _pip_execute
_pip_execute ( * a... |
def int2base36 ( n ) :
"""Convert int base10 to base36.
Back convert : int ( ' < base36 > ' , 36)""" | assert isinstance ( n , ( int , long ) )
c = '0123456789abcdefghijklmnopqrstuvwxyz'
if n < 0 :
return '-' + int2base36 ( - n )
elif n < 36 :
return c [ n ]
b36 = ''
while n != 0 :
n , i = divmod ( n , 36 )
b36 = c [ i ] + b36
return b36 |
def _build_package_finder ( self , options , index_urls ) :
"""Create a package finder appropriate to this install command .
This method is meant to be overridden by subclasses , not
called directly .""" | return PackageFinder ( find_links = options . find_links , index_urls = index_urls , use_mirrors = options . use_mirrors , mirrors = options . mirrors ) |
def add_all_to_env ( env ) :
"""Add builders and construction variables for all supported fortran
dialects .""" | add_fortran_to_env ( env )
add_f77_to_env ( env )
add_f90_to_env ( env )
add_f95_to_env ( env )
add_f03_to_env ( env )
add_f08_to_env ( env ) |
def mean_squared_error ( true , pred ) :
"""L2 distance between tensors true and pred .
Args :
true : the ground truth image .
pred : the predicted image .
Returns :
mean squared error between ground truth and predicted image .""" | result = tf . reduce_sum ( tf . squared_difference ( true , pred ) ) / tf . to_float ( tf . size ( pred ) )
return result |
async def subscribe ( self , topic ) :
"""Subscribe the socket to the specified topic .
: param topic : The topic to subscribe to .""" | if self . socket_type not in { SUB , XSUB } :
raise AssertionError ( "A %s socket cannot subscribe." % self . socket_type . decode ( ) , )
# Do this * * BEFORE * * awaiting so that new connections created during
# the execution below honor the setting .
self . _subscriptions . append ( topic )
tasks = [ asyncio . e... |
def email_quote_txt ( text , indent_txt = '>>' , linebreak_input = "\n" , linebreak_output = "\n" ) :
"""Takes a text and returns it in a typical mail quoted format , e . g . : :
C ' est un lapin , lapin de bois .
> > Quoi ?
Un cadeau .
> > What ?
A present .
> > Oh , un cadeau .
will return : :
> >... | if ( text == "" ) :
return ""
lines = text . split ( linebreak_input )
text = ""
for line in lines :
text += indent_txt + line + linebreak_output
return text |
def get_context ( request , context = None ) :
"""Returns common context data for network topology views .""" | if context is None :
context = { }
network_config = getattr ( settings , 'OPENSTACK_NEUTRON_NETWORK' , { } )
context [ 'launch_instance_allowed' ] = policy . check ( ( ( "compute" , "os_compute_api:servers:create" ) , ) , request )
context [ 'instance_quota_exceeded' ] = _quota_exceeded ( request , 'instances' )
co... |
def check_child_attr_data_types ( self , ds ) :
"""For any variables which contain any of the following attributes :
- valid _ min / valid _ max
- valid _ range
- scale _ factor
- add _ offset
- _ FillValue
the data type of the attribute must match the type of its parent variable as specified in the
N... | ctx = TestCtx ( BaseCheck . MEDIUM , self . section_titles [ '2.5' ] )
special_attrs = { "actual_range" , "actual_min" , "actual_max" , "valid_min" , "valid_max" , "valid_range" , "scale_factor" , "add_offset" , "_FillValue" }
for var_name , var in ds . variables . items ( ) :
for att in special_attrs . intersectio... |
def setter_override ( attribute = None , # type : str
f = DECORATED ) :
"""A decorator to indicate an overridden setter for a given attribute . If the attribute name is None , the function name
will be used as the attribute name . The @ contract will still be dynamically added .
: param attribute : the attribut... | return autoprops_override_decorate ( f , attribute = attribute , is_getter = False ) |
def getAllSensors ( self ) :
"""Retrieve all the user ' s own sensors by iterating over the SensorsGet function
@ return ( list ) - Array of sensors""" | j = 0
sensors = [ ]
parameters = { 'page' : 0 , 'per_page' : 1000 , 'owned' : 1 }
while True :
parameters [ 'page' ] = j
if self . SensorsGet ( parameters ) :
s = json . loads ( self . getResponse ( ) ) [ 'sensors' ]
sensors . extend ( s )
else : # if any of the calls fails , we cannot be ca... |
def sha1sum ( filename ) :
"""Calculates sha1 hash of a file""" | sha1 = hashlib . sha1 ( )
with open ( filename , 'rb' ) as f :
for chunk in iter ( lambda : f . read ( 128 * sha1 . block_size ) , b'' ) :
sha1 . update ( chunk )
return sha1 . hexdigest ( ) |
def read ( self ) :
"""Reads data from the CSV file .""" | companies = [ ]
with open ( self . file ) as f :
reader = unicodecsv . reader ( f )
for line in reader :
if len ( line ) >= 1 :
cnpj = self . format ( line [ 0 ] )
if self . valid ( cnpj ) :
companies . append ( cnpj )
return companies |
def BSearch ( a , x , lo = 0 , hi = None ) :
"""Returns index of x in a , or - 1 if x not in a .
Arguments :
a - - ordered numeric sequence
x - - element to search within a
lo - - lowest index to consider in search *
hi - - highest index to consider in search *
* bisect . bisect _ left capability that w... | if len ( a ) == 0 :
return - 1
hi = hi if hi is not None else len ( a )
pos = bisect_left ( a , x , lo , hi )
return pos if pos != hi and a [ pos ] == x else - 1 |
def cash ( self ) :
"""[ float ] 可用资金""" | return sum ( account . cash for account in six . itervalues ( self . _accounts ) ) |
def updateD_H ( self , x ) :
"""Compute Hessian for update of D
See [ 2 ] for derivation of Hessian""" | self . precompute ( x )
H = zeros ( ( len ( x ) , len ( x ) ) )
Ai = zeros ( self . A . shape [ 0 ] )
Aj = zeros ( Ai . shape )
for i in range ( len ( x ) ) :
Ai = self . A [ : , i ]
ti = dot ( self . AD , outer ( self . R [ : , i ] , Ai ) ) + dot ( outer ( Ai , self . R [ i , : ] ) , self . ADt )
for j in ... |
def _json_default_encoder ( func ) :
"""Monkey - Patch the core json encoder library .
This isn ' t as bad as it sounds .
We override the default method so that if an object
falls through and can ' t be encoded normally , we see if it is
a Future object and return the result to be encoded .
I set a specia... | @ wraps ( func )
def inner ( self , o ) :
try :
return o . _redpipe_struct_as_dict
# noqa
except AttributeError :
pass
return func ( self , o )
return inner |
def findwithin ( data ) :
"""Returns an integer representing a binary vector , where 1 = within -
subject factor , 0 = between . Input equals the entire data 2D list ( i . e . ,
column 0 = random factor , column - 1 = measured values ( those two are skipped ) .
Note : input data is in | Stat format . . . a li... | numfact = len ( data [ 0 ] ) - 1
withinvec = 0
for col in range ( 1 , numfact ) :
examplelevel = pstat . unique ( pstat . colex ( data , col ) ) [ 0 ]
rows = pstat . linexand ( data , col , examplelevel )
# get 1 level of this factor
factsubjs = pstat . unique ( pstat . colex ( rows , 0 ) )
allsubjs... |
async def get_encryption_aes_key ( self ) -> Tuple [ bytes , Dict [ str , str ] , str ] :
"""Get encryption key to encrypt an S3 object
: return : Raw AES key bytes , Stringified JSON x - amz - matdesc , Base64 encoded x - amz - key""" | random_bytes = os . urandom ( 32 )
padder = PKCS7 ( AES . block_size ) . padder ( )
padded_result = await self . _loop . run_in_executor ( None , lambda : ( padder . update ( random_bytes ) + padder . finalize ( ) ) )
aesecb = self . _cipher . encryptor ( )
encrypted_result = await self . _loop . run_in_executor ( None... |
def create ( width , height , padding = 0 , padding_mode = 'constant' , mode = 'x' , tags = None ) :
"""Vel factory function""" | return RandomCrop ( size = ( width , height ) , padding = padding , padding_mode = padding_mode , mode = mode , tags = tags ) |
def _serialize ( self , array_parent , # type : ET . Element
value , # type : List
state # type : _ ProcessorState
) : # type : ( . . . ) - > None
"""Serialize the array value and add it to the array parent element .""" | if not value : # Nothing to do . Avoid attempting to iterate over a possibly
# None value .
return
for i , item_value in enumerate ( value ) :
state . push_location ( self . _item_processor . element_path , i )
item_element = self . _item_processor . serialize ( item_value , state )
array_parent . appen... |
def create_configuration ( self , node , ports ) :
"""Create RAID configuration on the bare metal .
This method creates the desired RAID configuration as read from
node [ ' target _ raid _ config ' ] .
: param node : A dictionary of the node object
: param ports : A list of dictionaries containing informati... | target_raid_config = node . get ( 'target_raid_config' , { } ) . copy ( )
return hpssa_manager . create_configuration ( raid_config = target_raid_config ) |
def target_exists ( self , target_id = 0 ) :
"""Returns True or False indicating whether or not the specified
target is present and valid .
` target _ id ` is a target ID ( or None for the first target )""" | try :
target = self . _target ( target_id = target_id )
except Exception as e :
log . error ( "Exception checking if target exists: {} {}" . format ( type ( e ) , e ) )
return False
return target is not None |
def resolve_to_callable ( callable_name ) :
"""Resolve string : callable _ name : to a callable .
: param callable _ name : String representing callable name as registered
in ramses registry or dotted import path of callable . Can be
wrapped in double curly brackets , e . g . ' { { my _ callable } } ' .""" | from . import registry
clean_callable_name = callable_name . replace ( '{{' , '' ) . replace ( '}}' , '' ) . strip ( )
try :
return registry . get ( clean_callable_name )
except KeyError :
try :
from zope . dottedname . resolve import resolve
return resolve ( clean_callable_name )
except Imp... |
def _after_request ( self , response ) :
"""The signal handler for the request _ finished signal .""" | if not getattr ( g , '_has_exception' , False ) :
extra = self . summary_extra ( )
self . summary_logger . info ( '' , extra = extra )
return response |
def plot_pauli_transfer_matrix ( ptransfermatrix , ax , labels , title ) :
"""Visualize the Pauli Transfer Matrix of a process .
: param numpy . ndarray ptransfermatrix : The Pauli Transfer Matrix
: param ax : The matplotlib axes .
: param labels : The labels for the operator basis states .
: param title : ... | im = ax . imshow ( ptransfermatrix , interpolation = "nearest" , cmap = rigetti_3_color_cm , vmin = - 1 , vmax = 1 )
dim = len ( labels )
plt . colorbar ( im , ax = ax )
ax . set_xticks ( range ( dim ) )
ax . set_xlabel ( "Input Pauli Operator" , fontsize = 20 )
ax . set_yticks ( range ( dim ) )
ax . set_ylabel ( "Outp... |
def _wait_for_macaroon ( wait_url ) :
'''Returns a macaroon from a legacy wait endpoint .''' | headers = { BAKERY_PROTOCOL_HEADER : str ( bakery . LATEST_VERSION ) }
resp = requests . get ( url = wait_url , headers = headers )
if resp . status_code != 200 :
raise InteractionError ( 'cannot get {}' . format ( wait_url ) )
return bakery . Macaroon . from_dict ( resp . json ( ) . get ( 'Macaroon' ) ) |
def _get_service_config ( self ) :
"""Will get configuration for the service from a service key .""" | key = self . _get_or_create_service_key ( )
config = { }
config [ 'service_key' ] = [ { 'name' : self . name } ]
config . update ( key [ 'entity' ] [ 'credentials' ] )
return config |
def offset ( polygons , distance , join = 'miter' , tolerance = 2 , precision = 0.001 , join_first = False , max_points = 199 , layer = 0 , datatype = 0 ) :
"""Shrink or expand a polygon or polygon set .
Parameters
polygons : polygon or array - like
Polygons to be offset . Must be a ` ` PolygonSet ` ` ,
` `... | poly = [ ]
if isinstance ( polygons , PolygonSet ) :
poly . extend ( polygons . polygons )
elif isinstance ( polygons , CellReference ) or isinstance ( polygons , CellArray ) :
poly . extend ( polygons . get_polygons ( ) )
else :
for obj in polygons :
if isinstance ( obj , PolygonSet ) :
... |
def find_installed_packages ( self ) :
"""Find the installed system packages .
: returns : A list of strings with system package names .
: raises : : exc : ` . SystemDependencyError ` when the command to list the
installed system packages fails .""" | list_command = subprocess . Popen ( self . list_command , shell = True , stdout = subprocess . PIPE )
stdout , stderr = list_command . communicate ( )
if list_command . returncode != 0 :
raise SystemDependencyError ( "The command to list the installed system packages failed! ({command})" , command = self . list_com... |
def collect_outs ( self ) :
"""Collect and store the outputs from this rule .""" | # TODO : this should probably live in CacheManager .
for outfile in self . rule . output_files or [ ] :
outfile_built = os . path . join ( self . buildroot , outfile )
if not os . path . exists ( outfile_built ) :
raise error . TargetBuildFailed ( self . address , 'Output file is missing: %s' % outfile ... |
def convert_join ( value ) :
"""Fix a Join ; )""" | if not isinstance ( value , list ) or len ( value ) != 2 : # Cowardly refuse
return value
sep , parts = value [ 0 ] , value [ 1 ]
if isinstance ( parts , six . string_types ) :
return parts
if not isinstance ( parts , list ) : # This looks tricky , just return the join as it was
return { "Fn::Join" : value ... |
def delete ( cont , path = None , profile = None ) :
'''Delete a container , or delete an object from a container .
CLI Example to delete a container : :
salt myminion swift . delete mycontainer
CLI Example to delete an object from a container : :
salt myminion swift . delete mycontainer remoteobject''' | swift_conn = _auth ( profile )
if path is None :
return swift_conn . delete_container ( cont )
else :
return swift_conn . delete_object ( cont , path ) |
def _parse_mibs ( iLOIP , snmp_credentials ) :
"""Parses the MIBs .
: param iLOIP : IP address of the server on which SNMP discovery
has to be executed .
: param snmp _ credentials : a Dictionary of SNMP credentials .
auth _ user : SNMP user
auth _ protocol : Auth Protocol
auth _ prot _ pp : Pass phrase... | result = { }
usm_user_obj = _create_usm_user_obj ( snmp_credentials )
try :
for ( errorIndication , errorStatus , errorIndex , varBinds ) in hlapi . nextCmd ( hlapi . SnmpEngine ( ) , usm_user_obj , hlapi . UdpTransportTarget ( ( iLOIP , 161 ) , timeout = 3 , retries = 3 ) , hlapi . ContextData ( ) , # cpqida cpqDa... |
def build ( c , clean = False , browse = False , nitpick = False , opts = None , source = None , target = None , ) :
"""Build the project ' s Sphinx docs .""" | if clean :
_clean ( c )
if opts is None :
opts = ""
if nitpick :
opts += " -n -W -T"
cmd = "sphinx-build{0} {1} {2}" . format ( ( " " + opts ) if opts else "" , source or c . sphinx . source , target or c . sphinx . target , )
c . run ( cmd , pty = True )
if browse :
_browse ( c ) |
def cql ( self , cql , start = 0 , limit = None , expand = None , include_archived_spaces = None , excerpt = None ) :
"""Get results from cql search result with all related fields
Search for entities in Confluence using the Confluence Query Language ( CQL )
: param cql :
: param start : OPTIONAL : The start p... | params = { }
if start is not None :
params [ 'start' ] = int ( start )
if limit is not None :
params [ 'limit' ] = int ( limit )
if cql is not None :
params [ 'cql' ] = cql
if expand is not None :
params [ 'expand' ] = expand
if include_archived_spaces is not None :
params [ 'includeArchivedSpaces' ... |
def clear ( self # type : ORMTask
) :
"""Delete all objects created by this task .
Iterate over ` self . object _ classes ` and delete all objects of the listed classes .""" | # mark this task as incomplete
self . mark_incomplete ( )
# delete objects
for object_class in self . object_classes :
self . session . query ( object_class ) . delete ( )
self . close_session ( ) |
def add_project ( self , path ) :
"""Adds a project .
: param path : Project path .
: type path : unicode
: return : Method success .
: rtype : bool""" | if not foundations . common . path_exists ( path ) :
return False
path = os . path . normpath ( path )
if self . __model . get_project_nodes ( path ) :
self . __engine . notifications_manager . warnify ( "{0} | '{1}' project is already opened!" . format ( self . __class__ . __name__ , path ) )
return False
... |
def from_str ( cls , value ) :
"""Create a MOC from a str .
This grammar is expressed is the ` MOC IVOA < http : / / ivoa . net / documents / MOC / 20190215 / WD - MOC - 1.1-20190215 . pdf > ` _ _
specification at section 2.3.2.
Parameters
value : str
The MOC as a string following the grammar rules .
Re... | # Import lark parser when from _ str is called
# at least one time
from lark import Lark , Transformer
class ParsingException ( Exception ) :
pass
class TreeToJson ( Transformer ) :
def value ( self , items ) :
res = { }
for item in items :
if item is not None : # Do not take into ac... |
def build_url_field ( self , field_name , model_class ) :
"""Create a field representing the object ' s own URL .""" | field_class = self . serializer_url_field
field_kwargs = get_url_kwargs ( model_class )
return field_class , field_kwargs |
def _patch_file ( path , content ) :
"""Will backup the file then patch it""" | f = open ( path )
existing_content = f . read ( )
f . close ( )
if existing_content == content : # already patched
log . warn ( 'Already patched.' )
return False
log . warn ( 'Patching...' )
_rename_path ( path )
f = open ( path , 'w' )
try :
f . write ( content )
finally :
f . close ( )
return True |
def metadata_converter_help_content ( ) :
"""Helper method that returns just the content in extent mode .
This method was added so that the text could be reused in the
wizard .
: returns : A message object without brand element .
: rtype : safe . messaging . message . Message""" | message = m . Message ( )
paragraph = m . Paragraph ( tr ( 'This tool will convert InaSAFE 4.x keyword metadata into the ' 'metadata format used by InaSAFE 3.5. The primary reason for doing ' 'this is to prepare data for use in GeoSAFE - the online version of ' 'InaSAFE.' ) )
message . add ( paragraph )
paragraph = m .... |
def determine_scale ( scale , img , mark ) :
"""Scales an image using a specified ratio , ' F ' or ' R ' . If ` scale ` is
' F ' , the image is scaled to be as big as possible to fit in ` img `
without falling off the edges . If ` scale ` is ' R ' , the watermark
resizes to a percentage of minimum size of sou... | if scale :
try :
scale = float ( scale )
except ( ValueError , TypeError ) :
pass
if isinstance ( scale , six . string_types ) and scale . upper ( ) == 'F' : # scale watermark to full , but preserve the aspect ratio
scale = min ( float ( img . size [ 0 ] ) / mark . size [ 0 ] , float... |
def runExperimentPool ( numObjects , numLocations , numFeatures , numColumns , longDistanceConnectionsRange = [ 0.0 ] , numWorkers = 7 , nTrials = 1 , numPoints = 10 , locationNoiseRange = [ 0.0 ] , featureNoiseRange = [ 0.0 ] , enableFeedback = [ True ] , ambiguousLocationsRange = [ 0 ] , numInferenceRpts = 1 , settli... | # Create function arguments for every possibility
args = [ ]
for c in reversed ( numColumns ) :
for o in reversed ( numObjects ) :
for l in numLocations :
for f in numFeatures :
for p in longDistanceConnectionsRange :
for t in range ( nTrials ) :
... |
def _build_fields ( self ) :
"""Builds a list of valid fields""" | declared_fields = self . solr . _send_request ( 'get' , ADMIN_URL )
result = decoder . decode ( declared_fields )
self . field_list = self . _parse_fields ( result , 'fields' )
# Build regular expressions to match dynamic fields .
# dynamic field names may have exactly one wildcard , either at
# the beginning or the en... |
def _generate_sql ( self , keys , changed_keys ) :
"""Generate forward operations for changing / creating SQL items .""" | for key in reversed ( keys ) :
app_label , sql_name = key
new_item = self . to_sql_graph . nodes [ key ]
sql_deps = [ n . key for n in self . to_sql_graph . node_map [ key ] . parents ]
reverse_sql = new_item . reverse_sql
if key in changed_keys :
operation_cls = AlterSQL
kwargs = { ... |
def feature_parser ( uni_feature , word_surface ) : # type : ( text _ type , text _ type ) - > Tuple [ Tuple [ text _ type , text _ type , text _ type ] , text _ type ]
"""Parse the POS feature output by Mecab
: param uni _ feature unicode :
: return ( ( pos1 , pos2 , pos3 ) , word _ stem ) :""" | list_feature_items = uni_feature . split ( ',' )
# if word has no feature at all
if len ( list_feature_items ) == 1 :
return ( '*' ) , ( '*' )
pos1 = list_feature_items [ 0 ]
pos2 = list_feature_items [ 1 ]
pos3 = list_feature_items [ 2 ]
tuple_pos = ( pos1 , pos2 , pos3 )
# if without constraint ( output is normal... |
def porttree_matches ( name ) :
'''Returns a list containing the matches for a given package name from the
portage tree . Note that the specific version of the package will not be
provided for packages that have several versions in the portage tree , but
rather the name of the package ( i . e . " dev - python... | matches = [ ]
for category in _porttree ( ) . dbapi . categories :
if _porttree ( ) . dbapi . cp_list ( category + "/" + name ) :
matches . append ( category + "/" + name )
return matches |
def write_config ( self ) :
"""Writes the provisioner ' s config file to disk and returns None .
: return : None""" | template = util . render_template ( self . _get_config_template ( ) , config_options = self . config_options )
util . write_file ( self . config_file , template ) |
def get_language_parameter ( request , query_language_key = 'language' , object = None , default = None ) :
"""Get the language parameter from the current request .""" | # This is the same logic as the django - admin uses .
# The only difference is the origin of the request parameter .
if not is_multilingual_project ( ) : # By default , the objects are stored in a single static language .
# This makes the transition to multilingual easier as well .
# The default language can operate as... |
def _login ( session ) :
"""Login .""" | _LOGGER . info ( "logging in (no valid cookie found)" )
session . cookies . clear ( )
resp = session . post ( SSO_URL , { 'USER' : session . auth . username , 'PASSWORD' : session . auth . password , 'TARGET' : TARGET_URL } )
parsed = BeautifulSoup ( resp . text , HTML_PARSER )
relay_state = parsed . find ( 'input' , {... |
def _delay_for_ratelimits ( cls , start ) :
"""If request was shorter than max request time , delay""" | stop = datetime . now ( )
duration_microseconds = ( stop - start ) . microseconds
if duration_microseconds < cls . REQUEST_TIME_MICROSECONDS :
time . sleep ( ( cls . REQUEST_TIME_MICROSECONDS - duration_microseconds ) / MICROSECONDS_PER_SECOND ) |
def del_membership ( self , user , role ) :
"""dismember user from a group""" | if not self . has_membership ( user , role ) :
return True
targetRecord = AuthMembership . objects ( creator = self . client , user = user ) . first ( )
if not targetRecord :
return True
for group in targetRecord . groups :
if group . role == role :
targetRecord . groups . remove ( group )
targetRec... |
def browse_website ( self , browser = None ) :
"""Launch web browser at project ' s homepage
@ param browser : name of web browser to use
@ type browser : string
@ returns : 0 if homepage found , 1 if no homepage found""" | if len ( self . all_versions ) :
metadata = self . pypi . release_data ( self . project_name , self . all_versions [ 0 ] )
self . logger . debug ( "DEBUG: browser: %s" % browser )
if metadata . has_key ( "home_page" ) :
self . logger . info ( "Launching browser: %s" % metadata [ "home_page" ] )
... |
def pip_version ( self ) :
"""Get the pip version in the environment . Useful for knowing which args we can use
when installing .""" | from . vendor . packaging . version import parse as parse_version
pip = next ( iter ( pkg for pkg in self . get_installed_packages ( ) if pkg . key == "pip" ) , None )
if pip is not None :
pip_version = parse_version ( pip . version )
return parse_version ( "18.0" ) |
def _coefficient_handler_factory ( trans_table , parse_func , assertion = lambda c , ctx : True , ion_type = None , append_first_if_not = None ) :
"""Generates a handler co - routine which tokenizes a numeric coefficient .
Args :
trans _ table ( dict ) : lookup table for the handler for the next component of th... | def transition ( prev , c , ctx , trans ) :
if prev == _UNDERSCORE :
_illegal_character ( c , ctx , 'Underscore before %s.' % ( _chr ( c ) , ) )
return ctx . immediate_transition ( trans_table [ c ] ( c , ctx ) )
return _numeric_handler_factory ( _DIGITS , transition , assertion , ( _DOT , ) , parse_fun... |
def post_config_hook ( self ) :
"""Initialization""" | self . _no_force_on_change = True
self . active_comb = None
self . active_layout = None
self . active_mode = "extend"
self . displayed = None
self . max_width = 0 |
def import_uploads ( self , uploads = None , upload_ids = None , synchronous = True , ** kwargs ) :
"""Import uploads into a repository
It expects either a list of uploads or upload _ ids ( but not both ) .
: param uploads : Array of uploads to be imported
: param upload _ ids : Array of upload ids to be impo... | kwargs = kwargs . copy ( )
# shadow the passed - in kwargs
kwargs . update ( self . _server_config . get_client_kwargs ( ) )
if uploads :
data = { 'uploads' : uploads }
elif upload_ids :
data = { 'upload_ids' : upload_ids }
response = client . put ( self . path ( 'import_uploads' ) , data , ** kwargs )
json = _... |
def daily_freezethaw_cycles ( tasmax , tasmin , freq = 'YS' ) :
r"""Number of days with a diurnal freeze - thaw cycle
The number of days where Tmax > 0 ° C and Tmin < 0 ° C .
Parameters
tasmax : xarray . DataArray
Maximum daily temperature [ ° C ] or [ K ]
tasmin : xarray . DataArray
Minimum daily tempe... | frz = utils . convert_units_to ( '0 degC' , tasmax )
ft = ( tasmin < frz ) * ( tasmax > frz ) * 1
out = ft . resample ( time = freq ) . sum ( dim = 'time' )
return out |
def _machine_bytes ( ) :
"""Get the machine portion of an ObjectId .""" | machine_hash = hashlib . md5 ( )
if PY3 : # gethostname ( ) returns a unicode string in python 3 . x
# while update ( ) requires a byte string .
machine_hash . update ( socket . gethostname ( ) . encode ( ) )
else : # Calling encode ( ) here will fail with non - ascii hostnames
machine_hash . update ( socket . ... |
def validate_bool ( b ) :
"""Convert b to a boolean or raise""" | if isinstance ( b , six . string_types ) :
b = b . lower ( )
if b in ( 't' , 'y' , 'yes' , 'on' , 'true' , '1' , 1 , True ) :
return True
elif b in ( 'f' , 'n' , 'no' , 'off' , 'false' , '0' , 0 , False ) :
return False
else :
raise ValueError ( 'Could not convert "%s" to boolean' % b ) |
def Y_dist ( self , new_y_distance ) :
"""Use preset values for the distance between lines .""" | self . parent . value ( 'y_distance' , new_y_distance )
self . parent . traces . display ( ) |
def merge ( id , card , cardscript = None ) :
"""Find the xmlcard and the card definition of \a id
Then return a merged class of the two""" | if card is None :
card = cardxml . CardXML ( id )
if cardscript is None :
cardscript = get_script_definition ( id )
if cardscript :
card . scripts = type ( id , ( cardscript , ) , { } )
else :
card . scripts = type ( id , ( ) , { } )
scriptnames = ( "activate" , "combo" , "deathrattle" , "draw" , "inspi... |
def query_signing ( self , contract_id = None , plan_id = None , contract_code = None , openid = None , version = "1.0" ) :
"""查询签约关系 api
: param contract _ id : 可选 委托代扣协议id 委托代扣签约成功后由微信返回的委托代扣协议id , 选择contract _ id查询 , 则此参数必填
: param plan _ id : 可选 模板id 商户在微信商户平台配置的代扣模板id , 选择plan _ id + contract _ code查询 , 则此... | if not contract_id and not ( plan_id and contract_code ) and not ( plan_id and openid ) :
raise ValueError ( "contract_id and (plan_id, contract_code) and (plan_id, openid) must be a choice." )
data = { "appid" : self . appid , "mch_id" : self . mch_id , "contract_id" : contract_id , "plan_id" : plan_id , "contract... |
def acquire_win ( lock_file ) : # pragma : no cover
"""Acquire a lock file on windows .""" | try :
fd = os . open ( lock_file , OPEN_MODE )
except OSError :
pass
else :
try :
msvcrt . locking ( fd , msvcrt . LK_NBLCK , 1 )
except ( IOError , OSError ) :
os . close ( fd )
else :
return fd |
def _prepare_variables ( self ) :
"""Prepare Variables for YellowFin .
Returns :
Grad * * 2 , Norm , Norm * * 2 , Mean ( Norm * * 2 ) ops""" | self . _moving_averager = tf . train . ExponentialMovingAverage ( decay = self . _beta , zero_debias = self . _zero_debias )
# assert self . _ grad is not None and len ( self . _ grad ) > 0
# List for the returned Operations
prepare_variables_op = [ ]
# Get per var g * * 2 and norm * * 2
self . _grad_squared = [ ]
self... |
def embed_file ( self , input_file : IO , output_file_path : str , output_format : str = "all" , batch_size : int = DEFAULT_BATCH_SIZE , forget_sentences : bool = False , use_sentence_keys : bool = False ) -> None :
"""Computes ELMo embeddings from an input _ file where each line contains a sentence tokenized by wh... | assert output_format in [ "all" , "top" , "average" ]
# Tokenizes the sentences .
sentences = [ line . strip ( ) for line in input_file ]
blank_lines = [ i for ( i , line ) in enumerate ( sentences ) if line == "" ]
if blank_lines :
raise ConfigurationError ( f"Your input file contains empty lines at indexes " f"{b... |
def get_sequence_time ( cycles , unit_converter = None , eres = None ) :
"""Calculates the time the move sequence will take to complete .
Calculates the amount of time it will take to complete the given
move sequence . Types of motion supported are moves from one position
to another ( the motion will always c... | # If we are doing unit conversion , then that is equivalent to motor
# units but with eres equal to one .
if unit_converter is not None :
eres = 1
# Starting with 0 time , steadily add the time of each movement .
tme = 0.0
# Go through each cycle and collect times .
for cycle in cycles : # Add all the wait times .
... |
def make_tophat_ei ( lower , upper ) :
"""Return a ufunc - like tophat function on the defined range , left - exclusive
and right - inclusive . Returns 1 if lower < x < = upper , 0 otherwise .""" | if not np . isfinite ( lower ) :
raise ValueError ( '"lower" argument must be finite number; got %r' % lower )
if not np . isfinite ( upper ) :
raise ValueError ( '"upper" argument must be finite number; got %r' % upper )
def range_tophat_ei ( x ) :
x = np . asarray ( x )
x1 = np . atleast_1d ( x )
... |
def compute_weight ( self , r , ytr = None , mask = None ) :
"""Returns the weight ( w ) using OLS of r * w = gp . _ ytr""" | ytr = self . _ytr if ytr is None else ytr
mask = self . _mask if mask is None else mask
return compute_weight ( r , ytr , mask ) |
def combine ( ctx , src , dst ) :
"""Combine several smother reports .""" | c = coverage . Coverage ( config_file = ctx . obj [ 'rcfile' ] )
result = Smother ( c )
for infile in src :
result |= Smother . load ( infile )
result . write ( dst ) |
def get_tile_metadata_name ( self ) :
""": return : name of tile metadata file
: rtype : str""" | if self . safe_type == EsaSafeType . OLD_TYPE :
name = _edit_name ( self . tile_id , 'MTD' , delete_end = True )
else :
name = 'MTD_TL'
return '{}.xml' . format ( name ) |
def from_value ( self , value ) :
"""Function infers TDS type from Python value .
: param value : value from which to infer TDS type
: return : An instance of subclass of : class : ` BaseType `""" | if value is None :
sql_type = NVarCharType ( size = 1 )
else :
sql_type = self . _from_class_value ( value , type ( value ) )
return sql_type |
def print_all_metadata ( fname ) :
"""high level that prints all as long list""" | print ( "Filename :" , fname )
print ( "Basename :" , os . path . basename ( fname ) )
print ( "Path :" , os . path . dirname ( fname ) )
print ( "Size :" , os . path . getsize ( fname ) )
img = Image . open ( fname )
# get the image ' s width and height in pixels
width , height = img . size
# get the l... |
def get_asset_content_form_for_create ( self , asset_id = None , asset_content_record_types = None ) :
"""Gets an asset content form for creating new assets .
arg : asset _ id ( osid . id . Id ) : the ` ` Id ` ` of an ` ` Asset ` `
arg : asset _ content _ record _ types ( osid . type . Type [ ] ) : array of
a... | if AWS_ASSET_CONTENT_RECORD_TYPE in asset_content_record_types :
asset_content_record_types . remove ( AWS_ASSET_CONTENT_RECORD_TYPE )
return AssetContentForm ( self . _provider_session . get_asset_content_form_for_create ( asset_id , asset_content_record_types ) , self . _config_map , self . get_repository_id ... |
def arquire_attributes ( self , attributes , active = True ) :
"""Claims a list of attributes for the current client .
Can also disable attributes . Returns update response object .""" | attribute_update = self . _post_object ( self . update_api . attributes . acquire , attributes )
return ExistAttributeResponse ( attribute_update ) |
def relations ( cls ) :
"""Return a ` list ` of relationship names or the given model""" | return [ c . key for c in cls . __mapper__ . iterate_properties if isinstance ( c , RelationshipProperty ) ] |
def get_thumbnail_source ( self , obj ) :
"""Obtains the source image field for the thumbnail .
: param obj : An object with a thumbnail _ field defined .
: return : Image field for thumbnail or None if not found .""" | if hasattr ( self , 'thumbnail_field' ) and self . thumbnail_field :
return resolve ( obj , self . thumbnail_field )
# try get _ list _ image , from ListableMixin
if hasattr ( obj , 'get_list_image' ) :
return resolve ( obj , "get_list_image" )
logger . warning ( 'ThumbnailAdminMixin.thumbnail_field unspecified... |
def _close ( self , args ) :
"""request a connection close
This method indicates that the sender wants to close the
connection . This may be due to internal conditions ( e . g . a
forced shut - down ) or due to an error handling a specific
method , i . e . an exception . When a close is due to an
exceptio... | reply_code = args . read_short ( )
reply_text = args . read_shortstr ( )
class_id = args . read_short ( )
method_id = args . read_short ( )
self . _x_close_ok ( )
raise AMQPConnectionException ( reply_code , reply_text , ( class_id , method_id ) ) |
def _massage_metakeys ( dct , prfx ) :
"""Returns a copy of the supplied dictionary , prefixing any keys that do
not begin with the specified prefix accordingly .""" | lowprefix = prfx . lower ( )
ret = { }
for k , v in list ( dct . items ( ) ) :
if not k . lower ( ) . startswith ( lowprefix ) :
k = "%s%s" % ( prfx , k )
ret [ k ] = v
return ret |
def create_napp ( cls , meta_package = False ) :
"""Bootstrap a basic NApp structure for you to develop your NApp .
This will create , on the current folder , a clean structure of a NAPP ,
filling some contents on this structure .""" | templates_path = SKEL_PATH / 'napp-structure/username/napp'
ui_templates_path = os . path . join ( templates_path , 'ui' )
username = None
napp_name = None
print ( '--------------------------------------------------------------' )
print ( 'Welcome to the bootstrap process of your NApp.' )
print ( '---------------------... |
def send ( self , uid , event , payload = None ) :
"""Send an event to a connected controller . Use pymlgame event type and correct payload .
To send a message to the controller use pymlgame . E _ MESSAGE event and a string as payload .
: param uid : Unique id of the controller
: param event : Event type
: ... | sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
if uid in self . controllers . keys ( ) :
addr = self . controllers [ uid ] [ 0 ]
port = self . controllers [ uid ] [ 1 ]
if event == E_MESSAGE : # print ( ' / message / { } = > { } : { } ' . format ( payload , addr , port ) )
return ... |
def subtract_lists ( list1 , list2 ) :
"""Compute the subtracted result of two lists element by element .
This function employs map function in conjunction with a lambda function to perform subtraction operation
between corresponding elements of the two lists .
Args :
list1 : The first list of numbers .
l... | subtraction_result = map ( ( lambda num1 , num2 : ( num1 - num2 ) ) , list1 , list2 )
return list ( subtraction_result ) |
def list_portgroups ( kwargs = None , call = None ) :
'''List all the distributed virtual portgroups for this VMware environment
CLI Example :
. . code - block : : bash
salt - cloud - f list _ portgroups my - vmware - config''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The list_portgroups function must be called with ' '-f or --function.' )
return { 'Portgroups' : salt . utils . vmware . list_portgroups ( _get_si ( ) ) } |
def momentum ( data , period ) :
"""Momentum .
Formula :
DATA [ i ] - DATA [ i - period ]""" | catch_errors . check_for_period_error ( data , period )
momentum = [ data [ idx ] - data [ idx + 1 - period ] for idx in range ( period - 1 , len ( data ) ) ]
momentum = fill_for_noncomputable_vals ( data , momentum )
return momentum |
def FilterItems ( self , filterFn ) :
"""Filter items in a ReservoirBucket , using a filtering function .
Filtering items from the reservoir bucket must update the
internal state variable self . _ num _ items _ seen , which is used for determining
the rate of replacement in reservoir sampling . Ideally , self... | with self . _mutex :
size_before = len ( self . items )
self . items = list ( filter ( filterFn , self . items ) )
size_diff = size_before - len ( self . items )
# Estimate a correction the number of items seen
prop_remaining = len ( self . items ) / float ( size_before ) if size_before > 0 else 0
... |
def search_schema_path ( self , index , ** options ) :
"""Builds a Yokozuna search Solr schema URL .
: param index : a name of a yz solr schema
: type index : string
: param options : optional list of additional arguments
: type index : dict
: rtype URL string""" | if not self . yz_wm_schema :
raise RiakError ( "Yokozuna search is unsupported by this Riak node" )
return mkpath ( self . yz_wm_schema , "schema" , quote_plus ( index ) , ** options ) |
def daemons_check ( self ) :
"""Manage the list of Alignak launched daemons
Check if the daemon process is running
: return : True if all daemons are running , else False""" | # First look if it ' s not too early to ping
start = time . time ( )
if self . daemons_last_check and self . daemons_last_check + self . conf . daemons_check_period > start :
logger . debug ( "Too early to check daemons, check period is %.2f seconds" , self . conf . daemons_check_period )
return True
logger . d... |
def template_cycles ( self ) -> int :
"""The number of cycles dedicated to template .""" | return sum ( ( int ( re . sub ( r'\D' , '' , op ) ) for op in self . template_tokens ) ) |
def _build_optml_volumes ( self , host , subdirs ) :
"""Generate a list of : class : ` ~ sagemaker . local _ session . Volume ` required for the container to start .
It takes a folder with the necessary files for training and creates a list of opt volumes that
the Container needs to start .
Args :
host ( st... | volumes = [ ]
for subdir in subdirs :
host_dir = os . path . join ( self . container_root , host , subdir )
container_dir = '/opt/ml/{}' . format ( subdir )
volume = _Volume ( host_dir , container_dir )
volumes . append ( volume )
return volumes |
def close ( self ) :
"""Commit and close the connection .
. . seealso : : : py : meth : ` sqlite3 . Connection . close `""" | if self . __delayed_connection_path and self . __connection is None :
self . __initialize_connection ( )
return
try :
self . check_connection ( )
except ( SystemError , NullDatabaseConnectionError ) :
return
logger . debug ( "close connection to a SQLite database: path='{}'" . format ( self . database_p... |
def _send_features ( self , features ) :
"""Send a query to the backend api with a list of observed features in this log file
: param features : Features found in the log file
: return : Response text from ThreshingFloor API""" | # Hit the auth endpoint with a list of features
try :
r = requests . post ( self . base_uri + self . api_endpoint , json = features , headers = { 'x-api-key' : self . api_key } )
except requests . exceptions . ConnectionError :
raise TFAPIUnavailable ( "The ThreshingFloor API appears to be unavailable." )
if r ... |
def rgb ( red , green , blue , content ) :
"""Colors a content using rgb for h
: param red : [ 0-5]
: type red : int
: param green : [ 0-5]
: type green : int
: param blue : [ 0-5]
: type blue : int
: param content : Whatever you want to say . . .
: type content : unicode
: return : ansi string
... | color = 16 + 36 * red + 6 * green + blue
return encode ( '38;5;' + str ( color ) ) + content + encode ( DEFAULT ) |
def load_random ( self , num_bytes , offset = 0 ) :
"""Ask YubiHSM to generate a number of random bytes to any offset of it ' s internal
buffer .
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L { generate _ aead }
commands to act... | return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Random_Load ( self . stick , num_bytes , offset ) . execute ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.