signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def yum_update ( downloadonly = False , dest_dir = '/tmp' ) :
"""Run a yum update on this system
This public method runs the yum - y update command to update
packages from yum . If downloadonly is set to true , the yum
updates will be downloaded to the specified dest _ dir .
: param dest _ dir : ( str ) Ful... | log = logging . getLogger ( mod_logger + '.yum_update' )
# Type checks on the args
if not isinstance ( dest_dir , basestring ) :
msg = 'dest_dir argument must be a string'
log . error ( msg )
raise CommandError ( msg )
if not isinstance ( downloadonly , bool ) :
msg = 'downloadonly argument must be a bo... |
def dataset_exists ( dataset , data_home = None ) :
"""Checks to see if a directory with the name of the specified dataset exists
in the data home directory , found with ` ` get _ data _ home ` ` .
Parameters
dataset : str
The name of the dataset ; should either be a folder in data home or
specified in th... | data_home = get_data_home ( data_home )
path = os . path . join ( data_home , dataset )
return os . path . exists ( path ) and os . path . isdir ( path ) |
def fetch_all ( self , R , depth = 1 , ** kwargs ) :
"Request multiple objects from API" | d , e = self . _fetcher . fetch_all ( R , depth , kwargs )
if e :
raise e
return d |
def to_bool ( val ) :
'''Returns the logical value .
. . code - block : : jinja
{ { ' yes ' | to _ bool } }
will be rendered as :
. . code - block : : text
True''' | if val is None :
return False
if isinstance ( val , bool ) :
return val
if isinstance ( val , ( six . text_type , six . string_types ) ) :
return val . lower ( ) in ( 'yes' , '1' , 'true' )
if isinstance ( val , six . integer_types ) :
return val > 0
if not isinstance ( val , collections . Hashable ) :
... |
def update_reminder_item ( self , reminder_item_id , reminder_item_dict ) :
"""Updates a reminder item
: param reminder _ item _ id : the reminder item id
: param reminder _ item _ dict : dict
: return : dict""" | return self . _create_put_request ( resource = REMINDER_ITEMS , billomat_id = reminder_item_id , send_data = reminder_item_dict ) |
def branch ( self ) :
"""Return whether the project is on master branch""" | result = get_branch ( repo = self . repo )
if result is None :
result = get_travis_branch ( )
return result |
def escape ( s , quote = False ) :
"""Replace special characters " & " , " < " and " > " to HTML - safe sequences . If
the optional flag ` quote ` is ` True ` , the quotation mark character is
also translated .
There is a special handling for ` None ` which escapes to an empty string .
: param s : the strin... | if s is None :
return ''
if hasattr ( s , '__html__' ) :
return s . __html__ ( )
if not isinstance ( s , ( text_type , binary_type ) ) :
s = text_type ( s )
if isinstance ( s , binary_type ) :
try :
s . decode ( 'ascii' )
except :
s = s . decode ( 'utf-8' , 'replace' )
s = s . replac... |
def use_educated_guess ( self ) :
"""Tries to guess the proper library names , include and library paths
if everything else failed .""" | preprocess_fallback_config ( )
global LIBIGRAPH_FALLBACK_LIBRARIES
global LIBIGRAPH_FALLBACK_INCLUDE_DIRS
global LIBIGRAPH_FALLBACK_LIBRARY_DIRS
print ( "WARNING: we were not able to detect where igraph is installed on" )
print ( "your machine (if it is installed at all). We will use the fallback" )
print ( "library an... |
def verify_url ( url , secret_key , ** kwargs ) :
"""Verify a signed URL ( excluding the domain and scheme ) .
: param url : URL to sign
: param secret _ key : Secret key
: rtype : bool
: raises : URLError""" | result = urlparse ( url )
query_args = MultiValueDict ( parse_qs ( result . query ) )
return verify_url_path ( result . path , query_args , secret_key , ** kwargs ) |
def getItem ( self , itemID ) :
""": desc : Given an ID return the note JSON object
{ u ' note ' : u ' note8 ' ,
u ' ID ' : 3.0,
u ' tags ' : [ u ' 8 ' ] ,
u ' timestamps ' : [ 1381719620.315899 ] }
: param int itemID : The item ID , an integer
: returns : The matching note
: rval : int""" | collections = self . get_data_collections ( )
itemID = scrubID ( itemID )
for coll in collections :
note = self . noteDB [ coll ] . find_one ( { "ID" : itemID } )
if note is not None :
del note [ "_id" ]
note [ 'type' ] = coll
break
return note |
def _pfp__add_child ( self , name , child , stream = None ) :
"""Add a child to the Union field
: name : The name of the child
: child : A : class : ` . Field ` instance
: returns : The resulting field""" | res = super ( Union , self ) . _pfp__add_child ( name , child )
self . _pfp__buff . seek ( 0 , 0 )
child . _pfp__build ( stream = self . _pfp__buff )
size = len ( self . _pfp__buff . getvalue ( ) )
self . _pfp__buff . seek ( 0 , 0 )
if stream is not None :
curr_pos = stream . tell ( )
stream . seek ( curr_pos -... |
def get_context_data ( self , ** kwargs ) :
"""Allow adding a ' render _ description ' parameter""" | context = super ( ScheduleXmlView , self ) . get_context_data ( ** kwargs )
if self . request . GET . get ( 'render_description' , None ) == '1' :
context [ 'render_description' ] = True
else :
context [ 'render_description' ] = False
return context |
def movMF ( X , n_clusters , posterior_type = "soft" , force_weights = None , n_init = 10 , n_jobs = 1 , max_iter = 300 , verbose = False , init = "random-class" , random_state = None , tol = 1e-6 , copy_x = True , ) :
"""Wrapper for parallelization of _ movMF and running n _ init times .""" | if n_init <= 0 :
raise ValueError ( "Invalid number of initializations." " n_init=%d must be bigger than zero." % n_init )
random_state = check_random_state ( random_state )
if max_iter <= 0 :
raise ValueError ( "Number of iterations should be a positive number," " got %d instead" % max_iter )
best_inertia = np... |
def _check_job_status ( self , job , desc , status_key_name ) :
"""Check to see if the job completed successfully and , if not , construct and
raise a ValueError .
Args :
job ( str ) : The name of the job to check .
desc ( dict [ str , str ] ) : The result of ` ` describe _ training _ job ( ) ` ` .
status... | status = desc [ status_key_name ]
# If the status is capital case , then convert it to Camel case
status = _STATUS_CODE_TABLE . get ( status , status )
if status != 'Completed' and status != 'Stopped' :
reason = desc . get ( 'FailureReason' , '(No reason provided)' )
job_type = status_key_name . replace ( 'JobS... |
def _UpdateCampaignDSASetting ( client , campaign_id , feed_id ) :
"""Updates the campaign DSA setting to DSA pagefeeds .
Args :
client : an AdWordsClient instance .
campaign _ id : a str Campaign ID .
feed _ id : a str page Feed ID .
Raises :
ValueError : If the given campaign is found not to be a dyna... | # Get the CampaignService .
campaign_service = client . GetService ( 'CampaignService' , version = 'v201809' )
selector = { 'fields' : [ 'Id' , 'Settings' ] , 'predicates' : [ { 'field' : 'Id' , 'operator' : 'EQUALS' , 'values' : [ campaign_id ] } ] }
response = campaign_service . get ( selector )
if response [ 'totalN... |
def calculated_intervals ( self ) :
"""Gets the calculated intervals from the database
: return : The calculated intervals""" | if self . _calculated_intervals is None :
logging . debug ( "get calculated intervals" )
self . load ( )
return self . mongo_model . get_calculated_intervals ( )
return self . _calculated_intervals |
def browse_home_listpage_url ( self , state = None , county = None , zipcode = None , street = None , ** kwargs ) :
"""Construct an url of home list page by state , county , zipcode , street .
Example :
- https : / / www . zillow . com / browse / homes / ca /
- https : / / www . zillow . com / browse / homes ... | url = self . domain_browse_homes
for item in [ state , county , zipcode , street ] :
if item :
url = url + "/%s" % item
url = url + "/"
return url |
def get_current_snapshot_name ( vm ) :
"""Returns the name of the current snapshot
: param vm : Virtual machine to find current snapshot name
: return : Snapshot name
: rtype str""" | all_snapshots = SnapshotRetriever . get_vm_snapshots ( vm )
# noinspection PyProtectedMember
if not vm . snapshot :
return None
current_snapshot_id = vm . snapshot . currentSnapshot . _moId
for snapshot_name in all_snapshots . keys ( ) : # noinspection PyProtectedMember
if all_snapshots [ snapshot_name ] . _moI... |
def cli ( env , context_id ) :
"""Request configuration of a tunnel context .
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices .""" | manager = SoftLayer . IPSECManager ( env . client )
# ensure context can be retrieved by given id
manager . get_tunnel_context ( context_id )
succeeded = manager . apply_configuration ( context_id )
if succeeded :
env . out ( 'Configuration request received for context #{}' . format ( context_id ) )
else :
rais... |
def build_latex ( hyp ) :
"""Parameters
hyp : dict
{ ' segmentation ' : [ [ 0 , 3 ] , [ 1 , 2 ] ] ,
' symbols ' : [ { ' symbol ' : ID , ' probability ' : 0.12 } ] ,
' geometry ' : { ' symbol ' : index ,
' bottom ' : None or dict ,
' subscript ' : None or dict ,
' right ' : None or dict ,
' superscri... | latex = [ ]
for symbol in hyp [ 'symbols' ] :
latex . append ( symbol [ 'symbol' ] . split ( ";" ) [ 1 ] )
return " " . join ( latex ) |
def chars ( string : any ) -> str :
"""Return all ( and only ) the chars in the given string .""" | return '' . join ( [ c if c . isalpha ( ) else '' for c in str ( string ) ] ) |
def _parse_ident ( self ) :
"""Parse an identifier and return it ( possibly an empty string ) .
Updates ` ` pos ` ` .""" | remainder = self . string [ self . pos : ]
ident = re . match ( r'\w*' , remainder ) . group ( 0 )
self . pos += len ( ident )
return ident |
def load_SampleData ( ) -> Tuple [ pandas . DataFrame , pandas . DataFrame ] :
'''Load sample data for quickly starting a demo run .
Returns
df _ state _ init , df _ forcing : Tuple [ pandas . DataFrame , pandas . DataFrame ]
- df _ state _ init : ` initial model states < df _ state _ var > `
- df _ forcing... | path_SampleData = Path ( path_supy_module ) / 'sample_run'
path_runcontrol = path_SampleData / 'RunControl.nml'
df_state_init = init_supy ( path_runcontrol )
# path _ input = path _ runcontrol . parent / ser _ mod _ cfg [ ' fileinputpath ' ]
df_forcing = load_forcing_grid ( path_runcontrol , df_state_init . index [ 0 ]... |
def Get ( self , key ) :
"""Get network by providing name , ID , or other unique key .
If key is not unique and finds multiple matches only the first
will be returned""" | for network in self . networks :
try :
if network . id == key :
return ( network )
if network . name == key :
return ( network )
if network . cidr == key :
return ( network )
except : # We ignore malformed records with missing attributes
pass |
def set_details ( self , details , ** kwargs ) :
""": param details : Details to set for the object
: type details : dict or list
: raises : : class : ` ~ dxpy . exceptions . DXAPIError ` if the object is not in the " open " state
Sets the details for the remote object with the specified value .
If the inpu... | return self . _set_details ( self . _dxid , details , ** kwargs ) |
def _gather_exposed_methods ( self ) :
"""Searches for the exposed methods in the current microservice class . A method is considered
exposed if it is decorated with the : py : func : ` gemstone . public _ method ` or
: py : func : ` gemstone . private _ api _ method ` .""" | self . _extract_methods_from_container ( self )
for module in self . modules :
self . _extract_methods_from_container ( module ) |
def ParseChat ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a chat message .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row .
row ( sqlite3 . Row ) :... | query_hash = hash ( query )
participants = self . _GetRowValue ( query_hash , row , 'participants' )
author = self . _GetRowValue ( query_hash , row , 'author' )
dialog_partner = self . _GetRowValue ( query_hash , row , 'dialog_partner' )
from_displayname = self . _GetRowValue ( query_hash , row , 'from_displayname' )
... |
def state ( self , filter_nodes = None , filter_routing_table = None , filter_metadata = None , filter_blocks = None , filter_indices = None ) :
"""Retrieve the : ref : ` cluster state < es - guide - reference - api - admin - cluster - state > ` .
: param filter _ nodes : set to * * true * * to filter out the * *... | path = make_path ( "_cluster" , "state" )
parameters = { }
if filter_nodes is not None :
parameters [ 'filter_nodes' ] = filter_nodes
if filter_routing_table is not None :
parameters [ 'filter_routing_table' ] = filter_routing_table
if filter_metadata is not None :
parameters [ 'filter_metadata' ] = filter_... |
def admin_tools_render_dashboard_module ( context , module ) :
"""Template tag that renders a given dashboard module , it takes a
` ` DashboardModule ` ` instance as first parameter .""" | module . init_with_context ( context )
context . update ( { 'template' : module . template , 'module' : module , 'admin_url' : reverse ( '%s:index' % get_admin_site_name ( context ) ) , } )
return context |
def listFigures ( self , walkTrace = tuple ( ) , case = None , element = None ) :
"""List section figures .""" | if case == 'sectionmain' :
print ( walkTrace , self . title )
if case == 'figure' :
caption , fig = element
try :
print ( walkTrace , fig . _leopardref , caption )
except AttributeError :
fig . _leopardref = next ( self . _reportSection . _fignr )
print ( walkTrace , fig . _leopa... |
def decorator ( caller , _func = None ) :
"""decorator ( caller ) converts a caller function into a decorator""" | if _func is not None : # return a decorated function
# this is obsolete behavior ; you should use decorate instead
return decorate ( _func , caller )
# else return a decorator function
defaultargs , defaults = '' , ( )
if inspect . isclass ( caller ) :
name = caller . __name__ . lower ( )
doc = 'decorator(%... |
def update_config ( updated_project ) :
'''Update project in configuration
args :
updated _ project ( dict ) : Updated project configuration values''' | home = os . path . expanduser ( '~' )
if os . path . isfile ( os . path . join ( home , '.transfer' , 'config.yaml' ) ) :
with open ( os . path . join ( home , '.transfer' , 'config.yaml' ) , 'r' ) as fp :
projects = yaml . load ( fp . read ( ) )
replace_index = - 1
for i , project in enumerate ( pr... |
def plot ( self , n = 500 , eigenvalues = None , sum = None , title = None , ax = None , ** kwargs ) :
r"""Docstring overloaded at import time .""" | from pygsp . plotting import _plot_filter
return _plot_filter ( self , n = n , eigenvalues = eigenvalues , sum = sum , title = title , ax = ax , ** kwargs ) |
def build_image ( image_path , image_name , build_args = None , dockerfile_path = None ) :
"""Build an image
Args :
image _ path ( str ) : the path to the image directory
image _ name ( str ) : image ' name : tag ' to build
build _ args ( dict , optional ) : dict of docker build arguments
dockerfile _ pat... | cmd = [ 'docker' , 'build' , '-t' , image_name , image_path ]
if dockerfile_path :
cmd . extend ( [ '-f' , dockerfile_path ] )
for k , v in ( build_args or { } ) . items ( ) :
cmd += [ '--build-arg' , '{}={}' . format ( k , v ) ]
check_call ( cmd ) |
def get_cursor_vertical_diff ( self ) :
"""Returns the how far down the cursor moved since last render .
Note :
If another get _ cursor _ vertical _ diff call is already in progress ,
immediately returns zero . ( This situation is likely if
get _ cursor _ vertical _ diff is called from a SIGWINCH signal
h... | # Probably called by a SIGWINCH handler , and therefore
# will do cursor querying until a SIGWINCH doesn ' t happen during
# the query . Calls to the function from a signal handler COULD STILL
# HAPPEN out of order -
# they just can ' t interrupt the actual cursor query .
if self . in_get_cursor_diff :
self . anoth... |
def _parse_years ( years ) :
"""Parse string of ints include ranges into a ` list ` of ` int `
Source : https : / / stackoverflow . com / a / 6405228/1307974""" | result = [ ]
for part in years . split ( ',' ) :
if '-' in part :
a , b = part . split ( '-' )
a , b = int ( a ) , int ( b )
result . extend ( range ( a , b + 1 ) )
else :
a = int ( part )
result . append ( a )
return result |
def parse_atom_site ( self , name , attributes ) :
'''Parse the atom tag attributes . Most atom tags do not have attributes .''' | if name == "PDBx:pdbx_PDB_ins_code" :
assert ( not ( self . current_atom_site . ATOMResidueiCodeIsNull ) )
if attributes . get ( 'xsi:nil' ) == 'true' :
self . current_atom_site . ATOMResidueiCodeIsNull = True
if name == "PDBx:auth_asym_id" :
assert ( not ( self . current_atom_site . PDBChainIDIsNul... |
def get_size ( conn , vm_ ) :
'''Return the VM ' s size object''' | sizes = conn . list_sizes ( )
vm_size = config . get_cloud_config_value ( 'size' , vm_ , __opts__ )
if not vm_size :
return sizes [ 0 ]
for size in sizes :
if vm_size and six . text_type ( vm_size ) in ( six . text_type ( sizes [ size ] [ 'id' ] ) , six . text_type ( size ) ) :
return sizes [ size ] [ '... |
def absl_to_cpp ( level ) :
"""Converts an absl log level to a cpp log level .
Args :
level : int , an absl . logging level .
Raises :
TypeError : Raised when level is not an integer .
Returns :
The corresponding integer level for use in Abseil C + + .""" | if not isinstance ( level , int ) :
raise TypeError ( 'Expect an int level, found {}' . format ( type ( level ) ) )
if level >= 0 : # C + + log levels must be > = 0
return 0
else :
return - level |
def batch_get_assets_history ( self , parent , content_type , read_time_window , asset_names = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Batch gets the update history of assets that overlap a time window . Fo... | # Wrap the transport method to add retry and timeout logic .
if "batch_get_assets_history" not in self . _inner_api_calls :
self . _inner_api_calls [ "batch_get_assets_history" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . batch_get_assets_history , default_retry = self . _method_conf... |
def train ( epochs , ctx ) :
"""Training function .""" | if isinstance ( ctx , mx . Context ) :
ctx = [ ctx ]
net . initialize ( mx . init . Xavier ( magnitude = 2 ) , ctx = ctx )
opt_options = { 'learning_rate' : opt . lr , 'wd' : opt . wd }
if opt . optimizer == 'sgd' :
opt_options [ 'momentum' ] = 0.9
if opt . optimizer == 'adam' :
opt_options [ 'epsilon' ] = ... |
def task_failure_handler ( task_id = None , exception = None , traceback = None , args = None , ** kwargs ) :
"""Task failure handler""" | # TODO : find a better way to acces workdir / archive / image
task_report = { 'task_id' : task_id , 'exception' : exception , 'traceback' : traceback , 'archive' : args [ 1 ] [ 'archive_path' ] , 'image' : args [ 1 ] [ 'image' ] }
notifier . send_task_failure_report ( task_report )
workdir = args [ 1 ] [ 'workdir' ]
re... |
def update_hpx_skymap_allsky ( map_in , map_out ) :
"""' Update ' a HEALPix skymap
This checks map _ out exists and creates it from map _ in if it does not .
If map _ out does exist , this adds the data in map _ in to map _ out""" | if map_out is None :
in_hpx = map_in . hpx
out_hpx = HPX . create_hpx ( in_hpx . nside , in_hpx . nest , in_hpx . coordsys , None , in_hpx . ebins , None , in_hpx . conv , None )
data_out = map_in . expanded_counts_map ( )
print ( data_out . shape , data_out . sum ( ) )
map_out = HpxMap ( data_out ,... |
def parser_factory ( fake_args = None ) :
"""Return a proper contextual OptionParser""" | parser = ArgumentParser ( description = 'aomi' )
subparsers = parser . add_subparsers ( dest = 'operation' , help = 'Specify the data ' ' or extraction operation' )
extract_file_args ( subparsers )
environment_args ( subparsers )
aws_env_args ( subparsers )
seed_args ( subparsers )
render_args ( subparsers )
diff_args ... |
def applyEdits ( self , addFeatures = [ ] , updateFeatures = [ ] , deleteFeatures = None , gdbVersion = None , rollbackOnFailure = True ) :
"""This operation adds , updates , and deletes features to the
associated feature layer or table in a single call .
Inputs :
addFeatures - The array of features to be add... | editURL = self . _url + "/applyEdits"
params = { "f" : "json" , 'rollbackOnFailure' : rollbackOnFailure }
if not gdbVersion is None :
params [ 'gdbVersion' ] = gdbVersion
if len ( addFeatures ) > 0 and isinstance ( addFeatures [ 0 ] , Feature ) :
params [ 'adds' ] = json . dumps ( [ f . asDictionary for f in ad... |
def _variant_po_to_dict ( tokens ) -> CentralDogma :
"""Convert a PyParsing data dictionary to a central dogma abundance ( i . e . , Protein , RNA , miRNA , Gene ) .
: type tokens : ParseResult""" | dsl = FUNC_TO_DSL . get ( tokens [ FUNCTION ] )
if dsl is None :
raise ValueError ( 'invalid tokens: {}' . format ( tokens ) )
return dsl ( namespace = tokens [ NAMESPACE ] , name = tokens [ NAME ] , variants = [ _variant_to_dsl_helper ( variant_tokens ) for variant_tokens in tokens [ VARIANTS ] ] , ) |
def unregister ( self , signal ) :
"""Unregisters an existing signal
: param signal : Name of the signal""" | if signal in self . signals . keys ( ) :
del ( self . signals [ signal ] )
self . __log . debug ( "Signal %s unregisterd" % signal )
else :
self . __log . debug ( "Signal %s does not exist and could not be unregistered." ) |
def refresh_token ( self ) :
"""Refreshing the current expired access token""" | self . token = self . oauth . refresh_token ( self . access_token_url , refresh_token = self . get_refresh_token ( ) )
self . access_token = self . token . get ( "access_token" ) |
def _variable ( lexer ) :
"""Return a variable expression .""" | names = _names ( lexer )
tok = next ( lexer )
# NAMES ' [ ' . . . ' ] '
if isinstance ( tok , LBRACK ) :
indices = _indices ( lexer )
_expect_token ( lexer , { RBRACK } )
# NAMES
else :
lexer . unpop_token ( tok )
indices = tuple ( )
return ( 'var' , names , indices ) |
def get_exceptions ( self ) :
"""a tuple of class names for the exception types this method may
raise , or None if this is not a method
reference : http : / / docs . oracle . com / javase / specs / jvms / se7 / html / jvms - 4 . html # jvms - 4.7.5""" | # noqa
buff = self . get_attribute ( "Exceptions" )
if buff is None :
return ( )
with unpack ( buff ) as up :
return tuple ( self . deref_const ( e [ 0 ] ) for e in up . unpack_struct_array ( _H ) ) |
def down ( removekeys = False , tgt = '*' , tgt_type = 'glob' , timeout = None , gather_job_timeout = None ) :
'''. . versionchanged : : 2017.7.0
The ` ` expr _ form ` ` argument has been renamed to ` ` tgt _ type ` ` , earlier
releases must use ` ` expr _ form ` ` .
Print a list of all the down or unresponsi... | ret = status ( output = False , tgt = tgt , tgt_type = tgt_type , timeout = timeout , gather_job_timeout = gather_job_timeout ) . get ( 'down' , [ ] )
for minion in ret :
if removekeys :
wheel = salt . wheel . Wheel ( __opts__ )
wheel . call_func ( 'key.delete' , match = minion )
return ret |
def text_lines_from_local_file ( document , remote = False ) :
"""Return the fulltext of the local file .
@ param document : fullpath to the file that should be read
@ param remote : boolean , if True does not count lines
@ return : list of lines if st was read or an empty list""" | try :
if is_pdf ( document ) :
if not executable_exists ( "pdftotext" ) :
current_app . logger . error ( "pdftotext is not available on the system." )
cmd = "pdftotext -q -enc UTF-8 %s -" % re . escape ( document )
out = subprocess . Popen ( [ "pdftotext" , "-q" , "-enc" , "UTF-8... |
def setDiscoveryTriples ( win , table = "discovery" ) :
"""Provide user with a list of triples that could be discovery triples""" | win . help ( "Getting a list of pointings with triples from the CFEPS db" )
pointings = getPointingsWithTriples ( )
win . help ( "Select the " + table + " triple form the list..." )
import time
for pointing in pointings :
header = "%10s %10s %8s %10s %8s" % ( pointing [ 1 ] , 'mjdate' , 'Elongation' , 'Filter' , 'I... |
def chunk_math ( text ) :
"""Parameters
text : string
A mathematical context
Returns
list :
A list of single LaTeX entities
Examples
> > > chunk _ math ( ' \ sum _ i ^ n i ^ 2 ' )
[ ' \\ \\ sum ' , ' _ ' , ' i ' , ' ^ ' , ' n ' , ' ' , ' i ' , ' ^ ' , ' 2 ' ]
> > > chunk _ math ( ' \ sum _ { i } ^... | # Fail when ' { ' and ' } ' don ' t match - be aware of escaped symbols !
opened_braces = 0
last_char = ''
for char in text :
if char == '{' and last_char != '\\' :
opened_braces += 1
if char == '}' and last_char != '\\' :
opened_braces -= 1
if opened_braces < 0 :
raise Value... |
def _process_with_multiprocessing ( self , X : Union [ pd . DataFrame , np . ndarray ] , n_refs : int , cluster_array : np . ndarray ) :
"""Process calling of . calculate _ gap ( ) method using the multiprocessing library""" | with ProcessPoolExecutor ( max_workers = self . n_jobs ) as executor :
jobs = [ executor . submit ( self . _calculate_gap , X , n_refs , n_clusters ) for n_clusters in cluster_array ]
for future in as_completed ( jobs ) :
gap_value , k = future . result ( )
yield ( gap_value , k ) |
def open ( dataset_dir , access_mode = READ_ONLY_ACCESS ) :
"""Opens a tensor dataset .""" | # check access mode
if access_mode == WRITE_ACCESS :
raise ValueError ( 'Cannot open a dataset with write-only access' )
# read config
try : # json load
config_filename = os . path . join ( dataset_dir , 'config.json' )
config = json . load ( open ( config_filename , 'r' ) )
except : # YAML load
config_... |
def encrypt_text ( self , text , * args , ** kwargs ) :
"""Encrypt a string .
input : unicode str , output : unicode str""" | b = text . encode ( "utf-8" )
token = self . encrypt ( b , * args , ** kwargs )
return base64 . b64encode ( token ) . decode ( "utf-8" ) |
def p_substr_assignment_no_let ( p ) :
"""statement : ID LP expr RP EQ expr""" | # This can be only a substr assignment like a $ ( i + 3 ) = " . " , since arrays
# have ARRAY _ ID already
entry = SYMBOL_TABLE . access_call ( p [ 1 ] , p . lineno ( 1 ) )
if entry is None :
return
if entry . class_ == CLASS . unknown :
entry . class_ = CLASS . var
if p [ 6 ] . type_ != TYPE . string :
api... |
def to_size ( value , convert_to_human = True ) :
'''Convert python int ( bytes ) to zfs size
NOTE : http : / / src . illumos . org / source / xref / illumos - gate / usr / src / lib / pyzfs / common / util . py # 114''' | value = from_size ( value )
if value is None :
value = 'none'
if isinstance ( value , Number ) and value > 1024 and convert_to_human :
v_power = int ( math . floor ( math . log ( value , 1024 ) ) )
v_multiplier = math . pow ( 1024 , v_power )
# NOTE : zfs is a bit odd on how it does the rounding ,
#... |
def _create_minimum_needs_options_action ( self ) :
"""Create action for global minimum needs dialog .""" | icon = resources_path ( 'img' , 'icons' , 'show-global-minimum-needs.svg' )
self . action_minimum_needs_config = QAction ( QIcon ( icon ) , self . tr ( 'Minimum Needs Configuration' ) , self . iface . mainWindow ( ) )
self . action_minimum_needs_config . setStatusTip ( self . tr ( 'Open InaSAFE minimum needs configurat... |
def tile_y_size ( self , zoom ) :
"""Height of a tile in SRID units at zoom level .
- zoom : zoom level""" | warnings . warn ( DeprecationWarning ( "tile_y_size is deprecated" ) )
validate_zoom ( zoom )
return round ( self . y_size / self . matrix_height ( zoom ) , ROUND ) |
def convert_user_to_ldap ( self , ID , DN ) :
"""Convert a normal user to a LDAP user .""" | # http : / / teampasswordmanager . com / docs / api - users / # convert _ to _ ldap
data = { 'login_dn' : DN }
log . info ( 'Convert User %s to LDAP DN %s' % ( ID , DN ) )
self . put ( 'users/%s/convert_to_ldap.json' % ID , data ) |
def _add_generate_sub_commands ( self ) :
"""Sub commands for generating models for usage by clients .
Currently supports Google Closure .""" | gen_parser = self . _subparsers_handle . add_parser ( name = "gen" , help = "generate client side model stubs, filters" )
gen_parser . add_argument ( "-t" , "--template" , choices = [ 'closure.model' , 'closure.filter' ] , default = 'closure.model' , required = True , dest = "template" , help = "template to use for cli... |
def _init_multicast_socket ( self ) :
"""Init multicast socket
: rtype : None""" | self . debug ( "()" )
# Create a UDP socket
self . _multicast_socket = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
# Allow reuse of addresses
self . _multicast_socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )
# Set multicast interface to local _ ip
self . _multicast_socket . setsoc... |
def _clean_dead_sessions ( self ) :
"""Traverses sessions to determine if any sockets
were removed ( indicates a stopped session ) .
In these cases , remove the session .""" | for sck in list ( self . sessions . keys ( ) ) :
session = self . sessions [ sck ]
if session . socket is None :
del self . sessions [ sck ] |
def download ( self , name : str , force : bool = False ) -> bool :
"""Attempts to download a given Docker image . If ` force = True ` , then any
previously installed version of the image ( described by the
instructions ) will be replaced by the image on DockerHub .
Parameters :
name : the name of the Docke... | try :
self . __docker . images . pull ( name )
return True
except docker . errors . NotFound :
print ( "Failed to locate image on DockerHub: {}" . format ( name ) )
return False |
def parse ( self , descriptor ) :
"""Creates a text styling from a descriptor
A descriptor is a dictionary containing any of the following keys :
* fg : The foreground color ( name or int )
See ` bgseq `
* bg : The background color ( name or int )
See ` fgseq `
* fmt : The types of special text formatti... | fg = descriptor . get ( 'fg' )
bg = descriptor . get ( 'bg' )
types = descriptor . get ( 'fmt' )
ret = ""
if fg :
ret += fgseq ( fg )
if bg :
ret += bgseq ( bg )
if types :
t = typeseq ( types )
if t :
ret += t
# wew , strings and bytes , what ' s a guy to do !
reset = resetseq ( )
if not isinst... |
def add_task_db ( self , task ) :
'''向数据库中写入一个新的任务记录''' | sql = 'INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
req = self . cursor . execute ( sql , task )
self . check_commit ( ) |
def get_option ( options = None , local_tag = None , doc = None , doc_tag = None , default = None , error_on_none = True ) :
"""fetch an option variable ,
from either a local ( element ) level option / attribute tag ,
document level metadata tag ,
or a default
: type options : ` ` dict ` `
: type local _ ... | variable = None
# element level
if options is not None and local_tag is not None :
if local_tag in options and options [ local_tag ] is not None :
variable = options [ local_tag ]
if variable is not None :
return variable
# doc level
if doc is not None and doc_tag is not None :
variable = doc . get_... |
def autoUseMyMetrics ( ttGlyph , glyphName , hmtx ) :
"""Set the " USE _ MY _ METRICS " flag on the first component having the
same advance width as the composite glyph , no transform and no
horizontal shift ( but allow it to shift vertically ) .
This forces the composite glyph to use the possibly hinted hori... | width = hmtx [ glyphName ] [ 0 ]
for component in ttGlyph . components :
try :
baseName , transform = component . getComponentInfo ( )
except AttributeError : # component uses ' { first , second } Pt ' instead of ' x ' and ' y '
continue
try :
baseMetrics = hmtx [ baseName ]
exce... |
def _get_url ( self , url ) :
"""Returns normalized url . If schema is not given , would fall
to filesystem
( ` ` file : / / / ` ` ) schema .""" | url = str ( url )
if url != 'default' and not '://' in url :
url = "file:" + urllib . pathname2url ( url )
return url |
def retry_it ( exceptions = ( Exception , ) , tries = 10 , wait = 0 , handler = None , raised_exception = ReusablesError , raised_message = None ) :
"""Retry a function if an exception is raised , or if output _ check returns
False .
Message format options : { func } { args } { kwargs }
: param exceptions : t... | def func_wrapper ( func ) :
@ wraps ( func )
def wrapper ( * args , ** kwargs ) :
msg = ( raised_message if raised_message else "Max retries exceeded for function '{func}'" )
if not raised_message :
msg = _add_args ( msg , * args , ** kwargs )
try :
result = func ... |
def naive_request ( self , url , method , ** kwargs ) :
"""Makes a request to url using an without oauth authorization
session , but through a normal session
: param str url : url to send request to
: param str method : type of request ( get / put / post / patch / delete )
: param kwargs : extra params to s... | return self . _internal_request ( self . naive_session , url , method , ** kwargs ) |
def process ( self , sched , coro ) :
"""Add the calling coro in a waiting for signal queue .""" | super ( WaitForSignal , self ) . process ( sched , coro )
waitlist = sched . sigwait [ self . name ]
waitlist . append ( ( self , coro ) )
if self . name in sched . signals :
sig = sched . signals [ self . name ]
if sig . recipients <= len ( waitlist ) :
sig . process ( sched , sig . coro )
del ... |
def refresh_devices ( self ) :
'''Queries hub for list of devices , and creates new device objects''' | try :
response = self . api . get ( "/api/v2/devices" , { 'properties' : 'all' } )
for device_data in response [ 'DeviceList' ] :
self . devices . append ( Device ( device_data , self ) )
except APIError as e :
print ( "API error: " )
for key , value in e . data . iteritems :
print ( str... |
def set_sort_order ( self , sort_order ) :
"""Use the SortOrder object to sort the listings descending or ascending .
: param sort _ order :
: return :""" | if not isinstance ( sort_order , SortOrder ) :
raise DaftException ( "sort_order should be an instance of SortOrder." )
self . _sort_order = str ( sort_order ) |
def _encode_image ( self , np_image ) :
"""Returns np _ image encoded as jpeg or png .""" | if np_image . dtype != np . uint8 :
raise ValueError ( 'Image should be uint8. Detected: %s.' % np_image . dtype )
utils . assert_shape_match ( np_image . shape , self . _shape )
return self . _runner . run ( ENCODE_FN [ self . _encoding_format ] , np_image ) |
def _merge_meta ( self , encoded_meta , meta ) :
"""Merge new meta dict into encoded meta . Returns new encoded meta .""" | new_meta = None
if meta :
_meta = self . _decode_meta ( encoded_meta )
for key , value in six . iteritems ( meta ) :
if value is None :
_meta . pop ( key , None )
else :
_meta [ key ] = value
new_meta = self . _encode_meta ( _meta )
return new_meta |
def parse_host ( parser , event , node ) :
"""Parse and return the host entity if that is the next entity
< ! ELEMENT HOST ( # PCDATA ) >""" | # pylint : disable = unused - argument
host = ''
( next_event , next_node ) = six . next ( parser )
if next_event == pulldom . CHARACTERS :
host = next_node . nodeValue
( next_event , next_node ) = six . next ( parser )
if not _is_end ( next_event , next_node , 'HOST' ) :
raise ParseError ( 'Expecting end H... |
def _request ( self , url , api_call , request_args , method = 'GET' ) :
"""Function to request and returning JSON data .
Parameters :
url ( str ) : Base url call .
api _ call ( str ) : API function to be called .
request _ args ( dict ) : All requests parameters .
method ( str ) : ( Defauld : GET ) HTTP ... | try :
if method != 'GET' : # Reset content - type for data encoded as a multipart form
self . client . headers . update ( { 'content-type' : None } )
response = self . client . request ( method , url , ** request_args )
self . last_call . update ( { 'API' : api_call , 'url' : response . url , 'statu... |
def fixed_length_split ( s , width ) :
"""固定长度分割字符串
: param s :
: param width :
: return :""" | # 使用正则的方法
# import re
# split = re . findall ( r ' . { % s } ' % width , string )
return [ s [ x : x + width ] for x in range ( 0 , len ( s ) , width ) ] |
def sentryDSN ( self , * args , ** kwargs ) :
"""Get DSN for Sentry Project
Get temporary DSN ( access credentials ) for a sentry project .
The credentials returned can be used with any Sentry client for up to
24 hours , after which the credentials will be automatically disabled .
If the project doesn ' t e... | return self . _makeApiCall ( self . funcinfo [ "sentryDSN" ] , * args , ** kwargs ) |
def records ( credentials , url = "https://freedns.afraid.org/api/" ) :
"""Yield the dynamic DNS records associated with this account .
: param credentials : an AfraidCredentials instance
: param url : the service URL""" | params = { "action" : "getdyndns" , "sha" : credentials . sha }
req = requests . get ( url , params = params , headers = constants . REQUEST_HEADERS_DEFAULT , timeout = 60 )
for record_line in ( line . strip ( ) for line in req . text . splitlines ( ) if len ( line . strip ( ) ) > 0 ) :
yield AfraidDynDNSRecord ( *... |
def legacy_events_view ( request ) :
"""View to see legacy events .""" | events = TeacherEvent . objects . all ( )
event_count = events . count ( )
paginator = Paginator ( events , 100 )
page = request . GET . get ( 'page' )
try :
events = paginator . page ( page )
except PageNotAnInteger :
events = paginator . page ( 1 )
except EmptyPage :
events = paginator . page ( paginator ... |
def from_structures ( cls , structures , authors , projects = None , references = '' , remarks = None , data = None , histories = None , created_at = None ) :
"""A convenience method for getting a list of StructureNL objects by
specifying structures and metadata separately . Some of the metadata
is applied to a... | data = [ { } ] * len ( structures ) if data is None else data
histories = [ [ ] ] * len ( structures ) if histories is None else histories
snl_list = [ ]
for i , struct in enumerate ( structures ) :
snl = StructureNL ( struct , authors , projects = projects , references = references , remarks = remarks , data = dat... |
def _mask_to_bytes ( self , mask ) :
"""Convert the ( type long ) mask to a cpu _ set _ t .""" | chunks = [ ]
shiftmask = ( 2 ** 64 ) - 1
for x in range ( 16 ) :
chunks . append ( struct . pack ( '<Q' , mask & shiftmask ) )
mask >>= 64
return mitogen . core . b ( '' ) . join ( chunks ) |
def strip_ssh_from_git_uri ( uri ) : # type : ( S ) - > S
"""Return git + ssh : / / formatted URI to git + git @ format""" | if isinstance ( uri , six . string_types ) :
if "git+ssh://" in uri :
parsed = urlparse ( uri )
# split the path on the first separating / so we can put the first segment
# into the ' netloc ' section with a : separator
path_part , _ , path = parsed . path . lstrip ( "/" ) . partitio... |
def copyto ( self , src , where = None ) :
"""Emulates function ` copyto ` in NumPy .
Parameters
where : ( N , ) bool ndarray
True if particle n in src must be copied .
src : ( N , ) ` ThetaParticles ` object
source
for each n such that where [ n ] is True , copy particle n in src
into self ( at locat... | for k in self . containers :
v = self . __dict__ [ k ]
if isinstance ( v , np . ndarray ) :
np . copyto ( v , src . __dict__ [ k ] , where = where )
else :
v . copyto ( src . __dict__ [ k ] , where = where ) |
def from_python_src ( cls , pySrc , lambdas_path , json_filename : str , stem : str , save_file : bool = False , ) :
"""Builds GrFN object from Python source code .""" | asts = [ ast . parse ( pySrc ) ]
pgm_dict = genPGM . create_pgm_dict ( lambdas_path , asts , json_filename , { "FileName" : f"{stem}.py" } , # HACK
)
lambdas = importlib . __import__ ( stem + "_lambdas" )
return cls . from_dict ( pgm_dict , lambdas ) |
def encrypt_file_inline ( filename , passphrase ) :
"""Encrypt file inline , with an optional passphrase .
If you set the passphrase to None , a default is used .
This will make you vulnerable to confirmation attacks
and learn - partial - information attacks .
: param filename : The name of the file to encr... | key = key_generators . key_from_file ( filename , passphrase )
inline_transform ( filename , key )
return key |
def get_formatted_interval ( results_range , default = _marker ) :
"""Returns a string representation of the interval defined by the results
range passed in
: param results _ range : a dict or a ResultsRangeDict""" | if not isinstance ( results_range , Mapping ) :
if default is not _marker :
return default
api . fail ( "Type not supported" )
results_range = ResultsRangeDict ( results_range )
min_str = results_range . min if api . is_floatable ( results_range . min ) else None
max_str = results_range . max if api . i... |
def _isinstance ( obj , cls , bound_Generic = None , bound_typevars = None , bound_typevars_readonly = False , follow_fwd_refs = True , _recursion_check = None ) :
"""Access this via ` ` pytypes . is _ of _ type ` ` .
Works like ` ` isinstance ` ` , but supports PEP 484 style types from ` ` typing ` ` module .
... | if bound_typevars is None :
bound_typevars = { }
# Special treatment if cls is Iterable [ . . . ]
if is_Generic ( cls ) and cls . __origin__ is typing . Iterable :
if not is_iterable ( obj ) :
return False
itp = get_iterable_itemtype ( obj )
if itp is None :
return not pytypes . check_it... |
def recent_changes ( request ) :
"""Display the recent changes .""" | page = max ( 1 , request . args . get ( "page" , type = int ) )
query = RevisionedPage . query . order_by ( RevisionedPage . revision_id . desc ( ) )
return Response ( generate_template ( "recent_changes.html" , pagination = Pagination ( query , 20 , page , "Special:Recent_Changes" ) , ) ) |
def log_likelihood ( z , x , P , H , R ) :
"""Returns log - likelihood of the measurement z given the Gaussian
posterior ( x , P ) using measurement function H and measurement
covariance error R""" | S = np . dot ( H , np . dot ( P , H . T ) ) + R
return logpdf ( z , np . dot ( H , x ) , S ) |
def contiguous_slice ( in1 ) :
"""This function unpads an array on the GPU in such a way as to make it contiguous .
INPUTS :
in1 ( no default ) : Array containing data which has been padded .
OUTPUTS :
gpu _ out1 Array containing unpadded , contiguous data .""" | ker = SourceModule ( """
__global__ void contiguous_slice_ker(float *in1, float *out1)
{
const int len = gridDim.x*blockDim.x;
const int col = (blockDim.x * blockIdx.x + threadIdx.x);
cons... |
def from_yaml ( cls , yaml_path , ** kwargs ) :
"""Create cluster with worker pod spec defined by a YAML file
We can start a cluster with pods defined in an accompanying YAML file
like the following :
. . code - block : : yaml
kind : Pod
metadata :
labels :
foo : bar
baz : quux
spec :
containers... | if not yaml :
raise ImportError ( "PyYaml is required to use yaml functionality, please install it!" )
with open ( yaml_path ) as f :
d = yaml . safe_load ( f )
d = dask . config . expand_environment_variables ( d )
return cls . from_dict ( d , ** kwargs ) |
def copy_doc ( klass , fnname ) :
"""Copies documentation string of a method from the super class into the
rewritten method of the given class""" | base_meth , base_func = __get_meth_func ( klass . __base__ , fnname )
meth , func = __get_meth_func ( klass , fnname )
func . __doc__ = base_func . __doc__ |
def runcmd ( command , command_input = None , cwd = None ) :
"""Run a command , potentially sending stdin , and capturing stdout / err .""" | proc = subprocess . Popen ( command , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , cwd = cwd )
( stdout , stderr ) = proc . communicate ( command_input )
if proc . returncode != 0 :
sys . stderr . write ( 'ABORTING: command "%s" failed w/ code %s:\n' '%s\n%s' % ( command , p... |
def read_line ( csv_contents , options , prop_indices , mol , ensemble_list = None ) :
"""read csv line""" | if not ensemble_list :
score_field = options . score_field
status_field = options . status_field
active_label = options . active_label
decoy_label = options . decoy_label
# do the active / decoy labels have appropriate values ?
active_value_matcher = re . compile ( active_label )
decoy_value_matcher = re . compile ... |
def browse_morelikethis_preview ( self , seed ) :
"""Fetch More Like This preview result for a seed deviation
: param seed : The deviationid to fetch more like""" | response = self . _req ( '/browse/morelikethis/preview' , { "seed" : seed } )
returned_seed = response [ 'seed' ]
author = User ( )
author . from_dict ( response [ 'author' ] )
more_from_artist = [ ]
for item in response [ 'more_from_artist' ] :
d = Deviation ( )
d . from_dict ( item )
more_from_artist . ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.