signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def check_access_token ( self , request_token ) :
"""Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper .""" | lower , upper = self . access_token_length
return ( set ( request_token ) <= self . safe_characters and lower <= len ( request_token ) <= upper ) |
def evaluate_impl ( expression , params = None ) :
'''Implementation of CalculatorImpl : : evaluate ( ) , also shared by
FunctionImpl : : call ( ) . In the latter case , ` params ` are the parameter
values passed to the function ; in the former case , ` params ` is just an
empty list .''' | which = expression . which ( )
if which == 'literal' :
return capnp . Promise ( expression . literal )
elif which == 'previousResult' :
return read_value ( expression . previousResult )
elif which == 'parameter' :
assert expression . parameter < len ( params )
return capnp . Promise ( params [ expressio... |
def copy_to ( self , dest , buffering : int = - 1 ) :
'''copy the file to dest path .
` dest ` canbe ` str ` , ` FileInfo ` or ` DirectoryInfo ` .
if ` dest ` is ` DirectoryInfo ` , that mean copy into the dir with same name .''' | if isinstance ( dest , str ) :
dest_path = dest
elif isinstance ( dest , FileInfo ) :
dest_path = dest . path
elif isinstance ( dest , DirectoryInfo ) :
dest_path = dest . path / self . path . name
else :
raise TypeError ( 'dest is not one of `str`, `FileInfo`, `DirectoryInfo`' )
with open ( self . _pat... |
def CheckProg ( context , prog_name ) :
"""Simple check if a program exists in the path . Returns the path
for the application , or None if not found .""" | res = SCons . Conftest . CheckProg ( context , prog_name )
context . did_show_result = 1
return res |
def lock_file ( f , block = False ) :
"""If block = False ( the default ) , die hard and fast if another process has
already grabbed the lock for this file .
If block = True , wait for the lock to be released , then continue .""" | try :
flags = fcntl . LOCK_EX
if not block :
flags |= fcntl . LOCK_NB
fcntl . flock ( f . fileno ( ) , flags )
except IOError as e :
if e . errno in ( errno . EACCES , errno . EAGAIN ) :
raise SystemExit ( "ERROR: %s is locked by another process." % f . name )
raise |
def iter_breadth_first ( self , start = None , do_paths = False , do_duplicates = False ) :
"""Iterate over the vertices with the breadth first algorithm .
See http : / / en . wikipedia . org / wiki / Breadth - first _ search for more info .
If not start vertex is given , the central vertex is taken .
By defa... | if start is None :
start = self . central_vertex
else :
try :
start = int ( start )
except ValueError :
raise TypeError ( "First argument (start) must be an integer." )
if start < 0 or start >= self . num_vertices :
raise ValueError ( "start must be in the range [0, %i[" % self .... |
def tt ( self , year = None , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 , jd = None ) :
"""Build a ` Time ` from a TT calendar date .
Supply the Terrestrial Time ( TT ) as a proleptic Gregorian
calendar date :
> > > t = ts . tt ( 2014 , 1 , 18 , 1 , 35 , 37.5)
> > > t . tt
2456675.5664062... | if jd is not None :
tt = jd
else :
tt = julian_date ( _to_array ( year ) , _to_array ( month ) , _to_array ( day ) , _to_array ( hour ) , _to_array ( minute ) , _to_array ( second ) , )
tt = _to_array ( tt )
return Time ( self , tt ) |
def isItemAllowed ( self , obj ) :
"""Checks if the passed in Analysis must be displayed in the list .
: param obj : A single Analysis brain or content object
: type obj : ATContentType / CatalogBrain
: returns : True if the item can be added to the list .
: rtype : bool""" | if not obj :
return False
# Does the user has enough privileges to see retracted analyses ?
if obj . review_state == 'retracted' and not self . has_permission ( ViewRetractedAnalyses ) :
return False
return True |
def list_subdomains ( self , limit = None , offset = None ) :
"""Returns a list of all subdomains for this domain .""" | return self . manager . list_subdomains ( self , limit = limit , offset = offset ) |
def remove_directories ( list_of_paths ) :
"""Removes non - leafs from a list of directory paths""" | found_dirs = set ( '/' )
for path in list_of_paths :
dirs = path . strip ( ) . split ( '/' )
for i in range ( 2 , len ( dirs ) ) :
found_dirs . add ( '/' . join ( dirs [ : i ] ) )
paths = [ path for path in list_of_paths if ( path . strip ( ) not in found_dirs ) and path . strip ( ) [ - 1 ] != '/' ]
ret... |
def get_date ( self ) :
"""Collects sensing date of the product .
: return : Sensing date
: rtype : str""" | if self . safe_type == EsaSafeType . OLD_TYPE :
name = self . product_id . split ( '_' ) [ - 2 ]
date = [ name [ 1 : 5 ] , name [ 5 : 7 ] , name [ 7 : 9 ] ]
else :
name = self . product_id . split ( '_' ) [ 2 ]
date = [ name [ : 4 ] , name [ 4 : 6 ] , name [ 6 : 8 ] ]
return '-' . join ( date_part . lst... |
def lhs ( self ) :
"""The left - hand - side of the equation""" | lhs = self . _lhs
i = 0
while lhs is None :
i -= 1
lhs = self . _prev_lhs [ i ]
return lhs |
def drawBernoulli ( N , p = 0.5 , seed = 0 ) :
'''Generates arrays of booleans drawn from a simple Bernoulli distribution .
The input p can be a float or a list - like of floats ; its length T determines
the number of entries in the output . The t - th entry of the output is an
array of N booleans which are T... | # Set up the RNG
RNG = np . random . RandomState ( seed )
if isinstance ( p , float ) : # Return a single array of size N
draws = RNG . uniform ( size = N ) < p
else : # Set up empty list to populate , then loop and populate list with draws :
draws = [ ]
for t in range ( len ( p ) ) :
draws . append... |
def getinputfilename ( self , inputtemplate , filename ) :
"""Determine the final filename for an input file given an inputtemplate and a given filename .
Example : :
filenameonserver = client . getinputfilename ( " someinputtemplate " , " / path / to / local / file " )""" | if inputtemplate . filename :
filename = inputtemplate . filename
elif inputtemplate . extension :
if filename . lower ( ) [ - 4 : ] == '.zip' or filename . lower ( ) [ - 7 : ] == '.tar.gz' or filename . lower ( ) [ - 8 : ] == '.tar.bz2' : # pass archives as - is
return filename
if filename [ - len ... |
def _get_sts_token ( self ) :
"""Assume a role via STS and return the credentials .
First connect to STS via : py : func : ` boto3 . client ` , then
assume a role using ` boto3 . STS . Client . assume _ role < https : / / boto3 . readthe
docs . org / en / latest / reference / services / sts . html # STS . Cli... | logger . debug ( "Connecting to STS in region %s" , self . region )
sts = boto3 . client ( 'sts' , region_name = self . region )
arn = "arn:aws:iam::%s:role/%s" % ( self . account_id , self . account_role )
logger . debug ( "STS assume role for %s" , arn )
assume_kwargs = { 'RoleArn' : arn , 'RoleSessionName' : 'awslim... |
def _set_linkinfo_isllink_srcport_type ( self , v , load = False ) :
"""Setter method for linkinfo _ isllink _ srcport _ type , mapped from YANG variable / brocade _ fabric _ service _ rpc / show _ linkinfo / output / show _ link _ info / linkinfo _ isl / linkinfo _ isllink _ srcport _ type ( interfacetype - type )... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'pattern' : u'Te|Fi' , 'length' : [ u'2' ] } ) , is_leaf = True , yang_name = "linkinfo-isllink-srcport-type" , rest_name = "linkinfo-isllink-srcport-type" , pa... |
def _pfp__snapshot ( self , recurse = True ) :
"""Save off the current value of the field""" | if hasattr ( self , "_pfp__value" ) :
self . _pfp__snapshot_value = self . _pfp__value |
def extendbed ( args ) :
"""% prog extend agpfile componentfasta
Extend the components to fill the component range . For example , a bed / gff3 file
that was converted from the agp will contain only the BAC sequence intervals
that are ' represented ' - sometimes leaving the 5 ` and 3 ` out ( those that
over... | from jcvi . formats . sizes import Sizes
p = OptionParser ( extendbed . __doc__ )
p . add_option ( "--nogaps" , default = False , action = "store_true" , help = "Do not print bed lines for gaps [default: %default]" )
p . add_option ( "--bed12" , default = False , action = "store_true" , help = "Produce bed12 formatted ... |
def html ( self ) :
"""Returns an HTML citation .""" | s = ( u'{authors}, {title}, {journal}, {volissue}, {pages}, ' '({date}). {doi}.' )
au_link = ( '<a href="https://www.scopus.com/authid/detail.url' '?origin=AuthorProfile&authorId={0}">{1}</a>' )
if len ( self . authors ) > 1 :
authors = u', ' . join ( [ au_link . format ( a . auid , ( str ( a . given_name ) + ' ' +... |
def IsWalletTransaction ( self , tx ) :
"""Verifies if a transaction belongs to the wallet .
Args :
tx ( TransactionOutput ) : an instance of type neo . Core . TX . Transaction . TransactionOutput to verify .
Returns :
bool : True , if transaction belongs to wallet . False , if not .""" | for key , contract in self . _contracts . items ( ) :
for output in tx . outputs :
if output . ScriptHash . ToBytes ( ) == contract . ScriptHash . ToBytes ( ) :
return True
for script in tx . scripts :
if script . VerificationScript :
if bytes ( contract . Script ) == scr... |
def json ( self , var , default = NOTSET , force = True ) :
"""Get environment variable , parsed as a json string""" | return self . _get ( var , default = default , cast = json . loads , force = force ) |
def engine ( self ) :
"""Return an engine instance , creating it if it doesn ' t exist .
Recreate the engine connection if it wasn ' t originally created
by the current process .""" | pid = os . getpid ( )
conn = SQLAlchemyTarget . _engine_dict . get ( self . connection_string )
if not conn or conn . pid != pid : # create and reset connection
engine = sqlalchemy . create_engine ( self . connection_string , connect_args = self . connect_args , echo = self . echo )
SQLAlchemyTarget . _engine_d... |
def read_file ( filepath : str ) -> str :
"""Read a file and return it as a string""" | # ? Check this is ok if absolute paths passed in
filepath = os . path . expanduser ( filepath )
with open ( filepath ) as opened_file : # type : IO
file_read = opened_file . read ( )
# type : str
return file_read |
def missing_whitespace_after_import_keyword ( logical_line ) :
r"""Multiple imports in form from x import ( a , b , c ) should have space
between import statement and parenthesised name list .
Okay : from foo import ( bar , baz )
E275 : from foo import ( bar , baz )
E275 : from importable . module import ( ... | line = logical_line
indicator = ' import('
if line . startswith ( 'from ' ) :
found = line . find ( indicator )
if - 1 < found :
pos = found + len ( indicator ) - 1
yield pos , "E275 missing whitespace after keyword" |
def get_comments_of_offer_per_page ( self , offer_id , per_page = 1000 , page = 1 ) :
"""Get comments of offer per page
: param offer _ id : the offer id
: param per _ page : How many objects per page . Default : 1000
: param page : Which page . Default : 1
: return : list""" | return self . _get_resource_per_page ( resource = OFFER_COMMENTS , per_page = per_page , page = page , params = { 'offer_id' : offer_id } , ) |
def create ( cls , client_payment_service_provider_certificate , client_payment_service_provider_certificate_chain , client_public_key_signature , custom_headers = None ) :
""": param client _ payment _ service _ provider _ certificate : Payment Services
Directive 2 compatible QSEAL certificate
: type client _ ... | if custom_headers is None :
custom_headers = { }
request_map = { cls . FIELD_CLIENT_PAYMENT_SERVICE_PROVIDER_CERTIFICATE : client_payment_service_provider_certificate , cls . FIELD_CLIENT_PAYMENT_SERVICE_PROVIDER_CERTIFICATE_CHAIN : client_payment_service_provider_certificate_chain , cls . FIELD_CLIENT_PUBLIC_KEY_S... |
def check_indexes_all_same ( indexes , message = "Indexes are not equal." ) :
"""Check that a list of Index objects are all equal .
Parameters
indexes : iterable [ pd . Index ]
Iterable of indexes to check .
Raises
ValueError
If the indexes are not all the same .""" | iterator = iter ( indexes )
first = next ( iterator )
for other in iterator :
same = ( first == other )
if not same . all ( ) :
bad_loc = np . flatnonzero ( ~ same ) [ 0 ]
raise ValueError ( "{}\nFirst difference is at index {}: " "{} != {}" . format ( message , bad_loc , first [ bad_loc ] , oth... |
def gen_lock ( self , lock_type = 'update' , timeout = 0 , poll_interval = 0.5 ) :
'''Set and automatically clear a lock''' | if not isinstance ( lock_type , six . string_types ) :
raise GitLockError ( errno . EINVAL , 'Invalid lock_type \'{0}\'' . format ( lock_type ) )
# Make sure that we have a positive integer timeout , otherwise just set
# it to zero .
try :
timeout = int ( timeout )
except ValueError :
timeout = 0
else :
... |
def trial ( log_dir = None , upload_dir = None , sync_period = None , trial_prefix = "" , param_map = None , init_logging = True ) :
"""Generates a trial within a with context .""" | global _trial
# pylint : disable = global - statement
if _trial : # TODO : would be nice to stack crawl at creation time to report
# where that initial trial was created , and that creation line
# info is helpful to keep around anyway .
raise ValueError ( "A trial already exists in the current context" )
local_tria... |
def on_before_trading ( self , date_time ) :
"""开盘的时候检查 , 如果有持仓 , 就把持有天数 + 1""" | if self . cta_call [ 'pos' ] > 0 :
self . cta_call [ 'days' ] += 1
if self . cta_put [ 'pos' ] > 0 :
self . cta_put [ 'days' ] += 1
self . cta_call [ 'done' ] = False
self . cta_put [ 'done' ] = False |
def loss_ratio_exceedance_matrix ( self , loss_ratios ) :
"""Compute the LREM ( Loss Ratio Exceedance Matrix ) .""" | # LREM has number of rows equal to the number of loss ratios
# and number of columns equal to the number of imls
lrem = numpy . empty ( ( len ( loss_ratios ) , len ( self . imls ) ) )
for row , loss_ratio in enumerate ( loss_ratios ) :
for col , ( mean_loss_ratio , stddev ) in enumerate ( zip ( self . mean_loss_rat... |
def tokenize ( self , sentence , normalize = True , is_feature = False , is_surface = False , return_list = False , func_normalizer = text_preprocess . normalize_text ) : # type : ( text _ preprocess , bool , bool , bool , bool , Callable [ [ str ] , text _ type ] ) - > Union [ List [ text _ type ] , TokenizedSenetence... | assert isinstance ( normalize , bool )
assert isinstance ( sentence , text_type )
normalized_sentence = func_normalizer ( sentence )
result = self . call_juman_interface ( normalized_sentence )
token_objects = [ self . __extract_morphological_information ( mrph_object = morph_object , is_surface = is_surface , is_featu... |
def phase_progeny_by_transmission ( g ) :
"""Phase progeny genotypes from a trio or cross using Mendelian
transmission .
Parameters
g : array _ like , int , shape ( n _ variants , n _ samples , 2)
Genotype array , with parents as first two columns and progeny as
remaining columns .
Returns
g : ndarray... | # setup
g = GenotypeArray ( g , dtype = 'i1' , copy = True )
check_ploidy ( g . ploidy , 2 )
check_min_samples ( g . n_samples , 3 )
# run the phasing
# N . B . , a copy has already been made , so no need to make memoryview safe
is_phased = _opt_phase_progeny_by_transmission ( g . values )
g . is_phased = np . asarray ... |
def traceit ( frame , event , arg ) :
"""Trace every lie of a program . Use :
import sys
sys . settrace ( traceit )
: param frame :
: param event :
: param arg :
: return :""" | import linecache
try :
if event == "line" :
lineno = frame . f_lineno
filename = frame . f_globals . get ( "__file__" )
if ( filename . endswith ( ".pyc" ) or filename . endswith ( ".pyo" ) ) :
filename = filename [ : - 1 ]
name = frame . f_globals [ "__name__" ]
... |
def unit_position ( self ) -> typing . Tuple [ float , float ] :
"""Returns : unit position""" | return self . unit_pos_x , self . unit_pos_y |
def unmangle_name ( name , classname ) :
"""Remove _ _ from the end of _ name _ if it starts with _ _ classname _ _
return the " unmangled " name .""" | if name . startswith ( classname ) and name [ - 2 : ] != '__' :
return name [ len ( classname ) - 2 : ]
return name |
def loopalt_gtd ( time : datetime , glat : Union [ float , np . ndarray ] , glon : Union [ float , np . ndarray ] , altkm : Union [ float , List [ float ] , np . ndarray ] , * , f107a : float = None , f107 : float = None , Ap : int = None ) -> xarray . Dataset :
"""loop over location and time
time : datetime or n... | glat = np . atleast_2d ( glat )
glon = np . atleast_2d ( glon )
assert glat . ndim == glon . ndim == 2
times = np . atleast_1d ( time )
assert times . ndim == 1
atmos = xarray . Dataset ( )
for k , t in enumerate ( times ) :
print ( 'computing' , t )
for i in range ( glat . shape [ 0 ] ) :
for j in rang... |
def wavenumber ( src , rec , depth , res , freq , wavenumber , ab = 11 , aniso = None , epermH = None , epermV = None , mpermH = None , mpermV = None , verb = 2 ) :
r"""Depreciated . Use ` dipole _ k ` instead .""" | # Issue warning
mesg = ( "\n The use of `model.wavenumber` is deprecated and will " + "be removed;\n use `model.dipole_k` instead." )
warnings . warn ( mesg , DeprecationWarning )
return dipole_k ( src , rec , depth , res , freq , wavenumber , ab , aniso , epermH , epermV , mpermH , mpermV , verb ) |
def retrieve_split_adjustment_data_for_sid ( self , dates , sid , split_adjusted_asof_idx ) :
"""dates : pd . DatetimeIndex
The calendar dates .
sid : int
The sid for which we want to retrieve adjustments .
split _ adjusted _ asof _ idx : int
The index in ` dates ` as - of which the data is split adjusted... | adjustments = self . _split_adjustments . get_adjustments_for_sid ( 'splits' , sid )
sorted ( adjustments , key = lambda adj : adj [ 0 ] )
# Get rid of any adjustments that happen outside of our date index .
adjustments = list ( filter ( lambda x : dates [ 0 ] <= x [ 0 ] <= dates [ - 1 ] , adjustments ) )
adjustment_va... |
def get_all_tags_of_recurring ( self , recurring_id ) :
"""Get all tags of recurring
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param recurring _ id : the recurring id
: return : list""" | return self . _iterate_through_pages ( get_function = self . get_tags_of_recurring_per_page , resource = RECURRING_TAGS , ** { 'recurring_id' : recurring_id } ) |
def _get ( self , resource , payload = None ) :
'''Wrapper around requests . get that shorten caller url and takes care
of errors''' | # Avoid dangerous default function argument ` { } `
payload = payload or { }
# Build the request and return json response
return requests . get ( '{}/{}/{}' . format ( self . master , pyconsul . __consul_api_version__ , resource ) , params = payload ) |
def from_location ( cls , location ) :
"""Try to create a Ladybug location from a location string .
Args :
locationString : Location string
Usage :
l = Location . from _ location ( locationString )""" | if not location :
return cls ( )
try :
if hasattr ( location , 'isLocation' ) : # Ladybug location
return location
elif hasattr ( location , 'Latitude' ) : # Revit ' s location
return cls ( city = str ( location . Name . replace ( "," , " " ) ) , latitude = location . Latitude , longitude = ... |
def _prepare_instance_properties ( self , properties , factory_properties ) : # type : ( dict , dict ) - > dict
"""Prepares the properties of a component instance , based on its
configuration , factory and framework properties
: param properties : Component instance properties
: param factory _ properties : C... | # Normalize given properties
if properties is None or not isinstance ( properties , dict ) :
properties = { }
# Use framework properties to fill missing ones
framework = self . __context . get_framework ( )
for property_name in factory_properties :
if property_name not in properties : # Missing property
... |
def main ( ) :
"""Run the program .""" | args = parse_arguments ( )
ext = os . path . splitext ( args . input_file ) [ - 1 ] . lower ( )
with gzip . open ( args . output_file , mode = 'wt' ) as outfile :
csvwriter = csv . writer ( outfile , delimiter = str ( '\t' ) , lineterminator = '\n' )
try :
if ext in ( '.tab' , '.txt' , '.tsv' ) :
... |
def alter ( self , id_environment_vip , finalidade_txt , cliente_txt , ambiente_p44_txt , description ) :
"""Change Environment VIP from by the identifier .
: param id _ environment _ vip : Identifier of the Environment VIP . Integer value and greater than zero .
: param finalidade _ txt : Finality . String wit... | if not is_valid_int_param ( id_environment_vip ) :
raise InvalidParameterError ( u'The identifier of Environment VIP is invalid or was not informed.' )
environmentvip_map = dict ( )
environmentvip_map [ 'finalidade_txt' ] = finalidade_txt
environmentvip_map [ 'cliente_txt' ] = cliente_txt
environmentvip_map [ 'ambi... |
def condensed_coords_within ( pop , n ) :
"""Return indices into a condensed distance matrix for all
pairwise comparisons within the given population .
Parameters
pop : array _ like , int
Indices of samples or haplotypes within the population .
n : int
Size of the square matrix ( length of first or seco... | return [ condensed_coords ( i , j , n ) for i , j in itertools . combinations ( sorted ( pop ) , 2 ) ] |
def export_node ( bpmn_graph , export_elements , node , nodes_classification , order = 0 , prefix = "" , condition = "" , who = "" , add_join = False ) :
"""General method for node exporting
: param bpmn _ graph : an instance of BpmnDiagramGraph class ,
: param export _ elements : a dictionary object . The key ... | node_type = node [ 1 ] [ consts . Consts . type ]
if node_type == consts . Consts . start_event :
return BpmnDiagramGraphCsvExport . export_start_event ( bpmn_graph , export_elements , node , nodes_classification , order = order , prefix = prefix , condition = condition , who = who )
elif node_type == consts . Cons... |
def check_xsrf_cookie ( self ) -> None :
"""Verifies that the ` ` _ xsrf ` ` cookie matches the ` ` _ xsrf ` ` argument .
To prevent cross - site request forgery , we set an ` ` _ xsrf ` `
cookie and include the same value as a non - cookie
field with all ` ` POST ` ` requests . If the two do not match , we
... | # Prior to release 1.1.1 , this check was ignored if the HTTP header
# ` ` X - Requested - With : XMLHTTPRequest ` ` was present . This exception
# has been shown to be insecure and has been removed . For more
# information please see
# http : / / www . djangoproject . com / weblog / 2011 / feb / 08 / security /
# http... |
def _from_dict ( cls , _dict ) :
"""Initialize a DialogSuggestionValue object from a json dictionary .""" | args = { }
if 'input' in _dict :
args [ 'input' ] = MessageInput . _from_dict ( _dict . get ( 'input' ) )
if 'intents' in _dict :
args [ 'intents' ] = [ RuntimeIntent . _from_dict ( x ) for x in ( _dict . get ( 'intents' ) ) ]
if 'entities' in _dict :
args [ 'entities' ] = [ RuntimeEntity . _from_dict ( x )... |
def html_factory ( tag , ** defaults ) :
'''Returns an : class : ` Html ` factory function for ` ` tag ` ` and a given
dictionary of ` ` defaults ` ` parameters . For example : :
> > > input _ factory = html _ factory ( ' input ' , type = ' text ' )
> > > html = input _ factory ( value = ' bla ' )''' | def html_input ( * children , ** params ) :
p = defaults . copy ( )
p . update ( params )
return Html ( tag , * children , ** p )
return html_input |
def save_asset ( self , asset_form , * args , ** kwargs ) :
"""Pass through to provider AssetAdminSession . update _ asset""" | # Implemented from kitosid template for -
# osid . resource . ResourceAdminSession . update _ resource
if asset_form . is_for_update ( ) :
return self . update_asset ( asset_form , * args , ** kwargs )
else :
return self . create_asset ( asset_form , * args , ** kwargs ) |
def store ( auth , provider , config_location = DEFAULT_CONFIG_DIR ) :
"""Store auth info in file for specified provider""" | auth_file = None
try : # only for custom locations
_create_config_dir ( config_location , "Creating custom config directory [%s]... " )
config_dir = os . path . join ( config_location , NOIPY_CONFIG )
_create_config_dir ( config_dir , "Creating directory [%s]... " )
auth_file = os . path . join ( config... |
def safe_print ( msg ) :
"""Safely print a given Unicode string to stdout ,
possibly replacing characters non - printable
in the current stdout encoding .
: param string msg : the message""" | try :
print ( msg )
except UnicodeEncodeError :
try : # NOTE encoding and decoding so that in Python 3 no b " . . . " is printed
encoded = msg . encode ( sys . stdout . encoding , "replace" )
decoded = encoded . decode ( sys . stdout . encoding , "replace" )
print ( decoded )
except ... |
def _showItemContextMenu ( self , item , point , col ) :
"""Callback for contextMenuRequested ( ) signal . Pops up item menu , if defined""" | self . _startOrStopEditing ( )
menu = getattr ( item , '_menu' , None )
if menu : # self . _ current _ item tells callbacks what item the menu was referring to
self . _current_item = item
self . clearSelection ( )
self . setItemSelected ( item , True )
menu . exec_ ( point )
else :
self . _current_i... |
def create_ca ( self , name , ca_name = '' , cert_type = crypto . TYPE_RSA , bits = 2048 , alt_names = None , years = 5 , serial = 0 , pathlen = 0 , overwrite = False ) :
"""Create a certificate authority
Arguments : name - The name of the CA
cert _ type - The type of the cert . TYPE _ RSA or TYPE _ DSA
bits ... | cakey = self . create_key_pair ( cert_type , bits )
req = self . create_request ( cakey , CN = name )
signing_key = cakey
signing_cert = req
parent_ca = ''
if ca_name :
ca_bundle = self . store . get_files ( ca_name )
signing_key = ca_bundle . key . load ( )
signing_cert = ca_bundle . cert . load ( )
pa... |
def toggle_tbstyle ( self , button ) :
"""Toogle the ToolButtonStyle of the given button between : data : ` ToolButtonIconOnly ` and : data : ` ToolButtonTextBesideIcon `
: param button : a tool button
: type button : : class : ` QtGui . QToolButton `
: returns : None
: rtype : None
: raises : None""" | old = button . toolButtonStyle ( )
if old == QtCore . Qt . ToolButtonIconOnly :
new = QtCore . Qt . ToolButtonTextBesideIcon
else :
new = QtCore . Qt . ToolButtonIconOnly
button . setToolButtonStyle ( new ) |
def create_new ( cls , mapreduce_id , shard_number ) :
"""Create new shard state .
Args :
mapreduce _ id : unique mapreduce id as string .
shard _ number : shard number for which to create shard state .
Returns :
new instance of ShardState ready to put into datastore .""" | shard_id = cls . shard_id_from_number ( mapreduce_id , shard_number )
state = cls ( key_name = shard_id , mapreduce_id = mapreduce_id )
return state |
def start ( component , exact ) : # type : ( str , str ) - > None
"""Create a new release branch .
Args :
component ( str ) :
Version component to bump when creating the release . Can be * major * ,
* minor * or * patch * .
exact ( str ) :
The exact version to set for the release . Overrides the compone... | version_file = conf . get_path ( 'version_file' , 'VERSION' )
develop = conf . get ( 'git.devel_branch' , 'develop' )
common . assert_on_branch ( develop )
with conf . within_proj_dir ( ) :
out = shell . run ( 'git status --porcelain' , capture = True ) . stdout
lines = out . split ( os . linesep )
has_chan... |
def find_key ( self , regex ) :
"""Attempts to find a single S3 key based on the passed regex
Given a regular expression , this method searches the S3 bucket
for a matching key , and returns it if exactly 1 key matches .
Otherwise , None is returned .
: param regex : ( str ) Regular expression for an S3 key... | log = logging . getLogger ( self . cls_logger + '.find_key' )
if not isinstance ( regex , basestring ) :
log . error ( 'regex argument is not a string' )
return None
log . info ( 'Looking up a single S3 key based on regex: %s' , regex )
matched_keys = [ ]
for item in self . bucket . objects . all ( ) :
log ... |
def _name_things ( self ) :
"""Easy names for debugging""" | edges = { }
nodes = { None : 'root' }
for n in self . _tree . postorder_node_iter ( ) :
nodes [ n ] = '.' . join ( [ str ( x . taxon ) for x in n . leaf_nodes ( ) ] )
for e in self . _tree . preorder_edge_iter ( ) :
edges [ e ] = ' ---> ' . join ( [ nodes [ e . tail_node ] , nodes [ e . head_node ] ] )
r_edges ... |
def seek ( self , partition , offset ) :
"""Manually specify the fetch offset for a TopicPartition .
Overrides the fetch offsets that the consumer will use on the next
: meth : ` ~ kafka . KafkaConsumer . poll ` . If this API is invoked for the same
partition more than once , the latest offset will be used on... | if not isinstance ( partition , TopicPartition ) :
raise TypeError ( 'partition must be a TopicPartition namedtuple' )
assert isinstance ( offset , int ) and offset >= 0 , 'Offset must be >= 0'
assert partition in self . _subscription . assigned_partitions ( ) , 'Unassigned partition'
log . debug ( "Seeking to offs... |
def solve ( self ) :
"""Solve the pair .""" | cycle = [ "FR" , "RB" , "BL" , "LF" ]
combine = self . combine ( )
put = Formula ( Step ( "y" ) * cycle . index ( self . pair ) or [ ] )
self . cube ( put )
self . pair = "FR"
estimated = self . estimated_position ( )
for U_act in [ Formula ( ) , Formula ( "U" ) , Formula ( "U2" ) , Formula ( "U'" ) ] :
self . cube... |
def fill_sampling ( slice_list , N ) :
"""Given a list of slices , draw N samples such that each slice contributes as much as possible
Parameters
slice _ list : list of Slice
List of slices
N : int
Number of samples to draw""" | A = [ len ( s . inliers ) for s in slice_list ]
N_max = np . sum ( A )
if N > N_max :
raise ValueError ( "Tried to draw {:d} samples from a pool of only {:d} items" . format ( N , N_max ) )
samples_from = np . zeros ( ( len ( A ) , ) , dtype = 'int' )
# Number of samples to draw from each group
remaining = N
while ... |
def validate ( self ) :
"""Base validation + each cell is instance of DSM or MDM .""" | super ( ) . validate ( )
message_dsm = 'Matrix at [%s:%s] is not an instance of ' 'DesignStructureMatrix or MultipleDomainMatrix.'
message_ddm = 'Matrix at [%s:%s] is not an instance of ' 'DomainMappingMatrix or MultipleDomainMatrix.'
messages = [ ]
for i , row in enumerate ( self . data ) :
for j , cell in enumera... |
def function_from_string ( func_string ) :
"""Returns a function object from the function string .
: param the string which needs to be resolved .""" | func = None
func_string_splitted = func_string . split ( '.' )
module_name = '.' . join ( func_string_splitted [ : - 1 ] )
function_name = func_string_splitted [ - 1 ]
module = import_module ( module_name )
if module and function_name :
func = getattr ( module , function_name )
return func |
async def main ( ) :
"""Main class .""" | opts , args = option_parser ( )
url = args [ 0 ]
if opts . links :
getlinks ( url )
raise SystemExit ( 0 )
depth = opts . depth
sTime = time . time ( )
webcrawler = Webcrawler ( url , depth )
webcrawler . crawl ( )
eTime = time . time ( )
tTime = eTime - sTime
print ( "CRAWLER STARTED:" )
print ( "%s, will craw... |
def is_network_source_fw ( cls , nwk , nwk_name ) :
"""Check if SOURCE is FIREWALL , if yes return TRUE .
If source is None or entry not in NWK DB , check from Name .
Name should have constant AND length should match .""" | if nwk is not None :
if nwk . source == fw_const . FW_CONST :
return True
return False
if nwk_name in fw_const . DUMMY_SERVICE_NWK and ( len ( nwk_name ) == len ( fw_const . DUMMY_SERVICE_NWK ) + fw_const . SERVICE_NAME_EXTRA_LEN ) :
return True
if nwk_name in fw_const . IN_SERVICE_NWK and ( len ( n... |
def sorted_outrows ( outrows ) : # type : ( Iterable [ InstalledCSVRow ] ) - > List [ InstalledCSVRow ]
"""Return the given rows of a RECORD file in sorted order .
Each row is a 3 - tuple ( path , hash , size ) and corresponds to a record of
a RECORD file ( see PEP 376 and PEP 427 for details ) . For the rows
... | # Normally , there should only be one row per path , in which case the
# second and third elements don ' t come into play when sorting .
# However , in cases in the wild where a path might happen to occur twice ,
# we don ' t want the sort operation to trigger an error ( but still want
# determinism ) . Since the third... |
def _compute_standard_dev ( self , rup , imt , C ) :
"""Compute the the standard deviation in terms of magnitude
described on page 744 , eq . 4""" | sigma_mean = 0.
if imt . name in "SA PGA" :
psi = - 6.898E-3
else :
psi = - 3.054E-5
if rup . mag <= 6.5 :
sigma_mean = ( C [ 'c12' ] * rup . mag ) + C [ 'c13' ]
elif rup . mag > 6.5 :
sigma_mean = ( psi * rup . mag ) + C [ 'c14' ]
return sigma_mean |
def mac_address_table_static_mac_address ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
mac_address_table = ET . SubElement ( config , "mac-address-table" , xmlns = "urn:brocade.com:mgmt:brocade-mac-address-table" )
static = ET . SubElement ( mac_address_table , "static" )
forward_key = ET . SubElement ( static , "forward" )
forward_key . text = kwargs . pop ( 'forward' ... |
def get_icohp_dict_of_site ( self , site , minsummedicohp = None , maxsummedicohp = None , minbondlength = 0.0 , maxbondlength = 8.0 , only_bonds_to = None ) :
"""get a dict of IcohpValue for a certain site ( indicated by integer )
Args :
site : integer describing the site of interest , order as in Icohplist . ... | newicohp_dict = { }
for key , value in self . _icohplist . items ( ) :
atomnumber1 = int ( re . split ( r'(\d+)' , value . _atom1 ) [ 1 ] ) - 1
atomnumber2 = int ( re . split ( r'(\d+)' , value . _atom2 ) [ 1 ] ) - 1
if site == atomnumber1 or site == atomnumber2 : # manipulate order of atoms so that searche... |
def load_from_string ( self , content , container , ** kwargs ) :
"""Load config from given string ' content ' .
: param content : Config content string
: param container : callble to make a container object later
: param kwargs : optional keyword parameters to be sanitized : : dict
: return : Dict - like o... | _not_implemented ( self , content , container , ** kwargs ) |
def doi_to_wos ( wosclient , doi ) :
"""Convert DOI to WOS identifier .""" | results = query ( wosclient , 'DO="%s"' % doi , './REC/UID' , count = 1 )
return results [ 0 ] . lstrip ( 'WOS:' ) if results else None |
def __skip_this ( self , level ) :
"""Check whether this comparison should be skipped because one of the objects to compare meets exclusion criteria .
: rtype : bool""" | skip = False
if self . exclude_paths and level . path ( ) in self . exclude_paths :
skip = True
elif self . exclude_regex_paths and any ( [ exclude_regex_path . search ( level . path ( ) ) for exclude_regex_path in self . exclude_regex_paths ] ) :
skip = True
else :
if self . exclude_types_tuple and ( isins... |
def get_screen_density ( self ) -> str :
'''Show device screen density ( PPI ) .''' | output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'wm' , 'density' )
return output . split ( ) [ 2 ] |
def GetServices ( ) :
"""Obtains all the connected eDNA services .
: return : A pandas DataFrame of connected eDNA services in the form [ Name ,
Description , Type , Status ]""" | # Define all required variables in the correct ctypes format
pulKey = c_ulong ( 0 )
szType = c_char_p ( "" . encode ( 'utf-8' ) )
szStartSvcName = c_char_p ( "" . encode ( 'utf-8' ) )
szSvcName , szSvcDesc = create_string_buffer ( 30 ) , create_string_buffer ( 90 )
szSvcType , szSvcStat = create_string_buffer ( 30 ) , ... |
def cut ( self , bits , start = None , end = None , count = None ) :
"""Return bitstring generator by cutting into bits sized chunks .
bits - - The size in bits of the bitstring chunks to generate .
start - - The bit position to start the first cut . Defaults to 0.
end - - The bit position one past the last b... | start , end = self . _validate_slice ( start , end )
if count is not None and count < 0 :
raise ValueError ( "Cannot cut - count must be >= 0." )
if bits <= 0 :
raise ValueError ( "Cannot cut - bits must be >= 0." )
c = 0
while count is None or c < count :
c += 1
nextchunk = self . _slice ( start , min ... |
def trace_error ( function_index = 2 ) :
"""This will return the line number and line text of the last error
: param function _ index : int to tell what frame to look from
: return : int , str of the line number and line text""" | info = function_info ( function_index )
traces = traceback . format_stack ( limit = 10 )
for trace in traces :
file_ , line_number , line_text = trace . split ( ',' , 2 )
if file_ == ' File "%s"' % info [ 'file' ] and line_number != 'line %s' % info [ 'line_number' ] :
return line_number . split ( ) [ ... |
def get_minimum ( self ) :
'''Return
( t1 , t2 , value ) triple where the value is the minimal one .''' | return ( self . _min_value_t1 , self . _min_value_t2 , self . _min_value , self . _min_value_data ) |
def bibtex_run ( self ) :
'''Start bibtex run .''' | self . log . info ( 'Running bibtex...' )
try :
with open ( os . devnull , 'w' ) as null :
Popen ( [ 'bibtex' , self . project_name ] , stdout = null ) . wait ( )
except OSError :
self . log . error ( NO_LATEX_ERROR % 'bibtex' )
sys . exit ( 1 )
shutil . copy ( '%s.bib' % self . bib_file , '%s.bib.o... |
def uninstall_all_passbands ( local = True ) :
"""Uninstall all passbands , either globally or locally ( need to call twice to
delete ALL passbands )
If local = False , you must have permission to access the installation directory""" | pbdir = _pbdir_local if local else _pbdir_global
for f in os . listdir ( pbdir ) :
pbpath = os . path . join ( pbdir , f )
logger . warning ( "deleting file: {}" . format ( pbpath ) )
os . remove ( pbpath ) |
def create_order ( self , debtor , is_vat_included = True , due_date = None , heading = '' , text_line1 = '' , text_line2 = '' , debtor_data = None , delivery_data = None , products = None , project = None , other_reference = '' , model = models . Order , ** extra ) :
"""Create a new Order .
Args :
debtor ( Deb... | debtor_data = debtor_data or { }
delivery_data = delivery_data or { }
delivery_date = delivery_data . get ( 'date' , datetime . datetime . now ( ) )
our_reference = extra . get ( 'our_reference' , debtor . our_reference )
currency = extra . get ( 'currency' , debtor . currency )
layout = extra . get ( 'layout' , debtor... |
def set_configs ( self , key , d ) :
"""Set the whole configuration for a key""" | if '_config' in self . proxy :
self . proxy [ '_config' ] [ key ] = d
else :
self . proxy [ '_config' ] = { key : d } |
def _make_parameters ( self ) :
"""Converts a list of Parameters into DEAP format .""" | self . value_means = [ ]
self . value_ranges = [ ]
self . arrangement = [ ]
self . variable_parameters = [ ]
current_var = 0
for parameter in self . parameters :
if parameter . type == ParameterType . DYNAMIC :
self . value_means . append ( parameter . value [ 0 ] )
if parameter . value [ 1 ] < 0 :
... |
def choose ( self , context_ms = None ) :
"""Returns a point chosen by the interest model""" | try :
if self . context_mode is None :
x = self . interest_model . sample ( )
else :
if self . context_mode [ "mode" ] == 'mdmsds' :
if self . expl_dims == self . conf . s_dims :
x = np . hstack ( ( context_ms [ self . conf . m_ndims // 2 : ] , self . interest_model .... |
def tune_learning_rate ( self , h , parameter_list = None ) :
"""Naive tuning of the the learning rate on the in - sample data
Parameters
h : int
How many steps to run Aggregate on
parameter _ list : list
List of parameters to search for a good learning rate over
Returns
- Void ( changes self . learni... | if parameter_list is None :
parameter_list = [ 0.001 , 0.01 , 0.1 , 1.0 , 10.0 , 100.0 , 1000.0 , 10000.0 , 100000.0 ]
for parameter in parameter_list :
self . learning_rate = parameter
_ , losses , _ = self . run ( h , recalculate = False )
loss = losses [ 0 ]
if parameter == parameter_list [ 0 ] :... |
def server_call ( method , server , timeout = DEFAULT_TIMEOUT , verify_ssl = True , ** parameters ) :
"""Makes a call to an un - authenticated method on a server
: param method : The method name .
: type method : str
: param server : The MyGeotab server .
: type server : str
: param timeout : The timeout ... | if method is None :
raise Exception ( "A method name must be specified" )
if server is None :
raise Exception ( "A server (eg. my3.geotab.com) must be specified" )
parameters = process_parameters ( parameters )
return _query ( server , method , parameters , timeout = timeout , verify_ssl = verify_ssl ) |
def to_bytes ( self ) :
'''Create bytes from properties''' | # Verify that properties make sense
self . sanitize ( )
# Start with the type
bitstream = BitArray ( 'uint:4=%d' % self . message_type )
# Add the flags
bitstream += BitArray ( 'bool=%d, bool=%d, bool=%d' % ( self . probe , self . enlra_enabled , self . security ) )
# Add padding
bitstream += self . _reserved1
# Add re... |
def ekopr ( fname ) :
"""Open an existing E - kernel file for reading .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ekopr _ c . html
: param fname : Name of EK file .
: type fname : str
: return : Handle attached to EK file .
: rtype : int""" | fname = stypes . stringToCharP ( fname )
handle = ctypes . c_int ( )
libspice . ekopr_c ( fname , ctypes . byref ( handle ) )
return handle . value |
def create_service_key ( self , service_name , key_name ) :
"""Create a service key for the given service .""" | if self . has_key ( service_name , key_name ) :
logging . warning ( "Reusing existing service key %s" % ( key_name ) )
return self . get_service_key ( service_name , key_name )
body = { 'service_instance_guid' : self . get_instance_guid ( service_name ) , 'name' : key_name }
return self . api . post ( '/v2/serv... |
def maxsize ( self , size ) :
"""Resize the cache , evicting the oldest items if necessary .""" | if size < 0 :
raise ValueError ( 'maxsize must be non-negative' )
with self . _lock :
self . _enforce_size_limit ( size )
self . _maxsize = size |
def is_maximal_matching ( G , matching ) :
"""Determines whether the given set of edges is a maximal matching .
A matching is a subset of edges in which no node occurs more than
once . The cardinality of a matching is the number of matched edges .
A maximal matching is one where one cannot add any more edges ... | touched_nodes = set ( ) . union ( * matching )
# first check if a matching
if len ( touched_nodes ) != len ( matching ) * 2 :
return False
# now for each edge , check that at least one of its variables is
# already in the matching
for ( u , v ) in G . edges :
if u not in touched_nodes and v not in touched_nodes... |
def filter ( self , func ) :
""": param func :
: type func : ( K , T ) - > bool
: rtype : TList [ T ]
Usage :
> > > TDict ( k1 = 1 , k2 = 2 , k3 = 3 ) . filter ( lambda k , v : v < 2)""" | return TList ( [ v for k , v in self . items ( ) if func ( k , v ) ] ) |
def _compute ( self , data ) :
"""Perform the calculation .""" | local_ts = self . _local_ts ( * data )
dt = local_ts [ internal_names . TIME_WEIGHTS_STR ]
# Convert dt to units of days to prevent overflow
dt = dt / np . timedelta64 ( 1 , 'D' )
return local_ts , dt |
def _merge_pool_kwargs ( self , override ) :
"""Merge a dictionary of override values for self . connection _ pool _ kw .
This does not modify self . connection _ pool _ kw and returns a new dict .
Any keys in the override dictionary with a value of ` ` None ` ` are
removed from the merged dictionary .""" | base_pool_kwargs = self . connection_pool_kw . copy ( )
if override :
for key , value in override . items ( ) :
if value is None :
try :
del base_pool_kwargs [ key ]
except KeyError :
pass
else :
base_pool_kwargs [ key ] = value
ret... |
def parse_changes ( ) :
"""grab version from CHANGES and validate entry""" | with open ( 'CHANGES' ) as changes :
for match in re . finditer ( RE_CHANGES , changes . read ( 1024 ) , re . M ) :
if len ( match . group ( 1 ) ) != len ( match . group ( 3 ) ) :
error ( 'incorrect underline in CHANGES' )
date = datetime . datetime . strptime ( match . group ( 4 ) , '%Y... |
def dimap ( D , I ) :
"""Function to map directions to x , y pairs in equal area projection
Parameters
D : list or array of declinations ( as float )
I : list or array or inclinations ( as float )
Returns
XY : x , y values of directions for equal area projection [ x , y ]""" | try :
D = float ( D )
I = float ( I )
except TypeError : # is an array
return dimap_V ( D , I )
# DEFINE FUNCTION VARIABLES
# initialize equal area projection x , y
XY = [ 0. , 0. ]
# GET CARTESIAN COMPONENTS OF INPUT DIRECTION
X = dir2cart ( [ D , I , 1. ] )
# CHECK IF Z = 1 AND ABORT
if X [ 2 ] == 1.0 :
... |
def get_bool ( self , key , default = None ) :
"""Args :
key ( str | unicode ) : Key to lookup
default ( bool | None ) : Default to use if key is not configured
Returns :
( bool | None ) : Value of key , if defined""" | value = self . get_str ( key )
if value is not None :
return to_boolean ( value )
return default |
def get_shared_nodes ( G1 : nx . DiGraph , G2 : nx . DiGraph ) -> List [ str ] :
"""Get all the nodes that are common to both networks .""" | return list ( set ( G1 . nodes ( ) ) . intersection ( set ( G2 . nodes ( ) ) ) ) |
def get_minimal_id ( self ) :
"""Returns the minimal tweet ID of the current response
: returns : minimal tweet identification number
: raises : TwitterSearchException""" | if not self . __response :
raise TwitterSearchException ( 1013 )
return min ( self . __response [ 'content' ] [ 'statuses' ] if self . __order_is_search else self . __response [ 'content' ] , key = lambda i : i [ 'id' ] ) [ 'id' ] - 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.