signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def on_board ( self , * args ) :
"""Draw myself for the first time as soon as I have the properties I
need to do so .""" | if None in ( self . board , self . origin , self . destination ) :
Clock . schedule_once ( self . on_board , 0 )
return
self . _trigger_repoint ( ) |
def file_type ( self , file ) :
"""Use python - magic to determine file type .
Returns ' png ' or ' jpg ' on success , nothing on failure .""" | try :
magic_text = magic . from_file ( file )
if ( isinstance ( magic_text , bytes ) ) : # In python2 and travis python3 ( ? ! ) decode to get unicode string
magic_text = magic_text . decode ( 'utf-8' )
except ( TypeError , IOError ) :
return
if ( re . search ( 'PNG image data' , magic_text ) ) :
... |
def prepare_body ( self , data , files ) :
"""Prepares the given HTTP body data .""" | # Check if file , fo , generator , iterator .
# If not , run through normal process .
# Nottin ' on you .
body = None
content_type = None
length = None
is_stream = all ( [ hasattr ( data , '__iter__' ) , not isinstance ( data , ( basestring , list , tuple , dict ) ) ] )
try :
length = super_len ( data )
except ( Ty... |
def extra ( self , ** kwargs ) :
"""Add extra keys to the request body . Mostly here for backwards
compatibility .""" | s = self . _clone ( )
if 'from_' in kwargs :
kwargs [ 'from' ] = kwargs . pop ( 'from_' )
s . _extra . update ( kwargs )
return s |
def update ( self ) :
"""Update the screens contents in every loop .""" | # this is not really neccesary because the surface is black after initializing
self . corners . fill ( BLACK )
self . corners . draw_dot ( ( 0 , 0 ) , self . colors [ 0 ] )
self . corners . draw_dot ( ( self . screen . width - 1 , 0 ) , self . colors [ 0 ] )
self . corners . draw_dot ( ( self . screen . width - 1 , sel... |
def rich_item ( self , method_name , value ) :
"""Convert this value into the rich txkoji objects ( if applicable )""" | if value is None :
return None
if method_name == 'getAverageBuildDuration' :
return timedelta ( seconds = value )
types = ( Build , Channel , Package , Task )
if isinstance ( value , Munch ) :
for type_ in types :
if type_ . __name__ in method_name :
item = type_ ( value )
it... |
def add_edge ( self , u , v ) :
"""self = EulerTourForest ( )
self . add _ node ( 1)
self . add _ node ( 2)
u , v = 1 , 2""" | # ubin = self . find _ root ( u )
ru = self . find_root ( u )
rv = self . find_root ( v )
ru = self . reroot ( ru , u )
rv = self . reroot ( rv , v )
ubin . set_child ( vbin )
pass |
def sport_delete ( self , sport_id = "0.0.0" , account = None , ** kwargs ) :
"""Remove a sport . This needs to be * * proposed * * .
: param str sport _ id : Sport ID to identify the Sport to be deleted
: param str account : ( optional ) Account used to verify the operation""" | if not account :
if "default_account" in config :
account = config [ "default_account" ]
if not account :
raise ValueError ( "You need to provide an account" )
account = Account ( account )
sport = Sport ( sport_id )
op = operations . Sport_delete ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.... |
def compile_graphql_to_gremlin ( schema , graphql_string , type_equivalence_hints = None ) :
"""Compile the GraphQL input using the schema into a Gremlin query and associated metadata .
Args :
schema : GraphQL schema object describing the schema of the graph to be queried
graphql _ string : the GraphQL query ... | lowering_func = ir_lowering_gremlin . lower_ir
query_emitter_func = emit_gremlin . emit_code_from_ir
return _compile_graphql_generic ( GREMLIN_LANGUAGE , lowering_func , query_emitter_func , schema , graphql_string , type_equivalence_hints , None ) |
def ensure_size ( self , size = None ) :
"""This function removes the least frequent elements until the size
constraint is met .""" | if size is None :
size = self . size_constraint
while sys . getsizeof ( self ) > size :
element_frequencies = collections . Counter ( self )
infrequent_element = element_frequencies . most_common ( ) [ - 1 : ] [ 0 ] [ 0 ]
self . remove ( infrequent_element ) |
def instagram_profile_json ( username ) :
"""Get the JSON data string from the scripts .
: param username :
: return :""" | scripts = instagram_profile_js ( username )
source = None
if scripts :
for script in scripts :
if script . text :
if script . text [ 0 : SCRIPT_JSON_PREFIX ] == "window._sharedData" :
source = script . text [ SCRIPT_JSON_DATA_INDEX : - 1 ]
return source |
def _set_pspf6_timer ( self , v , load = False ) :
"""Setter method for pspf6 _ timer , mapped from YANG variable / isis _ state / router _ isis _ config / pspf6 _ timer ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ pspf6 _ timer is considered as a priva... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = pspf6_timer . pspf6_timer , is_container = 'container' , presence = False , yang_name = "pspf6-timer" , rest_name = "pspf6-timer" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe... |
def update_group_entitlement ( self , document , group_id , rule_option = None ) :
"""UpdateGroupEntitlement .
[ Preview API ] Update entitlements ( License Rule , Extensions Rule , Project memberships etc . ) for a group .
: param : class : ` < [ JsonPatchOperation ] > < azure . devops . v5_0 . member _ entitl... | route_values = { }
if group_id is not None :
route_values [ 'groupId' ] = self . _serialize . url ( 'group_id' , group_id , 'str' )
query_parameters = { }
if rule_option is not None :
query_parameters [ 'ruleOption' ] = self . _serialize . query ( 'rule_option' , rule_option , 'str' )
content = self . _serializ... |
def junction_overlap ( self , tx , tolerance = 0 ) :
"""Calculate the junction overlap between two transcripts
: param tx : Other transcript
: type tx : Transcript
: param tolerance : how close to consider two junctions as overlapped ( default = 0)
: type tolerance : int
: return : Junction Overlap Report... | self . _initialize ( )
return JunctionOverlap ( self , tx , tolerance ) |
def has_a_conf ( self , magic_hash = None ) : # pragma : no cover
"""Send a HTTP request to the satellite ( GET / have _ conf )
Used to know if the satellite has a conf
: param magic _ hash : Config hash . Only used for HA arbiter communication
: type magic _ hash : int
: return : Boolean indicating if the ... | logger . debug ( "Have a configuration for %s, %s %s" , self . name , self . alive , self . reachable )
self . have_conf = self . con . get ( '_have_conf' , { 'magic_hash' : magic_hash } )
return self . have_conf |
async def run_tasks ( context ) :
"""Run any tasks returned by claimWork .
Returns the integer status of the task that was run , or None if no task was
run .
args :
context ( scriptworker . context . Context ) : the scriptworker context .
Raises :
Exception : on unexpected exception .
Returns :
int ... | running_tasks = RunTasks ( )
context . running_tasks = running_tasks
status = await running_tasks . invoke ( context )
context . running_tasks = None
return status |
async def items ( self ) :
"""Lists all the active tokens
Returns :
ObjectMeta : where value is a list of tokens
It returns a body like this : :
" CreateIndex " : 3,
" ModifyIndex " : 3,
" ID " : " 8f246b77 - f3e1 - ff88-5b48-8ec93abf3e05 " ,
" Name " : " Client Token " ,
" Type " : " client " ,
"... | response = await self . _api . get ( "/v1/acl/list" )
results = [ decode_token ( r ) for r in response . body ]
return consul ( results , meta = extract_meta ( response . headers ) ) |
def create ( login , password , password_hashed = False , machine_account = False ) :
'''Create user account
login : string
login name
password : string
password
password _ hashed : boolean
set if password is a nt hash instead of plain text
machine _ account : boolean
set to create a machine trust a... | ret = 'unchanged'
# generate nt hash if needed
if password_hashed :
password_hash = password . upper ( )
password = ""
# wipe password
else :
password_hash = generate_nt_hash ( password )
# create user
if login not in list_users ( False ) : # NOTE : - - create requires a password , even if blank
res... |
def format_output_compare ( self , key , left , right ) :
"""Format an output for printing""" | if isinstance ( left , six . string_types ) :
left = _trim_base64 ( left )
if isinstance ( right , six . string_types ) :
right = _trim_base64 ( right )
cc = self . colors
self . comparison_traceback . append ( cc . OKBLUE + " mismatch '%s'" % key + cc . FAIL )
# Use comparison repr from pytest :
hook_result = ... |
def extend ( self , new_leaves : List [ bytes ] ) :
"""Extend this tree with new _ leaves on the end .
The algorithm works by using _ push _ subtree ( ) as a primitive , calling
it with the maximum number of allowed leaves until we can add the
remaining leaves as a valid entire ( non - full ) subtree in one g... | size = len ( new_leaves )
final_size = self . tree_size + size
idx = 0
while True : # keep pushing subtrees until mintree _ size > remaining
max_h = self . __mintree_height
max_size = 1 << ( max_h - 1 ) if max_h > 0 else 0
if max_h > 0 and size - idx >= max_size :
self . _push_subtree ( new_leaves [... |
def pack_data ( self , remaining_size ) :
"""Pack data . readoffset has to be increased by one , seems like HANA starts from 1 , not zero .""" | payload = self . part_struct . pack ( self . locator_id , self . readoffset + 1 , self . readlength , b' ' )
return 4 , payload |
def safe_tag ( self , tag , errors = 'strict' ) :
"""URL Encode and truncate tag to match limit ( 128 characters ) of ThreatConnect API .
Args :
tag ( string ) : The tag to be truncated
Returns :
( string ) : The truncated tag""" | if tag is not None :
try : # handle unicode characters and url encode tag value
tag = quote ( self . s ( tag , errors = errors ) , safe = '~' ) [ : 128 ]
except KeyError as e :
warn = 'Failed converting tag to safetag ({})' . format ( e )
self . log . warning ( warn )
return tag |
def split_command ( cmd , posix = None ) :
'''- cmd is string list - > nothing to do
- cmd is string - > split it using shlex
: param cmd : string ( ' ls - l ' ) or list of strings ( [ ' ls ' , ' - l ' ] )
: rtype : string list''' | if not isinstance ( cmd , string_types ) : # cmd is string list
pass
else :
if not PY3 : # cmd is string
# The shlex module currently does not support Unicode input ( in
# 2 . x ) !
if isinstance ( cmd , unicode ) :
try :
cmd = unicodedata . normalize ( 'NFKD' , cmd )... |
def get_foreign_keys ( cls ) :
"""Get foreign keys and models they refer to , so we can pre - process
the data for load _ bulk""" | foreign_keys = { }
for field in cls . _meta . fields :
if ( field . get_internal_type ( ) == 'ForeignKey' and field . name != 'parent' ) :
if django . VERSION >= ( 1 , 9 ) :
foreign_keys [ field . name ] = field . remote_field . model
else :
foreign_keys [ field . name ] = fi... |
def analysis_evensen ( self ) :
"""Ayman here ! ! ! . some peices that may be useful :
self . parcov = parameter covariance matrix
self . obscov = obseravtion noise covariance matrix
self . parensmeble = current parameter ensemble
self . obsensemble = current observation ( model output ) ensemble
the ense... | nz_names = self . pst . nnz_obs_names
nreals = self . obsensemble . shape [ 0 ]
self . parensemble . _transform ( )
# nonzero weighted state deviations
HA_prime = self . obsensemble . get_deviations ( ) . loc [ : , nz_names ] . T
# obs noise pertubations - move to constuctor
E = ( self . obsensemble_0 . loc [ : , nz_na... |
def needs ( cls , * service_names ) :
"""A class decorator to indicate that an XBlock class needs particular services .""" | def _decorator ( cls_ ) : # pylint : disable = missing - docstring
for service_name in service_names :
cls_ . _services_requested [ service_name ] = "need"
# pylint : disable = protected - access
return cls_
return _decorator |
def ReadTag ( buffer , pos ) :
"""Read a tag from the buffer , and return a ( tag _ bytes , new _ pos ) tuple .
We return the raw bytes of the tag rather than decoding them . The raw
bytes can then be used to look up the proper decoder . This effectively allows
us to trade some work that would be done in pure... | start = pos
while six . indexbytes ( buffer , pos ) & 0x80 :
pos += 1
pos += 1
return ( buffer [ start : pos ] , pos ) |
def add_services ( self , info ) :
"""Add auth service descriptions to an IIIFInfo object .
Login service description is the wrapper for all other
auth service descriptions so we have nothing unless
self . login _ uri is specified . If we do then add any other
auth services at children .
Exactly the same ... | if ( self . login_uri ) :
svc = self . login_service_description ( )
svcs = [ ]
if ( self . logout_uri ) :
svcs . append ( self . logout_service_description ( ) )
if ( self . client_id_uri ) :
svcs . append ( self . client_id_service_description ( ) )
if ( self . access_token_uri ) :... |
def is_path ( value ) :
"""Checks whether the given value represents a path , i . e . a string which starts with an indicator for absolute or
relative paths .
: param value : Value to check .
: return : ` ` True ` ` , if the value appears to be representing a path .
: rtype : bool""" | return value and isinstance ( value , six . string_types ) and ( value [ 0 ] == posixpath . sep or value [ : 2 ] == CURRENT_DIR ) |
def choose_branch ( exclude = None ) : # type : ( List [ str ] ) - > str
"""Show the user a menu to pick a branch from the existing ones .
Args :
exclude ( list [ str ] ) :
List of branch names to exclude from the menu . By default it will
exclude master and develop branches . To show all branches pass an
... | if exclude is None :
master = conf . get ( 'git.master_branch' , 'master' )
develop = conf . get ( 'git.devel_branch' , 'develop' )
exclude = { master , develop }
branches = list ( set ( git . branches ( ) ) - exclude )
# Print the menu
for i , branch_name in enumerate ( branches ) :
shell . cprint ( '<... |
def DisplayEstimate ( message , min_estimate , max_estimate ) :
"""Displays mean average cpc , position , clicks , and total cost for estimate .
Args :
message : str message to display for the given estimate .
min _ estimate : sudsobject containing a minimum estimate from the
TrafficEstimatorService respons... | # Find the mean of the min and max values .
mean_avg_cpc = ( _CalculateMean ( min_estimate [ 'averageCpc' ] [ 'microAmount' ] , max_estimate [ 'averageCpc' ] [ 'microAmount' ] ) if 'averageCpc' in min_estimate and min_estimate [ 'averageCpc' ] else None )
mean_avg_pos = ( _CalculateMean ( min_estimate [ 'averagePositio... |
def basename ( path : Optional [ str ] ) -> Optional [ str ] :
"""Returns the final component of a pathname and None if the argument is None""" | if path is not None :
return os . path . basename ( path ) |
def delete_tagging ( Bucket , region = None , key = None , keyid = None , profile = None ) :
'''Delete the tags from the given bucket
Returns { deleted : true } if tags were deleted and returns
{ deleted : False } if tags were not deleted .
CLI Example :
. . code - block : : bash
salt myminion boto _ s3 _... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
conn . delete_bucket_tagging ( Bucket = Bucket )
return { 'deleted' : True , 'name' : Bucket }
except ClientError as e :
return { 'deleted' : False , 'error' : __utils__ [ 'boto3.get_error' ] ( e ) } |
def remove_range ( self , start , end ) :
'''Remove a range by score .''' | return self . _sl . remove_range ( start , end , callback = lambda sc , value : self . _dict . pop ( value ) ) |
def get_custom_annotations_recursive ( data_type ) :
"""Given a Stone data type , returns all custom annotations applied to any of
its memebers , as well as submembers , . . . , to an arbitrary depth .""" | # because Stone structs can contain references to themselves ( or otherwise
# be cyclical ) , we need ot keep track of the data types we ' ve already seen
data_types_seen = set ( )
def recurse ( data_type ) :
if data_type in data_types_seen :
return
data_types_seen . add ( data_type )
dt , _ , _ = u... |
def select_batch ( self , batch , batch_col_name = None ) :
"""selects the rows in column batch _ col _ number
( default : DbSheetCols . batch )""" | if not batch_col_name :
batch_col_name = self . db_sheet_cols . batch
logger . debug ( "selecting batch - %s" % batch )
sheet = self . table
identity = self . db_sheet_cols . id
exists_col_number = self . db_sheet_cols . exists
criterion = sheet . loc [ : , batch_col_name ] == batch
exists = sheet . loc [ : , exist... |
def get_group ( self , group_id ) :
"""Get a single group .
: param str group _ id : group ID
: returns : group
: rtype : : class : ` marathon . models . group . MarathonGroup `""" | response = self . _do_request ( 'GET' , '/v2/groups/{group_id}' . format ( group_id = group_id ) )
return self . _parse_response ( response , MarathonGroup ) |
def plot ( data , pconfig = None ) :
"""Plot a scatter plot with X , Y data .
: param data : 2D dict , first keys as sample names , then x : y data pairs
: param pconfig : optional dict with config key : value pairs . See CONTRIBUTING . md
: return : HTML and JS , ready to be inserted into the page""" | if pconfig is None :
pconfig = { }
# Allow user to overwrite any given config for this plot
if 'id' in pconfig and pconfig [ 'id' ] and pconfig [ 'id' ] in config . custom_plot_config :
for k , v in config . custom_plot_config [ pconfig [ 'id' ] ] . items ( ) :
pconfig [ k ] = v
# Given one dataset - tu... |
def proc_response ( self , resp ) :
"""Process response hook .
Process non - redirect responses received by the send ( ) method .
May augment the response . The default implementation causes
an exception to be raised if the response status code is > =
400.""" | # Raise exceptions for error responses
if resp . status >= 400 :
e = exc . exception_map . get ( resp . status , exc . HTTPException )
self . _debug ( " Response was a %d fault, raising %s" , resp . status , e . __name__ )
raise e ( resp ) |
def parse_reports ( self ) :
"""Find Picard InsertSizeMetrics reports and parse their data""" | # Set up vars
self . picard_insertSize_data = dict ( )
self . picard_insertSize_histogram = dict ( )
self . picard_insertSize_samplestats = dict ( )
# Go through logs and find Metrics
for f in self . find_log_files ( 'picard/insertsize' , filehandles = True ) :
s_name = None
in_hist = False
for l in f [ 'f'... |
def _load_cache ( self , filename ) :
"""Load the cached page references from ` < filename > . ptc ` .""" | try :
with open ( filename + self . CACHE_EXTENSION , 'rb' ) as file :
prev_number_of_pages , prev_page_references = pickle . load ( file )
except ( IOError , TypeError ) :
prev_number_of_pages , prev_page_references = { } , { }
return prev_number_of_pages , prev_page_references |
def add ( self , key , source ) :
"""Add the persisted source to the store under the given key
key : str
The unique token of the un - persisted , original source
source : DataSource instance
The thing to add to the persisted catalogue , referring to persisted
data""" | from intake . catalog . local import LocalCatalogEntry
try :
with self . fs . open ( self . path , 'rb' ) as f :
data = yaml . safe_load ( f )
except IOError :
data = { 'sources' : { } }
ds = source . _yaml ( ) [ 'sources' ] [ source . name ]
data [ 'sources' ] [ key ] = ds
with self . fs . open ( self ... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'types' ) and self . types is not None :
_dict [ 'types' ] = [ x . _to_dict ( ) for x in self . types ]
if hasattr ( self , 'categories' ) and self . categories is not None :
_dict [ 'categories' ] = [ x . _to_dict ( ) for x in self . categories ]
return _dict |
def confirm_registration ( request , key , template = "locksmith/confirmed.html" ) :
'''API key confirmation
visiting this URL marks a Key as ready for use''' | context = { 'LOCKSMITH_BASE_TEMPLATE' : settings . LOCKSMITH_BASE_TEMPLATE }
try :
context [ 'key' ] = key_obj = Key . objects . get ( key = key )
if key_obj . status != 'U' :
context [ 'error' ] = 'Key Already Activated'
else :
key_obj . status = 'A'
key_obj . save ( )
key_o... |
def bottom ( self ) :
"""The row index that marks the bottom extent of the vertical span of
this cell . This is one greater than the index of the bottom - most row
of the span , similar to how a slice of the cell ' s rows would be
specified .""" | if self . vMerge is not None :
tc_below = self . _tc_below
if tc_below is not None and tc_below . vMerge == ST_Merge . CONTINUE :
return tc_below . bottom
return self . _tr_idx + 1 |
def new_children ( self , ** kwargs ) :
"""Create new children from kwargs""" | for k , v in kwargs . items ( ) :
self . new_child ( k , v )
return self |
def get_year_week ( timestamp ) :
"""Get the year and week for a given timestamp .""" | time_ = datetime . fromtimestamp ( timestamp )
year = time_ . isocalendar ( ) [ 0 ]
week = time_ . isocalendar ( ) [ 1 ]
return year , week |
def update_repositories ( repositories , conf_path ) :
"""Upadate with user custom repositories""" | repo_file = "{0}custom-repositories" . format ( conf_path )
if os . path . isfile ( repo_file ) :
f = open ( repo_file , "r" )
repositories_list = f . read ( )
f . close ( )
for line in repositories_list . splitlines ( ) :
line = line . lstrip ( )
if line and not line . startswith ( "#" ... |
def send_vdp_assoc ( self , vsiid = None , mgrid = None , typeid = None , typeid_ver = None , vsiid_frmt = vdp_const . VDP_VSIFRMT_UUID , filter_frmt = vdp_const . VDP_FILTER_GIDMACVID , gid = 0 , mac = "" , vlan = 0 , oui_id = "" , oui_data = "" , sw_resp = False ) :
"""Sends the VDP Associate Message .
Please r... | if sw_resp and filter_frmt == vdp_const . VDP_FILTER_GIDMACVID :
reply = self . send_vdp_query_msg ( "assoc" , mgrid , typeid , typeid_ver , vsiid_frmt , vsiid , filter_frmt , gid , mac , vlan , oui_id , oui_data )
vlan_resp , fail_reason = self . get_vlan_from_query_reply ( reply , vsiid , mac )
if vlan_re... |
def delete ( self ) :
"""Delete this Vlan interface from the parent interface .
This will also remove stale routes if the interface has
networks associated with it .
: return : None""" | if self in self . _parent . vlan_interface :
self . _parent . data [ 'vlanInterfaces' ] = [ v for v in self . _parent . vlan_interface if v != self ]
self . update ( )
for route in self . _parent . _engine . routing :
if route . to_delete :
route . delete ( ) |
def debug_contents ( self , indent = 1 , file = sys . stdout , _ids = None ) :
"""Debug the contents of an object .""" | if _debug :
_log . debug ( "debug_contents indent=%r file=%r _ids=%r" , indent , file , _ids )
klasses = list ( self . __class__ . __mro__ )
klasses . reverse ( )
if _debug :
_log . debug ( " - klasses: %r" , klasses )
# loop through the classes and look for _ debug _ contents
attrs = [ ]
cids = [ ]
ownFn = ... |
def settings ( package , reload_ = False ) :
"""Returns the config settings for the specified package .
Args :
package ( str ) : name of the python package to get settings for .""" | global packages
if package not in packages or reload_ :
from os import path
result = CaseConfigParser ( )
if package != "acorn" :
confpath = _package_path ( package )
_read_single ( result , confpath )
_read_single ( result , _package_path ( "acorn" ) )
packages [ package ] = result
... |
def show_firmware_version_output_show_firmware_version_control_processor_memory ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_firmware_version = ET . Element ( "show_firmware_version" )
config = show_firmware_version
output = ET . SubElement ( show_firmware_version , "output" )
show_firmware_version = ET . SubElement ( output , "show-firmware-version" )
control_processor_memory = ET . SubElement ( show_... |
def query_nexus ( query_url , timeout_sec , basic_auth = None ) :
"""Queries Nexus for an artifact
: param query _ url : ( str ) Query URL
: param timeout _ sec : ( int ) query timeout
: param basic _ auth ( HTTPBasicAuth ) object or none
: return : requests . Response object
: raises : RuntimeError""" | log = logging . getLogger ( mod_logger + '.query_nexus' )
# Attempt to query Nexus
retry_sec = 5
max_retries = 6
try_num = 1
query_success = False
nexus_response = None
while try_num <= max_retries :
if query_success :
break
log . debug ( 'Attempt # {n} of {m} to query the Nexus URL: {u}' . format ( n =... |
def add_to_parser ( self , parser ) :
"""Add this container : attr : ` settings ` to an existing ` ` parser ` ` .""" | setts = self . settings
def sorter ( x ) :
return ( setts [ x ] . section , setts [ x ] . order )
for k in sorted ( setts , key = sorter ) :
setts [ k ] . add_argument ( parser )
return parser |
def initialize_notebook ( ) :
"""Initialize the IPython notebook display elements""" | try :
from IPython . core . display import display , HTML
except ImportError :
print ( "IPython Notebook could not be loaded." )
lib_js = ENV . get_template ( 'ipynb_init_js.html' )
lib_css = ENV . get_template ( 'ipynb_init_css.html' )
display ( HTML ( lib_js . render ( ) ) )
display ( HTML ( lib_css . render ... |
def setup_column ( self , widget , column = 0 , attribute = None , renderer = None , property = None , from_python = None , to_python = None , model = None ) : # Maybe this is too overloaded .
"""Set up a : class : ` TreeView ` to display attributes of Python objects
stored in its : class : ` TreeModel ` .
This... | if isinstance ( widget , str ) :
widget = self . view [ widget ]
if not model and isinstance ( self . model , Gtk . TreeModel ) :
model = self . model
return setup_column ( widget , column = column , attribute = attribute , renderer = renderer , property = property , from_python = from_python , to_python = to_p... |
def web_upload ( self , package ) :
"""* Smart enough to not save things we already have
* Idempotent , you can call as many times as you need
* The caller names the package ( its basename )""" | pkg = request . files [ package ]
self . index . from_data ( package , pkg . read ( ) )
return 'ok' |
def add_tag ( self , tag ) :
"""* Add a tag this taskpaper object *
* * Key Arguments : * *
- ` ` tag ` ` - - the tag to add to the object
* * Usage : * *
. . code - block : : python
aTask . add _ tag ( " @ due " )""" | if tag . replace ( "@" , "" ) in self . tags :
return
self . refresh
oldContent = self . to_string ( indentLevel = 1 )
self . tags += [ tag . replace ( "@" , "" ) ]
newContent = self . to_string ( indentLevel = 1 )
# ADD DIRECTLY TO CONTENT IF THE PROJECT IS BEING ADDED SPECIFICALLY TO
# THIS OBJECT
self . parent .... |
def create ( self , vm_ , local_master = True ) :
'''Create a single VM''' | output = { }
minion_dict = salt . config . get_cloud_config_value ( 'minion' , vm_ , self . opts , default = { } )
alias , driver = vm_ [ 'provider' ] . split ( ':' )
fun = '{0}.create' . format ( driver )
if fun not in self . clouds :
log . error ( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete s... |
def _edge_opposite_point ( self , tri , i ) :
"""Given a triangle , return the edge that is opposite point i .
Vertexes are returned in the same orientation as in tri .""" | ind = tri . index ( i )
return ( tri [ ( ind + 1 ) % 3 ] , tri [ ( ind + 2 ) % 3 ] ) |
def updatePrefix ( self , p , u ) :
"""Update ( redefine ) a prefix mapping for the branch .
@ param p : A prefix .
@ type p : basestring
@ param u : A namespace URI .
@ type u : basestring
@ return : self
@ rtype : L { Element }
@ note : This method traverses down the entire branch !""" | if p in self . nsprefixes :
self . nsprefixes [ p ] = u
for c in self . children :
c . updatePrefix ( p , u )
return self |
def _diff_dict ( orig , new ) :
"""Diff a nested dictionary , returning only key / values that differ .""" | final = { }
for k , v in new . items ( ) :
if isinstance ( v , dict ) :
v = _diff_dict ( orig . get ( k , { } ) , v )
if len ( v ) > 0 :
final [ k ] = v
elif v != orig . get ( k ) :
final [ k ] = v
for k , v in orig . items ( ) :
if k not in new :
final [ k ] = No... |
def use_federated_gradebook_view ( self ) :
"""Pass through to provider GradeSystemLookupSession . use _ federated _ gradebook _ view""" | self . _gradebook_view = FEDERATED
# self . _ get _ provider _ session ( ' grade _ system _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_federated_gradebook_view ( )
except AttributeError :
pass |
def rel ( path , parent = None , par = False ) :
"""Takes * path * and computes the relative path from * parent * . If * parent * is
omitted , the current working directory is used .
If * par * is # True , a relative path is always created when possible .
Otherwise , a relative path is only returned if * path... | try :
res = os . path . relpath ( path , parent )
except ValueError : # Raised eg . on Windows for differing drive letters .
if not par :
return abs ( path )
raise
else :
if not par and not issub ( res ) :
return abs ( path )
return res |
def attachedimage_form_factory ( lang = 'en' , debug = False ) :
'''Returns ModelForm class to be used in admin .
' lang ' is the language for GearsUploader ( can be ' en ' and ' ru ' at the
moment ) .''' | yui = '' if debug else '.yui'
class _AttachedImageAdminForm ( forms . ModelForm ) :
caption = forms . CharField ( label = _ ( 'Caption' ) , required = False )
class Media :
js = [ 'generic_images/js/mootools-1.2.4-core-yc.js' , 'generic_images/js/GearsUploader.%s%s.js' % ( lang , yui , ) , 'generic_imag... |
def qteKeyPress ( self , msgObj ) :
"""Record the key presses reported by the key handler .""" | # Unpack the data structure .
( srcObj , keysequence , macroName ) = msgObj . data
# Append the last QKeyEvent object to the so far recorded
# sequence . Note that both ` ` keysequence ` ` and
# ` ` self . recorded _ keysequence ` ` are ` ` QtmacsKeysequence ` `
# instances .
last_key = keysequence . toQKeyEventList ( ... |
def __prep_mod_opts ( self , opts ) :
'''Strip out of the opts any logger instance''' | if '__grains__' not in self . pack :
grains = opts . get ( 'grains' , { } )
if isinstance ( grains , ThreadLocalProxy ) :
grains = ThreadLocalProxy . unproxy ( grains )
self . context_dict [ 'grains' ] = grains
self . pack [ '__grains__' ] = salt . utils . context . NamespacedDictWrapper ( self ... |
def write ( self ) :
"""If data exists for the entity , writes it to disk as a . JSON file with
the url - encoded URI as the filename and returns True . Else , returns
False .""" | if ( self . data ) :
dataPath = self . client . local_dir / ( urllib . parse . quote_plus ( self . uri ) + '.json' )
with dataPath . open ( mode = 'w' ) as dump_file :
json . dump ( self . data , dump_file )
dump_file . close ( )
logger . info ( 'Wrote ' + self . uri + ' to file' )
retur... |
def maps ( self ) :
"""A dictionary of dictionaries .
Each dictionary defines a map which is used to extend the metadata .
The precise way maps interact with the metadata is defined by ` figure . fit . _ extend _ meta ` .
That method should be redefined or extended to suit specific use cases .""" | if not hasattr ( self , '_maps' ) :
maps = { }
maps [ 'tex_symbol' ] = { }
maps [ 'siunitx' ] = { }
maps [ 'value_transforms' ] = { '__default__' : lambda x : round ( x , 2 ) , }
self . _maps = maps
return self . _maps |
def delete_bams ( job , bams , patient_id ) :
"""Delete the bams from the job Store once their purpose has been achieved ( i . e . after all
mutation calling steps ) . Will also delete the chimeric junction file from Star .
: param dict bams : Dict of bam and bai files
: param str patient _ id : The ID of the... | bams = { b : v for b , v in bams . items ( ) if ( b . endswith ( '.bam' ) or b . endswith ( '.bai' ) ) and v is not None }
if bams :
for key , val in bams . items ( ) :
job . fileStore . logToMaster ( 'Deleting "%s" for patient "%s".' % ( key , patient_id ) )
job . fileStore . deleteGlobalFile ( val... |
def wkhtmltopdf_args_mapping ( data ) :
"""fix our names to wkhtmltopdf ' s args""" | mapping = { 'cookies' : 'cookie' , 'custom-headers' : 'custom-header' , 'run-scripts' : 'run-script' }
return { mapping . get ( k , k ) : v for k , v in data . items ( ) } |
def parse_filename_meta ( filename ) :
"""taken from suvi code by vhsu
Parse the metadata from a product filename , either L1b or l2.
- file start
- file end
- platform
- product
: param filename : string filename of product
: return : ( start datetime , end datetime , platform )""" | common_pattern = "_%s_%s" % ( "(?P<product>[a-zA-Z]{3}[a-zA-Z]?-[a-zA-Z0-9]{2}[a-zA-Z0-9]?-[a-zA-Z0-9]{4}[a-zA-Z0-9]?)" , # product l1b , or l2
"(?P<platform>[gG][1-9]{2})" # patform , like g16
)
patterns = { # all patterns must have the common componennt
"l2_pattern" : re . compile ( "%s_s(?P<start>[0-9]{8}T[0-9]{6})Z... |
def validate_instance ( cls , opts ) :
"""Validates an instance of global options for cases that are not prohibited via registration .
For example : mutually exclusive options may be registered by passing a ` mutually _ exclusive _ group ` ,
but when multiple flags must be specified together , it can be necessa... | if opts . loop and ( not opts . v2 or opts . v1 ) :
raise OptionsError ( 'The --loop option only works with @console_rules, and thus requires ' '`--v2 --no-v1` to function as expected.' )
if opts . loop and not opts . enable_pantsd :
raise OptionsError ( 'The --loop option requires `--enable-pantsd`, in order t... |
def to_file ( self , filepath ) :
"""Write the contents of the reflog instance to a file at the given filepath .
: param filepath : path to file , parent directories are assumed to exist""" | lfd = LockedFD ( filepath )
assure_directory_exists ( filepath , is_file = True )
fp = lfd . open ( write = True , stream = True )
try :
self . _serialize ( fp )
lfd . commit ( )
except Exception : # on failure it rolls back automatically , but we make it clear
lfd . rollback ( )
raise |
def get_subject ( self , text ) :
"""Email template subject is the first
line of the email template , we can optionally
add SUBJECT : to make it clearer""" | first_line = text . splitlines ( True ) [ 0 ]
# TODO second line should be empty
if first_line . startswith ( 'SUBJECT:' ) :
subject = first_line [ len ( 'SUBJECT:' ) : ]
else :
subject = first_line
return subject . strip ( ) |
def get_vmpolicy_macaddr_input_mac ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vmpolicy_macaddr = ET . Element ( "get_vmpolicy_macaddr" )
config = get_vmpolicy_macaddr
input = ET . SubElement ( get_vmpolicy_macaddr , "input" )
mac = ET . SubElement ( input , "mac" )
mac . text = kwargs . pop ( 'mac' )
callback = kwargs . pop ( 'callback' , self . _callback )... |
def color_worker ( srcs , window , ij , args ) :
"""A user function .""" | src = srcs [ 0 ]
arr = src . read ( window = window )
arr = to_math_type ( arr )
for func in parse_operations ( args [ "ops_string" ] ) :
arr = func ( arr )
# scaled 0 to 1 , now scale to outtype
return scale_dtype ( arr , args [ "out_dtype" ] ) |
def _inject_config_source ( self , source_filename , files_to_inject ) :
"""Inject existing environmental config with namespace sourcing .
Returns a tuple of the first file name and path found .""" | # src _ path = os . path . join ( self . directory . root _ dir , source _ filename )
# src _ exec = " [ - r % s ] & & . % s " % ( src _ path , src _ path )
src_exec = "[ -r {0} ] && . {0}" . format ( os . path . join ( self . directory . root_dir , source_filename ) )
# The ridiculous construction above is necessary t... |
def with_cache_loader ( self , func , only_read = False ) :
"""> > > cache = Cache ( log _ level = logging . WARNING )
> > > def cache _ loader ( key ) : pass
> > > cache . with _ cache _ loader ( cache _ loader )
True
> > > def cache _ loader _ b ( key , value ) : pass
> > > cache . with _ cache _ loader... | self . logger . info ( 'Enabled cache loader %s' % get_function_signature ( func ) )
self . cache_loader = func
return True |
def h_boiling_Han_Lee_Kim ( m , x , Dh , rhol , rhog , mul , kl , Hvap , Cpl , q , A_channel_flow , wavelength , chevron_angle = 45 ) :
r'''Calculates the two - phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger , as
developed in [ 1 ] _ from experiments ... | chevron_angle = radians ( chevron_angle )
G = m / A_channel_flow
# For once , clearly defined in the publication
G_eq = G * ( ( 1. - x ) + x * ( rhol / rhog ) ** 0.5 )
Re_eq = G_eq * Dh / mul
Bo_eq = q / ( G_eq * Hvap )
Pr = Prandtl ( Cp = Cpl , k = kl , mu = mul )
Ge1 = 2.81 * ( wavelength / Dh ) ** - 0.041 * chevron_... |
def _do_stack ( self , cmd , args ) :
"""Manage the shell stack .
stack Display the stack .
stack < depth > Exit to the stack by its depth .""" | if not args :
self . __dump_stack ( )
return
if len ( args ) > 1 :
self . stderr . write ( 'stack: too many arguments: {}\n' . format ( args ) )
return
try :
depth = int ( args [ 0 ] )
except ValueError :
self . stderr . write ( "stack: depth is not an integer: '{}'\n" . format ( args [ 0 ] ) )
... |
def get_op_result_name ( left , right ) :
"""Find the appropriate name to pin to an operation result . This result
should always be either an Index or a Series .
Parameters
left : { Series , Index }
right : object
Returns
name : object
Usually a string""" | # ` left ` is always a pd . Series when called from within ops
if isinstance ( right , ( ABCSeries , pd . Index ) ) :
name = _maybe_match_name ( left , right )
else :
name = left . name
return name |
def with_subquery ( cls , * paths ) :
"""Eagerload for simple cases where we need to just
joined load some relations
In strings syntax , you can split relations with dot
( it ' s SQLAlchemy feature )
: type paths : * List [ str ] | * List [ InstrumentedAttribute ]
Example 1:
User . with _ subquery ( ' p... | options = [ subqueryload ( path ) for path in paths ]
return cls . query . options ( * options ) |
def set_roots ( self , uproot_with = None ) :
'''Set the roots of the tree in the os environment
Parameters :
uproot _ with ( str ) :
A new TREE _ DIR path used to override an existing TREE _ DIR environment variable''' | # Check for TREE _ DIR
self . treedir = os . environ . get ( 'TREE_DIR' , None ) if not uproot_with else uproot_with
if not self . treedir :
treefilepath = os . path . dirname ( os . path . abspath ( __file__ ) )
if 'python/' in treefilepath :
self . treedir = treefilepath . rsplit ( '/' , 2 ) [ 0 ]
... |
def _decrypt_object ( obj , ** kwargs ) :
'''Recursively try to decrypt any object . If the object is a six . string _ types
( string or unicode ) , and it contains a valid NACLENC pretext , decrypt it ,
otherwise keep going until a string is found .''' | if salt . utils . stringio . is_readable ( obj ) :
return _decrypt_object ( obj . getvalue ( ) , ** kwargs )
if isinstance ( obj , six . string_types ) :
if re . search ( NACL_REGEX , obj ) is not None :
return __salt__ [ 'nacl.dec' ] ( re . search ( NACL_REGEX , obj ) . group ( 1 ) , ** kwargs )
el... |
def set_available ( self , show = None ) :
"""Sets the agent availability to True .
Args :
show ( aioxmpp . PresenceShow , optional ) : the show state of the presence ( Default value = None )""" | show = self . state . show if show is None else show
self . set_presence ( PresenceState ( available = True , show = show ) ) |
def disable_key ( self ) :
"""Disable an existing API Key .""" | print ( "This command will disable a enabled key." )
apiKeyID = input ( "API Key ID: " )
try :
key = self . _curl_bitmex ( "/apiKey/disable" , postdict = { "apiKeyID" : apiKeyID } )
print ( "Key with ID %s disabled." % key [ "id" ] )
except :
print ( "Unable to disable key, please try again." )
self . d... |
def _removeLru ( self ) :
"""Remove the least recently used file handle from the cache .
The pop method removes an element from the right of the deque .
Returns the name of the file that has been removed .""" | ( dataFile , handle ) = self . _cache . pop ( )
handle . close ( )
return dataFile |
def _set_mpls_state ( self , v , load = False ) :
"""Setter method for mpls _ state , mapped from YANG variable / mpls _ state ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ mpls _ state is considered as a private
method . Backends looking to populate t... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = mpls_state . mpls_state , is_container = 'container' , presence = False , yang_name = "mpls-state" , rest_name = "mpls-state" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa... |
def get_optparser ( self ) :
"""Hook for subclasses to set the option parser for the
top - level command / shell .
This option parser is used retrieved and used by ` . main ( ) ' to
handle top - level options .
The default implements a single ' - h | - - help ' option . Sub - classes
can return None to ha... | version = ( self . version is not None and "%s %s" % ( self . _name_str , self . version ) or None )
return CmdlnOptionParser ( self , version = version ) |
def SetUsername ( self , username ) :
"""Sets the username .
Args :
username ( str ) : username to authenticate with .""" | self . _username = username
logger . debug ( 'Elasticsearch username: {0!s}' . format ( username ) ) |
def fromWSDL ( self , wsdl ) :
'''setup the service description from WSDL ,
should not need to override .''' | assert isinstance ( wsdl , WSDLTools . WSDL ) , 'expecting WSDL instance'
if len ( wsdl . services ) == 0 :
raise WsdlGeneratorError , 'No service defined'
self . reset ( )
self . wsdl = wsdl
self . setUpHeader ( )
self . setUpImports ( )
for service in wsdl . services :
sd = self . _service_class ( service . n... |
def split_raster ( rs , split_shp , field_name , temp_dir ) :
"""Split raster by given shapefile and field name .
Args :
rs : origin raster file .
split _ shp : boundary ( ESRI Shapefile ) used to spilt raster .
field _ name : field name identify the spilt value .
temp _ dir : directory to store the spilt... | UtilClass . rmmkdir ( temp_dir )
ds = ogr_Open ( split_shp )
lyr = ds . GetLayer ( 0 )
lyr . ResetReading ( )
ft = lyr . GetNextFeature ( )
while ft :
cur_field_name = ft . GetFieldAsString ( field_name )
for r in rs :
cur_file_name = r . split ( os . sep ) [ - 1 ]
outraster = temp_dir + os . se... |
def createComboContract ( self , symbol , legs , currency = "USD" , exchange = None ) :
"""Used for ComboLegs . Expecting list of legs""" | exchange = legs [ 0 ] . m_exchange if exchange is None else exchange
contract_tuple = ( symbol , "BAG" , exchange , currency , "" , 0.0 , "" )
contract = self . createContract ( contract_tuple , comboLegs = legs )
return contract |
def close ( self ) :
"""Closes the connection .
No further operations are allowed , either on the connection or any
of its cursors , once the connection is closed .
If the connection is used in a ` ` with ` ` statement , this method will
be automatically called at the end of the ` ` with ` ` block .""" | if self . _closed :
raise ProgrammingError ( 'the connection is already closed' )
for cursor_ref in self . _cursors :
cursor = cursor_ref ( )
if cursor is not None and not cursor . _closed :
cursor . close ( )
self . _client . close_connection ( self . _id )
self . _client . close ( )
self . _closed... |
def EnablePlugins ( self , plugin_includes ) :
"""Enables parser plugins .
Args :
plugin _ includes ( list [ str ] ) : names of the plugins to enable , where None
or an empty list represents all plugins . Note that the default plugin
is handled separately .""" | super ( SyslogParser , self ) . EnablePlugins ( plugin_includes )
self . _plugin_by_reporter = { }
for plugin in self . _plugins :
self . _plugin_by_reporter [ plugin . REPORTER ] = plugin |
def _id_or_key ( list_item ) :
'''Return the value at key ' id ' or ' key ' .''' | if isinstance ( list_item , dict ) :
if 'id' in list_item :
return list_item [ 'id' ]
if 'key' in list_item :
return list_item [ 'key' ]
return list_item |
def load ( self , file_key ) :
"""Load the data .""" | var = self . sd . select ( file_key )
data = xr . DataArray ( from_sds ( var , chunks = CHUNK_SIZE ) , dims = [ 'y' , 'x' ] ) . astype ( np . float32 )
data = data . where ( data != var . _FillValue )
try :
data = data * np . float32 ( var . scale_factor )
except AttributeError :
pass
return data |
def _minimize_and_clip ( optimizer , objective , var_list , clip_val = 10 ) :
"""Minimized ` objective ` using ` optimizer ` w . r . t . variables in
` var _ list ` while ensure the norm of the gradients for each
variable is clipped to ` clip _ val `""" | gradients = optimizer . compute_gradients ( objective , var_list = var_list )
for i , ( grad , var ) in enumerate ( gradients ) :
if grad is not None :
gradients [ i ] = ( tf . clip_by_norm ( grad , clip_val ) , var )
return gradients |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.