signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def create_model ( schema , collection , class_name = None ) : """Main entry point to creating a new mongothon model . Both schema and Pymongo collection objects must be provided . Returns a new class which can be used as a model class . The class name of the model class by default is inferred from the prov...
if not class_name : class_name = camelize ( str ( collection . name ) ) model_class = type ( class_name , ( Model , ) , dict ( schema = schema , _collection_factory = staticmethod ( lambda : collection ) ) ) # Since we are dynamically creating this class here , we modify _ _ module _ _ on the # created class to poi...
def progress ( UserUser_presence = 0 ) : """PROGRESS Section 9.3.17"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x3 ) # 0000011 c = ProgressIndicator ( ) packet = a / b / c if UserUser_presence is 1 : d = UserUserHdr ( ) packet = packet / d return packet
def can ( self , permission , obj , ** kwargs ) : """Check if we can do something with an object . : param permission : The permission to look for . : param obj : The object to check the ACL of . : param * * kwargs : The context to pass to predicates . > > > auth . can ( ' read ' , some _ object ) > > > a...
context = { 'user' : current_user } for func in self . context_processors : context . update ( func ( ) ) context . update ( get_object_context ( obj ) ) context . update ( kwargs ) return check ( permission , iter_object_acl ( obj ) , ** context )
def _compute_derivatives ( self ) : """Compute derivatives of the time series ."""
derivatives = [ ] for i , ( timestamp , value ) in enumerate ( self . time_series_items ) : if i > 0 : pre_item = self . time_series_items [ i - 1 ] pre_timestamp = pre_item [ 0 ] pre_value = pre_item [ 1 ] td = timestamp - pre_timestamp derivative = ( value - pre_value ) / t...
def solveConsIndShock ( solution_next , IncomeDstn , LivPrb , DiscFac , CRRA , Rfree , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool ) : '''Solves a single period consumption - saving problem with CRRA utility and risky income ( subject to permanent and transitory shocks ) . Can generate a value ...
# Use the basic solver if user doesn ' t want cubic splines or the value function if ( not CubicBool ) and ( not vFuncBool ) : solver = ConsIndShockSolverBasic ( solution_next , IncomeDstn , LivPrb , DiscFac , CRRA , Rfree , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool ) else : # Use the " advanced ...
def update_build_configuration_set ( id , ** kwargs ) : """Update a BuildConfigurationSet"""
data = update_build_configuration_set_raw ( id , ** kwargs ) if data : return utils . format_json ( data )
def get_public_events ( self ) : """: calls : ` GET / users / : user / events / public < http : / / developer . github . com / v3 / activity / events > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . Event . Event `"""
return github . PaginatedList . PaginatedList ( github . Event . Event , self . _requester , self . url + "/events/public" , None )
def get_template ( template_dict , parameter_overrides = None ) : """Given a SAM template dictionary , return a cleaned copy of the template where SAM plugins have been run and parameter values have been substituted . Parameters template _ dict : dict unprocessed SAM template dictionary parameter _ overri...
template_dict = template_dict or { } if template_dict : template_dict = SamTranslatorWrapper ( template_dict ) . run_plugins ( ) template_dict = SamBaseProvider . _resolve_parameters ( template_dict , parameter_overrides ) ResourceMetadataNormalizer . normalize ( template_dict ) return template_dict
def _search_for_import_symbols ( self , matches ) : '''Just encapsulating a search that takes place fairly often'''
# Sanity check if not hasattr ( self . pefile_handle , 'DIRECTORY_ENTRY_IMPORT' ) : return [ ] # Find symbols that match pattern = '|' . join ( re . escape ( match ) for match in matches ) exp = re . compile ( pattern ) symbol_list = [ ] for module in self . pefile_handle . DIRECTORY_ENTRY_IMPORT : for symbol i...
def load ( self , code , setup = '' , teardown = '' ) : """Prepares a set of setup , test , and teardown code to be run in the console . PARAMETERS : code - - list ; processed lines of code . Elements in the list are either strings ( input ) or CodeAnswer objects ( output ) setup - - str ; raw setup code ...
super ( ) . load ( code , setup , teardown ) self . _frame = self . _original_frame . copy ( )
def get_blank_row ( self , filler = "-" , splitter = "+" ) : """Gets blank row : param filler : Fill empty columns with this char : param splitter : Separate columns with this char : return : Pretty formatted blank row ( with no meaningful data in it )"""
return self . get_pretty_row ( [ "" for _ in self . widths ] , # blanks filler , # fill with this splitter , # split columns with this )
def load_commodities ( self ) : """Load the commodities for Amounts in this object ."""
if isinstance ( self . available , Amount ) : self . available = Amount ( "{0:.8f} {1}" . format ( self . available . to_double ( ) , self . currency ) ) else : self . available = Amount ( "{0:.8f} {1}" . format ( self . available , self . currency ) ) if isinstance ( self . total , Amount ) : self . total ...
def _split_multiline_prompt ( get_prompt_tokens ) : """Take a ` get _ prompt _ tokens ` function and return three new functions instead . One that tells whether this prompt consists of multiple lines ; one that returns the tokens to be shown on the lines above the input ; and another one with the tokens to be...
def has_before_tokens ( cli ) : for token , char in get_prompt_tokens ( cli ) : if '\n' in char : return True return False def before ( cli ) : result = [ ] found_nl = False for token , char in reversed ( explode_tokens ( get_prompt_tokens ( cli ) ) ) : if found_nl : ...
def get_multifile_object_child_location ( self , parent_item_prefix : str , child_name : str ) -> str : """Implementation of the parent abstract method . In this mode the attribute is a file inside the parent object folder : param parent _ item _ prefix : the absolute file prefix of the parent item . : return...
check_var ( parent_item_prefix , var_types = str , var_name = 'parent_item_prefix' ) check_var ( child_name , var_types = str , var_name = 'item_name' ) # assert that folder _ path is a folder if not isdir ( parent_item_prefix ) : raise ValueError ( 'Cannot get attribute item in non-flat mode, parent item path is n...
def value_counts ( values , sort = True , ascending = False , normalize = False , bins = None , dropna = True ) : """Compute a histogram of the counts of non - null values . Parameters values : ndarray ( 1 - d ) sort : boolean , default True Sort by values ascending : boolean , default False Sort in asc...
from pandas . core . series import Series , Index name = getattr ( values , 'name' , None ) if bins is not None : try : from pandas . core . reshape . tile import cut values = Series ( values ) ii = cut ( values , bins , include_lowest = True ) except TypeError : raise TypeError ...
def dict ( self , ** kwargs ) : """Dictionary representation ."""
return dict ( time = self . timestamp , address = self . address , channel = self . channel , value = self . value , ** kwargs )
def check_int ( integer ) : """Check if number is integer or not . : param integer : Number as str : return : Boolean"""
if not isinstance ( integer , str ) : return False if integer [ 0 ] in ( '-' , '+' ) : return integer [ 1 : ] . isdigit ( ) return integer . isdigit ( )
def luks_cleartext_holder ( self ) : """Get wrapper to the unlocked luks cleartext device ."""
if not self . is_luks : return None for device in self . _daemon : if device . luks_cleartext_slave == self : return device return None
def get_destinations ( cls , domain , source ) : """Retrieve forward information ."""
forwards = cls . list ( domain , { 'items_per_page' : 500 } ) for fwd in forwards : if fwd [ 'source' ] == source : return fwd [ 'destinations' ] return [ ]
def validate_packet ( packet ) : """Check if packet is valid OF packet . Raises : UnpackException : If the packet is invalid ."""
if not isinstance ( packet , bytes ) : raise UnpackException ( 'invalid packet' ) packet_length = len ( packet ) if packet_length < 8 or packet_length > 2 ** 16 : raise UnpackException ( 'invalid packet' ) if packet_length != int . from_bytes ( packet [ 2 : 4 ] , byteorder = 'big' ) : raise UnpackException ...
def get_output_metadata ( self , path , filename ) : """Describe a file by its metadata . : return : dict"""
checksums = get_checksums ( path , [ 'md5' ] ) metadata = { 'filename' : filename , 'filesize' : os . path . getsize ( path ) , 'checksum' : checksums [ 'md5sum' ] , 'checksum_type' : 'md5' } if self . metadata_only : metadata [ 'metadata_only' ] = True return metadata
def pop_choice ( params : Dict [ str , Any ] , key : str , choices : List [ Any ] , default_to_first_choice : bool = False , history : str = "?." ) -> Any : """Performs the same function as : func : ` Params . pop _ choice ` , but is required in order to deal with places that the Params object is not welcome , su...
value = Params ( params , history ) . pop_choice ( key , choices , default_to_first_choice ) return value
def shadow_copy ( self ) : """Return a copy of the resource with same raw data : return : copy of the resource"""
ret = self . __class__ ( ) if not self . _is_updated ( ) : # before copy , make sure source is updated . self . update ( ) ret . _parsed_resource = self . _parsed_resource return ret
def post ( self , request , * args , ** kwargs ) : """Method for handling POST requests . Checks for a modify confirmation and performs the action by calling ` process _ action ` ."""
queryset = self . get_selected ( request ) if request . POST . get ( 'modify' ) : response = self . process_action ( request , queryset ) if not response : url = self . get_done_url ( ) return self . render ( request , redirect_url = url ) else : return response else : return sel...
def sg_aconv ( tensor , opt ) : r"""Applies a 2 - D atrous ( or dilated ) convolution . Args : tensor : A 4 - D ` Tensor ` ( automatically passed by decorator ) . opt : size : A tuple / list of positive integers of length 2 representing ` [ kernel height , kernel width ] ` . Can be an integer if both valu...
# default options opt += tf . sg_opt ( size = ( 3 , 3 ) , rate = 2 , pad = 'SAME' ) opt . size = opt . size if isinstance ( opt . size , ( tuple , list ) ) else [ opt . size , opt . size ] # parameter tf . sg _ initializer w = tf . sg_initializer . he_uniform ( 'W' , ( opt . size [ 0 ] , opt . size [ 1 ] , opt . in_dim...
def users_me_merge ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / users # merge - self - with - another - user"
api_path = "/api/v2/users/me/merge.json" return self . call ( api_path , method = "PUT" , data = data , ** kwargs )
def statistics ( self ) : """Access the statistics : returns : twilio . rest . taskrouter . v1 . workspace . worker . worker _ statistics . WorkerStatisticsList : rtype : twilio . rest . taskrouter . v1 . workspace . worker . worker _ statistics . WorkerStatisticsList"""
if self . _statistics is None : self . _statistics = WorkerStatisticsList ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , worker_sid = self . _solution [ 'sid' ] , ) return self . _statistics
def matplot ( x , y , z , ax = None , colorbar = True , ** kwargs ) : """Plot x , y , z as expected with correct axis labels . Examples > > > import matplotlib . pyplot as plt > > > import numpy as np > > > from reda . plotters import matplot > > > a = np . arange ( 4) > > > b = np . arange ( 3 ) + 3 ...
xmin = x . min ( ) xmax = x . max ( ) dx = np . abs ( x [ 0 , 1 ] - x [ 0 , 0 ] ) ymin = y . min ( ) ymax = y . max ( ) dy = np . abs ( y [ 1 , 0 ] - y [ 0 , 0 ] ) x2 , y2 = np . meshgrid ( np . arange ( xmin , xmax + 2 * dx , dx ) - dx / 2. , np . arange ( ymin , ymax + 2 * dy , dy ) - dy / 2. ) if not ax : fig , ...
def serialize ( self , value , greedy = True ) : """Greedy serialization requires the value to either be a column or convertible to a column , whereas non - greedy serialization will pass through any string as - is and will only serialize Column objects . Non - greedy serialization is useful when preparing ...
if greedy and not isinstance ( value , Column ) : value = self . normalize ( value ) if isinstance ( value , Column ) : return value . id else : return value
def process_request_body ( fn ) : '''A decorator to skip a processor function if process _ request _ body is False'''
@ functools . wraps ( fn ) def wrapped ( * args , ** kwargs ) : # pylint : disable = C0111 if cherrypy . request . process_request_body is not False : fn ( * args , ** kwargs ) return wrapped
def process_date_from_to_options ( options , to_datetime = False , default_dt_to = False ) : """to _ datetime - приводить ли date к datetime default _ dt _ to - устанавливать заведомо будущее дефолтное значение для dt _ to"""
start_time = datetime . datetime . now ( ) if options . get ( 'last_week' ) : dt_from = start_time - datetime . timedelta ( days = 7 ) dt_to = start_time elif options . get ( 'last_day' ) : dt_from = start_time - datetime . timedelta ( days = 1 ) dt_to = start_time elif options . get ( 'last_2hours' ) :...
def servicegroup_server_exists ( sg_name , s_name , s_port = None , ** connection_args ) : '''Check if a server : port combination is a member of a servicegroup CLI Example : . . code - block : : bash salt ' * ' netscaler . servicegroup _ server _ exists ' serviceGroupName ' ' serverName ' ' serverPort ' '''
return _servicegroup_get_server ( sg_name , s_name , s_port , ** connection_args ) is not None
def throttle ( self , wait ) : """Returns a function , that , when invoked , will only be triggered at most once during a given window of time ."""
ns = self . Namespace ( ) ns . timeout = None ns . throttling = None ns . more = None ns . result = None def done ( ) : ns . more = ns . throttling = False whenDone = _ . debounce ( done , wait ) wait = ( float ( wait ) / float ( 1000 ) ) def throttled ( * args , ** kwargs ) : def later ( ) : ns . timeo...
def _convert_timedelta_to_seconds ( timedelta ) : """Returns the total seconds calculated from the supplied timedelta . ( Function provided to enable running on Python 2.6 which lacks timedelta . total _ seconds ( ) ) ."""
days_in_seconds = timedelta . days * 24 * 3600 return int ( ( timedelta . microseconds + ( timedelta . seconds + days_in_seconds ) * 10 ** 6 ) / 10 ** 6 )
def purge_queues ( queues = None ) : """Purge the given queues ."""
current_queues . purge ( queues = queues ) click . secho ( 'Queues {} have been purged.' . format ( queues or current_queues . queues . keys ( ) ) , fg = 'green' )
def _pack3 ( obj , fp , ** options ) : """Serialize a Python object into MessagePack bytes . Args : obj : a Python object fp : a . write ( ) - supporting file - like object Kwargs : ext _ handlers ( dict ) : dictionary of Ext handlers , mapping a custom type to a callable that packs an instance of the t...
global compatibility ext_handlers = options . get ( "ext_handlers" ) if obj is None : _pack_nil ( obj , fp , options ) elif ext_handlers and obj . __class__ in ext_handlers : _pack_ext ( ext_handlers [ obj . __class__ ] ( obj ) , fp , options ) elif isinstance ( obj , bool ) : _pack_boolean ( obj , fp , opt...
def _on_loop_start ( self , variables ) : """performs on - loop - start actions like callbacks variables contains local namespace variables . Parameters variables : dict of available variables Returns None"""
for callback in self . callbacks : if hasattr ( callback , 'on_loop_start' ) : self . logs_ [ str ( callback ) ] . append ( callback . on_loop_start ( ** variables ) )
def paste_as ( self , key , data ) : """Paste and transform data Data may be given as a Python code as well as a tab separated multi - line strings similar to paste ."""
def error_msg ( err ) : msg = _ ( "Error evaluating data: " ) + str ( err ) post_command_event ( self . main_window , self . StatusBarMsg , text = msg ) interfaces = self . main_window . interfaces key = self . main_window . grid . actions . cursor try : obj = ast . literal_eval ( data ) except ( SyntaxErro...
def percent_encode_plus ( text , encode_set = QUERY_ENCODE_SET , encoding = 'utf-8' ) : '''Percent encode text for query strings . Unlike Python ' s ` ` quote _ plus ` ` , this function accepts a blacklist instead of a whitelist of safe characters .'''
if ' ' not in text : return percent_encode ( text , encode_set , encoding ) else : result = percent_encode ( text , encode_set , encoding ) return result . replace ( ' ' , '+' )
def remove_invalid ( self ) : """Remove entities which declare themselves invalid Alters self . entities : shortened"""
valid = np . array ( [ i . is_valid for i in self . entities ] , dtype = np . bool ) self . entities = self . entities [ valid ]
def create ( self ) : """Create a new reminder ."""
params = { } return self . send ( url = self . _base_url + 'create' , method = 'POST' , json = params )
def _generatePayload ( self , query ) : """Adds the following defaults to the payload : _ _ rev , _ _ user , _ _ a , ttstamp , fb _ dtsg , _ _ req"""
payload = self . _payload_default . copy ( ) if query : payload . update ( query ) payload [ "__req" ] = str_base ( self . _req_counter , 36 ) payload [ "seq" ] = self . _seq self . _req_counter += 1 return payload
def delete_from_matching_blacklist ( db , entity ) : """Remove an blacklisted entity from the registry . This function removes the given blacklisted entity from the registry . It checks first whether the excluded entity is already on the registry . When it is found , the entity is removed . Otherwise , it wil...
with db . connect ( ) as session : mb = session . query ( MatchingBlacklist ) . filter ( MatchingBlacklist . excluded == entity ) . first ( ) if not mb : raise NotFoundError ( entity = entity ) delete_from_matching_blacklist_db ( session , mb )
def not_equal ( lhs , rhs ) : """Returns the result of element - wise * * not equal to * * ( ! = ) comparison operation with broadcasting . For each element in input arrays , return 1 ( true ) if corresponding elements are different , otherwise return 0 ( false ) . Equivalent to ` ` lhs ! = rhs ` ` and ` ` ...
# pylint : disable = no - member , protected - access return _ufunc_helper ( lhs , rhs , op . broadcast_not_equal , lambda x , y : 1 if x != y else 0 , _internal . _not_equal_scalar , None )
def second_params_two ( test , two ) : """Second resource * POST : return [ test , two , request data ] * GET : return [ test , two ]"""
if request . method == 'POST' : return [ test , two , request . data ] return { 'result' : [ test , two ] }
def is_solid ( regex ) : """Check the given regular expression is solid . > > > is _ solid ( r ' a ' ) True > > > is _ solid ( r ' [ ab ] ' ) True > > > is _ solid ( r ' ( a | b | c ) ' ) True > > > is _ solid ( r ' ( a | b | c ) ? ' ) True > > > is _ solid ( r ' ( a | b ) ( c ) ' ) False > > ...
shape = re . sub ( r'(\\.|[^\[\]\(\)\|\?\+\*])' , '#' , regex ) skeleton = shape . replace ( '#' , '' ) if len ( shape ) <= 1 : return True if re . match ( r'^\[[^\]]*\][\*\+\?]?$' , shape ) : return True if re . match ( r'^\([^\(]*\)[\*\+\?]?$' , shape ) : return True if re . match ( r'^\(\)#*?\)\)' , skel...
def fix_bam_header ( job , bamfile , sample_type , univ_options , samtools_options , retained_chroms = None ) : """Fix the bam header to remove the command line call . Failing to do this causes Picard to reject the bam . : param dict bamfile : The input bam file : param str sample _ type : Description of the ...
if retained_chroms is None : retained_chroms = [ ] work_dir = os . getcwd ( ) input_files = { sample_type + '.bam' : bamfile } input_files = get_files_from_filestore ( job , input_files , work_dir , docker = True ) parameters = [ 'view' , '-H' , input_files [ sample_type + '.bam' ] ] with open ( '/' . join ( [ work...
def parse ( self , contents ) : """Parse the document . : param contents : The text contents of the document . : rtype : a * generator * of tokenized text ."""
i = 0 for text in contents . split ( self . delim ) : if not len ( text . strip ( ) ) : continue words = text . split ( ) char_offsets = [ 0 ] + [ int ( _ ) for _ in np . cumsum ( [ len ( x ) + 1 for x in words ] ) [ : - 1 ] ] text = " " . join ( words ) yield { "text" : text , "words" : wor...
def debug ( self , value ) : """Turn on debug logging if necessary . : param value : Value of debug flag"""
self . _debug = value if self . _debug : # Turn on debug logging logging . getLogger ( ) . setLevel ( logging . DEBUG )
def main ( ) : """Budou main method for the command line tool ."""
args = docopt ( __doc__ ) if args [ '--version' ] : print ( __version__ ) sys . exit ( ) result = parse ( args [ '<source>' ] , segmenter = args [ '--segmenter' ] , language = args [ '--language' ] , classname = args [ '--classname' ] ) print ( result [ 'html_code' ] ) sys . exit ( )
def index ( self , row , column , parent = None ) : """Return the index of the item in the model specified by the given row , column and parent index . : param row : the row of the item : type row : int : param column : the column for the item : type column : int : param parent : the parent index : ty...
if parent is None : parent = QtCore . QModelIndex ( ) if not self . hasIndex ( row , column , parent ) : return QtCore . QModelIndex ( ) if parent . isValid ( ) : parentItem = parent . internalPointer ( ) else : parentItem = self . _root try : childItem = parentItem . child ( row ) return self ....
def mzn2fzn ( mzn , * dzn_files , args = None , data = None , include = None , stdlib_dir = None , globals_dir = None , declare_enums = True , allow_multiple_assignments = False , keep = False , output_vars = None , output_base = None , output_mode = 'item' , no_ozn = False ) : """Flatten a MiniZinc model into a Fl...
mzn_file , dzn_files , data_file , data , keep , _output_mode , types = _minizinc_preliminaries ( mzn , * dzn_files , args = args , data = data , include = include , stdlib_dir = stdlib_dir , globals_dir = globals_dir , output_vars = output_vars , keep = keep , output_base = output_base , output_mode = output_mode , de...
def _get_acceptable_response_type ( ) : """Return the mimetype for this request ."""
if ( 'Accept' not in request . headers or request . headers [ 'Accept' ] in ALL_CONTENT_TYPES ) : return JSON acceptable_content_types = set ( request . headers [ 'ACCEPT' ] . strip ( ) . split ( ',' ) ) if acceptable_content_types & HTML_CONTENT_TYPES : return HTML elif acceptable_content_types & JSON_CONTENT_...
def is_logon ( self , verify = False ) : """Return a boolean indicating whether the session is currently logged on to the HMC . By default , this method checks whether there is a session - id set and considers that sufficient for determining that the session is logged on . The ` verify ` parameter can be us...
if self . _session_id is None : return False if verify : try : self . get ( '/api/console' , logon_required = True ) except ServerAuthError : return False return True
def memory_usage ( self , index = True , deep = False ) : """Returns the memory usage of each column in bytes Args : index ( bool ) : Whether to include the memory usage of the DataFrame ' s index in returned Series . Defaults to True deep ( bool ) : If True , introspect the data deeply by interrogating o...
assert not index , "Internal Error. Index must be evaluated in child class" return self . _reduce_dimension ( self . _query_compiler . memory_usage ( index = index , deep = deep ) )
def get_station_and_time ( wxdata : [ str ] ) -> ( [ str ] , str , str ) : # type : ignore """Returns the report list and removed station ident and time strings"""
station = wxdata . pop ( 0 ) qtime = wxdata [ 0 ] if wxdata and qtime . endswith ( 'Z' ) and qtime [ : - 1 ] . isdigit ( ) : rtime = wxdata . pop ( 0 ) elif wxdata and len ( qtime ) == 6 and qtime . isdigit ( ) : rtime = wxdata . pop ( 0 ) + 'Z' else : rtime = '' return wxdata , station , rtime
def bind_to_instance ( self , instance ) : """Bind a ResourceApi instance to an operation ."""
self . binding = instance self . middleware . append ( instance )
def png ( out , metadata , f ) : """Convert to PNG format . ` metadata ` should be a Plan9 5 - tuple ; ` f ` the input file ( see : meth : ` pixmeta ` ) ."""
import png pixels , meta = pixmeta ( metadata , f ) p = png . Writer ( ** meta ) p . write ( out , pixels )
def vcenter_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) vcenter = ET . SubElement ( config , "vcenter" , xmlns = "urn:brocade.com:mgmt:brocade-vswitch" ) id = ET . SubElement ( vcenter , "id" ) id . text = kwargs . pop ( 'id' ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def get_assessment_part_form ( self , * args , ** kwargs ) : """Pass through to provider AssessmentPartAdminSession . get _ assessment _ part _ form _ for _ update"""
# This method might be a bit sketchy . Time will tell . if isinstance ( args [ - 1 ] , list ) or 'assessment_part_record_types' in kwargs : return self . get_assessment_part_form_for_create ( * args , ** kwargs ) else : return self . get_assessment_part_form_for_update ( * args , ** kwargs )
def getBinding ( self ) : """Return the Binding object that is referenced by this port ."""
wsdl = self . getService ( ) . getWSDL ( ) return wsdl . bindings [ self . binding ]
def order_limit ( self , timeInForce = TIME_IN_FORCE_GTC , ** params ) : """Send in a new limit order Any order with an icebergQty MUST have timeInForce set to GTC . : param symbol : required : type symbol : str : param side : required : type side : str : param quantity : required : type quantity : de...
params . update ( { 'type' : self . ORDER_TYPE_LIMIT , 'timeInForce' : timeInForce } ) return self . create_order ( ** params )
def p_val ( p ) : """bexpr : VAL bexpr % prec UMINUS"""
def val ( s ) : try : x = float ( s ) except : x = 0 warning ( p . lineno ( 1 ) , "Invalid string numeric constant '%s' evaluated as 0" % s ) return x if p [ 2 ] . type_ != TYPE . string : api . errmsg . syntax_error_expected_string ( p . lineno ( 1 ) , TYPE . to_string ( p [ 2 ]...
def _get ( url , profile ) : '''Get a specific dashboard .'''
request_url = "{0}/api/dashboards/{1}" . format ( profile . get ( 'grafana_url' ) , url ) response = requests . get ( request_url , headers = { "Accept" : "application/json" , "Authorization" : "Bearer {0}" . format ( profile . get ( 'grafana_token' ) ) } , timeout = profile . get ( 'grafana_timeout' , 3 ) , ) data = r...
def winning_name ( self ) : """Returns a ` ` string ` ` of the winning team ' s name , such as ' Purdue Boilermakers ' ."""
if self . winner == HOME : if 'cbb/schools' not in str ( self . _home_name ) : return str ( self . _home_name ) return self . _home_name . text ( ) if 'cbb/schools' not in str ( self . _away_name ) : return str ( self . _away_name ) return self . _away_name . text ( )
def handle ( self , pkt , raddress , rport ) : """Handle the packet in response to an ACK , which should be a DAT ."""
if isinstance ( pkt , TftpPacketDAT ) : return self . handleDat ( pkt ) # Every other packet type is a problem . elif isinstance ( pkt , TftpPacketACK ) : # Umm , we ACK , you don ' t . self . sendError ( TftpErrors . IllegalTftpOp ) raise TftpException ( "Received ACK from peer when expecting DAT" ) elif i...
def set_metadata ( self , set_id , fp ) : """Set the XML metadata on a set . : param file fp : file - like object to read the XML metadata from ."""
base_url = self . client . get_url ( 'SET' , 'GET' , 'single' , { 'id' : set_id } ) self . _metadata . set ( base_url , fp )
def resend_presence ( self ) : """Re - send the currently configured presence . : return : Stanza token of the presence stanza or : data : ` None ` if the stream is not established . : rtype : : class : ` ~ . stream . StanzaToken ` . . note : : : meth : ` set _ presence ` automatically broadcasts the new ...
if self . client . established : return self . client . enqueue ( self . make_stanza ( ) )
def get_urls ( self ) : """Add ` ` layout _ placeholder _ data ` ` URL ."""
# See : ` fluent _ pages . pagetypes . fluentpage . admin . FluentPageAdmin ` . urls = super ( LayoutAdmin , self ) . get_urls ( ) my_urls = patterns ( '' , url ( r'^placeholder_data/(?P<id>\d+)/$' , self . admin_site . admin_view ( self . placeholder_data_view ) , name = 'layout_placeholder_data' , ) ) return my_urls ...
def build_unique_fragments ( self ) : """Find all possible fragment combinations of the MoleculeGraphs ( in other words , all connected induced subgraphs ) : return :"""
self . set_node_attributes ( ) graph = self . graph . to_undirected ( ) nm = iso . categorical_node_match ( "specie" , "ERROR" ) # find all possible fragments , aka connected induced subgraphs all_fragments = [ ] for ii in range ( 1 , len ( self . molecule ) ) : for combination in combinations ( graph . nodes , ii ...
def request_permission ( cls , permissions ) : """Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied ."""
app = AndroidApplication . instance ( ) f = app . create_future ( ) def on_result ( perms ) : allowed = True for p in permissions : allowed = allowed and perms . get ( p , False ) f . set_result ( allowed ) app . request_permissions ( permissions ) . then ( on_result ) return f
def send_http_error ( self , http_code , cim_error = None , cim_error_details = None , headers = None ) : """Send an HTTP response back to the WBEM server that indicates an error at the HTTP level ."""
self . send_response ( http_code , http_client . responses . get ( http_code , '' ) ) self . send_header ( "CIMExport" , "MethodResponse" ) if cim_error is not None : self . send_header ( "CIMError" , cim_error ) if cim_error_details is not None : self . send_header ( "CIMErrorDetails" , cim_error_details ) if ...
def add_wikilink ( self , title , href , ** attrs ) : """Add a Wiki link to the project and returns a : class : ` WikiLink ` object . : param title : title of the : class : ` WikiLink ` : param href : href of the : class : ` WikiLink ` : param attrs : optional attributes for : class : ` WikiLink `"""
return WikiLinks ( self . requester ) . create ( self . id , title , href , ** attrs )
def compute_aic ( model_object ) : """Compute the Akaike Information Criteria for an estimated model . Parameters model _ object : an MNDC _ Model ( multinomial discrete choice model ) instance . The model should have already been estimated . ` model _ object . log _ likelihood ` should be a number , and ...
assert isinstance ( model_object . params , pd . Series ) assert isinstance ( model_object . log_likelihood , Number ) return - 2 * model_object . log_likelihood + 2 * model_object . params . size
def extract ( self , item , list_article_candidate ) : """Compares the extracted publish dates . : param item : The corresponding NewscrawlerItem : param list _ article _ candidate : A list , the list of ArticleCandidate - Objects which have been extracted : return : A string , the most likely publish date"""
list_publish_date = [ ] for article_candidate in list_article_candidate : if article_candidate . publish_date != None : list_publish_date . append ( ( article_candidate . publish_date , article_candidate . extractor ) ) # If there is no value in the list , return None . if len ( list_publish_date ) == 0 : ...
def GetLinkedFileEntry ( self ) : """Retrieves the linked file entry , for example for a symbolic link . Returns : OSFileEntry : linked file entry or None if not available ."""
link = self . _GetLink ( ) if not link : return None path_spec = os_path_spec . OSPathSpec ( location = link ) return OSFileEntry ( self . _resolver_context , self . _file_system , path_spec )
def flag_values_dict ( self ) : """Returns a dictionary that maps flag names to flag values ."""
return { name : flag . value for name , flag in six . iteritems ( self . _flags ( ) ) }
def set_last_position ( self , last_position ) : """Called from the manager , it is in charge of updating the last position of data commited by the writer , in order to have resume support"""
last_position = last_position or { } last_position . setdefault ( 'readed_streams' , [ ] ) last_position . setdefault ( 'stream_offset' , { } ) self . last_position = last_position
def inject_nmi ( self ) : """Inject NMI , Non Maskable Interrupt . Inject NMI ( Non Maskable Interrupt ) for a node immediately . : raises : IloError , on an error from iLO"""
sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID ) if sushy_system . power_state != sushy . SYSTEM_POWER_STATE_ON : raise exception . IloError ( "Server is not in powered on state." ) try : sushy_system . reset_system ( sushy . RESET_NMI ) except sushy . exceptions . SushyError as e : msg = ( se...
def fit ( self , X , y , cost_mat , sample_weight = None ) : """Build a Bagging ensemble of estimators from the training set ( X , y ) . Parameters X : { array - like , sparse matrix } of shape = [ n _ samples , n _ features ] The training input samples . Sparse matrices are accepted only if they are suppor...
random_state = check_random_state ( self . random_state ) # Convert data # X , y = check _ X _ y ( X , y , [ ' csr ' , ' csc ' , ' coo ' ] ) # Not in sklearn verion 0.15 # Remap output n_samples , self . n_features_ = X . shape y = self . _validate_y ( y ) # Check parameters self . _validate_estimator ( ) if isinstance...
def find_gap ( l , value ) : """try to find a address gap in the list of modbus registers"""
for index in range ( len ( l ) ) : if l [ index ] == value : return None if l [ index ] > value : return index
def parse_marker ( cls , line ) : """Returns a pair ( prepend , leader ) iff the line has a valid leader ."""
match_obj = cls . pattern . match ( line ) if match_obj is None : return None # no valid leader leader = match_obj . group ( 1 ) content = match_obj . group ( 0 ) . replace ( leader + '\t' , leader + ' ' , 1 ) # reassign prepend and leader prepend = len ( content ) if prepend == len ( line . rstrip ( '\n' ) )...
def send_pgroup_snapshot ( self , source , ** kwargs ) : """Send an existing pgroup snapshot to target ( s ) : param source : Name of pgroup snapshot to send . : type source : str : param \ * \ * kwargs : See the REST API Guide on your array for the documentation on the request : * * POST pgroup * * : t...
data = { "name" : [ source ] , "action" : "send" } data . update ( kwargs ) return self . _request ( "POST" , "pgroup" , data )
def committed ( self , partition ) : """Get the last committed offset for the given partition . This offset will be used as the position for the consumer in the event of a failure . This call may block to do a remote call if the partition in question isn ' t assigned to this consumer or if the consumer hasn...
assert self . config [ 'api_version' ] >= ( 0 , 8 , 1 ) , 'Requires >= Kafka 0.8.1' assert self . config [ 'group_id' ] is not None , 'Requires group_id' if not isinstance ( partition , TopicPartition ) : raise TypeError ( 'partition must be a TopicPartition namedtuple' ) if self . _subscription . is_assigned ( par...
def inversion ( origin = ( 0 , 0 , 0 ) ) : """Inversion symmetry operation about axis . Args : origin ( 3x1 array ) : Origin of the inversion operation . Defaults to [ 0 , 0 , 0 ] . Returns : SymmOp representing an inversion operation about the origin ."""
mat = - np . eye ( 4 ) mat [ 3 , 3 ] = 1 mat [ 0 : 3 , 3 ] = 2 * np . array ( origin ) return SymmOp ( mat )
def _lal_spectrum ( timeseries , segmentlength , noverlap = None , method = 'welch' , window = None , plan = None ) : """Generate a PSD ` FrequencySeries ` using | lal | _ Parameters timeseries : ` ~ gwpy . timeseries . TimeSeries ` input ` TimeSeries ` data . segmentlength : ` int ` number of samples in ...
import lal from . . . utils . lal import find_typed_function # default to 50 % overlap if noverlap is None : noverlap = int ( segmentlength // 2 ) stride = segmentlength - noverlap # get window if window is None : window = generate_window ( segmentlength , dtype = timeseries . dtype ) # get FFT plan if plan is ...
def run_analysis ( args ) : """Builds an analysis files for training ."""
# Read the schema and input feature types schema_list = json . loads ( file_io . read_file_to_string ( args . schema_file ) ) run_numerical_categorical_analysis ( args , schema_list ) # Also save a copy of the schema in the output folder . file_io . copy ( args . schema_file , os . path . join ( args . output_dir , SCH...
def pull ( self , bookName = None , sheetName = None ) : """pull data into this OR . SHEET from a real book / sheet in Origin"""
# tons of validation if bookName is None and self . bookName : bookName = self . bookName if sheetName is None and self . sheetName : sheetName = self . sheetName if bookName is None : bookName = OR . activeBook ( ) if bookName and sheetName is None : sheetName = OR . activeSheet ( ) if not bookName or ...
def get_chron_data ( temp_sheet , row , total_vars ) : """Capture all data in for a specific chron data row ( for csv output ) : param obj temp _ sheet : : param int row : : param int total _ vars : : return list : data _ row"""
data_row = [ ] missing_val_list = [ 'none' , 'na' , '' , '-' ] for i in range ( 0 , total_vars ) : cell = temp_sheet . cell_value ( row , i ) if isinstance ( cell , str ) : cell = cell . lower ( ) if cell in missing_val_list : cell = 'nan' data_row . append ( cell ) return data_row
def apply_boundary_conditions ( self , ** params ) : """Applies each distributions ' boundary conditions to the given list of parameters , returning a new list with the conditions applied . Parameters * * params : Keyword arguments should give the parameters to apply the conditions to . Returns dict ...
for dist in self . distributions : params . update ( dist . apply_boundary_conditions ( ** params ) ) return params
def save_mat ( ts , filename ) : """save a Timeseries to a MATLAB . mat file Args : ts ( Timeseries ) : the timeseries to save filename ( str ) : . mat filename to save to"""
import scipy . io as sio tspan = ts . tspan fs = ( 1.0 * len ( tspan ) - 1 ) / ( tspan [ - 1 ] - tspan [ 0 ] ) mat_dict = { 'data' : np . asarray ( ts ) , 'fs' : fs , 'labels' : ts . labels [ 1 ] } sio . savemat ( filename , mat_dict , do_compression = True ) return
def get_plugin_actions ( self ) : """Return a list of actions related to plugin"""
quit_action = create_action ( self , _ ( "&Quit" ) , icon = ima . icon ( 'exit' ) , tip = _ ( "Quit" ) , triggered = self . quit ) self . register_shortcut ( quit_action , "_" , "Quit" , "Ctrl+Q" ) run_action = create_action ( self , _ ( "&Run..." ) , None , ima . icon ( 'run_small' ) , _ ( "Run a Python script" ) , tr...
def publish_price_feed ( self , symbol , settlement_price , cer = None , mssr = 110 , mcr = 200 , account = None ) : """Publish a price feed for a market - pegged asset : param str symbol : Symbol of the asset to publish feed for : param bitshares . price . Price settlement _ price : Price for settlement : pa...
assert mcr > 100 assert mssr > 100 assert isinstance ( settlement_price , Price ) , "settlement_price needs to be instance of `bitshares.price.Price`!" assert cer is None or isinstance ( cer , Price ) , "cer needs to be instance of `bitshares.price.Price`!" if not account : if "default_account" in self . config : ...
def class_wise_accuracy ( self , event_label , factor = 0.5 ) : """Class - wise accuracy metrics ( sensitivity , specificity , accuracy , and balanced _ accuracy ) Returns dict results in a dictionary format"""
sensitivity = metric . sensitivity ( Ntp = self . class_wise [ event_label ] [ 'Ntp' ] , Nfn = self . class_wise [ event_label ] [ 'Nfn' ] ) specificity = metric . specificity ( Ntn = self . class_wise [ event_label ] [ 'Ntn' ] , Nfp = self . class_wise [ event_label ] [ 'Nfp' ] ) balanced_accuracy = metric . balanced_...
def predict ( self , data ) : """Predict a new data set based on an estimated model . Parameters data : pandas . DataFrame Data to use for prediction . Must contain all the columns referenced by the right - hand side of the ` model _ expression ` . Returns result : pandas . Series Predicted values as ...
self . assert_fitted ( ) with log_start_finish ( 'predicting model {}' . format ( self . name ) , logger ) : return predict ( data , self . predict_filters , self . model_fit , self . ytransform )
def load ( self , walkthrough ) : """Loads the XML text for a new walkthrough . : param walkthrough | < XWalkthrough > | | < str > | | < xml . etree . ElementTree . Element >"""
if type ( walkthrough ) in ( str , unicode ) : walkthrough = XWalkthrough . load ( walkthrough ) self . setUpdatesEnabled ( False ) self . clear ( ) for slide in walkthrough . slides ( ) : self . addSlide ( slide ) self . setUpdatesEnabled ( True ) self . updateUi ( )
def fill_gaps ( lat , lon , sla , mask , remove_edges = False ) : """# FILL _ GAPS # @ summary : This function allow interpolating data in gaps , depending on gap size . Data must be regularly gridded # @ param lat { type : numeric } : latitude # @ param lon { type : numeric } : longitude # @ param sla { ty...
dst = calcul_distance ( lat , lon ) # Find gaps in data dx = dst [ 1 : ] - dst [ : - 1 ] mn_dx = np . median ( dx ) nx = len ( sla ) flag = ~ mask # Get filled bins indices outsla = sla . copy ( ) outlon = lon . copy ( ) outlat = lat . copy ( ) outind = np . arange ( nx ) # Replace missing data on edges by the latest v...
def on_use_runtime_value_toggled ( self , widget , path ) : """Try to set the use runtime value flag to the newly entered one"""
try : data_port_id = self . list_store [ path ] [ self . ID_STORAGE_ID ] self . toggle_runtime_value_usage ( data_port_id ) except TypeError as e : logger . exception ( "Error while trying to change the use_runtime_value flag" )
def _parse_command_line_arguments ( ) : """Transform vispy specific command line args to vispy config . Put into a function so that any variables dont leak in the vispy namespace ."""
global config # Get command line args for vispy argnames = [ 'vispy-backend=' , 'vispy-gl-debug' , 'vispy-glir-file=' , 'vispy-log=' , 'vispy-help' , 'vispy-profile=' , 'vispy-cprofile' , 'vispy-dpi=' , 'vispy-audit-tests' ] try : opts , args = getopt . getopt ( sys . argv [ 1 : ] , '' , argnames ) except getopt . ...
def _RawGlobPathSpecWithNumericSchema ( file_system , parent_path_spec , segment_format , location , segment_number ) : """Globs for path specifications according to a numeric naming schema . Args : file _ system ( FileSystem ) : file system . parent _ path _ spec ( PathSpec ) : parent path specification . ...
segment_files = [ ] while True : segment_location = segment_format . format ( location , segment_number ) # Note that we don ' t want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise . kwargs = path_spec_factor...