signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def flush ( self ) : """Flush ( apply ) all changed to datastore ."""
self . puts . flush ( ) self . deletes . flush ( ) self . ndb_puts . flush ( ) self . ndb_deletes . flush ( )
def w ( self ) : """Extract write lock ( w ) counter if available ( lazy ) ."""
if not self . _counters_calculated : self . _counters_calculated = True self . _extract_counters ( ) return self . _w
def getConParams ( virtualhost ) : """Connection object builder . Args : virtualhost ( str ) : selected virtualhost in rabbitmq Returns : pika . ConnectionParameters : object filled by ` constants ` from : class : ` edeposit . amqp . settings ` ."""
return pika . ConnectionParameters ( host = settings . RABBITMQ_HOST , port = int ( settings . RABBITMQ_PORT ) , virtual_host = virtualhost , credentials = pika . PlainCredentials ( settings . RABBITMQ_USER_NAME , settings . RABBITMQ_USER_PASSWORD ) )
def get_pipeline ( self , id = None , params = None ) : """` < https : / / www . elastic . co / guide / en / elasticsearch / plugins / current / ingest . html > ` _ : arg id : Comma separated list of pipeline ids . Wildcards supported : arg master _ timeout : Explicit operation timeout for connection to master ...
return self . transport . perform_request ( 'GET' , _make_path ( '_ingest' , 'pipeline' , id ) , params = params )
def get_labels ( self , gt_tables ) : """: param gt _ tables : dict , keys are page number and values are list of tables bbox within that page : return :"""
labels = np . zeros ( len ( self . candidates ) ) for i , candidate in enumerate ( self . candidates ) : page_num = candidate [ 0 ] try : tables = gt_tables [ page_num ] for gt_table in tables : page_width , page_height , y0 , x0 , y1 , x1 = gt_table w_ratio = float ( can...
def _get_stack_events ( h_client , stack_id , event_args ) : '''Get event for stack'''
event_args [ 'stack_id' ] = stack_id event_args [ 'resource_name' ] = None try : events = h_client . events . list ( ** event_args ) except heatclient . exc . HTTPNotFound as exc : raise heatclient . exc . CommandError ( six . text_type ( exc ) ) else : for event in events : event . stack_name = sta...
def _equal ( self , row1 , row2 ) : """Returns True if two rows are identical excluding start and end date . Returns False otherwise . : param dict [ str , T ] row1 : The first row . : param dict [ str , T ] row2 : The second row . : rtype : bool"""
for key in row1 . keys ( ) : if key not in [ self . _key_start_date , self . _key_end_date ] : if row1 [ key ] != row2 [ key ] : return False return True
def connect_ensime_server ( self ) : """Start initial connection with the server ."""
self . log . debug ( 'connect_ensime_server: in' ) server_v2 = isinstance ( self , EnsimeClientV2 ) def disable_completely ( e ) : if e : self . log . error ( 'connection error: %s' , e , exc_info = True ) self . shutdown_server ( ) self . _display_ws_warning ( ) if self . running and self . number_...
async def check_presets ( cls ) : '''Lists all resource presets in the current scaling group with additiona information .'''
rqst = Request ( cls . session , 'POST' , '/resource/check-presets' ) async with rqst . fetch ( ) as resp : return await resp . json ( )
def create_db ( name , ** client_args ) : '''Create a database . name Name of the database to create . CLI Example : . . code - block : : bash salt ' * ' influxdb . create _ db < name >'''
if db_exists ( name , ** client_args ) : log . info ( 'DB \'%s\' already exists' , name ) return False client = _client ( ** client_args ) client . create_database ( name ) return True
def delete ( self , uri , force = False , timeout = - 1 , custom_headers = None ) : """Deletes current resource . Args : force : Flag to delete the resource forcefully , default is False . timeout : Timeout in seconds . custom _ headers : Allows to set custom http headers ."""
if force : uri += '?force=True' logger . debug ( "Delete resource (uri = %s)" % ( str ( uri ) ) ) task , body = self . _connection . delete ( uri , custom_headers = custom_headers ) if not task : # 204 NO CONTENT # Successful return from a synchronous delete operation . return True task = self . _task_monitor ....
def deriv ( self , t , y , data = None ) : "Calculate [ dtheta / dt , d2theta / dt2 ] from [ theta , dtheta / dt ] ."
theta , dtheta_dt = y return np . array ( [ dtheta_dt , - self . g_l * gv . sin ( theta ) ] )
def _generate_message ( self ) : """Reformat ` path ` attributes of each ` error ` and create a new message . Join ` path ` attributes together in a more readable way , to enable easy debugging of an invalid Checkmatefile . : returns : Reformatted error paths and messages , as a multi - line string ."""
reformatted_paths = ( '' . join ( "[%s]" % str ( x ) # If it ' s not a string , don ' t put quotes around it . We do this , # for example , when the value is an int , in the case of a list # index . if isinstance ( x , six . integer_types ) # Otherwise , assume the path node is a string and put quotes # around the key ...
def build_tx_cigar ( exons , strand ) : """builds a single CIGAR string representing an alignment of the transcript sequence to a reference sequence , including introns . The input exons are expected to be in transcript order , and the resulting CIGAR is also in transcript order . > > > build _ tx _ cigar (...
cigarelem_re = re . compile ( r"\d+[=DIMNX]" ) def _reverse_cigar ( c ) : return '' . join ( reversed ( cigarelem_re . findall ( c ) ) ) if len ( exons ) == 0 : return None # flip orientation of all CIGARs if on - strand if strand == - 1 : cigars = [ _reverse_cigar ( e [ "cigar" ] ) for e in exons ] else : ...
def zero_handling ( x ) : """This function handle the issue with zero values if the are exposed to become an argument for any log function . : param x : The vector . : return : The vector with zeros substituted with epsilon values ."""
return np . where ( x == 0 , np . finfo ( float ) . eps , x )
def toprettyxml ( self , indent = " " , newl = os . linesep , encoding = "UTF-8" ) : """Return the manifest as pretty - printed XML"""
domtree = self . todom ( ) # WARNING : The XML declaration has to follow the order # version - encoding - standalone ( standalone being optional ) , otherwise # if it is embedded in an exe the exe will fail to launch ! # ( ' application configuration incorrect ' ) if sys . version_info >= ( 2 , 3 ) : xmlstr = domtr...
def resize_to_contents ( self ) : """Resize cells to contents"""
QApplication . setOverrideCursor ( QCursor ( Qt . WaitCursor ) ) self . resizeColumnsToContents ( ) self . model ( ) . fetch_more ( columns = True ) self . resizeColumnsToContents ( ) QApplication . restoreOverrideCursor ( )
def get_dict_from_response ( response ) : """Check for errors in the response and return the resulting JSON ."""
if getattr ( response , '_resp' ) and response . _resp . code > 400 : raise OAuthResponseError ( 'Application mis-configuration in Globus' , None , response ) return response . data
def cmd_rctrim ( self , args ) : '''set RCx _ TRIM'''
if not 'RC_CHANNELS_RAW' in self . status . msgs : print ( "No RC_CHANNELS_RAW to trim with" ) return m = self . status . msgs [ 'RC_CHANNELS_RAW' ] for ch in range ( 1 , 5 ) : self . param_set ( 'RC%u_TRIM' % ch , getattr ( m , 'chan%u_raw' % ch ) )
def _reconstruct_record ( self , record_object ) : '''a helper method for reconstructing record fields from record object'''
record_details = { } current_details = record_details for key , value in self . model . keyMap . items ( ) : record_key = key [ 1 : ] if record_key : record_value = getattr ( record_object , record_key , None ) if record_value != None : record_segments = record_key . split ( '.' ) ...
def get_tracks ( self , * args , ** kwargs ) : """Convenience method for ` get _ music _ library _ information ` with ` ` search _ type = ' tracks ' ` ` . For details of other arguments , see ` that method < # soco . music _ library . MusicLibrary . get _ music _ library _ information > ` _ ."""
args = tuple ( [ 'tracks' ] + list ( args ) ) return self . get_music_library_information ( * args , ** kwargs )
def git_list_remotes ( repo_dir ) : """Return a listing of configured remotes ."""
command = [ 'git' , 'remote' , '--verbose' , 'show' ] raw = execute_git_command ( command , repo_dir = repo_dir ) . splitlines ( ) output = [ l . strip ( ) for l in raw if l . strip ( ) ] # < name > < location > ( < cmd > ) # make a list of lists with clean elements of equal length headers = [ 'name' , 'location' , 'cm...
def constructFMIndex ( self , logger ) : '''This function iterates through the BWT and counts the letters as it goes to create the FM index . For example , the string ' ACC $ ' would have BWT ' C $ CA ' . The FM index would iterate over this and count the occurence of the letter it found so you ' d end up with th...
# sampling method self . searchCache = { } self . bitPower = 11 self . binSize = 2 ** self . bitPower self . fmIndexFN = self . dirName + '/fmIndex.npy' if os . path . exists ( self . fmIndexFN ) : self . partialFM = np . load ( self . fmIndexFN , 'r' ) else : if logger != None : logger . info ( 'First ...
def nl_list_entry ( ptr , type_ , member ) : """https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / include / netlink / list . h # L64."""
if ptr . container_of : return ptr . container_of null_data = type_ ( ) setattr ( null_data , member , ptr ) return null_data
def _finish_fragment ( self ) : """Creates fragment"""
if self . fragment : self . fragment . finish ( ) if self . fragment . headers : # Regardless of what ' s been seen to this point , if we encounter a headers fragment , # all the previous fragments should be marked hidden and found _ visible set to False . self . found_visible = False for f ...
def challenge ( arg : ChallengeArg ) -> dict : """Response is dict like ` Trial ` because Status ( OwlEnum ) can ' t be pickled ."""
name : str = arg . req . name . get_or ( str ( arg . seq ) ) log_prefix = f"[{arg.seq} / {arg.number_of_request}]" logger . info_lv3 ( f"{log_prefix} {'-'*80}" ) logger . info_lv3 ( f"{log_prefix} {arg.seq}. {arg.req.name.get_or(arg.req.path)}" ) logger . info_lv3 ( f"{log_prefix} {'-'*80}" ) path_str_one = arg . path...
def link ( args ) : """% prog link metafile Link source to target based on a tabular file ."""
from jcvi . apps . base import mkdir p = OptionParser ( link . __doc__ ) p . add_option ( "--dir" , help = "Place links in a subdirectory [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) meta , = args d = opts . dir if d : mkdir ( d ) fp =...
def _enable_l1_keepalives ( self , command ) : """Enables L1 keepalive messages if supported . : param command : command line"""
env = os . environ . copy ( ) if "IOURC" not in os . environ : env [ "IOURC" ] = self . iourc_path try : output = yield from gns3server . utils . asyncio . subprocess_check_output ( self . _path , "-h" , cwd = self . working_dir , env = env , stderr = True ) if re . search ( "-l\s+Enable Layer 1 keepalive m...
def patch_csi_node ( self , name , body , ** kwargs ) : """partially update the specified CSINode This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . patch _ csi _ node ( name , body , async _ req = True ) > > >...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_csi_node_with_http_info ( name , body , ** kwargs ) else : ( data ) = self . patch_csi_node_with_http_info ( name , body , ** kwargs ) return data
def search_line ( line , search , searchtype ) : """Return True if search term is found in given line , False otherwise ."""
if searchtype == 're' or searchtype == 'word' : return re . search ( search , line ) # , re . IGNORECASE ) elif searchtype == 'pos' : return searcher . search_out ( line , search ) elif searchtype == 'hyper' : return searcher . hypernym_search ( line , search )
def Friedel ( m , x , rhol , rhog , mul , mug , sigma , D , roughness = 0 , L = 1 ) : r'''Calculates two - phase pressure drop with the Friedel correlation . . . math : : \ Delta P _ { friction } = \ Delta P _ { lo } \ phi _ { lo } ^ 2 . . math : : \ phi _ { lo } ^ 2 = E + \ frac { 3.24FH } { Fr ^ { 0.0454 ...
# Liquid - only properties , for calculation of E , dP _ lo v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5 * rhol * v_lo ** 2 ) # Gas - only properties , for calculation of E v_...
def _is_whitespace ( self , char ) : """Checks whether ` chars ` is a whitespace character ."""
# \ t , \ n , and \ r are technically contorl characters but we treat them # as whitespace since they are generally considered as such . if char in [ ' ' , '\t' , '\n' , '\r' ] : return True cat = unicodedata . category ( char ) if cat == 'Zs' : return True return False
def itemFromLink ( self , link ) : """@ type link : C { unicode } @ param link : A webID to translate into an item . @ rtype : L { Item } @ return : The item to which the given link referred ."""
return self . siteStore . getItemByID ( self . webTranslator . linkFrom ( link ) )
def create_geometry ( self , input_geometry , upper_depth , lower_depth ) : '''If geometry is defined as a numpy array then create instance of nhlib . geo . polygon . Polygon class , otherwise if already instance of class accept class : param input _ geometry : Input geometry ( polygon ) as either i ) ins...
self . _check_seismogenic_depths ( upper_depth , lower_depth ) # Check / create the geometry class if not isinstance ( input_geometry , Polygon ) : if not isinstance ( input_geometry , np . ndarray ) : raise ValueError ( 'Unrecognised or unsupported geometry ' 'definition' ) if np . shape ( input_geomet...
def timecds2datetime ( tcds ) : """Method for converting time _ cds - variables to datetime - objectsself . Works both with a dictionary and a numpy record _ array ."""
days = int ( tcds [ 'Days' ] ) milliseconds = int ( tcds [ 'Milliseconds' ] ) try : microseconds = int ( tcds [ 'Microseconds' ] ) except ( KeyError , ValueError ) : microseconds = 0 try : microseconds += int ( tcds [ 'Nanoseconds' ] ) / 1000. except ( KeyError , ValueError ) : pass reference = datetime...
def _Main ( self ) : """The main loop ."""
# We need a resolver context per process to prevent multi processing # issues with file objects stored in images . resolver_context = context . Context ( ) for credential_configuration in self . _processing_configuration . credentials : resolver . Resolver . key_chain . SetCredential ( credential_configuration . pa...
def has_table ( table_name ) : """Return True if table exists , False otherwise ."""
return db . engine . dialect . has_table ( db . engine . connect ( ) , table_name )
def start ( self ) : """Perform full system setup . Method logs in and sets auth token , urls , and ids for future requests . Essentially this is just a wrapper function for ease of use ."""
if self . _username is None or self . _password is None : if not self . login ( ) : return elif not self . get_auth_token ( ) : return camera_list = self . get_cameras ( ) networks = self . get_ids ( ) for network_name , network_id in networks . items ( ) : if network_id not in camera_list . keys ( ...
def get_device_id ( self , use_cached = True ) : """Get this device ' s device id"""
device_json = self . get_device_json ( use_cached ) return device_json [ "id" ] . get ( "devId" )
def done ( item , done_type = None , max_tries = None , ttl = None ) : '''Wrapper for any type of finish , successful , permanant failure or temporary failure'''
if done_type is None or done_type == _c . FSQ_SUCCESS : return success ( item ) return fail ( item , fail_type = done_type , max_tries = max_tries , ttl = ttl )
def create_element ( tag : str , name : str = None , base : type = None , attr : dict = None ) -> Node : """Create element with a tag of ` ` name ` ` . : arg str name : html tag . : arg type base : Base class of the created element ( defatlt : ` ` WdomElement ` ` ) : arg dict attr : Attributes ( key - value...
from wdom . web_node import WdomElement from wdom . tag import Tag from wdom . window import customElements if attr is None : attr = { } if name : base_class = customElements . get ( ( name , tag ) ) else : base_class = customElements . get ( ( tag , None ) ) if base_class is None : attr [ '_registered'...
def find_all ( pattern = None ) : """Returns all serial ports present . : param pattern : pattern to search for when retrieving serial ports : type pattern : string : returns : list of devices : raises : : py : class : ` ~ alarmdecoder . util . CommError `"""
devices = [ ] try : if pattern : devices = serial . tools . list_ports . grep ( pattern ) else : devices = serial . tools . list_ports . comports ( ) except serial . SerialException as err : raise CommError ( 'Error enumerating serial devices: {0}' . format ( str ( err ) ) , err ) return dev...
def permission_to_pyramid_acls ( permissions ) : """Returns a list of permissions in a format understood by pyramid : param permissions : : return :"""
acls = [ ] for perm in permissions : if perm . type == "user" : acls . append ( ( Allow , perm . user . id , perm . perm_name ) ) elif perm . type == "group" : acls . append ( ( Allow , "group:%s" % perm . group . id , perm . perm_name ) ) return acls
def Nu_conv_internal ( Re , Pr , eD = 0 , Di = None , x = None , fd = None , Method = None , AvailableMethods = False ) : r'''This function calculates the heat transfer coefficient for internal convection inside a circular pipe . Requires at a minimum a flow ' s Reynolds and Prandtl numbers ` Re ` and ` Pr ` . ...
def list_methods ( ) : methods = [ ] if Re < LAMINAR_TRANSITION_PIPE : # Laminar ! if all ( ( Re , Pr , x , Di ) ) : methods . append ( 'Baehr-Stephan laminar thermal/velocity entry' ) methods . append ( 'Hausen laminar thermal entry' ) methods . append ( 'Seider-Tate...
def parse_summary ( content , reference_id = None ) : """Extracts the summary from the ` content ` of the cable . If no summary can be found , ` ` None ` ` is returned . ` content ` The content of the cable . ` reference _ id ` The reference identifier of the cable ."""
summary = None m = _END_SUMMARY_PATTERN . search ( content ) if m : end_of_summary = m . start ( ) m = _START_SUMMARY_PATTERN . search ( content , 0 , end_of_summary ) or _ALTERNATIVE_START_SUMMARY_PATTERN . search ( content , 0 , end_of_summary ) if m : summary = content [ m . end ( ) : end_of_summ...
def _item_exists_in_bucket ( self , bucket , key , checksums ) : """Returns true if the key already exists in the current bucket and the clientside checksum matches the file ' s checksums , and false otherwise ."""
try : obj = self . target_s3 . meta . client . head_object ( Bucket = bucket , Key = key ) if obj and obj . containsKey ( 'Metadata' ) : if obj [ 'Metadata' ] == checksums : return True except ClientError : # An exception from calling ` head _ object ` indicates that no file with the specifi...
def split ( self , box_size ) : """Splits the box object into many boxes each of given size . Assumption : the entire box can be split into rows and columns with the given size . : param box _ size : ( width , height ) of the new tiny boxes : return : Array of tiny boxes"""
w , h = box_size rows = round ( self . height / h ) cols = round ( self . width / w ) boxes = [ ] for row in range ( rows ) : for col in range ( cols ) : box = Box ( self . x + ( col * w ) , self . y + ( row * h ) , w , h ) boxes . append ( box ) return boxes
def dedent ( line ) : """Banana banana"""
indentation = 0 for char in line : if char not in ' \t' : break indentation += 1 if char == '\t' : indentation = _round8 ( indentation ) if indentation % 8 != 0 : raise IndentError ( column = indentation ) return indentation // 8 , line . strip ( )
def configure ( ) : """Configures YAML parser for Step serialization and deserialization Called in drain / _ _ init _ _ . py"""
yaml . add_multi_representer ( Step , step_multi_representer ) yaml . add_multi_constructor ( '!step' , step_multi_constructor ) yaml . Dumper . ignore_aliases = lambda * args : True
def _set_state ( self , state ) : """Transition the SCTP association to a new state ."""
if state != self . _association_state : self . __log_debug ( '- %s -> %s' , self . _association_state , state ) self . _association_state = state if state == self . State . ESTABLISHED : self . __state = 'connected' for channel in list ( self . _data_channels . values ( ) ) : if channel . negoti...
def require_variable ( self , variable , unit = None , year = None , exclude_on_fail = False ) : """Check whether all scenarios have a required variable Parameters variable : str required variable unit : str , default None name of unit ( optional ) year : int or list , default None years ( optional ) ...
criteria = { 'variable' : variable } if unit : criteria . update ( { 'unit' : unit } ) if year : criteria . update ( { 'year' : year } ) keep = self . _apply_filters ( ** criteria ) idx = self . meta . index . difference ( _meta_idx ( self . data [ keep ] ) ) n = len ( idx ) if n == 0 : logger ( ) . info ( ...
def resolve_meta_key ( hub , key , meta ) : """Resolve a value when it ' s a string and starts with ' > '"""
if key not in meta : return None value = meta [ key ] if isinstance ( value , str ) and value [ 0 ] == '>' : topic = value [ 1 : ] if topic not in hub : raise KeyError ( 'topic %s not found in hub' % topic ) return hub [ topic ] . get ( ) return value
def client_authentication ( self , request , auth = None , ** kwargs ) : """Do client authentication : param endpoint _ context : A : py : class : ` oidcendpoint . endpoint _ context . SrvInfo ` instance : param request : Parsed request , a self . request _ cls class instance : param authn : Authorization i...
return verify_client ( self . endpoint_context , request , auth )
def setup_gdt ( self , state , gdt ) : """Write the GlobalDescriptorTable object in the current state memory : param state : state in which to write the GDT : param gdt : GlobalDescriptorTable object : return :"""
state . memory . store ( gdt . addr + 8 , gdt . table ) state . regs . gdt = gdt . gdt state . regs . cs = gdt . cs state . regs . ds = gdt . ds state . regs . es = gdt . es state . regs . ss = gdt . ss state . regs . fs = gdt . fs state . regs . gs = gdt . gs
def print_middleware_tree ( self , * , EOL = os . linesep , ** kwargs ) : # noqa pragma : no cover """Prints a unix - tree - like output of the structure of the web application to the file specified ( stdout by default ) . Args : EOL ( str ) : The character or string that ends the line . * * kwargs : Argume...
def mask_to_method_name ( mask ) : if mask == HTTPMethod . ALL : return 'ALL' methods = set ( HTTPMethod ) - { HTTPMethod . ALL } names = ( method . name for method in methods if method . value & mask ) return '+' . join ( names ) def path_to_str ( path ) : if isinstance ( path , str ) : ...
def check_collision ( self , other ) : """Check another network against the given network ."""
other = Network ( other ) return self . network_long ( ) <= other . network_long ( ) <= self . broadcast_long ( ) or other . network_long ( ) <= self . network_long ( ) <= other . broadcast_long ( )
def get_array_dimensions ( data ) : """Given an array type data item , check that it is an array and return the dimensions as a tuple . Ex : get _ array _ dimensions ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ) returns ( 2 , 3)"""
depths_and_dimensions = get_depths_and_dimensions ( data , 0 ) # re - form as a dictionary with ` depth ` as key , and all of the dimensions found at that depth . grouped_by_depth = { depth : tuple ( dimension for depth , dimension in group ) for depth , group in groupby ( depths_and_dimensions , itemgetter ( 0 ) ) } #...
def parents ( self ) : """~ TermList : The direct parents of the ` Term ` ."""
if self . _parents is None : bottomups = tuple ( Relationship . bottomup ( ) ) self . _parents = TermList ( ) self . _parents . extend ( [ other for rship , others in six . iteritems ( self . relations ) for other in others if rship in bottomups ] ) return self . _parents
def add_def ( self , def_item ) : """Adds a def universally ."""
self . defs . append ( def_item ) for other in self . others : other . add_def ( def_item )
def list_commands ( self , ctx ) : """Override for showing commands in particular order"""
commands = super ( LegitGroup , self ) . list_commands ( ctx ) return [ cmd for cmd in order_manually ( commands ) ]
def from_json ( self , json_text ) : """Deserialize a JSON object into this object . This method will check that the JSON object has the required keys and will set each of the keys in that JSON object as an instance attribute of this object . : param json _ text : the JSON text or object to deserialize from...
# due to the architecture of response parsing , particularly # where the API returns lists , the JSON might have already been # parsed by the time it gets here if type ( json_text ) in [ str , unicode ] : j = json . loads ( json_text ) else : j = json_text try : for p in self . properties : setattr ...
def load_credentials ( self , profile = "default" ) : """Loads crentials for a given profile . Profiles are stored in ~ / . db . py _ { profile _ name } and are a base64 encoded JSON file . This is not to say this a secure way to store sensitive data , but it will probably stop your little sister from stealin...
f = profile_path ( DBPY_PROFILE_ID , profile ) if f : creds = load_from_json ( f ) self . username = creds . get ( 'username' ) self . password = creds . get ( 'password' ) self . hostname = creds . get ( 'hostname' ) self . port = creds . get ( 'port' ) self . filename = creds . get ( 'filename...
def monthdatescalendar ( cls , year , month ) : """Returns a list of week in a month . A week is a list of NepDate objects"""
weeks = [ ] week = [ ] for day in NepCal . itermonthdates ( year , month ) : week . append ( day ) if len ( week ) == 7 : weeks . append ( week ) week = [ ] if len ( week ) > 0 : weeks . append ( week ) return weeks
def create_producer ( self ) : """Context manager that yields an instance of ` ` Producer ` ` ."""
with self . connection_pool . acquire ( block = True ) as conn : yield self . producer ( conn )
def rotate ( self , g ) : '''rotate the matrix by a given amount on 3 axes'''
temp_matrix = Matrix3 ( ) a = self . a b = self . b c = self . c temp_matrix . a . x = a . y * g . z - a . z * g . y temp_matrix . a . y = a . z * g . x - a . x * g . z temp_matrix . a . z = a . x * g . y - a . y * g . x temp_matrix . b . x = b . y * g . z - b . z * g . y temp_matrix . b . y = b . z * g . x - b . x * g...
def _submit_results ( self ) : """Adding current values as a Raw Result and Resetting everything ."""
if self . _cur_res_id and self . _cur_values : # Setting DefaultResult just because it is obligatory . self . _addRawResult ( self . _cur_res_id , self . _cur_values ) self . _reset ( )
def works ( self , funder_id ) : """This method retrieve a iterable of Works of the given funder . args : Crossref allowed document Types ( String ) return : Works ( )"""
context = '%s/%s' % ( self . ENDPOINT , str ( funder_id ) ) return Works ( context = context )
def screen_cv2 ( self ) : """cv2 Image of current window screen"""
hwnd = win32gui . GetDesktopWindow ( ) left , top , right , bottom = self . rect width , height = right - left , bottom - top # copy bits to temporary dc win32gui . BitBlt ( self . _hdcmem , 0 , 0 , width , height , self . _hdcwin , left , top , win32con . SRCCOPY ) # read bits into buffer windll . gdi32 . GetDIBits ( ...
def get_aa_info ( code ) : """Get dictionary of information relating to a new amino acid code not currently in the database . Notes Use this function to get a dictionary that is then to be sent to the function add _ amino _ acid _ to _ json ( ) . use to fill in rows of amino _ acid table for new amino acid co...
letter = 'X' # Try to get content from PDBE . url_string = 'http://www.ebi.ac.uk/pdbe-srv/pdbechem/chemicalCompound/show/{0}' . format ( code ) r = requests . get ( url_string ) # Raise error if content not obtained . if not r . ok : raise IOError ( "Could not get to url {0}" . format ( url_string ) ) # Parse r . t...
def filter_properties ( self , model , context = None ) : """Filter simple properties Runs filters on simple properties changing them in place . : param model : object or dict : param context : object , dict or None : return : None"""
if model is None : return for property_name in self . properties : prop = self . properties [ property_name ] value = self . get ( model , property_name ) if value is None : continue filtered_value = prop . filter ( value = value , model = model , context = context ) if value != filtered...
def date_range ( start , end , boo ) : """Return list of dates within a specified range , inclusive . Args : start : earliest date to include , String ( " 2015-11-25 " ) end : latest date to include , String ( " 2015-12-01 " ) boo : if true , output list contains Numbers ( 20151230 ) ; if false , list conta...
earliest = datetime . strptime ( start . replace ( '-' , ' ' ) , '%Y %m %d' ) latest = datetime . strptime ( end . replace ( '-' , ' ' ) , '%Y %m %d' ) num_days = ( latest - earliest ) . days + 1 all_days = [ latest - timedelta ( days = x ) for x in range ( num_days ) ] all_days . reverse ( ) output = [ ] if boo : # Re...
def DEFAULT_NULLVALUE ( test ) : """Returns a null value for each of various kinds of test values . * * Parameters * * * * test * * : bool , int , float or string Value to test . * * Returns * * * * null * * : element in ` [ False , 0 , 0.0 , ' ' ] ` Null value corresponding to the given test value : ...
return False if isinstance ( test , bool ) else 0 if isinstance ( test , int ) else 0.0 if isinstance ( test , float ) else ''
def new ( obj ) : """Create a new post or page . : param str obj : Object to create ( post or page )"""
title = request . form [ 'title' ] _site . config [ 'ADDITIONAL_METADATA' ] [ 'author.uid' ] = current_user . uid try : title = title . encode ( sys . stdin . encoding ) except ( AttributeError , TypeError ) : title = title . encode ( 'utf-8' ) try : if obj == 'post' : f = NewPostForm ( ) if...
def build_accumulate ( function : Callable [ [ Any , Any ] , Tuple [ Any , Any ] ] = None , * , init : Any = NONE ) : """Decorator to wrap a function to return an Accumulate operator . : param function : function to be wrapped : param init : optional initialization for state"""
_init = init def _build_accumulate ( function : Callable [ [ Any , Any ] , Tuple [ Any , Any ] ] ) : @ wraps ( function ) def _wrapper ( init = NONE ) -> Accumulate : init = _init if init is NONE else init if init is NONE : raise TypeError ( '"init" argument has to be defined' ) ...
def jinja_template ( template_name , name = 'data' , mimetype = "text/html" ) : """Meta - renderer for rendering jinja templates"""
def jinja_renderer ( result , errors ) : template = get_jinja_template ( template_name ) context = { name : result or Mock ( ) , 'errors' : errors , 'enumerate' : enumerate } rendered = template . render ( ** context ) return { 'body' : rendered , 'mimetype' : mimetype } return jinja_renderer
def CopyFromStringISO8601 ( self , time_string ) : """Copies time elements from an ISO 8601 date and time string . Currently not supported : * Duration notation : " P . . . " * Week notation " 2016 - W33" * Date with week number notation " 2016 - W33-3" * Date without year notation " - - 08-17" * Ordina...
date_time_values = self . _CopyDateTimeFromStringISO8601 ( time_string ) self . _CopyFromDateTimeValues ( date_time_values )
def validate_version ( self , service_id , version_number ) : """Validate the version for a particular service and version ."""
content = self . _fetch ( "/service/%s/version/%d/validate" % ( service_id , version_number ) ) return self . _status ( content )
def set_item ( self , key , value ) : """Sets the item by key , and refills the table sorted ."""
keys = list ( self . keys ( ) ) # if it exists , update if key in keys : self . set_value ( 1 , keys . index ( key ) , str ( value ) ) # otherwise we have to add an element else : self . set_value ( 0 , len ( self ) , str ( key ) ) self . set_value ( 1 , len ( self ) - 1 , str ( value ) )
async def blob ( self , elem = None , elem_type = None , params = None ) : """Loads / dumps blob : return :"""
elem_type = elem_type if elem_type else elem . __class__ if hasattr ( elem_type , "serialize_archive" ) : elem = elem_type ( ) if elem is None else elem return await elem . serialize_archive ( self , elem = elem , elem_type = elem_type , params = params ) if self . writing : return await dump_blob ( self . ...
def subscribe ( self , event ) : """Subscribe to an object ' s future changes"""
uuids = event . data if not isinstance ( uuids , list ) : uuids = [ uuids ] subscribed = [ ] for uuid in uuids : try : self . _add_subscription ( uuid , event ) subscribed . append ( uuid ) except KeyError : continue result = { 'component' : 'hfos.events.objectmanager' , 'action' : '...
def removeID ( self , doc ) : """Remove the given attribute from the ID table maintained internally ."""
if doc is None : doc__o = None else : doc__o = doc . _o ret = libxml2mod . xmlRemoveID ( doc__o , self . _o ) return ret
def text ( cls , text , * , resize = None , single_use = None , selective = None ) : """Creates a new button with the given text . Args : resize ( ` bool ` ) : If present , the entire keyboard will be reconfigured to be resized and be smaller if there are not many buttons . single _ use ( ` bool ` ) : I...
return cls ( types . KeyboardButton ( text ) , resize = resize , single_use = single_use , selective = selective )
def remove_interval_helper ( self , interval , done , should_raise_error ) : """Returns self after removing interval and balancing . If interval doesn ' t exist , raise ValueError . This method may set done to [ 1 ] to tell all callers that rebalancing has completed . See Eternally Confuzzled ' s jsw _ remo...
# trace = interval . begin = = 347 and interval . end = = 353 # if trace : print ( ' \ nRemoving from { } interval { } ' . format ( # self . x _ center , interval ) ) if self . center_hit ( interval ) : # if trace : print ( ' Hit at { } ' . format ( self . x _ center ) ) if not should_raise_error and interval not i...
def _make_cell_set_template_code ( ) : """Get the Python compiler to emit LOAD _ FAST ( arg ) ; STORE _ DEREF Notes In Python 3 , we could use an easier function : . . code - block : : python def f ( ) : cell = None def _ stub ( value ) : nonlocal cell cell = value return _ stub _ cell _ set _ t...
def inner ( value ) : lambda : cell # make ` ` cell ` ` a closure so that we get a STORE _ DEREF cell = value co = inner . __code__ # NOTE : we are marking the cell variable as a free variable intentionally # so that we simulate an inner function instead of the outer function . This # is what gives us the `...
def update_translations ( self , project_id , file_path = None , language_code = None , overwrite = False , fuzzy_trigger = None ) : """Updates translations overwrite : set it to True if you want to overwrite definitions fuzzy _ trigger : set it to True to mark corresponding translations from the other langua...
return self . _upload ( project_id = project_id , updating = self . UPDATING_TRANSLATIONS , file_path = file_path , language_code = language_code , overwrite = overwrite , fuzzy_trigger = fuzzy_trigger )
def mouseDoubleClickEvent ( self , event ) : """Reimplement Qt method"""
index_clicked = self . indexAt ( event . pos ( ) ) if self . model . breakpoints : filename = self . model . breakpoints [ index_clicked . row ( ) ] [ 0 ] line_number_str = self . model . breakpoints [ index_clicked . row ( ) ] [ 1 ] self . edit_goto . emit ( filename , int ( line_number_str ) , '' ) if ind...
async def getNodesBy ( self , full , valu , cmpr = '=' ) : '''Get nodes by a property value or lift syntax . Args : full ( str ) : The full name of a property < form > : < prop > . valu ( obj ) : A value that the type knows how to lift by . cmpr ( str ) : The comparison operator you are lifting by . Some ...
async with await self . snap ( ) as snap : async for node in snap . getNodesBy ( full , valu , cmpr = cmpr ) : yield node
def _populate_tournament_payoff_array1 ( payoff_array , k ) : """Populate ` payoff _ array ` with the payoff values for player 1 in the tournament game . Parameters payoff _ array : ndarray ( float , ndim = 2) ndarray of shape ( m , n ) , where m = n choose k , prefilled with zeros . Modified in place . ...
m = payoff_array . shape [ 0 ] X = np . arange ( k ) for j in range ( m ) : for i in range ( k ) : payoff_array [ j , X [ i ] ] = 1 X = next_k_array ( X )
def trapz2 ( f , x = None , y = None , dx = 1.0 , dy = 1.0 ) : """Double integrate ."""
return numpy . trapz ( numpy . trapz ( f , x = y , dx = dy ) , x = x , dx = dx )
def exceptions_by_country ( country_code ) : """Returns a list of exception names for the given country : param country _ code : The two - character country code for the user : raises : ValueError - if country _ code is not two characers : return : A list of strings that are VAT exceptions for the count...
if not country_code or not isinstance ( country_code , str_cls ) or len ( country_code ) != 2 : raise ValueError ( 'Invalidly formatted country code' ) country_code = country_code . upper ( ) return EXCEPTIONS_BY_COUNTRY . get ( country_code , [ ] )
def _do_add_floating_ip_asr1k ( self , floating_ip , fixed_ip , vrf , ex_gw_port ) : """To implement a floating ip , an ip static nat is configured in the underlying router ex _ gw _ port contains data to derive the vlan associated with related subnet for the fixed ip . The vlan in turn is applied to the redu...
vlan = ex_gw_port [ 'hosting_info' ] [ 'segmentation_id' ] hsrp_grp = ex_gw_port [ ha . HA_INFO ] [ 'group' ] LOG . debug ( "add floating_ip: %(fip)s, fixed_ip: %(fixed_ip)s, " "vrf: %(vrf)s, ex_gw_port: %(port)s" , { 'fip' : floating_ip , 'fixed_ip' : fixed_ip , 'vrf' : vrf , 'port' : ex_gw_port } ) confstr = ( asr1k_...
def near ( self , center , sphere = False , min = None , max = None ) : """Order results by their distance from the given point , optionally with range limits in meters . Geospatial operator : { $ near : { . . . } } Documentation : https : / / docs . mongodb . com / manual / reference / operator / query / near ...
from marrow . mongo . geo import Point near = { '$geometry' : Point ( * center ) } if min : near [ '$minDistance' ] = float ( min ) if max : near [ '$maxDistance' ] = float ( max ) return Filter ( { self . _name : { '$nearSphere' if sphere else '$near' : near } } )
def add ( self , obj ) : """Add an instance of : class : ` Component < hl7apy . core . Component > ` to the list of children : param obj : an instance of : class : ` Component < hl7apy . core . Component > ` > > > f = Field ( ' PID _ 5 ' ) > > > f . xpn _ 1 = ' EVERYMAN ' > > > c = Component ( ' XPN _ 2 ' )...
# base datatype components can ' t have more than one child if self . name and is_base_datatype ( self . datatype , self . version ) and len ( self . children ) >= 1 : raise MaxChildLimitReached ( self , obj , 1 ) return super ( Field , self ) . add ( obj )
def van_image_enc_2d ( x , first_depth , reuse = False , hparams = None ) : """The image encoder for the VAN . Similar architecture as Ruben ' s paper ( http : / / proceedings . mlr . press / v70 / villegas17a / villegas17a . pdf ) . Args : x : The image to encode . first _ depth : The depth of the first ...
with tf . variable_scope ( 'van_image_enc' , reuse = reuse ) : enc_history = [ x ] enc = tf . layers . conv2d ( x , first_depth , 3 , padding = 'same' , activation = tf . nn . relu , strides = 1 ) enc = tf . contrib . layers . layer_norm ( enc ) enc = tf . layers . conv2d ( enc , first_depth , 3 , paddi...
def set_autostart_entry ( autostart_data : AutostartSettings ) : """Activates or deactivates autostarting autokey during user login . Autostart is handled by placing a . desktop file into ' $ XDG _ CONFIG _ HOME / autostart ' , typically ' ~ / . config / autostart '"""
_logger . info ( "Save autostart settings: {}" . format ( autostart_data ) ) autostart_file = Path ( common . AUTOSTART_DIR ) / "autokey.desktop" if autostart_data . desktop_file_name is None : # Choosing None as the GUI signals deleting the entry . delete_autostart_entry ( ) else : autostart_file . parent . mk...
def collect ( self ) : """Collect and publish disk temperatures"""
instances = { } # Support disks such as / dev / ( sd . * ) for device in os . listdir ( '/dev/' ) : instances . update ( self . match_device ( device , '/dev/' ) ) # Support disk by id such as / dev / disk / by - id / wwn - ( . * ) for device_id in os . listdir ( '/dev/disk/by-id/' ) : instances . update ( self...
def common_tuples ( list1 : list , list2 : list ) -> set : """This function computes the intersection of tuples present in two lists irrespective of the order of elements inside tuples . Args : list1 : A list containing tuples . list2 : Another list containing tuples . Returns : A set of tuples that are c...
common_set = set ( map ( tuple , map ( sorted , list1 ) ) ) & set ( map ( tuple , map ( sorted , list2 ) ) ) return common_set
def parse_shebang ( bytesio ) : """Parse the shebang from a file opened for reading binary ."""
if bytesio . read ( 2 ) != b'#!' : return ( ) first_line = bytesio . readline ( ) try : first_line = first_line . decode ( 'UTF-8' ) except UnicodeDecodeError : return ( ) # Require only printable ascii for c in first_line : if c not in printable : return ( ) cmd = tuple ( _shebang_split ( first...
def end_time ( self ) : """Return the end time of the current valid segment of data"""
return float ( self . strain . start_time + ( len ( self . strain ) - self . total_corruption ) / self . sample_rate )
def _parse_character_information ( self , rows ) : """Parses the character ' s basic information and applies the found values . Parameters rows : : class : ` list ` of : class : ` bs4 . Tag ` A list of all rows contained in the table ."""
int_rows = [ "level" , "achievement_points" ] char = { } house = { } for row in rows : cols_raw = row . find_all ( 'td' ) cols = [ ele . text . strip ( ) for ele in cols_raw ] field , value = cols field = field . replace ( "\xa0" , "_" ) . replace ( " " , "_" ) . replace ( ":" , "" ) . lower ( ) val...