signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def clone ( self ) : """Return a new Scope object that has the curr _ scope pinned at the current one : returns : A new scope object"""
self . _dlog ( "cloning the stack" ) # TODO is this really necessary to create a brand new one ? # I think it is . . . need to think about it more . # or . . . are we going to need ref counters and a global # scope object that allows a view into ( or a snapshot of ) # a specific scope stack ? res = Scope ( self . _log ...
def get_based_on_grades_metadata ( self ) : """Gets the metadata for a grade - based designation . return : ( osid . Metadata ) - metadata for the grade - based designation * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template metadata = dict ( self . _mdata [ 'based_on_grades' ] ) metadata . update ( { 'existing_boolean_values' : self . _my_map [ 'basedOnGrades' ] } ) return Metadata ( ** metadata )
def handle_http_error ( self , code , error ) : """Helper that renders ` error { code } . html ` . Convenient way to use it : : from functools import partial handler = partial ( app . handle _ http _ error , code ) app . errorhandler ( code ) ( handler )"""
# 5xx code : error on server side if ( code // 100 ) == 5 : # ensure rollback if needed , else error page may # have an error , too , resulting in raw 500 page : - ( db . session . rollback ( ) template = f"error{code:d}.html" return render_template ( template , error = error ) , code
def set_role_id ( self , role_name , role_id , mount_point = 'approle' ) : """POST / auth / < mount _ point > / role / < role name > / role - id : param role _ name : : type role _ name : : param role _ id : : type role _ id : : param mount _ point : : type mount _ point : : return : : rtype :"""
url = '/v1/auth/{0}/role/{1}/role-id' . format ( mount_point , role_name ) params = { 'role_id' : role_id } return self . _adapter . post ( url , json = params )
def asarray ( self , out = None , squeeze = True , lock = None , reopen = True , maxsize = None , maxworkers = None , validate = True ) : """Read image data from file and return as numpy array . Raise ValueError if format is unsupported . Parameters out : numpy . ndarray , str , or file - like object Buffer...
# properties from TiffPage or TiffFrame fh = self . parent . filehandle byteorder = self . parent . tiff . byteorder offsets , bytecounts = self . _offsetscounts self_ = self self = self . keyframe # self or keyframe if not self . _shape or product ( self . _shape ) == 0 : return None tags = self . tags if validate...
def cookie_encode ( data , key ) : '''Encode and sign a pickle - able object . Return a ( byte ) string'''
msg = base64 . b64encode ( pickle . dumps ( data , - 1 ) ) sig = base64 . b64encode ( hmac . new ( tob ( key ) , msg ) . digest ( ) ) return tob ( '!' ) + sig + tob ( '?' ) + msg
def request ( self , method , params = None ) : """Send a JSON RPC request to the client . Args : method ( str ) : The method name of the message to send params ( any ) : The payload of the message Returns : Future that will resolve once a response has been received"""
msg_id = self . _id_generator ( ) log . debug ( 'Sending request with id %s: %s %s' , msg_id , method , params ) message = { 'jsonrpc' : JSONRPC_VERSION , 'id' : msg_id , 'method' : method , } if params is not None : message [ 'params' ] = params request_future = futures . Future ( ) request_future . add_done_callb...
def chats_search ( self , q = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / chat / chats # search - chats"
api_path = "/api/v2/chats/search" api_query = { } if "query" in kwargs . keys ( ) : api_query . update ( kwargs [ "query" ] ) del kwargs [ "query" ] if q : api_query . update ( { "q" : q , } ) return self . call ( api_path , query = api_query , ** kwargs )
def dump ( df , fp ) : """dump DataFrame to file : param DataFrame df : : param file fp :"""
arff = __dump ( df ) liacarff . dump ( arff , fp )
def exceptionCaught ( self , exc = None , ** kwargs ) : 'Maintain list of most recent errors and return most recent one .'
if isinstance ( exc , ExpectedException ) : # already reported , don ' t log return self . lastErrors . append ( stacktrace ( ) ) if kwargs . get ( 'status' , True ) : status ( self . lastErrors [ - 1 ] [ - 1 ] , priority = 2 ) # last line of latest error if options . debug : raise
def maps_get_default_rules_output_rules_monitor ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) maps_get_default_rules = ET . Element ( "maps_get_default_rules" ) config = maps_get_default_rules output = ET . SubElement ( maps_get_default_rules , "output" ) rules = ET . SubElement ( output , "rules" ) monitor = ET . SubElement ( rules , "monitor" ) monitor . text = kwargs . pop ...
def _aspirate_plunger_position ( self , ul ) : """Calculate axis position for a given liquid volume . Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette . Calibration of the pipette motor ' s ul - to - mm conversion is required"""
millimeters = ul / self . _ul_per_mm ( ul , 'aspirate' ) destination_mm = self . _get_plunger_position ( 'bottom' ) + millimeters return round ( destination_mm , 6 )
def _is_valid_token ( self , auth_token ) : '''Check if this is a valid salt - api token or valid Salt token salt - api tokens are regular session tokens that tie back to a real Salt token . Salt tokens are tokens generated by Salt ' s eauth system . : return bool : True if valid , False if not valid .'''
# Make sure that auth token is hex . If it ' s None , or something other # than hex , this will raise a ValueError . try : int ( auth_token , 16 ) except ( TypeError , ValueError ) : return False # First check if the given token is in our session table ; if so it ' s a # salt - api token and we need to get the ...
def difference ( * sets , ** kwargs ) : """subtracts all tail sets from the head set Parameters sets : tuple of indexable objects first set is the head , from which we subtract other items form the tail , which are subtracted from head Returns items which are in the head but not in any of the tail sets ...
head , tail = sets [ 0 ] , sets [ 1 : ] idx = as_index ( head , ** kwargs ) lhs = idx . unique rhs = [ intersection ( idx , s , ** kwargs ) for s in tail ] return exclusive ( lhs , * rhs , axis = 0 , assume_unique = True )
def sunset_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : """Calculate sunset time in the UTC timezone . : param date : Date to calculate for . : type date : : class : ` datetime . date ` : param latitude : Latitude - Northern latitudes should be positive : type latitude : float : p...
try : return self . _calc_time ( 90 + 0.833 , SUN_SETTING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches the horizon on this day, " "at this location." ) ) else : raise
async def _put_chunk ( cls , session : aiohttp . ClientSession , upload_uri : str , buf : bytes ) : """Upload one chunk to ` upload _ uri ` ."""
# Build the correct headers . headers = { 'Content-Type' : 'application/octet-stream' , 'Content-Length' : '%s' % len ( buf ) , } credentials = cls . _handler . session . credentials if credentials is not None : utils . sign ( upload_uri , headers , credentials ) # Perform upload of chunk . async with await session...
def exception ( function ) : """A decorator that wraps the passed in function and prints exception should one occur"""
@ functools . wraps ( function ) def wrapper ( * args , ** kwargs ) : try : return function ( * args , ** kwargs ) except Exception as e : # print err = "There was an exception in %s():" % ( function . __name__ ) print ( ( "%s \n %s \n%s" % ( err , e , sys . exc_info ( ) ) ) ) re...
def add_post_configure_callback ( self , callback , run_once = False ) : """Add a new callback to be run after every call to : meth : ` configure ` . Functions run at the end of : meth : ` configure ` are given the application ' s resulting configuration and the arguments passed to : meth : ` configure ` , in...
if run_once : self . _post_configure_callbacks [ 'single' ] . append ( callback ) else : self . _post_configure_callbacks [ 'multiple' ] . append ( callback ) return self
def login ( self ) : """Logs the user in . The log in information is saved in the client - userid - username - cookies : return : The raw response from the request"""
if self . options [ 'token' ] : self . client . token = self . options [ 'token' ] result = self . users . get_user ( 'me' ) else : response = self . users . login_user ( { 'login_id' : self . options [ 'login_id' ] , 'password' : self . options [ 'password' ] , 'token' : self . options [ 'mfa_token' ] } ) ...
def output_callback ( self , line , kill_switch ) : """Set status of openvpn according to what we process"""
self . notifications += line + "\n" if "Initialization Sequence Completed" in line : self . started = True if "ERROR:" in line or "Cannot resolve host address:" in line : self . error = True if "process exiting" in line : self . stopped = True
def _label_to_tag ( self , name , labels , scraper_config , tag_name = None ) : """Search for ` name ` in labels name and returns corresponding tag string . Tag name is label name if not specified . Returns None if name was not found ."""
value = labels . get ( name ) if value : return self . _format_tag ( tag_name or name , value , scraper_config ) else : return None
def dedupe ( items ) : """Remove duplicates from a sequence ( of hashable items ) while maintaining order . NOTE : This only works if items in the list are hashable types . Taken from the Python Cookbook , 3rd ed . Such a great book !"""
seen = set ( ) for item in items : if item not in seen : yield item seen . add ( item )
def read_hector_constraint ( constraint_file ) : """Reads a Hector contraint CSV file and returns it as a Pandas Series"""
df = pd . read_csv ( constraint_file , index_col = 0 , comment = ";" ) df = df [ df . applymap ( lambda x : isinstance ( x , ( int , float ) ) ) ] df . index = df . index . astype ( int ) return df . iloc [ : , 0 ]
def get_cancer_studies ( study_filter = None ) : """Return a list of cancer study identifiers , optionally filtered . There are typically multiple studies for a given type of cancer and a filter can be used to constrain the returned list . Parameters study _ filter : Optional [ str ] A string used to filt...
data = { 'cmd' : 'getCancerStudies' } df = send_request ( ** data ) res = _filter_data_frame ( df , [ 'cancer_study_id' ] , 'cancer_study_id' , study_filter ) study_ids = list ( res [ 'cancer_study_id' ] . values ( ) ) return study_ids
def rgb_to_xyz ( r , g = None , b = None ) : """Convert the color from sRGB to CIE XYZ . The methods assumes that the RGB coordinates are given in the sRGB colorspace ( D65 ) . . . note : : Compensation for the sRGB gamma correction is applied before converting . Parameters : The Red component value [ 0...
if type ( r ) in [ list , tuple ] : r , g , b = r r , g , b = [ ( ( v <= 0.03928 ) and [ v / 12.92 ] or [ ( ( v + 0.055 ) / 1.055 ) ** 2.4 ] ) [ 0 ] for v in ( r , g , b ) ] x = ( r * 0.4124 ) + ( g * 0.3576 ) + ( b * 0.1805 ) y = ( r * 0.2126 ) + ( g * 0.7152 ) + ( b * 0.0722 ) z = ( r * 0.0193 ) + ( g * 0.1192 ) ...
def designator ( self ) : """Returns the version and error correction level as string ` V - E ` where ` V ` represents the version number and ` E ` the error level ."""
version = str ( self . version ) return '-' . join ( ( version , self . error ) if self . error else ( version , ) )
def upcoming_releases ( self , product ) : """Get upcoming releases for this product . Specifically we search for releases with a GA date greater - than or equal to today ' s date . : param product : str , eg . " ceph " : returns : deferred that when fired returns a list of Munch ( dict - like ) objects r...
url = 'api/v6/releases/' url = url + '?product__shortname=' + product url = url + '&ga_date__gte=' + date . today ( ) . strftime ( '%Y-%m-%d' ) url = url + '&ordering=shortname_sort' releases = yield self . _get ( url ) result = munchify ( releases ) defer . returnValue ( result )
def create_textview ( self , wrap_mode = Gtk . WrapMode . WORD_CHAR , justify = Gtk . Justification . LEFT , visible = True , editable = True ) : """Function creates a text view with wrap _ mode and justification"""
text_view = Gtk . TextView ( ) text_view . set_wrap_mode ( wrap_mode ) text_view . set_editable ( editable ) if not editable : text_view . set_cursor_visible ( False ) else : text_view . set_cursor_visible ( visible ) text_view . set_justification ( justify ) return text_view
def get_q_version ( q_home ) : """Return version of q installed at q _ home"""
with open ( os . path . join ( q_home , 'q.k' ) ) as f : for line in f : if line . startswith ( 'k:' ) : return line [ 2 : 5 ] return '2.2'
def contribute_error_pages ( self ) : """Contributes generic static error massage pages to an existing section ."""
static_dir = self . settings . STATIC_ROOT if not static_dir : # Source static directory is not configured . Use temporary . import tempfile static_dir = os . path . join ( tempfile . gettempdir ( ) , self . project_name ) self . settings . STATIC_ROOT = static_dir self . section . routing . set_error_pages...
def element ( self ) : """Returns the instance of the element who owns the first line number for the operation in the cached source code ."""
# We assume here that the entire operation is associated with a single # code element . Since the sequence matcher groups operations by contiguous # lines of code to change , this is a safe assumption . if self . _element is None : line = self . icached [ 0 ] # If we are inserting a new line , the location at t...
def equiv ( self , other ) : """Return True if other is an equivalent weighting . Returns equivalent : bool ` ` True ` ` if ` ` other ` ` is a ` Weighting ` instance with the same ` Weighting . impl ` , which yields the same result as this weighting for any input , ` ` False ` ` otherwise . This is checke...
# Optimization for equality if self == other : return True elif ( not isinstance ( other , Weighting ) or self . exponent != other . exponent ) : return False elif isinstance ( other , MatrixWeighting ) : return other . equiv ( self ) elif isinstance ( other , ConstWeighting ) : return np . array_equiv ...
def delete_kwargs_s ( cls , s , args = None , kwargs = None ) : """Deletes the ` ` * args ` ` or ` ` * * kwargs ` ` part from the parameters section Either ` args ` or ` kwargs ` must not be None . Parameters s : str The string to delete the args and kwargs from args : None or str The string for the arg...
if not args and not kwargs : return s types = [ ] if args is not None : types . append ( '`?`?\*%s`?`?' % args ) if kwargs is not None : types . append ( '`?`?\*\*%s`?`?' % kwargs ) return cls . delete_types_s ( s , types )
def firmware_autoupgrade_params_pss ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) firmware = ET . SubElement ( config , "firmware" , xmlns = "urn:brocade.com:mgmt:brocade-firmware" ) autoupgrade_params = ET . SubElement ( firmware , "autoupgrade-params" ) pss = ET . SubElement ( autoupgrade_params , "pass" ) pss . text = kwargs . pop ( 'pss' ) callback = kwargs . p...
def __replace_repeat ( sentence ) : """Allows the use of repeating random - elements such as in the ' Ten green bottles ' type sentences . : param sentence :"""
# # # # # # USE SENTENCE _ ID 47 for testing ! repeat_dict = { } if sentence is not None : while sentence . find ( '#DEFINE_REPEAT' ) != - 1 : begin_index = sentence . find ( '#DEFINE_REPEAT' ) start_index = begin_index + 15 end_index = sentence . find ( ']' ) if sentence . find ( '#...
def _diff_group_position ( group ) : """Generate a unified diff position line for a diff group"""
old_start = group [ 0 ] [ 0 ] new_start = group [ 0 ] [ 1 ] old_length = new_length = 0 for old_line , new_line , line_or_conflict in group : if isinstance ( line_or_conflict , tuple ) : old , new = line_or_conflict old_length += len ( old ) new_length += len ( new ) else : old_l...
def nl_complete_msg ( sk , msg ) : """Finalize Netlink message . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / nl . c # L450 This function finalizes a Netlink message by completing the message with desirable flags and values depending on the socket configuration . - If not yet fill...
nlh = msg . nm_nlh if nlh . nlmsg_pid == NL_AUTO_PORT : nlh . nlmsg_pid = nl_socket_get_local_port ( sk ) if nlh . nlmsg_seq == NL_AUTO_SEQ : nlh . nlmsg_seq = sk . s_seq_next sk . s_seq_next += 1 if msg . nm_protocol == - 1 : msg . nm_protocol = sk . s_proto nlh . nlmsg_flags |= NLM_F_REQUEST if not sk...
def add_cpds ( self , * cpds ) : """Add CPD ( Conditional Probability Distribution ) to the Bayesian Model . Parameters cpds : list , set , tuple ( array - like ) List of CPDs which will be associated with the model EXAMPLE > > > from pgmpy . models import BayesianModel > > > from pgmpy . factors . disc...
for cpd in cpds : if not isinstance ( cpd , ( TabularCPD , ContinuousFactor ) ) : raise ValueError ( 'Only TabularCPD or ContinuousFactor can be added.' ) if set ( cpd . scope ( ) ) - set ( cpd . scope ( ) ) . intersection ( set ( self . nodes ( ) ) ) : raise ValueError ( 'CPD defined on variabl...
def shutdown ( self , force = False ) : """Shut down and power off the HMC represented by this Console object . While the HMC is powered off , any Python resource objects retrieved from this HMC may raise exceptions upon further use . In order to continue using Python resource objects retrieved from this HM...
body = { 'force' : force } self . manager . session . post ( self . uri + '/operations/shutdown' , body = body )
def write ( self , buffer = bytes ( ) , address = 0 , count = 0 ) : """Writes the content of the * buffer * to the : attr : ` cache ` beginning at the start * address * . : param bytes buffer : content to write . : param int address : start address . : param int count : number of bytes to write to the cache...
view = memoryview ( self . _cache ) view [ address : address + count ] = buffer
def main ( ) : """Provide the entry point in the the modutils command ."""
mod_choices = ( 'banned' , 'contributor' , 'moderator' ) mod_choices_dsp = ', ' . join ( [ '`{}`' . format ( x ) for x in mod_choices ] ) msg = { 'add' : ( 'Add users to one of the following categories: {}' . format ( mod_choices_dsp ) ) , 'clear' : 'Remove users who have no flair set.' , 'css' : 'Ignore the CSS field ...
def ciphertext_length ( header , plaintext_length ) : """Calculates the complete ciphertext message length , given a complete header . : param header : Complete message header object : type header : aws _ encryption _ sdk . structures . MessageHeader : param int plaintext _ length : Length of plaintext in byt...
ciphertext_length = header_length ( header ) ciphertext_length += body_length ( header , plaintext_length ) ciphertext_length += footer_length ( header ) return ciphertext_length
def _submit_bundle ( cmd_args , app ) : """Submit an existing bundle to the service"""
sac = streamsx . rest . StreamingAnalyticsConnection ( service_name = cmd_args . service_name ) sas = sac . get_streaming_analytics ( ) sr = sas . submit_job ( bundle = app . app , job_config = app . cfg [ ctx . ConfigParams . JOB_CONFIG ] ) if 'exception' in sr : rc = 1 elif 'status_code' in sr : try : ...
def put_tagging ( Bucket , region = None , key = None , keyid = None , profile = None , ** kwargs ) : '''Given a valid config , update the tags for a bucket . Returns { updated : true } if tags were updated and returns { updated : False } if tags were not updated . CLI Example : . . code - block : : bash ...
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) tagslist = [ ] for k , v in six . iteritems ( kwargs ) : if six . text_type ( k ) . startswith ( '__' ) : continue tagslist . append ( { 'Key' : six . text_type ( k ) , 'Value' : six . text...
def assemble ( self , roboset = None , color = None , format = None , bgset = None , sizex = 300 , sizey = 300 ) : """Build our Robot ! Returns the robot image itself ."""
# Allow users to manually specify a robot ' set ' that they like . # Ensure that this is one of the allowed choices , or allow all # If they don ' t set one , take the first entry from sets above . if roboset == 'any' : roboset = self . sets [ self . hasharray [ 1 ] % len ( self . sets ) ] elif roboset in self . se...
def on_clipboard_mode_change ( self , clipboard_mode ) : """Notification when the shared clipboard mode changes . in clipboard _ mode of type : class : ` ClipboardMode ` The new shared clipboard mode ."""
if not isinstance ( clipboard_mode , ClipboardMode ) : raise TypeError ( "clipboard_mode can only be an instance of type ClipboardMode" ) self . _call ( "onClipboardModeChange" , in_p = [ clipboard_mode ] )
def poll ( self , id ) : """Poll with a given id . Parameters id : int Poll id . Returns an : class : ` ApiQuery ` of : class : ` Poll ` Raises : class : ` NotFound ` If a poll with the requested id doesn ' t exist ."""
@ api_query ( 'poll' , pollid = str ( id ) ) async def result ( _ , root ) : elem = root . find ( 'POLL' ) if not elem : raise NotFound ( f'No poll found with id {id}' ) return Poll ( elem ) return result ( self )
def Nu_vertical_cylinder_Al_Arabi_Khamis ( Pr , Gr , L , D , turbulent = None ) : r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to [ 1 ] _ , also as presented in [ 2 ] _ and [ 3 ] _ . . . math : : Nu _ H = 2.9Ra _ H ^ { 0.25 } / Gr _ D ^ { 1/12 } , \ ; 9....
Gr_D = Gr / L ** 3 * D ** 3 Ra = Pr * Gr if turbulent or ( Ra > 2.6E9 and turbulent is None ) : return 0.47 * Ra ** ( 1 / 3. ) * Gr_D ** ( - 1 / 12. ) else : return 2.9 * Ra ** 0.25 * Gr_D ** ( - 1 / 12. )
def expire_hit ( self , hit_id ) : """Expire a HIT , which will change its status to " Reviewable " , allowing it to be deleted ."""
try : self . mturk . update_expiration_for_hit ( HITId = hit_id , ExpireAt = 0 ) except Exception as ex : raise MTurkServiceException ( "Failed to expire HIT {}: {}" . format ( hit_id , str ( ex ) ) ) return True
def setCurveModel ( self , model ) : """Sets the stimulus model for the calibration curve test : param model : Stimulus model that has a tone curve configured : type model : : class : ` StimulusModel < sparkle . stim . stimulus _ model . StimulusModel > `"""
self . stimModel = model self . ui . curveWidget . setModel ( model )
def parse_section_extras_require ( self , section_options ) : """Parses ` extras _ require ` configuration file section . : param dict section _ options :"""
parse_list = partial ( self . _parse_list , separator = ';' ) self [ 'extras_require' ] = self . _parse_section_to_dict ( section_options , parse_list )
def format_listeners ( elb_settings = None , env = 'dev' , region = 'us-east-1' ) : """Format ELB Listeners into standard list . Args : elb _ settings ( dict ) : ELB settings including ELB Listeners to add , e . g . : : # old " certificate " : null , " i _ port " : 8080, " lb _ port " : 80, " subnet...
LOG . debug ( 'ELB settings:\n%s' , elb_settings ) credential = get_env_credential ( env = env ) account = credential [ 'accountId' ] listeners = [ ] if 'ports' in elb_settings : for listener in elb_settings [ 'ports' ] : cert_name = format_cert_name ( env = env , region = region , account = account , certi...
def p_iteration_statement_4 ( self , p ) : """iteration _ statement : FOR LPAREN left _ hand _ side _ expr IN expr RPAREN statement"""
p [ 0 ] = self . asttypes . ForIn ( item = p [ 3 ] , iterable = p [ 5 ] , statement = p [ 7 ] ) p [ 0 ] . setpos ( p )
def parse_binary ( self , data , display , rawdict = 0 ) : """values , remdata = s . parse _ binary ( data , display , rawdict = 0) Convert a binary representation of the structure into Python values . DATA is a string or a buffer containing the binary data . DISPLAY should be a Xlib . protocol . display . Di...
ret = { } val = struct . unpack ( self . static_codes , data [ : self . static_size ] ) lengths = { } formats = { } vno = 0 for f in self . static_fields : # Fields without name should be ignored . This is typically # pad and constant fields if not f . name : pass # Store index in val for Length and For...
def clearDay ( self , date ) : """Remove all stored information about this date ( meals or closed information ) . : param date : Date of the day : type date : datetime . date"""
date = self . _handleDate ( date ) if date in self . _days : del self . _days [ date ]
def _status_code_check ( self , response : Dict [ str , Any ] ) : """检查响应码并进行对不同的响应进行处理 . 主要包括 : + 编码在500 ~ 599段为服务异常 , 直接抛出对应异常 + 编码在400 ~ 499段为调用异常 , 为对应ID的future设置异常 + 编码在300 ~ 399段为警告 , 会抛出对应警告 + 编码在200 ~ 399段为执行成功响应 , 将结果设置给对应ID的future . + 编码在100 ~ 199段为服务器响应 , 主要是处理验证响应和心跳响应 Parameters : respo...
code = response . get ( "CODE" ) if self . debug : print ( "resv:{}" . format ( response ) ) print ( code ) if code >= 500 : if self . debug : print ( "server error" ) return self . _server_error_handler ( code ) elif 500 > code >= 400 : if self . debug : print ( "call method error" ...
def timedelta_to_str ( aTimedelta ) : """a conversion function for time deltas to string in the form DD : HH : MM : SS"""
days = aTimedelta . days temp_seconds = aTimedelta . seconds hours = int ( temp_seconds / 3600 ) minutes = int ( ( temp_seconds - hours * 3600 ) / 60 ) seconds = temp_seconds - hours * 3600 - minutes * 60 return '%d %02d:%02d:%02d' % ( days , hours , minutes , seconds )
def _download_subs ( self , download_link , videofile , referer = '' , sub_title = '' ) : """下载字幕 videofile : 视频文件路径 sub _ title : 字幕标题 ( 文件名 ) download _ link : 下载链接 referer : referer"""
root = os . path . dirname ( videofile ) name , _ = os . path . splitext ( os . path . basename ( videofile ) ) ext = '' headers = { 'Referer' : referer } res = self . session . get ( download_link , headers = headers , stream = True ) referer = res . url # 尝试从 Content - Disposition 中获取文件后缀名 content_disposition = res ....
def _ellipsoid_phantom_3d ( space , ellipsoids ) : """Create an ellipsoid phantom in 3d space . Parameters space : ` DiscreteLp ` Space in which the phantom should be generated . If ` ` space . shape ` ` is 1 in an axis , a corresponding slice of the phantom is created ( instead of squashing the whole pha...
# Blank volume p = np . zeros ( space . shape , dtype = space . dtype ) minp = space . grid . min_pt maxp = space . grid . max_pt # Create the pixel grid grid_in = space . grid . meshgrid # Move points to [ - 1 , 1] grid = [ ] for i in range ( 3 ) : mean_i = ( minp [ i ] + maxp [ i ] ) / 2.0 # Where space . sha...
def updateNewsBulletin ( self , msgId , msgType , newsMessage , originExch ) : """updateNewsBulletin ( EWrapper self , int msgId , int msgType , IBString const & newsMessage , IBString const & originExch )"""
return _swigibpy . EWrapper_updateNewsBulletin ( self , msgId , msgType , newsMessage , originExch )
def into_hold ( self , name , obj ) : """Add data into the a storage area provided by the framework . Note : The data is stored with the thread local instance . : param name : name of the data to be stored : param obj : data to be stored : returns : N / A : raises : N / A"""
logger . debug ( 'StackInABox({0}): Holding onto {1} of type {2} ' 'with id {3}' . format ( self . __id , name , type ( obj ) , id ( obj ) ) ) self . holds [ name ] = obj
def api_stop ( server_state ) : """Stop the global API server thread"""
api_srv = server_state [ 'api' ] if api_srv is not None : log . info ( "Shutting down API" ) api_srv . stop_server ( ) api_srv . join ( ) log . info ( "API server joined" ) else : log . info ( "API already joined" ) server_state [ 'api' ] = None
def get_size ( self , value = None ) : """Return the action length including the padding ( multiple of 8 ) ."""
if isinstance ( value , ActionHeader ) : return value . get_size ( ) elif value is None : current_size = super ( ) . get_size ( ) return ceil ( current_size / 8 ) * 8 raise ValueError ( f'Invalid value "{value}" for Action*.get_size()' )
def fragment6 ( pkt , fragSize ) : """Performs fragmentation of an IPv6 packet . Provided packet ( ' pkt ' ) must already contain an IPv6ExtHdrFragment ( ) class . ' fragSize ' argument is the expected maximum size of fragments ( MTU ) . The list of packets is returned . If packet does not contain an IPv6ExtH...
pkt = pkt . copy ( ) if IPv6ExtHdrFragment not in pkt : # TODO : automatically add a fragment before upper Layer # at the moment , we do nothing and return initial packet # as single element of a list return [ pkt ] # If the payload is bigger than 65535 , a Jumbo payload must be used , as # an IPv6 packet can ' t b...
def nlargest ( self , n , columns , keep = 'first' ) : """Return the first ` n ` rows ordered by ` columns ` in descending order . Return the first ` n ` rows with the largest values in ` columns ` , in descending order . The columns that are not specified are returned as well , but not used for ordering . ...
return algorithms . SelectNFrame ( self , n = n , keep = keep , columns = columns ) . nlargest ( )
def main ( ) : """Testing function for Flex Regular Expressions to FST DFA"""
if len ( argv ) < 2 : print 'Usage: %s fst_file [optional: save_file]' % argv [ 0 ] return flex_a = Flexparser ( ) mma = flex_a . yyparse ( argv [ 1 ] ) mma . minimize ( ) print mma if len ( argv ) == 3 : mma . save ( argv [ 2 ] )
def reflash_firmware ( self , hardware_id , ipmi = True , raid_controller = True , bios = True ) : """Reflash hardware firmware . This will cause the server to be unavailable for ~ 60 minutes . The firmware will not be upgraded but rather reflashed to the version installed . : param int hardware _ id : The ID...
return self . hardware . createFirmwareReflashTransaction ( bool ( ipmi ) , bool ( raid_controller ) , bool ( bios ) , id = hardware_id )
def temporary_dir ( ) : """Context manager that creates a temporary directory and chdirs to it . When the context manager exits it returns to the previous cwd and deletes the temporary directory ."""
d = tempfile . mkdtemp ( ) try : with cd ( d ) : yield d finally : if os . path . exists ( d ) : shutil . rmtree ( d )
def splits ( cls , exts , fields , root = '.data' , train = 'train' , validation = 'IWSLT16.TED.tst2013' , test = 'IWSLT16.TED.tst2014' , ** kwargs ) : """Create dataset objects for splits of the IWSLT dataset . Arguments : exts : A tuple containing the extension to path for each language . fields : A tuple c...
cls . dirname = cls . base_dirname . format ( exts [ 0 ] [ 1 : ] , exts [ 1 ] [ 1 : ] ) cls . urls = [ cls . base_url . format ( exts [ 0 ] [ 1 : ] , exts [ 1 ] [ 1 : ] , cls . dirname ) ] check = os . path . join ( root , cls . name , cls . dirname ) path = cls . download ( root , check = check ) train = '.' . join ( ...
def select_renderer ( self , request , renderers , format_suffix = None ) : """Given a request and a list of renderers , return a two - tuple of : ( renderer , media type ) ."""
# Allow URL style format override . eg . " ? format = json format_query_param = self . settings . URL_FORMAT_OVERRIDE format = format_suffix or request . query_params . get ( format_query_param ) if format : renderers = self . filter_renderers ( renderers , format ) accepts = self . get_accept_list ( request ) # Ch...
def mass_2d ( self , R , Rs , rho0 ) : """mass enclosed a 3d sphere or radius r : param r : : param Ra : : param Rs : : return :"""
x = R / Rs gx = self . g_ ( x ) m_2d = 4 * rho0 * Rs * R ** 2 * gx / x ** 2 * np . pi return m_2d
def share_model_ndex ( ) : """Upload the model to NDEX"""
if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_str = body . get ( 'stmts' ) stmts_json = json . loads ( stmts_str ) stmts = stmts_from_json ( stmts_json [ "statements" ] ) ca = CxAssembler ( stmts ) for n , v in body . i...
def add_related ( self , * objects ) : """Add related items The arguments can be individual items or cluster objects containing several items . When two groups of related items share one or more common members , they will be merged into one cluster ."""
master = None # this will become the common cluster of all related items slaves = set ( [ ] ) # set of clusters that are going to be merged in the master solitaire = set ( [ ] ) # set of new items that are not yet part of a cluster for new in objects : if isinstance ( new , self . cls ) : if master is None ...
def get_user_metadata ( self , bucket : str , key : str ) -> typing . Dict [ str , str ] : """Retrieves the user metadata for a given object in a given bucket . If the platform has any mandatory prefixes or suffixes for the metadata keys , they should be stripped before being returned . : param bucket : the buc...
raise NotImplementedError ( )
def update ( self , query , attributes , upsert = False ) : """Updates data in the table . : Parameters : - query ( dict ) , specify the WHERE clause - attributes ( dict ) , specify the SET clause - upsert : boolean . If True , then when there ' s no row matches the query , insert the values : Return : Nu...
if upsert : found_result = self . find_one ( query ) if not found_result : id = self . insert ( attributes ) if id > 0 : return 1 else : return 0 sql = build_update ( self . name , query , attributes ) return self . cursor . execute ( sql )
def parse_radl ( data ) : """Parse a RADL document . Args : - data ( str ) : filepath to a RADL content or a string with content . Return : RADL object ."""
if data is None : return None elif os . path . isfile ( data ) : f = open ( data ) data = "" . join ( f . readlines ( ) ) f . close ( ) elif data . strip ( ) == "" : return RADL ( ) data = data + "\n" parser = RADLParser ( lextab = 'radl' ) return parser . parse ( data )
def cmd_reload_global ( self , plname ) : """reload _ global ` plname ` Reload the * global * plugin named ` plname ` . You should close all instances of the plugin before attempting to reload ."""
gpmon = self . fv . gpmon p_info = gpmon . get_plugin_info ( plname ) gpmon . stop_plugin ( p_info ) self . fv . update_pending ( 0.5 ) self . fv . mm . load_module ( plname ) gpmon . reload_plugin ( plname ) self . fv . start_global_plugin ( plname ) return True
def notebook_authenticate ( cmd_args , force = False , silent = True ) : """Similiar to authenticate but prints student emails after all calls and uses a different way to get codes . If SILENT is True , it will suppress the error message and redirect to FORCE = True"""
server = server_url ( cmd_args ) network . check_ssl ( ) access_token = None if not force : try : access_token = refresh_local_token ( server ) except OAuthException as e : # Account for Invalid Grant Error During make _ token _ post if not silent : raise e return notebook_au...
def _get_memory_contents ( self ) : """Runs the scheduler to determine memory contents at every point in time . Returns : a list of frozenset of strings , where the ith entry describes the tensors in memory when executing operation i ( where schedule [ i ] is an index into GetAllOperationNames ( ) ) ."""
if self . _memory_contents is not None : return self . _memory_contents schedule = scheduler . minimize_peak_memory ( self . _graph , self . _scheduler_alg ) self . _memory_contents = self . _graph . compute_memory_contents_under_schedule ( schedule ) return self . _memory_contents
def _get_index_of_monomial ( self , element , enablesubstitution = True , daggered = False ) : """Returns the index of a monomial ."""
result = [ ] processed_element , coeff1 = separate_scalar_factor ( element ) if processed_element in self . moment_substitutions : r = self . _get_index_of_monomial ( self . moment_substitutions [ processed_element ] , enablesubstitution ) return [ ( k , coeff * coeff1 ) for k , coeff in r ] if enablesubstituti...
def _apply_bracket_layers ( self ) : """Extract bracket layers in a GSGlyph into free - standing UFO glyphs with Designspace substitution rules . As of Glyphs . app 2.6 , only single axis bracket layers are supported , we assume the axis to be the first axis in the Designspace . Bracket layer backgrounds ar...
if not self . _designspace . axes : raise ValueError ( "Cannot apply bracket layers unless at least one axis is defined." ) bracket_axis = self . _designspace . axes [ 0 ] # Determine the axis scale in design space because crossovers / locations are # in design space ( axis . default / minimum / maximum may be user...
def get_previous_version ( version : str ) -> Optional [ str ] : """Returns the version prior to the given version . : param version : A string with the version number . : return : A string with the previous version number"""
debug ( 'get_previous_version' ) found_version = False for commit_hash , commit_message in get_commit_log ( ) : debug ( 'checking commit {}' . format ( commit_hash ) ) if version in commit_message : found_version = True debug ( 'found_version in "{}"' . format ( commit_message ) ) contin...
def build_includes ( ) : """Creates rst files in the _ include directory using the python scripts there . This will ignore any files in the _ include directory that start with ` ` _ ` ` ."""
print ( "Running scripts in _include:" ) cwd = os . getcwd ( ) os . chdir ( '_include' ) pyfiles = glob . glob ( '*.py' ) for fn in pyfiles : if not fn . startswith ( '_' ) : print ( ' {}' . format ( fn ) ) subprocess . check_output ( [ 'python' , fn ] ) os . chdir ( cwd )
def get_raw_input ( description , default = False ) : """Get user input from the command line via raw _ input / input . description ( unicode ) : Text to display before prompt . default ( unicode or False / None ) : Default value to display with prompt . RETURNS ( unicode ) : User input ."""
additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % ( description , additional ) user_input = input_ ( prompt ) return user_input
def curtailment ( self ) : """Get curtailment time series of dispatchable generators ( only active power ) Parameters curtailment : list or : pandas : ` pandas . DataFrame < dataframe > ` See class definition for details . Returns : pandas : ` pandas . DataFrame < dataframe > ` In the case curtailment...
if self . _curtailment is not None : if isinstance ( self . _curtailment , pd . DataFrame ) : try : return self . _curtailment . loc [ [ self . timeindex ] , : ] except : return self . _curtailment . loc [ self . timeindex , : ] elif isinstance ( self . _curtailment , lis...
def plot ( self , axis = None , ** kargs ) : """- plot ( axis = None , * * kwarg ) : Finally , sphviewer . Scene class has its own plotting method . It shows the scene as seen by the camera . It is to say , it plots the particles according to their aparent coordinates ; axis makes a reference to an existing axi...
if ( axis == None ) : axis = plt . gca ( ) axis . plot ( self . __x , self . __y , 'k.' , ** kargs )
def dense ( x , output_dim , reduced_dims = None , expert_dims = None , use_bias = True , activation = None , master_dtype = tf . float32 , slice_dtype = tf . float32 , variable_dtype = None , name = None ) : """Dense layer doing ( kernel * x + bias ) computation . Args : x : a mtf . Tensor of shape [ . . . , r...
if variable_dtype is None : variable_dtype = mtf . VariableDType ( master_dtype , slice_dtype , x . dtype ) if expert_dims is None : expert_dims = [ ] if reduced_dims is None : reduced_dims = x . shape . dims [ - 1 : ] w_shape = mtf . Shape ( expert_dims + reduced_dims + [ output_dim ] ) output_shape = mtf ...
def add_atype ( self , ) : """Add a atype and store it in the self . atypes : returns : None : rtype : None : raises : None"""
i = self . atype_tablev . currentIndex ( ) item = i . internalPointer ( ) if item : atype = item . internal_data ( ) atype . projects . add ( self . _project ) self . atypes . append ( atype ) item . set_parent ( None )
def generate_signed_url ( self , expiration = None , api_access_endpoint = _API_ACCESS_ENDPOINT , method = "GET" , content_md5 = None , content_type = None , response_disposition = None , response_type = None , generation = None , headers = None , query_parameters = None , client = None , credentials = None , version =...
if version is None : version = "v2" elif version not in ( "v2" , "v4" ) : raise ValueError ( "'version' must be either 'v2' or 'v4'" ) resource = "/{bucket_name}/{quoted_name}" . format ( bucket_name = self . bucket . name , quoted_name = quote ( self . name . encode ( "utf-8" ) ) ) if credentials is None : ...
def groupby_apply ( df , cols , func , * args , ** kwargs ) : """Groupby cols and call the function fn on each grouped dataframe . Parameters cols : str | list of str columns to groupby func : function function to call on the grouped data * args : tuple positional parameters to pass to func * * kwar...
try : axis = kwargs . pop ( 'axis' ) except KeyError : axis = 0 lst = [ ] for _ , d in df . groupby ( cols ) : # function fn should be free to modify dataframe d , therefore # do not mark d as a slice of df i . e no SettingWithCopyWarning lst . append ( func ( d , * args , ** kwargs ) ) return pd . concat (...
def visit_VariableDeclaration ( self , node ) : """Visitor for ` VariableDeclaration ` AST node ."""
var_name = node . assignment . left . identifier . name var_is_mutable = node . assignment . left . is_mutable var_symbol = VariableSymbol ( var_name , var_is_mutable ) if self . table [ var_name ] is not None : raise SementicError ( f"Variable `{var_name}` is already declared." ) self . table [ var_symbol . name ]...
def compile_results ( self ) : """Compile all results for the current test"""
self . _init_dataframes ( ) self . total_transactions = len ( self . main_results [ 'raw' ] ) self . _init_dates ( )
def to_dqflag ( self , name = None , minlen = 1 , dtype = None , round = False , label = None , description = None ) : """Convert this series into a ` ~ gwpy . segments . DataQualityFlag ` . Each contiguous set of ` True ` values are grouped as a ` ~ gwpy . segments . Segment ` running from the GPS time the fir...
from . . segments import DataQualityFlag # format dtype if dtype is None : dtype = self . t0 . dtype if isinstance ( dtype , numpy . dtype ) : # use callable dtype dtype = dtype . type start = dtype ( self . t0 . value ) dt = dtype ( self . dt . value ) # build segmentlists ( can use simple objects since DQFlag...
def predict ( self , X , cut_point = 0.5 ) : """Predicted class . Parameters X : array - like , shape = [ n _ samples , n _ features ] Returns T : array - like , shape = [ n _ samples ] Returns the prediction of the sample . ."""
return np . floor ( self . predict_proba ( X ) [ : , 1 ] + ( 1 - cut_point ) )
def _get_subclass_names ( self , classname , namespace , deep_inheritance ) : """Get class names that are subclasses of the classname input parameter from the repository . If DeepInheritance is False , get only classes in the repository for the defined namespace for which this class is a direct super class ...
assert classname is None or isinstance ( classname , ( six . string_types , CIMClassName ) ) if isinstance ( classname , CIMClassName ) : classname = classname . classname # retrieve first level of subclasses for which classname is superclass try : classes = self . classes [ namespace ] except KeyError : cl...
def start_server ( data_stream , port = 5557 , hwm = 10 ) : """Start a data processing server . This command starts a server in the current process that performs the actual data processing ( by retrieving data from the given data stream ) . It also starts a second process , the broker , which mediates between...
logging . basicConfig ( level = 'INFO' ) context = zmq . Context ( ) socket = context . socket ( zmq . PUSH ) socket . set_hwm ( hwm ) socket . bind ( 'tcp://*:{}' . format ( port ) ) it = data_stream . get_epoch_iterator ( ) logger . info ( 'server started' ) while True : try : data = next ( it ) s...
def error_page ( participant = None , error_text = None , compensate = True , error_type = "default" , request_data = "" , ) : """Render HTML for error page ."""
config = _config ( ) if error_text is None : error_text = """There has been an error and so you are unable to continue, sorry!""" if participant is not None : hit_id = ( participant . hit_id , ) assignment_id = ( participant . assignment_id , ) worker_id = participant . worker_id participant...
def _suicide_when_without_parent ( self , parent_pid ) : '''Kill this process when the parent died .'''
while True : time . sleep ( 5 ) try : # Check pid alive os . kill ( parent_pid , 0 ) except OSError : # Forcibly exit # Regular sys . exit raises an exception self . stop ( ) log . warning ( 'The parent is not alive, exiting.' ) os . _exit ( 999 )
def cov ( self , other = None , pairwise = None , bias = False , ** kwargs ) : """Exponential weighted sample covariance ."""
if other is None : other = self . _selected_obj # only default unset pairwise = True if pairwise is None else pairwise other = self . _shallow_copy ( other ) def _get_cov ( X , Y ) : X = self . _shallow_copy ( X ) Y = self . _shallow_copy ( Y ) cov = libwindow . ewmcov ( X . _prep_values ( ) , Y...
def _imagpart ( self , f ) : """Function returning the imaginary part of the result from ` ` f ` ` ."""
def f_im ( x , ** kwargs ) : result = np . asarray ( f ( x , ** kwargs ) , dtype = self . scalar_out_dtype ) return result . imag if is_real_dtype ( self . out_dtype ) : return self . zero ( ) else : return self . real_space . element ( f_im )