signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def addRule ( self , doc , func , _preprocess = True ) :
"""Add a grammar rules to _ self . rules _ , _ self . rule2func _ ,
and _ self . rule2name _
Comments , lines starting with # and blank lines are stripped from
doc . We also allow limited form of * and + when there it is of
the RHS has a single item ,... | fn = func
# remove blanks lines and comment lines , e . g . lines starting with " # "
doc = os . linesep . join ( [ s for s in doc . splitlines ( ) if s and not re . match ( "^\s*#" , s ) ] )
rules = doc . split ( )
index = [ ]
for i in range ( len ( rules ) ) :
if rules [ i ] == '::=' :
index . append ( i ... |
def prior ( self , samples ) :
"""priori distribution
Parameters
samples : list
a collection of sample , it ' s a ( NUM _ OF _ INSTANCE * NUM _ OF _ FUNCTIONS ) matrix ,
representing { { w11 , w12 , . . . , w1k } , { w21 , w22 , . . . w2k } , . . . { wk1 , wk2 , . . . , wkk } }
Returns
float
priori di... | ret = np . ones ( NUM_OF_INSTANCE )
for i in range ( NUM_OF_INSTANCE ) :
for j in range ( self . effective_model_num ) :
if not samples [ i ] [ j ] > 0 :
ret [ i ] = 0
if self . f_comb ( 1 , samples [ i ] ) >= self . f_comb ( self . target_pos , samples [ i ] ) :
ret [ i ] = 0
return... |
def list_images ( img_dpath_ , ignore_list = [ ] , recursive = False , fullpath = False , full = None , sort = True ) :
r"""Returns a list of images in a directory . By default returns relative paths .
TODO : rename to ls _ images
TODO : Change all instances of fullpath to full
Args :
img _ dpath _ ( str ) ... | # if not QUIET :
# print ( ignore _ list )
if full is not None :
fullpath = fullpath or full
img_dpath_ = util_str . ensure_unicode ( img_dpath_ )
img_dpath = realpath ( img_dpath_ )
ignore_set = set ( ignore_list )
gname_list_ = [ ]
assertpath ( img_dpath )
# Get all the files in a directory recursively
true_imgpa... |
def data_files ( self ) :
"""Returns a python list of all ( sharded ) data subset files .
Returns :
python list of all ( sharded ) data set files .
Raises :
ValueError : if there are not data _ files matching the subset .""" | tf_record_pattern = os . path . join ( FLAGS . data_dir , '%s-*' % self . subset )
data_files = tf . gfile . Glob ( tf_record_pattern )
if not data_files :
print ( 'No files found for dataset %s/%s at %s' % ( self . name , self . subset , FLAGS . data_dir ) )
self . download_message ( )
exit ( - 1 )
return ... |
def _make_class_unpicklable ( cls ) :
"""Make the given class un - picklable .""" | def _break_on_call_reduce ( self ) :
raise TypeError ( '%r cannot be pickled' % self )
cls . __reduce__ = _break_on_call_reduce
cls . __module__ = '<unknown>' |
def list_permissions ( self , group_name = None , resource = None , url_prefix = None , auth = None , session = None , send_opts = None ) :
"""List the permission sets for the logged in user
Optionally filter by resource or group .
Args :
group _ name ( string ) : Name of group to filter on
resource ( inter... | filter_params = { }
if group_name :
filter_params [ "group" ] = group_name
if resource :
filter_params . update ( resource . get_dict_route ( ) )
req = self . get_permission_request ( 'GET' , 'application/json' , url_prefix , auth , query_params = filter_params )
prep = session . prepare_request ( req )
resp = ... |
def Overlay_setInspectMode ( self , mode , ** kwargs ) :
"""Function path : Overlay . setInspectMode
Domain : Overlay
Method name : setInspectMode
Parameters :
Required arguments :
' mode ' ( type : InspectMode ) - > Set an inspection mode .
Optional arguments :
' highlightConfig ' ( type : HighlightC... | expected = [ 'highlightConfig' ]
passed_keys = list ( kwargs . keys ( ) )
assert all ( [ ( key in expected ) for key in passed_keys ] ) , "Allowed kwargs are ['highlightConfig']. Passed kwargs: %s" % passed_keys
subdom_funcs = self . synchronous_command ( 'Overlay.setInspectMode' , mode = mode , ** kwargs )
return subd... |
def read_blocking ( self ) :
"""Same as read , except blocks untill data is available to be read .""" | while True :
data = self . _read ( )
if data != None :
break
return self . _parse_message ( data ) |
def update_frame ( self , key , ranges = None , plot = None , element = None ) :
"""Updates an existing plot with data corresponding
to the key .""" | reused = isinstance ( self . hmap , DynamicMap ) and ( self . overlaid or self . batched )
if not reused and element is None :
element = self . _get_frame ( key )
elif element is not None :
self . current_key = key
self . current_frame = element
renderer = self . handles . get ( 'glyph_renderer' , None )
gl... |
def step_note_that ( context , remark ) :
"""Used as generic step that provides an additional remark / hint
and enhance the readability / understanding without performing any check .
. . code - block : : gherkin
Given that today is " April 1st "
But note that " April 1st is Fools day ( and beware ) " """ | log = getattr ( context , "log" , None )
if log :
log . info ( u"NOTE: %s;" % remark ) |
def wait_for_responses ( self , client ) :
"""Waits for all responses to come back and resolves the
eventual results .""" | assert_open ( self )
if self . has_pending_requests :
raise RuntimeError ( 'Cannot wait for responses if there are ' 'pending requests outstanding. You need ' 'to wait for pending requests to be sent ' 'first.' )
pending = self . pending_responses
self . pending_responses = [ ]
for command_name , options , promise... |
def WindowsSdkVersion ( self ) :
"""Microsoft Windows SDK versions for specified MSVC + + version .""" | if self . vc_ver <= 9.0 :
return ( '7.0' , '6.1' , '6.0a' )
elif self . vc_ver == 10.0 :
return ( '7.1' , '7.0a' )
elif self . vc_ver == 11.0 :
return ( '8.0' , '8.0a' )
elif self . vc_ver == 12.0 :
return ( '8.1' , '8.1a' )
elif self . vc_ver >= 14.0 :
return ( '10.0' , '8.1' ) |
def qos_map_cos_traffic_class_cos4 ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" )
map = ET . SubElement ( qos , "map" )
cos_traffic_class = ET . SubElement ( map , "cos-traffic-class" )
name_key = ET . SubElement ( cos_traffic_class , "name" )
name_key . text = kwargs . pop ( 'nam... |
def _schedule_pending_unlocked ( self , state ) :
"""Consider the pending transfers for a stream , pumping new chunks while
the unacknowledged byte count is below : attr : ` window _ size _ bytes ` . Must
be called with the FileStreamState lock held .
: param FileStreamState state :
Stream to schedule chunk... | while state . jobs and state . unacked < self . window_size_bytes :
sender , fp = state . jobs [ 0 ]
s = fp . read ( self . IO_SIZE )
if s :
state . unacked += len ( s )
sender . send ( mitogen . core . Blob ( s ) )
else : # File is done . Cause the target ' s receive loop to exit by
... |
def search_url ( self , searchterm ) :
"""Search for URLs
: type searchterm : str
: rtype : list""" | return self . __search ( type_attribute = self . __mispurltypes ( ) , value = searchterm ) |
def dots_to_empty_cells ( config , tsv_fpath ) :
"""Put dots instead of empty cells in order to view TSV with column - t""" | def proc_line ( l , i ) :
while '\t\t' in l :
l = l . replace ( '\t\t' , '\t.\t' )
return l
return iterate_file ( config , tsv_fpath , proc_line , suffix = 'dots' ) |
def deprecate_and_include ( parser , token ) :
"""Raises a deprecation warning about using the first argument . The
remaining arguments are passed to an ` ` { % include % } ` ` tag . Usage : :
{ % deprecate _ and _ include " old _ template . html " " new _ template . html " % }
In order to avoid re - implemen... | split_contents = token . split_contents ( )
current_template = split_contents [ 1 ]
new_template = split_contents [ 2 ]
if settings . DEBUG :
warnings . simplefilter ( 'always' , DeprecationWarning )
warnings . warn ( "The %s template is deprecated; Use %s instead." % ( current_template , new_template ) , Deprecati... |
def exchange_partition ( self , partitionSpecs , source_db , source_table_name , dest_db , dest_table_name ) :
"""Parameters :
- partitionSpecs
- source _ db
- source _ table _ name
- dest _ db
- dest _ table _ name""" | self . send_exchange_partition ( partitionSpecs , source_db , source_table_name , dest_db , dest_table_name )
return self . recv_exchange_partition ( ) |
def phi_from_spinx_spiny ( spinx , spiny ) :
"""Returns the angle between the x - component axis and the in - plane spin .""" | phi = numpy . arctan2 ( spiny , spinx )
return phi % ( 2 * numpy . pi ) |
def list_cron_job_for_all_namespaces ( self , ** kwargs ) :
"""list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . list _ cron _ job _ for _ all _ namespaces ( async _ req = T... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_cron_job_for_all_namespaces_with_http_info ( ** kwargs )
else :
( data ) = self . list_cron_job_for_all_namespaces_with_http_info ( ** kwargs )
return data |
def _remove_duplicates ( self ) :
"""Remove every maximal rectangle contained by another one .""" | contained = set ( )
for m1 , m2 in itertools . combinations ( self . _max_rects , 2 ) :
if m1 . contains ( m2 ) :
contained . add ( m2 )
elif m2 . contains ( m1 ) :
contained . add ( m1 )
# Remove from max _ rects
self . _max_rects = [ m for m in self . _max_rects if m not in contained ] |
def transform ( self , X ) :
"""Return this basis applied to X .
Parameters
X : ndarray
of shape ( N , d ) of observations where N is the number of samples ,
and d is the dimensionality of X .
Returns
ndarray :
of shape ( N , d + 1 ) , or ( N , d ) depending on onescol .""" | N , D = X . shape
return np . hstack ( ( np . ones ( ( N , 1 ) ) , X ) ) if self . onescol else X |
def project ( self , projected_meta = None , new_attr_dict = None , all_but_meta = None , projected_regs = None , new_field_dict = None , all_but_regs = None ) :
"""* Wrapper of * ` ` PROJECT ` `
The PROJECT operator creates , from an existing dataset , a new dataset with all the samples
( with their regions an... | projected_meta_exists = False
if isinstance ( projected_meta , list ) and all ( [ isinstance ( x , str ) for x in projected_meta ] ) :
projected_meta = Some ( projected_meta )
projected_meta_exists = True
elif projected_meta is None :
projected_meta = none ( )
else :
raise TypeError ( "projected_meta mu... |
def cmd ( self , endpoints , cmd ) :
"""endpoints is [ ( host1 , port1 ) , ( host2 , port ) , . . . ]""" | replies = [ ]
for ep in endpoints :
try :
replies . append ( self . _cmd ( ep , cmd ) )
except self . CmdFailed as ex : # if there ' s only 1 endpoint , give up .
# if there ' s more , keep trying .
if len ( endpoints ) == 1 :
raise ex
return "" . join ( replies ) |
def insert_from_segwizard ( self , fileobj , instruments , name , version = None , comment = None ) :
"""Parse the contents of the file object fileobj as a
segwizard - format segment list , and insert the result as a
new list of " active " segments into this LigolwSegments
object . A new entry will be created... | self . add ( LigolwSegmentList ( active = segmentsUtils . fromsegwizard ( fileobj , coltype = LIGOTimeGPS ) , instruments = instruments , name = name , version = version , comment = comment ) ) |
def move ( self , i , lat , lng , change_time = True ) :
'''move a rally point''' | if i < 1 or i > self . rally_count ( ) :
print ( "Invalid rally point number %u" % i )
self . rally_points [ i - 1 ] . lat = int ( lat * 1e7 )
self . rally_points [ i - 1 ] . lng = int ( lng * 1e7 )
if change_time :
self . last_change = time . time ( ) |
def help ( self , print_output = True ) :
"""Calls the help RPC , which returns the list of RPC calls available .
This RPC should normally be used in an interactive console environment
where the output should be printed instead of returned . Otherwise ,
newlines will be escaped , which will make the output di... | help_text = self . _rpc ( 'help' )
if print_output :
print ( help_text )
else :
return help_text |
def detect_ts ( df , max_anoms = 0.10 , direction = 'pos' , alpha = 0.05 , only_last = None , threshold = None , e_value = False , longterm = False , piecewise_median_period_weeks = 2 , plot = False , y_log = False , xlabel = '' , ylabel = 'count' , title = None , verbose = False ) :
"""Anomaly Detection Using Seas... | if not isinstance ( df , DataFrame ) :
raise ValueError ( "data must be a single data frame." )
else :
if len ( df . columns ) != 2 or not df . iloc [ : , 1 ] . map ( np . isreal ) . all ( ) :
raise ValueError ( ( "data must be a 2 column data.frame, with the" "first column being a set of timestamps, an... |
def get_trees ( self , data , showerrors = False ) : # - > list :
"""returns a list of trees with valid guesses""" | if not all ( check ( self . _productionset . alphabet , [ x ] ) for x in data ) :
raise ValueError ( "Unknown element in {}, alphabet:{}" . format ( str ( data ) , self . productionset . alphabet ) )
result = self . __recursive_parser ( self . _productionset . initialsymbol , data , self . _productionset . main_pro... |
def _getGlobals ( self , ** kwargs ) :
"""Return the globals dictionary for the formula calculation""" | # Default globals
globs = { "__builtins__" : None , "all" : all , "any" : any , "bool" : bool , "chr" : chr , "cmp" : cmp , "complex" : complex , "divmod" : divmod , "enumerate" : enumerate , "float" : float , "format" : format , "frozenset" : frozenset , "hex" : hex , "int" : int , "len" : len , "list" : list , "long"... |
def rand_email ( ) :
"""Random email .
Usage Example : :
> > > rand _ email ( )
Z4Lljcbdw7m @ npa . net""" | name = random . choice ( string . ascii_letters ) + rand_str ( string . ascii_letters + string . digits , random . randint ( 4 , 14 ) )
domain = rand_str ( string . ascii_lowercase , random . randint ( 2 , 10 ) )
kind = random . choice ( _all_email_kinds )
return "%s@%s%s" % ( name , domain , kind ) |
def delete_collection_node ( self , ** kwargs ) : # noqa : E501
"""delete _ collection _ node # noqa : E501
delete collection of Node # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ co... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_collection_node_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . delete_collection_node_with_http_info ( ** kwargs )
# noqa : E501
return data |
def getMapScale ( self , latitude , level , dpi = 96 ) :
'''returns the map scale on the dpi of the screen''' | dpm = dpi / 0.0254
# convert to dots per meter
return self . getGroundResolution ( latitude , level ) * dpm |
def request_system_arm ( blink , network ) :
"""Arm system .
: param blink : Blink instance .
: param network : Sync module network id .""" | url = "{}/network/{}/arm" . format ( blink . urls . base_url , network )
return http_post ( blink , url ) |
def close ( self ) :
"""Flush data , write 28 bytes BGZF EOF marker , and close BGZF file .
samtools will look for a magic EOF marker , just a 28 byte empty BGZF
block , and if it is missing warns the BAM file may be truncated . In
addition to samtools writing this block , so too does bgzip - so this
implem... | if self . _buffer :
self . flush ( )
self . _handle . write ( _bgzf_eof )
self . _handle . flush ( )
self . _handle . close ( ) |
def __display_top ( self , stat_display , stats ) :
"""Display the second line in the Curses interface .
< QUICKLOOK > + CPU | PERCPU + < GPU > + MEM + SWAP + LOAD""" | self . init_column ( )
self . new_line ( )
# Init quicklook
stat_display [ 'quicklook' ] = { 'msgdict' : [ ] }
# Dict for plugins width
plugin_widths = { }
for p in self . _top :
plugin_widths [ p ] = self . get_stats_display_width ( stat_display . get ( p , 0 ) ) if hasattr ( self . args , 'disable_' + p ) else 0
... |
def signedDistance ( actor , maxradius = 0.5 , bounds = ( 0 , 1 , 0 , 1 , 0 , 1 ) , dims = ( 10 , 10 , 10 ) ) :
"""` ` vtkSignedDistance ` ` filter .
: param float maxradius : how far out to propagate distance calculation
: param list bounds : volume bounds .""" | dist = vtk . vtkSignedDistance ( )
dist . SetInputData ( actor . polydata ( True ) )
dist . SetRadius ( maxradius )
dist . SetBounds ( bounds )
dist . SetDimensions ( dims )
dist . Update ( )
return Volume ( dist . GetOutput ( ) ) |
def determine_intent ( self , utterance , num_results = 1 , include_tags = False , context_manager = None ) :
"""Given an utterance , provide a valid intent .
Args :
utterance ( str ) : an ascii or unicode string representing natural language speech
include _ tags ( list ) : includes the parsed tags ( includi... | parser = Parser ( self . tokenizer , self . tagger )
parser . on ( 'tagged_entities' , ( lambda result : self . emit ( "tagged_entities" , result ) ) )
context = [ ]
if context_manager :
context = context_manager . get_context ( )
for result in parser . parse ( utterance , N = num_results , context = context ) :
... |
def checkMgtKeyInUse ( self , CorpNum , MgtKeyType , MgtKey ) :
"""파트너 관리번호 사용중 여부 확인 .
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of [ ' SELL ' , ' BUY ' , ' TRUSTEE ' ]
MgtKey : 파트너 관리번호
return
사용중 여부 by True / False
raise
PopbillExcept... | if MgtKeyType not in self . __MgtKeyTypes :
raise PopbillException ( - 99999999 , "관리번호 형태가 올바르지 않습니다." )
if MgtKey == None or MgtKey == "" :
raise PopbillException ( - 99999999 , "관리번호가 입력되지 않았습니다." )
try :
result = self . _httpget ( '/Taxinvoice/' + MgtKeyType + "/" + MgtKey , CorpNum )
return result ... |
def get_version ( ) :
"returns the libdbus library version as a tuple of integers ( major , minor , micro ) ." | major = ct . c_int ( )
minor = ct . c_int ( )
micro = ct . c_int ( )
dbus . dbus_get_version ( ct . byref ( major ) , ct . byref ( minor ) , ct . byref ( micro ) )
return ( major . value , minor . value , micro . value ) |
def _required_attr ( self , attr , key ) :
"""Wrapper for getting required attributes .""" | assert isinstance ( attr , dict )
if key not in attr :
raise AttributeError ( "Required attribute {} not found." . format ( key ) )
return attr [ key ] |
def default_partfactory ( part_number = None , content_length = None , content_type = None , content_md5 = None ) :
"""Get default part factory .
: param part _ number : The part number . ( Default : ` ` None ` ` )
: param content _ length : The content length . ( Default : ` ` None ` ` )
: param content _ ty... | return content_length , part_number , request . stream , content_type , content_md5 , None |
def outputjson ( self , obj ) :
"""Serialize ` obj ` with JSON and output to the client""" | self . header ( 'Content-Type' , 'application/json' )
self . outputdata ( json . dumps ( obj ) . encode ( 'ascii' ) ) |
def make_node_dict ( outer_list , sort = "zone" ) :
"""Convert node data from nested - list to sorted dict .""" | raw_dict = { }
x = 1
for inner_list in outer_list :
for node in inner_list :
raw_dict [ x ] = node
x += 1
if sort == "name" : # sort by provider - name
srt_dict = OrderedDict ( sorted ( raw_dict . items ( ) , key = lambda k : ( k [ 1 ] . cloud , k [ 1 ] . name . lower ( ) ) ) )
else : # sort by ... |
async def on_data_error ( self , exception ) :
"""Handle error .""" | self . logger . error ( 'Encountered error on socket.' , exc_info = ( type ( exception ) , exception , None ) )
await self . disconnect ( expected = False ) |
def initialise_arrays ( group , f ) :
"""Create EArrays for calibrated hits""" | for node in [ 'pos_x' , 'pos_y' , 'pos_z' , 'dir_x' , 'dir_y' , 'dir_z' , 'du' , 'floor' , 't0' ] :
if node in [ 'floor' , 'du' ] :
atom = U1_ATOM
else :
atom = F4_ATOM
f . create_earray ( group , node , atom , ( 0 , ) , filters = FILTERS ) |
def parse_plunge_bearing ( plunge , bearing ) :
"""Parses strings of plunge and bearing and returns a consistent plunge and
bearing measurement as floats . Plunge angles returned by this function will
always be between 0 and 90.
If no direction letter ( s ) is present , the plunge is assumed to be measured
... | bearing = parse_azimuth ( bearing )
plunge , direction = split_trailing_letters ( plunge )
if direction is not None :
if opposite_end ( bearing , direction ) :
bearing += 180
if plunge < 0 :
bearing += 180
plunge = - plunge
if plunge > 90 :
bearing += 180
plunge = 180 - plunge
if bearing > 3... |
def value ( self , name ) :
"""get value of a track at the current time""" | return self . tracks . get ( name ) . row_value ( self . controller . row ) |
def cdx_limit ( cdx_iter , limit ) :
"""limit cdx to at most ` limit ` .""" | # for cdx , _ in itertools . izip ( cdx _ iter , xrange ( limit ) ) :
# yield cdx
return ( cdx for cdx , _ in zip ( cdx_iter , range ( limit ) ) ) |
def calibrate_counts ( array , attributes , index ) :
"""Calibration for counts channels .""" | offset = np . float32 ( attributes [ "corrected_counts_offsets" ] [ index ] )
scale = np . float32 ( attributes [ "corrected_counts_scales" ] [ index ] )
array = ( array - offset ) * scale
return array |
def get_derived_metric_tags ( self , id , ** kwargs ) : # noqa : E501
"""Get all tags associated with a specific derived metric definition # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_derived_metric_tags_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . get_derived_metric_tags_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def _format_local_file ( self ) :
"""When args . local _ file empty on Windows , tries to map args . entity to a
unc path .
Updates args . local _ file in - place without returning anything .""" | if self . type != 'file' :
return
if not self . entity :
return
if not is_win :
return
if self . _file_exists ( ) :
return
self . args . local_file = self . _to_unc_path ( self . entity ) |
def _check_file ( self ) :
"""Checks watched file moficiation time and permission changes .""" | try :
self . editor . toPlainText ( )
except RuntimeError :
self . _timer . stop ( )
return
if self . editor and self . editor . file . path :
if not os . path . exists ( self . editor . file . path ) and self . _mtime :
self . _notify_deleted_file ( )
else :
mtime = os . path . getm... |
def write_file ( self , filename , cart_coords = False ) :
"""Write the input string into a file
Option : see _ _ str _ _ method""" | with zopen ( filename , "w" ) as f :
f . write ( self . to_string ( cart_coords ) ) |
def shape ( self ) :
"""Returns ( rowCount , valueCount )""" | bf = self . copy ( )
content = requests . get ( bf . dataset_url ) . json ( )
rowCount = content [ 'status' ] [ 'rowCount' ]
valueCount = content [ 'status' ] [ 'valueCount' ]
return ( rowCount , valueCount ) |
def emitCurrentChanged ( self ) :
"""Emits the current schema changed signal for this combobox , provided \
the signals aren ' t blocked .""" | if ( not self . signalsBlocked ( ) ) :
schema = self . currentSchema ( )
self . currentSchemaChanged . emit ( schema )
if ( schema ) :
self . currentTableChanged . emit ( schema . model ( ) )
else :
self . currentTableChanged . emit ( None ) |
def data ( self , ctx = None ) :
"""Returns a copy of this parameter on one context . Must have been
initialized on this context before .
Parameters
ctx : Context
Desired context .
Returns
NDArray on ctx""" | d = self . _check_and_get ( self . _data , ctx )
if self . _rate :
d = nd . Dropout ( d , self . _rate , self . _mode , self . _axes )
return d |
def find_tags ( self , tokens , ** kwargs ) :
"""Annotates the given list of tokens with part - of - speech tags .
Returns a list of tokens , where each token is now a [ word , tag ] - list .""" | # [ " The " , " cat " , " purs " ] = > [ [ " The " , " DT " ] , [ " cat " , " NN " ] , [ " purs " , " VB " ] ]
return find_tags ( tokens , lexicon = kwargs . get ( "lexicon" , self . lexicon or { } ) , model = kwargs . get ( "model" , self . model ) , morphology = kwargs . get ( "morphology" , self . morphology ) , con... |
def process_infile ( f , fileStore ) :
"""Takes an array of files or a single file and imports into the jobstore .
This returns a tuple or an array of tuples replacing all previous path
strings . Toil does not preserve a file ' s original name upon import and
so the tuple keeps track of this with the format :... | # check if this has already been processed
if isinstance ( f , tuple ) :
return f
elif isinstance ( f , list ) :
return process_array_infile ( f , fileStore )
elif isinstance ( f , basestring ) :
return process_single_infile ( f , fileStore )
else :
raise RuntimeError ( 'Error processing file: ' . forma... |
def _check_rev_dict ( tree , ebt ) :
"""Verifyies that ` ebt ` is the inverse of the ` edgeBySourceId ` data member of ` tree `""" | ebs = defaultdict ( dict )
for edge in ebt . values ( ) :
source_id = edge [ '@source' ]
edge_id = edge [ '@id' ]
ebs [ source_id ] [ edge_id ] = edge
assert ebs == tree [ 'edgeBySourceId' ] |
def create_container ( self , conf , detach , tty ) :
"""Create a single container""" | name = conf . name
image_name = conf . image_name
if conf . tag is not NotSpecified :
image_name = conf . image_name_with_tag
container_name = conf . container_name
with conf . assumed_role ( ) :
env = dict ( e . pair for e in conf . env )
binds = conf . volumes . binds
command = conf . formatted_command
volume... |
def _unweave ( target , advices , pointcut , ctx , depth , depth_predicate ) :
"""Unweave deeply advices in target .""" | # if weaving has to be done
if pointcut is None or pointcut ( target ) : # do something only if target is intercepted
if is_intercepted ( target ) :
_remove_advices ( target = target , advices = advices , ctx = ctx )
# search inside the target
if depth > 0 : # for an object or a class , weave on methods
# g... |
def GetMessages ( self , formatter_mediator , event ) :
"""Determines the formatted message strings for an event object .
Args :
formatter _ mediator ( FormatterMediator ) : mediates the interactions
between formatters and other components , such as storage and Windows
EventLog resources .
event ( EventOb... | if self . DATA_TYPE != event . data_type :
raise errors . WrongFormatter ( 'Invalid event object - unsupported data type: {0:s}' . format ( event . data_type ) )
event_values = event . CopyToDict ( )
number_of_volumes = event_values . get ( 'number_of_volumes' , 0 )
volume_serial_numbers = event_values . get ( 'vol... |
def get_Generic_parameters ( tp , generic_supertype ) :
"""tp must be a subclass of generic _ supertype .
Retrieves the type values from tp that correspond to parameters
defined by generic _ supertype .
E . g . get _ Generic _ parameters ( tp , typing . Mapping ) is equivalent
to get _ Mapping _ key _ value... | try :
res = _select_Generic_superclass_parameters ( tp , generic_supertype )
except TypeError :
res = None
if res is None :
raise TypeError ( "%s has no proper parameters defined by %s." % ( type_str ( tp ) , type_str ( generic_supertype ) ) )
else :
return tuple ( res ) |
def print ( * args , ** kwargs ) :
"""Normally print function in python prints values to a stream / stdout
> > print ( value1 , value2 , sep = ' ' , end = ' \n ' , file = sys . stdout )
Current package usage :
print ( value1 , value2 , sep = ' ' , end = ' \n ' , file = sys . stdout , color = None ,
bg _ col... | # Pop out color and background values from kwargs
color_name = kwargs . pop ( 'color' , None )
bg_color = kwargs . pop ( 'bg_color' , None )
log_type = kwargs . pop ( 'log_type' , None )
# Check formats , create a list of text formats
txt_formats = kwargs . pop ( 'text_format' , [ ] )
if sys . version_info [ 0 ] == 2 :... |
def unproxy ( possible_proxy ) :
'''Unwrap and return the object referenced by a proxy .
This function is very similar to : func : ` get _ reference ` , but works for
both proxies and regular objects . If the specified object is a proxy ,
its reference is extracted with ` ` get _ reference ` ` and returned . ... | while isinstance ( possible_proxy , ThreadLocalProxy ) :
possible_proxy = ThreadLocalProxy . get_reference ( possible_proxy )
return possible_proxy |
def get_culture_pair ( self , code ) :
"""# Return a tuple of the language and country for a given culture code
: param code :
: return :""" | if not any ( x in code for x in ( '_' , '-' ) ) :
raise ValueError ( "%s is not a valid culture code" % code )
cc = CultureCode . objects . get ( code = code . replace ( '_' , '-' ) )
return cc . language , cc . country |
def _reset ( self , server , ** kwargs ) :
"""Reset the server object with new values given as params .
- server : a dict representing the server . e . g the API response .
- kwargs : any meta fields such as cloud _ manager and populated .
Note : storage _ devices and ip _ addresses may be given in server as ... | if server : # handle storage , ip _ address dicts and tags if they exist
Server . _handle_server_subobjs ( server , kwargs . get ( 'cloud_manager' ) )
for key in server :
object . __setattr__ ( self , key , server [ key ] )
for key in kwargs :
object . __setattr__ ( self , key , kwargs [ key ] ) |
def mean_absolute_error ( data , ground_truth , mask = None , normalized = False , force_lower_is_better = True ) :
r"""Return L1 - distance between ` ` data ` ` and ` ` ground _ truth ` ` .
See also ` this Wikipedia article
< https : / / en . wikipedia . org / wiki / Mean _ absolute _ error > ` _ .
Parameter... | if not hasattr ( data , 'space' ) :
data = odl . vector ( data )
space = data . space
ground_truth = space . element ( ground_truth )
l1_norm = odl . solvers . L1Norm ( space )
if mask is not None :
data = data * mask
ground_truth = ground_truth * mask
diff = data - ground_truth
fom = l1_norm ( diff )
if no... |
def get_gradebook_columns_by_gradebooks ( self , gradebook_ids ) :
"""Gets the list of gradebook columns corresponding to a list of ` ` Gradebooks ` ` .
arg : gradebook _ ids ( osid . id . IdList ) : list of gradebook
` ` Ids ` `
return : ( osid . grading . GradebookColumnList ) - list of gradebook
columns ... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ resources _ by _ bins
gradebook_column_list = [ ]
for gradebook_id in gradebook_ids :
gradebook_column_list += list ( self . get_gradebook_columns_by_gradebook ( gradebook_id ) )
return objects . GradebookColumnList ( gradebook_column_li... |
def get_metadata ( self , filename ) :
'''Fetch all availabe metadata''' | obj = self . bucket . Object ( filename )
checksum = 'md5:{0}' . format ( obj . e_tag [ 1 : - 1 ] )
mime = obj . content_type . split ( ';' , 1 ) [ 0 ] if obj . content_type else None
return { 'checksum' : checksum , 'size' : obj . content_length , 'mime' : mime , 'modified' : obj . last_modified , } |
def _get_selected_ids ( self ) :
"""List of currently selected ids""" | selection = self . get_selection ( )
if selection . get_mode ( ) != gtk . SELECTION_MULTIPLE :
raise AttributeError ( 'selected_ids only valid for select_multiple' )
model , selected_paths = selection . get_selected_rows ( )
if selected_paths :
return zip ( * selected_paths ) [ 0 ]
else :
return ( ) |
def patched_function ( self , * args , ** kwargs ) :
"""Step 3 . Wrapped function calling .""" | result = self . function ( * args , ** kwargs )
self . validate ( result )
return result |
def filePath ( self , index ) :
"""Gets the file path of the item at the specified ` ` index ` ` .
: param index : item index - QModelIndex
: return : str""" | return self . _fs_model_source . filePath ( self . _fs_model_proxy . mapToSource ( index ) ) |
def merge ( self , recarray , columns = None ) :
"""Merge another recarray with the same columns into this table .
: Arguments :
recarray
numpy record array that describes the layout and initializes the
table
: Returns :
n number of inserted rows
: Raises :
Raises an exception if duplicate and incom... | len_before = len ( self )
# CREATE TEMP TABLE in database
tmparray = SQLarray ( self . tmp_table_name , records = recarray , columns = columns , connection = self . connection , is_tmp = True )
len_tmp = len ( tmparray )
# insert into main table
SQL = """INSERT OR ABORT INTO __self__ SELECT * FROM %s""" % self . tmp_ta... |
def dataflagatom ( chans , pol , d , sig , mode , conv ) :
"""Wrapper function to get shared memory as numpy array into pool
Assumes data _ mem is global mps . Array""" | data = numpyview ( data_mem , 'complex64' , datashape ( d ) )
# data = n . ma . masked _ array ( data , data = = 0j ) # this causes massive overflagging on 14sep03 data
return rtlib . dataflag ( data , chans , pol , d , sig , mode , conv ) |
def exp_cov ( prices , span = 180 , frequency = 252 ) :
"""Estimate the exponentially - weighted covariance matrix , which gives
greater weight to more recent data .
: param prices : adjusted closing prices of the asset , each row is a date
and each column is a ticker / id .
: type prices : pd . DataFrame
... | if not isinstance ( prices , pd . DataFrame ) :
warnings . warn ( "prices are not in a dataframe" , RuntimeWarning )
prices = pd . DataFrame ( prices )
assets = prices . columns
daily_returns = daily_price_returns ( prices )
N = len ( assets )
# Loop over matrix , filling entries with the pairwise exp cov
S = n... |
def addlayer ( self , name , srs , geomType ) :
"""add a layer to the vector layer
Parameters
name : str
the layer name
srs : int , str or : osgeo : class : ` osr . SpatialReference `
the spatial reference system . See : func : ` spatialist . auxil . crsConvert ` for options .
geomType : int
an OGR we... | self . vector . CreateLayer ( name , srs , geomType )
self . init_layer ( ) |
def get_source_link ( thing , source_location ) :
"""Get a link to the line number a module / class / function is defined at .
Parameters
thing : function or class
Thing to get the link for
source _ location : str
GitHub url of the source code
Returns
str
String with link to the file & line number ,... | try :
lineno = get_line ( thing )
try :
owner_module = inspect . getmodule ( thing )
assert owner_module is not None
except ( TypeError , AssertionError ) :
owner_module = inspect . getmodule ( thing . fget )
thing_file = "/" . join ( owner_module . __name__ . split ( "." ) )
... |
def _create_mapping ( self , func , switch ) :
"""Internal function to create the mapping .""" | mapping = { }
for feature in self . data [ 'features' ] :
content = func ( feature )
if switch == 'style' :
for key , value in content . items ( ) :
if isinstance ( value , MacroElement ) : # Make sure objects are rendered :
if value . _parent is None :
va... |
def make_mutant_tuples ( example_protos , original_feature , index_to_mutate , viz_params ) :
"""Return a list of ` MutantFeatureValue ` s and a list of mutant Examples .
Args :
example _ protos : The examples to mutate .
original _ feature : A ` OriginalFeatureList ` that encapsulates the feature to
mutate... | mutant_features = make_mutant_features ( original_feature , index_to_mutate , viz_params )
mutant_examples = [ ]
for example_proto in example_protos :
for mutant_feature in mutant_features :
copied_example = copy . deepcopy ( example_proto )
feature_name = mutant_feature . original_feature . feature... |
def handle_endtag ( self , tag ) :
"""Handles every end tag like e . g . < / p > .""" | if tag in self . stroke_after_elements :
if self . text . endswith ( self . stroke_text ) : # Only add a stroke if there isn ' t already a stroke posted
# In this case , there was no content between the tags , so
# remove the starting stroke
self . text = self . text [ : - len ( self . stroke_text )... |
def get_beamarea_deg2 ( self , ra , dec ) :
"""Calculate the area of the synthesized beam in square degrees .
Parameters
ra , dec : float
The sky coordinates at which the calculation is made .
Returns
area : float
The beam area in square degrees .""" | barea = abs ( self . beam . a * self . beam . b * np . pi )
# in deg * * 2 at reference coords
if self . lat is not None :
barea /= np . cos ( np . radians ( dec - self . lat ) )
return barea |
def download_setuptools ( version = DEFAULT_VERSION , download_base = DEFAULT_URL , to_dir = os . curdir , delay = 15 ) :
"""Download setuptools from a specified location and return its filename
` version ` should be a valid setuptools version number that is available
as an egg for download under the ` download... | import urllib2 , shutil
egg_name = "setuptools-%s-py%s.egg" % ( version , sys . version [ : 3 ] )
url = download_base + egg_name
saveto = os . path . join ( to_dir , egg_name )
src = dst = None
if not os . path . exists ( saveto ) : # Avoid repeated downloads
try :
from distutils import log
if delay... |
def getSamplingStrategy ( self , serviceName ) :
"""Parameters :
- serviceName""" | self . _seqid += 1
future = self . _reqs [ self . _seqid ] = concurrent . Future ( )
self . send_getSamplingStrategy ( serviceName )
return future |
def save ( self , path ) :
'''Save source video to file .
Args :
path ( str ) : Filename to save to .
Notes : Saves entire source video to file , not just currently selected
frames .''' | # IMPORTANT WARNING : saves entire source video
self . clip . write_videofile ( path , audio_fps = self . clip . audio . fps ) |
def run ( self ) :
"""Index the document . Since ids are predictable ,
we won ' t index anything twice .""" | with self . input ( ) . open ( ) as handle :
body = json . loads ( handle . read ( ) )
es = elasticsearch . Elasticsearch ( )
id = body . get ( '_id' )
es . index ( index = 'frontpage' , doc_type = 'html' , id = id , body = body ) |
def on ( self , event , f = None ) :
"""Registers the function ` ` f ` ` to the event name ` ` event ` ` .
If ` ` f ` ` isn ' t provided , this method returns a function that
takes ` ` f ` ` as a callback ; in other words , you can use this method
as a decorator , like so : :
@ ee . on ( ' data ' )
def da... | def _on ( f ) :
self . _add_event_handler ( event , f , f )
return f
if f is None :
return _on
else :
return _on ( f ) |
def run ( self ) :
"""Include a file as part of the content of this reST file .""" | if not self . state . document . settings . file_insertion_enabled :
raise self . warning ( '"%s" directive disabled.' % self . name )
source = self . state_machine . input_lines . source ( self . lineno - self . state_machine . input_offset - 1 )
source_dir = os . path . dirname ( os . path . abspath ( source ) )
... |
def run_LDA ( df ) :
"""Run LinearDiscriminantAnalysis on input dataframe ( df ) and return
transformed data , scalings and explained variance by discriminants .""" | # Prep variables for sklearn LDA
X = df . iloc [ : , 1 : df . shape [ 1 ] ] . values
# input data matrix
y = df [ "Condition" ] . values
# data categories list
# Calculate LDA
sklearn_lda = LDA ( )
X_lda_sklearn = sklearn_lda . fit_transform ( X , y )
try :
exp_var = sklearn_lda . explained_variance_ratio_
except A... |
def set_connection_ip_list ( addresses = None , grant_by_default = False , server = _DEFAULT_SERVER ) :
'''Set the IPGrant list for the SMTP virtual server .
: param str addresses : A dictionary of IP + subnet pairs .
: param bool grant _ by _ default : Whether the addresses should be a blacklist or whitelist .... | setting = 'IPGrant'
formatted_addresses = list ( )
# It ' s okay to accept an empty list for set _ connection _ ip _ list ,
# since an empty list may be desirable .
if not addresses :
addresses = dict ( )
_LOG . debug ( 'Empty %s specified.' , setting )
# Convert addresses to the ' ip _ address , subnet ' forma... |
def console_get_height_rect ( con : tcod . console . Console , x : int , y : int , w : int , h : int , fmt : str ) -> int :
"""Return the height of this text once word - wrapped into this rectangle .
Returns :
int : The number of lines of text once word - wrapped .
. . deprecated : : 8.5
Use : any : ` Conso... | return int ( lib . TCOD_console_get_height_rect_fmt ( _console ( con ) , x , y , w , h , _fmt ( fmt ) ) ) |
def _set_rightMargin ( self , value ) :
"""value will be an int or float .
Subclasses may override this method .""" | bounds = self . bounds
if bounds is None :
self . width = value
else :
xMin , yMin , xMax , yMax = bounds
self . width = xMax + value |
def qAx ( mt , x , q ) :
"""This function evaluates the APV of a geometrically increasing annual annuity - due""" | q = float ( q )
j = ( mt . i - q ) / ( 1 + q )
mtj = Actuarial ( nt = mt . nt , i = j )
return Ax ( mtj , x ) |
def wrap_response ( resp , api_call ) :
"""Wrap the requests response in an ` ApiResponse ` object
: param object resp : response object provided by the ` requests ` library .
: param object api _ call : Api Call
: return : An ` ApiResponse ` object that wraps the content of the response .
: rtype : object ... | try :
js_resp = resp . json ( )
if resp . ok :
if "items" in js_resp . keys ( ) :
r = ApiListResponse ( js_resp [ "items" ] )
else :
r = ApiDictResponse ( js_resp )
if "paging" in js_resp . keys ( ) :
cursors = js_resp . get ( "paging" , { } ) . get ( ... |
def windows ( self , window_size = 60 , context_len = 90 , step = 10 ) :
'''Walk through the sequence of interest in windows of window _ size ,
evaluate free ( unbound ) pair probabilities .
: param window _ size : Window size in base pairs .
: type window _ size : int
: param context _ len : The number of ... | self . walked = _context_walk ( self . template , window_size , context_len , step )
self . core_starts , self . core_ends , self . scores = zip ( * self . walked )
return self . walked |
def reference_text ( ref ) :
'''Convert a single reference to plain text format
Parameters
ref : dict
Information about a single reference''' | ref_wrap = textwrap . TextWrapper ( initial_indent = '' , subsequent_indent = ' ' * 8 )
s = ''
if ref [ 'type' ] == 'unpublished' :
s += ref_wrap . fill ( ', ' . join ( ref [ 'authors' ] ) ) + '\n'
s += ref_wrap . fill ( ref [ 'title' ] ) + '\n'
s += ref_wrap . fill ( ref [ 'note' ] ) + '\n'
elif ref [ 'typ... |
def get_data ( self , file_id ) :
"""Acquires the data from the table identified by the id .
The file is read only once , consecutive calls to this method will
return the sale collection .
: param file _ id : identifier for the table
: return : all the values from the table""" | if file_id not in self . _file_values :
file_contents = 'cwr_%s.csv' % file_id
self . _file_values [ file_id ] = self . _reader . read_csv_file ( file_contents )
return self . _file_values [ file_id ] |
def check_git ( ) :
"""Check if git command is available .""" | try :
with open ( os . devnull , "wb" ) as devnull :
subprocess . check_call ( [ "git" , "--version" ] , stdout = devnull , stderr = devnull )
except :
raise RuntimeError ( "Please make sure git is installed and on your path." ) |
def rot_rads_v2 ( vec_a , rads ) :
"""Rotate vector by angle in radians .""" | x = vec_a . x * math . cos ( rads ) - vec_a . y * math . sin ( rads )
y = vec_a . x * math . sin ( rads ) + vec_a . y * math . cos ( rads )
return Vec2 ( x , y ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.