signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_distance_term ( self , C , rjb , mag ) : """Returns the general distance scaling term - equation 2"""
c_3 = self . _get_anelastic_coeff ( C ) rval = np . sqrt ( rjb ** 2. + C [ "h" ] ** 2. ) return ( C [ "c1" ] + C [ "c2" ] * ( mag - self . CONSTS [ "Mref" ] ) ) * np . log ( rval / self . CONSTS [ "Rref" ] ) + c_3 * ( rval - self . CONSTS [ "Rref" ] )
def _get_station_codes ( self , force = False ) : """Gets and caches a list of station codes optionally within a bbox . Will return the cached version if it exists unless force is True ."""
if not force and self . station_codes is not None : return self . station_codes state_urls = self . _get_state_urls ( ) # filter by bounding box against a shapefile state_matches = None if self . bbox : with collection ( os . path . join ( "resources" , "ne_50m_admin_1_states_provinces_lakes_shp.shp" , ) , "r" ...
def parse_value ( v , parser , config , description ) : """Convert a string received on the command - line into a value or None . : param str v : The value to parse . : param parser : The fallback callable to load the value if loading from scheme fails . : param dict config : The config to use . :...
val = None if v == '' : return if v is not None : try : val = load_value_from_schema ( v ) except Exception as e : six . raise_from ( CertifierTypeError ( message = '{kind}' . format ( description = description , kind = type ( v ) . __name__ , ) , required = config [ 'required' ] , value = v...
def releases ( self ) : """The releases for this app ."""
return self . _h . _get_resources ( resource = ( 'apps' , self . name , 'releases' ) , obj = Release , app = self )
async def get_first_search_result ( self , term : str ) : """Get first search result . This function will parse the information from the link that search _ novel _ updates returns and then return it as a dictionary : param term : The novel to search for and parse"""
# Uses the other method in the class # to search the search page for the actual page that we want to_parse = await self . get_search_page ( term ) async with self . session . get ( to_parse ) as response : # If the response is OK if response . status == 200 : # The information to parse parse_info = Beautifu...
def get_matcher ( self , reqt ) : """Get a version matcher for a requirement . : param reqt : The requirement : type reqt : str : return : A version matcher ( an instance of : class : ` distlib . version . Matcher ` ) ."""
try : matcher = self . scheme . matcher ( reqt ) except UnsupportedVersionError : # pragma : no cover # XXX compat - mode if cannot read the version name = reqt . split ( ) [ 0 ] matcher = self . scheme . matcher ( name ) return matcher
def start_parallel ( self ) : """Prepare threads to run tasks"""
for _ in range ( self . num_threads ) : Worker ( self . tasks_queue , self . results_queue , self . exceptions_queue )
def claim_keys ( self , key_request , timeout = None ) : """Claims one - time keys for use in pre - key messages . Args : key _ request ( dict ) : The keys to be claimed . Format should be < user _ id > : { < device _ id > : < algorithm > } . timeout ( int ) : Optional . The time ( in milliseconds ) to wait...
content = { "one_time_keys" : key_request } if timeout : content [ "timeout" ] = timeout return self . _send ( "POST" , "/keys/claim" , content = content )
def has_flag ( compiler , flagname ) : """Return a boolean indicating whether a flag name is supported on the specified compiler ."""
with TemporaryDirectory ( ) as tmpdir , stdchannel_redirected ( sys . stderr , os . devnull ) , stdchannel_redirected ( sys . stdout , os . devnull ) : f = tempfile . mktemp ( suffix = '.cpp' , dir = tmpdir ) with open ( f , 'w' ) as fh : fh . write ( 'int main (int argc, char **argv) { return 0; }' ) ...
def createReader ( clazz , readername ) : """Static method to create a reader from a reader clazz . @ param clazz : the reader class name @ param readername : the reader name"""
if not clazz in ReaderFactory . factories : ReaderFactory . factories [ clazz ] = get_class ( clazz ) . Factory ( ) return ReaderFactory . factories [ clazz ] . create ( readername )
def get_ci ( theta_star , blockratio = 1.0 ) : """Get the confidence interval ."""
# get rid of nans while we sort b_star = np . sort ( theta_star [ ~ np . isnan ( theta_star ) ] ) se = np . std ( b_star ) * np . sqrt ( blockratio ) # bootstrap 95 % CI based on empirical percentiles ci = [ b_star [ int ( len ( b_star ) * .025 ) ] , b_star [ int ( len ( b_star ) * .975 ) ] ] return ci
def __find_new ( self , hueobjecttype ) : '''Starts a search for new Hue objects'''
assert hueobjecttype in [ 'lights' , 'sensors' ] , 'Unsupported object type {}' . format ( hueobjecttype ) url = '{}/{}' . format ( self . API , hueobjecttype ) return self . _request ( method = 'POST' , url = url )
def step ( self , t , x_im1 , v_im1_2 , dt ) : """Step forward the positions and velocities by the given timestep . Parameters dt : numeric The timestep to move forward ."""
x_i = x_im1 + v_im1_2 * dt F_i = self . F ( t , np . vstack ( ( x_i , v_im1_2 ) ) , * self . _func_args ) a_i = F_i [ self . ndim : ] v_i = v_im1_2 + a_i * dt / 2 v_ip1_2 = v_i + a_i * dt / 2 return x_i , v_i , v_ip1_2
def add_graph_copy ( self , graph , tags = None ) : """Adds a copy of Graph with the specified set of tags ."""
with graph . as_default ( ) : # Remove default attrs so that Modules created by a tensorflow version # with ops that have new attrs that are left to their default values can # still be loaded by older versions unware of those attributes . meta_graph = tf_v1 . train . export_meta_graph ( strip_default_attrs = True )...
def _validate_templates ( self , templates ) : """: param templates : : return :"""
if templates is None : return templates if not isinstance ( templates , list ) : raise TypeError ( logger . error ( "templates should be a list." ) ) for template in templates : if not isinstance ( template , dict ) : raise TypeError ( logger . error ( "each item to be injected must be a dict." ) ) ...
def _get ( self , api_call , params = None , method = 'GET' , auth = False , file_ = None ) : """Function to preapre API call . Parameters : api _ call ( str ) : API function to be called . params ( str ) : API function parameters . method ( str ) : ( Defauld : GET ) HTTP method ( GET , POST , PUT or DELE...
url = "{0}/{1}" . format ( self . site_url , api_call ) if method == 'GET' : request_args = { 'params' : params } else : request_args = { 'data' : params , 'files' : file_ } # Adds auth . Also adds auth if username and api _ key are specified # Members + have less restrictions if auth or ( self . username and s...
def parse_wyckoff_csv ( wyckoff_file ) : """Parse Wyckoff . csv There are 530 data sets . For one example : 9 : C 1 2 1 : : : : : : : 4 : c : 1 : ( x , y , z ) : ( - x , y , - z ) : : : : 2 : b : 2 : ( 0 , y , 1/2 ) : : : : : 2 : a : 2 : ( 0 , y , 0 ) : : :"""
rowdata = [ ] points = [ ] hP_nums = [ 433 , 436 , 444 , 450 , 452 , 458 , 460 ] for i , line in enumerate ( wyckoff_file ) : if line . strip ( ) == 'end of data' : break rowdata . append ( line . strip ( ) . split ( ':' ) ) # 2 : P - 1 : : : : : < - - store line number if first element is number ...
def edit ( parent , profile ) : """Edits the given profile . : param parent | < QWidget > profile | < projexui . widgets . xviewwidget . XViewProfile > : return < bool >"""
dlg = XViewProfileDialog ( parent ) dlg . setProfile ( profile ) if ( dlg . exec_ ( ) ) : return True return False
def get_pair ( self ) : """Get the F2L pair ( corner , edge ) ."""
colours = ( self . cube [ self . pair [ 0 ] ] . colour , self . cube [ self . pair [ 1 ] ] . colour , self . cube [ "D" ] . colour ) result_corner = self . cube . children . copy ( ) for c in colours [ : 2 ] : result_corner &= self . cube . has_colour ( c ) result_edge = result_corner & self . cube . select_type ( ...
def pick_best_coinc ( cls , coinc_results ) : """Choose the best two - ifo coinc by ifar first , then statistic if needed . This function picks which of the available double - ifo coincs to use . It chooses the best ( highest ) ifar . The ranking statistic is used as a tie - breaker . A trials factor is app...
mstat = 0 mifar = 0 mresult = None # record the trials factor from the possible coincs we could # maximize over trials = 0 for result in coinc_results : # Check that a coinc was possible . See the ' add _ singles ' method # to see where this flag was added into the results dict if 'coinc_possible' in result : ...
def _paddr ( ins ) : """Returns code sequence which points to local variable or parameter ( HL )"""
output = [ ] oper = ins . quad [ 1 ] indirect = ( oper [ 0 ] == '*' ) if indirect : oper = oper [ 1 : ] I = int ( oper ) if I >= 0 : I += 4 # Return Address + " push IX " output . append ( 'push ix' ) output . append ( 'pop hl' ) output . append ( 'ld de, %i' % I ) output . append ( 'add hl, de' ) if indirect :...
def _add_exac ( self , variant_obj , info_dict ) : """Add the gmaf frequency Args : variant _ obj ( puzzle . models . Variant ) info _ dict ( dict ) : A info dictionary"""
exac = None exac_keys = [ 'ExAC' , 'EXAC' , 'ExACAF' , 'EXACAF' ] for key in exac_keys : if info_dict . get ( key ) : exac = float ( info_dict [ key ] ) # If not found in vcf search transcripts if not exac : for transcript in variant_obj . transcripts : exac_raw = transcript . ExAC_MAF i...
def _children ( self ) : """Yield all direct children of this object ."""
if isinstance ( self . condition , CodeExpression ) : yield self . condition for codeobj in self . body . _children ( ) : yield codeobj for codeobj in self . else_body . _children ( ) : yield codeobj
def logger ( self ) : '''Lazy logger'''
if self . __logger is None : self . __logger = logging . getLogger ( self . __name ) return self . __logger
def receive_verify_post ( self , post_params ) : """Returns true if the incoming request is an authenticated verify post ."""
if isinstance ( post_params , dict ) : required_params = [ 'action' , 'email' , 'send_id' , 'sig' ] if not self . check_for_valid_postback_actions ( required_params , post_params ) : return False else : return False if post_params [ 'action' ] != 'verify' : return False sig = post_params [ 'sig'...
def user_getfield ( self , field , access_token = None ) : """Request a single field of information about the user . : param field : The name of the field requested . : type field : str : returns : The value of the field . Depending on the type , this may be a string , list , dict , or something else . : ...
info = self . user_getinfo ( [ field ] , access_token ) return info . get ( field )
def run ( ) : """CLI main entry point ."""
# Use print ( ) instead of logging when running in CLI mode : set_pyftpsync_logger ( None ) parser = argparse . ArgumentParser ( description = "Synchronize folders over FTP." , epilog = "See also https://github.com/mar10/pyftpsync" , parents = [ verbose_parser ] , ) # Note : we want to allow - - version to be combined ...
def _revint ( self , version ) : '''Internal function to convert a version string to an integer .'''
intrev = 0 vsplit = version . split ( '.' ) for c in range ( len ( vsplit ) ) : item = int ( vsplit [ c ] ) * ( 10 ** ( ( ( len ( vsplit ) - c - 1 ) * 2 ) ) ) intrev += item return intrev
def _prepare_commit_msg ( tmp_file , author , files_modified = None , template = None ) : """Prepare the commit message in tmp _ file . It will build the commit message prefilling the component line , as well as the signature using the git author and the modified files . The file remains untouched if it is no...
files_modified = files_modified or [ ] template = template or "{component}:\n\nSigned-off-by: {author}\n{extra}" if hasattr ( template , "decode" ) : template = template . decode ( ) with open ( tmp_file , "r" , "utf-8" ) as fh : contents = fh . readlines ( ) msg = filter ( lambda x : not ( x . startswith (...
def key_file ( self ) : """Get the path to the key file containig our auth key , or None ."""
if self . auth_key : key_file_path = os . path . join ( orchestration_mkdtemp ( ) , 'key' ) with open ( key_file_path , 'w' ) as fd : fd . write ( self . auth_key ) os . chmod ( key_file_path , stat . S_IRUSR ) return key_file_path
def set_key ( dotenv_path , key_to_set , value_to_set , quote_mode = "always" ) : """Adds or Updates a key / value to the given . env If the . env path given doesn ' t exist , fails instead of risking creating an orphan . env somewhere in the filesystem"""
value_to_set = value_to_set . strip ( "'" ) . strip ( '"' ) if not os . path . exists ( dotenv_path ) : warnings . warn ( "can't write to %s - it doesn't exist." % dotenv_path ) return None , key_to_set , value_to_set if " " in value_to_set : quote_mode = "always" line_template = '{}="{}"\n' if quote_mode =...
def wait_for_deps ( self , conf , images ) : """Wait for all our dependencies"""
from harpoon . option_spec . image_objs import WaitCondition api = conf . harpoon . docker_context_maker ( ) . api waited = set ( ) last_attempt = { } dependencies = set ( dep for dep , _ in conf . dependency_images ( ) ) # Wait conditions come from dependency _ options first # Or if none specified there , they come fr...
def learnSequences ( self , sequences ) : """Learns all provided sequences . Always reset the network in between sequences . Sequences format : sequences = [ set ( [ 16 , 22 , 32 ] ) , # S0 , position 0 set ( [ 13 , 15 , 33 ] ) # S0 , position 1 set ( [ 6 , 12 , 52 ] ) , # S1 , position 0 set ( [ 6 , ...
# This method goes through four phases : # 1 ) We first train L4 on the sequences , over multiple passes # 2 ) We then train L2 in one pass . # 3 ) We then continue training on L4 so the apical segments learn # 4 ) We run inference to store L2 representations for each sequence # retrieve L2 representations # print " 1 ...
def set_action_cache ( self , action_key , data ) : """Store action needs and excludes . . . note : : The action is saved only if a cache system is defined . : param action _ key : The unique action name . : param data : The action to be saved ."""
if self . cache : self . cache . set ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key , data )
def events ( self ) : """: rtype : twilio . rest . monitor . v1 . event . EventList"""
if self . _events is None : self . _events = EventList ( self ) return self . _events
def fetchMyCgi ( self ) : """Fetches statistics from my _ cgi . cgi"""
try : response = urlopen ( Request ( 'http://{}/my_cgi.cgi' . format ( self . ip ) , b'request=create_chklst' ) ) ; except ( HTTPError , URLError ) : _LOGGER . warning ( "Failed to open url to {}" . format ( self . ip ) ) self . _error_report = True return None lines = response . readlines ( ) return { ...
def array_scanlines_interlace ( self , pixels ) : """Generator for interlaced scanlines from an array . ` pixels ` is the full source image as a single array of values . The generator yields each scanline of the reduced passes in turn , each scanline being a sequence of values ."""
# http : / / www . w3 . org / TR / PNG / # 8InterlaceMethods # Array type . fmt = 'BH' [ self . bitdepth > 8 ] # Value per row vpr = self . width * self . planes # Each iteration generates a scanline starting at ( x , y ) # and consisting of every xstep pixels . for lines in adam7_generate ( self . width , self . heigh...
def on_message ( self , client , userdata , msg ) : '''Callback for when a ` ` PUBLISH ` ` message is received from the broker .'''
if msg . topic == 'serial_device/refresh_comports' : self . refresh_comports ( ) return match = CRE_MANAGER . match ( msg . topic ) if match is None : logger . debug ( 'Topic NOT matched: `%s`' , msg . topic ) else : logger . debug ( 'Topic matched: `%s`' , msg . topic ) # Message topic matches comm...
def wait_for_mouse_move_from ( self , origin_x , origin_y ) : """Wait for the mouse to move from a location . This function will block until the condition has been satisified . : param origin _ x : the X position you expect the mouse to move from : param origin _ y : the Y position you expect the mouse to mov...
_libxdo . xdo_wait_for_mouse_move_from ( self . _xdo , origin_x , origin_y )
def _decode_telegram_base64 ( string ) : """Decodes an url - safe base64 - encoded string into its bytes by first adding the stripped necessary padding characters . This is the way Telegram shares binary data as strings , such as Bot API - style file IDs or invite links . Returns ` ` None ` ` if the input s...
try : return base64 . urlsafe_b64decode ( string + '=' * ( len ( string ) % 4 ) ) except ( binascii . Error , ValueError , TypeError ) : return None
def filter ( self , userinfo , user_info_claims = None ) : """Return only those claims that are asked for . It ' s a best effort task ; if essential claims are not present no error is flagged . : param userinfo : A dictionary containing the available info for one user : param user _ info _ claims : A dictio...
if user_info_claims is None : return copy . copy ( userinfo ) else : result = { } missing = [ ] optional = [ ] for key , restr in user_info_claims . items ( ) : try : result [ key ] = userinfo [ key ] except KeyError : if restr == { "essential" : True } : ...
def add_papyrus_routes ( self , route_name_prefix , base_url ) : """A helper method that adds routes to view callables that , together , implement the MapFish HTTP interface . Example : : import papyrus config . include ( papyrus ) config . add _ papyrus _ routes ( ' spots ' , ' / spots ' ) config . sca...
route_name = route_name_prefix + '_read_many' self . add_route ( route_name , base_url , request_method = 'GET' ) route_name = route_name_prefix + '_read_one' self . add_route ( route_name , base_url + '/{id}' , request_method = 'GET' ) route_name = route_name_prefix + '_count' self . add_route ( route_name , base_url ...
def set_meta ( self , meta_data ) : '''node . set _ meta ( meta ) yields a calculation node identical to the given node except that its meta _ data attribute has been set to the given dictionary meta . If meta is not persistent , it is cast to a persistent dictionary first .'''
if not ( isinstance ( meta_data , ps . PMap ) or isinstance ( meta_data , IMap ) ) : meta_data = ps . pmap ( meta_data ) new_cnode = copy . copy ( self ) object . __setattr__ ( new_cnode , 'meta_data' , meta_data ) return new_cnode
def get_semantic_data ( self , path_as_list ) : """Retrieves an entry of the semantic data . : param list path _ as _ list : The path in the vividict to retrieve the value from : return :"""
target_dict = self . semantic_data for path_element in path_as_list : if path_element in target_dict : target_dict = target_dict [ path_element ] else : raise KeyError ( "The state with name {1} and id {2} holds no semantic data with path {0}." "" . format ( path_as_list [ : path_as_list . index...
def create_named_notebook ( fname , context ) : """Create a named notebook if one doesn ' t exist ."""
if os . path . exists ( fname ) : return from nbformat import v4 as nbf # Courtesy of http : / / nbviewer . ipython . org / gist / fperez / 9716279 text = "Welcome to *pyramid_notebook!* Use *File* *>* *Shutdown* to close this." cells = [ nbf . new_markdown_cell ( text ) ] greeting = context . get ( "greeting" ) if...
def recordParser ( paper ) : """This is function that is used to create [ Records ] ( . . / classes / Record . html # metaknowledge . Record ) from files . * * recordParser * * ( ) reads the file _ paper _ until it reaches ' ER ' . For each field tag it adds an entry to the returned dict with the tag as the key a...
tagList = [ ] doneReading = False l = ( 0 , '' ) for l in paper : if len ( l [ 1 ] ) < 3 : # Line too short raise BadWOSRecord ( "Missing field on line {} : {}" . format ( l [ 0 ] , l [ 1 ] ) ) elif 'ER' in l [ 1 ] [ : 2 ] : # Reached the end of the record doneReading = True break el...
def updateData ( self , signal , fs ) : """Displays a spectrogram of the provided signal : param signal : 1 - D signal of audio : type signal : numpy . ndarray : param fs : samplerate of signal : type fs : int"""
# use a separate thread to calculate spectrogram so UI doesn ' t lag t = threading . Thread ( target = _doSpectrogram , args = ( self . spec_done , ( fs , signal ) , ) , kwargs = self . specgramArgs ) t . start ( )
def _patched_method ( self , method , * args , ** kwargs ) : """Step 4 ( 1st flow ) . Call method"""
self . _validate ( ) result = method ( * args , ** kwargs ) self . _validate ( ) return result
def returnDepositsWithdrawals ( self , start = 0 , end = 2 ** 32 - 1 ) : """Returns your deposit and withdrawal history within a range , specified by the " start " and " end " POST parameters , both of which should be given as UNIX timestamps ."""
return self . _private ( 'returnDepositsWithdrawals' , start = start , end = end )
def vnic_add_new_to_vm_task ( vm , network , logger ) : """Compose new vNIC and attach it to VM & connect to Network : param nicspec : < vim . vm . VM > : param network : < vim network obj > : return : < Task >"""
nicspes = VNicService . vnic_new_attached_to_network ( network ) task = VNicService . vnic_add_to_vm_task ( nicspes , vm , logger ) return task
def make_pass_decorator ( object_type , ensure = False ) : """Given an object type this creates a decorator that will work similar to : func : ` pass _ obj ` but instead of passing the object of the current context , it will find the innermost context of type : func : ` object _ type ` . This generates a de...
def decorator ( f ) : def new_func ( * args , ** kwargs ) : ctx = get_current_context ( ) if ensure : obj = ctx . ensure_object ( object_type ) else : obj = ctx . find_object ( object_type ) if obj is None : raise RuntimeError ( 'Managed to invoke ...
def add_to_space_size ( self , addition_bytes ) : # type : ( int ) - > None '''A method to add bytes to the space size tracked by this Volume Descriptor . Parameters : addition _ bytes - The number of bytes to add to the space size . Returns : Nothing .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'This Volume Descriptor is not yet initialized' ) # The ' addition ' parameter is expected to be in bytes , but the space # size we track is in extents . Round up to the next extent . self . space_size += utils . ceiling_div ( addition_byt...
def start_module ( self ) : """Wrapper for _ main function . Catch and raise any exception occurring in the main function : return : None"""
try : self . _main ( ) except Exception as exp : logger . exception ( '%s' , traceback . format_exc ( ) ) raise Exception ( exp )
def adjust_logging ( self , context ) : """Adjust logging configuration . : param context : The guacamole context object . This method uses the context and the results of early argument parsing to adjust the configuration of the logging subsystem . In practice the values passed to ` ` - - log - level ` ` ...
if context . early_args . log_level : log_level = context . early_args . log_level logging . getLogger ( "" ) . setLevel ( log_level ) for name in context . early_args . trace : logging . getLogger ( name ) . setLevel ( logging . DEBUG ) _logger . info ( "Enabled tracing on logger %r" , name )
def execute_command ( self ) : """Execute the shell command ."""
stderr = "" role_count = 0 for role in utils . roles_dict ( self . roles_path ) : self . command = self . command . replace ( "%role_name" , role ) ( _ , err ) = utils . capture_shell ( "cd {0} && {1}" . format ( os . path . join ( self . roles_path , role ) , self . command ) ) stderr = err role_count ...
def fit ( self , X , y = None , ** kwargs ) : """The fit method is the primary drawing input for the dispersion visualization . Parameters X : list or generator Should be provided as a list of documents or a generator that yields a list of documents that contain a list of words in the order they appear ...
if y is not None : self . classes_ = np . unique ( y ) elif y is None and self . labels is not None : self . classes_ = np . array ( [ self . labels [ 0 ] ] ) else : self . classes_ = np . array ( [ self . NULL_CLASS ] ) # Create an index ( e . g . the y position ) for the target words self . indexed_words_...
def get_resolution ( self ) -> list : '''Show device resolution .'''
output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'wm' , 'size' ) return output . split ( ) [ 2 ] . split ( 'x' )
def save_optimizer_for_phase ( phase ) : """Save the optimizer associated with the phase as a pickle"""
with open ( make_optimizer_pickle_path ( phase ) , "w+b" ) as f : f . write ( pickle . dumps ( phase . optimizer ) )
def _get_exceptions_db ( self ) : """Return a list of dictionaries suitable to be used with ptrie module ."""
template = "{extype} ({exmsg}){raised}" if not self . _full_cname : # When full callable name is not used the calling path is # irrelevant and there is no function associated with an # exception ret = [ ] for _ , fdict in self . _ex_dict . items ( ) : for key in fdict . keys ( ) : ret . appe...
def initializenb ( ) : """Find input files and log initialization info"""
logger . info ( 'Working directory: {0}' . format ( os . getcwd ( ) ) ) logger . info ( 'Run on {0}' . format ( asctime ( ) ) ) try : fileroot = os . environ [ 'fileroot' ] logger . info ( 'Setting fileroot to {0} from environment variable.\n' . format ( fileroot ) ) candsfile = 'cands_{0}_merge.pkl' . form...
def get_default_config ( self ) : """Return the default config for the handler"""
config = super ( StatsdHandler , self ) . get_default_config ( ) config . update ( { 'host' : '' , 'port' : 1234 , 'batch' : 1 , } ) return config
def main ( args = sys . argv [ 1 : ] ) : """Run the commandline script"""
usage = "%prog --help" parser = OptionParser ( usage , add_help_option = False ) parser . add_option ( '-c' , '--config' , help = "Configuration file to use" , action = 'store' , type = 'string' , dest = 'config_file' ) parser . add_option ( '-h' , '-H' , '--host' , help = ( "Hostname of the Trovebox server " "(overrid...
def find_module ( self , name ) : """Find the Module by its name ."""
defmodule = lib . EnvFindDefmodule ( self . _env , name . encode ( ) ) if defmodule == ffi . NULL : raise LookupError ( "Module '%s' not found" % name ) return Module ( self . _env , defmodule )
def register ( self , notification_cls = None ) : """Registers a Notification class unique by name ."""
self . loaded = True display_names = [ n . display_name for n in self . registry . values ( ) ] if ( notification_cls . name not in self . registry and notification_cls . display_name not in display_names ) : self . registry . update ( { notification_cls . name : notification_cls } ) models = getattr ( notifica...
def ToCategorizedPath ( path_type , components ) : """Translates a path type and a list of components to a categorized path ."""
try : prefix = { PathInfo . PathType . OS : ( "fs" , "os" ) , PathInfo . PathType . TSK : ( "fs" , "tsk" ) , PathInfo . PathType . REGISTRY : ( "registry" , ) , PathInfo . PathType . TEMP : ( "temp" , ) , } [ path_type ] except KeyError : raise ValueError ( "Unknown path type: `%s`" % path_type ) return "/" . j...
def parse_doc ( doc ) : """Exract list of sentences containing ( text , label ) pairs ."""
word_spans = [ ] sentence_spans = [ ] sentence_chunks = doc . split ( '\n\n' ) sentences = [ ] for chunk in sentence_chunks : sent_texts , sent_labels = get_texts_and_labels ( chunk . strip ( ) ) sentences . append ( list ( zip ( sent_texts , sent_labels ) ) ) return sentences
def networks ( self , names = None , ids = None , filters = None ) : """List networks . Similar to the ` ` docker networks ls ` ` command . Args : names ( : py : class : ` list ` ) : List of names to filter by ids ( : py : class : ` list ` ) : List of ids to filter by filters ( dict ) : Filters to be proces...
if filters is None : filters = { } if names : filters [ 'name' ] = names if ids : filters [ 'id' ] = ids params = { 'filters' : utils . convert_filters ( filters ) } url = self . _url ( "/networks" ) res = self . _get ( url , params = params ) return self . _result ( res , json = True )
def parse ( self , s , term_join = None ) : """Parses search term to Args : s ( str ) : string with search term . or _ join ( callable ) : function to join ' OR ' terms . Returns : dict : all of the terms grouped by marker . Key is a marker , value is a term . Example : > > > SearchTermParser ( ) . pa...
if not term_join : term_join = lambda x : '(' + ' OR ' . join ( x ) + ')' toks = self . scan ( s ) # Examples : starting with this query : # diabetes from 2014 to 2016 source healthindicators . gov # Assume the first term is ABOUT , if it is not marked with a marker . if toks and toks [ 0 ] and ( toks [ 0 ] [ 0 ] =...
def handle_padding ( self , padding ) : '''Pads the image with transparent pixels if necessary .'''
left = padding [ 0 ] top = padding [ 1 ] right = padding [ 2 ] bottom = padding [ 3 ] offset_x = 0 offset_y = 0 new_width = self . engine . size [ 0 ] new_height = self . engine . size [ 1 ] if left > 0 : offset_x = left new_width += left if top > 0 : offset_y = top new_height += top if right > 0 : ...
def query ( self , sql , timeout = 10 ) : """Submit a query and return results . : param sql : string : param timeout : int : return : pydrill . client . ResultQuery"""
if not sql : raise QueryError ( 'No query passed to drill.' ) result = ResultQuery ( * self . perform_request ( ** { 'method' : 'POST' , 'url' : '/query.json' , 'body' : { "queryType" : "SQL" , "query" : sql } , 'params' : { 'request_timeout' : timeout } } ) ) return result
def setup_logger ( log_dir = None , loglevel = logging . DEBUG ) : """Instantiate logger Parameters log _ dir : str Directory to save log , default : ~ / . ding0 / logging / loglevel : Level of logger ."""
create_home_dir ( ) create_dir ( os . path . join ( get_default_home_dir ( ) , 'log' ) ) if log_dir is None : log_dir = os . path . join ( get_default_home_dir ( ) , 'log' ) logger = logging . getLogger ( 'ding0' ) # use filename as name in log logger . setLevel ( loglevel ) # create a file handler handler = loggin...
def get_all ( self , uids : Iterable [ int ] ) -> Mapping [ int , Record ] : """Get records by a set of UIDs . Args : uids : The message UIDs ."""
return { uid : self . _records [ uid ] for uid in uids if uid in self . _records }
def flush ( self ) : """Synchronizes data to the underlying database file ."""
if self . flag [ 0 ] != 'r' : with self . write_mutex : if hasattr ( self . db , 'sync' ) : self . db . sync ( ) else : # fall - back , close and re - open , needed for ndbm flag = self . flag if flag [ 0 ] == 'n' : flag = 'c' + flag [ 1 : ] ...
def origin_mexico ( origin ) : """Returns if the origin is Mexico . ` origin ` The origin to check ."""
return origin in ( u'CIUDADJUAREZ' , u'GUADALAJARA' , u'HERMOSILLO' , u'MATAMOROS' , u'MERIDA' , u'MEXICO' , u'MONTERREY' , u'NOGALES' , u'NUEVOLAREDO' , u'TIJUANA' )
def _fuzzy_time_parse ( self , value ) : """Parses a fuzzy time value into a meaningful interpretation . ` value ` String value to parse ."""
value = value . lower ( ) . strip ( ) today = datetime . date . today ( ) if value in ( 'today' , 't' ) : return today else : kwargs = { } if value in ( 'y' , 'yesterday' ) : kwargs [ 'days' ] = - 1 elif value in ( 'w' , 'wk' , 'week' , 'last week' ) : kwargs [ 'days' ] = - 7 else : ...
def get_score ( self , terms ) : """Get score for a list of terms . : type terms : list : param terms : A list of terms to be analyzed . : returns : dict"""
assert isinstance ( terms , list ) or isinstance ( terms , tuple ) score_li = np . asarray ( [ self . _get_score ( t ) for t in terms ] ) s_pos = np . sum ( score_li [ score_li > 0 ] ) s_neg = - np . sum ( score_li [ score_li < 0 ] ) s_pol = ( s_pos - s_neg ) * 1.0 / ( ( s_pos + s_neg ) + self . EPSILON ) s_sub = ( s_p...
def _should_send ( self , rebuild , success , auto_canceled , manual_canceled ) : """Return True if any state in ` self . send _ on ` meets given conditions , thus meaning that a notification mail should be sent ."""
should_send = False should_send_mapping = { self . MANUAL_SUCCESS : not rebuild and success , self . MANUAL_FAIL : not rebuild and not success , self . MANUAL_CANCELED : not rebuild and manual_canceled , self . AUTO_SUCCESS : rebuild and success , self . AUTO_FAIL : rebuild and not success , self . AUTO_CANCELED : rebu...
def py2round ( value ) : """Round values as in Python 2 , for Python 3 compatibility . All x . 5 values are rounded away from zero . In Python 3 , this has changed to avoid bias : when x is even , rounding is towards zero , when x is odd , rounding is away from zero . Thus , in Python 3 , round ( 2.5 ) resu...
if value > 0 : return float ( floor ( float ( value ) + 0.5 ) ) else : return float ( ceil ( float ( value ) - 0.5 ) )
def get ( self , request , bot_id , id , format = None ) : """Get list of telegram recipients of a hook serializer : TelegramRecipientSerializer responseMessages : - code : 401 message : Not authenticated"""
return super ( TelegramRecipientList , self ) . get ( request , bot_id , id , format )
def get_winner ( trials ) : """Get winner trial of a job ."""
winner = { } # TODO : sort _ key should be customized here sort_key = "accuracy" if trials and len ( trials ) > 0 : first_metrics = get_trial_info ( trials [ 0 ] ) [ "metrics" ] if first_metrics and not first_metrics . get ( "accuracy" , None ) : sort_key = "episode_reward" max_metric = float ( "-In...
def create ( name = 'local' ) : """Creates a new KVStore . For single machine training , there are two commonly used types : ` ` local ` ` : Copies all gradients to CPU memory and updates weights there . ` ` device ` ` : Aggregates gradients and updates weights on GPUs . With this setting , the KVStore also...
if not isinstance ( name , string_types ) : raise TypeError ( 'name must be a string' ) handle = KVStoreHandle ( ) check_call ( _LIB . MXKVStoreCreate ( c_str ( name ) , ctypes . byref ( handle ) ) ) kv = KVStore ( handle ) set_kvstore_handle ( kv . handle ) return kv
def desc ( self , table ) : '''Returns table description > > > yql . desc ( ' geo . countries ' )'''
query = "desc {0}" . format ( table ) response = self . raw_query ( query ) return response
def verify_not_equal ( self , first , second , msg = "" ) : """Soft assert for inequality : params want : the value to compare against : params second : the value to compare with : params msg : ( Optional ) msg explaining the difference"""
try : self . assert_not_equal ( first , second , msg ) except AssertionError , e : if msg : m = "%s:\n%s" % ( msg , str ( e ) ) else : m = str ( e ) self . verification_erorrs . append ( m )
def add ( self , recipients ) : """Add the supplied recipients to the exiting list : param recipients : list of either address strings or tuples ( name , address ) or dictionary elements : type recipients : list [ str ] or list [ tuple ] or list [ dict ]"""
if recipients : if isinstance ( recipients , str ) : self . _recipients . append ( Recipient ( address = recipients , parent = self . _parent , field = self . _field ) ) elif isinstance ( recipients , Recipient ) : self . _recipients . append ( recipients ) elif isinstance ( recipients , tup...
def read_files ( self , condition = '*' ) : """Read specific files from archive into memory . If " condition " is a list of numbers , then return files which have those positions in infolist . If " condition " is a string , then it is treated as a wildcard for names of files to extract . If " condition " is a...
checker = condition2checker ( condition ) return RarFileImplementation . read_files ( self , checker )
def read_pseudo_zval ( self ) : """Create pseudopotential ZVAL dictionary ."""
try : def poscar_line ( results , match ) : poscar_line = match . group ( 1 ) results . poscar_line = re . findall ( r'[A-Z][a-z]?' , poscar_line ) def zvals ( results , match ) : zvals = match . group ( 1 ) results . zvals = map ( float , re . findall ( r'-?\d+\.\d*' , zvals ) )...
def hide_intf_loopback_holder_interface_loopback_vrf_forwarding ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_intf_loopback_holder = ET . SubElement ( config , "hide-intf-loopback-holder" , xmlns = "urn:brocade.com:mgmt:brocade-intf-loopback" ) interface = ET . SubElement ( hide_intf_loopback_holder , "interface" ) loopback = ET . SubElement ( interface , "loopback" ) id_key = ET . SubEl...
def kmer_count ( seq_list , k ) : """Generate k - mer counts from a set of sequences Args : seq _ list ( iterable ) : List of DNA sequences ( with letters from { A , C , G , T } ) k ( int ) : K in k - mer . Returns : pandas . DataFrame : Count matrix for seach sequence in seq _ list Example : > > > km...
# generate all k - mers all_kmers = generate_all_kmers ( k ) kmer_count_list = [ ] for seq in seq_list : kmer_count_list . append ( [ seq . count ( kmer ) for kmer in all_kmers ] ) return pd . DataFrame ( kmer_count_list , columns = all_kmers )
def _extract_coeffs ( self , imt ) : """Extract dictionaries of coefficients specific to required intensity measure type ."""
C_HR = self . COEFFS_HARD_ROCK [ imt ] C_BC = self . COEFFS_BC [ imt ] C_SR = self . COEFFS_SOIL_RESPONSE [ imt ] SC = self . COEFFS_STRESS [ imt ] return C_HR , C_BC , C_SR , SC
def load ( fp , ** kwargs ) -> BioCCollection : """Deserialize fp ( a . read ( ) - supporting text file or binary file containing a JSON document ) to a BioCCollection object Args : fp : a file containing a JSON document * * kwargs : Returns : BioCCollection : a collection"""
obj = json . load ( fp , ** kwargs ) return parse_collection ( obj )
def from_optional_dicts_by_key ( cls , ds : Optional [ dict ] , force_snake_case = True , force_cast : bool = False , restrict : bool = True ) -> TOption [ TDict [ T ] ] : """From dict of dict to optional dict of instance . : param ds : Dict of dict : param force _ snake _ case : Keys are transformed to snake c...
return TOption ( cls . from_dicts_by_key ( ds , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) if ds is not None else None )
def missing ( self , * args , ** kwds ) : """Return whether an output is considered missing or not ."""
from functools import reduce indexer = kwds [ 'indexer' ] freq = kwds [ 'freq' ] or generic . default_freq ( ** indexer ) miss = ( checks . missing_any ( generic . select_time ( da , ** indexer ) , freq ) for da in args ) return reduce ( np . logical_or , miss )
def process_xml_file ( file_name ) : """Return a TripsProcessor by processing a TRIPS EKB XML file . Parameters file _ name : str Path to a TRIPS extraction knowledge base ( EKB ) file to be processed . Returns tp : TripsProcessor A TripsProcessor containing the extracted INDRA Statements in tp . stat...
with open ( file_name , 'rb' ) as fh : ekb = fh . read ( ) . decode ( 'utf-8' ) return process_xml ( ekb )
def all_es_aliases ( self ) : """List all aliases used in ES"""
r = self . requests . get ( self . url + "/_aliases" , headers = HEADER_JSON , verify = False ) try : r . raise_for_status ( ) except requests . exceptions . HTTPError as ex : logger . warning ( "Something went wrong when retrieving aliases on %s." , self . anonymize_url ( self . index_url ) ) logger . warn...
def calc_qiga2_v1 ( self ) : """Perform the runoff concentration calculation for the second interflow component . The working equation is the analytical solution of the linear storage equation under the assumption of constant change in inflow during the simulation time step . Required derived parameter : ...
der = self . parameters . derived . fastaccess old = self . sequences . states . fastaccess_old new = self . sequences . states . fastaccess_new if der . ki2 <= 0. : new . qiga2 = new . qigz2 elif der . ki2 > 1e200 : new . qiga2 = old . qiga2 + new . qigz2 - old . qigz2 else : d_temp = ( 1. - modelutils . e...
def get_inasafe_default_value_qsetting ( qsetting , category , inasafe_field_key ) : """Helper method to get the inasafe default value from qsetting . : param qsetting : QSetting . : type qsetting : QSetting : param category : Category of the default value . It can be global or recent . Global means the glo...
key = 'inasafe/default_value/%s/%s' % ( category , inasafe_field_key ) default_value = qsetting . value ( key ) if default_value is None : if category == GLOBAL : # If empty for global setting , use default one . inasafe_field = definition ( inasafe_field_key ) default_value = inasafe_field . get ( ...
def org_invite ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / org - xxxx / invite API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Organizations # API - method % 3A - % 2Forg - xxxx % 2Finvite"""
return DXHTTPRequest ( '/%s/invite' % object_id , input_params , always_retry = always_retry , ** kwargs )
def held ( name ) : '''Set package in ' hold ' state , meaning it will not be upgraded . name The name of the package , e . g . , ' tmux ' '''
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } state = __salt__ [ 'pkg.get_selections' ] ( pattern = name , ) if not state : ret . update ( comment = 'Package {0} does not have a state' . format ( name ) ) elif not salt . utils . data . is_true ( state . get ( 'hold' , False ) ) : ...
def group_attrib ( self ) : '''return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member'''
group_attributes = [ g . attrib for g in self . dataset . groups if self in g ] if group_attributes : return concat_namedtuples ( * group_attributes )
def get_labels_encoder ( self , data_dir ) : """Builds encoder for the given class labels . Args : data _ dir : data directory Returns : An encoder for class labels ."""
label_filepath = os . path . join ( data_dir , self . vocab_filename ) return text_encoder . TokenTextEncoder ( label_filepath )