signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def mnn_correct ( * datas , var_index = None , var_subset = None , batch_key = 'batch' , index_unique = '-' , batch_categories = None , k = 20 , sigma = 1. , cos_norm_in = True , cos_norm_out = True , svd_dim = None , var_adj = True , compute_angle = False , mnn_order = None , svd_mode = 'rsvd' , do_concatenate = True ...
try : from mnnpy import mnn_correct as mnn_cor n_jobs = settings . n_jobs if n_jobs is None else n_jobs datas , mnn_list , angle_list = mnn_cor ( * datas , var_index = var_index , var_subset = var_subset , batch_key = batch_key , index_unique = index_unique , batch_categories = batch_categories , k = k , si...
def std_dev ( self , value ) : """The std _ dev property . Args : value ( float ) . the property value ."""
if value == self . _defaults [ 'stdDev' ] and 'stdDev' in self . _values : del self . _values [ 'stdDev' ] else : self . _values [ 'stdDev' ] = value
def verify ( token , public_key , validate_nonce = None , algorithms = [ DEFAULT_ALGORITHM ] ) : """Verify the validity of the given JWT using the given public key . : param token : JWM claim : param public _ key : Public key to use when verifying the claim ' s signature . : param validate _ nonce : Callable ...
try : token_data = jwt . decode ( token , public_key , algorithms = algorithms ) except jwt . InvalidTokenError : logger . debug ( 'JWT failed verification' ) return False claimed_username = token_data . get ( 'username' ) claimed_time = token_data . get ( 'time' , 0 ) claimed_nonce = token_data . get ( 'no...
def startup ( self ) : """Start the instance This is mainly use to start the proxy"""
self . runner . info_log ( "Startup" ) if self . browser_config . config . get ( 'enable_proxy' ) : self . start_proxy ( )
def count_prime_factors ( num ) : """Create a Python function to calculate the number of unique prime factor powers for a given number . Args : num : An integer for which we need to calculate the number of unique prime factor powers Returns : An integer count of unique prime factor powers . Examples : >...
value = num factor_count = 0 factor = 2 while ( ( factor * factor ) <= value ) : powers = 0 while ( ( num % factor ) == 0 ) : num /= factor powers += 1 threshold = 0 increment = 1 while ( ( threshold + increment ) <= powers ) : threshold += increment factor_count += 1...
def plot_profile ( ribo_counts , transcript_name , transcript_length , start_stops , read_lengths = None , read_offsets = None , rna_counts = None , color_scheme = 'default' , html_file = 'index.html' , output_path = 'output' ) : """Plot read counts ( in all 3 frames ) and RNA coverage if provided for a single tr...
colors = get_color_palette ( scheme = color_scheme ) gs = gridspec . GridSpec ( 3 , 1 , height_ratios = [ 6 , 1.3 , 0.5 ] , hspace = 0.35 ) font_axis = { 'family' : 'sans-serif' , 'color' : colors [ 'color' ] , 'weight' : 'bold' , 'size' : 7 } # riboseq bar plots gs2 = gridspec . GridSpecFromSubplotSpec ( 1 , 1 , subpl...
def new ( self , bootstrap_with = None , use_timer = False , with_proof = False ) : """Actual constructor of the solver ."""
if not self . maplesat : self . maplesat = pysolvers . maplesat_new ( ) if bootstrap_with : for clause in bootstrap_with : self . add_clause ( clause ) self . use_timer = use_timer self . call_time = 0.0 # time spent for the last call to oracle self . accu_time = 0.0 # ti...
def get_current_line ( self ) : """Return a SourceLine of the current line ."""
if not self . has_space ( ) : return None pos = self . pos - self . col string = self . string end = self . length output = [ ] while pos < len ( string ) and string [ pos ] != '\n' : output . append ( string [ pos ] ) pos += 1 if pos == end : break else : output . append ( string [ pos ] ) ...
def handle_response ( self , response , ** kwargs ) : """Takes the given response and tries kerberos - auth , as needed ."""
num_401s = kwargs . pop ( 'num_401s' , 0 ) # Check if we have already tried to get the CBT data value if not self . cbt_binding_tried and self . send_cbt : # If we haven ' t tried , try getting it now cbt_application_data = _get_channel_bindings_application_data ( response ) if cbt_application_data : # Only the...
def check_color ( c , greyscale , which ) : """Checks that a colour argument for transparent or background options is the right form . Returns the colour ( which , if it ' s a bare integer , is " corrected " to a 1 - tuple ) ."""
if c is None : return c if greyscale : try : len ( c ) except TypeError : c = ( c , ) if len ( c ) != 1 : raise ProtocolError ( "%s for greyscale must be 1-tuple" % which ) if not is_natural ( c [ 0 ] ) : raise ProtocolError ( "%s colour for greyscale must be integer"...
def options ( self , context , module_options ) : '''SERVER IP of the SMB server NAME LNK file name CLEANUP Cleanup ( choices : True or False )'''
self . cleanup = False if 'CLEANUP' in module_options : self . cleanup = bool ( module_options [ 'CLEANUP' ] ) if 'NAME' not in module_options : context . log . error ( 'NAME option is required!' ) exit ( 1 ) if not self . cleanup and 'SERVER' not in module_options : context . log . error ( 'SERVER opti...
def exit_full_screen ( self ) : """Change from full screen to windowed mode and remove key binding"""
self . tk . attributes ( "-fullscreen" , False ) self . _full_screen = False self . events . remove_event ( "<FullScreen.Escape>" )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'type' ) and self . type is not None : _dict [ 'type' ] = self . type if hasattr ( self , 'text' ) and self . text is not None : _dict [ 'text' ] = self . text return _dict
def fuzzy_date ( date ) : """Formats a ` datetime . datetime ` object relative to the current time ."""
date = date . replace ( tzinfo = None ) if date <= datetime . now ( ) : diff = datetime . now ( ) - date seconds = diff . total_seconds ( ) minutes = seconds // 60 hours = minutes // 60 if minutes <= 1 : return "moments ago" elif minutes < 60 : return "{} minutes ago" . format ( ...
def load_metadata ( self , data_dir , feature_name = None ) : """See base class for details ."""
# Restore names if defined names_filepath = _get_names_filepath ( data_dir , feature_name ) if tf . io . gfile . exists ( names_filepath ) : self . names = _load_names_from_file ( names_filepath )
def split_ ( self , col : str ) -> "list(Ds)" : """Split the main dataframe according to a column ' s unique values and return a dict of dataswim instances : return : list of dataswim instances : rtype : list ( Ds ) : example : ` ` dss = ds . slit _ ( " Col 1 " ) ` `"""
try : dss = { } unique = self . df [ col ] . unique ( ) for key in unique : df2 = self . df . loc [ self . df [ col ] == key ] ds2 = self . _duplicate_ ( df2 ) dss [ key ] = ds2 return dss except Exception as e : self . err ( e , "Can not split dataframe" )
import re def find_five_letter_words ( sentence : str ) -> list : """This function extracts all five - letter words from the passed string using regular expressions . Examples : > > > find _ five _ letter _ words ( ' Please move back to strem ' ) [ ' strem ' ] > > > find _ five _ letter _ words ( ' 4K Ultra...
return re . findall ( r'\b\w{5}\b' , sentence )
def _build_filepath_for_phantomcss ( filepath ) : """Prepare screenshot filename for use with phantomcss . ie , append ' diff ' to the end of the file if a baseline exists"""
try : if os . path . exists ( filepath ) : new_root = '.' . join ( ( os . path . splitext ( filepath ) [ 0 ] , 'diff' ) ) ext = os . path . splitext ( filepath ) [ 1 ] diff_filepath = '' . join ( ( new_root , ext ) ) if os . path . exists ( diff_filepath ) : print 'removi...
def __prepare ( self , filestem , pos , neg , b ) : """Prepares the needed files ."""
posFile = open ( '%s/%s.f' % ( self . tmpdir , filestem ) , 'w' ) negFile = open ( '%s/%s.n' % ( self . tmpdir , filestem ) , 'w' ) bFile = open ( '%s/%s.b' % ( self . tmpdir , filestem ) , 'w' ) posFile . write ( pos ) negFile . write ( neg ) bFile . write ( b ) posFile . close ( ) negFile . close ( ) bFile . close ( ...
def tasks_by_tag ( self , registry_tag ) : """Get tasks from registry by its tag : param registry _ tag : any hash - able object : return : Return task ( if : attr : ` . WTaskRegistryStorage . _ _ multiple _ tasks _ per _ tag _ _ ` is not True ) or list of tasks"""
if registry_tag not in self . __registry . keys ( ) : return None tasks = self . __registry [ registry_tag ] return tasks if self . __multiple_tasks_per_tag__ is True else tasks [ 0 ]
def Add_text ( self , s ) : """Add text to measurement data window ."""
self . logger . DeleteAllItems ( ) FONT_RATIO = self . GUI_RESOLUTION + ( self . GUI_RESOLUTION - 1 ) * 5 if self . GUI_RESOLUTION > 1.1 : font1 = wx . Font ( 11 , wx . SWISS , wx . NORMAL , wx . NORMAL , False , self . font_type ) elif self . GUI_RESOLUTION <= 0.9 : font1 = wx . Font ( 8 , wx . SWISS , wx . NO...
def _parse_singlefile ( self , desired_type : Type [ T ] , file_path : str , encoding : str , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : """Relies on the inner parsing function to parse the file . If _ streaming _ mode is True , the file will be opened and closed by this method . Other...
opts = get_options_for_id ( options , self . get_id_for_options ( ) ) if self . _streaming_mode : # We open the stream , and let the function parse from it file_stream = None try : # Open the file with the appropriate encoding file_stream = open ( file_path , 'r' , encoding = encoding ) # Apply ...
def mutate_in ( self , key , * specs , ** kwargs ) : """Perform multiple atomic modifications within a document . : param key : The key of the document to modify : param specs : A list of specs ( See : mod : ` . couchbase . subdocument ` ) : param bool create _ doc : Whether the document should be create if...
# Note we don ' t verify the validity of the options . lcb does that for # us . sdflags = kwargs . pop ( '_sd_doc_flags' , 0 ) if kwargs . pop ( 'insert_doc' , False ) : sdflags |= _P . CMDSUBDOC_F_INSERT_DOC if kwargs . pop ( 'upsert_doc' , False ) : sdflags |= _P . CMDSUBDOC_F_UPSERT_DOC kwargs [ '_sd_doc_fla...
def __map_entity ( self , entity : dal . AssetClass ) -> AssetClass : """maps the entity onto the model object"""
mapper = self . __get_mapper ( ) ac = mapper . map_entity ( entity ) return ac
def repository_create ( name , body , hosts = None , profile = None ) : '''. . versionadded : : 2017.7.0 Create repository for storing snapshots . Note that shared repository paths have to be specified in path . repo Elasticsearch configuration option . name Repository name body Repository definition as i...
es = _get_instance ( hosts , profile ) try : result = es . snapshot . create_repository ( repository = name , body = body ) return result . get ( 'acknowledged' , False ) except elasticsearch . TransportError as e : raise CommandExecutionError ( "Cannot create repository {0}, server returned code {1} with m...
def remove_duplicates ( items ) : """Returns a list without duplicates , keeping elements order : param items : A list of items : return : The list without duplicates , in the same order"""
if items is None : return items new_list = [ ] for item in items : if item not in new_list : new_list . append ( item ) return new_list
async def proxy_new ( connection , flags , info , name , object_path , interface_name ) : """Asynchronously call the specified method on a DBus proxy object ."""
future = Future ( ) cancellable = None Gio . DBusProxy . new ( connection , flags , info , name , object_path , interface_name , cancellable , gio_callback , future , ) result = await future value = Gio . DBusProxy . new_finish ( result ) if value is None : raise RuntimeError ( "Failed to connect DBus object!" ) re...
def getpaths ( self ) : '''If we have children , use a list comprehension to instantiate new paths objects to traverse .'''
self . children = self . getchildren ( ) if self . children is None : return if self . paths is None : self . paths = [ Paths ( self . screen , os . path . join ( self . name , child ) , self . hidden , self . picked , self . expanded , self . sized ) for child in self . children ] return self . paths
def distances_within ( coords_a , coords_b , cutoff , periodic = False , method = "simple" ) : """Calculate distances between the array of coordinates * coord _ a * and * coord _ b * within a certain cutoff . This function is a wrapper around different routines and data structures for distance searches . It r...
mat = distance_matrix ( coords_a , coords_b , cutoff , periodic , method ) return mat [ mat . nonzero ( ) ]
def get_cached_files ( url , server_name = "" , document_root = None ) : """Given a URL , return a list of paths of all cached variations of that file . Doesn ' t include the original file ."""
import glob url_info = process_url ( url , server_name , document_root , check_security = False ) # get path to cache directory with basename of file ( no extension ) filedir = os . path . dirname ( url_info [ 'requested_file' ] ) fileglob = '{0}*{1}' . format ( url_info [ 'base_filename' ] , url_info [ 'ext' ] ) retur...
def granted ( self , lock ) : '''Return True if a previously requested lock has been granted'''
unit = hookenv . local_unit ( ) ts = self . requests [ unit ] . get ( lock ) if ts and self . grants . get ( unit , { } ) . get ( lock ) == ts : return True return False
def poll ( self , scraper_config , headers = None ) : """Custom headers can be added to the default headers . Returns a valid requests . Response , raise requests . HTTPError if the status code of the requests . Response isn ' t valid - see response . raise _ for _ status ( ) The caller needs to close the req...
endpoint = scraper_config . get ( 'prometheus_url' ) # Should we send a service check for when we make a request health_service_check = scraper_config [ 'health_service_check' ] service_check_name = '{}{}' . format ( scraper_config [ 'namespace' ] , '.prometheus.health' ) service_check_tags = [ 'endpoint:{}' . format (...
def set_slotname ( slot , name , host = None , admin_username = None , admin_password = None ) : '''Set the name of a slot in a chassis . slot The slot number to change . name The name to set . Can only be 15 characters long . host The chassis host . admin _ username The username used to access the ...
return __execute_cmd ( 'config -g cfgServerInfo -o cfgServerName -i {0} {1}' . format ( slot , name ) , host = host , admin_username = admin_username , admin_password = admin_password )
def _detect ( env ) : """Detect all the command line tools that we might need for creating the requested output formats ."""
global prefer_xsltproc if env . get ( 'DOCBOOK_PREFER_XSLTPROC' , '' ) : prefer_xsltproc = True if ( ( not has_libxml2 and not has_lxml ) or ( prefer_xsltproc ) ) : # Try to find the XSLT processors __detect_cl_tool ( env , 'DOCBOOK_XSLTPROC' , xsltproc_com , xsltproc_com_priority ) __detect_cl_tool ( env ,...
async def UpgradeSeriesComplete ( self , force , series , tag ) : '''force : bool series : str tag : Entity Returns - > Error'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'MachineManager' , request = 'UpgradeSeriesComplete' , version = 5 , params = _params ) _params [ 'force' ] = force _params [ 'series' ] = series _params [ 'tag' ] = tag reply = await self . rpc ( msg ) return reply
def _open_usb_handle ( serial_number = None , ** kwargs ) : """Open a UsbHandle subclass , based on configuration . If configuration ' remote _ usb ' is set , use it to connect to remote usb , otherwise attempt to connect locally . ' remote _ usb ' is set to usb type , EtherSync or other . Example of Cambri...
init_dependent_flags ( ) remote_usb = conf . remote_usb if remote_usb : if remote_usb . strip ( ) == 'ethersync' : device = conf . ethersync try : mac_addr = device [ 'mac_addr' ] port = device [ 'plug_port' ] except ( KeyError , TypeError ) : raise ValueE...
def TriCross ( self , A = [ ( 100 , 0 , 0 ) , ( 0 , 50 , 60 ) ] , B = [ ( 50 , 50 , 0 ) , ( 0 , 0 , 100 ) ] ) : '''Return the crosspoint of two line A and B in triangular coord . : param A : first line : type A : a list consist of two tuples , beginning and end point of the line : param B : second line : ty...
x0 , y0 = self . TriToBin ( A [ 0 ] [ 0 ] , A [ 0 ] [ 1 ] , A [ 0 ] [ 2 ] ) x1 , y1 = self . TriToBin ( A [ 1 ] [ 0 ] , A [ 1 ] [ 1 ] , A [ 1 ] [ 2 ] ) x2 , y2 = self . TriToBin ( B [ 0 ] [ 0 ] , B [ 0 ] [ 1 ] , B [ 0 ] [ 2 ] ) x3 , y3 = self . TriToBin ( B [ 1 ] [ 0 ] , B [ 1 ] [ 1 ] , B [ 1 ] [ 2 ] ) b1 = ( y1 - y0 )...
def parse_paragraph ( l , c , last_div_node , last_section_node , line ) : """Extracts a paragraph node : param l : The line number ( starting from 0) : param last _ div _ node : The last div node found : param last _ section _ node : The last section node found : param line : The line string ( without inde...
if not line . endswith ( '.' ) : return None name = line . replace ( "." , "" ) if name . strip ( ) == '' : return None if name . upper ( ) in ALL_KEYWORDS : return None parent_node = last_div_node if last_section_node is not None : parent_node = last_section_node node = Name ( Name . Type . Paragraph ,...
def addEntryText ( self ) : """Returns the text to be used for the add new record item . : return < str >"""
if self . tableType ( ) : name = self . tableType ( ) . schema ( ) . displayName ( ) . lower ( ) return 'add new {0}...' . format ( name ) return 'add new record...'
def configure ( self , ** configs ) : """Configure the consumer instance Configuration settings can be passed to constructor , otherwise defaults will be used : Keyword Arguments : bootstrap _ servers ( list ) : List of initial broker nodes the consumer should contact to bootstrap initial cluster metadata...
configs = self . _deprecate_configs ( ** configs ) self . _config = { } for key in self . DEFAULT_CONFIG : self . _config [ key ] = configs . pop ( key , self . DEFAULT_CONFIG [ key ] ) if configs : raise KafkaConfigurationError ( 'Unknown configuration key(s): ' + str ( list ( configs . keys ( ) ) ) ) if self ...
def kld ( d1 , d2 ) : """Return the Kullback - Leibler Divergence ( KLD ) between two distributions . Args : d1 ( np . ndarray ) : The first distribution . d2 ( np . ndarray ) : The second distribution . Returns : float : The KLD of ` ` d1 ` ` from ` ` d2 ` ` ."""
d1 , d2 = flatten ( d1 ) , flatten ( d2 ) return entropy ( d1 , d2 , 2.0 )
def track_to_ref ( track , with_track_no = False ) : """Convert a mopidy track to a mopidy ref ."""
if with_track_no and track . track_no > 0 : name = '%d - ' % track . track_no else : name = '' for artist in track . artists : if len ( name ) > 0 : name += ', ' name += artist . name if ( len ( name ) ) > 0 : name += ' - ' name += track . name return Ref . track ( uri = track . uri , name =...
def check_network ( session , configure_network , network , subnet , dns_nameservers = None , allocation_pool = None ) : """Check the network status for the deployment . If needed , it creates a dedicated : * private network / subnet * router between this network and the external network"""
nclient = neutron . Client ( '2' , session = session , region_name = os . environ [ 'OS_REGION_NAME' ] ) # Check the security groups secgroups = nclient . list_security_groups ( ) [ 'security_groups' ] secgroup_name = SECGROUP_NAME if secgroup_name not in list ( map ( itemgetter ( 'name' ) , secgroups ) ) : secgrou...
def StaticAdd ( cls , collection_urn , rdf_value , timestamp = None , suffix = None , mutation_pool = None ) : """Adds an rdf value to a collection . Adds an rdf value to a collection . Does not require that the collection be open . NOTE : The caller is responsible for ensuring that the collection exists and ...
if rdf_value is None : raise ValueError ( "Can't add None to MultiTypeCollection" ) if mutation_pool is None : raise ValueError ( "Mutation pool can't be none." ) if not isinstance ( rdf_value , rdf_flows . GrrMessage ) : rdf_value = rdf_flows . GrrMessage ( payload = rdf_value ) value_type = rdf_value . ar...
def median_high ( data ) : """Return the high median of data . When the number of data points is odd , the middle value is returned . When it is even , the larger of the two middle values is returned ."""
data = sorted ( data ) n = len ( data ) if n == 0 : raise StatisticsError ( "no median for empty data" ) return data [ n // 2 ]
def color ( self ) : """Whether or not color should be output"""
return self . tty_stream if self . options . color is None else self . options . color
def set_volume ( self , volume ) : """Set volume ."""
for data in self . _group . get ( 'clients' ) : client = self . _server . client ( data . get ( 'id' ) ) yield from client . set_volume ( volume , update_group = False ) client . update_volume ( { 'volume' : { 'percent' : volume , 'muted' : client . muted } } ) _LOGGER . info ( 'set volume to %s on clients ...
def rpc_get_refactor_options ( self , filename , start , end = None ) : """Return a list of possible refactoring options . This list will be filtered depending on whether it ' s applicable at the point START and possibly the region between START and END ."""
try : from elpy import refactor except : raise ImportError ( "Rope not installed, refactorings unavailable" ) ref = refactor . Refactor ( self . project_root , filename ) return ref . get_refactor_options ( start , end )
def circle_right ( self , radius_m , velocity = VELOCITY , angle_degrees = 360.0 ) : """Go in circle , clock wise : param radius _ m : The radius of the circle ( meters ) : param velocity : The velocity along the circle ( meters / second ) : param angle _ degrees : How far to go in the circle ( degrees ) : ...
distance = 2 * radius_m * math . pi * angle_degrees / 360.0 flight_time = distance / velocity self . start_circle_right ( radius_m , velocity ) time . sleep ( flight_time ) self . stop ( )
def get_types ( json_type : StrOrList ) -> typing . Tuple [ str , str ] : """Returns the json and native python type based on the json _ type input . If json _ type is a list of types it will return the first non ' null ' value . : param json _ type : A json type or a list of json types . : returns : A tuple ...
# If the type is a list , use the first non ' null ' value as the type . if isinstance ( json_type , list ) : for j_type in json_type : if j_type != 'null' : json_type = j_type break return ( json_type , JSON_TYPES_TO_NATIVE [ json_type ] )
def wait ( fs , timeout = None , return_when = ALL_COMPLETED ) : """Wait for the futures in the given sequence to complete . Args : fs : The sequence of Futures ( possibly created by different Executors ) to wait upon . timeout : The maximum number of seconds to wait . If None , then there is no limit on ...
with _AcquireFutures ( fs ) : done = set ( f for f in fs if f . _state in [ CANCELLED_AND_NOTIFIED , FINISHED ] ) not_done = set ( fs ) - done if ( return_when == FIRST_COMPLETED ) and done : return DoneAndNotDoneFutures ( done , not_done ) elif ( return_when == FIRST_EXCEPTION ) and done : ...
def fmtstring ( offset , writes , written = 0 , max_width = 2 , target = None ) : """Build a format string that writes given data to given locations . Can be used easily create format strings to exploit format string bugs . ` writes ` is a list of 2 - or 3 - item tuples . Each tuple represents a memory write ...
if max_width not in ( 1 , 2 , 4 ) : raise ValueError ( 'max_width should be 1, 2 or 4' ) if target is None : target = pwnypack . target . target addrs = [ ] cmds = [ ] piece_writes = [ ] for write in writes : if len ( write ) == 2 : addr , value = write width = target . bits // 8 else : ...
def add_char ( self , char ) : """Process the next character of input through the translation finite state maching ( FSM ) . There are two possible states , buffer pending and not pending , but those are hidden behind the ` ` . flush ( ) ` ` method which must be called at the end of text to ensure any pending...
if char == '\t' : self . flush ( ) self . _r . add_tab ( ) elif char in '\r\n' : self . flush ( ) self . _r . add_br ( ) else : self . _bfr . append ( char )
def _driver_signing_reg_reverse_conversion ( cls , val , ** kwargs ) : '''converts the string value seen in the GUI to the correct registry value for secedit'''
if val is not None : if val . upper ( ) == 'SILENTLY SUCCEED' : return ',' . join ( [ '3' , '0' ] ) elif val . upper ( ) == 'WARN BUT ALLOW INSTALLATION' : return ',' . join ( [ '3' , chr ( 1 ) ] ) elif val . upper ( ) == 'DO NOT ALLOW INSTALLATION' : return ',' . join ( [ '3' , chr ...
def incr ( self , stat , count = 1 , rate = 1 ) : """Increment a stat by ` count ` ."""
self . _send_stat ( stat , '%s|c' % count , rate )
def by_type ( self , type_name ) : '''Return an iterator of doc _ ids of the documents of the specified type .'''
if IRestorator . providedBy ( type_name ) : type_name = type_name . type_name return ( x [ 1 ] for x in self . _links if x [ 0 ] == type_name )
def _do_batched_write_command ( namespace , operation , command , docs , check_keys , opts , ctx ) : """Batched write commands entry point ."""
if ctx . sock_info . compression_context : return _batched_write_command_compressed ( namespace , operation , command , docs , check_keys , opts , ctx ) return _batched_write_command ( namespace , operation , command , docs , check_keys , opts , ctx )
def is_complete ( self ) : """Returns True if this is a complete solution , i . e , all nodes are allocated Todo TO BE REVIEWED Returns bool True if this is a complete solution ."""
allocated = all ( [ node . route_allocation ( ) is not None for node in list ( self . _nodes . values ( ) ) if node . name ( ) != self . _problem . depot ( ) . name ( ) ] ) valid_routes = len ( self . _routes ) == 1 # workaround : try to use only one route ( otherwise process will stop if no of vehicles is reached ) re...
def write_single_xso ( x , dest ) : """Write a single XSO ` x ` to a binary file - like object ` dest ` ."""
gen = XMPPXMLGenerator ( dest , short_empty_elements = True , sorted_attributes = True ) x . unparse_to_sax ( gen )
def groups_remove_moderator ( self , room_id , user_id , ** kwargs ) : """Removes the role of moderator from a user in the current groups ."""
return self . __call_api_post ( 'groups.removeModerator' , roomId = room_id , userId = user_id , kwargs = kwargs )
def add_loadout_preset ( self , file_path : str ) : """Loads a preset using file _ path with all values from that path loaded : param file _ path : the path to load the preset from , if invalid a default preset is returned : return preset : the loadout preset created"""
if file_path is not None and os . path . isfile ( file_path ) : name = pathlib . Path ( file_path ) . stem else : name = "new preset" if file_path in self . loadout_presets : return self . loadout_presets [ file_path ] preset = LoadoutPreset ( name , file_path ) self . loadout_presets [ preset . config_path...
def top ( self , z : float = 0.0 ) -> Location : """: param z : the z distance in mm : return : a Point corresponding to the absolute position of the top - center of the well relative to the deck ( with the front - left corner of slot 1 as ( 0,0,0 ) ) . If z is specified , returns a point offset by z mm fro...
return Location ( self . _position + Point ( 0 , 0 , z ) , self )
def pys_width2xls_width ( self , pys_width ) : """Returns xls width from given pyspread width"""
width_0 = get_default_text_extent ( "0" ) [ 0 ] # Scale relative to 12 point font instead of 10 point width_0_char = pys_width * 1.2 / width_0 return int ( width_0_char * 256.0 )
def get_reviews ( self , listing_id , offset = 0 , limit = 20 ) : """Get reviews for a given listing"""
params = { '_order' : 'language_country' , 'listing_id' : str ( listing_id ) , '_offset' : str ( offset ) , 'role' : 'all' , '_limit' : str ( limit ) , '_format' : 'for_mobile_client' , } print ( self . _session . headers ) r = self . _session . get ( API_URL + "/reviews" , params = params ) r . raise_for_status ( ) re...
def push_to_cache ( self ) : """Try to push the node into a cache"""
# This should get called before the Nodes ' . built ( ) method is # called , which would clear the build signature if the file has # a source scanner . # We have to clear the local memoized values * before * we push # the node to cache so that the memoization of the self . exists ( ) # return value doesn ' t interfere ...
def agent_updated ( self , context , payload ) : """Deal with agent updated RPC message ."""
try : if payload [ 'admin_state_up' ] : # TODO ( hareeshp ) : implement agent updated handling pass except KeyError as e : LOG . error ( "Invalid payload format for received RPC message " "`agent_updated`. Error is %(error)s. Payload is " "%(payload)s" , { 'error' : e , 'payload' : payload } )
def update ( self , pointvol ) : """Update the bounding ellipsoids using the current set of live points ."""
# Check if we should use the pool for updating . if self . use_pool_update : pool = self . pool else : pool = None # Update the bounding ellipsoids . self . mell . update ( self . live_u , pointvol = pointvol , vol_dec = self . vol_dec , vol_check = self . vol_check , rstate = self . rstate , bootstrap = self ....
def portfolio_from_orders ( orders , funds = 1e5 , price_type = 'close' ) : """Create a DataFrame of portfolio holdings ( # ' s ' of shares for the symbols and dates ) Appends the " $ CASH " symbol to the porfolio and initializes it to ` funds ` indicated . Appends the symbol " total _ value " to store the tota...
portfolio = orders . copy ( ) prices = price_dataframe ( orders . columns , start = orders . index [ 0 ] , end = orders . index [ - 1 ] , price_type = price_type , cleaner = clean_dataframe ) portfolio [ "$CASH" ] = funds - ( orders * prices ) . sum ( axis = 1 ) . cumsum ( ) portfolio [ "total_value" ] = portfolio [ "$...
def create_new ( cls , oldvalue , * args ) : "Raise if the old value already exists"
if oldvalue is not None : raise AlreadyExistsException ( '%r already exists' % ( oldvalue , ) ) return cls . create_instance ( * args )
def add_observer ( self , observer ) : """Adds weak ref to an observer . @ param observer : Instance of class registered with PowerManagementObserver @ raise TypeError : If observer is not registered with PowerManagementObserver abstract class"""
if not isinstance ( observer , PowerManagementObserver ) : raise TypeError ( "observer MUST conform to power.PowerManagementObserver" ) self . _weak_observers . append ( weakref . ref ( observer ) )
def factor_positions ( factor_data , period , long_short = True , group_neutral = False , equal_weight = False , quantiles = None , groups = None ) : """Simulate a portfolio using the factor in input and returns the assets positions as percentage of the total portfolio . Parameters factor _ data : pd . DataFr...
fwd_ret_cols = utils . get_forward_returns_columns ( factor_data . columns ) if period not in fwd_ret_cols : raise ValueError ( "Period '%s' not found" % period ) todrop = list ( fwd_ret_cols ) todrop . remove ( period ) portfolio_data = factor_data . drop ( todrop , axis = 1 ) if quantiles is not None : portfo...
def reset_directory ( directory ) : """Remove ` directory ` if it exists , then create it if it doesn ' t exist ."""
if os . path . isdir ( directory ) : shutil . rmtree ( directory ) if not os . path . isdir ( directory ) : os . makedirs ( directory )
def getAllCols ( self , sddsfile = None ) : """get all available column names from sddsfile : param sddsfile : sdds file name , if not given , rollback to the one that from ` ` _ _ init _ _ ( ) ` ` : return : all sdds data column names : rtype : list : Example : > > > dh = DataExtracter ( ' test . out ' )...
if SDDS_ : if sddsfile is not None : sddsobj = sdds . SDDS ( 2 ) sddsobj . load ( sddsfile ) else : sddsobj = self . sddsobj return sddsobj . columnName else : if sddsfile is None : sddsfile = self . sddsfile return subprocess . check_output ( [ 'sddsquery' , '-col' ,...
def sort ( data , fieldnames = None , already_normalized = False ) : """PASS A FIELD NAME , OR LIST OF FIELD NAMES , OR LIST OF STRUCTS WITH { " field " : field _ name , " sort " : direction }"""
try : if data == None : return Null if not fieldnames : return wrap ( sort_using_cmp ( data , value_compare ) ) if already_normalized : formal = fieldnames else : formal = query . _normalize_sort ( fieldnames ) funcs = [ ( jx_expression_to_function ( f . value ) , f ....
def _batch_norm_new_params ( input_shape , rng , axis = ( 0 , 1 , 2 ) , center = True , scale = True , ** kwargs ) : """Helper to initialize batch norm params ."""
del rng , kwargs axis = ( axis , ) if np . isscalar ( axis ) else axis shape = tuple ( d for i , d in enumerate ( input_shape ) if i not in axis ) beta = np . zeros ( shape , dtype = 'float32' ) if center else ( ) gamma = np . ones ( shape , dtype = 'float32' ) if scale else ( ) return ( beta , gamma )
def _get_query ( self , callback , schema , query = None , * args , ** kwargs ) : """this is just a common wrapper around all the get queries since they are all really similar in how they execute"""
if not query : query = Query ( ) ret = None with self . connection ( ** kwargs ) as connection : kwargs [ 'connection' ] = connection try : if connection . in_transaction ( ) : # we wrap SELECT queries in a transaction if we are in a transaction because # it could cause data loss if it faile...
def _do_layout ( self , data ) : """Lays the text out into separate lines and calculates their total height ."""
c = data [ 'output' ] word_space = c . text_width ( ' ' , font_name = self . font_name , font_size = self . font_size ) # Arrange the text as words on lines self . _layout = [ [ ] ] x = self . font_size if self . paragraph_indent else 0 for word in self . text . split ( ) : ww = c . text_width ( word , font_name = ...
def unpackSample ( self , rawData ) : """unpacks a single sample of data ( where sample length is based on the currently enabled sensors ) . : param rawData : the data to convert : return : a converted data set ."""
length = len ( rawData ) # TODO error if not multiple of 2 # logger . debug ( " > > unpacking sample % d length % d " , self . _ sampleIdx , length ) unpacked = struct . unpack ( ">" + ( 'h' * ( length // 2 ) ) , memoryview ( bytearray ( rawData ) ) . tobytes ( ) ) # store the data in a dictionary mpu6050 = collections...
def post_task ( task_data , task_uri = '/tasks' ) : """Create Spinnaker Task . Args : task _ data ( str ) : Task JSON definition . Returns : str : Spinnaker Task ID . Raises : AssertionError : Error response from Spinnaker ."""
url = '{}/{}' . format ( API_URL , task_uri . lstrip ( '/' ) ) if isinstance ( task_data , str ) : task_json = task_data else : task_json = json . dumps ( task_data ) resp = requests . post ( url , data = task_json , headers = HEADERS , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) resp_json = resp . json...
def load_project_definition ( path : str ) -> dict : """Load the cauldron . json project definition file for the given path . The path can be either a source path to the cauldron . json file or the source directory where a cauldron . json file resides . : param path : The source path or directory where the ...
source_path = get_project_source_path ( path ) if not os . path . exists ( source_path ) : raise FileNotFoundError ( 'Missing project file: {}' . format ( source_path ) ) with open ( source_path , 'r' ) as f : out = json . load ( f ) project_folder = os . path . split ( os . path . dirname ( source_path ) ) [ -...
def main ( ) : '''Main entry point for the bioinfo CLI .'''
args = docopt ( __doc__ , version = __version__ ) if 'bam_coverage' in args : bam_coverage ( args [ '<reference>' ] , args [ '<alignments>' ] , int ( args [ '<minmatch>' ] ) , min_mapq = int ( args [ '--mapq' ] ) , min_len = float ( args [ '--minlen' ] ) )
def run_init ( device_type , args ) : """Initialize hardware - based GnuPG identity ."""
util . setup_logging ( verbosity = args . verbose ) log . warning ( 'This GPG tool is still in EXPERIMENTAL mode, ' 'so please note that the API and features may ' 'change without backwards compatibility!' ) verify_gpg_version ( ) # Prepare new GPG home directory for hardware - based identity device_name = os . path . ...
def build_db_tables ( db ) : """Build Seshet ' s basic database schema . Requires one parameter , ` db ` as ` pydal . DAL ` instance ."""
if not isinstance ( db , DAL ) or not db . _uri : raise Exception ( "Need valid DAL object to define tables" ) # event log - self - explanatory , logs all events db . define_table ( 'event_log' , Field ( 'event_type' ) , Field ( 'event_time' , 'datetime' ) , Field ( 'source' ) , Field ( 'target' ) , Field ( 'messag...
def validateSatellite ( config , isochrone , kernel , stellar_mass , distance_modulus , trials = 1 , debug = False , seed = 0 ) : """Tool for simple MC validation studies - - specifically to create multiple realizations of a satellite given an CompositeIsochrone object , Kernel object , stellar mass ( M _ sol ) f...
logger . info ( '=== Validate Satellite ===' ) config . params [ 'kernel' ] [ 'params' ] = [ kernel . r_h ] # TODO : Need better solution to update size ? ? logger . debug ( 'Using Plummer profile spatial model with half-light radius %.2f deg' % ( config . params [ 'kernel' ] [ 'params' ] [ 0 ] ) ) roi = ugali . observ...
def calculate_tuple_product ( numbers ) : """This Python function computes the product of all numbers in a given tuple . Examples : calculate _ tuple _ product ( ( 4 , 3 , 2 , 2 , - 1 , 18 ) ) - > - 864 calculate _ tuple _ product ( ( 1 , 2 , 3 ) ) - > 6 calculate _ tuple _ product ( ( - 2 , - 4 , - 6 ) ) -...
result = 1 for num in numbers : result *= num return result
async def change_presence ( self , * , activity = None , status = None , afk = False ) : """| coro | Changes the client ' s presence . The activity parameter is a : class : ` . Activity ` object ( not a string ) that represents the activity being done currently . This could also be the slimmed down versions ,...
if status is None : status = 'online' status_enum = Status . online elif status is Status . offline : status = 'invisible' status_enum = Status . offline else : status_enum = status status = str ( status ) await self . ws . change_presence ( activity = activity , status = status , afk = afk ) fo...
def _set_proto_vrrpv3 ( self , v , load = False ) : """Setter method for proto _ vrrpv3 , mapped from YANG variable / rbridge _ id / ipv6 / proto _ vrrpv3 ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ proto _ vrrpv3 is considered as a private method . ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = proto_vrrpv3 . proto_vrrpv3 , is_container = 'container' , presence = False , yang_name = "proto-vrrpv3" , rest_name = "protocol" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe...
def visit_lambda ( self , node ) : """return an astroid . Lambda node as string"""
args = node . args . accept ( self ) body = node . body . accept ( self ) if args : return "lambda %s: %s" % ( args , body ) return "lambda: %s" % body
def shutdown_mp ( self , clean = True ) : """Shutdown all the multiprocessing . : param bool clean : Whether to shutdown things cleanly , or force a quick and dirty shutdown ."""
# The server runs on a worker thread , so we need to shut it down first . if hasattr ( self , 'server' ) : # Shutdown the server quickly . try : # For some strange reason , this throws an OSError on windows . self . server . socket . shutdown ( socket . SHUT_RDWR ) except OSError : pass self...
def write_section ( self , name , features , info , f ) : """Provides formatting for one section ( e . g . hydrogen bonds )"""
if not len ( info ) == 0 : f . write ( '\n\n### %s ###\n' % name ) f . write ( '%s\n' % '\t' . join ( features ) ) for line in info : f . write ( '%s\n' % '\t' . join ( map ( str , line ) ) )
def extractall ( self , path = None , members = None , pwd = None ) : """Extract all members from the archive to the current working directory . ` path ' specifies a different directory to extract to . ` members ' is optional and must be a subset of the list returned by namelist ( ) ."""
if members is None : members = self . namelist ( ) for zipinfo in members : self . extract ( zipinfo , path , pwd )
def _basic_mult ( A , B ) : """A stripped - down copy of the Wallace multiplier in rtllib"""
if len ( B ) == 1 : A , B = B , A # so that we can reuse the code below : ) if len ( A ) == 1 : return concat_list ( list ( A & b for b in B ) + [ Const ( 0 ) ] ) # keep WireVector len consistent result_bitwidth = len ( A ) + len ( B ) bits = [ [ ] for weight in range ( result_bitwidth ) ] for i , a in enum...
def port ( self ) : """Port part of URL , with scheme - based fallback . None for relative URLs or URLs without explicit port and scheme without default port substitution ."""
return self . _val . port or DEFAULT_PORTS . get ( self . _val . scheme )
def process_runs ( mv_districts , n_of_districts , output_info , run_id , base_path ) : '''Runs a process organized by parallel _ run ( ) The function take all districts mv _ districts and divide them into clusters of n _ of _ districts each . For each cluster , ding0 is run and the resulting network is saved...
# database connection / session engine = db . connection ( section = 'oedb' ) session = sessionmaker ( bind = engine ) ( ) clusters = [ mv_districts [ x : x + n_of_districts ] for x in range ( 0 , len ( mv_districts ) , n_of_districts ) ] output_clusters = [ ] for cl in clusters : print ( '\n#######################...
def homegearCheckInit ( self , remote ) : """Check if proxy is still initialized"""
rdict = self . remotes . get ( remote ) if not rdict : return False if rdict . get ( 'type' ) != BACKEND_HOMEGEAR : return False try : interface_id = "%s-%s" % ( self . _interface_id , remote ) return self . proxies [ interface_id ] . clientServerInitialized ( interface_id ) except Exception as err : ...
def get_remote_file ( url ) : """Wrapper around ` ` request . get ` ` which nicely handles connection errors"""
try : return requests . get ( url ) except requests . exceptions . ConnectionError as e : print ( "Connection error!" ) print ( e . message . reason ) exit ( 1 )
def add_user ( self , user , group ) : """Adds user to a group"""
if self . is_user_in ( user , group ) : raise UserAlreadyInAGroup self . new_groups . add ( group , user )
def add_entry_listener ( self , key = None , predicate = None , added_func = None , removed_func = None , updated_func = None , evicted_func = None , clear_all_func = None ) : """Adds a continuous entry listener for this map . Listener will get notified for map events filtered with given parameters . : param ke...
if key and predicate : key_data = self . _to_data ( key ) predicate_data = self . _to_data ( predicate ) request = replicated_map_add_entry_listener_to_key_with_predicate_codec . encode_request ( self . name , key_data , predicate_data , False ) elif key and not predicate : key_data = self . _to_data ( ...
def parse_args ( args = None ) : """Parse arguments from sys . argv"""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '-w' , '--window' , default = "pyqt5" , choices = find_window_classes ( ) , help = 'Name for the window type to use' , ) parser . add_argument ( '-fs' , '--fullscreen' , action = "store_true" , help = 'Open the window in fullscreen mode' , ) parser . add_ar...
def get_tree_zip ( self , repository_id , sha1 , project = None , project_id = None , recursive = None , file_name = None , ** kwargs ) : """GetTreeZip . [ Preview API ] The Tree endpoint returns the collection of objects underneath the specified tree . Trees are folders in a Git repository . : param str reposi...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) if sha1 is not None : route_values [ 'sha1' ] ...