signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def sg_summary_gradient ( tensor , gradient , prefix = None , name = None ) : r"""Register ` tensor ` to summary report as ` gradient ` Args : tensor : A ` Tensor ` to log as gradient gradient : A 0 - D ` Tensor ` . A gradient to log prefix : A ` string ` . A prefix to display in the tensor board web UI . ...
# defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics # noinspection PyBroadException _scalar ( name + '/grad' , tf . reduce_mean ( tf . abs ( gradient ) ) ) _histogram ( name + '/grad-h' , tf . abs ( gra...
def _query ( self , ResponseGroup = "Large" , ** kwargs ) : """Query . Query Amazon search and check for errors . : return : An lxml root element ."""
response = self . api . ItemSearch ( ResponseGroup = ResponseGroup , ** kwargs ) root = objectify . fromstring ( response ) if ( hasattr ( root . Items . Request , 'Errors' ) and not hasattr ( root . Items , 'Item' ) ) : code = root . Items . Request . Errors . Error . Code msg = root . Items . Request . Errors...
def file_comparison ( files0 , files1 ) : """Compares two dictionaries of files returning their difference . { ' created _ files ' : [ < files in files1 and not in files0 > ] , ' deleted _ files ' : [ < files in files0 and not in files1 > ] , ' modified _ files ' : [ < files in both files0 and files1 but diff...
comparison = { 'created_files' : [ ] , 'deleted_files' : [ ] , 'modified_files' : [ ] } for path , sha1 in files1 . items ( ) : if path in files0 : if sha1 != files0 [ path ] : comparison [ 'modified_files' ] . append ( { 'path' : path , 'original_sha1' : files0 [ path ] , 'sha1' : sha1 } ) ...
def calculate_fitness ( self ) : """Calculcate your fitness ."""
if self . fitness is not None : raise Exception ( "You are calculating the fitness of agent {}, " . format ( self . id ) + "but they already have a fitness" ) infos = self . infos ( ) said_blue = ( [ i for i in infos if isinstance ( i , Meme ) ] [ 0 ] . contents == "blue" ) proportion = float ( max ( State . query ...
def accepts_admin_roles ( func ) : """Decorator that accepts only admin roles : param func : : return :"""
if inspect . isclass ( func ) : apply_function_to_members ( func , accepts_admin_roles ) return func else : @ functools . wraps ( func ) def decorator ( * args , ** kwargs ) : return accepts_roles ( * ROLES_ADMIN ) ( func ) ( * args , ** kwargs ) return decorator
def sayHelloPromise ( self , name = "Not given" , message = "nothing" ) : """Implementation of IHello . sayHelloPromise . This method will be executed via some thread , and the remote caller will not block ."""
print ( "Python.sayHelloPromise called by: {0} " "with message: '{1}'" . format ( name , message ) ) return ( "PythonPromise says: Howdy {0} " "that's a nice runtime you got there" . format ( name ) )
def send_enable_vlan_on_trunk_int ( self , nexus_host , vlanid , intf_type , interface , is_native , add_mode = False ) : """Gathers and sends an interface trunk XML snippet ."""
path_snip , body_snip = self . _get_vlan_body_on_trunk_int ( nexus_host , vlanid , intf_type , interface , is_native , False , add_mode ) self . send_edit_string ( nexus_host , path_snip , body_snip )
def fastq_verifier ( entries , ambiguous = False ) : """Raises error if invalid FASTQ format detected Args : entries ( list ) : A list of FastqEntry instances ambiguous ( bool ) : Permit ambiguous bases , i . e . permit non - ACGTU bases Raises : FormatError : Error when FASTQ format incorrect with descri...
if ambiguous : regex = r'^@.+{0}[ACGTURYKMSWBDHVNX]+{0}' r'\+.*{0}[!"#$%&\'()*+,-./0123456' r'789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ' r'[\]^_`abcdefghijklmnopqrstuvwxyz' r'{{|}}~]+{0}$' . format ( os . linesep ) else : regex = r'^@.+{0}[ACGTU]+{0}' r'\+.*{0}[!-~]+{0}$' . format ( os . linesep ) delimiter = r'{0}'...
def load_components ( * paths , ** kwargs ) : """Loads all components on the paths . Each path should be a package or module . All components beneath a path are loaded . Args : paths ( str ) : A package or module to load Keyword Args : include ( str ) : A regular expression of packages and modules to incl...
num_loaded = 0 for path in paths : num_loaded += _load_components ( path , ** kwargs ) return num_loaded
def _check_config ( self ) : """Check presence of default config files . : rtype : bool"""
current_path = os . path . relpath ( os . getcwd ( ) ) accepted_files = [ "orator.yml" , "orator.py" ] for accepted_file in accepted_files : config_file = os . path . join ( current_path , accepted_file ) if os . path . exists ( config_file ) : if self . _handle_config ( config_file ) : retu...
def update ( self , ** args ) : """Updates a Clip . Parameters : - args Dictionary of other fields Accepted fields can be found here : https : / / github . com / kippt / api - documentation / blob / master / objects / clip . md"""
# JSONify our data . data = json . dumps ( args ) r = requests . put ( "https://kippt.com/api/clips/%s" % ( self . id ) , headers = self . kippt . header , data = data ) return ( r . json ( ) )
from typing import List def longest_subarray ( nums : List [ int ] , threshold : int ) -> int : """Finds the length of the longest subarray of nums starting at index l and ending at index r ( 0 < = l < = r < nums . length ) that satisfies the following conditions : - nums [ l ] % 2 = = 0 - For all indices i...
l = 0 ans = 0 while l < len ( nums ) : if nums [ l ] % 2 == 0 and nums [ l ] <= threshold : r = l + 1 while r < len ( nums ) and nums [ r - 1 ] % 2 != nums [ r ] % 2 and nums [ r ] <= threshold : r += 1 ans = max ( ans , r - l ) l = r else : l = l + 1 return a...
def init ( self , conf ) : """Initialize MacroResolver instance with conf . Must be called at least once . : param conf : configuration to load : type conf : alignak . objects . Config : return : None"""
# For searching class and elements for on - demand # we need link to types self . my_conf = conf self . lists_on_demand = [ ] self . hosts = self . my_conf . hosts # For special void host _ name handling . . . self . host_class = self . hosts . inner_class self . lists_on_demand . append ( self . hosts ) self . service...
def from_dsn ( dsn , ** kwargs ) : r"""Return an instaance of InfluxDBClient from given data source name . Returns an instance of InfluxDBClient from the provided data source name . Supported schemes are " influxdb " , " https + influxdb " , " udp + influxdb " . Parameters for the InfluxDBClient constructor m...
init_args = { } conn_params = urlparse ( dsn ) scheme_info = conn_params . scheme . split ( '+' ) if len ( scheme_info ) == 1 : scheme = scheme_info [ 0 ] modifier = None else : modifier , scheme = scheme_info if scheme != 'influxdb' : raise ValueError ( 'Unknown scheme "{0}".' . format ( scheme ) ) if ...
def _parse_pem_data ( pem_data ) : """Parse PEM - encoded X . 509 certificate chain . Args : pem _ data : str . PEM file retrieved from SignatureCertChainUrl . Returns : list or bool : If url is valid , returns the certificate chain as a list of cryptography . hazmat . backends . openssl . x509 . _ Certif...
sep = '-----BEGIN CERTIFICATE-----' cert_chain = [ six . b ( sep + s ) for s in pem_data . split ( sep ) [ 1 : ] ] certs = [ ] load_cert = x509 . load_pem_x509_certificate for cert in cert_chain : try : certs . append ( load_cert ( cert , default_backend ( ) ) ) except ValueError : warnings . wa...
def getDeviceToAbsoluteTrackingPose ( self , eOrigin , fPredictedSecondsToPhotonsFromNow , unTrackedDevicePoseArrayCount , pTrackedDevicePoseArray = None ) : """The pose that the tracker thinks that the HMD will be in at the specified number of seconds into the future . Pass 0 to get the state at the instant the ...
fn = self . function_table . getDeviceToAbsoluteTrackingPose if pTrackedDevicePoseArray is None : pTrackedDevicePoseArray = ( TrackedDevicePose_t * unTrackedDevicePoseArrayCount ) ( ) pTrackedDevicePoseArray = cast ( pTrackedDevicePoseArray , POINTER ( TrackedDevicePose_t ) ) fn ( eOrigin , fPredictedSecondsToPhoto...
def send ( self , message ) : """Sends a message , but does not return a response : returns : None - can ' t receive a response over UDP"""
self . socket . sendto ( message . SerializeToString ( ) , self . address ) return None
def get_catalog_admin_session ( self , proxy ) : """Gets the catalog administrative session for creating , updating and deleting catalogs . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . cataloging . CatalogAdminSession ) - a ` ` CatalogAdminSession ` ` raise : NullArgument - ` ` proxy ` `...
if not self . supports_catalog_admin ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . CatalogAdminSession ( proxy = proxy , runtime = self . _runtime )
def _wrap_angle ( self , theta ) : """Helper method : Wrap any angle to lie between - pi and pi Odd multiples of pi are wrapped to + pi ( as opposed to - pi )"""
result = ( ( theta + pi ) % ( 2 * pi ) ) - pi if result == - pi : result = pi return result
def longest_common_substring ( s1 , s2 ) : """References : # https : / / en . wikibooks . org / wiki / Algorithm _ Implementation / Strings / Longest _ common _ substring # Python2"""
m = [ [ 0 ] * ( 1 + len ( s2 ) ) for i in range ( 1 + len ( s1 ) ) ] longest , x_longest = 0 , 0 for x in range ( 1 , 1 + len ( s1 ) ) : for y in range ( 1 , 1 + len ( s2 ) ) : if s1 [ x - 1 ] == s2 [ y - 1 ] : m [ x ] [ y ] = m [ x - 1 ] [ y - 1 ] + 1 if m [ x ] [ y ] > longest : ...
def update_profiles ( adapter ) : """For all cases having vcf _ path , update the profile string for the samples Args : adapter ( MongoAdapter ) : Adapter to mongodb"""
for case in adapter . cases ( ) : # If the case has a vcf _ path , get the profiles and update the # case with new profiled individuals . if case . get ( 'profile_path' ) : profiles = get_profiles ( adapter , case [ 'profile_path' ] ) profiled_individuals = deepcopy ( case [ 'individuals' ] ) ...
def assert_keys_have_values ( self , caller , * keys ) : """Check that keys list are all in context and all have values . Args : * keys : Will check each of these keys in context caller : string . Calling function name - just used for informational messages Raises : KeyNotInContextError : Key doesn ' t ...
for key in keys : self . assert_key_has_value ( key , caller )
def get_model_changes ( entity_type , year = None , month = None , day = None , hour = None , since = None ) : # type : ( Text , int , int , int , int , datetime ) - > Query """Get models modified at the given date with the Audit service . : param entity _ type : string like " extranet _ medicen . apps . crm . mo...
query = AuditEntry . query if since : query = query . filter ( AuditEntry . happened_at >= since ) if year : query = query . filter ( extract ( "year" , AuditEntry . happened_at ) == year ) if month : query = query . filter ( extract ( "month" , AuditEntry . happened_at ) == month ) if day : query = que...
def failure_reason ( self , failure_index = None ) : """Get the reason for a failure . Args : failure _ index : Index of the fail to return the graph for ( can be negative ) . If None , the most appropriate failure is chosen according to these rules : - If the fail is cyclic , the most recent fail ( the o...
phase , _ = self . _get_failed_phase ( failure_index ) return phase . failure_reason
def _add_list_getter ( self ) : """Add a read - only ` ` { prop _ name } _ lst ` ` property to the element class to retrieve a list of child elements matching this type ."""
prop_name = '%s_lst' % self . _prop_name property_ = property ( self . _list_getter , None , None ) setattr ( self . _element_cls , prop_name , property_ )
def nfa_complementation ( nfa : dict ) -> dict : """Returns a DFA reading the complemented language read by input NFA . Complement a nondeterministic automaton is possible complementing the determinization of it . The construction is effective , but it involves an exponential blow - up , since determiniza...
determinized_nfa = nfa_determinization ( nfa ) return DFA . dfa_complementation ( determinized_nfa )
def _get_ref ( repo , name ) : '''Return ref tuple if ref is in the repo .'''
if name == 'base' : name = repo [ 'base' ] if name == repo [ 'base' ] or name in envs ( ) : if repo [ 'branch_method' ] == 'branches' : return _get_branch ( repo [ 'repo' ] , name ) or _get_tag ( repo [ 'repo' ] , name ) elif repo [ 'branch_method' ] == 'bookmarks' : return _get_bookmark ( r...
def unlock ( self ) : """Unlock the table ( s )"""
cursor = connection . cursor ( ) cursor . execute ( "UNLOCK TABLES" ) logger . debug ( 'Unlocked tables' ) row = cursor . fetchone ( ) return row
def source_debianize_name ( name ) : "make name acceptable as a Debian source package name"
name = name . replace ( '_' , '-' ) name = name . replace ( '.' , '-' ) name = name . lower ( ) return name
def _check_require_version ( namespace , stacklevel ) : """A context manager which tries to give helpful warnings about missing gi . require _ version ( ) which could potentially break code if only an older version than expected is installed or a new version gets introduced . with _ check _ require _ versio...
repository = GIRepository ( ) was_loaded = repository . is_registered ( namespace ) yield if was_loaded : # it was loaded before by another import which depended on this # namespace or by C code like libpeas return if namespace in ( "GLib" , "GObject" , "Gio" ) : # part of glib ( we have bigger problems if versions...
def add_key ( self , key , label , notes = None ) : """Adds a new SSH key to the account . : param string key : The SSH key to add : param string label : The label for the key : param string notes : Additional notes for the key : returns : A dictionary of the new key ' s information ."""
order = { 'key' : key , 'label' : label , 'notes' : notes , } return self . sshkey . createObject ( order )
def snooze ( self , requester , duration ) : """Snooze incident . : param requester : The email address of the individual requesting snooze ."""
path = '{0}/{1}/{2}' . format ( self . collection . name , self . id , 'snooze' ) data = { "duration" : duration } extra_headers = { "From" : requester } return self . pagerduty . request ( 'POST' , path , data = _json_dumper ( data ) , extra_headers = extra_headers )
def convert_to_struct ( value ) : """Convert the following to Structs : - dicts - list elements that are dicts This function is harmless to call on arbitrary variables ."""
direct_converts = [ dict , OrderedDict , UserDict ] if type ( value ) in direct_converts : # Convert dict - like things to Struct value = Struct ( value ) elif isinstance ( value , list ) : # Process list elements value = [ convert_to_struct ( z ) for z in value ] # Done return value
def extract_polygon_area ( self , pid , polygon_points ) : """Extract all data points whose element centroid lies within the given polygon . Parameters Returns"""
polygon = shapgeo . Polygon ( polygon_points ) xy = self . grid . get_element_centroids ( ) in_poly = [ ] for nr , point in enumerate ( xy ) : if shapgeo . Point ( point ) . within ( polygon ) : in_poly . append ( nr ) values = self . parsets [ pid ] [ in_poly ] return np . array ( in_poly ) , values
def check_symmetric ( array , tol = 1E-10 , raise_warning = True , raise_exception = False ) : """Make sure that array is 2D , square and symmetric . If the array is not symmetric , then a symmetrized version is returned . Optionally , a warning or exception is raised if the matrix is not symmetric . Parame...
if ( array . ndim != 2 ) or ( array . shape [ 0 ] != array . shape [ 1 ] ) : raise ValueError ( "array must be 2-dimensional and square. " "shape = {0}" . format ( array . shape ) ) if sp . issparse ( array ) : diff = array - array . T # only csr , csc , and coo have ` data ` attribute if diff . format ...
def add_data_dict ( self , datadict ) : '''Sets the data and country codes via a dictionary . i . e . { ' DE ' : 50 , ' GB ' : 30 , ' AT ' : 70}'''
self . set_codes ( list ( datadict . keys ( ) ) ) self . add_data ( list ( datadict . values ( ) ) )
def set_dryrun ( dryrun ) : """: param bool dryrun : New value for runez . DRYRUN : return bool : Old value"""
r = _get_runez ( ) old = r . DRYRUN r . DRYRUN = bool ( dryrun ) return old
def add_point_by_masses ( self , mass1 , mass2 , spin1z , spin2z , vary_fupper = False ) : """Add a point to the template bank . This differs from add point to bank as it assumes that the chi coordinates and the products needed to use vary _ fupper have not already been calculated . This function calculates t...
# Test that masses are the expected way around ( ie . mass1 > mass2) if mass2 > mass1 : if not self . spin_warning_given : warn_msg = "Am adding a template where mass2 > mass1. The " warn_msg += "convention is that mass1 > mass2. Swapping mass1 " warn_msg += "and mass2 and adding point to ba...
def get_neighbors ( distance_matrix , source , eps ) : """Given a matrix of distance between couples of points , return the list of every point closer than eps from a certain point ."""
return [ dest for dest , distance in enumerate ( distance_matrix [ source ] ) if distance < eps ]
def filter_values ( self , pattern , flags = 0 ) : """| Filters the : meth : ` PlistFileParser . elements ` class property elements using given pattern . | Will return a list of matching elements values , if you want to get only one element value , use the : meth : ` PlistFileParser . get _ value ` method inste...
values = [ ] if not self . __elements : return values for item in foundations . walkers . dictionaries_walker ( self . __elements ) : path , element , value = item if re . search ( pattern , element , flags ) : values . append ( value ) return values
def get_long_task_info ( self , long_task_id , expand = None , callback = None ) : """Returns information about a long - running task . : param long _ task _ id ( string ) : The key of the task to be returned . : param expand ( string ) : A comma separated list of properties to expand on the task . Default : Em...
params = { } if expand : params [ "expand" ] = expand return self . _service_get_request ( "rest/api/longtask/{id}" . format ( id = long_task_id ) , params = params , callback = callback )
def close ( self , cancelled = False ) : """Close this temporary pop - up . : param cancelled : Whether the pop - up was cancelled ( e . g . by pressing Esc ) ."""
self . _on_close ( cancelled ) self . _scene . remove_effect ( self )
def minimum_font_point_size ( self , value ) : """Setter for * * self . _ _ minimum _ font _ point _ size * * attribute . : param value : Attribute value . : type value : int"""
if value is not None : assert type ( value ) in ( int , float ) , "'{0}' attribute: '{1}' type is not 'int' or 'float'!" . format ( "minimum_font_point_size" , value ) assert value > 0 , "'{0}' attribute: '{1}' need to be exactly positive!" . format ( "minimum_font_point_size" , value ) self . __minimum_font_po...
def _write_num_zeros ( self ) -> None : "Writes the number of zeroes in the gradients to Tensorboard ."
gradient_nps = [ to_np ( x . data ) for x in self . gradients ] num_zeros = sum ( ( np . asarray ( x ) == 0.0 ) . sum ( ) for x in gradient_nps ) self . _add_gradient_scalar ( 'num_zeros' , scalar_value = num_zeros )
def value ( self ) : """The current value of the mean ."""
return self . _sum / tf . cast ( self . _count , self . _dtype )
def is_mouse_over ( self , event , include_label = True , width_modifier = 0 ) : """Check if the specified mouse event is over this widget . : param event : The MouseEvent to check . : param include _ label : Include space reserved for the label when checking . : param width _ modifier : Adjustement to width ...
# Disabled widgets should not react to the mouse . logger . debug ( "Widget: %s (%d, %d) (%d, %d)" , self , self . _x , self . _y , self . _w , self . _h ) if self . _is_disabled : return False # Check for any overlap if self . _y <= event . y < self . _y + self . _h : if ( ( include_label and self . _x <= even...
def write ( self , message , opcode = None , encode = True , ** kw ) : '''Write a new ` ` message ` ` into the wire . It uses the : meth : ` ~ . FrameParser . encode ` method of the websocket : attr : ` parser ` . : param message : message to send , must be a string or bytes : param opcode : optional ` ` op...
if encode : message = self . parser . encode ( message , opcode = opcode , ** kw ) result = self . connection . write ( message ) if opcode == 0x8 : self . connection . close ( ) return result
def move_datetime_month ( dt , direction , num_shifts ) : """Move datetime 1 month in the chosen direction . unit is a no - op , to keep the API the same as the day case"""
delta = relativedelta ( months = + num_shifts ) return _move_datetime ( dt , direction , delta )
def batchcn ( args ) : """% prog batchcn workdir samples . csv Run CNV segmentation caller in batch mode . Scans a workdir ."""
p = OptionParser ( batchcn . __doc__ ) p . add_option ( "--upload" , default = "s3://hli-mv-data-science/htang/ccn" , help = "Upload cn and seg results to s3" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) workdir , samples = args upload = opts . upload store = ...
def setWritePrivs ( fname , makeWritable , ignoreErrors = False ) : """Set a file named fname to be writable ( or not ) by user , with the option to ignore errors . There is nothing ground - breaking here , but I was annoyed with having to repeate this little bit of code ."""
privs = os . stat ( fname ) . st_mode try : if makeWritable : os . chmod ( fname , privs | stat . S_IWUSR ) else : os . chmod ( fname , privs & ( ~ stat . S_IWUSR ) ) except OSError : if ignoreErrors : pass # just try , don ' t whine else : raise
def install_handler ( self , app ) : """Install log handler on Flask application ."""
# Check if directory exists . basedir = dirname ( app . config [ 'LOGGING_FS_LOGFILE' ] ) if not exists ( basedir ) : raise ValueError ( 'Log directory {0} does not exists.' . format ( basedir ) ) handler = RotatingFileHandler ( app . config [ 'LOGGING_FS_LOGFILE' ] , backupCount = app . config [ 'LOGGING_FS_BACKUP...
def listdir ( self , path ) : """Get an iterable with GCS folder contents . Iterable contains paths relative to queried path ."""
bucket , obj = self . _path_to_bucket_and_key ( path ) obj_prefix = self . _add_path_delimiter ( obj ) if self . _is_root ( obj_prefix ) : obj_prefix = '' obj_prefix_len = len ( obj_prefix ) for it in self . _list_iter ( bucket , obj_prefix ) : yield self . _add_path_delimiter ( path ) + it [ 'name' ] [ obj_pre...
def _zforce ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ zforce PURPOSE : evaluate the vertical force for this potential INPUT : R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT : the vertical force = - dphi / dz HISTORY : 2016-05-09 - Written - A...
return - nu . sign ( z ) * self . _denom ( R , z ) ** - 1.5 * ( self . _a + nu . fabs ( z ) )
def list_all_before ( self , message_id , limit = None ) : """Return all group messages created before a message . : param str message _ id : the ID of a message : param int limit : maximum number of messages per page : return : group messages : rtype : generator"""
return self . list_before ( message_id , limit = limit ) . autopage ( )
def get_translation_cache_key ( translated_model , master_id , language_code ) : """The low - level function to get the cache key for a translation ."""
# Always cache the entire object , as this already produces # a lot of queries . Don ' t go for caching individual fields . return 'parler.{0}.{1}.{2}.{3}' . format ( translated_model . _meta . app_label , translated_model . __name__ , master_id , language_code )
def readExcel ( usr_path = "" ) : """Read Excel file ( s ) Enter a file path , directory path , or leave args blank to trigger gui . : param str usr _ path : Path to file / directory ( optional ) : return str cwd : Current working directory"""
global cwd , files start = clock ( ) files [ ".xls" ] = [ ] __read ( usr_path , ".xls" ) end = clock ( ) logger_benchmark . info ( log_benchmark ( "readExcel" , start , end ) ) return cwd
def get_anonymous_session ( self ) -> requests . Session : """Returns our default anonymous requests . Session object ."""
session = requests . Session ( ) session . cookies . update ( { 'sessionid' : '' , 'mid' : '' , 'ig_pr' : '1' , 'ig_vw' : '1920' , 'csrftoken' : '' , 's_network' : '' , 'ds_user_id' : '' } ) session . headers . update ( self . _default_http_header ( empty_session_only = True ) ) return session
async def remove_items ( self , * items ) : '''remove items from the playlist | coro | Parameters items : array _ like list of items to remove ( or their ids ) See Also add _ items :'''
items = [ i . id for i in ( await self . process ( items ) ) if i in self . items ] if not items : return await self . connector . delete ( 'Playlists/{Id}/Items' . format ( Id = self . id ) , EntryIds = ',' . join ( items ) , remote = False )
def _load_device ( self , name , config ) : """Load a device either from a script or from an installed module"""
if config is None : config_dict = { } elif isinstance ( config , dict ) : config_dict = config elif config [ 0 ] == '#' : # Allow passing base64 encoded json directly in the port string to ease testing . import base64 config_str = str ( base64 . b64decode ( config [ 1 : ] ) , 'utf-8' ) config_dict =...
def main ( ) : """NAME measurements _ normalize . py DESCRIPTION takes magic _ measurements file and normalized moment by sample _ weight and sample _ volume in the er _ specimens table SYNTAX measurements _ normalize . py [ command line options ] OPTIONS - f FILE : specify input file , default is : m...
# initialize variables dir_path = '.' if "-WD" in sys . argv : ind = sys . argv . index ( "-WD" ) dir_path = sys . argv [ ind + 1 ] meas_file , spec_file = dir_path + "/magic_measurements.txt" , dir_path + "/er_specimens.txt" out_file = meas_file MeasRecs , SpecRecs = [ ] , [ ] OutRecs = [ ] if "-h" in sys . ar...
def str_to_time ( time_str : str ) -> datetime . datetime : """Convert human readable string to datetime . datetime ."""
pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
def __pop_driver_auth_args ( ** kwargs ) : """Try to construct the arguments that should be passed as initialization of a driver : param kwargs : options passed to the class : return : args or none"""
if 'username' in kwargs : return [ kwargs . pop ( 'username' ) , kwargs . pop ( 'password' ) ] elif 'access_token' in kwargs : return kwargs . pop ( 'access token' ) elif 'access_id' in kwargs : return kwargs . pop ( 'access_id' ) , kwargs . pop ( 'secret_key' ) elif 'service_account_email' in kwargs : ...
def cut_from_block ( html_message ) : """Cuts div tag which wraps block starting with " From : " ."""
# handle the case when From : block is enclosed in some tag block = html_message . xpath ( ( "//*[starts-with(mg:text_content(), 'From:')]|" "//*[starts-with(mg:text_content(), 'Date:')]" ) ) if block : block = block [ - 1 ] parent_div = None while block . getparent ( ) is not None : if block . tag ...
def get_members ( self , selector ) : """Returns the members that satisfy the given selector . : param selector : ( : class : ` ~ hazelcast . core . MemberSelector ` ) , Selector to be applied to the members . : return : ( List ) , List of members ."""
members = [ ] for member in self . get_member_list ( ) : if selector . select ( member ) : members . append ( member ) return members
def import_discord_user ( self , uid , user ) : """Add a discord user to the database if not already present , get if is present ."""
url = api_url + 'users/social/' payload = { 'user' : int ( user ) , 'provider' : 'discord' , 'uid' : str ( uid ) } print ( json . dumps ( payload ) ) r = requests . put ( url , data = json . dumps ( payload ) , headers = self . headers ) print ( request_status ( r ) ) r . raise_for_status ( ) return DiscordUser ( r . j...
def build_fptree ( self , transactions , root_value , root_count , frequent , headers ) : """Build the FP tree and return the root node ."""
root = FPNode ( root_value , root_count , None ) for transaction in transactions : sorted_items = [ x for x in transaction if x in frequent ] sorted_items . sort ( key = lambda x : frequent [ x ] , reverse = True ) if len ( sorted_items ) > 0 : self . insert_tree ( sorted_items , root , headers ) re...
def unassign_grade_system_from_gradebook ( self , grade_system_id , gradebook_id ) : """Removes a ` ` GradeSystem ` ` from a ` ` Gradebook ` ` . arg : grade _ system _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` GradeSystem ` ` arg : gradebook _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Gradeb...
# Implemented from template for # osid . resource . ResourceBinAssignmentSession . unassign _ resource _ from _ bin mgr = self . _get_provider_manager ( 'GRADING' , local = True ) lookup_session = mgr . get_gradebook_lookup_session ( proxy = self . _proxy ) lookup_session . get_gradebook ( gradebook_id ) # to raise Not...
def dims_knight ( self , move ) : '''Knight on the rim is dim'''
if self . board . piece_type_at ( move . from_square ) == chess . KNIGHT : rim = SquareSet ( chess . BB_RANK_1 | chess . BB_RANK_8 | chess . BB_FILE_A | chess . BB_FILE_H ) return move . to_square in rim
def data ( self , column , role ) : """Return the data for the specified column and role The column addresses one attribute of the data . : param column : the data column : type column : int : param role : the data role : type role : QtCore . Qt . ItemDataRole : returns : data depending on the role : ...
return self . columns [ column ] ( self . _note , role )
def make_cache_key ( request ) : """Generate a cache key from request object data"""
headers = frozenset ( request . _p [ 'header' ] . items ( ) ) path = frozenset ( request . _p [ 'path' ] . items ( ) ) query = frozenset ( request . _p [ 'query' ] ) return ( request . url , headers , path , query )
def slicewise ( tf_fn , xs , output_shape = None , output_dtype = None , splittable_dims = None , grad_function = None , name = None ) : """Slice - wise call to any tensorflow function . The output shape and dtype default to those of the first input . splittable _ dims is a list of Dimensions which can be split...
multiple_outputs = isinstance ( output_dtype , list ) output_shapes = output_shape if multiple_outputs else [ output_shape ] output_dtypes = output_dtype if multiple_outputs else [ output_dtype ] op = SlicewiseOperation ( tf_fn , xs , [ convert_to_shape ( shape ) or xs [ 0 ] . shape for shape in output_shapes ] , [ dty...
def rescan_images ( registry ) : '''Update the kernel image metadata from all configured docker registries .'''
with Session ( ) as session : try : result = session . Image . rescanImages ( registry ) except Exception as e : print_error ( e ) sys . exit ( 1 ) if result [ 'ok' ] : print ( "kernel image metadata updated" ) else : print ( "rescanning failed: {0}" . format ( re...
def error_perturbation ( C , S ) : r"""Error perturbation for given sensitivity matrix . Parameters C : ( M , M ) ndarray Count matrix S : ( M , M ) ndarray or ( K , M , M ) ndarray Sensitivity matrix ( for scalar observable ) or sensitivity tensor for vector observable Returns X : float or ( K , K ...
if issparse ( C ) : warnings . warn ( "Error-perturbation will be dense for sparse input" ) C = C . toarray ( ) return dense . covariance . error_perturbation ( C , S )
def bgzip_and_index ( in_file , config = None , remove_orig = True , prep_cmd = "" , tabix_args = None , out_dir = None ) : """bgzip and tabix index an input file , handling VCF and BED ."""
if config is None : config = { } out_file = in_file if in_file . endswith ( ".gz" ) else in_file + ".gz" if out_dir : remove_orig = False out_file = os . path . join ( out_dir , os . path . basename ( out_file ) ) if ( not utils . file_exists ( out_file ) or not os . path . lexists ( out_file ) or ( utils ....
def filter_communities ( cls , p , so , with_deleted = False ) : """Search for communities . Helper function which takes from database only those communities which match search criteria . Uses parameter ' so ' to set communities in the correct order . Parameter ' page ' is introduced to restrict results and...
query = cls . query if with_deleted else cls . query . filter ( cls . deleted_at . is_ ( None ) ) if p : p = p . replace ( ' ' , '%' ) query = query . filter ( db . or_ ( cls . id . ilike ( '%' + p + '%' ) , cls . title . ilike ( '%' + p + '%' ) , cls . description . ilike ( '%' + p + '%' ) , ) ) if so in curre...
def init_event_loop ( self ) : """Every cell should have its own event loop for proper containment . The type of event loop is not so important however ."""
self . loop = asyncio . new_event_loop ( ) self . loop . set_debug ( self . debug ) if hasattr ( self . loop , '_set_coroutine_wrapper' ) : self . loop . _set_coroutine_wrapper ( self . debug ) elif self . debug : warnings . warn ( "Cannot set debug on loop: %s" % self . loop ) self . loop_policy = IOCellEventL...
def main ( ) : """NAME fishqq . py DESCRIPTION makes qq plot from dec , inc input data INPUT FORMAT takes dec / inc pairs in space delimited file SYNTAX fishqq . py [ command line options ] OPTIONS - h help message - f FILE , specify file on command line - F FILE , specify output file for stat...
fmt , plot = 'svg' , 0 outfile = "" if '-h' in sys . argv : # check if help is needed print ( main . __doc__ ) sys . exit ( ) # graceful quit elif '-f' in sys . argv : # ask for filename ind = sys . argv . index ( '-f' ) file = sys . argv [ ind + 1 ] f = open ( file , 'r' ) data = f . readli...
def load ( self , data_dir ) : """Load graph and weight data . Args : data _ dir ( : obj : ` str ` ) : location of Keras checkpoint ( ` . hdf5 ` ) files and model ( in ` . json ` ) structure . The default behavior is to take the latest of each , by OS timestamp ."""
# for tensorflow compatibility K . set_learning_phase ( 0 ) # find newest ckpt and graph files try : latest_ckpt = max ( glob . iglob ( os . path . join ( data_dir , '*.h*5' ) ) , key = os . path . getctime ) latest_ckpt_name = os . path . basename ( latest_ckpt ) latest_ckpt_time = str ( datetime . fromtim...
def _do_lumping ( self ) : """Do the BACE lumping ."""
c = copy . deepcopy ( self . countsmat_ ) if self . sliding_window : c *= self . lag_time c , macro_map , statesKeep = self . _filterFunc ( c ) w = np . array ( c . sum ( axis = 1 ) ) . flatten ( ) w [ statesKeep ] += 1 unmerged = np . zeros ( w . shape [ 0 ] , dtype = np . int8 ) unmerged [ statesKeep ] = 1 # get ...
def complete ( self , query , current_url ) : """Called to interpret the server ' s response to an OpenID request . It is called in step 4 of the flow described in the consumer overview . @ param query : A dictionary of the query parameters for this HTTP request . @ param current _ url : The URL used to i...
endpoint = self . session . get ( self . _token_key ) message = Message . fromPostArgs ( query ) response = self . consumer . complete ( message , endpoint , current_url ) try : del self . session [ self . _token_key ] except KeyError : pass if ( response . status in [ 'success' , 'cancel' ] and response . iden...
def update_w ( self ) : """Update the attributes of self . widget based on self . flagged ."""
if self . flagged : self . _w . attr = 'flagged' self . _w . focus_attr = 'flagged focus' else : self . _w . attr = 'body' self . _w . focus_attr = 'focus'
def release ( self ) : """Releases the lock , that was acquired with the same object . . . note : : If you want to release a lock that you acquired in a different place you have two choices : * Use ` ` Lock ( " name " , id = id _ from _ other _ place ) . release ( ) ` ` * Use ` ` Lock ( " name " ) . reset (...
if self . _lock_renewal_thread is not None : self . _stop_lock_renewer ( ) logger . debug ( "Releasing %r." , self . _name ) error = _eval_script ( self . _client , UNLOCK , self . _name , self . _signal , args = ( self . _id , ) ) if error == 1 : raise NotAcquired ( "Lock %s is not acquired or it already expir...
def get_by_id ( self , reply_id ) : '''Get the reply by id .'''
reply = MReply . get_by_uid ( reply_id ) logger . info ( 'get_reply: {0}' . format ( reply_id ) ) self . render ( 'misc/reply/show_reply.html' , reply = reply , username = reply . user_name , date = reply . date , vote = reply . vote , uid = reply . uid , userinfo = self . userinfo , kwd = { } )
def acquire_connection ( settings , tag = None , logger_name = None , auto_commit = False ) : """Return a connection to a Relational DataBase Management System ( RDBMS ) the most appropriate for the service requesting this connection . @ param settings : a dictionary of connection properties : : None : { ' ...
try : connection_properties = settings . get ( tag , settings [ None ] ) except KeyError : raise RdbmsConnection . DefaultConnectionPropertiesSettingException ( ) return RdbmsConnection ( connection_properties [ 'rdbms_hostname' ] , connection_properties [ 'rdbms_port' ] , connection_properties [ 'rdbms_databas...
def pairwise ( iterable ) : "s - > ( s0 , s1 ) , ( s1 , s2 ) , ( s2 , s3 ) , . . ."
a , b = tee ( iterable ) next ( b , None ) return izip ( a , b )
def info ( model = None , markdown = False , silent = False ) : """Print info about spaCy installation . If a model shortcut link is speficied as an argument , print model information . Flag - - markdown prints details in Markdown for easy copy - pasting to GitHub issues ."""
msg = Printer ( ) if model : if util . is_package ( model ) : model_path = util . get_package_path ( model ) else : model_path = util . get_data_path ( ) / model meta_path = model_path / "meta.json" if not meta_path . is_file ( ) : msg . fail ( "Can't find model meta.json" , meta...
def verify_high ( self , high ) : '''Verify that the high data is viable and follows the data structure'''
errors = [ ] if not isinstance ( high , dict ) : errors . append ( 'High data is not a dictionary and is invalid' ) reqs = OrderedDict ( ) for name , body in six . iteritems ( high ) : if name . startswith ( '__' ) : continue if not isinstance ( name , six . string_types ) : errors . append ...
def set ( self , mode , disable ) : """create logger object , enable or disable logging"""
global logger try : if logger : if disable : logger . disabled = True else : if mode in ( 'STREAM' , 'FILE' ) : logger = logd . getLogger ( mode , __version__ ) except Exception as e : logger . exception ( '%s: Problem incurred during logging setup' % inspect . stack ...
def autoload ( self , state = True ) : """Begins the process for autoloading this item when it becomes visible within the tree . : param state | < bool >"""
if state and not self . _timer : self . _timer = QtCore . QTimer ( ) self . _timer . setInterval ( 500 ) self . _timer . timeout . connect ( self . testAutoload ) if state and self . _timer and not self . _timer . isActive ( ) : self . _timer . start ( ) elif not state and self . _timer and self . _time...
def _get_filesystems_and_globs ( datetime_to_task , datetime_to_re ) : """Yields a ( filesystem , glob ) tuple per every output location of task . The task can have one or several FileSystemTarget outputs . For convenience , the task can be a luigi . WrapperTask , in which case outputs of all its dependencies...
# probe some scattered datetimes unlikely to all occur in paths , other than by being sincere datetime parameter ' s representations # TODO limit to [ self . start , self . stop ) so messages are less confusing ? Done trivially it can kill correctness sample_datetimes = [ datetime ( y , m , d , h ) for y in range ( 200...
def optimize_restarts ( self , num_restarts = 10 , robust = False , verbose = True , parallel = False , num_processes = None , ** kwargs ) : """Perform random restarts of the model , and set the model to the best seen solution . If the robust flag is set , exceptions raised during optimizations will be handle...
initial_length = len ( self . optimization_runs ) initial_parameters = self . optimizer_array . copy ( ) if parallel : # pragma : no cover try : pool = mp . Pool ( processes = num_processes ) obs = [ self . copy ( ) for i in range ( num_restarts ) ] [ obs [ i ] . randomize ( ) for i in range...
def nbytes ( self ) : """The number of bytes required to encode this command . Encoded commands are comprised of a two byte opcode , followed by a one byte size , and then the command argument bytes . The size indicates the number of bytes required to represent command arguments ."""
return len ( self . opcode ) + 1 + sum ( arg . nbytes for arg in self . argdefns )
def parse_item ( self , key , value , flags : Flags ) -> Optional [ TransItem ] : """Parse an item ( and more specifically its key ) ."""
parts = key . split ( '+' ) pure_key = parts [ 0 ] try : if len ( parts ) == 2 : index = int ( parts [ 1 ] ) elif len ( parts ) > 2 : return else : index = 1 except ( ValueError , TypeError ) : return if index < 1 : return return TransItem ( key = pure_key , index = index , v...
def read_varint32 ( self ) : """Reads a varint from the stream , interprets this varint as a signed , 32 - bit integer , and returns the integer ."""
i = self . read_varint64 ( ) if not wire_format . INT32_MIN <= i <= wire_format . INT32_MAX : raise errors . DecodeError ( 'Value out of range for int32: %d' % i ) return int ( i )
def infos ( self , typ , light = None , date = None ) : '''Args : typ : type of calibration to look for . See . coeffs . keys ( ) for all types available date ( Optional [ str ] ) : date of calibration Returns : list : all infos available for given typ'''
d = self . _getDate ( typ , light ) if date is None : return [ c [ 1 ] for c in d ] # TODO : not struct time , but time in ms since epoch return _getFromDate ( d , date ) [ 1 ]
def frame_from_raw ( raw ) : """Create and return frame from raw bytes ."""
command , payload = extract_from_frame ( raw ) frame = create_frame ( command ) if frame is None : PYVLXLOG . warning ( "Command %s not implemented, raw: %s" , command , ":" . join ( "{:02x}" . format ( c ) for c in raw ) ) return None frame . validate_payload_len ( payload ) frame . from_payload ( payload ) re...
def _compile_int ( self ) : """Time Domain Simulation routine execution"""
string = '"""\n' # evaluate the algebraic equations g string += 'system.dae.init_fg(resetz=False)\n' for gcall , call in zip ( self . gcall , self . gcalls ) : if gcall : string += call string += '\n' string += 'system.dae.reset_small_g()\n' # handle islands string += self . gisland # evaluate differential ...
def write_message ( self , message : Union [ str , bytes ] , binary : bool = False ) -> "Future[None]" : """Sends a message to the WebSocket server . If the stream is closed , raises ` WebSocketClosedError ` . Returns a ` . Future ` which can be used for flow control . . . versionchanged : : 5.0 Exception r...
return self . protocol . write_message ( message , binary = binary )
def return_or_raise ( cls , response , expected_status_code ) : """Check for ` ` expected _ status _ code ` ` ."""
try : if response . status_code in expected_status_code : return response except TypeError : if response . status_code == expected_status_code : return response raise cls ( response )
def random_draft ( card_class : CardClass , exclude = [ ] ) : """Return a deck of 30 random cards for the \a card _ class"""
from . import cards from . deck import Deck deck = [ ] collection = [ ] # hero = card _ class . default _ hero for card in cards . db . keys ( ) : if card in exclude : continue cls = cards . db [ card ] if not cls . collectible : continue if cls . type == CardType . HERO : # Heroes are c...