idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,400
def _get_char_x ( self , charno ) : return charno * self . fontw + self . image_pad + self . line_number_width
Get the X coordinate of a character position .
241,401
def _get_text_pos ( self , charno , lineno ) : return self . _get_char_x ( charno ) , self . _get_line_y ( lineno )
Get the actual position for a character and line position .
241,402
def _get_image_size ( self , maxcharno , maxlineno ) : return ( self . _get_char_x ( maxcharno ) + self . image_pad , self . _get_line_y ( maxlineno + 0 ) + self . image_pad )
Get the required image size .
241,403
def _draw_linenumber ( self , posno , lineno ) : self . _draw_text ( self . _get_linenumber_pos ( posno ) , str ( lineno ) . rjust ( self . line_number_chars ) , font = self . fonts . get_font ( self . line_number_bold , self . line_number_italic ) , fill = self . line_number_fg , )
Remember a line number drawable to paint later .
241,404
def _draw_text ( self , pos , text , font , ** kw ) : self . drawables . append ( ( pos , text , font , kw ) )
Remember a single drawable tuple to paint later .
241,405
def _create_drawables ( self , tokensource ) : lineno = charno = maxcharno = 0 for ttype , value in tokensource : while ttype not in self . styles : ttype = ttype . parent style = self . styles [ ttype ] value = value . expandtabs ( 4 ) lines = value . splitlines ( True ) for i , line in enumerate ( lines ) : temp = li...
Create drawables for the token content .
241,406
def _draw_line_numbers ( self ) : if not self . line_numbers : return for p in xrange ( self . maxlineno ) : n = p + self . line_number_start if ( n % self . line_number_step ) == 0 : self . _draw_linenumber ( p , n )
Create drawables for the line numbers .
241,407
def _paint_line_number_bg ( self , im ) : if not self . line_numbers : return if self . line_number_fg is None : return draw = ImageDraw . Draw ( im ) recth = im . size [ - 1 ] rectw = self . image_pad + self . line_number_width - self . line_number_pad draw . rectangle ( [ ( 0 , 0 ) , ( rectw , recth ) ] , fill = self...
Paint the line number background on the image .
241,408
def update ( self , attrs ) : data = self . dict ( ) data . update ( attrs ) heartbeat = Heartbeat ( data , self . args , self . configs , _clone = True ) return heartbeat
Return a copy of the current Heartbeat with updated attributes .
241,409
def sanitize ( self ) : if not self . args . hide_file_names : return self if self . entity is None : return self if self . type != 'file' : return self if self . should_obfuscate_filename ( ) : self . _sanitize_metadata ( ) extension = u ( os . path . splitext ( self . entity ) [ 1 ] ) self . entity = u ( 'HIDDEN{0}' ...
Removes sensitive data including file names and dependencies .
241,410
def should_obfuscate_filename ( self ) : for pattern in self . args . hide_file_names : try : compiled = re . compile ( pattern , re . IGNORECASE ) if compiled . search ( self . entity ) : return True except re . error as ex : log . warning ( u ( 'Regex error ({msg}) for hide_file_names pattern: {pattern}' ) . format (...
Returns True if hide_file_names is true or the entity file path matches one in the list of obfuscated file paths .
241,411
def _format_local_file ( self ) : if self . type != 'file' : return if not self . entity : return if not is_win : return if self . _file_exists ( ) : return self . args . local_file = self . _to_unc_path ( self . entity )
When args . local_file empty on Windows tries to map args . entity to a unc path .
241,412
def create_negotiate_message ( self , domain_name = None , workstation = None ) : self . negotiate_message = NegotiateMessage ( self . negotiate_flags , domain_name , workstation ) return base64 . b64encode ( self . negotiate_message . get_data ( ) )
Create an NTLM NEGOTIATE_MESSAGE
241,413
def parse_challenge_message ( self , msg2 ) : msg2 = base64 . b64decode ( msg2 ) self . challenge_message = ChallengeMessage ( msg2 )
Parse the NTLM CHALLENGE_MESSAGE from the server and add it to the Ntlm context fields
241,414
def create_authenticate_message ( self , user_name , password , domain_name = None , workstation = None , server_certificate_hash = None ) : self . authenticate_message = AuthenticateMessage ( user_name , password , domain_name , workstation , self . challenge_message , self . ntlm_compatibility , server_certificate_ha...
Create an NTLM AUTHENTICATE_MESSAGE based on the Ntlm context and the previous messages sent and received
241,415
def lex ( code , lexer ) : try : return lexer . get_tokens ( code ) except TypeError as err : if ( isinstance ( err . args [ 0 ] , str ) and ( 'unbound method get_tokens' in err . args [ 0 ] or 'missing 1 required positional argument' in err . args [ 0 ] ) ) : raise TypeError ( 'lex() argument must be a lexer instance,...
Lex code with lexer and return an iterable of tokens .
241,416
def format ( tokens , formatter , outfile = None ) : try : if not outfile : realoutfile = getattr ( formatter , 'encoding' , None ) and BytesIO ( ) or StringIO ( ) formatter . format ( tokens , realoutfile ) return realoutfile . getvalue ( ) else : formatter . format ( tokens , outfile ) except TypeError as err : if ( ...
Format a tokenlist tokens with the formatter formatter .
241,417
def highlight ( code , lexer , formatter , outfile = None ) : return format ( lex ( code , lexer ) , formatter , outfile )
Lex code with lexer and format it with the formatter formatter .
241,418
def getConfigFile ( ) : fileName = '.wakatime.cfg' home = os . environ . get ( 'WAKATIME_HOME' ) if home : return os . path . join ( os . path . expanduser ( home ) , fileName ) return os . path . join ( os . path . expanduser ( '~' ) , fileName )
Returns the config file location .
241,419
def find_filter_class ( filtername ) : if filtername in FILTERS : return FILTERS [ filtername ] for name , cls in find_plugin_filters ( ) : if name == filtername : return cls return None
Lookup a filter by name . Return None if not found .
241,420
def get_filter_by_name ( filtername , ** options ) : cls = find_filter_class ( filtername ) if cls : return cls ( ** options ) else : raise ClassNotFound ( 'filter %r not found' % filtername )
Return an instantiated filter .
241,421
def get_tokens_unprocessed ( self , text ) : tokens = self . _block_re . split ( text ) tokens . reverse ( ) state = idx = 0 try : while True : if state == 0 : val = tokens . pop ( ) yield idx , Other , val idx += len ( val ) state = 1 elif state == 1 : tag = tokens . pop ( ) if tag in ( '<%%' , '%%>' ) : yield idx , O...
Since ERB doesn t allow <% and other tags inside of ruby blocks we have to use a split approach here that fails for that too .
241,422
def format_file_path ( filepath ) : try : is_windows_network_mount = WINDOWS_NETWORK_MOUNT_PATTERN . match ( filepath ) filepath = os . path . realpath ( os . path . abspath ( filepath ) ) filepath = re . sub ( BACKSLASH_REPLACE_PATTERN , '/' , filepath ) is_windows_drive = WINDOWS_DRIVE_PATTERN . match ( filepath ) if...
Formats a path as absolute and with the correct platform separator .
241,423
def close ( self ) : old_pool , self . pool = self . pool , None try : while True : conn = old_pool . get ( block = False ) if conn : conn . close ( ) except queue . Empty : pass
Close all pooled connections and disable the pool .
241,424
def is_same_host ( self , url ) : if url . startswith ( '/' ) : return True scheme , host , port = get_host ( url ) host = _ipv6_host ( host ) . lower ( ) if self . port and not port : port = port_by_scheme . get ( scheme ) elif not self . port and port == port_by_scheme . get ( scheme ) : port = None return ( scheme ,...
Check if the given url is a member of the same host as this connection pool .
241,425
def filename ( self , value ) : warnings . warn ( "The 'filename' attribute will be removed in future versions. " "Use 'source' instead." , DeprecationWarning , stacklevel = 2 ) self . source = value
Deprecated user source .
241,426
def options ( self , section ) : try : opts = self . _sections [ section ] . copy ( ) except KeyError : raise from_none ( NoSectionError ( section ) ) opts . update ( self . _defaults ) return list ( opts . keys ( ) )
Return a list of option names for the given section name .
241,427
def read_string ( self , string , source = '<string>' ) : sfile = io . StringIO ( string ) self . read_file ( sfile , source )
Read configuration from a given string .
241,428
def read_dict ( self , dictionary , source = '<dict>' ) : elements_added = set ( ) for section , keys in dictionary . items ( ) : section = str ( section ) try : self . add_section ( section ) except ( DuplicateSectionError , ValueError ) : if self . _strict and section in elements_added : raise elements_added . add ( ...
Read configuration from a dictionary .
241,429
def readfp ( self , fp , filename = None ) : warnings . warn ( "This method will be removed in future versions. " "Use 'parser.read_file()' instead." , DeprecationWarning , stacklevel = 2 ) self . read_file ( fp , source = filename )
Deprecated use read_file instead .
241,430
def has_option ( self , section , option ) : if not section or section == self . default_section : option = self . optionxform ( option ) return option in self . _defaults elif section not in self . _sections : return False else : option = self . optionxform ( option ) return ( option in self . _sections [ section ] or...
Check for the existence of a given option in a given section . If the specified section is None or an empty string DEFAULT is assumed . If the specified section does not exist returns False .
241,431
def _write_section ( self , fp , section_name , section_items , delimiter ) : fp . write ( "[{0}]\n" . format ( section_name ) ) for key , value in section_items : value = self . _interpolation . before_write ( self , section_name , key , value ) if value is not None or not self . _allow_no_value : value = delimiter + ...
Write a single section to the specified fp .
241,432
def _unify_values ( self , section , vars ) : sectiondict = { } try : sectiondict = self . _sections [ section ] except KeyError : if section != self . default_section : raise NoSectionError ( section ) vardict = { } if vars : for key , value in vars . items ( ) : if value is not None : value = str ( value ) vardict [ ...
Create a sequence of lookups with vars taking priority over the section which takes priority over the DEFAULTSECT .
241,433
def _convert_to_boolean ( self , value ) : if value . lower ( ) not in self . BOOLEAN_STATES : raise ValueError ( 'Not a boolean: %s' % value ) return self . BOOLEAN_STATES [ value . lower ( ) ]
Return a boolean value translating from other types if necessary .
241,434
def _validate_value_types ( self , ** kwargs ) : section = kwargs . get ( 'section' , "" ) option = kwargs . get ( 'option' , "" ) value = kwargs . get ( 'value' , "" ) if PY2 and bytes in ( type ( section ) , type ( option ) , type ( value ) ) : warnings . warn ( "You passed a bytestring. Implicitly decoding as UTF-8 ...
Raises a TypeError for non - string values .
241,435
def set ( self , section , option , value = None ) : _ , option , value = self . _validate_value_types ( option = option , value = value ) super ( ConfigParser , self ) . set ( section , option , value )
Set an option . Extends RawConfigParser . set by validating type and interpolation syntax on the value .
241,436
def add_section ( self , section ) : section , _ , _ = self . _validate_value_types ( section = section ) super ( ConfigParser , self ) . add_section ( section )
Create a new section in the configuration . Extends RawConfigParser . add_section by validating if the section name is a string .
241,437
def get ( self , option , fallback = None , ** kwargs ) : kwargs . setdefault ( 'raw' , False ) kwargs . setdefault ( 'vars' , None ) _impl = kwargs . pop ( '_impl' , None ) if not _impl : _impl = self . _parser . get return _impl ( self . _name , option , fallback = fallback , ** kwargs )
Get an option value .
241,438
def analyse_text ( text ) : if re . match ( r'^\s*REBOL\s*\[' , text , re . IGNORECASE ) : return 1.0 elif re . search ( r'\s*REBOL\s*[' , text , re . IGNORECASE ) : return 0.5
Check if code contains REBOL header and so it probably not R code
241,439
def get_sign_key ( exported_session_key , magic_constant ) : sign_key = hashlib . md5 ( exported_session_key + magic_constant ) . digest ( ) return sign_key
3 . 4 . 5 . 2 SIGNKEY
241,440
def _wait_for_io_events ( socks , events , timeout = None ) : if not HAS_SELECT : raise ValueError ( 'Platform does not have a selector' ) if not isinstance ( socks , list ) : if hasattr ( socks , "fileno" ) : socks = [ socks ] else : socks = list ( socks ) with DefaultSelector ( ) as selector : for sock in socks : sel...
Waits for IO events to be available from a list of sockets or optionally a single socket if passed in . Returns a list of sockets that can be interacted with immediately .
241,441
def make_analysator ( f ) : def text_analyse ( text ) : try : rv = f ( text ) except Exception : return 0.0 if not rv : return 0.0 try : return min ( 1.0 , max ( 0.0 , float ( rv ) ) ) except ( ValueError , TypeError ) : return 0.0 text_analyse . __doc__ = f . __doc__ return staticmethod ( text_analyse )
Return a static text analyser function that returns float values .
241,442
def shebang_matches ( text , regex ) : r index = text . find ( '\n' ) if index >= 0 : first_line = text [ : index ] . lower ( ) else : first_line = text . lower ( ) if first_line . startswith ( '#!' ) : try : found = [ x for x in split_path_re . split ( first_line [ 2 : ] . strip ( ) ) if x and not x . startswith ( '-'...
r Check if the given regular expression matches the last part of the shebang if one exists .
241,443
def looks_like_xml ( text ) : if xml_decl_re . match ( text ) : return True key = hash ( text ) try : return _looks_like_xml_cache [ key ] except KeyError : m = doctype_lookup_re . match ( text ) if m is not None : return True rv = tag_re . search ( text [ : 1000 ] ) is not None _looks_like_xml_cache [ key ] = rv retur...
Check if a doctype exists or if we have some tags .
241,444
def unirange ( a , b ) : if b < a : raise ValueError ( "Bad character range" ) if a < 0x10000 or b < 0x10000 : raise ValueError ( "unirange is only defined for non-BMP ranges" ) if sys . maxunicode > 0xffff : return u'[%s-%s]' % ( unichr ( a ) , unichr ( b ) ) else : ah , al = _surrogatepair ( a ) bh , bl = _surrogatep...
Returns a regular expression string to match the given non - BMP range .
241,445
def format_lines ( var_name , seq , raw = False , indent_level = 0 ) : lines = [ ] base_indent = ' ' * indent_level * 4 inner_indent = ' ' * ( indent_level + 1 ) * 4 lines . append ( base_indent + var_name + ' = (' ) if raw : for i in seq : lines . append ( inner_indent + i + ',' ) else : for i in seq : r = repr ( i + ...
Formats a sequence of strings for output .
241,446
def duplicates_removed ( it , already_seen = ( ) ) : lst = [ ] seen = set ( ) for i in it : if i in seen or i in already_seen : continue lst . append ( i ) seen . add ( i ) return lst
Returns a list with duplicates removed from the iterable it .
241,447
def _lex_fortran ( self , match , ctx = None ) : lexer = FortranLexer ( ) text = match . group ( 0 ) + "\n" for index , token , value in lexer . get_tokens_unprocessed ( text ) : value = value . replace ( '\n' , '' ) if value != '' : yield index , token , value
Lex a line just as free form fortran without line break .
241,448
def get_project_info ( configs , heartbeat , data ) : project_name , branch_name = heartbeat . project , heartbeat . branch if heartbeat . type != 'file' : project_name = project_name or heartbeat . args . project or heartbeat . args . alternate_project return project_name , branch_name if project_name is None or branc...
Find the current project and branch .
241,449
def generate_project_name ( ) : adjectives = [ 'aged' , 'ancient' , 'autumn' , 'billowing' , 'bitter' , 'black' , 'blue' , 'bold' , 'broad' , 'broken' , 'calm' , 'cold' , 'cool' , 'crimson' , 'curly' , 'damp' , 'dark' , 'dawn' , 'delicate' , 'divine' , 'dry' , 'empty' , 'falling' , 'fancy' , 'flat' , 'floral' , 'fragra...
Generates a random project name .
241,450
def save ( self , session ) : if not HAS_SQL : return try : conn , c = self . connect ( ) c . execute ( 'DELETE FROM {0}' . format ( self . table_name ) ) values = { 'value' : sqlite3 . Binary ( pickle . dumps ( session , protocol = 2 ) ) , } c . execute ( 'INSERT INTO {0} VALUES (:value)' . format ( self . table_name ...
Saves a requests . Session object for the next heartbeat process .
241,451
def get ( self ) : if not HAS_SQL : return requests . session ( ) try : conn , c = self . connect ( ) except : log . traceback ( logging . DEBUG ) return requests . session ( ) session = None try : c . execute ( 'BEGIN IMMEDIATE' ) c . execute ( 'SELECT value FROM {0} LIMIT 1' . format ( self . table_name ) ) row = c ....
Returns a requests . Session object .
241,452
def delete ( self ) : if not HAS_SQL : return try : conn , c = self . connect ( ) c . execute ( 'DELETE FROM {0}' . format ( self . table_name ) ) conn . commit ( ) conn . close ( ) except : log . traceback ( logging . DEBUG )
Clears all cached Session objects .
241,453
def resolve_redirects ( self , resp , req , stream = False , timeout = None , verify = True , cert = None , proxies = None , yield_requests = False , ** adapter_kwargs ) : hist = [ ] url = self . get_redirect_target ( resp ) while url : prepared_request = req . copy ( ) hist . append ( resp ) resp . history = hist [ 1 ...
Receives a Response . Returns a generator of Responses or Requests .
241,454
def rebuild_method ( self , prepared_request , response ) : method = prepared_request . method if response . status_code == codes . see_other and method != 'HEAD' : method = 'GET' if response . status_code == codes . found and method != 'HEAD' : method = 'GET' if response . status_code == codes . moved and method == 'P...
When being redirected we may want to change the method of the request based on certain specs or browser behavior .
241,455
def apply_filters ( stream , filters , lexer = None ) : def _apply ( filter_ , stream ) : for token in filter_ . filter ( lexer , stream ) : yield token for filter_ in filters : stream = _apply ( filter_ , stream ) return stream
Use this method to apply an iterable of filters to a stream . If lexer is given it s forwarded to the filter otherwise the filter receives None .
241,456
def reset_indent ( token_class ) : def callback ( lexer , match , context ) : text = match . group ( ) context . indent_stack = [ ] context . indent = - 1 context . next_indent = 0 context . block_scalar_indent = None yield match . start ( ) , token_class , text context . pos = match . end ( ) return callback
Reset the indentation levels .
241,457
def save_indent ( token_class , start = False ) : def callback ( lexer , match , context ) : text = match . group ( ) extra = '' if start : context . next_indent = len ( text ) if context . next_indent < context . indent : while context . next_indent < context . indent : context . indent = context . indent_stack . pop ...
Save a possible indentation level .
241,458
def set_block_scalar_indent ( token_class ) : def callback ( lexer , match , context ) : text = match . group ( ) context . block_scalar_indent = None if not text : return increment = match . group ( 1 ) if increment : current_indent = max ( context . indent , 0 ) increment = int ( increment ) context . block_scalar_in...
Set an explicit indentation level for a block scalar .
241,459
def parse_block_scalar_indent ( token_class ) : def callback ( lexer , match , context ) : text = match . group ( ) if context . block_scalar_indent is None : if len ( text ) <= max ( context . indent , 0 ) : context . stack . pop ( ) context . stack . pop ( ) return context . block_scalar_indent = len ( text ) else : ...
Process indentation spaces in a block scalar .
241,460
def content ( self ) : if self . _content is False : if self . _content_consumed : raise RuntimeError ( 'The content for this response was already consumed' ) if self . status_code == 0 or self . raw is None : self . _content = None else : self . _content = bytes ( ) . join ( self . iter_content ( CONTENT_CHUNK_SIZE ) ...
Content of the response in bytes .
241,461
def py_scanstring ( s , end , encoding = None , strict = True , _b = BACKSLASH , _m = STRINGCHUNK . match , _join = u ( '' ) . join , _PY3 = PY3 , _maxunicode = sys . maxunicode ) : if encoding is None : encoding = DEFAULT_ENCODING chunks = [ ] _append = chunks . append begin = end - 1 while 1 : chunk = _m ( s , end ) ...
Scan the string s for a JSON string . End is the index of the character in s after the quote that started the JSON string . Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string . If strict is False then literal control characters are allowed in the string .
241,462
def _get_css_class ( self , ttype ) : ttypeclass = _get_ttype_class ( ttype ) if ttypeclass : return self . classprefix + ttypeclass return ''
Return the css class of this token type prefixed with the classprefix option .
241,463
def _get_css_classes ( self , ttype ) : cls = self . _get_css_class ( ttype ) while ttype not in STANDARD_TYPES : ttype = ttype . parent cls = self . _get_css_class ( ttype ) + ' ' + cls return cls
Return the css classes of this token type prefixed with the classprefix option .
241,464
def get_style_defs ( self , arg = None ) : if arg is None : arg = ( 'cssclass' in self . options and '.' + self . cssclass or '' ) if isinstance ( arg , string_types ) : args = [ arg ] else : args = list ( arg ) def prefix ( cls ) : if cls : cls = '.' + cls tmp = [ ] for arg in args : tmp . append ( ( arg and arg + ' '...
Return CSS style definitions for the classes produced by the current highlighting style . arg can be a string or list of selectors to insert before the token type classes .
241,465
def _format_lines ( self , tokensource ) : nocls = self . noclasses lsep = self . lineseparator getcls = self . ttype2class . get c2s = self . class2style escape_table = _escape_html_table tagsfile = self . tagsfile lspan = '' line = [ ] for ttype , value in tokensource : if nocls : cclass = getcls ( ttype ) while ccla...
Just format the tokens without any wrapping tags . Yield individual lines .
241,466
def _highlight_lines ( self , tokensource ) : hls = self . hl_lines for i , ( t , value ) in enumerate ( tokensource ) : if t != 1 : yield t , value if i + 1 in hls : if self . noclasses : style = '' if self . style . highlight_color is not None : style = ( ' style="background-color: %s"' % ( self . style . highlight_c...
Highlighted the lines specified in the hl_lines option by post - processing the token stream coming from _format_lines .
241,467
def format_unencoded ( self , tokensource , outfile ) : source = self . _format_lines ( tokensource ) if self . hl_lines : source = self . _highlight_lines ( source ) if not self . nowrap : if self . linenos == 2 : source = self . _wrap_inlinelinenos ( source ) if self . lineanchors : source = self . _wrap_lineanchors ...
The formatting process uses several nested generators ; which of them are used is determined by the user s options .
241,468
def bygroups ( * args ) : def callback ( lexer , match , ctx = None ) : for i , action in enumerate ( args ) : if action is None : continue elif type ( action ) is _TokenType : data = match . group ( i + 1 ) if data : yield match . start ( i + 1 ) , action , data else : data = match . group ( i + 1 ) if data is not Non...
Callback that yields multiple actions for each group in the match .
241,469
def using ( _other , ** kwargs ) : gt_kwargs = { } if 'state' in kwargs : s = kwargs . pop ( 'state' ) if isinstance ( s , ( list , tuple ) ) : gt_kwargs [ 'stack' ] = s else : gt_kwargs [ 'stack' ] = ( 'root' , s ) if _other is this : def callback ( lexer , match , ctx = None ) : if kwargs : kwargs . update ( lexer . ...
Callback that processes the match with a different lexer .
241,470
def do_insertions ( insertions , tokens ) : insertions = iter ( insertions ) try : index , itokens = next ( insertions ) except StopIteration : for item in tokens : yield item return realpos = None insleft = True for i , t , v in tokens : if realpos is None : realpos = i oldi = 0 while insleft and i + len ( v ) >= inde...
Helper for lexers which must combine the results of several sublexers .
241,471
def _process_regex ( cls , regex , rflags , state ) : if isinstance ( regex , Future ) : regex = regex . get ( ) return re . compile ( regex , rflags ) . match
Preprocess the regular expression component of a token definition .
241,472
def _process_token ( cls , token ) : assert type ( token ) is _TokenType or callable ( token ) , 'token type must be simple type or callable, not %r' % ( token , ) return token
Preprocess the token component of a token definition .
241,473
def _process_new_state ( cls , new_state , unprocessed , processed ) : if isinstance ( new_state , str ) : if new_state == '#pop' : return - 1 elif new_state in unprocessed : return ( new_state , ) elif new_state == '#push' : return new_state elif new_state [ : 5 ] == '#pop:' : return - int ( new_state [ 5 : ] ) else :...
Preprocess the state transition action of a token definition .
241,474
def _process_state ( cls , unprocessed , processed , state ) : assert type ( state ) is str , "wrong state name %r" % state assert state [ 0 ] != '#' , "invalid state name %r" % state if state in processed : return processed [ state ] tokens = processed [ state ] = [ ] rflags = cls . flags for tdef in unprocessed [ sta...
Preprocess a single state definition .
241,475
def process_tokendef ( cls , name , tokendefs = None ) : processed = cls . _all_tokens [ name ] = { } tokendefs = tokendefs or cls . tokens [ name ] for state in list ( tokendefs ) : cls . _process_state ( tokendefs , processed , state ) return processed
Preprocess a dictionary of token definitions .
241,476
def get_tokendefs ( cls ) : tokens = { } inheritable = { } for c in cls . __mro__ : toks = c . __dict__ . get ( 'tokens' , { } ) for state , items in iteritems ( toks ) : curitems = tokens . get ( state ) if curitems is None : tokens [ state ] = items try : inherit_ndx = items . index ( inherit ) except ValueError : co...
Merge tokens from superclasses in MRO order returning a single tokendef dictionary .
241,477
def memorized_timedelta ( seconds ) : try : return _timedelta_cache [ seconds ] except KeyError : delta = timedelta ( seconds = seconds ) _timedelta_cache [ seconds ] = delta return delta
Create only one instance of each distinct timedelta
241,478
def memorized_datetime ( seconds ) : try : return _datetime_cache [ seconds ] except KeyError : dt = _epoch + timedelta ( seconds = seconds ) _datetime_cache [ seconds ] = dt return dt
Create only one instance of each distinct datetime
241,479
def memorized_ttinfo ( * args ) : try : return _ttinfo_cache [ args ] except KeyError : ttinfo = ( memorized_timedelta ( args [ 0 ] ) , memorized_timedelta ( args [ 1 ] ) , args [ 2 ] ) _ttinfo_cache [ args ] = ttinfo return ttinfo
Create only one instance of each distinct tuple
241,480
def unpickler ( zone , utcoffset = None , dstoffset = None , tzname = None ) : tz = pytz . timezone ( zone ) if utcoffset is None : return tz utcoffset = memorized_timedelta ( utcoffset ) dstoffset = memorized_timedelta ( dstoffset ) try : return tz . _tzinfos [ ( utcoffset , dstoffset , tzname ) ] except KeyError : pa...
Factory function for unpickling pytz tzinfo instances .
241,481
def utcoffset ( self , dt , is_dst = None ) : if dt is None : return None elif dt . tzinfo is not self : dt = self . localize ( dt , is_dst ) return dt . tzinfo . _utcoffset else : return self . _utcoffset
See datetime . tzinfo . utcoffset
241,482
def dst ( self , dt , is_dst = None ) : if dt is None : return None elif dt . tzinfo is not self : dt = self . localize ( dt , is_dst ) return dt . tzinfo . _dst else : return self . _dst
See datetime . tzinfo . dst
241,483
def tzname ( self , dt , is_dst = None ) : if dt is None : return self . zone elif dt . tzinfo is not self : dt = self . localize ( dt , is_dst ) return dt . tzinfo . _tzname else : return self . _tzname
See datetime . tzinfo . tzname
241,484
def check_range ( number , min_r , max_r , name = "" ) : try : number = float ( number ) if number < min_r or number > max_r : raise FFmpegNormalizeError ( "{} must be within [{},{}]" . format ( name , min_r , max_r ) ) return number pass except Exception as e : raise e
Check if a number is within a given range
241,485
def add_media_file ( self , input_file , output_file ) : if not os . path . exists ( input_file ) : raise FFmpegNormalizeError ( "file " + input_file + " does not exist" ) ext = os . path . splitext ( output_file ) [ 1 ] [ 1 : ] if ( self . audio_codec is None or 'pcm' in self . audio_codec ) and ext in PCM_INCOMPATIBL...
Add a media file to normalize
241,486
def run_normalization ( self ) : for index , media_file in enumerate ( tqdm ( self . media_files , desc = "File" , disable = not self . progress , position = 0 ) ) : logger . info ( "Normalizing file {} ({} of {})" . format ( media_file , index + 1 , self . file_count ) ) media_file . run_normalization ( ) logger . inf...
Run the normalization procedures
241,487
def get_ffmpeg_exe ( ) : if 'FFMPEG_PATH' in os . environ : ffmpeg_exe = os . environ [ 'FFMPEG_PATH' ] else : ffmpeg_exe = which ( 'ffmpeg' ) if not ffmpeg_exe : if which ( 'avconv' ) : raise FFmpegNormalizeError ( "avconv is not supported. " "Please install ffmpeg from http://ffmpeg.org instead." ) else : raise FFmpe...
Return path to ffmpeg executable
241,488
def ffmpeg_has_loudnorm ( ) : cmd_runner = CommandRunner ( [ get_ffmpeg_exe ( ) , '-filters' ] ) cmd_runner . run_command ( ) output = cmd_runner . get_output ( ) if 'loudnorm' in output : return True else : logger . warning ( "Your ffmpeg version does not support the 'loudnorm' filter. " "Please make sure you are runn...
Run feature detection on ffmpeg returns True if ffmpeg supports the loudnorm filter
241,489
def parse_streams ( self ) : logger . debug ( "Parsing streams of {}" . format ( self . input_file ) ) cmd = [ self . ffmpeg_normalize . ffmpeg_exe , '-i' , self . input_file , '-c' , 'copy' , '-t' , '0' , '-map' , '0' , '-f' , 'null' , NUL ] cmd_runner = CommandRunner ( cmd ) cmd_runner . run_command ( ) output = cmd_...
Try to parse all input streams from file
241,490
def _get_audio_filter_cmd ( self ) : all_filters = [ ] output_labels = [ ] for audio_stream in self . streams [ 'audio' ] . values ( ) : if self . ffmpeg_normalize . normalization_type == 'ebu' : stream_filter = audio_stream . get_second_pass_opts_ebu ( ) else : stream_filter = audio_stream . get_second_pass_opts_peakr...
Return filter_complex command and output labels needed
241,491
def parse_volumedetect_stats ( self ) : logger . info ( "Running first pass volumedetect filter for stream {}" . format ( self . stream_id ) ) filter_str = '[0:{}]volumedetect' . format ( self . stream_id ) cmd = [ self . media_file . ffmpeg_normalize . ffmpeg_exe , '-nostdin' , '-y' , '-i' , self . media_file . input_...
Use ffmpeg with volumedetect filter to get the mean volume of the input file .
241,492
def parse_loudnorm_stats ( self ) : logger . info ( "Running first pass loudnorm filter for stream {}" . format ( self . stream_id ) ) opts = { 'i' : self . media_file . ffmpeg_normalize . target_level , 'lra' : self . media_file . ffmpeg_normalize . loudness_range_target , 'tp' : self . media_file . ffmpeg_normalize ....
Run a first pass loudnorm filter to get measured data .
241,493
def get_second_pass_opts_ebu ( self ) : if not self . loudness_statistics [ 'ebu' ] : raise FFmpegNormalizeError ( "First pass not run, you must call parse_loudnorm_stats first" ) input_i = float ( self . loudness_statistics [ 'ebu' ] [ "input_i" ] ) if input_i > 0 : logger . warn ( "Input file had measured input loudn...
Return second pass loudnorm filter options string for ffmpeg
241,494
def setup_custom_logger ( name ) : global loggers if loggers . get ( name ) : return loggers . get ( name ) formatter = logging . Formatter ( fmt = '%(levelname)s: %(message)s' ) handler = TqdmLoggingHandler ( ) handler . setFormatter ( formatter ) if system ( ) not in [ 'Windows' , 'cli' ] : logging . addLevelName ( l...
Create a logger with a certain name and level
241,495
def register_checkers ( linter ) : linter . register_checker ( ModelChecker ( linter ) ) linter . register_checker ( DjangoInstalledChecker ( linter ) ) linter . register_checker ( JsonResponseChecker ( linter ) ) linter . register_checker ( FormChecker ( linter ) )
Register checkers .
241,496
def register ( linter ) : linter . register_checker ( NewDbFieldWithDefaultChecker ( linter ) ) if not compat . LOAD_CONFIGURATION_SUPPORTED : load_configuration ( linter )
Required method to auto register this checker .
241,497
def ignore_import_warnings_for_related_fields ( orig_method , self , node ) : consumer = self . _to_consume [ 0 ] new_things = { } iterat = consumer . to_consume . items if PY3 else consumer . to_consume . iteritems for name , stmts in iterat ( ) : if isinstance ( stmts [ 0 ] , ImportFrom ) : if any ( [ n [ 0 ] in ( 'F...
Replaces the leave_module method on the VariablesChecker class to prevent unused - import warnings which are caused by the ForeignKey and OneToOneField transformations . By replacing the nodes in the AST with their type rather than the django field imports of the form from django . db . models import OneToOneField rais...
241,498
def is_model_admin_subclass ( node ) : if node . name [ - 5 : ] != 'Admin' or isinstance ( node . parent , ClassDef ) : return False return node_is_subclass ( node , 'django.contrib.admin.options.ModelAdmin' )
Checks that node is derivative of ModelAdmin class .
241,499
def is_model_factory ( node ) : try : parent_classes = node . expr . inferred ( ) except : return False parents = ( 'factory.declarations.LazyFunction' , 'factory.declarations.SubFactory' , 'factory.django.DjangoModelFactory' ) for parent_class in parent_classes : try : if parent_class . qname ( ) in parents : return T...
Checks that node is derivative of DjangoModelFactory or SubFactory class .