signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_unspent_outputs ( self , address ) : """Get unspent outputs at the address : param address : : return :"""
logging . debug ( 'get_unspent_outputs for address=%s' , address ) spendables = self . spendables_for_address ( bitcoin_address = address ) if spendables : return sorted ( spendables , key = lambda x : hash ( x . coin_value ) ) return None
def get_page_property ( self , page_id , page_property_key ) : """Get the page ( content ) property e . g . get key of hash : param page _ id : content _ id format : param page _ property _ key : key of property : return :"""
url = 'rest/api/content/{page_id}/property/{key}' . format ( page_id = page_id , key = str ( page_property_key ) ) return self . get ( path = url )
def get_all ( self , keys ) : """Returns the entries for the given keys . * * Warning : The returned map is NOT backed by the original map , so changes to the original map are NOT reflected in the returned map , and vice - versa . * * * * Warning 2 : This method uses _ _ hash _ _ and _ _ eq _ _ methods of b...
check_not_none ( keys , "keys can't be None" ) if not keys : return ImmediateFuture ( { } ) partition_service = self . _client . partition_service partition_to_keys = { } for key in keys : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) partition_id = partition_service . ...
def preparse ( output_format ) : """Do any special processing of a template , and return the result ."""
try : return templating . preparse ( output_format , lambda path : os . path . join ( config . config_dir , "templates" , path ) ) except ImportError as exc : if "tempita" in str ( exc ) : raise error . UserError ( "To be able to use Tempita templates, install the 'tempita' package (%s)\n" " Possibly...
def import_links ( self , links ) : """Import links , returns import result ( http : / / confluence . jetbrains . net / display / YTD2 / Import + Links ) Accepts result of getLinks ( ) Example : importLinks ( [ { ' login ' : ' vadim ' , ' fullName ' : ' vadim ' , ' email ' : ' eee @ ss . com ' , ' jabber ' : ' ...
xml = '<list>\n' for l in links : # ignore typeOutward and typeInward returned by getLinks ( ) xml += ' <link ' + "" . join ( attr + '=' + quoteattr ( l [ attr ] ) + ' ' for attr in l if attr not in [ 'typeInward' , 'typeOutward' ] ) + '/>\n' xml += '</list>' # TODO : convert response xml into python objects res =...
def old_div ( a , b ) : """DEPRECATED : import ` ` old _ div ` ` from ` ` past . utils ` ` instead . Equivalent to ` ` a / b ` ` on Python 2 without ` ` from _ _ future _ _ import division ` ` . TODO : generalize this to other objects ( like arrays etc . )"""
if isinstance ( a , numbers . Integral ) and isinstance ( b , numbers . Integral ) : return a // b else : return a / b
def check_kwargs ( kwargs ) : """Check the type and values of keyword arguments to : meth : ` _ _ init _ _ ` : param kwargs : Dictionary of keyword arguments : type kwargs : dict [ str , Any ] : raises : TypeError , ValueError"""
# width , height width = kwargs . get ( "width" , 400 ) height = kwargs . get ( "height" , 200 ) if not isinstance ( width , int ) or not isinstance ( height , int ) : raise TypeError ( "width and/or height arguments not of int type" ) if not width > 0 or not height > 0 : raise ValueError ( "width and/or height...
def getOverlayMouseScale ( self , ulOverlayHandle ) : """Gets the mouse scaling factor that is used for mouse events . The actual texture may be a different size , but this is typically the size of the underlying UI in pixels ."""
fn = self . function_table . getOverlayMouseScale pvecMouseScale = HmdVector2_t ( ) result = fn ( ulOverlayHandle , byref ( pvecMouseScale ) ) return result , pvecMouseScale
def from_inputs ( cls , workdir , inputs , manager = None , pickle_protocol = - 1 , task_class = ScfTask , work_class = Work , remove = False ) : """Construct a simple flow from a list of inputs . The flow contains a single Work with tasks whose class is given by task _ class . . . warning : : Don ' t use thi...
if not isinstance ( inputs , ( list , tuple ) ) : inputs = [ inputs ] flow = cls ( workdir , manager = manager , pickle_protocol = pickle_protocol , remove = remove ) work = work_class ( ) for inp in inputs : work . register ( inp , task_class = task_class ) flow . register_work ( work ) return flow . allocate ...
def json_encode ( self , out , limit = None , sort_keys = False , indent = None ) : '''Encode the results of this paged response as JSON writing to the provided file - like ` out ` object . This function will iteratively read as many pages as present , streaming the contents out as JSON . : param file - like ...
stream = self . _json_stream ( limit ) enc = json . JSONEncoder ( indent = indent , sort_keys = sort_keys ) for chunk in enc . iterencode ( stream ) : out . write ( u'%s' % chunk )
def retrieveVals ( self ) : """Retrieve values for graphs ."""
file_stats = self . _fileInfo . getContainerStats ( ) for contname in self . _fileContList : stats = file_stats . get ( contname ) if stats is not None : if self . hasGraph ( 'rackspace_cloudfiles_container_size' ) : self . setGraphVal ( 'rackspace_cloudfiles_container_size' , contname , sta...
def get_matrix ( self , indexes , columns ) : """For a list of indexes and list of columns return a DataFrame of the values . : param indexes : either a list of index values or a list of booleans with same length as all indexes : param columns : list of column names : return : DataFrame"""
if all ( [ isinstance ( i , bool ) for i in indexes ] ) : # boolean list is_bool_indexes = True if len ( indexes ) != len ( self . _index ) : raise ValueError ( 'boolean index list must be same size of existing index' ) bool_indexes = indexes indexes = list ( compress ( self . _index , indexes )...
def make_thread_stack_str ( self , frame , frame_id_to_lineno = None ) : ''': param frame _ id _ to _ lineno : If available , the line number for the frame will be gotten from this dict , otherwise frame . f _ lineno will be used ( needed for unhandled exceptions as the place where we report may be different ...
if frame_id_to_lineno is None : frame_id_to_lineno = { } make_valid_xml_value = pydevd_xml . make_valid_xml_value cmd_text_list = [ ] append = cmd_text_list . append curr_frame = frame frame = None # Clear frame reference try : py_db = get_global_debugger ( ) for frame_id , frame , method_name , _original_f...
def compare_profiles ( profile1 , profile2 ) : """Given two profiles , determine the ratio of similarity , i . e . the hamming distance between the strings . Args : profile1/2 ( str ) : profile string Returns : similarity _ ratio ( float ) : the ratio of similiarity ( 0-1)"""
length = len ( profile1 ) profile1 = np . array ( list ( profile1 ) ) profile2 = np . array ( list ( profile2 ) ) similarity_array = profile1 == profile2 matches = np . sum ( similarity_array ) similarity_ratio = matches / length return similarity_ratio
def pushall ( args ) : """% prog pushall unitig1 . * Push a bunch of unitig layout changes ."""
p = OptionParser ( pushall . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) flist = args for f in flist : if f . endswith ( ".log" ) : continue push ( [ f ] )
def get_score ( self , member , default = None , pipe = None ) : """Return the score of * member * , or * default * if it is not in the collection ."""
pipe = self . redis if pipe is None else pipe score = pipe . zscore ( self . key , self . _pickle ( member ) ) if ( score is None ) and ( default is not None ) : score = float ( default ) return score
def local_path ( force_download = False ) : """Downloads allele database from IEDB , returns local path to XML file ."""
return cache . fetch ( filename = ALLELE_XML_FILENAME , url = ALLELE_XML_URL , decompress = ALLELE_XML_DECOMPRESS , force = force_download )
def _gerrit_user_to_author ( props , username = "unknown" ) : """Convert Gerrit account properties to Buildbot format Take into account missing values"""
username = props . get ( "username" , username ) username = props . get ( "name" , username ) if "email" in props : username += " <%(email)s>" % props return username
def image_needs_building ( image ) : """Return whether an image needs building Checks if the image exists ( ignores commit range ) , either locally or on the registry . Args : image ( str ) : the ` repository : tag ` image to be build . Returns : True : if image needs to be built False : if not ( imag...
d = docker_client ( ) # first , check for locally built image try : d . images . get ( image ) except docker . errors . ImageNotFound : # image not found , check registry pass else : # it exists locally , no need to check remote return False # image may need building if it ' s not on the registry return ima...
def _refine_upcheck ( merge , min_goodness ) : """Remove from the merge any entries which would be covered by entries between their current position and the merge insertion position . For example , the third entry of : : 0011 - > N 0100 - > N 1000 - > N X000 - > NE Cannot be merged with the first two ...
# Remove any entries which would be covered by entries above the merge # position . changed = False for i in sorted ( merge . entries , reverse = True ) : # Get all the entries that are between the entry we ' re looking at the # insertion index of the proposed merged index . If this entry would be # covered up by any o...
def arg_bool ( name , default = False ) : """Fetch a query argument , as a boolean ."""
v = request . args . get ( name , '' ) if not len ( v ) : return default return v in BOOL_TRUISH
def get ( self , field , cluster ) : """Retrieve the value of one cluster ."""
if _is_list ( cluster ) : return [ self . get ( field , c ) for c in cluster ] assert field in self . _fields default = self . _fields [ field ] return self . _data . get ( cluster , { } ) . get ( field , default )
def create_table_index ( self , key , ** kwargs ) : """Create a pytables index on the table Parameters key : object ( the node to index ) Exceptions raises if the node is not a table"""
# version requirements _tables ( ) s = self . get_storer ( key ) if s is None : return if not s . is_table : raise TypeError ( "cannot create table index on a Fixed format store" ) s . create_index ( ** kwargs )
def load_hdf ( cls , filename , path = '' ) : # perhaps this doesn ' t need to be written ? """Loads EclipsePopulation from HDF file Also runs : func : ` EclipsePopulation . _ make _ kde ` if it can . : param filename : HDF file : param path : ( optional ) Path within HDF file"""
new = StarPopulation . load_hdf ( filename , path = path ) # setup lazy loading of starmodel if present try : with pd . HDFStore ( filename ) as store : if '{}/starmodel' . format ( path ) in store : new . _starmodel = None new . _starmodel_file = filename new . _starmode...
def query ( self , sparql , mode = "get" , namespace = None , rtn_format = "json" , ** kwargs ) : """runs a sparql query and returns the results args : sparql : the sparql query to run namespace : the namespace to run the sparql query against mode : [ ' get ' ( default ) , ' update ' ] the type of sparql qu...
if kwargs . get ( "debug" ) : log . setLevel ( logging . DEBUG ) conn = self . conn if namespace and namespace != self . namespace : conn = self . tstore . get_namespace ( namespace ) else : namespace = self . namespace if rtn_format not in self . qry_results_formats : raise KeyError ( "rtn_format was '...
def endpoint ( url , methods = [ 'GET' ] ) : """Returns a decorator which when applied a function , causes that function to serve ` url ` and only allows the HTTP methods in ` methods `"""
def decorator ( function , methods = methods ) : # Always allow OPTIONS since CORS requests will need it . methods = set ( methods ) methods . add ( 'OPTIONS' ) @ wraps ( function ) def wrapper ( environment , start_response ) : try : start_time = time . time ( ) if funct...
def _cache_normalize_path ( path ) : """abspath with caching"""
# _ module _ file calls abspath on every path in sys . path every time it ' s # called ; on a larger codebase this easily adds up to half a second just # assembling path components . This cache alleviates that . try : return _NORM_PATH_CACHE [ path ] except KeyError : if not path : # don ' t cache result for ' ...
def show_vcs_output_cluster_specific_status ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_vcs = ET . Element ( "show_vcs" ) config = show_vcs output = ET . SubElement ( show_vcs , "output" ) cluster_specific_status = ET . SubElement ( output , "cluster-specific-status" ) cluster_specific_status . text = kwargs . pop ( 'cluster_specific_status' ) callback = kwargs . po...
def get_mol_filename ( self ) : '''Returns mol filename'''
mol_filename = parsers . get_mol_filename ( self . __chebi_id ) if mol_filename is None : mol_filename = parsers . get_mol_filename ( self . get_parent_id ( ) ) if mol_filename is None : for parent_or_child_id in self . __get_all_ids ( ) : mol_filename = parsers . get_mol_filename ( parent_or_child_id )...
def get_activities_for_project ( self , module = None , ** kwargs ) : """Get the related activities of a project . : param str module : Stages of a given module : return : JSON"""
_module_id = kwargs . get ( 'module' , module ) _activities_url = ACTIVITIES_URL . format ( module_id = _module_id ) return self . _request_api ( url = _activities_url ) . json ( )
async def listTasks ( self , * args , ** kwargs ) : """List Tasks List the tasks immediately under a given namespace . This endpoint lists up to 1000 tasks . If more tasks are present , a ` continuationToken ` will be returned , which can be given in the next request . For the initial request , the payloa...
return await self . _makeApiCall ( self . funcinfo [ "listTasks" ] , * args , ** kwargs )
def read_ndk_event ( self , raw_data , id0 ) : """Reads a 5 - line batch of data into a set of GCMTs"""
gcmt = GCMTEvent ( ) # Get hypocentre ndkstring = raw_data [ id0 ] . rstrip ( '\n' ) gcmt . hypocentre = self . _read_hypocentre_from_ndk_string ( ndkstring ) # GCMT metadata ndkstring = raw_data [ id0 + 1 ] . rstrip ( '\n' ) gcmt = self . _get_metadata_from_ndk_string ( gcmt , ndkstring ) # Get Centroid ndkstring = ra...
def store_sentry ( self , username , sentry_bytes ) : """Store sentry bytes under a username : param username : username : type username : : class : ` str ` : return : Whenver the operation succeed : rtype : : class : ` bool `"""
filepath = self . _get_sentry_path ( username ) if filepath : try : with open ( filepath , 'wb' ) as f : f . write ( sentry_bytes ) return True except IOError as e : self . _LOG . error ( "store_sentry: %s" % str ( e ) ) return False
def go_to_next_buffer ( self , _previous = False ) : """Open next buffer in active window ."""
if self . active_editor_buffer : # Find the active opened buffer . index = self . editor_buffers . index ( self . active_editor_buffer ) # Get index of new buffer . if _previous : new_index = ( len ( self . editor_buffers ) + index - 1 ) % len ( self . editor_buffers ) else : new_index =...
def _setload ( l : Loader , value , type_ ) -> Set : """This loads into something like Set [ int ]"""
t = type_ . __args__ [ 0 ] return { l . load ( i , t ) for i in value }
def get_ec2_instances ( self ) : """Describes the EC2 instances : return : dict containing EC2 instance data : raises : EC2UtilError"""
log = logging . getLogger ( self . cls_logger + '.get_ec2_instances' ) log . info ( 'Describing EC2 instances...' ) try : response = self . client . describe_instances ( ) except ClientError : _ , ex , trace = sys . exc_info ( ) msg = '{n}: There was a problem describing EC2 instances\n{e}' . format ( n = e...
def imsave ( path , img , channel_first = False , as_uint16 = False , auto_scale = True ) : """Save image by cv2 module . Args : path ( str ) : output filename img ( numpy . ndarray ) : Image array to save . Image shape is considered as ( height , width , channel ) by default . channel _ first : This argu...
img = _imsave_before ( img , channel_first , auto_scale ) if auto_scale : img = upscale_pixel_intensity ( img , as_uint16 ) img = check_type_and_cast_if_necessary ( img , as_uint16 ) # revert channel order to opencv ` s one . if len ( img . shape ) == 3 : if img . shape [ - 1 ] == 3 : img = cv2 . cvtCol...
def template ( client , src , dest , paths , opt ) : """Writes a template using variables from a vault path"""
key_map = cli_hash ( opt . key_map ) obj = { } for path in paths : response = client . read ( path ) if not response : raise aomi . exceptions . VaultData ( "Unable to retrieve %s" % path ) if is_aws ( response [ 'data' ] ) and 'sts' not in path : renew_secret ( client , response , opt ) ...
def update_status ( dbfile , status_file , nas_addr ) : '''update status db'''
try : total = 0 params = [ ] for sid , su in parse_status_file ( status_file , nas_addr ) . items ( ) : if 'session_id' in su and 'inbytes' in su and 'outbytes' in su : params . append ( ( su [ 'inbytes' ] , su [ 'outbytes' ] , su [ 'session_id' ] ) ) total += 1 statusdb ...
async def mod ( self , iden , query ) : '''Change the query of an appointment'''
appt = self . appts . get ( iden ) if appt is None : raise s_exc . NoSuchIden ( ) if not query : raise ValueError ( 'empty query' ) if self . enabled : self . core . getStormQuery ( query ) appt . query = query appt . enabled = True # in case it was disabled for a bad query await self . _storeAppt ( appt )
def secondary_report_numbers ( self , key , value ) : """Populate the ` ` 037 ` ` MARC field . Also populates the ` ` 500 ` ` , ` ` 595 ` ` and ` ` 980 ` ` MARC field through side effects ."""
preliminary_results_prefixes = [ 'ATLAS-CONF-' , 'CMS-PAS-' , 'CMS-DP-' , 'LHCB-CONF-' ] note_prefixes = [ 'ALICE-INT-' , 'ATL-' , 'ATLAS-CONF-' , 'CMS-DP-' , 'CMS-PAS-' , 'LHCB-CONF-' , 'LHCB-PUB-' ] result_037 = self . get ( '037__' , [ ] ) result_500 = self . get ( '500__' , [ ] ) result_595 = self . get ( '595__' ,...
def randstring ( l ) : """Returns a random string of length l ( l > = 0)"""
return b"" . join ( struct . pack ( 'B' , random . randint ( 0 , 255 ) ) for _ in range ( l ) )
def values ( self , predicate = None ) : """Returns a list clone of the values contained in this map or values of the entries which are filtered with the predicate if provided . * * Warning : The list is NOT backed by the map , so changes to the map are NOT reflected in the list , and vice - versa . * * :...
if predicate : predicate_data = self . _to_data ( predicate ) return self . _encode_invoke ( map_values_with_predicate_codec , predicate = predicate_data ) else : return self . _encode_invoke ( map_values_codec )
def write_file_to_zip_with_neutral_metadata ( zfile , filename , content ) : """Write the string ` content ` to ` filename ` in the open ZipFile ` zfile ` . Args : zfile ( ZipFile ) : open ZipFile to write the content into filename ( str ) : the file path within the zip file to write into content ( str ) : ...
info = zipfile . ZipInfo ( filename , date_time = ( 2015 , 10 , 21 , 7 , 28 , 0 ) ) info . compress_type = zipfile . ZIP_DEFLATED info . comment = "" . encode ( ) info . create_system = 0 zfile . writestr ( info , content )
def add_components ( self , components ) : """Adds a list of components to instantiate : param components : The description of components : raise KeyError : Missing component configuration"""
if components : for component in components : self . _components [ component [ "name" ] ] = ( component [ "factory" ] , component . get ( "properties" , { } ) , )
def cmd ( self , fun , * args , ** kwargs ) : '''Call an execution module with the given arguments and keyword arguments . . versionchanged : : 2015.8.0 Added the ` ` cmd ` ` method for consistency with the other Salt clients . The existing ` ` function ` ` and ` ` sminion . functions ` ` interfaces still e...
return self . sminion . functions [ fun ] ( * args , ** kwargs )
def construct_nucmer_cmdline ( fname1 , fname2 , outdir = "." , nucmer_exe = pyani_config . NUCMER_DEFAULT , filter_exe = pyani_config . FILTER_DEFAULT , maxmatch = False , ) : """Returns a tuple of NUCmer and delta - filter commands The split into a tuple was made necessary by changes to SGE / OGE . The delta ...
outsubdir = os . path . join ( outdir , pyani_config . ALIGNDIR [ "ANIm" ] ) outprefix = os . path . join ( outsubdir , "%s_vs_%s" % ( os . path . splitext ( os . path . split ( fname1 ) [ - 1 ] ) [ 0 ] , os . path . splitext ( os . path . split ( fname2 ) [ - 1 ] ) [ 0 ] , ) , ) if maxmatch : mode = "--maxmatch" e...
def get_function ( function_name , composite_function_expression = None ) : """Returns the function " name " , which must be among the known functions or a composite function . : param function _ name : the name of the function ( use ' composite ' if the function is a composite function ) : param composite _ fu...
# Check whether this is a composite function or a simple function if composite_function_expression is not None : # Composite function return _parse_function_expression ( composite_function_expression ) else : if function_name in _known_functions : return _known_functions [ function_name ] ( ) else :...
def request ( cls , name , * args , ** kwargs ) : """Helper method for creating request messages . Parameters name : str The name of the message . args : list of strings The message arguments . Keyword arguments mid : str or None Message ID to use or None ( default ) for no Message ID"""
mid = kwargs . pop ( 'mid' , None ) if len ( kwargs ) > 0 : raise TypeError ( 'Invalid keyword argument(s): %r' % kwargs ) return cls ( cls . REQUEST , name , args , mid )
def convert_into_by_batch ( input_dir , output_format = 'csv' , java_options = None , ** kwargs ) : '''Convert tables from PDFs in a directory . Args : input _ dir ( str ) : Directory path . output _ format ( str , optional ) : Output format of this function ( csv , json or tsv ) java _ options ( list ,...
if input_dir is None or not os . path . isdir ( input_dir ) : raise AttributeError ( "'input_dir' shoud be directory path" ) kwargs [ 'format' ] = _extract_format_for_conversion ( output_format ) if java_options is None : java_options = [ ] elif isinstance ( java_options , str ) : java_options = shlex . spl...
def _get_partial_string_timestamp_match_key ( self , key , labels ) : """Translate any partial string timestamp matches in key , returning the new key ( GH 10331)"""
if isinstance ( labels , MultiIndex ) : if ( isinstance ( key , str ) and labels . levels [ 0 ] . is_all_dates ) : # Convert key ' 2016-01-01 ' to # ( ' 2016-01-01 ' [ , slice ( None , None , None ) ] + ) key = tuple ( [ key ] + [ slice ( None ) ] * ( len ( labels . levels ) - 1 ) ) if isinstance ( ...
def register_gpt_plugin ( self , fs_guid , plugin ) : """Used in plugin ' s registration routine , to associate it ' s detection method with given filesystem guid Args : fs _ guid : filesystem guid that is read from GPT partition entry plugin : plugin that supports this filesystem"""
key = uuid . UUID ( fs_guid . lower ( ) ) self . logger . debug ( 'GPT: {}, GUID: {}' . format ( self . __get_plugin_name ( plugin ) , fs_guid ) ) self . __gpt_plugins [ key ] . append ( plugin )
def client_kill_filter ( self , _id = None , _type = None , addr = None , skipme = None ) : """Disconnects client ( s ) using a variety of filter options : param id : Kills a client by its unique ID field : param type : Kills a client by type where type is one of ' normal ' , ' master ' , ' slave ' or ' pubsu...
args = [ ] if _type is not None : client_types = ( 'normal' , 'master' , 'slave' , 'pubsub' ) if str ( _type ) . lower ( ) not in client_types : raise DataError ( "CLIENT KILL type must be one of %r" % ( client_types , ) ) args . extend ( ( Token . get_token ( 'TYPE' ) , _type ) ) if skipme is not N...
def _load_config ( self , path ) : '''Read the configuration under a specific path and return the object .'''
config = { } log . debug ( 'Reading configuration from %s' , path ) if not os . path . isdir ( path ) : msg = ( 'Unable to read from {path}: ' 'the directory does not exist!' ) . format ( path = path ) log . error ( msg ) raise IOError ( msg ) # The directory tree should look like the following : # ├ ─ ─ _ ...
def read_stack_qwords ( self , count , offset = 0 ) : """Reads QWORDs from the top of the stack . @ type count : int @ param count : Number of QWORDs to read . @ type offset : int @ param offset : Offset from the stack pointer to begin reading . @ rtype : tuple ( int . . . ) @ return : Tuple of integers...
stackData = self . read_stack_data ( count * 8 , offset ) return struct . unpack ( '<' + ( 'Q' * count ) , stackData )
def list_all_addresses ( cls , ** kwargs ) : """List Addresses Return a list of Addresses This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ addresses ( async = True ) > > > result = thread . get ( ) ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_addresses_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_addresses_with_http_info ( ** kwargs ) return data
def update_password ( self , user , password , skip_validation = False ) : """Updates the password of a user"""
pwcol = self . options [ "password_column" ] pwhash = self . bcrypt . generate_password_hash ( password ) if not skip_validation : self . validate_password ( user , password , pwhash ) if self . options [ 'prevent_password_reuse' ] : user . previous_passwords = [ getattr ( user , pwcol ) ] + ( user . previous_p...
def html ( self , data = None , template = None ) : """Send html document to user . Args : - data : Dict to render template , or string with rendered HTML . - template : Name of template to render HTML document with passed data ."""
if data is None : data = { } if template : return render ( self . request , template , data ) return HttpResponse ( data )
def sg_context ( ** kwargs ) : r"""Context helper for computational graph building . Makes all elements within the with Block share the parameters . For example , in the following example , the default value of parameter ` bn ` will be set to True in the all layers within the with block . with tf . sg _ con...
global _context # set options when enter context_now = tf . sg_opt ( kwargs ) _context += [ context_now ] # if named context if context_now . name : context_now . scope_name = context_now . name context_now . name = None with tf . variable_scope ( context_now . scope_name ) : yield else : yield ...
def _populate_comptparms ( self , img_array ) : """Instantiate and populate comptparms structure . This structure defines the image components . Parameters img _ array : ndarray Image data to be written to file ."""
# Only two precisions are possible . if img_array . dtype == np . uint8 : comp_prec = 8 else : comp_prec = 16 numrows , numcols , num_comps = img_array . shape if version . openjpeg_version_tuple [ 0 ] == 1 : comptparms = ( opj . ImageComptParmType * num_comps ) ( ) else : comptparms = ( opj2 . ImageCom...
def computePerturbedFreeEnergies ( self , u_ln , compute_uncertainty = True , uncertainty_method = None , warning_cutoff = 1.0e-10 ) : """Compute the free energies for a new set of states . Here , we desire the free energy differences among a set of new states , as well as the uncertainty estimates in these diffe...
# Convert to np matrix . u_ln = np . array ( u_ln , dtype = np . float64 ) # Get the dimensions of the matrix of reduced potential energies , and convert if necessary if len ( np . shape ( u_ln ) ) == 3 : u_ln = kln_to_kn ( u_ln , N_k = self . N_k ) [ L , N ] = u_ln . shape # Check dimensions . if ( N < self . N ) ...
def elaborate ( self , top_def_name = None , inst_name = None , parameters = None ) : """Elaborates the design for the given top - level addrmap component . During elaboration , the following occurs : - An instance of the ` ` $ root ` ` meta - component is created . - The addrmap component specified by ` ` to...
if parameters is None : parameters = { } # Get top - level component definition to elaborate if top_def_name is not None : # Lookup top _ def _ name if top_def_name not in self . root . comp_defs : self . msg . fatal ( "Elaboration target '%s' not found" % top_def_name ) top_def = self . root . comp...
def flush_stream_threads ( process , out_formatter = None , err_formatter = terminal . fg . red , size = 1 ) : """Context manager that creates 2 threads , one for each standard stream ( stdout / stderr ) , updating in realtime the piped data . The formatters are callables that receives manipulates the data , ...
out = FlushStreamThread ( process = process , stream_name = "stdout" , formatter = out_formatter , size = size ) err = FlushStreamThread ( process = process , stream_name = "stderr" , formatter = err_formatter , size = size ) out . start ( ) err . start ( ) yield out , err out . join ( ) err . join ( )
def add ( cls , user , permissions , automation , api = None ) : """Add a member to the automation . : param user : Member username : param permissions : Permissions dictionary . : param automation : Automation object or id : param api : sevenbridges Api instance : return : Automation member object ."""
user = Transform . to_user ( user ) automation = Transform . to_automation ( automation ) api = api or cls . _API data = { 'username' : user } if isinstance ( permissions , dict ) : data . update ( { 'permissions' : permissions } ) member_data = api . post ( url = cls . _URL [ 'query' ] . format ( automation_id = a...
def show_message ( self ) : """Show message updatable ."""
print ( 'current version: {current_version}\n' 'latest version : {latest_version}' . format ( current_version = self . current_version , latest_version = self . latest_version ) )
def _str2datetime ( self , datetime_str ) : """Parse datetime from string . If there ' s no template matches your string , Please go https : / / github . com / MacHu - GWU / rolex - project / issues submit your datetime string . I ' ll update templates ASAP . This method is faster than : meth : ` dateutil ....
# try default datetime template try : a_datetime = datetime . strptime ( datetime_str , self . _default_datetime_template ) return a_datetime except : pass # try every datetime templates for template in datetime_template_list : try : a_datetime = datetime . strptime ( datetime_str , template ) ...
def power_down ( self , wakeup_enable ) : """Send the PowerDown command to put the PN531 ( including the contactless analog front end ) into power down mode in order to save power consumption . The * wakeup _ enable * argument must be a list of wake up sources with values from the : data : ` power _ down _ ...
wakeup_set = 0 for i , src in enumerate ( self . power_down_wakeup_sources ) : if src in wakeup_enable : wakeup_set |= 1 << i data = self . command ( 0x16 , chr ( wakeup_set ) , timeout = 0.1 ) if data [ 0 ] != 0 : self . chipset_error ( data )
def _path ( self , key ) : """Get the full path for the given cache key . : param key : The cache key : type key : str : rtype : str"""
hash_type , parts_count = self . _HASHES [ self . _hash_type ] h = hash_type ( encode ( key ) ) . hexdigest ( ) parts = [ h [ i : i + 2 ] for i in range ( 0 , len ( h ) , 2 ) ] [ : parts_count ] return os . path . join ( self . _directory , os . path . sep . join ( parts ) , h )
def request ( self , path , params = None , returns_json = True , method = 'POST' , api_version = API_VERSION ) : '''Process a request using the OAuth client ' s request method . : param str path : Path fragment to the API endpoint , e . g . " resource / ID " : param dict params : Parameters to pass to request ...
time . sleep ( REQUEST_DELAY_SECS ) full_path = '/' . join ( [ BASE_URL , 'api/%s' % api_version , path ] ) params = urlencode ( params ) if params else None log . debug ( 'URL: %s' , full_path ) request_kwargs = { 'method' : method } if params : request_kwargs [ 'body' ] = params response , content = self . oauth_...
def handler ( init , exposes , version = None ) : """Simple handler with default ` peek ` and ` poke ` procedures . Arguments : init ( callable ) : type constructor . exposes ( iterable ) : attributes to be ( de - ) serialized . version ( tuple ) : version number . Returns : StorableHandler : storable h...
return StorableHandler ( poke = poke ( exposes ) , peek = peek ( init , exposes ) , version = version )
def print_values ( self , parameter ) : """Print the list of values for the given parameter and exit . If ` ` parameter ` ` is invalid , print the list of parameter names that have allowed values . : param parameter : the parameter name : type parameter : Unicode string"""
if parameter in self . VALUES : self . print_info ( u"Available values for parameter '%s':" % parameter ) self . print_generic ( u"\n" . join ( self . VALUES [ parameter ] ) ) return self . HELP_EXIT_CODE if parameter not in [ u"?" , u"" ] : self . print_error ( u"Invalid parameter name '%s'" % paramete...
def ball_and_stick ( target , pore_area = 'pore.area' , throat_area = 'throat.area' , pore_diameter = 'pore.diameter' , throat_diameter = 'throat.diameter' , conduit_lengths = 'throat.conduit_lengths' ) : r"""Calculate conduit shape factors for hydraulic conductance , assuming pores and throats are spheres ( ball...
_np . warnings . filterwarnings ( 'ignore' , category = RuntimeWarning ) network = target . project . network throats = network . map_throats ( throats = target . Ts , origin = target ) cn = network [ 'throat.conns' ] [ throats ] # Get pore diameter D1 = network [ pore_diameter ] [ cn [ : , 0 ] ] D2 = network [ pore_di...
def config ( self ) : """Config resolution order : if this is a dependency model : - own project config - in - model config - active project config if this is a top - level model : - active project config - in - model config"""
defaults = { "enabled" : True , "materialized" : "view" } if self . node_type == NodeType . Seed : defaults [ 'materialized' ] = 'seed' elif self . node_type == NodeType . Archive : defaults [ 'materialized' ] = 'archive' active_config = self . load_config_from_active_project ( ) if self . active_project . proj...
def get ( self , rule , default = None ) : """Return the existing version of the given rule . If the rule is not present in the classifier set , return the default . If no default was given , use None . This is useful for eliminating duplicate copies of rules . Usage : unique _ rule = model . get ( possib...
assert isinstance ( rule , ClassifierRule ) if ( rule . condition not in self . _population or rule . action not in self . _population [ rule . condition ] ) : return default return self . _population [ rule . condition ] [ rule . action ]
async def prover_search_credentials ( wallet_handle : int , query_json : str ) -> ( int , int ) : """Search for credentials stored in wallet . Credentials can be filtered by tags created during saving of credential . Instead of immediately returning of fetched credentials this call returns search _ handle that ...
logger = logging . getLogger ( __name__ ) logger . debug ( "prover_search_credentials: >>> wallet_handle: %r, query_json: %r" , wallet_handle , query_json ) if not hasattr ( prover_search_credentials , "cb" ) : logger . debug ( "prover_search_credentials: Creating callback" ) prover_search_credentials . cb = cr...
def load_orthologs ( fo : IO , metadata : dict ) : """Load orthologs into ArangoDB Args : fo : file obj - orthologs file metadata : dict containing the metadata for orthologs"""
version = metadata [ "metadata" ] [ "version" ] # LOAD ORTHOLOGS INTO ArangoDB with timy . Timer ( "Load Orthologs" ) as timer : arango_client = arangodb . get_client ( ) belns_db = arangodb . get_belns_handle ( arango_client ) arangodb . batch_load_docs ( belns_db , orthologs_iterator ( fo , version ) , on...
def uand ( self ) : """Unary AND reduction operator"""
return reduce ( operator . and_ , self . _items , self . ftype . box ( 1 ) )
def render ( self ) : """Render report to HTML"""
template = self . get_template ( ) return template . render ( messages = self . _messages , metrics = self . metrics , report = self )
def eof ( ) : '''Parser EOF flag of a string .'''
@ Parser def eof_parser ( text , index = 0 ) : if index >= len ( text ) : return Value . success ( index , None ) else : return Value . failure ( index , 'EOF' ) return eof_parser
def store ( bank , key , data ) : '''Store a key value .'''
_init_client ( ) data = __context__ [ 'serial' ] . dumps ( data ) query = b"REPLACE INTO {0} (bank, etcd_key, data) values('{1}', '{2}', " b"'{3}')" . format ( _table_name , bank , key , data ) cur , cnt = run_query ( client , query ) cur . close ( ) if cnt not in ( 1 , 2 ) : raise SaltCacheError ( 'Error storing {...
def new_tbl ( cls , rows , cols , width , height , tableStyleId = None ) : """Return a new ` ` < p : tbl > ` ` element tree ."""
# working hypothesis is this is the default table style GUID if tableStyleId is None : tableStyleId = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}' xml = cls . _tbl_tmpl ( ) % ( tableStyleId ) tbl = parse_xml ( xml ) # add specified number of rows and columns rowheight = height // rows colwidth = width // cols for col i...
def wrap_function ( self , func ) : """Wrap a function to timestamp it ."""
def f ( * args , ** kwds ) : # Start time timestamps = [ _get_memory ( os . getpid ( ) , timestamps = True ) ] self . functions [ func ] . append ( timestamps ) try : result = func ( * args , ** kwds ) finally : # end time timestamps . append ( _get_memory ( os . getpid ( ) , timestamps ...
def do_shell ( self , args : argparse . Namespace ) -> None : """Execute a command as if at the OS prompt"""
import subprocess # Create a list of arguments to shell tokens = [ args . command ] + args . command_args # Support expanding ~ in quoted paths for index , _ in enumerate ( tokens ) : if tokens [ index ] : # Check if the token is quoted . Since parsing already passed , there isn ' t # an unclosed quote . So we ...
def get_forecast ( self , latitude , longitude ) : """Gets the weather data from darksky api and stores it in the respective dictionaries if available . This function should be used to fetch weather information ."""
reply = self . http_get ( self . url_builder ( latitude , longitude ) ) self . forecast = json . loads ( reply ) for item in self . forecast . keys ( ) : setattr ( self , item , self . forecast [ item ] )
def clean_description ( self ) : """Text content validation"""
description = self . cleaned_data . get ( "description" ) validation_helper = safe_import_module ( settings . FORUM_TEXT_VALIDATOR_HELPER_PATH ) if validation_helper is not None : return validation_helper ( self , description ) else : return description
def template_exists ( form , field ) : """Form validation : check that selected template exists ."""
try : current_app . jinja_env . get_template ( field . data ) except TemplateNotFound : raise ValidationError ( _ ( "Template selected does not exist" ) )
def _get_property_for ( self , p , indexed = True , depth = 0 ) : """Internal helper to get the Property for a protobuf - level property ."""
parts = p . name ( ) . split ( '.' ) if len ( parts ) <= depth : # Apparently there ' s an unstructured value here . # Assume it is a None written for a missing value . # ( It could also be that a schema change turned an unstructured # value into a structured one . In that case , too , it seems # better to return None ...
def validate_seeded_answers ( answers , options , algo ) : """Validate answers based on selection algorithm This is called when instructor setup the tool and providing seeded answers to the question . This function is trying to validate if instructor provided enough seeds for a give algorithm . e . g . we req...
if algo [ 'name' ] == 'simple' : return validate_seeded_answers_simple ( answers , options , algo ) elif algo [ 'name' ] == 'random' : return validate_seeded_answers_random ( answers ) else : raise UnknownChooseAnswerAlgorithm ( )
def connection ( filepath = None , section = 'oep' ) : """Instantiate a database connection ( for the use with SQLAlchemy ) . The keyword argument ` filepath ` specifies the location of the config file that contains database connection information . If not given , the default of ` ~ / . egoio / config . ini `...
# define default filepath if not provided if filepath is None : filepath = os . path . join ( os . path . expanduser ( "~" ) , '.egoio' , 'config.ini' ) # does the file exist ? if not os . path . isfile ( filepath ) : print ( 'DB config file {file} not found. ' 'This might be the first run of the tool. ' . form...
def get_field ( self , name ) : """Gets the XML field object of the given name ."""
# Quicker in case the exact name was used . field = self . _all_fields . get ( name ) if field is not None : return field for field_name , field in self . _all_fields . items ( ) : if self . _sanitize_field_name ( name ) == self . _sanitize_field_name ( field_name ) : return field
def pretty ( self , verbose = 0 ) : """Return pretty list description of parameter"""
# split prompt lines and add blanks in later lines to align them plines = self . prompt . split ( '\n' ) for i in range ( len ( plines ) - 1 ) : plines [ i + 1 ] = 32 * ' ' + plines [ i + 1 ] plines = '\n' . join ( plines ) namelen = min ( len ( self . name ) , 12 ) pvalue = self . get ( prompt = 0 , lpar = 1 ) alw...
def dim_axis_label ( dimensions , separator = ', ' ) : """Returns an axis label for one or more dimensions ."""
if not isinstance ( dimensions , list ) : dimensions = [ dimensions ] return separator . join ( [ d . pprint_label for d in dimensions ] )
def _filter_repeating_items ( download_list ) : """Because of data _ filter some requests in download list might be the same . In order not to download them again this method will reduce the list of requests . It will also return a mapping list which can be used to reconstruct the previous list of download requ...
unique_requests_map = { } mapping_list = [ ] unique_download_list = [ ] for download_request in download_list : if download_request not in unique_requests_map : unique_requests_map [ download_request ] = len ( unique_download_list ) unique_download_list . append ( download_request ) mapping_list...
async def create_scene_member ( self , shade_position , scene_id , shade_id ) : """Adds a shade to an existing scene"""
data = { ATTR_SCENE_MEMBER : { ATTR_POSITION_DATA : shade_position , ATTR_SCENE_ID : scene_id , ATTR_SHADE_ID : shade_id , } } return await self . request . post ( self . _base_path , data = data )
def register_animation ( self , animation_class ) : """Add a new animation"""
self . state . animationClasses . append ( animation_class ) return len ( self . state . animationClasses ) - 1
def pluralize ( self , measure , singular , plural ) : """Returns a string that contains the measure ( amount ) and its plural or singular form depending on the amount . Parameters : : param measure : Amount , value , always a numerical value : param singular : The singular form of the chosen word : param...
if measure == 1 : return "{} {}" . format ( measure , singular ) else : return "{} {}" . format ( measure , plural )
def create_from_response_pdu ( resp_pdu , req_pdu ) : """Create instance from response PDU . Response PDU is required together with the number of registers read . : param resp _ pdu : Byte array with request PDU . : param quantity : Number of coils read . : return : Instance of : class : ` ReadCoils ` ."""
read_holding_registers = ReadHoldingRegisters ( ) read_holding_registers . quantity = struct . unpack ( '>H' , req_pdu [ - 2 : ] ) [ 0 ] read_holding_registers . byte_count = struct . unpack ( '>B' , resp_pdu [ 1 : 2 ] ) [ 0 ] fmt = '>' + ( conf . TYPE_CHAR * read_holding_registers . quantity ) read_holding_registers ....
def plot ( self , x , y , panel = None , ** kws ) : """plot after clearing current plot"""
if panel is None : panel = self . current_panel opts = { } opts . update ( self . default_panelopts ) opts . update ( kws ) self . panels [ panel ] . plot ( x , y , ** opts )
def air_dps ( self ) -> Union [ int , float ] : """Does not include upgrades"""
if self . _weapons : weapon = next ( ( weapon for weapon in self . _weapons if weapon . type in { TargetType . Air . value , TargetType . Any . value } ) , None , ) if weapon : return ( weapon . damage * weapon . attacks ) / weapon . speed return 0
def get_next_token ( self , length = 15 , ** kwargs ) : """Gets the next available token . : param length : length of the token : param kwargs : additional filter criteria to check for when looking for a unique token ."""
return self . get_available_tokens ( count = 1 , token_length = length , ** kwargs ) [ 0 ]