signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def build_file_lines ( self ) : """Like ` target _ lines ` , the entire BUILD file ' s lines after dependency manipulation ."""
build_file_lines = self . _build_file_source_lines [ : ] target_begin , target_end = self . _target_interval build_file_lines [ target_begin : target_end ] = self . target_lines ( ) return build_file_lines
def clear_all ( self ) : """clear all files that were to be injected"""
self . injections . clear_all ( ) for config_file in CONFIG_FILES : self . injections . clear ( os . path . join ( "~" , config_file ) )
def remove_constraint ( self , table , constraint ) : """: param table : table name : param constraint : the constraint number as returned by list _ constraints"""
self . client . removeConstraint ( self . login , table , constraint )
def _machine_fqdn ( machine ) : """Returns the FQDN of the given learning machine ."""
from acorn . logging . decoration import _fqdn if hasattr ( machine , "__class__" ) : return _fqdn ( machine . __class__ , False ) else : # pragma : no cover # See what FQDN can get out of the class instance . return _fqdn ( machine )
def update ( self , async_ = False , ** kw ) : """Update online model parameters to server ."""
async_ = kw . get ( 'async' , async_ ) headers = { 'Content-Type' : 'application/xml' } new_kw = dict ( ) if self . offline_model_name : upload_keys = ( '_parent' , 'name' , 'offline_model_name' , 'offline_model_project' , 'qos' , 'instance_num' ) else : upload_keys = ( '_parent' , 'name' , 'qos' , '_model_reso...
def _set_ip_vrrp_extended ( self , v , load = False ) : """Setter method for ip _ vrrp _ extended , mapped from YANG variable / routing _ system / interface / ve / ip / ip _ vrrp _ extended ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ip _ vrrp _ extend...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = ip_vrrp_extended . ip_vrrp_extended , is_container = 'container' , presence = False , yang_name = "ip-vrrp-extended" , rest_name = "vrrp-extended" , parent = self , path_helper = self . _path_helper , extmethods = self . _ext...
def enable ( name ) : '''Set the named container to be launched at boot CLI Example : . . code - block : : bash salt myminion nspawn . enable < name >'''
cmd = 'systemctl enable systemd-nspawn@{0}' . format ( name ) if __salt__ [ 'cmd.retcode' ] ( cmd , python_shell = False ) != 0 : __context__ [ 'retcode' ] = salt . defaults . exitcodes . EX_UNAVAILABLE return False return True
def viscosity_kinematic_pacl ( conc_pacl , temp ) : """Return the dynamic viscosity of water at a given temperature . If given units , the function will automatically convert to Kelvin . If not given units , the function will assume Kelvin . This function assumes that the temperature dependence can be explain...
nu = ( 1 + ( 2.383 * 10 ** - 5 ) * conc_pacl ** 1.893 ) * pc . viscosity_kinematic ( temp ) . magnitude return nu
def make_processitem_portlist_portitem_remoteip ( remote_ip , condition = 'is' , negate = False ) : """Create a node for ProcessItem / PortList / PortItem / remoteIP : return : A IndicatorItem represented as an Element node"""
document = 'ProcessItem' search = 'ProcessItem/PortList/PortItem/remoteIP' content_type = 'IP' content = remote_ip ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate ) return ii_node
def _get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ Any ] , logger : Logger ) -> Dict [ str , Any ] : """Implementation of AnyParser API"""
raise Exception ( 'This should never happen, since this parser relies on underlying parsers' )
def to_deprecated_son ( self , prefix = '' , tag = 'i4x' ) : """Returns a SON object that represents this location"""
# This preserves the old SON keys ( ' tag ' , ' org ' , ' course ' , ' category ' , ' name ' , ' revision ' ) , # because that format was used to store data historically in mongo # adding tag b / c deprecated form used it son = SON ( { prefix + 'tag' : tag } ) for field_name in ( 'org' , 'course' ) : # Temporary filter...
def combine_cache_keys ( cls , cache_keys ) : """Returns a cache key for a list of target sets that already have cache keys . This operation is ' idempotent ' in the sense that if cache _ keys contains a single key then that key is returned . Note that this operation is commutative but not associative . We us...
if len ( cache_keys ) == 1 : return cache_keys [ 0 ] else : combined_id = Target . maybe_readable_combine_ids ( cache_key . id for cache_key in cache_keys ) combined_hash = hash_all ( sorted ( cache_key . hash for cache_key in cache_keys ) ) return cls ( combined_id , combined_hash )
def __dbfRecords ( self ) : """Writes the dbf records ."""
f = self . __getFileObj ( self . dbf ) for record in self . records : if not self . fields [ 0 ] [ 0 ] . startswith ( "Deletion" ) : f . write ( b ( ' ' ) ) # deletion flag for ( fieldName , fieldType , size , dec ) , value in zip ( self . fields , record ) : fieldType = fieldType . uppe...
def GetFileEntryByPathSpec ( self , path_spec ) : """Retrieves a file entry for a path specification . Args : path _ spec ( PathSpec ) : path specification . Returns : FileEntry : a file entry or None ."""
row_index = getattr ( path_spec , 'row_index' , None ) row_condition = getattr ( path_spec , 'row_condition' , None ) # If no row _ index or row _ condition is provided , return a directory . if row_index is None and row_condition is None : return sqlite_blob_file_entry . SQLiteBlobFileEntry ( self . _resolver_cont...
async def set_reply_markup ( msg : Dict , request : 'Request' , stack : 'Stack' ) -> None : """Add the " reply markup " to a message from the layers : param msg : Message dictionary : param request : Current request being replied : param stack : Stack to analyze"""
from bernard . platforms . telegram . layers import InlineKeyboard , ReplyKeyboard , ReplyKeyboardRemove try : keyboard = stack . get_layer ( InlineKeyboard ) except KeyError : pass else : msg [ 'reply_markup' ] = await keyboard . serialize ( request ) try : keyboard = stack . get_layer ( ReplyKeyboard ...
def _expand_list ( names ) : """Do a wildchar name expansion of object names in a list and return expanded list . The objects are expected to exist as this is used for copy sources or delete targets . Currently we support wildchars in the key name only ."""
if names is None : names = [ ] elif isinstance ( names , basestring ) : names = [ names ] results = [ ] # The expanded list . objects = { } # Cached contents of buckets ; used for matching . for name in names : bucket , key = google . datalab . storage . _bucket . parse_name ( name ) results_len = len (...
def merge_segments ( segments , exif = b"" ) : """Merges Exif with APP0 and APP1 manipulations ."""
if segments [ 1 ] [ 0 : 2 ] == b"\xff\xe0" and segments [ 2 ] [ 0 : 2 ] == b"\xff\xe1" and segments [ 2 ] [ 4 : 10 ] == b"Exif\x00\x00" : if exif : segments [ 2 ] = exif segments . pop ( 1 ) elif exif is None : segments . pop ( 2 ) else : segments . pop ( 1 ) elif segments [ ...
def hijack_attr ( self , attr_name ) : """Hijack an attribute on the target object . Updates the underlying class and delegating the call to the instance . This allows specially - handled attributes like _ _ call _ _ , _ _ enter _ _ , and _ _ exit _ _ to be mocked on a per - instance basis . : param str att...
if not self . _original_attr ( attr_name ) : setattr ( self . obj . __class__ , attr_name , _proxy_class_method_to_instance ( getattr ( self . obj . __class__ , attr_name , None ) , attr_name ) , )
def apply ( self , collection , ops , ** kwargs ) : """Apply the filter to collection ."""
validator = lambda obj : all ( op ( obj , val ) for ( op , val ) in ops ) # noqa return [ o for o in collection if validator ( o ) ]
def align ( self , referencewords , datatuple ) : """align the reference sentence with the tagged data"""
targetwords = [ ] for i , ( word , lemma , postag ) in enumerate ( zip ( datatuple [ 0 ] , datatuple [ 1 ] , datatuple [ 2 ] ) ) : if word : subwords = word . split ( "_" ) for w in subwords : # split multiword expressions targetwords . append ( ( w , lemma , postag , i , len ( subwords ...
def _process_gxd_genotype_summary_view ( self , limit = None ) : """Add the genotype internal id to mgiid mapping to the idhashmap . Also , add them as individuals to the graph . We re - format the label to put the background strain in brackets after the gvc . We must pass through the file once to get the i...
if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 geno_hash = { } raw = '/' . join ( ( self . rawdir , 'gxd_genotype_summary_view' ) ) LOG . info ( "building labels for genotypes" ) with open ( raw , 'r' ) as f : f . readline ( ) # read t...
def on_mouse_move ( self , event ) : """Mouse move handler Parameters event : instance of Event The event ."""
if event . is_dragging : dxy = event . pos - event . last_event . pos button = event . press_event . button if button == 1 : dxy = self . canvas_tr . map ( dxy ) o = self . canvas_tr . map ( [ 0 , 0 ] ) t = dxy - o self . move ( t ) elif button == 2 : center = sel...
def get_unresolved_variables ( f ) : """Gets unresolved vars from file"""
reporter = RReporter ( ) checkPath ( f , reporter = reporter ) return dict ( reporter . messages )
def set_inteface_down ( devid , ifindex ) : """function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut " the specifie d interface on the target device . : param devid : int or str value of the target device : param ifindex : int or str value of the target interfa...
if auth is None or url is None : # checks to see if the imc credentials are already available set_imc_creds ( ) set_int_down_url = "/imcrs/plat/res/device/" + str ( devid ) + "/interface/" + str ( ifindex ) + "/down" f_url = url + set_int_down_url payload = None r = requests . put ( f_url , auth = auth , headers = ...
def _parse_section_to_dict ( cls , section_options , values_parser = None ) : """Parses section options into a dictionary . Optionally applies a given parser to values . : param dict section _ options : : param callable values _ parser : : rtype : dict"""
value = { } values_parser = values_parser or ( lambda val : val ) for key , ( _ , val ) in section_options . items ( ) : value [ key ] = values_parser ( val ) return value
def profile_list ( self , provider , lookup = 'all' ) : '''Return a mapping of all configured profiles'''
data = { } lookups = self . lookup_profiles ( provider , lookup ) if not lookups : return data for alias , driver in lookups : if alias not in data : data [ alias ] = { } if driver not in data [ alias ] : data [ alias ] [ driver ] = { } return data
def protect_pip_from_modification_on_windows ( modifying_pip ) : """Protection of pip . exe from modification on Windows On Windows , any operation modifying pip should be run as : python - m pip . . ."""
pip_names = [ "pip.exe" , "pip{}.exe" . format ( sys . version_info [ 0 ] ) , "pip{}.{}.exe" . format ( * sys . version_info [ : 2 ] ) ] # See https : / / github . com / pypa / pip / issues / 1299 for more discussion should_show_use_python_msg = ( modifying_pip and WINDOWS and os . path . basename ( sys . argv [ 0 ] ) ...
def pst ( self ) : """get the pyemu . Pst attribute Returns pst : pyemu . Pst Note returns a references If LinearAnalysis . _ _ pst is None , then the pst attribute is dynamically loaded before returning"""
if self . __pst is None and self . pst_arg is None : raise Exception ( "linear_analysis.pst: can't access self.pst:" + "no pest control argument passed" ) elif self . __pst : return self . __pst else : self . __load_pst ( ) return self . __pst
def _lex_file_object ( file_obj ) : """Generates token tuples from an nginx config file object Yields 3 - tuples like ( token , lineno , quoted )"""
token = '' # the token buffer token_line = 0 # the line the token starts on next_token_is_directive = True it = itertools . chain . from_iterable ( file_obj ) it = _iterescape ( it ) # treat escaped characters differently it = _iterlinecount ( it ) # count the number of newline characters for char , line in it : # hand...
def from_obj ( cls , cls_obj ) : """Parse the generateDS object and return an Entity instance . This will attempt to extract type information from the input object and pass it to entity _ class to resolve the correct class for the type . Args : cls _ obj : A generateDS object . Returns : An Entity ins...
if not cls_obj : return None typekey = cls . objkey ( cls_obj ) klass = cls . entity_class ( typekey ) return klass . from_obj ( cls_obj )
def get_private ( self ) : """Derive private key from the brain key and the current sequence number"""
a = compat_bytes ( self . account + self . role + self . password , 'utf8' ) s = hashlib . sha256 ( a ) . digest ( ) return PrivateKey ( hexlify ( s ) . decode ( 'ascii' ) )
def set_project_pid ( project , old_pid , new_pid ) : """Project ' s PID was changed ."""
for datastore in _get_datastores ( ) : datastore . save_project ( project ) datastore . set_project_pid ( project , old_pid , new_pid )
def put_centered_text ( img , text , font_face , font_scale , color , thickness = 1 , line_type = 8 ) : """Utility for drawing vertically & horizontally centered text with line breaks : param img : Image . : param text : Text string to be drawn . : param font _ face : Font type . One of FONT _ HERSHEY _ SIMPL...
# Save img dimensions img_h , img_w = img . shape [ : 2 ] # Break text into list of text lines text_lines = text . split ( '\n' ) # Get height of text lines in pixels ( height of all lines is the same ; width differs ) _ , line_height = cv2 . getTextSize ( '' , font_face , font_scale , thickness ) [ 0 ] # Set distance ...
def queue ( self , value ) : """Sets the audioqueue . Parameters value : queue . Queue The buffer from which audioframes are received ."""
if not isinstance ( value , Queue ) : raise TypeError ( "queue is not a Queue object" ) self . _queue = value
def zipfiles ( self , path = None , arcdirname = 'data' ) : """Returns a . zip archive of selected rasters ."""
if path : fp = open ( path , 'w+b' ) else : prefix = '%s-' % arcdirname fp = tempfile . NamedTemporaryFile ( prefix = prefix , suffix = '.zip' ) with zipfile . ZipFile ( fp , mode = 'w' ) as zf : for obj in self : img = obj . image arcname = os . path . join ( arcdirname , os . path . ba...
def read ( self , response ) : """Reads the current state of the entity from the server ."""
results = self . _load_state ( response ) # In lower layers of the SDK , we end up trying to URL encode # text to be dispatched via HTTP . However , these links are already # URL encoded when they arrive , and we need to mark them as such . unquoted_links = dict ( [ ( k , UrlEncoded ( v , skip_encode = True ) ) for k ,...
def _build_synset_lookup ( imagenet_metadata_file ) : """Build lookup for synset to human - readable label . Args : imagenet _ metadata _ file : string , path to file containing mapping from synset to human - readable label . Assumes each line of the file looks like : n02119247 black fox n02119359 silve...
lines = tf . gfile . FastGFile ( imagenet_metadata_file , 'r' ) . readlines ( ) synset_to_human = { } for l in lines : if l : parts = l . strip ( ) . split ( '\t' ) assert len ( parts ) == 2 synset = parts [ 0 ] human = parts [ 1 ] synset_to_human [ synset ] = human return sy...
def datasets_create_version_by_id ( self , id , dataset_new_version_request , ** kwargs ) : # noqa : E501 """Create a new dataset version by id # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . dat...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . datasets_create_version_by_id_with_http_info ( id , dataset_new_version_request , ** kwargs ) # noqa : E501 else : ( data ) = self . datasets_create_version_by_id_with_http_info ( id , dataset_new_version_request , **...
def map_ott_ids ( self , ott_id_list , to_prune_fsi_set , root_ott_id ) : """returns : - a list of recognized ott _ ids . - a list of unrecognized ott _ ids - a list of ott _ ids that forward to unrecognized ott _ ids - a list of ott _ ids that do not appear in the tree because they are flagged to be pruned...
mapped , unrecog , forward2unrecog , pruned , above_root , old2new = [ ] , [ ] , [ ] , [ ] , [ ] , { } known_unpruned , known_pruned = set ( ) , set ( ) known_above_root , known_below_root = set ( ) , set ( ) oi2poi = self . ott_id2par_ott_id ft = self . forward_table for old_id in ott_id_list : if old_id in oi2poi...
def update_hash_prefix_cache ( self ) : """Update locally cached threat lists ."""
try : self . storage . cleanup_full_hashes ( ) self . storage . commit ( ) self . _sync_threat_lists ( ) self . storage . commit ( ) self . _sync_hash_prefix_cache ( ) except Exception : self . storage . rollback ( ) raise
def get_symbols_from_list ( list_name ) : """Retrieve a named ( symbol list name ) list of strings ( symbols ) If you ' ve installed the QSTK Quantitative analysis toolkit ` get _ symbols _ from _ list ( ' sp5002012 ' ) ` will produce a list of the symbols that were members of the S & P 500 in 2012. Otherwi...
try : # quant software toolkit has a method for retrieving lists of symbols like S & P500 for 2012 with ' sp5002012' import QSTK . qstkutil . DataAccess as da dataobj = da . DataAccess ( 'Yahoo' ) except ImportError : raise except : return [ ] try : return dataobj . get_symbols_from_list ( list_name...
def update ( self , function_values , es ) : """updates the weights for computing a boundary penalty . Arguments ` function _ values ` all function values of recent population of solutions ` es ` ` CMAEvolutionStrategy ` object instance , in particular mean and variances and the methods from the attribu...
if self . bounds is None or ( self . bounds [ 0 ] is None and self . bounds [ 1 ] is None ) : return self N = es . N # # # prepare # compute varis = sigma * * 2 * C _ ii varis = es . sigma ** 2 * array ( N * [ es . C ] if isscalar ( es . C ) else ( # scalar case es . C if isscalar ( es . C [ 0 ] ) else # diagonal m...
def by_col ( cls , df , e , b , w = None , inplace = False , ** kwargs ) : """Compute smoothing by columns in a dataframe . Parameters df : pandas . DataFrame a dataframe containing the data to be smoothed e : string or list of strings the name or names of columns containing event variables to be smooth...
if not inplace : new = df . copy ( ) cls . by_col ( new , e , b , w = w , inplace = True , ** kwargs ) return new if isinstance ( e , str ) : e = [ e ] if isinstance ( b , str ) : b = [ b ] if w is None : found = False for k in df . _metadata : w = df . __dict__ . get ( w , None ) ...
def matches ( self , hash_alg , hash_value ) : """Does our algorithm and hash value match the specified arguments . : param hash _ alg : str : hash algorithm : param hash _ value : str : hash value : return : boolean"""
return self . alg == hash_alg and self . value == hash_value
def invite ( self , user = None , party = None , tag = None ) : """邀请成员 https : / / work . weixin . qq . com / api / doc # 90000/90135/90975 企业可通过接口批量邀请成员使用企业微信 , 邀请后将通过短信或邮件下发通知 。 : param user : 成员ID列表 , 最多支持1000个 。 : param party : 成员ID列表 , 最多支持100个 。 : param tag : 成员ID列表 , 最多支持100个 。 : return : 返回的 JS...
data = optionaldict ( user = user , party = party , tag = tag ) return self . _post ( 'batch/invite' , data = data )
def call ( cmd_args , suppress_output = False ) : """Call an arbitary command and return the exit value , stdout , and stderr as a tuple Command can be passed in as either a string or iterable > > > result = call ( ' hatchery ' , suppress _ output = True ) > > > result . exitval > > > result = call ( [ ' ha...
if not funcy . is_list ( cmd_args ) and not funcy . is_tuple ( cmd_args ) : cmd_args = shlex . split ( cmd_args ) logger . info ( 'executing `{}`' . format ( ' ' . join ( cmd_args ) ) ) call_request = CallRequest ( cmd_args , suppress_output = suppress_output ) call_result = call_request . run ( ) if call_result . ...
def node_labels ( node_labels , node_indices ) : """Validate that there is a label for each node ."""
if len ( node_labels ) != len ( node_indices ) : raise ValueError ( "Labels {0} must label every node {1}." . format ( node_labels , node_indices ) ) if len ( node_labels ) != len ( set ( node_labels ) ) : raise ValueError ( "Labels {0} must be unique." . format ( node_labels ) )
def do_confusion_matrix ( sorting1 , sorting2 , unit_map12 , labels_st1 , labels_st2 ) : """Compute the confusion matrix between two sorting . Parameters sorting1 : SortingExtractor instance The ground truth sorting . sorting2 : SortingExtractor instance The tested sorting . unit _ map12 : dict Dict o...
unit1_ids = np . array ( sorting1 . get_unit_ids ( ) ) unit2_ids = np . array ( sorting2 . get_unit_ids ( ) ) N1 = len ( unit1_ids ) N2 = len ( unit2_ids ) conf_matrix = np . zeros ( ( N1 + 1 , N2 + 1 ) , dtype = int ) mapped_units = np . array ( list ( unit_map12 . values ( ) ) ) idxs_matched , = np . where ( mapped_u...
def _assemble_conversion ( stmt ) : """Assemble a Conversion statement into text ."""
reactants = _join_list ( [ _assemble_agent_str ( r ) for r in stmt . obj_from ] ) products = _join_list ( [ _assemble_agent_str ( r ) for r in stmt . obj_to ] ) if stmt . subj is not None : subj_str = _assemble_agent_str ( stmt . subj ) stmt_str = '%s catalyzes the conversion of %s into %s' % ( subj_str , react...
def get ( section , name ) : """Wrapper around ConfigParser ' s ` ` get ` ` method ."""
cfg = ConfigParser . SafeConfigParser ( { "working_dir" : "/tmp" , "debug" : "0" } ) cfg . read ( CONFIG_LOCATIONS ) val = cfg . get ( section , name ) return val . strip ( "'" ) . strip ( '"' )
def _S ( kappa , alpha , beta ) : """Compute the antiderivative of the Amos - type bound G on the modified Bessel function ratio . Note : Handles scalar kappa , alpha , and beta only . See " S < - " in movMF . R and utility function implementation notes from https : / / cran . r - project . org / web / pack...
kappa = 1. * np . abs ( kappa ) alpha = 1. * alpha beta = 1. * np . abs ( beta ) a_plus_b = alpha + beta u = np . sqrt ( kappa ** 2 + beta ** 2 ) if alpha == 0 : alpha_scale = 0 else : alpha_scale = alpha * np . log ( ( alpha + u ) / a_plus_b ) return u - beta - alpha_scale
def parse_data_writer ( self , node ) : """Parses < DataWriter > @ param node : Node containing the < DataWriter > element @ type node : xml . etree . Element"""
if 'path' in node . lattrib : path = node . lattrib [ 'path' ] else : self . raise_error ( '<DataWriter> must specify a path.' ) if 'filename' in node . lattrib : file_path = node . lattrib [ 'filename' ] else : self . raise_error ( "Data writer for '{0}' must specify a filename." , path ) self . curren...
def recalculate_concepts ( self , concepts , lang = None ) : """Recalculated given concepts for given users Args : concepts ( dict ) : user id ( int - > set of concepts to recalculate ) lang ( Optional [ str ] ) : language used to get items in all concepts ( cached ) . Defaults to None , in that case are ge...
if len ( concepts ) == 0 : return if lang is None : items = Concept . objects . get_concept_item_mapping ( concepts = Concept . objects . filter ( pk__in = set ( flatten ( concepts . values ( ) ) ) ) ) else : items = Concept . objects . get_concept_item_mapping ( lang = lang ) environment = get_environment ...
def delete ( self , client = None ) : """Deletes a blob from Cloud Storage . If : attr : ` user _ project ` is set on the bucket , bills the API request to that project . : type client : : class : ` ~ google . cloud . storage . client . Client ` or ` ` NoneType ` ` : param client : Optional . The client t...
return self . bucket . delete_blob ( self . name , client = client , generation = self . generation )
def vtrees ( self ) : """Get list of VTrees from ScaleIO cluster : return : List of VTree objects - Can be empty of no VTrees exist : rtype : VTree object"""
self . connection . _check_login ( ) response = self . connection . _do_get ( "{}/{}" . format ( self . connection . _api_url , "types/VTree/instances" ) ) . json ( ) all_vtrees = [ ] for vtree in response : all_vtrees . append ( SIO_Vtree . from_dict ( vtree ) ) return all_vtrees
def DateTimeField ( formatter = types . DEFAULT_DATETIME_FORMAT , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : """Create new datetime field on a model . : param formatter : datetime formatter string ( default : " ISO _ FORMAT " ) : param default : any datetime or string that c...
default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , datetime ) converter = converters . to_datetime_field ( formatter ) return attrib ( default = default , converter = converter , validator = validator , repr = repr , cmp = cmp , metadata = dict ( f...
def main ( ) : """NAME mk _ redo . py DESCRIPTION Makes thellier _ redo and zeq _ redo files from existing pmag _ specimens format file SYNTAX mk _ redo . py [ - h ] [ command line options ] INPUT takes specimens . txt formatted input file OPTIONS - h : prints help message and quits - f FILE : s...
if '-h' in sys . argv : print ( main . __doc__ ) sys . exit ( ) zfile , tfile = 'zeq_redo' , 'thellier_redo' zredo , tredo = "" , "" dir_path = pmag . get_named_arg ( '-WD' , '.' ) inspec = pmag . get_named_arg ( '-f' , 'specimens.txt' ) if '-F' in sys . argv : ind = sys . argv . index ( '-F' ) redo = s...
def append ( self , v ) : '''add a new setting'''
if isinstance ( v , MPSetting ) : setting = v else : ( name , type , default ) = v label = name tab = None if len ( v ) > 3 : label = v [ 3 ] if len ( v ) > 4 : tab = v [ 4 ] setting = MPSetting ( name , type , default , label = label , tab = tab ) # when a tab name is set , ...
def _process_items ( cls , vals ) : "Processes list of items assigning unique paths to each ."
if type ( vals ) is cls : return vals . data elif not isinstance ( vals , ( list , tuple ) ) : vals = [ vals ] items = [ ] counts = defaultdict ( lambda : 1 ) cls . _unpack_paths ( vals , items , counts ) items = cls . _deduplicate_items ( items ) return items
def include ( * what ) : """Whitelist * what * . : param what : What to whitelist . : type what : : class : ` list ` of : class : ` type ` or : class : ` attr . Attribute ` \\ s : rtype : : class : ` callable `"""
cls , attrs = _split_what ( what ) def include_ ( attribute , value ) : return value . __class__ in cls or attribute in attrs return include_
def _merge_default_values ( self ) : """Merge default values with resource data ."""
values = self . _get_default_values ( ) for key , value in values . items ( ) : if not self . data . get ( key ) : self . data [ key ] = value
def validate_username_for_new_person ( username ) : """Validate the new username for a new person . If the username is invalid or in use , raises : py : exc : ` UsernameInvalid ` or : py : exc : ` UsernameTaken ` . : param username : Username to validate ."""
# is the username valid ? validate_username ( username ) # Check for existing people count = Person . objects . filter ( username__exact = username ) . count ( ) if count >= 1 : raise UsernameTaken ( six . u ( 'The username is already taken. Please choose another. ' 'If this was the name of your old account please ...
def do_size ( self , w , h ) : """Apply size scaling ."""
# simeon @ ice ~ > cat m1 . pnm | pnmscale - width 50 > m2 . pnm infile = self . tmpfile outfile = self . basename + '.siz' if ( w is None ) : # print " size : no scaling " self . tmpfile = infile else : # print " size : scaling to ( % d , % d ) " % ( w , h ) if ( self . shell_call ( 'cat ' + infile + ' | ' + s...
def follow ( self , auth_secret , followee_username ) : """Follow a user . Parameters auth _ secret : str The authentication secret of the logged - in user . followee _ username : str The username of the followee . Returns bool True if the follow is successful , False otherwise . result None if ...
result = { pytwis_constants . ERROR_KEY : None } # Check if the user is logged in . loggedin , userid = self . _is_loggedin ( auth_secret ) if not loggedin : result [ pytwis_constants . ERROR_KEY ] = pytwis_constants . ERROR_NOT_LOGGED_IN return ( False , result ) with self . _rc . pipeline ( ) as pipe : # Chec...
def validate_positive_float ( option , value ) : """Validates that ' value ' is a float , or can be converted to one , and is positive ."""
errmsg = "%s must be an integer or float" % ( option , ) try : value = float ( value ) except ValueError : raise ValueError ( errmsg ) except TypeError : raise TypeError ( errmsg ) # float ( ' inf ' ) doesn ' t work in 2.4 or 2.5 on Windows , so just cap floats at # one billion - this is a reasonable approx...
def on_signout_action_activated ( self , action , params ) : '''在退出登录前 , 应该保存当前用户的所有数据'''
if self . profile : self . upload_page . pause_tasks ( ) self . download_page . pause_tasks ( ) self . show_signin_dialog ( auto_signin = False )
def read_config_file ( self , config_data = None , quiet = False ) : """read _ config _ file is the first effort to get a username and key to authenticate to the Kaggle API . Since we can get the username and password from the environment , it ' s not required . Parameters config _ data : the Configuration ...
if config_data is None : config_data = { } if os . path . exists ( self . config ) : try : if os . name != 'nt' : permissions = os . stat ( self . config ) . st_mode if ( permissions & 4 ) or ( permissions & 32 ) : print ( 'Warning: Your Kaggle API key is readable...
def register_type ( resolve_type , resolve_func ) : """Registers a type for lazy value resolution . Instances of AbstractLazyObject do not have to be registered . The exact type must be provided in ` ` resolve _ type ` ` , not a superclass of it . Types registered will be passed through the given function by : ...
if not isinstance ( resolve_type , type ) : raise ValueError ( "Expected type, got {0}." . format ( type ( resolve_type ) . __name__ ) ) if not callable ( resolve_func ) : raise ValueError ( "Function is not callable." ) type_registry [ expand_type_name ( resolve_type ) ] = resolve_func
def port ( self , port_range : PortRange = PortRange . ALL ) -> int : """Generate random port . : param port _ range : Range enum object . : return : Port number . : raises NonEnumerableError : if port _ range is not in PortRange . : Example : 8080"""
if port_range and port_range in PortRange : return self . random . randint ( * port_range . value ) else : raise NonEnumerableError ( PortRange )
def _load_manifest_from_file ( manifest , path ) : """load manifest from file"""
path = os . path . abspath ( os . path . expanduser ( path ) ) if not os . path . exists ( path ) : raise ManifestException ( "Manifest does not exist at {0}!" . format ( path ) ) manifest . read ( path ) if not manifest . has_option ( 'config' , 'source' ) : manifest . set ( 'config' , 'source' , str ( path ) ...
def filter ( self , func = None , ** query ) : """Tables can be filtered in one of two ways : - Simple keyword arguments return rows where values match * exactly * - Pass in a function and return rows where that function evaluates to True In either case , a new TableFu instance is returned"""
if callable ( func ) : result = filter ( func , self ) result . insert ( 0 , self . default_columns ) return TableFu ( result , ** self . options ) else : result = self for column , value in query . items ( ) : result = result . filter ( lambda r : r [ column ] == value ) return result
def _prepare_reserved_tokens ( reserved_tokens ) : """Prepare reserved tokens and a regex for splitting them out of strings ."""
reserved_tokens = [ tf . compat . as_text ( tok ) for tok in reserved_tokens or [ ] ] dups = _find_duplicates ( reserved_tokens ) if dups : raise ValueError ( "Duplicates found in tokens: %s" % dups ) reserved_tokens_re = _make_reserved_tokens_re ( reserved_tokens ) return reserved_tokens , reserved_tokens_re
def send_command ( self , command : str , * args , ** kwargs ) : """For request bot to perform some action"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s' self . _messaging_logger . command . info ( info , command , args , kwargs ) command = command . encode ( 'utf8' ) # target = target . encode ( ' ascii ' ) args = _json . dumps ( args ) . encode ( 'utf8' ) kwargs = _json . dumps ( kwargs ) . encode ( 'utf8' ) fra...
def write_to ( self , stream ) : """Write an XML representation of self , an ` ` Event ` ` object , to the given stream . The ` ` Event ` ` object will only be written if its data field is defined , otherwise a ` ` ValueError ` ` is raised . : param stream : stream to write XML to ."""
if self . data is None : raise ValueError ( "Events must have at least the data field set to be written to XML." ) event = ET . Element ( "event" ) if self . stanza is not None : event . set ( "stanza" , self . stanza ) event . set ( "unbroken" , str ( int ( self . unbroken ) ) ) # if a time isn ' t set , let S...
def noaa_prompt_1 ( ) : """For converting LiPD files to NOAA , we need a couple more pieces of information to create the WDS links : return str _ project : Project name : return float _ version : Version number"""
print ( "Enter the project information below. We'll use this to create the WDS URL" ) print ( "What is the project name?" ) _project = input ( ">" ) print ( "What is the project version?" ) _version = input ( ">" ) return _project , _version
def mat_to_laplacian ( mat , normalized ) : """Converts a sparse or dence adjacency matrix to Laplacian . Parameters mat : obj Input adjacency matrix . If it is a Laplacian matrix already , return it . normalized : bool Whether to use normalized Laplacian . Normalized and unnormalized Laplacians capture...
if sps . issparse ( mat ) : if np . all ( mat . diagonal ( ) >= 0 ) : # Check diagonal if np . all ( ( mat - sps . diags ( mat . diagonal ( ) ) ) . data <= 0 ) : # Check off - diagonal elements return mat else : if np . all ( np . diag ( mat ) >= 0 ) : # Check diagonal if np . all ( ...
def _update_x_transforms ( self ) : """Compute a new set of x - transform functions phik . phik ( xk ) = theta ( y ) - sum of phii ( xi ) over i ! = k This is the first of the eponymous conditional expectations . The conditional expectations are computed using the SuperSmoother ."""
# start by subtracting all transforms theta_minus_phis = self . y_transform - numpy . sum ( self . x_transforms , axis = 0 ) # add one transform at a time so as to exclude it from the subtracted sum for xtransform_index in range ( len ( self . x_transforms ) ) : xtransform = self . x_transforms [ xtransform_index ]...
def do_bot ( self , line ) : """Call the bot"""
with colorize ( 'blue' ) : if not line : self . say ( 'what?' ) try : res = self . adapter . receive ( message = line ) except UnknownCommand : self . say ( "I do not known what the '%s' directive is" % line ) else : self . say ( res )
def page_for_value ( cls , resp , value ) : """Return a new ` Page ` representing the given resource ` value ` retrieved using the HTTP response ` resp ` . This method records pagination ` ` Link ` ` headers present in ` resp ` , so that the returned ` Page ` can return their resources from its ` next _ pag...
page = cls ( value ) links = parse_link_value ( resp . getheader ( 'Link' ) ) for url , data in six . iteritems ( links ) : if data . get ( 'rel' ) == 'start' : page . start_url = url if data . get ( 'rel' ) == 'next' : page . next_url = url return page
def delete_rule ( self , rule_id ) : """Delete the specific Rule from dictionary indexed by rule id ."""
if rule_id not in self . rules : LOG . error ( "No Rule id present for deleting %s" , rule_id ) return del self . rules [ rule_id ] self . rule_cnt -= 1
def debug ( function ) : """Function : debug Summary : decorator to debug a function Examples : at the execution of the function wrapped , the decorator will allows to print the input and output of each execution Attributes : @ param ( function ) : function Returns : wrapped function"""
@ wraps ( function ) def _wrapper ( * args , ** kwargs ) : result = function ( * args , ** kwargs ) for key , value in kwargs . items ( ) : args += tuple ( [ '{}={!r}' . format ( key , value ) ] ) if len ( args ) == 1 : args = '({})' . format ( args [ 0 ] ) print ( '@{0}{1} -> {2}' . for...
def post ( self , request , provider = None ) : """method called on POST request : param django . http . HttpRequest request : The current request object : param unicode provider : Optional parameter . The user provider suffix ."""
# if settings . CAS _ FEDERATE is not True redirect to the login page if not settings . CAS_FEDERATE : logger . warning ( "CAS_FEDERATE is False, set it to True to use federation" ) return redirect ( "cas_server:login" ) # POST with a provider suffix , this is probably an SLO request . csrf is disabled for # al...
def call ( self , action , params = None ) : """Makes an RPC call to the server and returns the json response : param action : RPC method to call : type action : str : param params : Dict of arguments to send with RPC call : type params : dict : raises : : py : exc : ` nano . rpc . RPCException ` : rais...
params = params or { } params [ 'action' ] = action resp = self . session . post ( self . host , json = params , timeout = self . timeout ) result = resp . json ( ) if 'error' in result : raise RPCException ( result [ 'error' ] ) return result
def json_output ( f ) : """Format response to json and in case of web - request set response content type to ' application / json ' ."""
@ wraps ( f ) def json_output_decorator ( * args , ** kwargs ) : @ inject ( config = Config ) def get_config ( config ) : return config config = get_config ( ) rv = f ( * args , ** kwargs ) indent = None if config . get ( 'DEBUG' , False ) : logging . getLogger ( __name__ ) . deb...
def get_raw ( self ) : """Return the raw ( unformatted ) numeric value of the efuse bits Returns a simple integer or ( for some subclasses ) a bitstring ."""
value = self . parent . read_efuse ( self . data_reg_offs ) return ( value & self . mask ) >> self . shift
def new ( self ) : """The new value present in the event ."""
ori = self . original . action if isinstance ( ori , ( types . ChannelAdminLogEventActionChangeAbout , types . ChannelAdminLogEventActionChangeTitle , types . ChannelAdminLogEventActionChangeUsername , types . ChannelAdminLogEventActionToggleInvites , types . ChannelAdminLogEventActionTogglePreHistoryHidden , types . C...
def ball_pick ( n , d , rng = None ) : """Return cartesian vectors uniformly picked on the unit ball in an arbitrary number of dimensions . The unit ball is the space enclosed by the unit sphere . The picking is done by rejection sampling in the unit cube . In 3 - dimensional space , the fraction ` \ pi / 6...
def valid ( r ) : return vector_mag_sq ( r ) < 1.0 return rejection_pick ( L = 2.0 , n = n , d = d , valid = valid , rng = rng )
def initialize ( self , initialization_order = None ) : """This function tries to initialize the stateful objects . In the case where an initialization function for ` Stock A ` depends on the value of ` Stock B ` , if we try to initialize ` Stock A ` before ` Stock B ` then we will get an error , as the value...
# Initialize time if self . time is None : if self . time_initialization is None : self . time = Time ( ) else : self . time = self . time_initialization ( ) # if self . time is None : # self . time = time # self . components . time = self . time # self . components . functions . time = self . t...
def get_activity_streams ( self , activity_id , types = None , resolution = None , series_type = None ) : """Returns an streams for an activity . http : / / strava . github . io / api / v3 / streams / # activity Streams represent the raw data of the uploaded file . External applications may only access this i...
# stream are comma seperated list if types is not None : types = "," . join ( types ) params = { } if resolution is not None : params [ "resolution" ] = resolution if series_type is not None : params [ "series_type" ] = series_type result_fetcher = functools . partial ( self . protocol . get , '/activities/...
def overlay_gateway_access_lists_ipv6_in_cg_ipv6_acl_in_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" ) name_key = ET . SubElement ( overlay_gateway , "name" ) name_key . text = kwargs . pop ( 'name' ) access_lists = ET . SubElement ( overlay_gateway , "access-lists" ) ipv6 ...
def where ( self , field , value = None , operator = '=' ) : """Establece condiciones para la consulta unidas por AND"""
if field is None : return self conjunction = None if value is None and isinstance ( field , dict ) : for field , value in field . items ( ) : operator , value = value if isinstance ( value , tuple ) else ( '=' , value ) self . where ( field , value , operator ) else : if self . where_criteri...
def split_and_strip ( string , separator_regexp = None , maxsplit = 0 ) : """Split a string into items and trim any excess spaces from the items > > > split _ and _ strip ( ' fred , was , here ' ) [ ' fred ' , ' was ' , ' here ' ]"""
if not string : return [ '' ] if separator_regexp is None : separator_regexp = _default_separator ( ) if not separator_regexp : return string . split ( ) return [ item . strip ( ) for item in re . split ( separator_regexp , string , maxsplit ) ]
def send_data ( self , ** kwargs ) : """This method transmits data to the Gett service . Input : * ` ` put _ url ` ` A PUT url to use when transmitting the data ( required ) * ` ` data ` ` A byte stream ( required ) Output : * ` ` True ` ` Example : : if file . send _ data ( put _ url = file . upload ...
put_url = None if 'put_url' in kwargs : put_url = kwargs [ 'put_url' ] else : put_url = self . put_upload_url if 'data' not in kwargs : raise AttributeError ( "'data' parameter is required" ) if not put_url : raise AttributeError ( "'put_url' cannot be None" ) if not isinstance ( kwargs [ 'data' ] , str...
def _most_constrained_variable_chooser ( problem , variables , domains ) : '''Choose the variable that has less available values .'''
# the variable with fewer values available return sorted ( variables , key = lambda v : len ( domains [ v ] ) ) [ 0 ]
def centroids ( self , instrument , min_abundance = 1e-4 , points_per_fwhm = 25 ) : """Estimates centroided peaks for a given instrument model . : param instrument : instrument model : param min _ abundance : minimum abundance for including a peak : param points _ per _ fwhm : grid density used for envelope c...
assert self . ptr != ffi . NULL centroids = ims . spectrum_envelope_centroids ( self . ptr , instrument . ptr , min_abundance , points_per_fwhm ) return _new_spectrum ( CentroidedSpectrum , centroids )
def read_stdin ( self ) : """Reads STDIN until the end of input and returns a unicode string ."""
text = sys . stdin . read ( ) # Decode the bytes returned from earlier Python STDIN implementations if sys . version_info [ 0 ] < 3 and text is not None : text = text . decode ( sys . stdin . encoding or 'utf-8' ) return text
def ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_use_vrf_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ssh_sa = ET . SubElement ( config , "ssh-sa" , xmlns = "urn:brocade.com:mgmt:brocade-sec-services" ) ssh = ET . SubElement ( ssh_sa , "ssh" ) server = ET . SubElement ( ssh , "server" ) ssh_vrf_cont = ET . SubElement ( server , "ssh-vrf-cont" ) use_vrf = ET . SubElement ( ssh_vrf_cont...
def ad_hoc_magic_from_file ( filename , ** kwargs ) : """Ad - hoc emulation of magic . from _ file from python - magic ."""
with open ( filename , 'rb' ) as stream : head = stream . read ( 16 ) if head [ : 4 ] == b'\x7fELF' : return b'application/x-executable' elif head [ : 2 ] == b'MZ' : return b'application/x-dosexec' else : raise NotImplementedError ( )
def execute_async ( self , operation , parameters = None , configuration = None ) : """Asynchronously execute a SQL query . Immediately returns after query is sent to the HS2 server . Poll with ` is _ executing ` . A call to ` fetch * ` will block . Parameters operation : str The SQL query to execute . ...
log . debug ( 'Executing query %s' , operation ) def op ( ) : if parameters : self . _last_operation_string = _bind_parameters ( operation , parameters ) else : self . _last_operation_string = operation op = self . session . execute ( self . _last_operation_string , configuration , run_async...
def update ( self , counter , f , x_orig , gradient_orig ) : """Perform an update of the linear transformation Arguments : | ` ` counter ` ` - - the iteration counter of the minimizer | ` ` f ` ` - - the function value at ` ` x _ orig ` ` | ` ` x _ orig ` ` - - the unknowns in original coordinates | ` ` g...
if Preconditioner . update ( self , counter , f , x_orig , gradient_orig ) : # determine a new preconditioner hessian = compute_fd_hessian ( self . fun , x_orig , self . epsilon ) evals , evecs = np . linalg . eigh ( hessian ) self . scales = np . sqrt ( abs ( evals ) ) + self . epsilon self . rotation ...