signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _shorten_url ( self , text ) :
'''Shorten a URL and make sure to not cut of html entities .''' | if len ( text ) > self . _max_url_length and self . _max_url_length != - 1 :
text = text [ 0 : self . _max_url_length - 3 ]
amp = text . rfind ( '&' )
close = text . rfind ( ';' )
if amp != - 1 and ( close == - 1 or close < amp ) :
text = text [ 0 : amp ]
return text + '...'
else :
retur... |
def getStreamNetworkAsWkt ( self , session , withNodes = True ) :
"""Retrieve the stream network geometry in Well Known Text format .
Args :
session ( : mod : ` sqlalchemy . orm . session . Session ` ) : SQLAlchemy session object bound to PostGIS enabled database
withNodes ( bool , optional ) : Include nodes ... | wkt_list = [ ]
for link in self . streamLinks :
wkt_link = link . getAsWkt ( session )
if wkt_link :
wkt_list . append ( wkt_link )
if withNodes :
for node in link . nodes :
wkt_node = node . getAsWkt ( session )
if wkt_node :
wkt_list . append ( wkt_n... |
def tostring ( self , inject ) :
"""Convert an element to a single string and allow the passed inject method to place content before any
element .""" | return inject ( self , '\n' . join ( f'{division.tostring(inject)}' for division in self . divisions ) ) |
def reload ( self , client = None ) :
"""Update this notification from the server configuration .
See :
https : / / cloud . google . com / storage / docs / json _ api / v1 / notifications / get
If : attr : ` user _ project ` is set on the bucket , bills the API request
to that project .
: type client : : ... | if self . notification_id is None :
raise ValueError ( "Notification not intialized by server" )
client = self . _require_client ( client )
query_params = { }
if self . bucket . user_project is not None :
query_params [ "userProject" ] = self . bucket . user_project
response = client . _connection . api_request... |
def com_google_fonts_check_name_rfn ( ttFont ) :
"""Name table strings must not contain the string ' Reserved Font Name ' .""" | failed = False
for entry in ttFont [ "name" ] . names :
string = entry . toUnicode ( )
if "reserved font name" in string . lower ( ) :
yield WARN , ( "Name table entry (\"{}\")" " contains \"Reserved Font Name\"." " This is an error except in a few specific" " rare cases." ) . format ( string )
... |
def get_lint_config ( config_path = None ) :
"""Tries loading the config from the given path . If no path is specified , the default config path
is tried , and if that is not specified , we the default config is returned .""" | # config path specified
if config_path :
config = LintConfig . load_from_file ( config_path )
click . echo ( "Using config from {0}" . format ( config_path ) )
# default config path
elif os . path . exists ( DEFAULT_CONFIG_FILE ) :
config = LintConfig . load_from_file ( DEFAULT_CONFIG_FILE )
click . ech... |
def load_fam ( self , pheno_covar = None ) :
"""Load contents from the . fam file , updating the pheno _ covar with family ids found .
: param pheno _ covar : Phenotype / covariate object
: return : None""" | logging . info ( "Loading file: %s" % ( self . fam_file ) )
pheno_col = 5
if not DataParser . has_sex :
pheno_col -= 1
if not DataParser . has_parents :
pheno_col -= 2
if not DataParser . has_fid :
pheno_col -= 1
sex_col = pheno_col - 1
mask_components = [ ]
for line in open ( self . fam_file ) :
words ... |
def is_valid_pid_for_create ( did ) :
"""Assert that ` ` did ` ` can be used as a PID for creating a new object with
MNStorage . create ( ) or MNStorage . update ( ) .""" | if not d1_gmn . app . did . is_valid_pid_for_create ( did ) :
raise d1_common . types . exceptions . IdentifierNotUnique ( 0 , 'Identifier is already in use as {}. did="{}"' . format ( d1_gmn . app . did . classify_identifier ( did ) , did ) , identifier = did , ) |
def get_log_config ( component , handlers , level = 'DEBUG' , path = '/var/log/vfine/' ) :
"""Return a log config for django project .""" | config = { 'version' : 1 , 'disable_existing_loggers' : False , 'formatters' : { 'standard' : { 'format' : '%(asctime)s [%(levelname)s][%(threadName)s]' + '[%(name)s.%(funcName)s():%(lineno)d] %(message)s' } , 'color' : { '()' : 'shaw.log.SplitColoredFormatter' , 'format' : "%(asctime)s " + "%(log_color)s%(bold)s[%(lev... |
def apply_patches ( self , arch , build_dir = None ) :
'''Apply any patches for the Recipe .
. . versionchanged : : 0.6.0
Add ability to apply patches from any dir via kwarg ` build _ dir `''' | if self . patches :
info_main ( 'Applying patches for {}[{}]' . format ( self . name , arch . arch ) )
if self . is_patched ( arch ) :
info_main ( '{} already patched, skipping' . format ( self . name ) )
return
build_dir = build_dir if build_dir else self . get_build_dir ( arch . arch )
... |
def update_vrf_table ( self , route_dist , prefix = None , next_hop = None , route_family = None , route_type = None , tunnel_type = None , is_withdraw = False , redundancy_mode = None , pmsi_tunnel_type = None , ** kwargs ) :
"""Update a BGP route in the VRF table identified by ` route _ dist `
with the given ` ... | from ryu . services . protocols . bgp . core import BgpCoreError
assert route_dist
if is_withdraw :
gen_lbl = False
next_hop = None
else :
gen_lbl = True
if not ( is_valid_ipv4 ( next_hop ) or is_valid_ipv6 ( next_hop ) ) :
raise BgpCoreError ( desc = 'Invalid IPv4/IPv6 nexthop: %s' % next_hop )... |
def pipe_fetchpage ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A source that fetches the content of a given web site as a string .
Loopable .
context : pipe2py . Context object
_ INPUT : pipeforever asyncPipe or an iterable of items or fields
conf : dict
URL - - url object contain th... | conf = DotDict ( conf )
split_token = conf . get ( 'token' , ** kwargs )
urls = utils . listize ( conf [ 'URL' ] )
for item in _INPUT :
for item_url in urls :
url = utils . get_value ( DotDict ( item_url ) , DotDict ( item ) , ** kwargs )
url = utils . get_abspath ( url )
if not url :
... |
def from_string ( cls , input_string , cls_ = None ) :
"""Initialize a ` Structure ` object from a string with data in XSF format .
Args :
input _ string : String with the structure in XSF format .
See http : / / www . xcrysden . org / doc / XSF . html
cls _ : Structure class to be created . default : pymat... | # CRYSTAL see ( 1)
# these are primitive lattice vectors ( in Angstroms )
# PRIMVEC
# 0.00000 2.7100000 2.7100000 see ( 2)
# 2.7100000 0.00000 2.7100000
# 2.7100000 2.7100000 0.00000
# these are conventional lattice vectors ( in Angstroms )
# CONVVEC
# 5.4200000 0.00000 0.00000 see ( 3)
# 0.00000 5.4200000 0.00000
# 0.... |
def select_transformers ( grid , s_max = None ) :
"""Selects LV transformer according to peak load of LV grid district .
The transformers are chosen according to max . of load case and feedin - case
considering load factors and power factor .
The MV - LV transformer with the next higher available nominal appa... | load_factor_lv_trans_lc_normal = cfg_ding0 . get ( 'assumptions' , 'load_factor_lv_trans_lc_normal' )
load_factor_lv_trans_fc_normal = cfg_ding0 . get ( 'assumptions' , 'load_factor_lv_trans_fc_normal' )
cos_phi_load = cfg_ding0 . get ( 'assumptions' , 'cos_phi_load' )
cos_phi_gen = cfg_ding0 . get ( 'assumptions' , 'c... |
def read_levels ( text ) :
"""Read text and get there reffs
: param text : Collection ( Readable )
: return :""" | x = [ ]
for i in range ( 0 , len ( NAUTILUSRESOLVER . getMetadata ( text ) . citation ) ) :
x . append ( NAUTILUSRESOLVER . getReffs ( text , level = i ) )
return x |
def load_ext ( self ) :
"""Read time series data like method | IOSequence . load _ ext | of class
| IOSequence | , but with special handling of missing data .
The method ' s " special handling " is to convert errors to warnings .
We explain the reasons in the documentation on method | Obs . load _ ext |
of ... | try :
super ( ) . load_ext ( )
except BaseException :
if hydpy . pub . options . warnmissingsimfile :
warnings . warn ( str ( sys . exc_info ( ) [ 1 ] ) ) |
def getJournalDeals ( self , start = None ) :
"""Return all journal events from start .""" | # 1 - utworzenie aktu zakupowego ( deala ) , 2 - utworzenie formularza pozakupowego ( karta platnosci ) , 3 - anulowanie formularza pozakupowego ( karta platnosci ) , 4 - zakończenie ( opłacenie ) transakcji przez PzA
if start is not None :
self . last_event_id = start
events = [ ]
while self . getJournalDealsInfo... |
def show_backends ( socket = DEFAULT_SOCKET_URL ) :
'''Show HaProxy Backends
socket
haproxy stats socket , default ` ` / var / run / haproxy . sock ` `
CLI Example :
. . code - block : : bash
salt ' * ' haproxy . show _ backends''' | ha_conn = _get_conn ( socket )
ha_cmd = haproxy . cmds . showBackends ( )
return ha_conn . sendCmd ( ha_cmd ) |
def _get_style_of_faulting_term ( self , C , rake ) :
"""Returns the style of faulting term . Cauzzi et al . determind SOF from
the plunge of the B - , T - and P - axes . For consistency with existing
GMPEs the Wells & Coppersmith model is preferred""" | if rake > - 150.0 and rake <= - 30.0 :
return C [ 'fN' ]
elif rake > 30.0 and rake <= 150.0 :
return C [ 'fR' ]
else :
return C [ 'fSS' ] |
def error_leader ( self , infile = None , lineno = None ) :
"Emit a C - compiler - like , Emacs - friendly error - message leader ." | if infile is None :
infile = self . infile
if lineno is None :
lineno = self . lineno
return "\"%s\", line %d: " % ( infile , lineno ) |
def put ( value ) :
"""Store an object in the object store .
Args :
value : The Python object to be stored .
Returns :
The object ID assigned to this value .""" | worker = global_worker
worker . check_connected ( )
with profiling . profile ( "ray.put" ) :
if worker . mode == LOCAL_MODE : # In LOCAL _ MODE , ray . put is the identity operation .
return value
object_id = ray . _raylet . compute_put_id ( worker . current_task_id , worker . task_context . put_index ,... |
def info ( self , cloud = None , api_key = None , version = None , ** kwargs ) :
"""Return the current state of the model associated with a given collection""" | url_params = { "batch" : False , "api_key" : api_key , "version" : version , "method" : "info" }
return self . _api_handler ( None , cloud = cloud , api = "custom" , url_params = url_params , ** kwargs ) |
def _parse_ssl_options ( options ) :
"""Parse ssl options .""" | use_ssl = options . get ( 'ssl' )
if use_ssl is not None :
validate_boolean ( 'ssl' , use_ssl )
certfile = options . get ( 'ssl_certfile' )
keyfile = options . get ( 'ssl_keyfile' )
passphrase = options . get ( 'ssl_pem_passphrase' )
ca_certs = options . get ( 'ssl_ca_certs' )
cert_reqs = options . get ( 'ssl_cert_... |
def source_lookup ( request ) :
"""JSON endpoint that returns a list of potential sources .
Used for upload template autocomplete .""" | source = request . GET [ 'source' ]
source_slug = slugify ( source . strip ( ) )
source_candidates = Dataset . objects . values ( 'source' ) . filter ( source_slug__startswith = source_slug )
sources = json . dumps ( [ cand [ 'source' ] for cand in source_candidates ] )
return HttpResponse ( sources , content_type = 'a... |
def setup_link ( self , interface , cidr ) :
"""Setup a link .
ip addr add dev interface
ip link set dev interface up""" | # clear old ipaddr in interface
cmd = [ 'ip' , 'addr' , 'flush' , 'dev' , interface ]
agent_utils . execute ( cmd , root = True )
ip = IPNetwork ( cidr )
cmd = [ 'ip' , 'addr' , 'add' , cidr , 'broadcast' , str ( ip . broadcast ) , 'dev' , interface ]
stdcode , stdout = agent_utils . execute ( cmd , root = True )
if st... |
def _log_message ( self , level , freerun_entry , msg ) :
"""method performs logging into log file and the freerun _ entry""" | self . logger . log ( level , msg )
assert isinstance ( freerun_entry , FreerunProcessEntry )
event_log = freerun_entry . event_log
if len ( event_log ) > MAX_NUMBER_OF_EVENTS :
del event_log [ - 1 ]
event_log . insert ( 0 , msg )
self . freerun_process_dao . update ( freerun_entry ) |
def _install_requirement ( python_bin : str , package : str , version : str = None , index_url : str = None , clean : bool = True ) -> None :
"""Install requirements specified using suggested pip binary .""" | previous_version = _pipdeptree ( python_bin , package )
try :
cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}" . format ( python_bin , quote ( package ) )
if version :
cmd += "=={}" . format ( quote ( version ) )
if index_url :
cmd += ' --index-url "{}" ' . format ( qu... |
def _wrap_measure ( individual_state_measure_process , state_measure , loaded_processes ) :
"""Creates a function on a state _ collection , which creates analysis _ collections for each state in the collection .
Optionally sorts the collection if the state _ measure has a sort _ by parameter ( see funtool . lib .... | def wrapped_measure ( state_collection , overriding_parameters = None , loggers = None ) :
if loggers == None :
loggers = funtool . logger . set_default_loggers ( )
if loaded_processes != None :
if state_measure . grouping_selectors != None :
for grouping_selector_name in state_measu... |
def dumpToGLIF ( self , glyphFormatVersion = 2 ) :
"""This will return the glyph ' s contents as a string in
` GLIF format < http : / / unifiedfontobject . org / versions / ufo3 / glyphs / glif / > ` _ .
> > > xml = glyph . writeGlyphToString ( )
` ` glyphFormatVersion ` ` must be a : ref : ` type - int ` tha... | glyphFormatVersion = normalizers . normalizeGlyphFormatVersion ( glyphFormatVersion )
return self . _dumpToGLIF ( glyphFormatVersion ) |
def load ( self , name = None , * args , ** kwargs ) :
"Load the instance of the object from the stash ." | inst = self . stash . load ( name )
if inst is None :
inst = self . instance ( name , * args , ** kwargs )
logger . debug ( f'loaded (conf mng) instance: {inst}' )
return inst |
def mine_block ( chain : MiningChain , ** kwargs : Any ) -> MiningChain :
"""Mine a new block on the chain . Header parameters for the new block can be
overridden using keyword arguments .""" | if not isinstance ( chain , MiningChain ) :
raise ValidationError ( '`mine_block` may only be used on MiningChain instances' )
chain . mine_block ( ** kwargs )
return chain |
def set_bytes_at_offset ( self , offset , data ) :
"""Overwrite the bytes at the given file offset with the given string .
Return True if successful , False otherwise . It can fail if the
offset is outside the file ' s boundaries .""" | if not isinstance ( data , bytes ) :
raise TypeError ( 'data should be of type: bytes' )
if 0 <= offset < len ( self . __data__ ) :
self . __data__ = ( self . __data__ [ : offset ] + data + self . __data__ [ offset + len ( data ) : ] )
else :
return False
return True |
def commit_check ( self , commands = "" , req_format = "text" ) :
"""Execute a commit check operation .
Purpose : This method will take in string of multiple commands ,
| and perform and ' commit check ' on the device to ensure
| the commands are syntactically correct . The response can
| be formatted as te... | if not commands :
raise InvalidCommandError ( 'No commands specified' )
clean_cmds = [ ]
for cmd in clean_lines ( commands ) :
clean_cmds . append ( cmd )
self . lock ( )
self . _session . load_configuration ( action = 'set' , config = clean_cmds )
# conn . validate ( ) DOES NOT return a parse - able xml tree ,... |
def read_float ( self , little_endian = True ) :
"""Read 4 bytes as a float value from the stream .
Args :
little _ endian ( bool ) : specify the endianness . ( Default ) Little endian .
Returns :
float :""" | if little_endian :
endian = "<"
else :
endian = ">"
return self . unpack ( "%sf" % endian , 4 ) |
def bgp_time_conversion ( bgp_uptime ) :
"""Convert string time to seconds .
Examples
00:14:23
00:13:40
00:00:21
00:00:13
00:00:49
1d11h
1d17h
1w0d
8w5d
1y28w
never""" | bgp_uptime = bgp_uptime . strip ( )
uptime_letters = set ( [ 'w' , 'h' , 'd' ] )
if 'never' in bgp_uptime :
return - 1
elif ':' in bgp_uptime :
times = bgp_uptime . split ( ":" )
times = [ int ( x ) for x in times ]
hours , minutes , seconds = times
return ( hours * 3600 ) + ( minutes * 60 ) + secon... |
def import_submodules ( package_name : str ) -> None :
"""Import all submodules under the given package .
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered .""" | importlib . invalidate_caches ( )
# For some reason , python doesn ' t always add this by default to your path , but you pretty much
# always want it when using ` - - include - package ` . And if it ' s already there , adding it again at
# the end won ' t hurt anything .
sys . path . append ( '.' )
# Import at top leve... |
def stop_server ( self ) :
"""Stop serving . Also stops the thread .""" | if self . rpc_server is not None :
try :
self . rpc_server . socket . shutdown ( socket . SHUT_RDWR )
except :
log . warning ( "Failed to shut down server socket" )
self . rpc_server . shutdown ( ) |
def register ( self , pattern , view = None ) :
'''Allow decorator - style construction of URL pattern lists .''' | if view is None :
return partial ( self . register , pattern )
self . patterns . append ( self . _make_url ( ( pattern , view ) ) )
return view |
def list ( self , from_ = values . unset , to = values . unset , date_created_on_or_before = values . unset , date_created_after = values . unset , limit = None , page_size = None ) :
"""Lists FaxInstance records from the API as a list .
Unlike stream ( ) , this operation is eager and will load ` limit ` records ... | return list ( self . stream ( from_ = from_ , to = to , date_created_on_or_before = date_created_on_or_before , date_created_after = date_created_after , limit = limit , page_size = page_size , ) ) |
def validate ( self , profile ) :
"""Check to see if any args are " missing " from profile .
Validate all args from install . json are in the profile . This can be helpful to validate
that any new args added to App are included in the profiles .
. . Note : : This method does not work with layout . json Apps .... | ij = self . load_install_json ( profile . get ( 'install_json' ) )
print ( '{}{}Profile: "{}".' . format ( c . Style . BRIGHT , c . Fore . BLUE , profile . get ( 'profile_name' ) ) )
for arg in self . profile_settings_args_install_json ( ij , None ) :
if profile . get ( 'args' , { } ) . get ( 'app' , { } ) . get ( ... |
def citations ( self ) :
"""Cited references as a : class : ` . Feature ` \ .
Returns
citations : : class : ` . Feature `""" | if hasattr ( self , 'citedReferences' ) :
return [ cr . ayjid for cr in self . citedReferences if cr is not None ]
return [ ] |
def layer_mapping ( self , mapping ) :
"""Return the mappings that are active in this layer
Parameters
mapping : aes
mappings in the ggplot call
Notes
Once computed the layer mappings are also stored
in self . _ active _ mapping""" | # For certain geoms , it is useful to be able to
# ignore the default aesthetics and only use those
# set in the layer
if self . inherit_aes :
aesthetics = defaults ( self . mapping , mapping )
else :
aesthetics = self . mapping
# drop aesthetic parameters or the calculated aesthetics
calculated = set ( get_cal... |
def to_datetime ( arg ) :
"""Tries to convert any type of argument to datetime
Args :
arg : datetime , date , or str . If " ? " , will be converted to 1970-1-1.
if 0 or " now " , will be converted to datetime . datetime . now ( )""" | if isinstance ( arg , datetime . datetime ) :
return arg
elif arg == 0 :
return datetime . datetime . now ( )
elif isinstance ( arg , str ) :
if arg == "now" :
arg = datetime . datetime . now ( )
elif arg == "?" :
arg = datetime . datetime ( 1970 , 1 , 1 )
else :
arg = str2dt... |
def by_geopoint ( self , lat , long ) :
"""Perform a Yelp Neighborhood API Search based on a geopoint .
Args :
lat - geopoint latitude
long - geopoint longitude""" | header , content = self . _http_request ( self . BASE_URL , lat = lat , long = long )
return json . loads ( content ) |
def time_str_to_minutes ( time_str ) :
"""通过时间字符串计算得到这是一天中第多少分钟
: param time _ str : eg : ' 11:10:00'
: return : int""" | time_arr = time_str . split ( ":" )
hours = int ( time_arr [ 0 ] )
minutes = int ( time_arr [ 1 ] )
return hours * 60 + minutes |
def get_welcome_response ( ) :
"""If we wanted to initialize the session to have some attributes we could
add those here""" | session_attributes = { }
card_title = "Welcome"
speech_output = "Welcome to the Alexa Skills Kit sample. " "Please tell me your favorite color by saying, " "my favorite color is red"
# If the user either does not reply to the welcome message or says something
# that is not understood , they will be prompted again with ... |
def get_csv_reader ( csvfile , dialect = csv . excel , encoding = "utf-8" , ** kwds ) :
"""Returns csv reader .""" | try : # pylint : disable = pointless - statement
unicode
return UnicodeReader ( csvfile , dialect = dialect , encoding = encoding , ** kwds )
except NameError :
return csv . reader ( csvfile , dialect = dialect , ** kwds ) |
def _client_builder ( self ) :
"""Build Elasticsearch client .""" | client_config = self . app . config . get ( 'SEARCH_CLIENT_CONFIG' ) or { }
client_config . setdefault ( 'hosts' , self . app . config . get ( 'SEARCH_ELASTIC_HOSTS' ) )
client_config . setdefault ( 'connection_class' , RequestsHttpConnection )
return Elasticsearch ( ** client_config ) |
def setAccessPolicyResponse ( self , pid , accessPolicy , serialVersion , vendorSpecific = None ) :
"""CNAuthorization . setAccessPolicy ( session , pid , accessPolicy , serialVersion ) →
boolean https : / / releases . dataone . org / online / api -
documentation - v2.0.1 / apis / CN _ APIs . html # CNAuthoriza... | mmp_dict = { 'serialVersion' : str ( serialVersion ) , 'accessPolicy' : ( 'accessPolicy.xml' , accessPolicy . toxml ( 'utf-8' ) ) , }
return self . PUT ( [ 'accessRules' , pid ] , fields = mmp_dict , headers = vendorSpecific ) |
def plot ( self , file_type ) :
"""Call file _ type plotting function .""" | samples = self . mod_data [ file_type ]
plot_title = file_types [ file_type ] [ 'title' ]
plot_func = file_types [ file_type ] [ 'plot_func' ]
plot_params = file_types [ file_type ] [ 'plot_params' ]
return plot_func ( samples , file_type , plot_title = plot_title , plot_params = plot_params ) |
def is_ip_filter ( ip , options = None ) :
'''Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address .''' | return is_ipv4_filter ( ip , options = options ) or is_ipv6_filter ( ip , options = options ) |
def call ( self , op_name , query = None , ** kwargs ) :
"""Make a request to a method in this client . The response data is
returned from this call as native Python data structures .
This method differs from just calling the client method directly
in the following ways :
* It automatically handles the pagi... | LOG . debug ( kwargs )
if query :
query = jmespath . compile ( query )
if self . _client . can_paginate ( op_name ) :
paginator = self . _client . get_paginator ( op_name )
results = paginator . paginate ( ** kwargs )
data = results . build_full_result ( )
else :
op = getattr ( self . _client , op_n... |
def _find_mocker ( symbol : str , context : 'torment.contexts.TestContext' ) -> Callable [ [ ] , bool ] :
'''Find method within the context that mocks symbol .
Given a symbol ( i . e . ` ` tornado . httpclient . AsyncHTTPClient . fetch ` ` ) , find
the shortest ` ` mock _ ` ` method that resembles the symbol . ... | components = [ ]
method = None
for component in symbol . split ( '.' ) :
components . append ( component . lower ( ) )
name = '_' . join ( [ 'mock' ] + components )
if hasattr ( context , name ) :
method = getattr ( context , name )
break
if method is None :
logger . warn ( 'no mocker fo... |
def from_csv ( cls , path : PathOrStr , csv_name : str , cols : IntsOrStrs = 0 , delimiter : str = None , header : str = 'infer' , processor : PreProcessors = None , ** kwargs ) -> 'ItemList' :
"""Create an ` ItemList ` in ` path ` from the inputs in the ` cols ` of ` path / csv _ name `""" | df = pd . read_csv ( Path ( path ) / csv_name , delimiter = delimiter , header = header )
return cls . from_df ( df , path = path , cols = cols , processor = processor , ** kwargs ) |
def resolve ( self , other : Type ) -> Optional [ Type ] :
"""See ` ` PlaceholderType . resolve ` `""" | if not isinstance ( other , NltkComplexType ) :
return None
expected_second = ComplexType ( NUMBER_TYPE , ComplexType ( ANY_TYPE , ComplexType ( ComplexType ( ANY_TYPE , ANY_TYPE ) , ANY_TYPE ) ) )
resolved_second = other . second . resolve ( expected_second )
if resolved_second is None :
return None
# The lamb... |
def monthly_clear_sky_conditions ( self ) :
"""A list of 12 monthly clear sky conditions that are used on the design days .""" | if self . _monthly_tau_diffuse is [ ] or self . _monthly_tau_beam is [ ] :
return [ OriginalClearSkyCondition ( i , 21 ) for i in xrange ( 1 , 13 ) ]
return [ RevisedClearSkyCondition ( i , 21 , x , y ) for i , x , y in zip ( list ( xrange ( 1 , 13 ) ) , self . _monthly_tau_beam , self . _monthly_tau_diffuse ) ] |
def get_control ( self ) :
"""Return the text widget ( or similar ) to give focus to""" | # page _ control is the widget used for paging
page_control = self . shellwidget . _page_control
if page_control and page_control . isVisible ( ) :
return page_control
else :
return self . shellwidget . _control |
def spielman_wr ( self , norm = True ) :
"""Returns a list of site - specific omega values calculated from the ` ExpCM ` .
Args :
` norm ` ( bool )
If ` True ` , normalize the ` omega _ r ` values by the ExpCM
gene - wide ` omega ` .
Returns :
` wr ` ( list )
list of ` omega _ r ` values of length ` n... | wr = [ ]
for r in range ( self . nsites ) :
num = 0
den = 0
for i in range ( N_CODON ) :
j = scipy . intersect1d ( scipy . where ( CODON_SINGLEMUT [ i ] == True ) [ 0 ] , scipy . where ( CODON_NONSYN [ i ] == True ) [ 0 ] )
p_i = self . stationarystate [ r ] [ i ]
P_xy = self . Prxy ... |
def raise_error ( e ) :
"""Take a bravado - core Error model and raise it as an exception""" | code = e . error
if code in code_to_class :
raise code_to_class [ code ] ( e . error_description )
else :
raise InternalServerError ( e . error_description ) |
def extract_now_state ( self ) :
'''Extract now map state .
Returns :
` np . ndarray ` of state .''' | x , y = self . __agent_pos
state_arr = np . zeros ( self . __map_arr . shape )
state_arr [ x , y ] = 1
return np . expand_dims ( state_arr , axis = 0 ) |
def shutdown ( self , reason = ConnectionClosed ( ) ) :
"""Shutdown the socket server .
The socket server will stop accepting incoming connections .
All connections will be dropped .""" | if self . _shutdown :
raise ShutdownError ( )
self . stop ( )
self . _closing = True
for connection in self . connections :
connection . close ( )
self . connections = set ( )
self . _shutdown = True
if isinstance ( reason , ConnectionClosed ) :
logger . info ( "server shutdown" )
else :
logger . warn (... |
def to_hostnames_list ( ref , tab ) : # pragma : no cover , to be deprecated ?
"""Convert Host list into a list of host _ name
: param ref : Not used
: type ref :
: param tab : Host list
: type tab : list [ alignak . objects . host . Host ]
: return : host _ name list
: rtype : list""" | res = [ ]
for host in tab :
if hasattr ( host , 'host_name' ) :
res . append ( host . host_name )
return res |
def execute ( self , style , xpoints , ypoints , zpoints , mask = None , backend = 'vectorized' , specified_drift_arrays = None ) :
"""Calculates a kriged grid and the associated variance .
This is now the method that performs the main kriging calculation .
Note that currently measurements ( i . e . , z values ... | if self . verbose :
print ( "Executing Ordinary Kriging...\n" )
if style != 'grid' and style != 'masked' and style != 'points' :
raise ValueError ( "style argument must be 'grid', 'points', " "or 'masked'" )
xpts = np . atleast_1d ( np . squeeze ( np . array ( xpoints , copy = True ) ) )
ypts = np . atleast_1d ... |
def get_pull_requests ( self ) :
"https : / / developer . github . com / v3 / pulls / # list - pull - requests" | g = self . github
query = { 'state' : 'all' }
if self . args . github_token :
query [ 'access_token' ] = g [ 'token' ]
def f ( pull ) :
if self . args . ignore_closed :
return ( pull [ 'state' ] == 'opened' or ( pull [ 'state' ] == 'closed' and pull [ 'merged_at' ] ) )
else :
return True
pul... |
def reactivate ( domain_name ) :
'''Try to reactivate the expired domain name
Returns the following information :
- Whether or not the domain was reactivated successfully
- The amount charged for reactivation
- The order ID
- The transaction ID
CLI Example :
. . code - block : : bash
salt ' my - min... | opts = salt . utils . namecheap . get_opts ( 'namecheap.domains.reactivate' )
opts [ 'DomainName' ] = domain_name
response_xml = salt . utils . namecheap . post_request ( opts )
if response_xml is None :
return { }
domainreactivateresult = response_xml . getElementsByTagName ( 'DomainReactivateResult' ) [ 0 ]
retur... |
def field_value ( self , value ) :
"""Validate against NodeType .""" | if not self . is_array :
return self . field_type ( value )
if isinstance ( value , ( list , tuple , set ) ) :
return [ self . field_type ( item ) for item in value ]
return self . field_type ( value ) |
def get_learning_objectives ( self ) :
"""Gets the any ` ` Objectives ` ` corresponding to this item .
return : ( osid . learning . ObjectiveList ) - the learning objectives
raise : OperationFailed - unable to complete request
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . learning . Activity . get _ assets _ template
if not bool ( self . _my_map [ 'learningObjectiveIds' ] ) :
raise errors . IllegalState ( 'no learningObjectiveIds' )
mgr = self . _get_provider_manager ( 'LEARNING' )
if not mgr . supports_objective_lookup ( ) :
raise errors .... |
def Matches ( self , file_entry ) :
"""Compares the file entry against the filter .
Args :
file _ entry ( dfvfs . FileEntry ) : file entry to compare .
Returns :
bool : True if the file entry matches the filter , False if not or
None if the filter does not apply .""" | if not self . _file_scanner or not file_entry . IsFile ( ) :
return None
file_object = file_entry . GetFileObject ( )
if not file_object :
return False
try :
scan_state = pysigscan . scan_state ( )
self . _file_scanner . scan_file_object ( scan_state , file_object )
except IOError as exception : # TODO ... |
def execute_mgmt ( self , database , query , properties = None ) :
"""Executes a management command .
: param str database : Database against query will be executed .
: param str query : Query to be executed .
: param azure . kusto . data . request . ClientRequestProperties properties : Optional additional pr... | return self . _execute ( self . _mgmt_endpoint , database , query , KustoClient . _mgmt_default_timeout , properties ) |
def stats ( self ) -> pd . DataFrame :
"""Statistics about flights contained in the structure .
Useful for a meaningful representation .""" | key = [ "icao24" , "callsign" ] if self . flight_ids is None else "flight_id"
return ( self . data . groupby ( key ) [ [ "timestamp" ] ] . count ( ) . sort_values ( "timestamp" , ascending = False ) . rename ( columns = { "timestamp" : "count" } ) ) |
def add_load ( self , lv_load ) :
"""Adds a LV load to _ loads and grid graph if not already existing
Parameters
lv _ load :
Description # TODO""" | if lv_load not in self . _loads and isinstance ( lv_load , LVLoadDing0 ) :
self . _loads . append ( lv_load )
self . graph_add_node ( lv_load ) |
def _loop_payload ( params ) :
'''Pass in a dictionary of parameters , loop through them and build a payload containing ,
parameters who ' s values are not None .''' | # construct the payload
payload = { }
# set the payload
for param , value in six . iteritems ( params ) :
if value is not None :
payload [ param ] = value
return payload |
def emit_save_figure ( self ) :
"""Emit a signal when the toolbutton to save the figure is clicked .""" | self . sig_save_figure . emit ( self . canvas . fig , self . canvas . fmt ) |
def step ( self , disable_interrupts = True , start = 0 , end = 0 ) :
"""perform an instruction level step . This function preserves the previous
interrupt mask state""" | # Was ' if self . get _ state ( ) ! = TARGET _ HALTED : '
# but now value of dhcsr is saved
dhcsr = self . read_memory ( CortexM . DHCSR )
if not ( dhcsr & ( CortexM . C_STEP | CortexM . C_HALT ) ) :
logging . error ( 'cannot step: target not halted' )
return
self . notify ( Notification ( event = Target . EVEN... |
def event_detach ( self , eventtype ) :
"""Unregister an event notification .
@ param eventtype : the event type notification to be removed .""" | if not isinstance ( eventtype , EventType ) :
raise VLCException ( "%s required: %r" % ( 'EventType' , eventtype ) )
k = eventtype . value
if k in self . _callbacks :
del self . _callbacks [ k ]
# remove , regardless of libvlc return value
libvlc_event_detach ( self , k , self . _callback_handler , k ) |
def get_movielens_data ( ) :
"""Return ( train _ interactions , test _ interactions ) .""" | train_data , test_data = _get_raw_movielens_data ( )
uids = set ( )
iids = set ( )
for uid , iid , rating , timestamp in itertools . chain ( _parse ( train_data ) , _parse ( test_data ) ) :
uids . add ( uid )
iids . add ( iid )
rows = max ( uids ) + 1
cols = max ( iids ) + 1
return ( _build_interaction_matrix (... |
def register_pubkey ( self ) :
"""XXX Support compressed point format .
XXX Check that the pubkey received is on the curve .""" | # point _ format = 0
# if self . point [ 0 ] in [ b ' \ x02 ' , b ' \ x03 ' ] :
# point _ format = 1
curve_name = _tls_named_curves [ self . named_curve ]
curve = ec . _CURVE_TYPES [ curve_name ] ( )
import_point = ec . EllipticCurvePublicNumbers . from_encoded_point
pubnum = import_point ( curve , self . point )
s = s... |
def export_diagram_plane_elements ( root , diagram_attributes , plane_attributes ) :
"""Creates ' diagram ' and ' plane ' elements for exported BPMN XML file .
Returns a tuple ( diagram , plane ) .
: param root : object of Element class , representing a BPMN XML root element ( ' definitions ' ) ,
: param diag... | diagram = eTree . SubElement ( root , BpmnDiagramGraphExport . bpmndi_namespace + "BPMNDiagram" )
diagram . set ( consts . Consts . id , diagram_attributes [ consts . Consts . id ] )
diagram . set ( consts . Consts . name , diagram_attributes [ consts . Consts . name ] )
plane = eTree . SubElement ( diagram , BpmnDiagr... |
def bulk_get ( cls , exports , api = None ) :
"""Retrieve exports in bulk .
: param exports : Exports to be retrieved .
: param api : Api instance .
: return : list of ExportBulkRecord objects .""" | api = api or cls . _API
export_ids = [ Transform . to_export ( export ) for export in exports ]
data = { 'export_ids' : export_ids }
response = api . post ( url = cls . _URL [ 'bulk_get' ] , data = data )
return ExportBulkRecord . parse_records ( response = response , api = api ) |
def _init_zeo ( ) :
"""Start asyncore thread .""" | if not _ASYNCORE_RUNNING :
def _run_asyncore_loop ( ) :
asyncore . loop ( )
thread . start_new_thread ( _run_asyncore_loop , ( ) )
global _ASYNCORE_RUNNING
_ASYNCORE_RUNNING = True |
def nanskew ( values , axis = None , skipna = True , mask = None ) :
"""Compute the sample skewness .
The statistic computed here is the adjusted Fisher - Pearson standardized
moment coefficient G1 . The algorithm computes this coefficient directly
from the second and third central moment .
Parameters
val... | values = com . values_from_object ( values )
if mask is None :
mask = isna ( values )
if not is_float_dtype ( values . dtype ) :
values = values . astype ( 'f8' )
count = _get_counts ( mask , axis )
else :
count = _get_counts ( mask , axis , dtype = values . dtype )
if skipna :
values = values . cop... |
def load_from_module ( self , module ) :
'''Load all benchmarks from a given module''' | benchmarks = [ ]
for name in dir ( module ) :
obj = getattr ( module , name )
if ( inspect . isclass ( obj ) and issubclass ( obj , Benchmark ) and obj != Benchmark ) :
benchmarks . append ( obj )
return benchmarks |
def match_content_type ( entry , content_type , regex = True ) :
"""Matches the content type of a request using the mimeType metadata .
: param entry : ` ` dict ` ` of a single entry from a HarPage
: param content _ type : ` ` str ` ` of regex to use for finding content type
: param regex : ` ` bool ` ` indic... | mimeType = entry [ 'response' ] [ 'content' ] [ 'mimeType' ]
if regex and re . search ( content_type , mimeType , flags = re . IGNORECASE ) :
return True
elif content_type == mimeType :
return True
return False |
def join_states ( * states : State ) -> State :
"""Join two state vectors into a larger qubit state""" | vectors = [ ket . vec for ket in states ]
vec = reduce ( outer_product , vectors )
return State ( vec . tensor , vec . qubits ) |
def _get_pull_requests ( self ) :
"""Gets all pull requests from the repo since we can ' t do a filtered
date merged search""" | for pull in self . repo . pull_requests ( state = "closed" , base = self . github_info [ "master_branch" ] , direction = "asc" ) :
if self . _include_pull_request ( pull ) :
yield pull |
def init ( self , attrs = { } , * args , ** kwargs ) :
"""Default initialization from a dictionary responded by Mambu
in to the elements of the Mambu object .
It assings the response to attrs attribute and converts each of
its elements from a string to an adequate python object : number ,
datetime , etc .
... | self . attrs = attrs
self . preprocess ( )
self . convertDict2Attrs ( * args , ** kwargs )
self . postprocess ( )
try :
for meth in kwargs [ 'methods' ] :
try :
getattr ( self , meth ) ( )
except Exception :
pass
except Exception :
pass
try :
for propname , propval in... |
def generic_visit ( self , node : AST , dfltChaining : bool = True ) -> str :
"""Default handler , called if no explicit visitor function exists for
a node .""" | for field , value in ast . iter_fields ( node ) :
if isinstance ( value , list ) :
for item in value :
if isinstance ( item , AST ) :
self . visit ( item )
elif isinstance ( value , AST ) :
self . visit ( value ) |
def clean ( self , py_value ) :
"""Cleans the value before storing it .
: param : py _ value : < str >
: return : < str >""" | try :
from webhelpers . text import strip_tags
return strip_tags ( py_value )
except ImportError :
warnings . warn ( 'Unable to clean string column without webhelpers installed.' )
return py_value |
def get_event_noblock ( self ) :
'''Get the raw event without blocking or any other niceties''' | assert self . _run_io_loop_sync
if not self . cpub :
if not self . connect_pub ( ) :
return None
raw = self . subscriber . read_sync ( timeout = 0 )
if raw is None :
return None
mtag , data = self . unpack ( raw , self . serial )
return { 'data' : data , 'tag' : mtag } |
def getraw ( self , msgid , stream = sys . stdout ) :
"""Get the whole message and print it .""" | foldername , msgkey = msgid . split ( SEPERATOR )
folder = self . folder if foldername == "INBOX" else self . _getfolder ( foldername )
msg = folder [ msgkey ]
print ( msg . content ) |
def firstAttr ( self , * attrs ) :
"""Return the first attribute in attrs that is not None .""" | for attr in attrs :
value = self . __dict__ . get ( attr )
if value is not None :
return value |
def smart_search_prefix ( self , auth , query_str , search_options = None , extra_query = None ) :
"""Perform a smart search on prefix list .
* ` auth ` [ BaseAuth ]
AAA options .
* ` query _ str ` [ string ]
Search string
* ` search _ options ` [ options _ dict ]
Search options . See : func : ` search ... | if search_options is None :
search_options = { }
self . _logger . debug ( "smart_search_prefix query string: %s" % query_str )
success , query = self . _parse_prefix_query ( query_str )
if not success :
return { 'interpretation' : query , 'search_options' : search_options , 'result' : [ ] , 'error' : True , 'er... |
def find_common_root ( elements ) :
"""Find root which is common for all ` elements ` .
Args :
elements ( list ) : List of double - linked HTMLElement objects .
Returns :
list : Vector of HTMLElement containing path to common root .""" | if not elements :
raise UserWarning ( "Can't find common root - no elements suplied." )
root_path = el_to_path_vector ( elements . pop ( ) )
for el in elements :
el_path = el_to_path_vector ( el )
root_path = common_vector_root ( root_path , el_path )
if not root_path :
raise UserWarning ( "Vect... |
def _update_page ( self , uri , path ) :
"""Update page content .""" | if uri in self . _pages :
self . _pages [ uri ] . update ( )
else :
self . _pages [ uri ] = Page ( uri = uri , path = path ) |
def fb_github_project_workdir ( self , project_and_path , github_org = 'facebook' ) :
'This helper lets Facebook - internal CI special - cases FB projects' | project , path = project_and_path . split ( '/' , 1 )
return self . github_project_workdir ( github_org + '/' + project , path ) |
def trips ( self , val ) :
"""Update ` ` self . _ trips _ i ` ` if ` ` self . trips ` ` changes .""" | self . _trips = val
if val is not None and not val . empty :
self . _trips_i = self . _trips . set_index ( "trip_id" )
else :
self . _trips_i = None |
def add_datepart ( df , fldname , drop = True , time = False , errors = "raise" ) :
"""add _ datepart converts a column of df from a datetime64 to many columns containing
the information from the date . This applies changes inplace .
Parameters :
df : A pandas data frame . df gain several new columns .
fldn... | fld = df [ fldname ]
fld_dtype = fld . dtype
if isinstance ( fld_dtype , pd . core . dtypes . dtypes . DatetimeTZDtype ) :
fld_dtype = np . datetime64
if not np . issubdtype ( fld_dtype , np . datetime64 ) :
df [ fldname ] = fld = pd . to_datetime ( fld , infer_datetime_format = True , errors = errors )
targ_pr... |
def _parse_redistribution ( self , config ) :
"""Parses config file for the OSPF router ID
Args :
config ( str ) : Running configuration
Returns :
list : dict :
keys : protocol ( str )
route - map ( optional ) ( str )""" | redistributions = list ( )
regexp = r'redistribute .*'
matches = re . findall ( regexp , config )
for line in matches :
ospf_redist = line . split ( )
if len ( ospf_redist ) == 2 : # simple redist : eg ' redistribute bgp '
protocol = ospf_redist [ 1 ]
redistributions . append ( dict ( protocol =... |
def getUTMzone ( geom ) :
"""Determine UTM Zone for input geometry""" | # If geom has srs properly defined , can do this
# geom . TransformTo ( wgs _ srs )
# Get centroid lat / lon
lon , lat = geom . Centroid ( ) . GetPoint_2D ( )
# Make sure we ' re - 180 to 180
lon180 = ( lon + 180 ) - np . floor ( ( lon + 180 ) / 360 ) * 360 - 180
zonenum = int ( np . floor ( ( lon180 + 180 ) / 6 ) + 1 ... |
def list_containers ( self ) :
"""list all available nspawn containers
: return : collection of instances of : class : ` conu . backend . nspawn . container . NspawnContainer `""" | data = run_cmd ( [ "machinectl" , "list" , "--no-legend" , "--no-pager" ] , return_output = True )
output = [ ]
reg = re . compile ( r"\s+" )
for line in data . split ( "\n" ) :
stripped = line . strip ( )
if stripped :
parts = reg . split ( stripped )
name = parts [ 0 ]
output . append ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.