signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _wrap_attr ( self , attrs , context = None ) :
"""wrap bound methods of attrs in a InstanceMethod proxies""" | for attr in attrs :
if isinstance ( attr , UnboundMethod ) :
if _is_property ( attr ) :
yield from attr . infer_call_result ( self , context )
else :
yield BoundMethod ( attr , self )
elif hasattr ( attr , "name" ) and attr . name == "<lambda>" :
if attr . args . ... |
def finish ( self , message_id ) :
"""Finish a message ( indicate successful processing ) .""" | self . send ( nsq . finish ( message_id ) )
self . finish_inflight ( )
self . on_finish . send ( self , message_id = message_id ) |
def applyMassCalMs1 ( msrunContainer , specfile , dataFit , ** kwargs ) :
"""Applies a correction function to the MS1 ion m / z arrays in order to
correct for a m / z dependent m / z error .
: param msrunContainer : intance of : class : ` maspy . core . MsrunContainer ` ,
containing the : class : ` maspy . co... | toleranceMode = kwargs . get ( 'toleranceMode' , 'relative' )
if toleranceMode == 'relative' :
for si in msrunContainer . getItems ( specfile , selector = lambda si : si . msLevel == 1 ) :
mzArr = msrunContainer . saic [ specfile ] [ si . id ] . arrays [ 'mz' ]
corrArr = dataFit . corrArray ( mzArr ... |
def remove ( self , priority , observer , callble ) :
"""Remove one observer , which had priority and callble .""" | self . flush ( )
for i in range ( len ( self ) - 1 , - 1 , - 1 ) :
p , o , c = self [ i ]
if priority == p and observer == o and callble == c :
del self . _poc [ i ] |
def lastmod ( self , tag ) :
"""Return the last modification of the entry .""" | lastitems = EntryModel . objects . published ( ) . order_by ( '-modification_date' ) . filter ( tags = tag ) . only ( 'modification_date' )
return lastitems [ 0 ] . modification_date |
def set_physical_page_for_file ( self , pageId , ocrd_file , order = None , orderlabel = None ) :
"""Create a new physical page""" | # print ( pageId , ocrd _ file )
# delete any page mapping for this file . ID
for el_fptr in self . _tree . getroot ( ) . findall ( 'mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"]/mets:fptr[@FILEID="%s"]' % ocrd_file . ID , namespaces = NS ) :
el_fptr . getparent ( ) . remove... |
def child_added ( self , child ) :
"""When a child is added , schedule a data changed notification""" | super ( AndroidViewPager , self ) . child_added ( child )
self . _notify_count += 1
self . get_context ( ) . timed_call ( self . _notify_delay , self . _notify_change ) |
def uppercase_percent_encoding ( text ) :
'''Uppercases percent - encoded sequences .''' | if '%' not in text :
return text
return re . sub ( r'%[a-f0-9][a-f0-9]' , lambda match : match . group ( 0 ) . upper ( ) , text ) |
def PopEvents ( self ) :
"""Pops events from the heap .
Yields :
EventObject : event .""" | event = self . PopEvent ( )
while event :
yield event
event = self . PopEvent ( ) |
def change_issue_status ( self , issue_id , new_status , close_status = None ) :
"""Change the status of an issue .
: param issue _ id : the id of the issue
: param new _ status : the new status fo the issue
: param close _ status : optional param to add reason why issue
has been closed ( like wontfix , fix... | request_url = "{}issue/{}/status" . format ( self . create_basic_url ( ) , issue_id )
payload = { 'status' : new_status }
if close_status is not None :
payload [ 'close_status' ] = close_status
return_value = self . _call_api ( request_url , method = 'POST' , data = payload )
LOG . debug ( return_value ) |
def panzoom ( marks ) :
"""Helper function for panning and zooming over a set of marks .
Creates and returns a panzoom interaction with the ' x ' and ' y ' dimension
scales of the specified marks .""" | return PanZoom ( scales = { 'x' : sum ( [ mark . _get_dimension_scales ( 'x' , preserve_domain = True ) for mark in marks ] , [ ] ) , 'y' : sum ( [ mark . _get_dimension_scales ( 'y' , preserve_domain = True ) for mark in marks ] , [ ] ) } ) |
def pattern_of ( index ) :
'''Return the pattern represented by an index value''' | return np . array ( [ [ index & 2 ** 0 , index & 2 ** 1 , index & 2 ** 2 ] , [ index & 2 ** 3 , index & 2 ** 4 , index & 2 ** 5 ] , [ index & 2 ** 6 , index & 2 ** 7 , index & 2 ** 8 ] ] , bool ) |
def base_communities ( adjacency_matrix ) :
"""Forms the community indicator normalized feature matrix for any graph .
Inputs : - A in R ^ ( nxn ) : Adjacency matrix of an undirected network represented as a SciPy Sparse COOrdinate matrix .
Outputs : - X in R ^ ( nxC _ n ) : The latent space embedding represent... | number_of_nodes = adjacency_matrix . shape [ 0 ]
# X = A + I
adjacency_matrix = adjacency_matrix . tocsr ( )
adjacency_matrix = adjacency_matrix . transpose ( )
features = sparse . csr_matrix ( sparse . eye ( number_of_nodes , number_of_nodes ) ) + adjacency_matrix . tocsr ( )
features = features . tocsr ( )
features .... |
def statfs ( self , path ) :
"Return a statvfs ( 3 ) structure , for stat and df and friends" | # from fuse . py source code :
# class c _ statvfs ( Structure ) :
# _ fields _ = [
# ( ' f _ bsize ' , c _ ulong ) , # preferred size of file blocks , in bytes
# ( ' f _ frsize ' , c _ ulong ) , # fundamental size of file blcoks , in bytes
# ( ' f _ blocks ' , c _ fsblkcnt _ t ) , # total number of blocks in the files... |
def get_host ( environ ) :
"""Return the real host for the given WSGI environment . This takes care
of the ` X - Forwarded - Host ` header .
: param environ : the WSGI environment to get the host of .""" | scheme = environ . get ( 'wsgi.url_scheme' )
if 'HTTP_X_FORWARDED_HOST' in environ :
result = environ [ 'HTTP_X_FORWARDED_HOST' ]
elif 'HTTP_HOST' in environ :
result = environ [ 'HTTP_HOST' ]
else :
result = environ [ 'SERVER_NAME' ]
if ( scheme , str ( environ [ 'SERVER_PORT' ] ) ) not in ( ( 'https' ... |
def end_job_input ( self , job_id ) :
"""EndJobInput
https : / / mo . joyent . com / docs / muskie / master / api . html # EndJobInput""" | log . debug ( "EndJobInput %r" , job_id )
path = "/%s/jobs/%s/live/in/end" % ( self . account , job_id )
headers = { # " Content - Length " : " 0 " # XXX needed ?
}
res , content = self . _request ( path , "POST" , headers = headers )
if res [ "status" ] != '202' :
raise errors . MantaAPIError ( res , content ) |
def start ( token , control = False , trigger = '!' , groups = None , groups_pillar_name = None , fire_all = False , tag = 'salt/engines/slack' ) :
'''Listen to slack events and forward them to salt , new version''' | if ( not token ) or ( not token . startswith ( 'xoxb' ) ) :
time . sleep ( 2 )
# don ' t respawn too quickly
log . error ( 'Slack bot token not found, bailing...' )
raise UserWarning ( 'Slack Engine bot token not configured' )
try :
client = SlackClient ( token = token )
message_generator = clie... |
def get_full_description ( self , s , base = None ) :
"""Get the full description from a docstring
This here and the line above is the full description ( i . e . the
combination of the : meth : ` get _ summary ` and the
: meth : ` get _ extended _ summary ` ) output
Parameters
s : str
The docstring to u... | summary = self . get_summary ( s )
extended_summary = self . get_extended_summary ( s )
ret = ( summary + '\n\n' + extended_summary ) . strip ( )
if base is not None :
self . params [ base + '.full_desc' ] = ret
return ret |
def to_unitary_matrix ( self , qubit_order : ops . QubitOrderOrList = ops . QubitOrder . DEFAULT , qubits_that_should_be_present : Iterable [ ops . Qid ] = ( ) , ignore_terminal_measurements : bool = True , dtype : Type [ np . number ] = np . complex128 ) -> np . ndarray :
"""Converts the circuit into a unitary mat... | if not ignore_terminal_measurements and any ( protocols . is_measurement ( op ) for op in self . all_operations ( ) ) :
raise ValueError ( 'Circuit contains a measurement.' )
if not self . are_all_measurements_terminal ( ) :
raise ValueError ( 'Circuit contains a non-terminal measurement.' )
qs = ops . QubitOrd... |
def _is_parent ( self , roleid1 , roleid2 ) :
"""Test if roleid1 is contained inside roleid2""" | role2 = copy . deepcopy ( self . flatten [ roleid2 ] )
role1 = copy . deepcopy ( self . flatten [ roleid1 ] )
if role1 == role2 :
return False
# Check if role1 is contained by role2
for b1 in role1 [ 'backends_groups' ] :
if b1 not in role2 [ 'backends_groups' ] :
return False
for group in role1 [ '... |
def get_page_generator ( func , start_page = 0 , page_size = None ) :
"""Constructs a generator for retrieving pages from a paginated endpoint . This method is intended for internal
use .
: param func : Should take parameters ` ` page _ number ` ` and ` ` page _ size ` ` and return the corresponding | Page | ob... | # initialize starting values
page_number = start_page
more_pages = True
# continuously request the next page as long as more pages exist
while more_pages : # get next page
page = func ( page_number = page_number , page_size = page_size )
yield page
# determine whether more pages exist
more_pages = page ... |
def get_form_request ( self , submit_name = None , url = None , extra_post = None , remove_from_post = None ) :
"""Submit default form .
: param submit _ name : name of button which should be " clicked " to
submit form
: param url : explicitly specify form action url
: param extra _ post : ( dict or list of... | # pylint : disable = no - member
post = self . form_fields ( )
# Build list of submit buttons which have a name
submit_controls = { }
for elem in self . form . inputs :
if ( elem . tag == 'input' and elem . type == 'submit' and elem . get ( 'name' ) is not None ) :
submit_controls [ elem . name ] = elem
# A... |
def consolidate ( ipFile , opFile ) :
"""make a single index file with 1 record per word which shows the word , file and linenums
# storms , knowledge . csv - 3
# string , rawData . csv - 1
# structure , EVENT _ SYSTEM - PC - FILE . CSV - 18 , OBJECT _ SYSTEM - PC - FILE . CSV - 4 , sample - filelist - for - ... | curFile = ''
curWord = ''
curLineNums = ''
indexedWords = { }
with open ( ipFile , "r" , encoding = 'utf-8' , errors = 'replace' ) as ip :
for line in ip :
cols = line . split ( ',' )
curFile = cols [ 0 ]
curWord = cols [ 1 ]
curLineNums = cols [ 2 ] . strip ( )
# DebugIndexi... |
def random_sample ( value , field , row , num = 10 ) :
"""Collect a random sample of the values in a particular
field based on the reservoir sampling technique .""" | # TODO : Could become a more general DQ piece .
if value is None :
field [ 'has_nulls' ] = True
return
if value in field [ 'samples' ] :
return
if isinstance ( value , basestring ) and not len ( value . strip ( ) ) :
field [ 'has_empty' ] = True
return
if len ( field [ 'samples' ] ) < num :
fiel... |
def specific_path_check ( path , opt ) :
"""Will make checks against include / exclude to determine if we
actually care about the path in question .""" | if opt . exclude :
if path in opt . exclude :
return False
if opt . include :
if path not in opt . include :
return False
return True |
def run_selected_clicked ( self ) :
"""Run the selected scenario .""" | # get all selected rows
rows = sorted ( set ( index . row ( ) for index in self . table . selectedIndexes ( ) ) )
self . enable_busy_cursor ( )
# iterate over selected rows
for row in rows :
current_row = row
item = self . table . item ( current_row , 0 )
status_item = self . table . item ( current_row , 1 ... |
def setup_context_menu ( self ) :
"""Setup shell context menu""" | self . menu = QMenu ( self )
self . cut_action = create_action ( self , _ ( "Cut" ) , shortcut = keybinding ( 'Cut' ) , icon = ima . icon ( 'editcut' ) , triggered = self . cut )
self . copy_action = create_action ( self , _ ( "Copy" ) , shortcut = keybinding ( 'Copy' ) , icon = ima . icon ( 'editcopy' ) , triggered = ... |
def construction_error ( tot_items , block_shape , axes , e = None ) :
"""raise a helpful message about our construction""" | passed = tuple ( map ( int , [ tot_items ] + list ( block_shape ) ) )
# Correcting the user facing error message during dataframe construction
if len ( passed ) <= 2 :
passed = passed [ : : - 1 ]
implied = tuple ( len ( ax ) for ax in axes )
# Correcting the user facing error message during dataframe construction
i... |
def do_read ( self , args ) :
"""read < addr > ( < objid > ( < prop > [ < indx > ] ) . . . ) . . .""" | args = args . split ( )
if _debug :
ReadPropertyMultipleConsoleCmd . _debug ( "do_read %r" , args )
try :
i = 0
addr = args [ i ]
i += 1
read_access_spec_list = [ ]
while i < len ( args ) :
obj_id = ObjectIdentifier ( args [ i ] ) . value
i += 1
prop_reference_list = [ ]
... |
def create_from_url ( self , url , params = None ) :
'''/ vi / iso / create _ from _ url
POST - account
Create a new ISO image on the current account .
The ISO image will be downloaded from a given URL .
Download status can be checked with the v1 / iso / list call .
Link : https : / / www . vultr . com / ... | params = update_params ( params , { 'url' : url , } )
return self . request ( '/v1/iso/create_from_url' , params , 'POST' ) |
async def logout ( self , request ) :
"""Simple handler for logout""" | if "Authorization" not in request . headers :
msg = "Auth header is not present, can not destroy token"
raise JsonValidaitonError ( msg )
response = json_response ( )
await forget ( request , response )
return response |
def OneHot ( * xs , simplify = True , conj = True ) :
"""Return an expression that means
" exactly one input function is true " .
If * simplify * is ` ` True ` ` , return a simplified expression .
If * conj * is ` ` True ` ` , return a CNF .
Otherwise , return a DNF .""" | xs = [ Expression . box ( x ) . node for x in xs ]
terms = list ( )
if conj :
for x0 , x1 in itertools . combinations ( xs , 2 ) :
terms . append ( exprnode . or_ ( exprnode . not_ ( x0 ) , exprnode . not_ ( x1 ) ) )
terms . append ( exprnode . or_ ( * xs ) )
y = exprnode . and_ ( * terms )
else :
... |
def _on_report ( _loop , adapter , conn_id , report ) :
"""Callback when a report is received .""" | conn_string = None
if conn_id is not None :
conn_string = adapter . _get_property ( conn_id , 'connection_string' )
if isinstance ( report , BroadcastReport ) :
adapter . notify_event_nowait ( conn_string , 'broadcast' , report )
elif conn_string is not None :
adapter . notify_event_nowait ( conn_string , '... |
def wait_for_and_dismiss_alert ( driver , timeout = settings . LARGE_TIMEOUT ) :
"""Wait for and dismiss an alert . Returns the text from the alert .
@ Params
driver - the webdriver object ( required )
timeout - the time to wait for the alert in seconds""" | alert = wait_for_and_switch_to_alert ( driver , timeout )
alert_text = alert . text
alert . dismiss ( )
return alert_text |
def gen_rup_contexts ( self , src , sites ) :
""": param src : a hazardlib source
: param sites : the sites affected by it
: yields : ( rup , sctx , dctx )""" | sitecol = sites . complete
N = len ( sitecol )
fewsites = N <= FEWSITES
rupdata = [ ]
# rupture data
for rup , sites in self . _gen_rup_sites ( src , sites ) :
try :
with self . ctx_mon :
sctx , dctx = self . make_contexts ( sites , rup )
except FarAwayRupture :
continue
yield ru... |
def _execActions ( self , type , msg ) :
"""Execute Registered Actions""" | for action in self . ACTIONS :
action ( type , msg ) |
def mentions_links ( uri , s ) :
"""Turns mentions - like strings into HTML links ,
@ uri : / uri / root for the hashtag - like
@ s : the # str string you ' re looking for | @ | mentions in
- > # str HTML link | < a href = " / uri / mention " > mention < / a > |""" | for username , after in mentions_re . findall ( s ) :
_uri = '/' + ( uri or "" ) . lstrip ( "/" ) + quote ( username )
link = '<a href="{}">@{}</a>{}' . format ( _uri . lower ( ) , username , after )
s = s . replace ( '@' + username , link )
return s |
def _output ( self , file_like_object , path = None ) :
"""Display or save file like object .""" | if not path :
self . _output_to_display ( file_like_object )
else :
self . _output_to_file ( file_like_object , path ) |
def rc_channels_raw_encode ( self , time_boot_ms , port , chan1_raw , chan2_raw , chan3_raw , chan4_raw , chan5_raw , chan6_raw , chan7_raw , chan8_raw , rssi ) :
'''The RAW values of the RC channels received . The standard PPM
modulation is as follows : 1000 microseconds : 0 % , 2000
microseconds : 100 % . Ind... | return MAVLink_rc_channels_raw_message ( time_boot_ms , port , chan1_raw , chan2_raw , chan3_raw , chan4_raw , chan5_raw , chan6_raw , chan7_raw , chan8_raw , rssi ) |
def SWdensityFromCTD ( SA , t , p , potential = False ) :
'''Calculate seawater density at CTD depth
Args
SA : ndarray
Absolute salinity , g / kg
t : ndarray
In - situ temperature ( ITS - 90 ) , degrees C
p : ndarray
Sea pressure ( absolute pressure minus 10.1325 dbar ) , dbar
Returns
rho : ndarra... | import numpy
import gsw
CT = gsw . CT_from_t ( SA , t , p )
# Calculate potential density ( 0 bar ) instead of in - situ
if potential :
p = numpy . zeros ( len ( SA ) )
return gsw . rho ( SA , CT , p ) |
def close ( self ) :
"""Close a port on dummy _ serial .""" | if VERBOSE :
_print_out ( '\nDummy_serial: Closing port\n' )
if not self . _isOpen :
raise IOError ( 'Dummy_serial: The port is already closed' )
self . _isOpen = False
self . port = None |
def layer ( self , layer_name ) :
""": meth : ` . WMessengerOnionProto . layer ` method implementation .""" | if layer_name in self . __layers . keys ( ) :
return self . __layers [ layer_name ]
elif layer_name in self . __class__ . __builtin_layers__ :
return self . __class__ . __builtin_layers__ [ layer_name ]
raise RuntimeError ( 'Invalid layer name' ) |
def create_context ( ctx ) :
"""Loads and constructs the specified context with the specified arguments .
If a ' . ' isn ' t in the class name , the ' insights . core . context ' package is
assumed .""" | ctx_cls_name = ctx . get ( "class" , "insights.core.context.HostContext" )
if "." not in ctx_cls_name :
ctx_cls_name = "insights.core.context." + ctx_cls_name
ctx_cls = dr . get_component ( ctx_cls_name )
ctx_args = ctx . get ( "args" , { } )
return ctx_cls ( ** ctx_args ) |
def iteration ( self , node_status = True ) :
"""Execute a single model iteration
: return : Iteration _ id , Incremental node status ( dictionary node - > status )""" | # One iteration changes the opinion of several voters using the following procedure :
# - select randomly one voter ( speaker 1)
# - select randomly one of its neighbours ( speaker 2)
# - if the two voters agree , their neighbours take their opinion
self . clean_initial_status ( self . available_statuses . values ( ) )... |
def _hash ( expr , func = None ) :
"""Calculate the hash value .
: param expr :
: param func : hash function
: return :""" | if func is None :
func = lambda x : hash ( x )
return _map ( expr , func = func , rtype = types . int64 ) |
def show_page ( self , success ) :
"""Display main course list page""" | username = self . user_manager . session_username ( )
user_info = self . database . users . find_one ( { "username" : username } )
all_courses = self . course_factory . get_all_courses ( )
# Display
open_courses = { courseid : course for courseid , course in all_courses . items ( ) if self . user_manager . course_is_op... |
def get_pings_properties ( pings , paths , only_median = False , with_processes = False , histograms_url = None , additional_histograms = None ) :
"""Returns a RDD of a subset of properties of pings . Child histograms are
automatically merged with the parent histogram .
If one of the paths points to a keyedHist... | if isinstance ( pings . first ( ) , binary_type ) :
pings = pings . map ( lambda p : json . loads ( p . decode ( 'utf-8' ) ) )
if isinstance ( paths , str ) :
paths = [ paths ]
# Use ' / ' as dots can appear in keyed histograms
if isinstance ( paths , dict ) :
paths = [ ( prop_name , path . split ( "/" ) ) ... |
def scan_results ( self , obj ) :
"""Get the AP list after scanning .""" | avail_network_list = pointer ( WLAN_AVAILABLE_NETWORK_LIST ( ) )
self . _wlan_get_available_network_list ( self . _handle , byref ( obj [ 'guid' ] ) , byref ( avail_network_list ) )
networks = cast ( avail_network_list . contents . Network , POINTER ( WLAN_AVAILABLE_NETWORK ) )
self . _logger . debug ( "Scan found %d n... |
def get_occupation_updates ( self , offset = 0 , count = 1000 ) :
"""Returns < count > occupation updates from < offset > .
An occupation update is a quadrupel
( pc , source , timestamp , occupation )""" | ret = [ ]
c = self . conn . cursor ( )
for pc_id , source_id , datetime , occupation in c . execute ( """ SELECT pc, source, datetime, occupation
FROM occupationUpdates LIMIT ?, ? """ , ( offset , count ) ) :
ret . append ( ( self . id2pc_lut [ pc_id ] , self . id2source_lut [ source_id ... |
def add_regex_start_end ( pattern_function ) :
"""Decorator for adding regex pattern start and end characters .""" | @ wraps ( pattern_function )
def func_wrapper ( * args , ** kwargs ) :
return r'^{}$' . format ( pattern_function ( * args , ** kwargs ) )
return func_wrapper |
def ebalance ( sdat , tstart = None , tend = None ) :
"""Energy balance .
Compute Nu _ t - Nu _ b + V * dT / dt as a function of time using an explicit
Euler scheme . This should be zero if energy is conserved .
Args :
sdat ( : class : ` ~ stagpy . stagyydata . StagyyData ` ) : a StagyyData instance .
tst... | tseries = sdat . tseries_between ( tstart , tend )
rbot , rtop = misc . get_rbounds ( sdat . steps . last )
if rbot != 0 : # spherical
coefsurf = ( rtop / rbot ) ** 2
volume = rbot * ( ( rtop / rbot ) ** 3 - 1 ) / 3
else :
coefsurf = 1.
volume = 1.
dtdt , time = dt_dt ( sdat , tstart , tend )
ftop = tse... |
def _safe_write_to_file ( self , file , message ) :
"""Writes a string to a file safely ( with file locks ) .""" | target = file
lock_name = make_lock_name ( target , self . outfolder )
lock_file = self . _make_lock_path ( lock_name )
while True :
if os . path . isfile ( lock_file ) :
self . _wait_for_lock ( lock_file )
else :
try :
self . locks . append ( lock_file )
self . _create_f... |
def run ( * args , ** kwargs ) : # type : ( . . . ) - > None
"""Run cwltool .""" | signal . signal ( signal . SIGTERM , _signal_handler )
try :
sys . exit ( main ( * args , ** kwargs ) )
finally :
_terminate_processes ( ) |
def link_down ( self , ofp_port ) :
"""DESIGNATED _ PORT / NON _ DESIGNATED _ PORT : change status to DISABLE .
ROOT _ PORT : change status to DISABLE and recalculate STP .""" | port = self . ports [ ofp_port . port_no ]
init_stp_flg = bool ( port . role is ROOT_PORT )
port . down ( PORT_STATE_DISABLE , msg_init = True )
self . ports_state [ ofp_port . port_no ] = ofp_port . state
if init_stp_flg :
self . recalculate_spanning_tree ( ) |
def BatchConvert ( self , metadata_value_pairs , token = None ) :
"""Converts a batch of GrrMessages into a set of RDFValues at once .
Args :
metadata _ value _ pairs : a list or a generator of tuples ( metadata , value ) ,
where metadata is ExportedMetadata to be used for conversion and value
is a GrrMessa... | # Group messages by source ( i . e . by client urn ) .
msg_dict = { }
for metadata , msg in metadata_value_pairs :
msg_dict . setdefault ( msg . source , [ ] ) . append ( ( metadata , msg ) )
metadata_objects = [ ]
metadata_to_fetch = [ ]
# Open the clients we don ' t have metadata for and fetch metadata .
for clie... |
def get_grade_systems_by_gradebook ( self , gradebook_id ) :
"""Gets the list of grade systems associated with a ` ` Gradebook ` ` .
arg : gradebook _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Gradebook ` `
return : ( osid . grading . GradeSystemList ) - list of related grade
systems
raise : NotFound - ... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ resources _ by _ bin
mgr = self . _get_provider_manager ( 'GRADING' , local = True )
lookup_session = mgr . get_grade_system_lookup_session_for_gradebook ( gradebook_id , proxy = self . _proxy )
lookup_session . use_isolated_gradebook_view (... |
def contents ( self ) :
"""Contents returns a list of the files in the data directory .""" | data = find_dataset_path ( self . name , data_home = self . data_home , ext = None )
return os . listdir ( data ) |
def datetime ( self , start : int = 2000 , end : int = 2035 , timezone : Optional [ str ] = None ) -> DateTime :
"""Generate random datetime .
: param start : Minimum value of year .
: param end : Maximum value of year .
: param timezone : Set custom timezone ( pytz required ) .
: return : Datetime""" | datetime_obj = datetime . combine ( date = self . date ( start , end ) , time = self . time ( ) , )
if timezone :
if not pytz :
raise ImportError ( 'Timezones are supported only with pytz' )
tz = pytz . timezone ( timezone )
datetime_obj = tz . localize ( datetime_obj )
return datetime_obj |
def get_stop_times ( feed : "Feed" , date : Optional [ str ] = None ) -> DataFrame :
"""Return a subset of ` ` feed . stop _ times ` ` .
Parameters
feed : Feed
date : string
YYYYMMDD date string restricting the output to trips active
on the date
Returns
DataFrame
Subset of ` ` feed . stop _ times ` ... | f = feed . stop_times . copy ( )
if date is None :
return f
g = feed . get_trips ( date )
return f [ f [ "trip_id" ] . isin ( g [ "trip_id" ] ) ] |
def write_src ( hdf5_out , gctoo_object , out_file_name ) :
"""Writes src as attribute of gctx out file .
Input :
- hdf5 _ out ( h5py ) : hdf5 file to write to
- gctoo _ object ( GCToo ) : GCToo instance to be written to . gctx
- out _ file _ name ( str ) : name of hdf5 out file .""" | if gctoo_object . src == None :
hdf5_out . attrs [ src_attr ] = out_file_name
else :
hdf5_out . attrs [ src_attr ] = gctoo_object . src |
def _assemble_regulate_activity ( self , stmt ) :
"""Example : p ( HGNC : MAP2K1 ) = > act ( p ( HGNC : MAPK1 ) )""" | act_obj = deepcopy ( stmt . obj )
act_obj . activity = stmt . _get_activity_condition ( )
# We set is _ active to True here since the polarity is encoded
# in the edge ( decreases / increases )
act_obj . activity . is_active = True
activates = isinstance ( stmt , Activation )
relation = get_causal_edge ( stmt , activat... |
def __ssh_gateway_config_dict ( gateway ) :
'''Return a dictionary with gateway options . The result is used
to provide arguments to _ _ ssh _ gateway _ arguments method .''' | extended_kwargs = { }
if gateway :
extended_kwargs [ 'ssh_gateway' ] = gateway [ 'ssh_gateway' ]
extended_kwargs [ 'ssh_gateway_key' ] = gateway [ 'ssh_gateway_key' ]
extended_kwargs [ 'ssh_gateway_user' ] = gateway [ 'ssh_gateway_user' ]
extended_kwargs [ 'ssh_gateway_command' ] = gateway [ 'ssh_gatewa... |
def parse_route ( cls , template ) :
"""Parse a route definition , and return the compiled regex that matches it .""" | regex = ''
last_pos = 0
for match in cls . ROUTES_RE . finditer ( template ) :
regex += re . escape ( template [ last_pos : match . start ( ) ] )
var_name = match . group ( 1 )
expr = match . group ( 2 ) or '[^/]+'
expr = '(?P<%s>%s)' % ( var_name , expr )
regex += expr
last_pos = match . end ( ... |
def _parse_description ( details ) :
"""Parse description of the book .
Args :
details ( obj ) : HTMLElement containing slice of the page with details .
Returns :
str / None : Details as string with currency or None if not found .""" | description = details . find ( "div" , { "class" : "detailPopis" } )
# description not found
if not description :
return None
# remove links to ebook version
ekniha = description [ 0 ] . find ( "div" , { "class" : "ekniha" } )
if ekniha :
ekniha [ 0 ] . replaceWith ( dhtmlparser . HTMLElement ( "" ) )
# remove ... |
def fetch_events ( self ) -> List [ dict ] :
"""Fetch new RTM events from the API .""" | try :
return self . inner . rtm_read ( )
# TODO : The TimeoutError could be more elegantly resolved by making
# a PR to the websocket - client library and letting them coerce that
# exception to a WebSocketTimeoutException that could be caught by
# the slackclient library and then we could just use auto _ reconnect... |
def trainRegressor ( cls , data , categoricalFeaturesInfo , impurity = "variance" , maxDepth = 5 , maxBins = 32 , minInstancesPerNode = 1 , minInfoGain = 0.0 ) :
"""Train a decision tree model for regression .
: param data :
Training data : RDD of LabeledPoint . Labels are real numbers .
: param categoricalFe... | return cls . _train ( data , "regression" , 0 , categoricalFeaturesInfo , impurity , maxDepth , maxBins , minInstancesPerNode , minInfoGain ) |
def check_balances ( self , account = None ) :
'''Fetches an account balance and makes
necessary conversions''' | a = self . account ( account )
if a is not False and a is not None :
self . sbdbal = Amount ( a [ 'sbd_balance' ] ) . amount
self . steembal = Amount ( a [ 'balance' ] ) . amount
self . votepower = a [ 'voting_power' ]
self . lastvotetime = a [ 'last_vote_time' ]
vs = Amount ( a [ 'vesting_shares' ]... |
def _sorter ( n1 , n2 ) :
'''_ sorter ( n1 , n2 ) - > int
Sorting predicate for non - NS attributes .''' | i = cmp ( n1 . namespaceURI , n2 . namespaceURI )
if i :
return i
return cmp ( n1 . localName , n2 . localName ) |
def network_lpf ( network , snapshots = None , skip_pre = False ) :
"""Linear power flow for generic network .
Parameters
snapshots : list - like | single snapshot
A subset or an elements of network . snapshots on which to run
the power flow , defaults to network . snapshots
skip _ pre : bool , default Fa... | _network_prepare_and_run_pf ( network , snapshots , skip_pre , linear = True ) |
def validate_seal ( self , header : BlockHeader ) -> None :
"""Validate the seal on the given header .""" | VM_class = self . get_vm_class_for_block_number ( BlockNumber ( header . block_number ) )
VM_class . validate_seal ( header ) |
def get_imported_module_from_file ( file_path ) :
"""import module from python file path and return imported module""" | if p_compat . is_py3 :
imported_module = importlib . machinery . SourceFileLoader ( 'module_name' , file_path ) . load_module ( )
elif p_compat . is_py2 :
imported_module = imp . load_source ( 'module_name' , file_path )
else :
raise RuntimeError ( "Neither Python 3 nor Python 2." )
return imported_module |
def age ( self , ** kwargs ) :
"""Age this particle .
parameters ( optional , only one allowed ) :
days ( default )
hours
minutes
seconds""" | if kwargs . get ( 'days' , None ) is not None :
self . _age += kwargs . get ( 'days' )
return
if kwargs . get ( 'hours' , None ) is not None :
self . _age += kwargs . get ( 'hours' ) / 24.
return
if kwargs . get ( 'minutes' , None ) is not None :
self . _age += kwargs . get ( 'minutes' ) / 24. / 60.... |
def disconnect ( self , receiver ) :
"""Remove receiver .""" | try :
self . receivers . remove ( receiver )
except ValueError :
raise ValueError ( 'Unknown receiver: %s' % receiver ) |
def ExamineEvent ( self , mediator , event ) :
"""Analyzes an event .
Args :
mediator ( AnalysisMediator ) : mediates interactions between
analysis plugins and other components , such as storage and dfvfs .
event ( EventObject ) : event to examine .""" | # This event requires an URL attribute .
url = getattr ( event , 'url' , None )
if not url :
return
# TODO : refactor this the source should be used in formatting only .
# Check if we are dealing with a web history event .
source , _ = formatters_manager . FormattersManager . GetSourceStrings ( event )
if source !=... |
def parse_data_to_internal ( self , include_custom = False ) :
"""Invoke parse _ data _ to _ internal ( ) for every element
in self . data""" | for element in self . data :
self . data [ element ] . parse_data_to_internal ( )
if include_custom :
for element in self . custom_data :
self . custom_data [ element ] . parse_data_to_internal ( ) |
def _setup ( self ) :
"""Load the context module pointed to by the environment variable . This
is used the first time we need the context at all , if the user has not
previously configured the context manually .""" | context_module = os . environ . get ( ENVIRONMENT_CONTEXT_VARIABLE , 'context' )
if not context_module :
raise ImproperlyConfigured ( 'Requested context points to an empty variable. ' 'You must either define the environment variable {0} ' 'or call context.configure() before accessing the context.' . format ( ENVIRO... |
def __get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ Any ] , children_on_fs : Dict [ str , PersistedObject ] , logger : Logger ) -> Dict [ str , Any ] :
"""Simply inspects the required type to find the names and types of its constructor arguments .
Then relies... | # - - ( a ) collect pep - 484 information in the class constructor to be able to understand what is required
constructor_args_types_and_opt = get_constructor_attributes_types ( desired_type )
# - - ( b ) plan to parse each attribute required by the constructor
children_plan = dict ( )
# results will be put in this obje... |
def period_array ( data : Sequence [ Optional [ Period ] ] , freq : Optional [ Tick ] = None , copy : bool = False , ) -> PeriodArray :
"""Construct a new PeriodArray from a sequence of Period scalars .
Parameters
data : Sequence of Period objects
A sequence of Period objects . These are required to all have ... | if is_datetime64_dtype ( data ) :
return PeriodArray . _from_datetime64 ( data , freq )
if isinstance ( data , ( ABCPeriodIndex , ABCSeries , PeriodArray ) ) :
return PeriodArray ( data , freq )
# other iterable of some kind
if not isinstance ( data , ( np . ndarray , list , tuple ) ) :
data = list ( data )... |
def _concordance_summary_statistics ( event_times , predicted_event_times , event_observed ) : # pylint : disable = too - many - locals
"""Find the concordance index in n * log ( n ) time .
Assumes the data has been verified by lifelines . utils . concordance _ index first .""" | # Here ' s how this works .
# It would be pretty easy to do if we had no censored data and no ties . There , the basic idea
# would be to iterate over the cases in order of their true event time ( from least to greatest ) ,
# while keeping track of a pool of * predicted * event times for all cases previously seen ( = a... |
def queryset ( self , request , queryset ) :
"""Filter based on whether an update ( of any sort ) is available .""" | if self . value ( ) == '-1' :
return queryset . filter ( latest_version__isnull = True )
elif self . value ( ) == '0' :
return ( queryset . filter ( current_version__isnull = False , latest_version__isnull = False , latest_version = F ( 'current_version' ) ) )
elif self . value ( ) == '1' :
return ( queryse... |
def get_property ( self , name ) :
"""Return a named property for a resource , if available . Will raise an ` AttributeError ` if the property
does not exist
Args :
name ( str ) : Name of the property to return
Returns :
` ResourceProperty `""" | for prop in self . resource . properties :
if prop . name == name :
return prop
raise AttributeError ( name ) |
def remove_node ( self , node ) :
"""Removes node from circle and rebuild it .""" | try :
self . _nodes . remove ( node )
del self . _weights [ node ]
except ( KeyError , ValueError ) :
pass
self . _hashring = dict ( )
self . _sorted_keys = [ ]
self . _build_circle ( ) |
async def get_final_ranking ( self ) -> OrderedDict :
"""Get the ordered players ranking
Returns :
collections . OrderedDict [ rank , List [ Participant ] ] :
Raises :
APIException""" | if self . _state != TournamentState . complete . value :
return None
ranking = { }
for p in self . participants :
if p . final_rank in ranking :
ranking [ p . final_rank ] . append ( p )
else :
ranking [ p . final_rank ] = [ p ]
return OrderedDict ( sorted ( ranking . items ( ) , key = lambd... |
def decorate ( func , caller , extras = ( ) ) :
"""decorate ( func , caller ) decorates a function using a caller .""" | evaldict = dict ( _call_ = caller , _func_ = func )
es = ''
for i , extra in enumerate ( extras ) :
ex = '_e%d_' % i
evaldict [ ex ] = extra
es += ex + ', '
fun = FunctionMaker . create ( func , "return _call_(_func_, %s%%(shortsignature)s)" % es , evaldict , __wrapped__ = func )
if hasattr ( func , '__qual... |
def set_pattern_step_setpoint ( self , patternnumber , stepnumber , setpointvalue ) :
"""Set the setpoint value for a step .
Args :
* patternnumber ( integer ) : 0-7
* stepnumber ( integer ) : 0-7
* setpointvalue ( float ) : Setpoint value""" | _checkPatternNumber ( patternnumber )
_checkStepNumber ( stepnumber )
_checkSetpointValue ( setpointvalue , self . setpoint_max )
address = _calculateRegisterAddress ( 'setpoint' , patternnumber , stepnumber )
self . write_register ( address , setpointvalue , 1 ) |
def on_shutdown ( self , broker ) :
"""Called by : meth : ` Broker . shutdown ` to allow the stream time to
gracefully shutdown . The base implementation simply called
: meth : ` on _ disconnect ` .""" | _v and LOG . debug ( '%r.on_shutdown()' , self )
fire ( self , 'shutdown' )
self . on_disconnect ( broker ) |
def samples ( self , gp , Y_metadata ) :
"""Returns a set of samples of observations based on a given value of the latent variable .
: param gp : latent variable""" | N1 , N2 = gp . shape
Ysim = np . zeros ( ( N1 , N2 ) )
ind = Y_metadata [ 'output_index' ] . flatten ( )
for j in np . unique ( ind ) :
flt = ind == j
gp_filtered = gp [ flt , : ]
n1 = gp_filtered . shape [ 0 ]
lik = self . likelihoods_list [ j ]
_ysim = np . array ( [ np . random . normal ( lik . g... |
def focusNextPrevChild ( self , next_child ) :
"""The default ' focusNextPrevChild ' implementation .""" | fd = focus_registry . focused_declaration ( )
if next_child :
child = self . declaration . next_focus_child ( fd )
reason = Qt . TabFocusReason
else :
child = self . declaration . previous_focus_child ( fd )
reason = Qt . BacktabFocusReason
if child is not None and child . proxy_is_active :
return c... |
def _wake_up_first ( self ) :
"""Wake up the first waiter who isn ' t cancelled .""" | for fut in self . _waiters :
if not fut . done ( ) :
fut . set_result ( True )
break |
def create ( self , file_or_path , ** kwargs ) :
"""Creates an upload for the given file or path .""" | opened = False
if isinstance ( file_or_path , str_type ( ) ) :
file_or_path = open ( file_or_path , 'rb' )
opened = True
elif not getattr ( file_or_path , 'read' , False ) :
raise Exception ( "A file or path to a file is required for this operation." )
try :
return self . client . _post ( self . _url ( ... |
def initialize_partition_table ( self , format_p , whole_disk_in_one_entry ) :
"""Writes an empty partition table to the disk .
in format _ p of type : class : ` PartitionTableType `
The partition table format .
in whole _ disk _ in _ one _ entry of type bool
When @ c true a partition table entry for the wh... | if not isinstance ( format_p , PartitionTableType ) :
raise TypeError ( "format_p can only be an instance of type PartitionTableType" )
if not isinstance ( whole_disk_in_one_entry , bool ) :
raise TypeError ( "whole_disk_in_one_entry can only be an instance of type bool" )
self . _call ( "initializePartitionTab... |
def main ( args ) :
"""Nibble ' s entry point .
: param args : Command - line arguments , with the program in position 0.""" | args = _parse_args ( args )
# sort out logging output and level
level = util . log_level_from_vebosity ( args . verbosity )
root = logging . getLogger ( )
root . setLevel ( level )
handler = logging . StreamHandler ( sys . stdout )
handler . setLevel ( level )
handler . setFormatter ( logging . Formatter ( '%(levelname... |
def close ( self ) :
"""Mark the scope as closed , i . e . all symbols have been declared ,
and no further declarations should be done .""" | if self . _closed :
raise ValueError ( 'scope is already marked as closed' )
# By letting parent know which symbols this scope has leaked , it
# will let them reserve all lowest identifiers first .
if self . parent :
for symbol , c in self . leaked_referenced_symbols . items ( ) :
self . parent . refere... |
def get_iterargs ( self , item ) :
"""Returns a tuple of all iterags for item , sorted by name .""" | # iterargs should always be mandatory , unless there ' s a good reason
# not to , which I can ' t think of right now .
args = self . _get_aggregate_args ( item , 'mandatoryArgs' )
return tuple ( sorted ( [ arg for arg in args if arg in self . iterargs ] ) ) |
def normalize ( email_address , resolve = True ) :
"""Return the normalized email address , removing
: param str email _ address : The normalized email address
: param bool resolve : Resolve the domain
: rtype : str""" | address = utils . parseaddr ( email_address )
local_part , domain_part = address [ 1 ] . lower ( ) . split ( '@' )
# Plus addressing is supported by Microsoft domains and FastMail
if domain_part in MICROSOFT_DOMAINS :
if '+' in local_part :
local_part = local_part . split ( '+' ) [ 0 ]
# GMail supports plus... |
def start_instance ( self , # these are common to any
# CloudProvider . start _ instance ( ) call
key_name , public_key_path , private_key_path , security_group , flavor , image_id , image_userdata , username = None , # these params are specific to the
# GoogleCloudProvider
node_name = None , boot_disk_type = 'pd-stand... | # construct URLs
project_url = '%s%s' % ( GCE_URL , self . _project_id )
machine_type_url = '%s/zones/%s/machineTypes/%s' % ( project_url , self . _zone , flavor )
boot_disk_type_url = '%s/zones/%s/diskTypes/%s' % ( project_url , self . _zone , boot_disk_type )
# FIXME : ` conf . py ` should ensure that ` boot _ disk _... |
def update ( self , method = 'isel' , dims = { } , fmt = { } , replot = False , auto_update = False , draw = None , force = False , todefault = False , enable_post = None , ** kwargs ) :
"""Update the coordinates and the plot
This method updates all arrays in this list with the given coordinate
values and forma... | dims = dict ( dims )
fmt = dict ( fmt )
vars_and_coords = set ( chain ( self . dims , self . coords , [ 'name' , 'x' , 'y' , 'z' , 't' ] ) )
furtherdims , furtherfmt = utils . sort_kwargs ( kwargs , vars_and_coords )
dims . update ( furtherdims )
fmt . update ( furtherfmt )
self . _register_update ( method = method , r... |
def decode_cert ( cert ) :
"""Convert an X509 certificate into a Python dictionary
This function converts the given X509 certificate into a Python dictionary
in the manner established by the Python standard library ' s ssl module .""" | ret_dict = { }
subject_xname = X509_get_subject_name ( cert . value )
ret_dict [ "subject" ] = _create_tuple_for_X509_NAME ( subject_xname )
notAfter = X509_get_notAfter ( cert . value )
ret_dict [ "notAfter" ] = ASN1_TIME_print ( notAfter )
peer_alt_names = _get_peer_alt_names ( cert )
if peer_alt_names is not None :
... |
def join ( self , timeout = None ) :
"""Joins with a default timeout exposed on the class .""" | return super ( _StoppableDaemonThread , self ) . join ( timeout or self . JOIN_TIMEOUT ) |
def deserialize_unicode ( data ) :
"""Preserve unicode objects in Python 2 , otherwise return data
as a string .
: param str data : response string to be deserialized .
: rtype : str or unicode""" | # We might be here because we have an enum modeled as string ,
# and we try to deserialize a partial dict with enum inside
if isinstance ( data , Enum ) :
return data
# Consider this is real string
try :
if isinstance ( data , unicode ) :
return data
except NameError :
return str ( data )
else :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.