signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def reservations ( self ) : """get nodes of every reservations"""
command = [ SINFO , '--reservation' ] output = subprocess . check_output ( command , env = SINFO_ENV ) output = output . decode ( ) it = iter ( output . splitlines ( ) ) next ( it ) for line in it : rsv = Reservation . from_sinfo ( line ) yield rsv . name , rsv
def buffer_put_lines ( buf , lines ) : """Appends lines to a buffer . Parameters buf The buffer to write to lines The lines to append ."""
if any ( isinstance ( x , str ) for x in lines ) : lines = [ str ( x ) for x in lines ] buf . write ( '\n' . join ( lines ) )
def set_locale ( lang ) : """Set the ' locale ' used by a program . This affects the entire application , changing the way dates , currencies and numbers are represented . It should not be called from a library routine that may be used in another program . The ` ` lang ` ` parameter can be any string that i...
# get the default locale lc , encoding = locale . getdefaultlocale ( ) try : if '.' in lang : locale . setlocale ( locale . LC_ALL , lang ) else : locale . setlocale ( locale . LC_ALL , ( lang , encoding ) ) except locale . Error : return False return True
def parse_tibiadata_datetime ( date_dict ) -> Optional [ datetime . datetime ] : """Parses time objects from the TibiaData API . Time objects are made of a dictionary with three keys : date : contains a string representation of the time timezone : a string representation of the timezone the date time is based...
try : t = datetime . datetime . strptime ( date_dict [ "date" ] , "%Y-%m-%d %H:%M:%S.%f" ) except ( KeyError , ValueError , TypeError ) : return None if date_dict [ "timezone" ] == "CET" : timezone_offset = 1 elif date_dict [ "timezone" ] == "CEST" : timezone_offset = 2 else : return None # We subtr...
def join ( self , t2 , unique = False ) : """Join this triangulation with another . If the points are known to have no duplicates , then set unique = False to skip the testing and duplicate removal"""
x_v1 = np . concatenate ( ( self . x , t2 . x ) , axis = 0 ) y_v1 = np . concatenate ( ( self . y , t2 . y ) , axis = 0 ) # # remove any duplicates if not unique : a = np . ascontiguousarray ( np . vstack ( ( x_v1 , y_v1 ) ) . T ) unique_a = np . unique ( a . view ( [ ( '' , a . dtype ) ] * a . shape [ 1 ] ) ) ...
def apply_manual_indices ( self , manual_indices ) : """Write to ` self . manual ` Write ` manual _ indices ` to the boolean array ` self . manual ` and also store the indices as ` self . _ man _ root _ ids ` . Notes If ` self . parent _ changed ` is ` True ` , i . e . the parent applied a filter and the ...
if self . parent_changed : msg = "Cannot apply filter, because parent changed: " + "dataset {}. " . format ( self . rtdc_ds ) + "Run `RTDC_Hierarchy.apply_filter()` first!" raise HierarchyFilterError ( msg ) else : self . _man_root_ids = list ( manual_indices ) cidx = map_indices_root2child ( child = se...
def __starttls ( self , keyfile = None , certfile = None ) : """STARTTLS command See MANAGESIEVE specifications , section 2.2. : param keyfile : an eventual private key to use : param certfile : an eventual certificate to use : rtype : boolean"""
if not self . has_tls_support ( ) : raise Error ( "STARTTLS not supported by the server" ) code , data = self . __send_command ( "STARTTLS" ) if code != "OK" : return False try : nsock = ssl . wrap_socket ( self . sock , keyfile , certfile ) except ssl . SSLError as e : raise Error ( "SSL error: %s" % s...
def encode_canonical ( object , output_function = None ) : """< Purpose > Encode ' object ' in canonical JSON form , as specified at http : / / wiki . laptop . org / go / Canonical _ JSON . It ' s a restricted dialect of JSON in which keys are always lexically sorted , there is no whitespace , floats aren '...
result = None # If ' output _ function ' is unset , treat it as # appending to a list . if output_function is None : result = [ ] output_function = result . append try : _encode_canonical ( object , output_function ) except ( TypeError , securesystemslib . exceptions . FormatError ) as e : message = 'Co...
def form_valid ( self , form ) : '''Pass form data to the confirmation view'''
form . cleaned_data . pop ( 'template' , None ) self . request . session [ EMAIL_VALIDATION_STR ] = { 'form_data' : form . cleaned_data } return HttpResponseRedirect ( reverse ( 'emailConfirmation' ) )
def read_secret_version ( self , path , version = None , mount_point = DEFAULT_MOUNT_POINT ) : """Retrieve the secret at the specified location . Supported methods : GET : / { mount _ point } / data / { path } . Produces : 200 application / json : param path : Specifies the path of the secret to read . This i...
params = { } if version is not None : params [ 'version' ] = version api_path = '/v1/{mount_point}/data/{path}' . format ( mount_point = mount_point , path = path ) response = self . _adapter . get ( url = api_path , params = params , ) return response . json ( )
def unpublish ( self , request , article_id , language ) : """Publish or unpublish a language of a article"""
article = get_object_or_404 ( self . model , pk = article_id ) if not article . has_publish_permission ( request ) : return HttpResponseForbidden ( force_text ( _ ( 'You do not have permission to unpublish this article' ) ) ) if not article . publisher_public_id : return HttpResponseForbidden ( force_text ( _ (...
def normalize_attr_array ( a : Any ) -> np . ndarray : """Take all kinds of array - like inputs and normalize to a one - dimensional np . ndarray"""
if type ( a ) is np . ndarray : return a elif type ( a ) is np . matrix : if a . shape [ 0 ] == 1 : return np . array ( a ) [ 0 , : ] elif a . shape [ 1 ] == 1 : return np . array ( a ) [ : , 0 ] else : raise ValueError ( "Attribute values must be 1-dimensional." ) elif type ( a ...
def default ( self , obj ) : """if input object is a ndarray it will be converted into a dict holding dtype , shape and the data base64 encoded"""
if isinstance ( obj , np . ndarray ) : data_b64 = base64 . b64encode ( obj . data ) . decode ( 'utf-8' ) return dict ( __ndarray__ = data_b64 , dtype = str ( obj . dtype ) , shape = obj . shape ) elif sps . issparse ( obj ) : data_b64 = base64 . b64encode ( obj . data ) . decode ( 'utf-8' ) return dict ...
def generate_dataset ( self , cdl_path ) : '''Use ncgen to generate a netCDF file from a . cdl file Returns the path to the generated netcdf file : param str cdl _ path : Absolute path to cdl file that is used to generate netCDF file'''
if '.cdl' in cdl_path : # it ' s possible the filename doesn ' t have the . cdl extension ds_str = cdl_path . replace ( '.cdl' , '.nc' ) else : ds_str = cdl_path + '.nc' subprocess . call ( [ 'ncgen' , '-o' , ds_str , cdl_path ] ) return ds_str
def toNDArray ( self , image ) : """Converts an image to an array with metadata . : param ` Row ` image : A row that contains the image to be converted . It should have the attributes specified in ` ImageSchema . imageSchema ` . : return : a ` numpy . ndarray ` that is an image . . . versionadded : : 2.3.0"...
if not isinstance ( image , Row ) : raise TypeError ( "image argument should be pyspark.sql.types.Row; however, " "it got [%s]." % type ( image ) ) if any ( not hasattr ( image , f ) for f in self . imageFields ) : raise ValueError ( "image argument should have attributes specified in " "ImageSchema.imageSchema...
def remove_manager ( self , manager ) : """Remove a single manager to the scope . : param manager : single username to be added to the scope list of managers : type manager : basestring : raises APIError : when unable to update the scope manager"""
select_action = 'remove_manager' self . _update_scope_project_team ( select_action = select_action , user = manager , user_type = 'manager' )
def get_b_wiggle ( x , y , y_int ) : """returns instantaneous slope from the ratio of NRM lost to TRM gained at the ith step"""
if x == 0 : b_wiggle = 0 else : b_wiggle = old_div ( ( y_int - y ) , x ) return b_wiggle
def load ( cls , path ) : """load the keys from a path : param path : the filename ( path ) in which we find the keys : return :"""
auth = cls ( ) with open ( path ) as fd : for pubkey in itertools . imap ( str . strip , fd ) : # skip empty lines if not pubkey : continue auth . add ( pubkey ) return auth
def sasdata2dataframe ( self , table : str , libref : str = '' , dsopts : dict = None , rowsep : str = '\x01' , colsep : str = '\x02' , ** kwargs ) -> '<Pandas Data Frame object>' : """This method exports the SAS Data Set to a Pandas Data Frame , returning the Data Frame object . table - the name of the SAS Data ...
dsopts = dsopts if dsopts is not None else { } method = kwargs . pop ( 'method' , None ) if method and method . lower ( ) == 'csv' : return self . sasdata2dataframeCSV ( table , libref , dsopts , ** kwargs ) port = kwargs . get ( 'port' , 0 ) if port == 0 and self . sascfg . tunnel : # we are using a tunnel ; defau...
def MakePmfFromCdf ( cdf , name = None ) : """Makes a normalized Pmf from a Cdf object . Args : cdf : Cdf object name : string name for the new Pmf Returns : Pmf object"""
if name is None : name = cdf . name pmf = Pmf ( name = name ) prev = 0.0 for val , prob in cdf . Items ( ) : pmf . Incr ( val , prob - prev ) prev = prob return pmf
def _load_data ( self , equities , futures , exchanges , root_symbols , equity_supplementary_mappings ) : """Returns a standard set of pandas . DataFrames : equities , futures , exchanges , root _ symbols"""
# Set named identifier columns as indices , if provided . _normalize_index_columns_in_place ( equities = equities , equity_supplementary_mappings = equity_supplementary_mappings , futures = futures , exchanges = exchanges , root_symbols = root_symbols , ) futures_output = self . _normalize_futures ( futures ) equity_su...
def constant ( name , shape , value = 0 , dtype = tf . sg_floatx , summary = True , regularizer = None , trainable = True ) : r"""Creates a tensor variable of which initial values are ` value ` and shape is ` shape ` . Args : name : The name of new variable . shape : A tuple / list of integers or an integer ....
shape = shape if isinstance ( shape , ( tuple , list ) ) else [ shape ] x = tf . get_variable ( name , shape , dtype = dtype , initializer = tf . constant_initializer ( value ) , regularizer = regularizer , trainable = trainable ) # add summary if summary : tf . sg_summary_param ( x ) return x
def update ( self , stats ) : """Update stats to a server . The method builds two lists : names and values and calls the export method to export the stats . Note : this class can be overwrite ( for example in CSV and Graph ) ."""
if not self . export_enable : return False # Get all the stats & limits all_stats = stats . getAllExportsAsDict ( plugin_list = self . plugins_to_export ( ) ) all_limits = stats . getAllLimitsAsDict ( plugin_list = self . plugins_to_export ( ) ) # Loop over plugins to export for plugin in self . plugins_to_export (...
def merge_config ( configs ) : """recursively deep - merge the configs into one another ( highest priority comes first )"""
new_config = { } for name , config in configs . items ( ) : new_config = dictmerge ( new_config , config , name ) return new_config
def asRGBA ( self ) : """Return image as RGBA pixels . Greyscales are expanded into RGB triplets ; an alpha channel is synthesized if necessary . The return values are as for the : meth : ` read ` method except that the * metadata * reflect the returned pixels , not the source image . In particular , for ...
width , height , pixels , meta = self . asDirect ( ) if meta [ 'alpha' ] and not meta [ 'greyscale' ] : return width , height , pixels , meta maxval = 2 ** meta [ 'bitdepth' ] - 1 if meta [ 'bitdepth' ] > 8 : def newarray ( ) : return array ( 'H' , [ maxval ] * 4 * width ) else : def newarray ( ) : ...
def apply_settings ( settings ) : """Allows new settings to be added without users having to lose all their configuration"""
for key , value in settings . items ( ) : ConfigManager . SETTINGS [ key ] = value
def parse ( self ) : """Parses data in table : return : List of list of values in table"""
data = [ ] # add name of section for row in self . soup . find_all ( "tr" ) : # cycle through all rows parsed = self . _parse_row ( row ) if parsed : data . append ( parsed ) return data
def register ( self , model_or_iterable , moderation_class ) : """Register a model or a list of models for comment moderation , using a particular moderation class . Raise ` ` AlreadyModerated ` ` if any of the models are already registered ."""
if isinstance ( model_or_iterable , ModelBase ) : model_or_iterable = [ model_or_iterable ] for model in model_or_iterable : if model in self . _registry : raise AlreadyModerated ( "The model '%s' is already being moderated" % model . _meta . verbose_name ) self . _registry [ model ] = moderation_cl...
def on_mouse_wheel ( self , event ) : """Mouse wheel handler Parameters event : instance of Event The event ."""
self . zoom ( np . exp ( event . delta * ( 0.01 , - 0.01 ) ) , event . pos )
def combine_symbols ( * args ) : '''Combine different symbols into a ' super ' - symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage : 1 ) combine two symbols , each a number into just one symbol x = numpy . random . randint ( 0,4,1000) y = numpy . ran...
for arg in args : if len ( arg ) != len ( args [ 0 ] ) : raise ValueError ( "combine_symbols got inputs with different sizes" ) return tuple ( zip ( * args ) )
def maybe_download ( url , work_directory ) : """Download the data from Marlin ' s website , unless it ' s already here ."""
filename = url . split ( "/" ) [ - 1 ] filepath = os . path . join ( work_directory , filename ) if not os . path . exists ( filepath ) : logger . info ( "Downloading to {}..." . format ( filepath ) ) download ( url , work_directory ) return filepath
def getPutData ( request ) : """Adds raw post to the PUT and DELETE querydicts on the request so they behave like post : param request : Request object to add PUT / DELETE to : type request : Request"""
dataDict = { } data = request . body for n in urlparse . parse_qsl ( data ) : dataDict [ n [ 0 ] ] = n [ 1 ] setattr ( request , 'PUT' , dataDict ) setattr ( request , 'DELETE' , dataDict )
def modify_kpi ( self , kpi_id , product_id , measures = [ ] , append = False , ** kwargs ) : '''modify _ kpi ( self , kpi _ id , product _ id , measures = [ ] , append = False , * * kwargs ) Creates a new kpi or modifies existing one . : Parameters : * * kpi _ id * ( ` string ` ) - - The KPI identifier ( uni...
if not isinstance ( measures , list ) : measures = [ measures ] request_data = { 'kpi_id' : kpi_id , 'product_id' : product_id , 'measures' : measures , 'append' : append } request_data . update ( kwargs ) return self . _call_rest_api ( 'post' , '/kpi' , data = request_data , error = 'Failed to modify a kpi entry' ...
def quickstart ( ) : """Generate a brand - new ballet project"""
import ballet . templating import ballet . util . log ballet . util . log . enable ( level = 'INFO' , format = ballet . util . log . SIMPLE_LOG_FORMAT , echo = False ) ballet . templating . render_project_template ( )
def list_song_standby ( self , song , onlyone = True ) : """try to list all valid standby Search a song in all providers . The typical usage scenario is when a song is not available in one provider , we can try to acquire it from other providers . Standby choosing strategy : search from all providers , sele...
def get_score ( standby ) : score = 1 # 分数占比关系 : # title + album > artist # artist > title > album if song . artists_name != standby . artists_name : score -= 0.4 if song . title != standby . title : score -= 0.3 if song . album_name != standby . album_name : score -=...
def _set_period ( self , period ) : """Set the period for the timestamp . If period is 0 or None , no period will be used ."""
self . _period = period if period : self . _period_seconds = tempora . get_period_seconds ( self . _period ) self . _date_format = tempora . get_date_format_string ( self . _period_seconds ) else : self . _period_seconds = 0 self . _date_format = ''
def validate_key ( self , key ) : """Called if the key _ name class attribute is not None ."""
if not key : name = self . __class__ . __name__ msg = "%s response missing %s" % ( name , self . key_name ) raise ValidationException ( msg , self ) elif not isinstance ( key , str ) : msg = "Response contains invalid %s type" % self . key_name raise ValidationException ( msg , type ( key ) )
def process ( self , tup ) : """Process steps : 1 . Index third positional value from input to elasticsearch ."""
self . es . bulk ( self . generate_bulk_body ( tup . values [ 2 ] ) , index = self . index , doc_type = self . doc_type )
def find_gt ( array , x ) : """Find leftmost value greater than x . : type array : list : param array : an iterable object that support inex : param x : a comparable value Example : : > > > find _ gt ( [ 0 , 1 , 2 , 3 ] , 0.5) * * 中文文档 * * 寻找最小的大于x的数 。"""
i = bisect . bisect_right ( array , x ) if i != len ( array ) : return array [ i ] raise ValueError
def _publish_queue_grpc ( self ) : """send the messages in the tx queue to the GRPC manager : return : None"""
messages = EventHub_pb2 . Messages ( msg = self . _tx_queue ) publish_request = EventHub_pb2 . PublishRequest ( messages = messages ) self . grpc_manager . send_message ( publish_request )
def render_news_placeholder ( context , obj , name = False , truncate = False ) : # pragma : nocover # NOQA """DEPRECATED : Template tag to render a placeholder from an NewsEntry object We don ' t need this any more because we don ' t have a placeholders M2M field on the model any more . Just use the default ` ...
warnings . warn ( "render_news_placeholder is deprecated. Use render_placeholder" " instead" , DeprecationWarning , stacklevel = 2 ) result = '' if context . get ( 'request' ) : if isinstance ( name , int ) : # If the user doesn ' t want to use a placeholder name , but a cut , we # need to check if the user has...
def connect_to ( name ) : """Creates a node instance based on an entry from the config This function will retrieve the settings for the specified connection from the config and return a Node instance . The configuration must be loaded prior to calling this function . Args : name ( str ) : The name of the ...
kwargs = config_for ( name ) if not kwargs : raise AttributeError ( 'connection profile not found in config' ) node = connect ( return_node = True , ** kwargs ) return node
def root_cmd ( command , tty , sudo , allow_failure = False , ** kwargs ) : '''Wrapper for commands to be run as root'''
logging_command = command sudo_password = kwargs . get ( 'sudo_password' , None ) if sudo : if sudo_password is None : command = 'sudo {0}' . format ( command ) logging_command = command else : logging_command = 'sudo -S "XXX-REDACTED-XXX" {0}' . format ( command ) command = 'sud...
def check_for_git_repo ( url ) : """Check if a url points to a git repository ."""
u = parse . urlparse ( url ) is_git = False if os . path . splitext ( u . path ) [ 1 ] == '.git' : is_git = True elif u . scheme in ( '' , 'file' ) : from git import InvalidGitRepositoryError , Repo try : Repo ( u . path , search_parent_directories = True ) is_git = True except InvalidGi...
def decompose_atom_list ( atom_list ) : """Return elements and / or atom ids and coordinates from an ` atom list ` . Depending on input type of an atom list ( version 1 or 2) 1 . [ [ element , coordinates ( x , y , z ) ] , . . . ] 2 . [ [ element , atom key , coordinates ( x , y , z ) ] , . . . ] the functi...
transpose = list ( zip ( * atom_list ) ) if len ( transpose ) == 4 : elements = np . array ( transpose [ 0 ] ) array_a = np . array ( transpose [ 1 ] ) . reshape ( - 1 , 1 ) array_b = np . array ( transpose [ 2 ] ) . reshape ( - 1 , 1 ) array_c = np . array ( transpose [ 3 ] ) . reshape ( - 1 , 1 ) ...
def convert_datetime_to_local ( dt : PotentialDatetimeType ) -> DateTime : """Convert date / time with timezone to local timezone ."""
dt = coerce_to_pendulum ( dt ) tz = get_tz_local ( ) return dt . in_tz ( tz )
def get_id2gos ( self , ** kws ) : # # # # def get _ annotations _ dct ( self , taxid , options ) : """Return geneid2gos , or optionally go2geneids ."""
if len ( self . taxid2asscs ) == 1 : taxid = next ( iter ( self . taxid2asscs . keys ( ) ) ) return self . _get_id2gos ( self . taxid2asscs [ taxid ] , ** kws ) assert 'taxid' in kws , "**FATAL: 'taxid' NOT FOUND IN Gene2GoReader::get_id2gos({KW})" . format ( KW = kws ) taxid = kws [ 'taxid' ] assert taxid in s...
def bfd_packet ( src_mac , dst_mac , src_ip , dst_ip , ipv4_id , src_port , dst_port , diag = 0 , state = 0 , flags = 0 , detect_mult = 0 , my_discr = 0 , your_discr = 0 , desired_min_tx_interval = 0 , required_min_rx_interval = 0 , required_min_echo_rx_interval = 0 , auth_cls = None ) : """Generate BFD packet with...
# Generate ethernet header first . pkt = packet . Packet ( ) eth_pkt = ethernet . ethernet ( dst_mac , src_mac , ETH_TYPE_IP ) pkt . add_protocol ( eth_pkt ) # IPv4 encapsulation # set ToS to 192 ( Network control / CS6) # set TTL to 255 ( RFC5881 Section 5 . ) ipv4_pkt = ipv4 . ipv4 ( proto = inet . IPPROTO_UDP , src ...
def do_class ( self , element , decl , pseudo ) : """Implement class declaration - pre - match ."""
step = self . state [ self . state [ 'current_step' ] ] actions = step [ 'actions' ] strval = self . eval_string_value ( element , decl . value ) actions . append ( ( 'attrib' , ( 'class' , strval ) ) )
def proper_repr ( value : Any ) -> str : """Overrides sympy and numpy returning repr strings that don ' t parse ."""
if isinstance ( value , sympy . Basic ) : result = sympy . srepr ( value ) # HACK : work around https : / / github . com / sympy / sympy / issues / 16074 # ( only handles a few cases ) fixed_tokens = [ 'Symbol' , 'pi' , 'Mul' , 'Add' , 'Mod' , 'Integer' , 'Float' , 'Rational' ] for token in fixed_to...
def defverb ( self , s1 , p1 , s2 , p2 , s3 , p3 ) : """Set the verb plurals for s1 , s2 and s3 to p1 , p2 and p3 respectively . Where 1 , 2 and 3 represent the 1st , 2nd and 3rd person forms of the verb ."""
self . checkpat ( s1 ) self . checkpat ( s2 ) self . checkpat ( s3 ) self . checkpatplural ( p1 ) self . checkpatplural ( p2 ) self . checkpatplural ( p3 ) self . pl_v_user_defined . extend ( ( s1 , p1 , s2 , p2 , s3 , p3 ) ) return 1
def ignores_kwargs ( * kwarg_names ) : '''Decorator to filter out unexpected keyword arguments from the call kwarg _ names : List of argument names to ignore'''
def _ignores_kwargs ( fn ) : def __ignores_kwargs ( * args , ** kwargs ) : kwargs_filtered = kwargs . copy ( ) for name in kwarg_names : if name in kwargs_filtered : del kwargs_filtered [ name ] return fn ( * args , ** kwargs_filtered ) return __ignores_kwargs...
def set_write_bit ( fn ) : # type : ( str ) - > None """Set read - write permissions for the current user on the target path . Fail silently if the path doesn ' t exist . : param str fn : The target filename or path : return : None"""
fn = fs_encode ( fn ) if not os . path . exists ( fn ) : return file_stat = os . stat ( fn ) . st_mode os . chmod ( fn , file_stat | stat . S_IRWXU | stat . S_IRWXG | stat . S_IRWXO ) if os . name == "nt" : from . _winconsole import get_current_user user_sid = get_current_user ( ) icacls_exe = _find_ica...
def dateJDN ( year , month , day , calendar ) : """Converts date to Julian Day Number ."""
a = ( 14 - month ) // 12 y = year + 4800 - a m = month + 12 * a - 3 if calendar == GREGORIAN : return day + ( 153 * m + 2 ) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045 else : return day + ( 153 * m + 2 ) // 5 + 365 * y + y // 4 - 32083
def get_supported_languages ( self , parent = None , display_language_code = None , model = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Returns a list of supported languages for translation . Example : > > ...
# Wrap the transport method to add retry and timeout logic . if "get_supported_languages" not in self . _inner_api_calls : self . _inner_api_calls [ "get_supported_languages" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . get_supported_languages , default_retry = self . _method_configs...
def setup_random_indices_local_geometry ( self , coordination ) : """Sets up random indices for the local geometry , for testing purposes : param coordination : coordination of the local geometry"""
self . icentral_site = 0 self . indices = list ( range ( 1 , coordination + 1 ) ) np . random . shuffle ( self . indices )
def elementTypeName ( self ) : """String representation of the element type ."""
if self . _array is None : return super ( ArrayRti , self ) . elementTypeName else : dtype = self . _array . dtype return '<structured>' if dtype . names else str ( dtype )
def uv ( self , values ) : """Set the UV coordinates . Parameters values : ( n , 2 ) float Pixel locations on a texture per - vertex"""
if values is None : self . _data . clear ( ) else : self . _data [ 'uv' ] = np . asanyarray ( values , dtype = np . float64 )
def listdir_stat ( dirname , show_hidden = True ) : """Returns a list of tuples for each file contained in the named directory , or None if the directory does not exist . Each tuple contains the filename , followed by the tuple returned by calling os . stat on the filename ."""
import os try : files = os . listdir ( dirname ) except OSError : return None if dirname == '/' : return list ( ( file , stat ( '/' + file ) ) for file in files if is_visible ( file ) or show_hidden ) return list ( ( file , stat ( dirname + '/' + file ) ) for file in files if is_visible ( file ) or show_hid...
def security ( self ) : """Creates a reference to the Security operations for Portal"""
url = self . _url + "/security" return _Security ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
def init_with_context ( self , context ) : """Initializes the icon list ."""
super ( CmsAppIconList , self ) . init_with_context ( context ) apps = self . children cms_apps = [ a for a in apps if is_cms_app ( a [ 'name' ] ) ] non_cms_apps = [ a for a in apps if a not in cms_apps ] if cms_apps : # Group the models of all CMS apps in one group . cms_models = [ ] for app in cms_apps : ...
def _calculate ( self , startingPercentage , endPercentage , startDate , endDate ) : """This is the error calculation function that gets called by : py : meth : ` BaseErrorMeasure . get _ error ` . Both parameters will be correct at this time . : param float startingPercentage : Defines the start of the interva...
# get the defined subset of error values errorValues = self . _get_error_values ( startingPercentage , endPercentage , startDate , endDate ) errorValues = filter ( lambda item : item is not None , errorValues ) return float ( sum ( errorValues ) ) / float ( len ( errorValues ) )
def orderAction ( self , order : QA_Order ) : """委托回报"""
return self . pms [ order . code ] [ order . order_id ] . receive_order ( order )
def getWithPrompt ( self ) : """Interactively prompt for parameter value"""
if self . prompt : pstring = self . prompt . split ( "\n" ) [ 0 ] . strip ( ) else : pstring = self . name if self . choice : schoice = list ( map ( self . toString , self . choice ) ) pstring = pstring + " (" + "|" . join ( schoice ) + ")" elif self . min not in [ None , INDEF ] or self . max not in [ ...
def xread ( self , streams , timeout = 0 , count = None , latest_ids = None ) : """Perform a blocking read on the given stream : raises ValueError : if the length of streams and latest _ ids do not match"""
args = self . _xread ( streams , timeout , count , latest_ids ) fut = self . execute ( b'XREAD' , * args ) return wait_convert ( fut , parse_messages_by_stream )
def _finalize_response ( self , response ) : """Convert the ` ` Response ` ` object into django ' s ` ` HttpResponse ` ` : return : django ' s ` ` HttpResponse ` `"""
res = HttpResponse ( content = response . content , content_type = self . _get_content_type ( ) ) # status _ code is set separately to allow zero res . status_code = response . code return res
def get_write_subset ( self , spec_type ) : """Get a set of fields used to write the header ; either ' record ' or ' signal ' specification fields . Helper function for ` get _ write _ fields ` . Gets the default required fields , the user defined fields , and their dependencies . Parameters spec _ type :...
if spec_type == 'record' : write_fields = [ ] record_specs = RECORD_SPECS . copy ( ) # Remove the n _ seg requirement for single segment items if not hasattr ( self , 'n_seg' ) : record_specs . drop ( 'n_seg' , inplace = True ) for field in record_specs . index [ - 1 : : - 1 ] : # Continue i...
def cancel_email_change ( self ) : """Cancel email change for new users and roll back data"""
if not self . email_new : return self . email_new = None self . email_confirmed = True self . email_link = None self . email_new = None self . email_link_expires = None
def scroll_forward ( event , half = False ) : """Scroll window down ."""
w = _current_window_for_event ( event ) b = event . cli . current_buffer if w and w . render_info : info = w . render_info ui_content = info . ui_content # Height to scroll . scroll_height = info . window_height if half : scroll_height //= 2 # Calculate how many lines is equivalent to th...
def container_running ( self , container_name ) : """Finds out if a container with name ` ` container _ name ` ` is running . : return : : class : ` Container < docker . models . containers . Container > ` if it ' s running , ` ` None ` ` otherwise . : rtype : Optional [ docker . models . container . Container ...
filters = { "name" : container_name , "status" : "running" , } for container in self . client . containers . list ( filters = filters ) : if container_name == container . name : return container return None
def relocate_audio_to_wav_files ( self , target_path ) : """Copies every track to its own wav file in the given folder . Every track will be stored at ` ` target _ path / track _ id . wav ` ` ."""
if not os . path . isdir ( target_path ) : os . makedirs ( target_path ) new_tracks = { } # First create a new container track for all existing tracks for track in self . tracks . values ( ) : track_path = os . path . join ( target_path , '{}.wav' . format ( track . idx ) ) sr = track . sampling_rate sa...
def verify_cot_cmdln ( args = None , event_loop = None ) : """Test the chain of trust from the commandline , for debugging purposes . Args : args ( list , optional ) : the commandline args to parse . If None , use ` ` sys . argv [ 1 : ] ` ` . Defaults to None . event _ loop ( asyncio . events . AbstractEven...
args = args or sys . argv [ 1 : ] parser = argparse . ArgumentParser ( description = """Verify a given task's chain of trust. Given a task's `task_id`, get its task definition, then trace its chain of trust back to the tree. This doesn't verify chain of trust artifact signatures, but does run the other tests in `scri...
def patch_namespaced_pod_preset ( self , name , namespace , body , ** kwargs ) : # noqa : E501 """patch _ namespaced _ pod _ preset # noqa : E501 partially update the specified PodPreset # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_namespaced_pod_preset_with_http_info ( name , namespace , body , ** kwargs ) # noqa : E501 else : ( data ) = self . patch_namespaced_pod_preset_with_http_info ( name , namespace , body , ** kwargs ) # noqa :...
def extract_words ( files ) : '''Extracts individual words form files and exports them to individual files .'''
output_directory = 'extracted_words' if not os . path . exists ( output_directory ) : os . makedirs ( output_directory ) for f in files : file_format = None source_segment = None if f . lower ( ) . endswith ( '.mp3' ) : file_format = 'mp3' source_segment = AudioSegment . from_mp3 ( f ) ...
def extract_field ( self , field ) : """extract value from requests . Response ."""
if not isinstance ( field , basestring ) : err_msg = u"Invalid extractor! => {}\n" . format ( field ) logger . log_error ( err_msg ) raise exceptions . ParamsError ( err_msg ) msg = "extract: {}" . format ( field ) if text_extractor_regexp_compile . match ( field ) : value = self . _extract_field_with_r...
def correctly_signed_message ( self , decoded_xml , msgtype , must = False , origdoc = None , only_valid_cert = False ) : """Check if a request is correctly signed , if we have metadata for the entity that sent the info use that , if not use the key that are in the message if any . : param decoded _ xml : The...
attr = '{type}_from_string' . format ( type = msgtype ) _func = getattr ( saml , attr , None ) _func = getattr ( samlp , attr , _func ) msg = _func ( decoded_xml ) if not msg : raise TypeError ( 'Not a {type}' . format ( type = msgtype ) ) if not msg . signature : if must : err_msg = 'Required signature...
def reraise_context ( fmt , * args ) : """Reraise an exception with its message modified to specify additional context . This function tries to help provide context when a piece of code encounters an exception while trying to get something done , and it wishes to propagate contextual information farther up ...
import sys if len ( args ) : cstr = fmt % args else : cstr = text_type ( fmt ) ex = sys . exc_info ( ) [ 1 ] if isinstance ( ex , EnvironmentError ) : ex . strerror = '%s: %s' % ( cstr , ex . strerror ) ex . args = ( ex . errno , ex . strerror ) else : if len ( ex . args ) : cstr = '%s: %s' ...
def load_transcript_fpkm_dict_from_gtf ( gtf_path , transcript_id_column_name = "reference_id" , fpkm_column_name = "FPKM" , feature_column_name = "feature" ) : """Load a GTF file generated by StringTie which contains transcript - level quantification of abundance . Returns a dictionary mapping Ensembl IDs of t...
df = gtfparse . read_gtf ( gtf_path , column_converters = { fpkm_column_name : float } ) transcript_ids = _get_gtf_column ( transcript_id_column_name , gtf_path , df ) fpkm_values = _get_gtf_column ( fpkm_column_name , gtf_path , df ) features = _get_gtf_column ( feature_column_name , gtf_path , df ) logging . info ( "...
def generate_wave ( message , wpm = WPM , framerate = FRAMERATE , skip_frame = 0 , amplitude = AMPLITUDE , frequency = FREQUENCY , word_ref = WORD ) : """Generate binary Morse code of message at a given code speed wpm and framerate Parameters word : string wpm : int or float - word per minute framerate : nb...
lst_bin = _encode_binary ( message ) if amplitude > 1.0 : amplitude = 1.0 if amplitude < 0.0 : amplitude = 0.0 seconds_per_dot = _seconds_per_dot ( word_ref ) # = 1.2 for i in count ( skip_frame ) : bit = morse_bin ( i = i , lst_bin = lst_bin , wpm = wpm , framerate = framerate , default_value = 0.0 , secon...
def _read_file ( name , encoding = 'utf-8' ) -> str : """Read the contents of a file . : param name : The name of the file in the current directory . : param encoding : The encoding of the file ; defaults to utf - 8. : return : The contents of the file ."""
with open ( name , encoding = encoding ) as f : return f . read ( )
def gripper_factory ( name ) : """Genreator for grippers Creates a Gripper instance with the provided name . Args : name : the name of the gripper class Returns : gripper : Gripper instance Raises : XMLError : [ description ]"""
if name == "TwoFingerGripper" : return TwoFingerGripper ( ) if name == "LeftTwoFingerGripper" : return LeftTwoFingerGripper ( ) if name == "PR2Gripper" : return PR2Gripper ( ) if name == "RobotiqGripper" : return RobotiqGripper ( ) if name == "PushingGripper" : return PushingGripper ( ) if name == "...
def scroll ( self ) : '''Perfrom scroll action . Usage : d ( ) . scroll ( steps = 50 ) # default vertically and forward d ( ) . scroll . horiz . forward ( steps = 100) d ( ) . scroll . vert . backward ( steps = 100) d ( ) . scroll . horiz . toBeginning ( steps = 100 , max _ swipes = 100) d ( ) . scroll ...
def __scroll ( vertical , forward , steps = 100 ) : method = self . jsonrpc . scrollForward if forward else self . jsonrpc . scrollBackward return method ( self . selector , vertical , steps ) def __scroll_to_beginning ( vertical , steps = 100 , max_swipes = 1000 ) : return self . jsonrpc . scrollToBeginnin...
def add_days ( self , days : int ) -> datetime : """Adds days"""
self . value = self . value + relativedelta ( days = days ) return self . value
def _create_http_basic_session ( self , username , password , timeout = None ) : """Creates a basic http session . : param username : Username for the session : type username : str : param password : Password for the username : type password : str : param timeout : If set determines the timeout period for...
verify = self . _options [ 'verify' ] self . _session = ResilientSession ( timeout = timeout ) self . _session . verify = verify self . _session . auth = ( username , password ) self . _session . cert = self . _options [ 'client_cert' ]
def parseCatalogFile ( filename ) : """parse an XML file and build a tree . It ' s like xmlParseFile ( ) except it bypass all catalog lookups ."""
ret = libxml2mod . xmlParseCatalogFile ( filename ) if ret is None : raise parserError ( 'xmlParseCatalogFile() failed' ) return xmlDoc ( _obj = ret )
def get_observed_strains_and_df ( observation , observation_dict ) : """observation example : ' ros _ simulated ' observation _ dict example : { ' ros _ simulated ' : [ [ ' NT12204_755 ' , ' wt ' ] , [ ' NT12120_270 ' , ' wt ' ] , . . . ] . . . }"""
observed_df = pd . DataFrame . from_records ( observation_dict [ observation ] , columns = [ 'strain' , 'phenotype' ] ) . set_index ( 'strain' ) observed_strains = observed_df . index . tolist ( ) return observed_strains , observed_df
def get ( key , profile = None ) : '''Get a value from sqlite3'''
if not profile : return None _ , cur , table = _connect ( profile ) q = profile . get ( 'get_query' , ( 'SELECT value FROM {0} WHERE ' 'key=:key' . format ( table ) ) ) res = cur . execute ( q , { 'key' : key } ) res = res . fetchone ( ) if not res : return None return salt . utils . msgpack . unpackb ( res [ 0...
def construct ( self , request , service = None , http_args = None , ** kwargs ) : """Constructs a client assertion and signs it with a key . The request is modified as a side effect . : param request : The request : param service : A : py : class : ` oidcservice . service . Service ` instance : param http ...
if 'client_assertion' in kwargs : request [ "client_assertion" ] = kwargs [ 'client_assertion' ] if 'client_assertion_type' in kwargs : request [ 'client_assertion_type' ] = kwargs [ 'client_assertion_type' ] else : request [ "client_assertion_type" ] = JWT_BEARER elif 'client_assertion' in ...
def register_to_app ( self , app ) : """注册到app上"""
self . app = app # 注册上 self . app . blueprints . append ( self )
def get_plug_mro ( self , plug_type ) : """Returns a list of names identifying the plug classes in the plug ' s MRO . For example : [ ' openhtf . plugs . user _ input . UserInput ' ] Or : [ ' openhtf . plugs . user _ input . UserInput ' , ' my _ module . advanced _ user _ input . AdvancedUserInput ' ]"""
ignored_classes = ( BasePlug , FrontendAwareBasePlug ) return [ self . get_plug_name ( base_class ) for base_class in plug_type . mro ( ) if ( issubclass ( base_class , BasePlug ) and base_class not in ignored_classes ) ]
def defer_reduce ( func , items , test , accum = None ) : '''Recursively reduce items by func , but only the items that do not cause test ( items , accum ) to return False . Returns the reduced list ( accum ) and the list of remaining deferred items .'''
removals = [ ] for k , item in enumerate ( items ) : if test ( item , accum ) : removals . append ( k ) if accum is None : accum = item else : accum = func ( accum , item ) deferred = indices_removed ( items , removals ) if deferred == items or not deferred : retu...
def list_relations ( self ) : '''list every relation in the database as ( src , relation , dst )'''
for node in self . iter_nodes ( ) : for relation , target in self . relations_of ( node . obj , True ) : yield node . obj , relation , target
def _construct_error_handling ( self ) : """Updates the Flask app with Error Handlers for different Error Codes"""
self . _app . register_error_handler ( 500 , LambdaErrorResponses . generic_service_exception ) self . _app . register_error_handler ( 404 , LambdaErrorResponses . generic_path_not_found ) self . _app . register_error_handler ( 405 , LambdaErrorResponses . generic_method_not_allowed )
def __read_lipd_contents ( ) : """Use the file metadata to read in the LiPD file contents as a dataset library : return dict : Metadata"""
global files , settings _d = { } try : if len ( files [ ".lpd" ] ) == 1 : _d = lipd_read ( files [ ".lpd" ] [ 0 ] [ "full_path" ] ) if settings [ "verbose" ] : print ( "Finished read: 1 record" ) else : for file in files [ ".lpd" ] : _d [ file [ "filename_no_ext" ...
def pay_order_query ( self , out_trade_no ) : """查询订单状态 一般用于无法确定 订单状态时候补偿 : param out _ trade _ no : 本地订单号 : return : 订单信息dict"""
package = { 'partner' : self . pay_partner_id , 'out_trade_no' : out_trade_no , } _package = package . items ( ) _package . sort ( ) s = '&' . join ( [ "%s=%s" % ( p [ 0 ] , str ( p [ 1 ] ) ) for p in ( _package + [ ( 'key' , self . pay_partner_key ) ] ) ] ) package [ 'sign' ] = md5 ( s ) . hexdigest ( ) . upper ( ) pa...
def reboot ( search , one = True , force = False ) : '''Reboot one or more vms search : string filter vms , see the execution module . one : boolean reboot only one vm force : boolean force reboot , faster but no graceful shutdown . . note : : If the search parameter does not contain an equal ( = ) ...
return _action ( 'reboot' , search , one , force )
def Expand ( self ) : """Reads the contents of the current node and the full subtree . It then makes the subtree available until the next xmlTextReaderRead ( ) call"""
ret = libxml2mod . xmlTextReaderExpand ( self . _o ) if ret is None : raise treeError ( 'xmlTextReaderExpand() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def gen_all_subclasses ( cls : Type ) -> Generator [ Type , None , None ] : """Generates all subclasses of a class . Args : cls : a class Yields : all subclasses"""
for s1 in cls . __subclasses__ ( ) : yield s1 for s2 in gen_all_subclasses ( s1 ) : yield s2
def append ( self , code ) : """Core API method for appending to the source code stream . It can take the following as input . * Strings * The processor is called if specified . String values from the processed stream are added after newlines are alided and indented . Other values are recursed on . Mult...
# support one - shot push and pop of dictionaries using operators pop_next = self . _pop_next if pop_next : self . _pop_next = False if isinstance ( code , str ) : # Strings are processed , then indented appropriately for token in self . _process ( code ) : prev = self . last_string prev_ends_wi...
def quantile ( x , q ) : """Calculates the q quantile of x . This is the value of x greater than q % of the ordered values from x . : param x : the time series to calculate the feature of : type x : numpy . ndarray : param q : the quantile to calculate : type q : float : return : the value of this feature...
x = pd . Series ( x ) return pd . Series . quantile ( x , q )