signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def stop ( self ) : """Stop the service ."""
try : sh . systemctl . stop ( self . name ) except sh . ErrorReturnCode_5 : self . logger . debug ( 'Service not running.' )
def from_json ( cls , stream , json_data ) : """Create a new DataPoint object from device cloud JSON data : param DataStream stream : The : class : ` ~ DataStream ` out of which this data is coming : param dict json _ data : Deserialized JSON data from Device Cloud about this device : raises ValueError : if t...
type_converter = _get_decoder_method ( stream . get_data_type ( ) ) data = type_converter ( json_data . get ( "data" ) ) return cls ( # these are actually properties of the stream , not the data point stream_id = stream . get_stream_id ( ) , data_type = stream . get_data_type ( ) , units = stream . get_units ( ) , # an...
def print_status ( self ) : """Provide a snapshot of the current status ."""
s = [ ] s . append ( '=== State Machines: ===\n' ) for stm_id in Driver . _stms_by_id : stm = Driver . _stms_by_id [ stm_id ] s . append ( ' - {} in state {}\n' . format ( stm . id , stm . state ) ) s . append ( '=== Events in Queue: ===\n' ) for event in self . _event_queue . queue : if event is not Non...
def match_subselectors ( self , el , selectors ) : """Match selectors ."""
match = True for sel in selectors : if not self . match_selectors ( el , sel ) : match = False return match
def queue_draw_item ( self , * items ) : """Extends the base class method to allow Ports to be passed as item : param items : Items that are to be redrawn"""
gaphas_items = [ ] for item in items : if isinstance ( item , Element ) : gaphas_items . append ( item ) else : try : gaphas_items . append ( item . parent ) except AttributeError : pass super ( ExtendedGtkView , self ) . queue_draw_item ( * gaphas_items )
def add_task_attribute ( self , name , ** attrs ) : """Add a new Task attribute and return a : class : ` TaskAttribute ` object . : param name : name of the : class : ` TaskAttribute ` : param attrs : optional attributes for : class : ` TaskAttribute `"""
return TaskAttributes ( self . requester ) . create ( self . id , name , ** attrs )
def get_bin_and_lib ( self , x64 = False , native = False ) : """Get bin and lib ."""
if x64 : msvc = self . bin64 paths = self . lib64 else : msvc = self . bin32 paths = self . lib if native : arch = 'x64' if x64 else 'x86' paths += self . sdk . get_lib ( arch , native = True ) else : attr = 'lib64' if x64 else 'lib' paths += getattr ( self . sdk , attr ) return msvc , p...
def artifact2destination ( self , artifact , descriptor ) : """Translate an artifact into a receiver location : param artifact : The Base64 encoded SAML artifact : return :"""
_art = base64 . b64decode ( artifact ) assert _art [ : 2 ] == ARTIFACT_TYPECODE try : endpoint_index = str ( int ( _art [ 2 : 4 ] ) ) except ValueError : endpoint_index = str ( int ( hexlify ( _art [ 2 : 4 ] ) ) ) entity = self . sourceid [ _art [ 4 : 24 ] ] destination = None for desc in entity [ "%s_descripto...
def add_rule ( self , name , callable_ ) : """Makes rule ' name ' available to all subsequently loaded Jamfiles . Calling that rule wil relay to ' callable ' ."""
assert isinstance ( name , basestring ) assert callable ( callable_ ) self . project_rules_ . add_rule ( name , callable_ )
def get_report ( self , linewise = False , no_lines = False ) : """Returns a string describing all the errors collected so far ( the report ) . The first flag determines the type of report . The second flag is ignored if the first is set to True ."""
if linewise : return self . _get_linewise_report ( ) else : return self . _get_report ( not no_lines )
async def _create_proxy_connection ( self , req , * args , ** kwargs ) : """args , kwargs can contain different elements ( traces , timeout , . . . ) depending on aiohttp version"""
if req . proxy . scheme == 'http' : return await super ( ) . _create_proxy_connection ( req , * args , ** kwargs ) else : return await self . _create_socks_connection ( req = req )
def setup_regex ( self ) : """Sets up the patterns and regex objects for parsing the docstrings ."""
# Regex for grabbing out valid XML tags that represent known docstrings that we can work with . self . keywords = [ "summary" , "usage" , "errors" , "member" , "group" , "local" , "comments" , "parameter" ] # Regex for extracting the contents of docstrings minus the ! ! and any leading spaces . self . _RX_DOCS = "^\s*!...
def metrics ( self ) -> list : """List of metrics to track for this learning process"""
return [ AveragingNamedMetric ( "policy_loss" ) , AveragingNamedMetric ( "value_loss" ) , AveragingNamedMetric ( "policy_entropy" ) , AveragingNamedMetric ( "approx_kl_divergence" ) , AveragingNamedMetric ( "clip_fraction" ) , AveragingNamedMetric ( "grad_norm" ) , AveragingNamedMetric ( "advantage_norm" ) , AveragingN...
def resource_property ( klass , name , ** kwargs ) : """Builds a resource object property ."""
klass . PROPERTIES [ name ] = kwargs def getter ( self ) : return getattr ( self , '_%s' % name , kwargs . get ( 'default' , None ) ) if kwargs . get ( 'readonly' , False ) : setattr ( klass , name , property ( getter ) ) else : def setter ( self , value ) : setattr ( self , '_%s' % name , value ) ...
def build_contact ( request , slug = "" ) : """Builds appropriate contact form based on options set in the contact _ form controller ."""
controller = get_object_or_404 ( ContactFormController , slug = slug ) site = Site . objects . get_current ( ) UserModel = get_user_model ( ) user = request . user form = ContactForm ( request . POST or None , request . FILES or None , controller = controller ) # if we know , fill in the user name and email if user . i...
def _read_para_ack_data ( self , code , cbit , clen , * , desc , length , version ) : """Read HIP ACK _ DATA parameter . Structure of HIP ACK _ DATA parameter [ RFC 6078 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | Type | Length | | Acked Sequence number / Octets Bits Na...
if clen % 4 != 0 : raise ProtocolError ( f'HIPv{version}: [Parano {code}] invalid format' ) _ackn = list ( ) for _ in range ( clen // 4 ) : _ackn . append ( self . _read_unpack ( 4 ) ) ack_data = dict ( type = desc , critical = cbit , length = clen , ack = tuple ( _ackn ) , ) return ack_data
def get_all_completed_tasks ( self , api_token , ** kwargs ) : """Return a list of a user ' s completed tasks . . . warning : : Requires Todoist premium . : param api _ token : The user ' s login api _ token . : type api _ token : str : param project _ id : Filter the tasks by project . : type project _ i...
params = { 'token' : api_token } return self . _get ( 'get_all_completed_items' , params , ** kwargs )
def lookup_subclass ( cls , d ) : """Look up a class based on a serialized dictionary containing a typeid Args : d ( dict ) : Dictionary with key " typeid " Returns : Serializable subclass"""
try : typeid = d [ "typeid" ] except KeyError : raise FieldError ( "typeid not present in keys %s" % list ( d ) ) subclass = cls . _subcls_lookup . get ( typeid , None ) if not subclass : raise FieldError ( "'%s' not a valid typeid" % typeid ) else : return subclass
def _handle_if_block ( tokens , tokens_len , body_index , function_call ) : """Special handler for if - blocks . If blocks are special because they can have multiple bodies and have multiple terminating keywords for each of those sub - bodies"""
# First handle the if statement and body next_index , if_statement = _IF_BLOCK_IF_HANDLER ( tokens , tokens_len , body_index , function_call ) elseif_statements = [ ] else_statement = None footer = None # Keep going until we hit endif while True : # Back up a bit until we found out what terminated the if statement # bo...
def subscribe ( self , sr ) : """Login required . Send POST to subscribe to a subreddit . If ` ` sr ` ` is the name of the subreddit , a GET request is sent to retrieve the full id of the subreddit , which is necessary for this API call . Returns True or raises : class : ` exceptions . UnexpectedResponse ` if non -...
if not sr . startswith ( 't5_' ) : sr = self . subreddit ( sr ) . name data = dict ( action = 'sub' , sr = sr ) j = self . post ( 'api' , 'subscribe' , data = data ) return assert_truthy ( j )
def set_type ( self , value ) : """Setter for type attribute"""
if value not in self . types_available : log = "Sources field 'type' should be in one of %s" % ( self . types_available ) raise MalFormattedSource ( log ) self . _type = value
def auto_convert_cell_no_flags ( cell , units = None , parens_as_neg = True ) : '''Performs a first step conversion of the cell to check it ' s type or try to convert if a valid conversion exists . This version of conversion doesn ' t flag changes nor store cell units . Args : units : The dictionary holde...
units = units if units != None else { } return auto_convert_cell ( flagable = Flagable ( ) , cell = cell , position = None , worksheet = 0 , flags = { } , units = units , parens_as_neg = parens_as_neg )
def handle_scene ( self , obj ) : """Handle a scene event . This function applies a blocking wait at the start of a scene . : param obj : A : py : class : ` ~ turberfield . dialogue . model . Model . Shot ` object . : return : The supplied object ."""
print ( "{t.dim}{scene}{t.normal}" . format ( scene = obj . scene . capitalize ( ) , t = self . terminal ) , end = "\n" * 3 , file = self . terminal . stream ) time . sleep ( self . pause ) return obj
def tag ( words : List [ str ] , corpus : str = "pud" ) -> List [ Tuple [ str , str ] ] : """รับค่าเป็น ' ' list ' ' คืนค่าเป็น ' ' list ' ' เช่น [ ( ' คํา ' , ' ชนิดคํา ' ) , ( ' คํา ' , ' ชนิดคํา ' ) , . . . ]"""
if not words : return [ ] if corpus == "orchid" : tagger = _ORCHID_TAGGER i = 0 while i < len ( words ) : if words [ i ] == " " : words [ i ] = "<space>" elif words [ i ] == "+" : words [ i ] = "<plus>" elif words [ i ] == "-" : words [ i ] = "...
def runExperimentPool ( numObjects , numLocations , numFeatures , numColumns , networkType = [ "MultipleL4L2Columns" ] , longDistanceConnectionsRange = [ 0.0 ] , numWorkers = 7 , nTrials = 1 , pointRange = 1 , numPoints = 10 , numInferenceRpts = 1 , l2Params = None , l4Params = None , resultsName = "convergence_results...
# Create function arguments for every possibility args = [ ] for c in reversed ( numColumns ) : for o in reversed ( numObjects ) : for l in numLocations : for f in numFeatures : for n in networkType : for p in longDistanceConnectionsRange : ...
def __getPluginInfo ( self , plugin , package_abspath , package_name ) : """Organize plugin information . : returns : dict : plugin info"""
if not isValidSemver ( plugin . __version__ ) : raise VersionError ( "The plugin version does not conform to the standard named %s" % package_name ) try : url = plugin . __url__ except AttributeError : url = None try : license = plugin . __license__ except AttributeError : license = None try : l...
def build_kernel_to_data ( self , Y , knn = None , bandwidth = None , bandwidth_scale = None ) : """Build transition matrix from new data to the graph Creates a transition matrix such that ` Y ` can be approximated by a linear combination of landmarks . Any transformation of the landmarks can be trivially app...
if knn is None : knn = self . knn if bandwidth is None : bandwidth = self . bandwidth if bandwidth_scale is None : bandwidth_scale = self . bandwidth_scale if self . precomputed is not None : raise ValueError ( "Cannot extend kernel on precomputed graph" ) else : tasklogger . log_start ( "affinities...
def _build_toc_node ( docname , anchor = "anchor" , text = "test text" , bullet = False ) : """Create the node structure that Sphinx expects for TOC Tree entries . The ` ` bullet ` ` argument wraps it in a ` ` nodes . bullet _ list ` ` , which is how you nest TOC Tree entries ."""
reference = nodes . reference ( "" , "" , internal = True , refuri = docname , anchorname = "#" + anchor , * [ nodes . Text ( text , text ) ] ) para = addnodes . compact_paragraph ( "" , "" , reference ) ret_list = nodes . list_item ( "" , para ) return nodes . bullet_list ( "" , ret_list ) if bullet else ret_list
def merge_config ( original : Optional [ Dict [ str , Any ] ] , overrides : Optional [ Dict [ str , Any ] ] ) -> Dict [ str , Any ] : """Return a copy of the ` ` original ` ` configuration dictionary , with overrides from ` ` overrides ` ` applied . This similar to what : meth : ` dict . update ` does , but whe...
assert check_argument_types ( ) copied = original . copy ( ) if original else { } if overrides : for key , value in overrides . items ( ) : if '.' in key : key , rest = key . split ( '.' , 1 ) value = { rest : value } orig_value = copied . get ( key ) if isinstance ( ...
def __create_proper_names_lexicon ( self , docs ) : """Moodustab dokumendikollektsiooni põhjal pärisnimede sagedussõnastiku ( mis kirjeldab , mitu korda iga pärisnimelemma esines ) ;"""
lemmaFreq = dict ( ) for doc in docs : for word in doc [ WORDS ] : # 1 ) Leiame k6ik s6naga seotud unikaalsed pärisnimelemmad # ( kui neid on ) uniqLemmas = set ( ) for analysis in word [ ANALYSIS ] : if analysis [ POSTAG ] == 'H' : uniqLemmas . add ( analysis [ ROOT...
def getrange ( self , key , start , end , * , encoding = _NOTSET ) : """Get a substring of the string stored at a key . : raises TypeError : if start or end is not int"""
if not isinstance ( start , int ) : raise TypeError ( "start argument must be int" ) if not isinstance ( end , int ) : raise TypeError ( "end argument must be int" ) return self . execute ( b'GETRANGE' , key , start , end , encoding = encoding )
def _sampler_n_samples ( self , n_samples ) : """Return ( sampler , n _ samplers ) tuples"""
sampler_indices = self . rng_ . choice ( range ( len ( self . samplers ) ) , size = n_samples , replace = True , p = self . weights ) return [ ( self . samplers [ idx ] , freq ) for idx , freq in itemfreq ( sampler_indices ) ]
def fetch_parent_dir ( filepath , n = 1 ) : '''Returns a parent directory , n places above the input filepath . Equivalent to something like : ' / home / user / dir ' . split ( ' / ' ) [ - 2 ] if n = 2.'''
filepath = os . path . realpath ( filepath ) for i in range ( n ) : filepath = os . path . dirname ( filepath ) return os . path . basename ( filepath )
def createSQL ( self , sql , args = ( ) ) : """For use with auto - committing statements such as CREATE TABLE or CREATE INDEX ."""
before = time . time ( ) self . _execSQL ( sql , args ) after = time . time ( ) if after - before > 2.0 : log . msg ( 'Extremely long CREATE: %s' % ( after - before , ) ) log . msg ( sql )
def group_re ( self ) : '''Return a regexp pattern with named groups'''
out = '' for token , data in self . tokens ( ) : if token == 'TXT' : out += re . escape ( data ) elif token == 'VAR' : out += '(?P<%s>%s)' % ( data [ 1 ] , data [ 0 ] ) elif token == 'ANON' : out += '(?:%s)' % data return out
def add_artifact ( self , filename , name = None , metadata = None , content_type = None , ) : """Add a file as an artifact . In Sacred terminology an artifact is a file produced by the experiment run . In case of a MongoObserver that means storing the file in the database . This function can only be called...
assert self . current_run is not None , "Can only be called during a run." self . current_run . add_artifact ( filename , name , metadata , content_type )
def assert_valid_path ( path ) : """Checks if a path is a correct format that Marathon expects . Raises ValueError if not valid . : param str path : The app id . : rtype : str"""
if path is None : return # As seen in : # https : / / github . com / mesosphere / marathon / blob / 0c11661ca2f259f8a903d114ef79023649a6f04b / src / main / scala / mesosphere / marathon / state / PathId . scala # L71 for id in filter ( None , path . strip ( '/' ) . split ( '/' ) ) : if not ID_PATTERN . match ( ...
def _get_right_line_color ( self ) : """Returns color rgb tuple of right line"""
color = self . cell_attributes [ self . key ] [ "bordercolor_right" ] return tuple ( c / 255.0 for c in color_pack2rgb ( color ) )
def spawn_process ( self , target , * args ) : """: type target : function or class"""
p = Process ( target = target , args = args ) p . daemon = True if target == worker : p . daemon = Conf . DAEMONIZE_WORKERS p . timer = args [ 2 ] self . pool . append ( p ) p . start ( ) return p
def stop ( self ) : """Stop tracing . Reinstalls the : ref : ` hunter . Tracer . previous ` tracer ."""
if self . _handler is not None : sys . settrace ( self . _previous ) self . _handler = self . _previous = None if self . threading_support is None or self . threading_support : threading . settrace ( self . _threading_previous ) self . _threading_previous = None
def _is_in_set ( self , inpt , metadata ) : """checks if the input is in the metadata ' s * _ set list"""
# makes an assumption there is only one _ set in the metadata dict get_set_methods = [ m for m in dir ( metadata ) if 'get_' in m and '_set' in m ] set_results = None for m in get_set_methods : try : set_results = getattr ( metadata , m ) ( ) break except errors . IllegalState : pass if ...
def render_response ( self ) : """Render as a string formatted for HTTP response headers ( detailed ' Set - Cookie : ' style ) ."""
# Use whatever renderers are defined for name and value . # ( . attributes ( ) is responsible for all other rendering . ) name , value = self . name , self . value renderer = self . attribute_renderers . get ( 'name' , None ) if renderer : name = renderer ( name ) renderer = self . attribute_renderers . get ( 'valu...
def _mkpart ( root , fs_format , fs_opts , mount_dir ) : '''Make a partition , and make it bootable . . versionadded : : Beryllium'''
__salt__ [ 'partition.mklabel' ] ( root , 'msdos' ) loop1 = __salt__ [ 'cmd.run' ] ( 'losetup -f' ) log . debug ( 'First loop device is %s' , loop1 ) __salt__ [ 'cmd.run' ] ( 'losetup {0} {1}' . format ( loop1 , root ) ) part_info = __salt__ [ 'partition.list' ] ( loop1 ) start = six . text_type ( 2048 * 2048 ) + 'B' e...
def _convert_coords_to_abmn_X ( data , ** kwargs ) : """The syscal only stores positions for the electrodes . Yet , we need to infer electrode numbers for ( a , b , m , n ) by means of some heuristics . This heuristic uses the x - coordinates to infer an electrode spacing ( y / z coordinates are ignored ) . W...
assert data . shape [ 1 ] == 4 , 'data variable must only contain four columns' x0 = kwargs . get ( 'x0' , data . min ( ) . min ( ) ) electrode_spacing = kwargs . get ( 'spacing' , None ) # try to determine from the data itself if electrode_spacing is None : electrode_positions = data . values electrode_spacing...
def emitDataChanged ( self , treeItem ) : # TODO : move to BaseTreeItem ? """Emits the data changed for the model indices ( all columns ) for this treeItem"""
indexLeft , indexRight = self . indexTupleFromItem ( treeItem ) checkItem = self . getItem ( indexLeft ) assert checkItem is treeItem , "{} != {}" . format ( checkItem , treeItem ) # TODO : remove self . dataChanged . emit ( indexLeft , indexRight )
def get_record ( self , record_num ) : """Get a Record by record number . @ type record _ num : int @ param record _ num : The record number of the the record to fetch . @ rtype Record or None @ return The record request by record number , or None if the record is not found ."""
for chunk in self . chunks ( ) : first_record = chunk . log_first_record_number ( ) last_record = chunk . log_last_record_number ( ) if not ( first_record <= record_num <= last_record ) : continue for record in chunk . records ( ) : if record . record_num ( ) == record_num : ...
def _match_metric ( self , metric ) : """matches the metric path , if the metrics are empty , it shorts to True"""
if len ( self . _compiled_filters ) == 0 : return True for ( collector , filter_regex ) in self . _compiled_filters : if collector != metric . getCollectorPath ( ) : continue if filter_regex . match ( metric . getMetricPath ( ) ) : return True return False
def event_return ( events ) : '''Return event to CouchDB server Requires that configuration be enabled via ' event _ return ' option in master config . Example : event _ return : - couchdb'''
log . debug ( 'events data is: %s' , events ) options = _get_options ( ) # Check to see if the database exists . _response = _request ( "GET" , options [ 'url' ] + "_all_dbs" ) event_db = '{}-events' . format ( options [ 'db' ] ) if event_db not in _response : # Make a PUT request to create the database . log . inf...
def _validate_response ( self , response , message , exclude_code = None ) : # pylint : disable = no - self - use """validate an api server response : param dict response : server response to check : param str message : error message to raise : param int exclude _ code : error codes to exclude from errorhandl...
if 'code' in response and response [ 'code' ] >= 2000 : if exclude_code is not None and response [ 'code' ] == exclude_code : return raise Exception ( "{0}: {1} ({2})" . format ( message , response [ 'msg' ] , response [ 'code' ] ) )
def execute_notebook ( nb_path , pkg_dir , dataframes , write_notebook = False , env = None ) : """Execute a notebook after adding the prolog and epilog . Can also add % mt _ materialize magics to write dataframes to files : param nb _ path : path to a notebook . : param pkg _ dir : Directory to which datafra...
import nbformat from metapack . jupyter . preprocessors import AddEpilog , AddProlog from metapack . jupyter . exporters import ExecutePreprocessor , Config from os . path import dirname , join , splitext , basename from nbconvert . preprocessors . execute import CellExecutionError with open ( nb_path , encoding = 'utf...
def get_item_data ( self , session , item , byte_range = None ) : """Return a file pointer to the item file . Assumes ` item . file _ name ` points to the file on disk ."""
# Parse byte range if byte_range is not None : begin , end = parse_byte_range ( byte_range , max_byte = item . file_size ) else : begin , end = 0 , item . file_size # Open the file fp = open ( item . file_name , "rb+" ) if not begin : return fp , item . file_type , item . file_size elif begin and not end : ...
def from_response ( raw_response ) : """The Yelp Fusion API returns error messages with a json body like : ' error ' : { ' code ' : ' ALL _ CAPS _ CODE ' , ' description ' : ' Human readable description . ' Some errors may have additional fields . For example , a validation error : ' error ' : { ' c...
json_response = raw_response . json ( ) error_info = json_response [ "error" ] code = error_info [ "code" ] try : error_cls = _error_map [ code ] except KeyError : raise NotImplementedError ( "Unknown error code '{}' returned in Yelp API response. " "This code may have been newly added. Please ensure you are " ...
def forward_word_extend_selection ( self , e ) : u"""Move forward to the end of the next word . Words are composed of letters and digits ."""
self . l_buffer . forward_word_extend_selection ( self . argument_reset ) self . finalize ( )
def _GetDirectory ( self ) : """Retrieves a directory . Returns : VShadowDirectory : a directory None if not available ."""
if self . entry_type != definitions . FILE_ENTRY_TYPE_DIRECTORY : return None return VShadowDirectory ( self . _file_system , self . path_spec )
def set_scope ( self , http_method , scope ) : """Set a scope condition for the resource for a http _ method Parameters : * * * http _ method ( str ) : * * HTTP method like GET , POST , PUT , DELETE * * * scope ( str , list ) : * * the scope of access control as str if single , or as a list of strings if mult...
for con in self . conditions : if http_method in con [ 'httpMethods' ] : if isinstance ( scope , list ) : con [ 'scopes' ] = scope elif isinstance ( scope , str ) or isinstance ( scope , unicode ) : con [ 'scopes' ] . append ( scope ) return # If not present , then cr...
def GetFeedMapping ( client , feed , placeholder_type ) : """Gets the Feed Mapping for a given Feed . Args : client : an AdWordsClient instance . feed : the Feed we are retrieving the Feed Mapping for . placeholder _ type : the Placeholder Type we are looking for . Returns : A dictionary containing the ...
feed_mapping_service = client . GetService ( 'FeedMappingService' , 'v201809' ) attribute_mappings = { } more_pages = True selector = { 'fields' : [ 'FeedMappingId' , 'AttributeFieldMappings' ] , 'predicates' : [ { 'field' : 'FeedId' , 'operator' : 'EQUALS' , 'values' : [ feed [ 'id' ] ] } , { 'field' : 'PlaceholderTyp...
def print_extended_help ( ) : """print a detailed help message : return :"""
w = textwrap . TextWrapper ( ) w . expand_tabs = False w . width = 85 w . initial_indent = '\t' w . subsequent_indent = '\t ' print ( '' ) print ( textwrap . fill ( "<postanalyze> Complete parameter list:" , initial_indent = '' ) ) print ( '' ) cmd = "--input : (required) csv file to split into training and test sets"...
def with_inverse ( points , noise ) : """Smooths a set of points It smooths them twice , once in given order , another one in the reverse order . The the first half of the results will be taken from the reverse order and the second half from the normal order . Args : points ( : obj : ` list ` of : obj : `...
# noise _ sample = 20 n_points = len ( points ) / 2 break_point = n_points points_part = copy . deepcopy ( points ) points_part = list ( reversed ( points_part ) ) part = kalman_filter ( points_part , noise ) total = kalman_filter ( points , noise ) result = list ( reversed ( part ) ) [ : break_point ] + total [ break_...
def simxGetBooleanParameter ( clientID , paramIdentifier , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
paramValue = ct . c_ubyte ( ) return c_GetBooleanParameter ( clientID , paramIdentifier , ct . byref ( paramValue ) , operationMode ) , bool ( paramValue . value != 0 )
def plot_predict ( self , h = 5 , past_values = 20 , intervals = True , ** kwargs ) : """Makes forecast with the estimated model Parameters h : int ( default : 5) How many steps ahead would you like to forecast ? past _ values : int ( default : 20) How many past observations to show on the forecast graph ...
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : # Retrieve data , dates and ( transformed ) latent variables scale , shape , skewness = scale , ...
def is_json ( string ) : """Check if a string is a valid json . : param string : String to check . : type string : str : return : True if json , false otherwise : rtype : bool"""
if not is_full_string ( string ) : return False if bool ( JSON_WRAPPER_RE . search ( string ) ) : try : return isinstance ( json . loads ( string ) , dict ) except ( TypeError , ValueError , OverflowError ) : return False return False
def get_weather_code ( self , ip ) : '''Get weather _ code'''
rec = self . get_all ( ip ) return rec and rec . weather_code
def dumps ( value , encoding = None ) : """dumps ( object , encoding = None ) - > string This function dumps a python object as a tnetstring ."""
# This uses a deque to collect output fragments in reverse order , # then joins them together at the end . It ' s measurably faster # than creating all the intermediate strings . # If you ' re reading this to get a handle on the tnetstring format , # consider the _ gdumps ( ) function instead ; it ' s a standard top - ...
def set_maintainer ( self , maintainer ) : # type : ( Union [ hdx . data . user . User , Dict , str ] ) - > None """Set the dataset ' s maintainer . Args : maintainer ( Union [ User , Dict , str ] ) : Either a user id or User metadata from a User object or dictionary . Returns : None"""
if isinstance ( maintainer , hdx . data . user . User ) or isinstance ( maintainer , dict ) : if 'id' not in maintainer : maintainer = hdx . data . user . User . read_from_hdx ( maintainer [ 'name' ] , configuration = self . configuration ) maintainer = maintainer [ 'id' ] elif not isinstance ( maintain...
def install ( pkgs = None , # pylint : disable = R0912 , R0913 , R0914 requirements = None , bin_env = None , use_wheel = False , no_use_wheel = False , log = None , proxy = None , timeout = None , editable = None , find_links = None , index_url = None , extra_index_url = None , no_index = False , mirrors = None , buil...
cmd = _get_pip_bin ( bin_env ) cmd . append ( 'install' ) cleanup_requirements , error = _process_requirements ( requirements = requirements , cmd = cmd , cwd = cwd , saltenv = saltenv , user = user ) if error : return error cur_version = version ( bin_env ) if use_wheel : min_version = '1.4' max_version = ...
def to_array ( self ) : """Serializes this InlineQueryResultCachedDocument to a dictionary . : return : dictionary representation of this object . : rtype : dict"""
array = super ( InlineQueryResultCachedDocument , self ) . to_array ( ) # ' type ' and ' id ' given by superclass array [ 'title' ] = u ( self . title ) # py2 : type unicode , py3 : type str array [ 'document_file_id' ] = u ( self . document_file_id ) # py2 : type unicode , py3 : type str if self . description is not N...
def join ( self , column_label , other , other_label = None ) : """Creates a new table with the columns of self and other , containing rows for all values of a column that appear in both tables . Args : ` ` column _ label ` ` ( ` ` str ` ` ) : label of column in self that is used to join rows of ` ` other `...
if self . num_rows == 0 or other . num_rows == 0 : return None if not other_label : other_label = column_label self_rows = self . index_by ( column_label ) other_rows = other . index_by ( other_label ) # Gather joined rows from self _ rows that have join values in other _ rows joined_rows = [ ] for v , rows in ...
def cancel_download_task ( self , task_id , expires = None , ** kwargs ) : """取消离线下载任务 . : param task _ id : 要取消的任务ID号 。 : type task _ id : str : param expires : 请求失效时间 , 如果有 , 则会校验 。 : type expires : int : return : Response 对象"""
data = { 'expires' : expires , 'task_id' : task_id , } return self . _request ( 'services/cloud_dl' , 'cancle_task' , data = data , ** kwargs )
def get_reaction_values ( self , reaction_id ) : """Return stoichiometric values of reaction as a dictionary"""
if reaction_id not in self . _reaction_set : raise ValueError ( 'Unknown reaction: {}' . format ( repr ( reaction_id ) ) ) return self . _database . get_reaction_values ( reaction_id )
async def update_ports ( self , ports , ovsdb_ports ) : """Called from main module to update port information"""
new_port_names = dict ( ( p [ 'name' ] , _to32bitport ( p [ 'ofport' ] ) ) for p in ovsdb_ports ) new_port_ids = dict ( ( p [ 'id' ] , _to32bitport ( p [ 'ofport' ] ) ) for p in ovsdb_ports if p [ 'id' ] ) if new_port_names == self . _portnames and new_port_ids == self . _portids : return self . _portnames . clear ...
def optimize ( self , graph ) : """Build a dictionary mapping each pair of nodes to a number ( the distance between them ) . @ type graph : graph @ param graph : Graph ."""
for start in graph . nodes ( ) : for end in graph . nodes ( ) : for each in graph . node_attributes ( start ) : if ( each [ 0 ] == 'position' ) : start_attr = each [ 1 ] break for each in graph . node_attributes ( end ) : if ( each [ 0 ] == 'po...
def ticket_forms_reorder ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / ticket _ forms # reorder - ticket - forms"
api_path = "/api/v2/ticket_forms/reorder.json" return self . call ( api_path , method = "PUT" , data = data , ** kwargs )
def get_build_platform ( ) : """Return this platform ' s string for platform - specific distributions XXX Currently this is the same as ` ` distutils . util . get _ platform ( ) ` ` , but it needs some hacks for Linux and Mac OS X ."""
from sysconfig import get_platform plat = get_platform ( ) if sys . platform == "darwin" and not plat . startswith ( 'macosx-' ) : try : version = _macosx_vers ( ) machine = os . uname ( ) [ 4 ] . replace ( " " , "_" ) return "macosx-%d.%d-%s" % ( int ( version [ 0 ] ) , int ( version [ 1 ] ...
def check_property ( prop , name , ** kwargs ) : """Check and parse a property with either a specific checking function or a generic parser"""
checkers = { 'color' : check_color , 'alpha' : check_alpha , 'size' : check_size , 'thickness' : check_thickness , 'index' : check_index , 'coordinates' : check_coordinates , 'colormap' : check_colormap , 'bins' : check_bins , 'spec' : check_spec } if name in checkers : return checkers [ name ] ( prop , ** kwargs )...
def split ( data : mx . nd . NDArray , num_outputs : int , axis : int = 1 , squeeze_axis : bool = False ) -> List [ mx . nd . NDArray ] : """Version of mxnet . ndarray . split that always returns a list . The original implementation only returns a list if num _ outputs > 1: https : / / mxnet . incubator . apach...
ndarray_or_list = data . split ( num_outputs = num_outputs , axis = axis , squeeze_axis = squeeze_axis ) if num_outputs == 1 : return [ ndarray_or_list ] return ndarray_or_list
def sort_seq_records ( self , seq_records ) : """Checks that SeqExpandedRecords are sorted by gene _ code and then by voucher code . The dashes in taxon names need to be converted to underscores so the dataset will be accepted by Biopython to do format conversions ."""
for seq_record in seq_records : seq_record . voucher_code = seq_record . voucher_code . replace ( "-" , "_" ) unsorted_gene_codes = set ( [ i . gene_code for i in seq_records ] ) sorted_gene_codes = list ( unsorted_gene_codes ) sorted_gene_codes . sort ( key = lambda x : x . lower ( ) ) unsorted_voucher_codes = set...
def get_url_params ( url : str , fragment : bool = False ) -> dict : """Parse URL params"""
parsed_url = urlparse ( url ) if fragment : url_query = parse_qsl ( parsed_url . fragment ) else : url_query = parse_qsl ( parsed_url . query ) return dict ( url_query )
def getElementsByType ( self , type ) : """retrieves all Elements that are of type type @ type type : class @ param type : type of the element"""
foundElements = [ ] for element in self . getAllElementsOfHirarchy ( ) : if isinstance ( element , type ) : foundElements . append ( element ) return foundElements
def get_labs ( format ) : """Gets data from all labs from makeinitaly . foundation ."""
labs = [ ] # Get the first page of data wiki = MediaWiki ( makeinitaly__foundation_api_url ) wiki_response = wiki . call ( { 'action' : 'query' , 'list' : 'categorymembers' , 'cmtitle' : 'Category:Italian_FabLabs' , 'cmlimit' : '500' } ) if "query-continue" in wiki_response : nextpage = wiki_response [ "query-conti...
def tag ( self , name , user , revision = None , message = None , date = None , ** kwargs ) : """Creates and returns a tag for the given ` ` revision ` ` . : param name : name for new tag : param user : full username , i . e . : " Joe Doe < joe . doe @ example . com > " : param revision : changeset id for whi...
if name in self . tags : raise TagAlreadyExistError ( "Tag %s already exists" % name ) changeset = self . get_changeset ( revision ) local = kwargs . setdefault ( 'local' , False ) if message is None : message = "Added tag %s for changeset %s" % ( name , changeset . short_id ) if date is None : date = datet...
def generic_http_header_parser_for ( header_name ) : """A parser factory to extract the request id from an HTTP header : return : A parser that can be used to extract the request id from the current request context : rtype : ( ) - > str | None"""
def parser ( ) : request_id = request . headers . get ( header_name , '' ) . strip ( ) if not request_id : # If the request id is empty return None return None return request_id return parser
def process_auth ( self ) : """Reads and processes SSPI stream . Stream info : http : / / msdn . microsoft . com / en - us / library / dd302844 . aspx"""
r = self . _reader w = self . _writer pdu_size = r . get_smallint ( ) if not self . authentication : raise tds_base . Error ( 'Got unexpected token' ) packet = self . authentication . handle_next ( readall ( r , pdu_size ) ) if packet : w . write ( packet ) w . flush ( )
def accuracy ( input : Tensor , targs : Tensor ) -> Rank0Tensor : "Compute accuracy with ` targs ` when ` input ` is bs * n _ classes ."
n = targs . shape [ 0 ] input = input . argmax ( dim = - 1 ) . view ( n , - 1 ) targs = targs . view ( n , - 1 ) return ( input == targs ) . float ( ) . mean ( )
def connect ( * cmds , ** kwargs ) : """Connects multiple command streams together and yields the final stream . Args : cmds ( list ) : list of commands to pipe together . Each command will be an input to ` ` stream ` ` . stdin ( file like object ) : stream to use as the first command ' s standard input ....
stdin = kwargs . get ( "stdin" ) env = kwargs . get ( "env" , os . environ ) timeout = kwargs . get ( "timeout" ) end = len ( cmds ) - 1 @ contextmanager def inner ( idx , inp ) : with stream ( cmds [ idx ] , stdin = inp , env = env , timeout = timeout ) as s : if idx == end : yield s el...
def _format_with_same_year_and_month ( format_specifier ) : """Return a version of ` format _ specifier ` that renders a date assuming it has the same year and month as another date . Usually this means ommitting the year and month . This can be overridden by specifying a format that has ` _ SAME _ YEAR _ S...
test_format_specifier = format_specifier + "_SAME_YEAR_SAME_MONTH" test_format = get_format ( test_format_specifier , use_l10n = True ) if test_format == test_format_specifier : # this format string didn ' t resolve to anything and may be a raw format . # Use a regex to remove year and month markers instead . no_ye...
def get_jid ( jid ) : '''Return the information returned when the specified job id was executed'''
conn = _get_conn ( ret = None ) cur = conn . cursor ( ) sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = ?''' cur . execute ( sql , ( jid , ) ) data = cur . fetchall ( ) ret = { } if data : for minion , full_ret in data : ret [ minion ] = salt . utils . json . loads ( full_ret ) _close_conn ( conn...
def _parse_timeframe_line ( self , line ) : """Parse timeframe line and return start and end timestamps ."""
tf = self . _validate_timeframe_line ( line ) if not tf : raise MalformedCaptionError ( 'Invalid time format' ) return tf . group ( 1 ) , tf . group ( 2 )
def classifyplot_from_plotfiles ( plot_files , out_csv , outtype = "png" , title = None , size = None ) : """Create a plot from individual summary csv files with classification metrics ."""
dfs = [ pd . read_csv ( x ) for x in plot_files ] samples = [ ] for df in dfs : for sample in df [ "sample" ] . unique ( ) : if sample not in samples : samples . append ( sample ) df = pd . concat ( dfs ) df . to_csv ( out_csv , index = False ) return classifyplot_from_valfile ( out_csv , outtyp...
def check_str_length ( str_to_check , limit = MAX_LENGTH ) : """Check the length of a string . If exceeds limit , then truncate it . : type str _ to _ check : str : param str _ to _ check : String to check . : type limit : int : param limit : The upper limit of the length . : rtype : tuple : returns : T...
str_bytes = str_to_check . encode ( UTF8 ) str_len = len ( str_bytes ) truncated_byte_count = 0 if str_len > limit : truncated_byte_count = str_len - limit str_bytes = str_bytes [ : limit ] result = str ( str_bytes . decode ( UTF8 , errors = 'ignore' ) ) return ( result , truncated_byte_count )
def shrink ( image , apikey ) : """To shrink a PNG image , post the data to the API service . The response is a JSON message . The initial request must be authorized with HTTP Basic authorization . @ param image : PNG image bytes sequence @ param apikey : TinyPNG API key @ param filename : filename of inp...
def _handle_response ( response ) : body = json . loads ( response . read ( ) ) if response . code == TinyPNGResponse . SUCCESS_CODE : body [ 'location' ] = response . headers . getheader ( "Location" ) try : body [ 'bytes' ] = urlopen ( body [ 'location' ] ) . read ( ) excep...
def callback ( self , event ) : """Callback function to spawn a mini - browser when a feature is clicked ."""
artist = event . artist ind = artist . ind limit = 5 browser = True if len ( event . ind ) > limit : print "more than %s genes selected; not spawning browsers" % limit browser = False for i in event . ind : feature = artist . features [ ind [ i ] ] print feature , if browser : self . minibro...
def parse_timespan ( timedef ) : """Convert a string timespan definition to seconds , for example converting '1m30s ' to 90 . If * timedef * is already an int , the value will be returned unmodified . : param timedef : The timespan definition to convert to seconds . : type timedef : int , str : return : T...
if isinstance ( timedef , int ) : return timedef converter_order = ( 'w' , 'd' , 'h' , 'm' , 's' ) converters = { 'w' : 604800 , 'd' : 86400 , 'h' : 3600 , 'm' : 60 , 's' : 1 } timedef = timedef . lower ( ) if timedef . isdigit ( ) : return int ( timedef ) elif len ( timedef ) == 0 : return 0 seconds = - 1 ...
def complete ( self , uio , dropped = False ) : """Query for all missing information in the transaction"""
if self . dropped and not dropped : # do nothing for dropped xn , unless specifically told to return for end in [ 'src' , 'dst' ] : if getattr ( self , end ) : continue # we have this information uio . show ( '\nEnter ' + end + ' for transaction:' ) uio . show ( '' ) uio . show ( self . ...
def getBool ( self , pchSection , pchSettingsKey ) : """Users of the system need to provide a proper default in default . vrsettings in the resources / settings / directory of either the runtime or the driver _ xxx directory . Otherwise the default will be false , 0 , 0.0 or " " """
fn = self . function_table . getBool peError = EVRSettingsError ( ) result = fn ( pchSection , pchSettingsKey , byref ( peError ) ) return result , peError
def get ( cls , external_id , local_user_id , provider_name , db_session = None ) : """Fetch row using primary key - will use existing object in session if already present : param external _ id : : param local _ user _ id : : param provider _ name : : param db _ session : : return :"""
db_session = get_db_session ( db_session ) return db_session . query ( cls . model ) . get ( [ external_id , local_user_id , provider_name ] )
def check_levels ( imls , imt , min_iml = 1E-10 ) : """Raise a ValueError if the given levels are invalid . : param imls : a list of intensity measure and levels : param imt : the intensity measure type : param min _ iml : minimum intensity measure level ( default 1E - 10) > > > check _ levels ( [ 0.1 , 0.2...
if len ( imls ) < 1 : raise ValueError ( 'No imls for %s: %s' % ( imt , imls ) ) elif imls != sorted ( imls ) : raise ValueError ( 'The imls for %s are not sorted: %s' % ( imt , imls ) ) elif len ( distinct ( imls ) ) < len ( imls ) : raise ValueError ( "Found duplicated levels for %s: %s" % ( imt , imls ) ...
def WriteBlobsWithUnknownHashes ( self , blobs_data ) : """Calculates hash ids and writes contents of given data blobs . Args : blobs _ data : An iterable of bytes . Returns : A list of rdf _ objects . BlobID objects with each blob id corresponding to an element in the original blobs _ data argument ."""
blobs_ids = [ rdf_objects . BlobID . FromBlobData ( d ) for d in blobs_data ] self . WriteBlobs ( dict ( zip ( blobs_ids , blobs_data ) ) ) return blobs_ids
def write ( self , timeunit , timepoints ) -> None : """Open a new NetCDF file temporarily and call method | NetCDFVariableBase . write | of all handled | NetCDFVariableBase | objects ."""
with netcdf4 . Dataset ( self . filepath , "w" ) as ncfile : ncfile . Conventions = 'CF-1.6' self . _insert_timepoints ( ncfile , timepoints , timeunit ) for variable in self . variables . values ( ) : variable . write ( ncfile )
def write ( self , fileobj = sys . stdout , indent = u"" ) : """Recursively write an element and it ' s children to a file ."""
fileobj . write ( self . start_tag ( indent ) ) fileobj . write ( u"\n" ) for c in self . childNodes : if c . tagName not in self . validchildren : raise ElementError ( "invalid child %s for %s" % ( c . tagName , self . tagName ) ) c . write ( fileobj , indent + Indent ) if self . pcdata is not None : ...
def _list_locators ( self ) : """Lists locators . Returns : generator of tuple : locator name str , locator header dict"""
with _handle_client_exception ( ) : response = self . client . get_account ( ) for container in response [ 1 ] : yield container . pop ( 'name' ) , container