signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def index_next_crossing ( value , array , starting_index = 0 , direction = 1 ) : """starts at starting _ index , and walks through the array until it finds a crossing point with value set direction = - 1 for down crossing"""
for n in range ( starting_index , len ( array ) - 1 ) : if ( value - array [ n ] ) * direction >= 0 and ( value - array [ n + 1 ] ) * direction < 0 : return n # no crossing found return - 1
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'scope' ) and self . scope is not None : _dict [ 'scope' ] = self . scope if hasattr ( self , 'status' ) and self . status is not None : _dict [ 'status' ] = self . status if hasattr ( self , 'status_description' ) and self . status_description is not None : _dict [ 'status_d...
def fork_exec ( args , stdin = '' , ** kwargs ) : """Do a fork - exec through the subprocess . Popen abstraction in a way that takes a stdin and return stdout ."""
as_bytes = isinstance ( stdin , bytes ) source = stdin if as_bytes else stdin . encode ( locale ) p = Popen ( args , stdin = PIPE , stdout = PIPE , stderr = PIPE , ** kwargs ) stdout , stderr = p . communicate ( source ) if as_bytes : return stdout , stderr return ( stdout . decode ( locale ) , stderr . decode ( lo...
def _truncate_bitmap ( what ) : """Determine the index of greatest byte that isn ' t all zeros , and return the bitmap that contains all the bytes less than that index . @ param what : a string of octets representing a bitmap . @ type what : string @ rtype : string"""
for i in xrange ( len ( what ) - 1 , - 1 , - 1 ) : if what [ i ] != '\x00' : break return '' . join ( what [ 0 : i + 1 ] )
def from_code ( cls , schema , # type : GraphQLSchema code , # type : Union [ str , Any ] uptodate = None , # type : Optional [ bool ] extra_namespace = None , # type : Optional [ Dict [ str , Any ] ] ) : # type : ( . . . ) - > GraphQLCompiledDocument """Creates a GraphQLDocument object from compiled code and the g...
if isinstance ( code , string_types ) : filename = "<document>" code = compile ( code , filename , "exec" ) namespace = { "__file__" : code . co_filename } exec ( code , namespace ) if extra_namespace : namespace . update ( extra_namespace ) rv = cls . _from_namespace ( schema , namespace ) # rv . _ uptodat...
def generate ( self , tool , copied = False , copy = False ) : """Generates a project"""
tools = self . _validate_tools ( tool ) if tools == - 1 : return - 1 generated_files = { } result = 0 for export_tool in tools : exporter = ToolsSupported ( ) . get_tool ( export_tool ) # None is an error if exporter is None : result = - 1 logger . debug ( "Tool: %s was not found" % expo...
def _expand_paths ( self , paths ) : """Expand $ vars in an array of paths , e . g . from a ' build ' block ."""
paths = ninja_syntax . as_list ( paths ) return ' ' . join ( map ( self . _shell_escape , ( map ( self . _expand , paths ) ) ) )
def transitions ( self ) : """Transition matrix ( sparse matrix ) . Is conjugate to the symmetrized transition matrix via : : self . transitions = self . Z * self . transitions _ sym / self . Z where ` ` self . Z ` ` is the diagonal matrix storing the normalization of the underlying kernel matrix . Notes ...
if issparse ( self . Z ) : Zinv = self . Z . power ( - 1 ) else : Zinv = np . diag ( 1. / np . diag ( self . Z ) ) return self . Z . dot ( self . transitions_sym ) . dot ( Zinv )
def fmt_type ( data_type ) : """Returns a JSDoc annotation for a data type . May contain a union of enumerated subtypes ."""
if is_struct_type ( data_type ) and data_type . has_enumerated_subtypes ( ) : possible_types = [ ] possible_subtypes = data_type . get_all_subtypes_with_tags ( ) for _ , subtype in possible_subtypes : possible_types . append ( fmt_type_name ( subtype ) ) if data_type . is_catch_all ( ) : ...
def zdecr ( self , name , key , amount = 1 ) : """Decrease the value of ` ` key ` ` in zset ` ` name ` ` by ` ` amount ` ` . If no key exists , the value will be initialized as 0 - ` ` amount ` ` : param string name : the zset name : param string key : the key name : param int amount : increments : return...
amount = get_positive_integer ( 'amount' , amount ) return self . execute_command ( 'zdecr' , name , key , amount )
def _parse_alias_rule ( alias , alias_spec ) : """Parse an alias rule . The first token is the canonical name of the version . The remaining tokens are key = " quoted value " pairs that specify parameters ; these parameters are ignored by AVersion , but may be used by the application . : param alias : The a...
result = dict ( alias = alias , params = { } ) for token in quoted_split ( alias_spec , ' ' , quotes = '"\'' ) : if not token : continue # Suck out the canonical version name if 'version' not in result : result [ 'version' ] = token continue # What remains is key = " quoted value...
def run ( self ) : """Run FastGapFill command"""
# Create solver solver = self . _get_solver ( ) # Load compound information def compound_name ( id ) : if id not in self . _model . compounds : return id return self . _model . compounds [ id ] . properties . get ( 'name' , id ) # TODO : The exchange and transport reactions have tuple names . This # mea...
def decode_dict ( data , encoding = None , errors = 'strict' , keep = False , normalize = False , preserve_dict_class = False , preserve_tuples = False , to_str = False ) : '''Decode all string values to Unicode . Optionally use to _ str = True to ensure strings are str types and not unicode on Python 2.'''
_decode_func = salt . utils . stringutils . to_unicode if not to_str else salt . utils . stringutils . to_str # Make sure we preserve OrderedDicts rv = data . __class__ ( ) if preserve_dict_class else { } for key , value in six . iteritems ( data ) : if isinstance ( key , tuple ) : key = decode_tuple ( key ...
def interpolate_holes ( self ) : """Linearly interpolate over holes in this collection to make it continuous . Returns : continuous _ collection : A HourlyContinuousCollection with the same data as this collection but with missing data filled by means of a linear interpolation ."""
# validate analysis _ period and use the resulting period to generate datetimes assert self . validated_a_period is True , 'validated_a_period property must be' ' True to use interpolate_holes(). Run validate_analysis_period().' mins_per_step = int ( 60 / self . header . analysis_period . timestep ) new_datetimes = sel...
def get_string ( self , key , default = UndefinedKey ) : """Return string representation of value found at key : param key : key to use ( dot separated ) . E . g . , a . b . c : type key : basestring : param default : default value if key not found : type default : basestring : return : string value : t...
value = self . get ( key , default ) if value is None : return None string_value = unicode ( value ) if isinstance ( value , bool ) : string_value = string_value . lower ( ) return string_value
def auth_kubernetes ( self , role , jwt , use_token = True , mount_point = 'kubernetes' ) : """POST / auth / < mount _ point > / login : param role : Name of the role against which the login is being attempted . : type role : str . : param jwt : Signed JSON Web Token ( JWT ) for authenticating a service accou...
params = { 'role' : role , 'jwt' : jwt } url = 'v1/auth/{0}/login' . format ( mount_point ) return self . login ( url , json = params , use_token = use_token )
def apply_effect ( layer , image ) : """Apply effect to the image . . . note : Correct effect order is the following . All the effects are first applied to the original image then blended together . * dropshadow * outerglow * ( original ) * patternoverlay * gradientoverlay * coloroverlay * innersh...
for effect in layer . effects : if effect . __class__ . __name__ == 'PatternOverlay' : draw_pattern_fill ( image , layer . _psd , effect . value ) for effect in layer . effects : if effect . __class__ . __name__ == 'GradientOverlay' : draw_gradient_fill ( image , effect . value ) for effect in l...
def loadtxt ( fname , dtype = "float" , delimiter = "\t" , usecols = None , comments = "#" ) : r"""Load unyt _ arrays with unit information from a text file . Each row in the text file must have the same number of values . Parameters fname : str Filename to read . dtype : data - type , optional Data - t...
f = open ( fname , "r" ) next_one = False units = [ ] num_cols = - 1 for line in f . readlines ( ) : words = line . strip ( ) . split ( ) if len ( words ) == 0 : continue if line [ 0 ] == comments : if next_one : units = words [ 1 : ] if len ( words ) == 2 and words [ 1 ]...
def send_measurements ( self , list_of_measurements ) : """Posts data about the provided list of Measurement objects to the Station API . The objects may be related to different station IDs . : param list _ of _ measurements : list of * pyowm . stationsapi30 . measurement . Measurement * objects to be posted ...
assert list_of_measurements is not None assert all ( [ m . station_id is not None for m in list_of_measurements ] ) msmts = [ self . _structure_dict ( m ) for m in list_of_measurements ] status , _ = self . http_client . post ( MEASUREMENTS_URI , params = { 'appid' : self . API_key } , data = msmts , headers = { 'Conte...
def unsign ( self , token ) : """Extract the data from a signed ` ` token ` ` ."""
if self . max_age is None : data = self . signer . unsign ( token ) else : data = self . signer . unsign ( token , max_age = self . max_age ) return signing . b64_decode ( data . encode ( ) )
def CreateBitmap ( self , artid , client , size ) : """Adds custom images to Artprovider"""
if artid in self . extra_icons : return wx . Bitmap ( self . extra_icons [ artid ] , wx . BITMAP_TYPE_ANY ) else : return wx . ArtProvider . GetBitmap ( artid , client , size )
def _author_line ( self ) : """Helper method to concatenate author and institution values , if necessary : return : string"""
if self . author and self . institution : return self . author + ";" + self . institution elif self . author : return self . author else : return self . institution
def __make_dynamic ( self , method ) : '''Create a method for each of the exit codes .'''
def dynamic ( * args ) : self . plugin_info [ 'status' ] = method if not args : args = None self . output ( args ) sys . exit ( getattr ( self . exit_code , method ) ) method_lc = method . lower ( ) dynamic . __doc__ = "%s method" % method_lc dynamic . __name__ = method_lc setattr ( self , dynam...
def parseline ( self , line : str ) -> Tuple [ str , str , str ] : """Parse the line into a command name and a string containing the arguments . NOTE : This is an override of a parent class method . It is only used by other parent class methods . Different from the parent class method , this ignores self . iden...
statement = self . statement_parser . parse_command_only ( line ) return statement . command , statement . args , statement . command_and_args
def fromProfile ( cls , profile ) : """Return an ` Origin ` from a given configuration profile . : see : ` ProfileStore ` ."""
session = bones . SessionAPI . fromProfile ( profile ) return cls ( session )
def AnalizarAjusteCredito ( self ) : "Método para analizar la respuesta de AFIP para Ajuste Credito"
liq = { } if hasattr ( self , "liquidacion" ) and self . liquidacion : liq . update ( self . liquidacion ) if hasattr ( self , "ajuste" ) and 'ajusteCredito' in self . ajuste : liq . update ( self . ajuste [ 'ajusteCredito' ] ) if self . __ajuste_credito : liq . update ( self . __ajuste_credito ) self ....
def merge_split ( * paths ) : """Merge paths into a single path delimited by colons and split on colons to return a list of paths . : param paths : a variable length list of path strings : return : a list of paths from the merged path list split by colons"""
filtered_paths = filter ( None , paths ) return [ p for p in ':' . join ( filtered_paths ) . split ( ':' ) if p ]
def get_times_from_cli ( cli_token ) : """Convert a CLI token to a datetime tuple . Argument : cli _ token ( str ) : an isoformat datetime token ( [ ISO date ] : [ ISO date ] ) or a special value among : * thisday * thisweek * thismonth * thisyear Returns : tuple : a datetime . date objects couple...
today = datetime . date . today ( ) if cli_token == "thisday" : return today , today elif cli_token == "thisweek" : return today , today - dateutil . relativedelta . relativedelta ( days = 7 ) elif cli_token == "thismonth" : return today , today - dateutil . relativedelta . relativedelta ( months = 1 ) elif...
def diff_colormap ( ) : "Custom colormap to map low values to black or another color ."
# bottom = plt . cm . copper ( np . linspace ( 0 . , 1 , 6 ) ) black = np . atleast_2d ( [ 0. , 0. , 0. , 1. ] ) bottom = np . repeat ( black , 6 , axis = 0 ) middle = plt . cm . copper ( np . linspace ( 0 , 1 , 250 ) ) # remain = plt . cm . Reds ( np . linspace ( 0 , 1 , 240 ) ) colors = np . vstack ( ( bottom , middl...
def _from_fields ( self , fields ) : '''Parse from generator . Raise StopIteration if the property could not be read .'''
return _np . dtype ( self . dtype ( ) ) . type ( next ( fields ) )
def _set_retain ( self , v , load = False ) : """Setter method for retain , mapped from YANG variable / rbridge _ id / router / router _ bgp / address _ family / l2vpn / evpn / retain ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ retain is considered as ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = retain . retain , is_container = 'container' , presence = False , yang_name = "retain" , rest_name = "retain" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext...
def cache_card ( self , card ) : """Cache the card for faster future lookups . Removes the oldest card when the card cache stores more cards then this libraries cache limit ."""
code = card . code self . card_cache [ code ] = card if code in self . card_cache_list : self . card_cache_list . remove ( code ) self . card_cache_list . append ( code ) if len ( self . card_cache_list ) > self . cachelimit : del self . card_cache [ self . card_cache_list . pop ( 0 ) ]
def marvcli_run ( ctx , datasets , deps , excluded_nodes , force , force_dependent , force_deps , keep , keep_going , list_nodes , list_dependent , selected_nodes , update_detail , update_listing , cachesize , collections ) : """Run nodes for selected datasets . Datasets are specified by a list of set ids , or - ...
if collections and datasets : ctx . fail ( '--collection and DATASETS are mutually exclusive' ) if list_dependent and not selected_nodes : ctx . fail ( '--list-dependent needs at least one selected --node' ) if not any ( [ datasets , collections , list_nodes ] ) : click . echo ( ctx . get_help ( ) ) ctx...
def pointm ( self , x , y , m = None ) : """Creates a POINTM shape . If the m ( measure ) value is not set , it defaults to NoData ."""
shapeType = POINTM pointShape = Shape ( shapeType ) pointShape . points . append ( [ x , y , m ] ) self . shape ( pointShape )
def wraps ( wrapped , assigned = functools . WRAPPER_ASSIGNMENTS , updated = functools . WRAPPER_UPDATES ) : """Cython - compatible functools . wraps implementation ."""
if not is_cython_function ( wrapped ) : return functools . wraps ( wrapped , assigned , updated ) else : return lambda wrapper : wrapper
def graph_from_edges ( edges : Iterable [ Edge ] , ** kwargs ) -> BELGraph : """Build a BEL graph from edges ."""
graph = BELGraph ( ** kwargs ) for edge in edges : edge . insert_into_graph ( graph ) return graph
def get_range_around ( range_value , current_item , padding ) : """Returns a range of numbers around the given number . This is useful for pagination , where you might want to show something like this : : < < < . . . 4 5 ( 6 ) 7 8 . . > > > In this example ` 6 ` would be the current page and we show 2 items...
total_items = 1 + padding * 2 left_bound = padding right_bound = range_value - padding if range_value <= total_items : range_items = range ( 1 , range_value + 1 ) return { 'range_items' : range_items , 'left_padding' : False , 'right_padding' : False , } if current_item <= left_bound : range_items = range (...
def about ( self ) : """Shows the about message window ."""
aboutDialog = AboutDialog ( parent = self ) aboutDialog . show ( ) aboutDialog . addDependencyInfo ( )
def load_children ( self ) : """If the Shard doesn ' t have any children , tries to find some from DescribeStream . If the Shard is open this won ' t find any children , so an empty response doesn ' t mean the Shard will * * never * * have children ."""
# Child count is fixed the first time any of the following happen : # 0 : : stream closed or throughput decreased # 1 : : shard was open for ~ 4 hours # 2 : : throughput increased if self . children : return self . children # ParentShardId - > [ Shard , . . . ] by_parent = collections . defaultdict ( list ) # Shard...
async def login ( url , * , username = None , password = None , insecure = False ) : """Connect to MAAS at ` url ` with a user name and password . : param url : The URL of MAAS , e . g . http : / / maas . example . com : 5240 / MAAS / : param username : The user name to use , e . g . fred . : param password :...
from . facade import Client # Lazy . from . viscera import Origin # Lazy . profile , origin = await Origin . login ( url , username = username , password = password , insecure = insecure ) return Client ( origin )
async def wait_for_read_result ( self ) : """This is a utility function to wait for return data call back @ return : Returns resultant data from callback"""
while not self . callback_data : await asyncio . sleep ( .001 ) rval = self . callback_data self . callback_data = [ ] return rval
def _ancestry_line ( self ) : '''Returns the ancestry of this dict , back to the first dict that we don ' t recognize or that has more than one backer .'''
b = self . _get_backers ( ) while len ( b ) == 1 : yield b [ 0 ] if not hasattr ( b [ 0 ] , '_get_backers' ) : break b = b [ 0 ] . _get_backers ( )
def wrap ( cls , private_key , algorithm ) : """Wraps a private key in a PrivateKeyInfo structure : param private _ key : A byte string or Asn1Value object of the private key : param algorithm : A unicode string of " rsa " , " dsa " or " ec " : return : A PrivateKeyInfo object"""
if not isinstance ( private_key , byte_cls ) and not isinstance ( private_key , Asn1Value ) : raise TypeError ( unwrap ( ''' private_key must be a byte string or Asn1Value, not %s ''' , type_name ( private_key ) ) ) if algorithm == 'rsa' : if not isinstance ( private_key , RSAPri...
def refactor_ifs ( stmnt , ifs ) : '''for if statements in list comprehension'''
if isinstance ( stmnt , _ast . BoolOp ) : test , right = stmnt . values if isinstance ( stmnt . op , _ast . Or ) : test = _ast . UnaryOp ( op = _ast . Not ( ) , operand = test , lineno = 0 , col_offset = 0 ) ifs . append ( test ) return refactor_ifs ( right , ifs ) return stmnt
def point_mid ( pt1 , pt2 ) : """Computes the midpoint of the input points . : param pt1 : point 1 : type pt1 : list , tuple : param pt2 : point 2 : type pt2 : list , tuple : return : midpoint : rtype : list"""
if len ( pt1 ) != len ( pt2 ) : raise ValueError ( "The input points should have the same dimension" ) dist_vector = vector_generate ( pt1 , pt2 , normalize = False ) half_dist_vector = vector_multiply ( dist_vector , 0.5 ) return point_translate ( pt1 , half_dist_vector )
def parse_config_path ( args = sys . argv ) : """Preprocess sys . argv and extract - - config argument ."""
config = CONFIG_PATH if '--config' in args : idx = args . index ( '--config' ) if len ( args ) > idx + 1 : config = args . pop ( idx + 1 ) args . pop ( idx ) return config
def put ( self , key , data ) : """Implementation of : meth : ` ~ simplekv . KeyValueStore . put ` . Will store the value in the backing store . After a successful or unsuccessful store , the cache will be invalidated by deleting the key from it ."""
try : return self . _dstore . put ( key , data ) finally : self . cache . delete ( key )
def cull_portals ( self , stat , threshold = 0.5 , comparator = ge ) : """Delete portals whose stat > = ` ` threshold ` ` ( default 0.5 ) . Optional argument ` ` comparator ` ` will replace > = as the test for whether to cull . You can use the name of a stored function ."""
comparator = self . _lookup_comparator ( comparator ) dead = [ ] for u in self . portal : for v in self . portal [ u ] : if stat in self . portal [ u ] [ v ] and comparator ( self . portal [ u ] [ v ] [ stat ] , threshold ) : dead . append ( ( u , v ) ) self . remove_edges_from ( dead ) return s...
def export_csv_file ( self , directory , filename ) : """Exports diagram inner graph to BPMN 2.0 XML file ( with Diagram Interchange data ) . : param directory : strings representing output directory , : param filename : string representing output file name ."""
bpmn_csv_export . BpmnDiagramGraphCsvExport . export_process_to_csv ( self , directory , filename )
def is_noncontinuable ( self ) : """@ see : U { http : / / msdn . microsoft . com / en - us / library / aa363082 ( VS . 85 ) . aspx } @ rtype : bool @ return : C { True } if the exception is noncontinuable , C { False } otherwise . Attempting to continue a noncontinuable exception results in an EXCEPTION ...
return bool ( self . raw . u . Exception . ExceptionRecord . ExceptionFlags & win32 . EXCEPTION_NONCONTINUABLE )
def remove_extracontigs ( in_bam , data ) : """Remove extra contigs ( non chr1-22 , X , Y ) from an input BAM . These extra contigs can often be arranged in different ways , causing incompatibility issues with GATK and other tools . This also fixes the read group header as in fixrg . This does not yet handl...
work_dir = utils . safe_makedir ( os . path . join ( dd . get_work_dir ( data ) , "bamclean" , dd . get_sample_name ( data ) ) ) out_file = os . path . join ( work_dir , "%s-noextras.bam" % utils . splitext_plus ( os . path . basename ( in_bam ) ) [ 0 ] ) if not utils . file_exists ( out_file ) : out_file = os . pa...
def median_fltr_opencv ( dem , size = 3 , iterations = 1 ) : """OpenCV median filter"""
import cv2 dem = malib . checkma ( dem ) if size > 5 : print ( "Need to implement iteration" ) n = 0 out = dem while n <= iterations : dem_cv = cv2 . medianBlur ( out . astype ( np . float32 ) . filled ( np . nan ) , size ) out = np . ma . fix_invalid ( dem_cv ) out . set_fill_value ( dem . fill_value )...
def validate_type ( prop , value , expected ) : """Default validation for all types"""
# Validate on expected type ( s ) , but ignore None : defaults handled elsewhere if value is not None and not isinstance ( value , expected ) : _validation_error ( prop , type ( value ) . __name__ , None , expected )
def get_objective_admin_session ( self , proxy , * args , ** kwargs ) : """Gets the ` ` OsidSession ` ` associated with the objective administration service . : param proxy : a proxy : type proxy : ` ` osid . proxy . Proxy ` ` : return : an ` ` ObjectiveAdminSession ` ` : rtype : ` ` osid . learning . Objec...
if not self . supports_objective_admin ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . ObjectiveAdminSession ( proxy = proxy , runtime = self . _runtime ) except AttributeError : ...
def get_distro_info ( self , loglevel = logging . DEBUG ) : """Get information about which distro we are using , placing it in the environment object . Fails if distro could not be determined . Should be called with the container is started up , and uses as core info as possible . Note : if the install type...
shutit = self . shutit install_type = '' distro = '' distro_version = '' if shutit . build [ 'distro_override' ] != '' : key = shutit . build [ 'distro_override' ] distro = shutit . build [ 'distro_override' ] install_type = package_map . INSTALL_TYPE_MAP [ key ] distro_version = '' if install_type ...
def validate_encryption_services ( cmd , namespace ) : """Builds up the encryption services object for storage account operations based on the list of services passed in ."""
if namespace . encryption_services : t_encryption_services , t_encryption_service = get_sdk ( cmd . cli_ctx , CUSTOM_MGMT_STORAGE , 'EncryptionServices' , 'EncryptionService' , mod = 'models' ) services = { service : t_encryption_service ( enabled = True ) for service in namespace . encryption_services } na...
def process_update_records ( update_records ) : """Process the requests for S3 bucket update requests"""
events = sorted ( update_records , key = lambda x : x [ 'account' ] ) # Group records by account for more efficient processing for account_id , events in groupby ( events , lambda x : x [ 'account' ] ) : events = list ( events ) # Grab the bucket names ( de - dupe events ) : buckets = { } for event in e...
def output ( s ) : """Parse , transform , and pretty print the result"""
p = Parser ( ) t = ExpressionsTransformer ( ) ast = p . parse ( s ) logging . debug ( ast . pretty ( ) ) print ( ast . pretty ( ) ) d = t . transform ( ast ) print ( json . dumps ( d , indent = 4 ) ) return d
def _prepair ( self ) : '''Try to connect to the given dbus services . If successful it will return a callable dbus proxy and those arguments .'''
try : sessionbus = dbus . SessionBus ( ) systembus = dbus . SystemBus ( ) except : return ( None , None ) for dbus_props in self . DBUS_SHUTDOWN . values ( ) : try : if dbus_props [ 'bus' ] == SESSION_BUS : bus = sessionbus else : bus = systembus interface...
def tmppath ( path = None , include_unix_username = True ) : """@ param path : target path for which it is needed to generate temporary location @ type path : str @ type include _ unix _ username : bool @ rtype : str Note that include _ unix _ username might work on windows too ."""
addon = "luigitemp-%08d" % random . randrange ( 1e9 ) temp_dir = '/tmp' # default tmp dir if none is specified in config # 1 . Figure out to which temporary directory to place configured_hdfs_tmp_dir = hdfs ( ) . tmp_dir if configured_hdfs_tmp_dir is not None : # config is superior base_dir = configured_hdfs_tmp_di...
def prevnode ( edges , component ) : """get the pervious component in the loop"""
e = edges c = component n2c = [ ( a , b ) for a , b in e if type ( a ) == tuple ] c2n = [ ( a , b ) for a , b in e if type ( b ) == tuple ] node2cs = [ ( a , b ) for a , b in e if b == c ] c2nodes = [ ] for node2c in node2cs : c2node = [ ( a , b ) for a , b in c2n if b == node2c [ 0 ] ] if len ( c2node ) == 0 :...
def set_screen ( self , screen , overwrite = False ) : """Set a screen on this Pipeline . Parameters filter : zipline . pipeline . Filter The filter to apply as a screen . overwrite : bool Whether to overwrite any existing screen . If overwrite is False and self . screen is not None , we raise an error ...
if self . _screen is not None and not overwrite : raise ValueError ( "set_screen() called with overwrite=False and screen already " "set.\n" "If you want to apply multiple filters as a screen use " "set_screen(filter1 & filter2 & ...).\n" "If you want to replace the previous screen with a new one, " "use set_screen...
def clearCanvas ( self , fillColor = 0 ) : """\~engliash Clear up canvas and fill color at same time @ param fillColor : a color value @ note The fillColor value range depends on the setting of _ buffer _ color _ mode . * If it is SS _ COLOR _ MODE _ MONO ( " 1 " ) monochrome mode , it can only select 0 :...
self . Canvas . rectangle ( ( 0 , 0 , self . _display_size [ 0 ] , self . _display_size [ 1 ] ) , outline = 0 , fill = fillColor )
def get_properties ( obj ) : """Get values of all properties in specified object and its subobjects and returns them as a map . The object can be a user defined object , map or array . Returned properties correspondently are object properties , map key - pairs or array elements with their indexes . : param ob...
properties = { } if obj != None : cycle_detect = [ ] RecursiveObjectReader . _perform_get_properties ( obj , None , properties , cycle_detect ) return properties
def contains ( self , key ) : '''Returns whether the object named by ` key ` exists . Optimized to only check whether the file object exists . Args : key : Key naming the object to check . Returns : boalean whether the object exists'''
path = self . object_path ( key ) return os . path . exists ( path ) and os . path . isfile ( path )
def identify ( self , req , resp , resource , uri_kwargs ) : """Identify user using Authenticate header with Basic auth ."""
header = req . get_header ( "Authorization" , False ) auth = header . split ( " " ) if header else None if auth is None or auth [ 0 ] . lower ( ) != 'basic' : return None if len ( auth ) != 2 : raise HTTPBadRequest ( "Invalid Authorization header" , "The Authorization header for Basic auth should be in form:\n"...
def to_bioul ( tag_sequence : List [ str ] , encoding : str = "IOB1" ) -> List [ str ] : """Given a tag sequence encoded with IOB1 labels , recode to BIOUL . In the IOB1 scheme , I is a token inside a span , O is a token outside a span and B is the beginning of span immediately following another span of the s...
if not encoding in { "IOB1" , "BIO" } : raise ConfigurationError ( f"Invalid encoding {encoding} passed to 'to_bioul'." ) # pylint : disable = len - as - condition def replace_label ( full_label , new_label ) : # example : full _ label = ' I - PER ' , new _ label = ' U ' , returns ' U - PER ' parts = list ( ful...
def get_utt_regions ( self ) : """Return the regions of all utterances , assuming all utterances are concatenated . It is assumed that the utterances are sorted in ascending order for concatenation . A region is defined by offset ( in chunks ) , length ( num - chunks ) and a list of references to the utteranc...
regions = [ ] current_offset = 0 for utt_idx in sorted ( self . utt_ids ) : offset = current_offset num_frames = [ ] refs = [ ] for cnt in self . containers : num_frames . append ( cnt . get ( utt_idx ) . shape [ 0 ] ) refs . append ( cnt . get ( utt_idx , mem_map = True ) ) if len (...
def _update_raid_input_data ( target_raid_config , raid_input ) : """Process raid input data . : param target _ raid _ config : node raid info : param raid _ input : raid information for creating via eLCM : raises ELCMValueError : raise msg if wrong input : return : raid _ input : raid input data which crea...
logical_disk_list = target_raid_config [ 'logical_disks' ] raid_input [ 'Server' ] [ 'HWConfigurationIrmc' ] . update ( { '@Processing' : 'execute' } ) array_info = raid_input [ 'Server' ] [ 'HWConfigurationIrmc' ] [ 'Adapters' ] [ 'RAIDAdapter' ] [ 0 ] array_info [ 'LogicalDrives' ] = { 'LogicalDrive' : [ ] } array_in...
def get_template ( self , template_name , ** parameters ) : """Pull templates from the AWS templates folder"""
template_path = pathlib . Path ( self . template_dir ) . joinpath ( template_name ) return get_template ( template_path , ** parameters )
def split_buffer ( stream , splitter = None , decoder = lambda a : a ) : """Given a generator which yields strings and a splitter function , joins all input , splits on the separator and yields each chunk . Unlike string . split ( ) , each chunk includes the trailing separator , except for the last one if non...
splitter = splitter or line_splitter buffered = six . text_type ( '' ) for data in stream_as_text ( stream ) : buffered += data while True : buffer_split = splitter ( buffered ) if buffer_split is None : break item , buffered = buffer_split yield item if buffered : ...
def present_active ( self ) : """Weak verbs > > > verb = WeakOldNorseVerb ( ) > > > verb . set _ canonic _ forms ( [ " kalla " , " kallaði " , " kallaðinn " ] ) > > > verb . present _ active ( ) [ ' kalla ' , ' kallar ' , ' kallar ' , ' köllum ' , ' kallið ' , ' kalla ' ] II > > > verb = WeakOldNorseVe...
forms = [ ] stem_ending_by_j = self . sng [ - 1 ] == "a" and self . sng [ - 2 ] == "j" stem_ending_by_v = self . sng [ - 1 ] == "a" and self . sng [ - 2 ] == "v" stem = self . sng [ : - 1 ] if self . sng [ - 1 ] == "a" else self . sng if stem_ending_by_j or stem_ending_by_v : stem = stem [ : - 1 ] if self . subclas...
def _log_message ( self , level , process_name , timeperiod , msg ) : """method performs logging into log file and Timetable ' s tree node"""
self . timetable . add_log_entry ( process_name , timeperiod , msg ) self . logger . log ( level , msg )
def polygon ( self ) : '''return a polygon for the fence'''
points = [ ] for fp in self . points [ 1 : ] : points . append ( ( fp . lat , fp . lng ) ) return points
def help_func ( ) : """Print help page . : return : None"""
tprint ( "art" ) tprint ( "v" + VERSION ) print ( DESCRIPTION + "\n" ) print ( "Webpage : http://art.shaghighi.ir\n" ) print ( "Help : \n" ) print ( " - list --> (list of arts)\n" ) print ( " - fonts --> (list of fonts)\n" ) print ( " - test --> (run tests)\n" ) print ( " - text 'yourtext' 'font(optiona...
def delete_boot_script ( self ) : """DELETE / : login / machines / : id / metadata / user - script Deletes any existing boot script on the machine ."""
j , r = self . datacenter . request ( 'DELETE' , self . path + '/metadata/user-script' ) r . raise_for_status ( ) self . boot_script = None
def agreement_weighted ( ci , wts ) : '''D = AGREEMENT _ WEIGHTED ( CI , WTS ) is identical to AGREEMENT , with the exception that each partitions contribution is weighted according to the corresponding scalar value stored in the vector WTS . As an example , suppose CI contained partitions obtained using some...
ci = np . array ( ci ) m , n = ci . shape wts = np . array ( wts ) / np . sum ( wts ) D = np . zeros ( ( n , n ) ) for i in range ( m ) : d = dummyvar ( ci [ i , : ] . reshape ( 1 , n ) ) D += np . dot ( d , d . T ) * wts [ i ] return D
def action_spatial ( self , action ) : """Given an Action , return the right spatial action ."""
if self . surf . surf_type & SurfType . FEATURE : return action . action_feature_layer elif self . surf . surf_type & SurfType . RGB : return action . action_render else : assert self . surf . surf_type & ( SurfType . RGB | SurfType . FEATURE )
def put_settings ( self , app = None , index = None , settings = None , es = None ) : """Modify index settings . Index must exist already ."""
if not index : index = self . index if not app : app = self . app if not es : es = self . es if not settings : return for alias , old_settings in self . es . indices . get_settings ( index = index ) . items ( ) : try : if test_settings_contain ( old_settings [ 'settings' ] [ 'index' ] , sett...
def check_payment_v3 ( state_engine , state_op_type , nameop , fee_block_id , token_address , burn_address , name_fee , block_id ) : """Verify that for a version - 3 namespace ( burn Stacks ) , the nameop paid the right amount of STACKs . Return { ' status ' : True , ' tokens _ paid ' : . . . , ' token _ units ' ...
# priced in STACKs only . Name price will be STACKs epoch_features = get_epoch_features ( block_id ) name = nameop [ 'name' ] namespace_id = get_namespace_from_name ( name ) name_without_namespace = get_name_from_fq_name ( name ) namespace = state_engine . get_namespace ( namespace_id ) assert namespace [ 'version' ] =...
def download ( name , filenames ) : '''Download a file from the virtual folder to the current working directory . The files with the same names will be overwirtten . NAME : Name of a virtual folder . FILENAMES : Paths of the files to be uploaded .'''
with Session ( ) as session : try : session . VFolder ( name ) . download ( filenames , show_progress = True ) print_done ( 'Done.' ) except Exception as e : print_error ( e ) sys . exit ( 1 )
def draw ( self , surface ) : """Draw all sprites and map onto the surface : param surface : pygame surface to draw to : type surface : pygame . surface . Surface"""
ox , oy = self . _map_layer . get_center_offset ( ) new_surfaces = list ( ) spritedict = self . spritedict gl = self . get_layer_of_sprite new_surfaces_append = new_surfaces . append for spr in self . sprites ( ) : new_rect = spr . rect . move ( ox , oy ) try : new_surfaces_append ( ( spr . image , new_...
def calcparams_desoto ( effective_irradiance , temp_cell , alpha_sc , a_ref , I_L_ref , I_o_ref , R_sh_ref , R_s , EgRef = 1.121 , dEgdT = - 0.0002677 , irrad_ref = 1000 , temp_ref = 25 ) : '''Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the De ...
# test for use of function pre - v0.6.0 API change if isinstance ( a_ref , dict ) or ( isinstance ( a_ref , pd . Series ) and ( 'a_ref' in a_ref . keys ( ) ) ) : import warnings warnings . warn ( 'module_parameters detected as fourth positional' + ' argument of calcparams_desoto. calcparams_desoto' + ' will req...
def reissueOverLongJobs ( self ) : """Check each issued job - if it is running for longer than desirable issue a kill instruction . Wait for the job to die then we pass the job to processFinishedJob ."""
maxJobDuration = self . config . maxJobDuration jobsToKill = [ ] if maxJobDuration < 10000000 : # We won ' t bother doing anything if rescue time > 16 weeks . runningJobs = self . batchSystem . getRunningBatchJobIDs ( ) for jobBatchSystemID in list ( runningJobs . keys ( ) ) : if runningJobs [ jobBatchS...
def _signature_hash ( self , tx_out_script , unsigned_txs_out_idx , hash_type ) : """Return the canonical hash for a transaction . We need to remove references to the signature , since it ' s a signature of the hash before the signature is applied . : param tx _ out _ script : the script the coins for unsigne...
# In case concatenating two scripts ends up with two codeseparators , # or an extra one at the end , this prevents all those possible incompatibilities . tx_out_script = self . delete_subscript ( tx_out_script , self . ScriptTools . compile ( "OP_CODESEPARATOR" ) ) # blank out other inputs ' signatures txs_in = [ self ...
def toposimplify ( geojson , p ) : """Convert geojson and simplify topology . geojson is a dict representing geojson . p is a simplification threshold value between 0 and 1."""
proc_out = subprocess . run ( [ 'geo2topo' ] , input = bytes ( json . dumps ( geojson ) , 'utf-8' ) , stdout = subprocess . PIPE ) proc_out = subprocess . run ( [ 'toposimplify' , '-P' , p ] , input = proc_out . stdout , stdout = subprocess . PIPE , stderr = subprocess . DEVNULL ) topojson = json . loads ( proc_out . s...
def process_request ( self , req ) : '''Checks to see if data returned from database is useable'''
# Check status code of request req . raise_for_status ( ) # if codes not in 200s ; error raise # Proper status code , but check if server returned a warning try : output = req . json ( ) except : exit ( req . text ) # server returned html error # Try to find an error msg in the server response try : err...
def prt_objdesc ( self , prt ) : """Return description of this GoSubDag object ."""
txt = "INITIALIZING GoSubDag: {N:3} sources in {M:3} GOs rcnt({R}). {A} alt GO IDs\n" alt2obj = { go : o for go , o in self . go2obj . items ( ) if go != o . id } prt . write ( txt . format ( N = len ( self . go_sources ) , M = len ( self . go2obj ) , R = self . rcntobj is not None , A = len ( alt2obj ) ) ) prt . write...
def invoke_tool ( namespace , tool_class = None ) : """Invoke a tool and exit . ` namespace ` is a namespace - type dict from which the tool is initialized . It should contain exactly one value that is a ` Multitool ` subclass , and this subclass will be instantiated and populated ( see ` Multitool . popula...
import sys from . . import cli cli . propagate_sigint ( ) cli . unicode_stdio ( ) cli . backtrace_on_usr1 ( ) if tool_class is None : for value in itervalues ( namespace ) : if is_strict_subclass ( value , Multitool ) : if tool_class is not None : raise PKError ( 'do not know whi...
def ensure_unicode ( str_ ) : """TODO : rob gp " isinstance \\ ( . * \\ \\ bstr \\ \\ b \\ ) " """
if isinstance ( str_ , __STR__ ) : return str_ else : try : return __STR__ ( str_ ) except UnicodeDecodeError : if str_ . startswith ( codecs . BOM_UTF8 ) : # Can safely remove the utf8 marker # http : / / stackoverflow . com / questions / 12561063 / python - extract - data - from - ...
def insert_taxon_in_new_fasta_file ( self , aln ) : """primer4clades infers the codon usage table from the taxon names in the sequences . These names need to be enclosed by square brackets and be present in the description of the FASTA sequence . The position is not important . I will insert the names in th...
new_seq_records = [ ] for seq_record in SeqIO . parse ( aln , 'fasta' ) : new_seq_record_id = "[{0}] {1}" . format ( self . taxon_for_codon_usage , seq_record . id ) new_seq_record = SeqRecord ( seq_record . seq , id = new_seq_record_id ) new_seq_records . append ( new_seq_record ) base_filename = os . path...
def word_texts ( self ) : """The list of words representing ` ` words ` ` layer elements ."""
if not self . is_tagged ( WORDS ) : self . tokenize_words ( ) return [ word [ TEXT ] for word in self [ WORDS ] ]
def ng_save ( self , request , * args , ** kwargs ) : """Called on $ save ( ) Use modelform to save new object or modify an existing one"""
form = self . get_form ( self . get_form_class ( ) ) if form . is_valid ( ) : obj = form . save ( ) return self . build_json_response ( obj ) raise ValidationError ( form . errors )
def get_server_public ( self , password_verifier , server_private ) : """B = ( k * v + g ^ b ) % N : param int password _ verifier : : param int server _ private : : rtype : int"""
return ( ( self . _mult * password_verifier ) + pow ( self . _gen , server_private , self . _prime ) ) % self . _prime
def forget ( self , * keys ) : """Remove an item from the collection by key . : param keys : The keys to remove : type keys : tuple : rtype : Collection"""
keys = reversed ( sorted ( keys ) ) for key in keys : del self [ key ] return self
def connect_channels ( self , channels ) : """Connect the provided channels"""
self . log . info ( f"Connecting to channels..." ) for chan in channels : chan . connect ( self . sock ) self . log . info ( f"\t{chan.channel}" )
def c_ideal_gas ( T , k , MW ) : r'''Calculates speed of sound ` c ` in an ideal gas at temperature T . . . math : : c = \ sqrt { kR _ { specific } T } Parameters T : float Temperature of fluid , [ K ] k : float Isentropic exponent of fluid , [ - ] MW : float Molecular weight of fluid , [ g / mol ...
Rspecific = R * 1000. / MW return ( k * Rspecific * T ) ** 0.5
def extended_fade_in ( self , segment , duration ) : """Add a fade - in to a segment that extends the beginning of the segment . : param segment : Segment to fade in : type segment : : py : class : ` radiotool . composer . Segment ` : param duration : Duration of fade - in ( in seconds ) : returns : The f...
dur = int ( duration * segment . track . samplerate ) if segment . start - dur >= 0 : segment . start -= dur else : raise Exception ( "Cannot create fade-in that extends " "past the track's beginning" ) if segment . comp_location - dur >= 0 : segment . comp_location -= dur else : raise Exception ( "Cann...
def load ( obj , env = None , silent = None , key = None ) : """Reads and loads in to " settings " a single key or all keys from vault : param obj : the settings instance : param env : settings env default = ' DYNACONF ' : param silent : if errors should raise : param key : if defined load a single key , el...
client = get_client ( obj ) env_list = _get_env_list ( obj , env ) for env in env_list : path = "/" . join ( [ obj . VAULT_PATH_FOR_DYNACONF , env ] ) . replace ( "//" , "/" ) data = client . read ( path ) if data : # There seems to be a data dict within a data dict , # extract the inner data da...
def _l2deriv ( self , l , n ) : """NAME : _ l2deriv PURPOSE : evaluate the second derivative w . r . t . lambda for this potential INPUT : l - prolate spheroidal coordinate lambda n - prolate spheroidal coordinate nu OUTPUT : second derivative w . r . t . lambda HISTORY : 2015-02-15 - Written - ...
numer = - 3. * nu . sqrt ( l ) - nu . sqrt ( n ) denom = 4. * l ** 1.5 * ( nu . sqrt ( l ) + nu . sqrt ( n ) ) ** 3 return numer / denom