idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
24,000 | def setupTable_post ( self ) : if "post" not in self . tables : return self . otf [ "post" ] = post = newTable ( "post" ) font = self . ufo post . formatType = 3.0 # italic angle italicAngle = getAttrWithFallback ( font . info , "italicAngle" ) post . italicAngle = italicAngle # underline underlinePosition = getAttrWithFallback ( font . info , "postscriptUnderlinePosition" ) post . underlinePosition = otRound ( underlinePosition ) underlineThickness = getAttrWithFallback ( font . info , "postscriptUnderlineThickness" ) post . underlineThickness = otRound ( underlineThickness ) post . isFixedPitch = getAttrWithFallback ( font . info , "postscriptIsFixedPitch" ) # misc post . minMemType42 = 0 post . maxMemType42 = 0 post . minMemType1 = 0 post . maxMemType1 = 0 | Make the post table . | 235 | 5 |
24,001 | def importTTX ( self ) : import os import re prefix = "com.github.fonttools.ttx" sfntVersionRE = re . compile ( '(^<ttFont\s+)(sfntVersion=".*"\s+)(.*>$)' , flags = re . MULTILINE ) if not hasattr ( self . ufo , "data" ) : return if not self . ufo . data . fileNames : return for path in self . ufo . data . fileNames : foldername , filename = os . path . split ( path ) if ( foldername == prefix and filename . endswith ( ".ttx" ) ) : ttx = self . ufo . data [ path ] . decode ( 'utf-8' ) # strip 'sfntVersion' attribute from ttFont element, # if present, to avoid overwriting the current value ttx = sfntVersionRE . sub ( r'\1\3' , ttx ) fp = BytesIO ( ttx . encode ( 'utf-8' ) ) self . otf . importXML ( fp ) | Merge TTX files from data directory com . github . fonttools . ttx | 244 | 17 |
24,002 | def setupTable_post ( self ) : super ( OutlineTTFCompiler , self ) . setupTable_post ( ) if "post" not in self . otf : return post = self . otf [ "post" ] post . formatType = 2.0 post . extraNames = [ ] post . mapping = { } post . glyphOrder = self . glyphOrder | Make a format 2 post table with the compiler s glyph order . | 80 | 13 |
24,003 | def setupTable_glyf ( self ) : if not { "glyf" , "loca" } . issubset ( self . tables ) : return self . otf [ "loca" ] = newTable ( "loca" ) self . otf [ "glyf" ] = glyf = newTable ( "glyf" ) glyf . glyphs = { } glyf . glyphOrder = self . glyphOrder hmtx = self . otf . get ( "hmtx" ) allGlyphs = self . allGlyphs for name in self . glyphOrder : glyph = allGlyphs [ name ] pen = TTGlyphPen ( allGlyphs ) try : glyph . draw ( pen ) except NotImplementedError : logger . error ( "%r has invalid curve format; skipped" , name ) ttGlyph = Glyph ( ) else : ttGlyph = pen . glyph ( ) if ( ttGlyph . isComposite ( ) and hmtx is not None and self . autoUseMyMetrics ) : self . autoUseMyMetrics ( ttGlyph , name , hmtx ) glyf [ name ] = ttGlyph | Make the glyf table . | 271 | 6 |
24,004 | def loadLanguage ( filename ) : L = { "consonants" : [ ] , "vowels" : [ ] , "onsets" : [ ] } f = open ( filename , "r" ) section = None for line in f : line = line . strip ( ) if line in ( "[consonants]" , "[vowels]" , "[onsets]" ) : section = line [ 1 : - 1 ] elif section == None : raise ValueError , "File must start with a section header such as [consonants]." elif not section in L : raise ValueError , "Invalid section: " + section else : L [ section ] . append ( line ) for section in "consonants" , "vowels" , "onsets" : if len ( L [ section ] ) == 0 : raise ValueError , "File does not contain any consonants, vowels, or onsets." return L | This function loads up a language configuration file and returns the configuration to be passed to the syllabify function . | 199 | 22 |
24,005 | def stringify ( syllables ) : ret = [ ] for syl in syllables : stress , onset , nucleus , coda = syl if stress != None and len ( nucleus ) != 0 : nucleus [ 0 ] += str ( stress ) ret . append ( " " . join ( onset + nucleus + coda ) ) return " . " . join ( ret ) | This function takes a syllabification returned by syllabify and turns it into a string with phonemes spearated by spaces and syllables spearated by periods . | 77 | 34 |
24,006 | def slice ( l , num_slices = None , slice_length = None , runts = True , random = False ) : if random : import random random . shuffle ( l ) if not num_slices and not slice_length : return l if not slice_length : slice_length = int ( len ( l ) / num_slices ) newlist = [ l [ i : i + slice_length ] for i in range ( 0 , len ( l ) , slice_length ) ] if runts : return newlist return [ lx for lx in newlist if len ( lx ) == slice_length ] | Returns a new list of n evenly - sized segments of the original list | 137 | 14 |
24,007 | def u2s ( self , u ) : try : return u . encode ( 'utf-8' , errors = 'ignore' ) except ( UnicodeDecodeError , AttributeError ) as e : try : return str ( u ) except UnicodeEncodeError : return unicode ( u ) . encode ( 'utf-8' , errors = 'ignore' ) | Returns an ASCII representation of the Unicode string u . | 77 | 10 |
24,008 | def wordtokens ( self , include_punct = True ) : ws = self . ents ( 'WordToken' ) if not include_punct : return [ w for w in ws if not w . is_punct ] return ws | Returns a list of this object s Words in order of their appearance . Set flattenList to False to receive a list of lists of Words . | 56 | 29 |
24,009 | def dir ( self , methods = True , showall = True ) : import inspect #print "[attributes]" for k , v in sorted ( self . __dict__ . items ( ) ) : if k . startswith ( "_" ) : continue print makeminlength ( "." + k , being . linelen ) , "\t" , v if not methods : return entmethods = dir ( entity ) print #print "[methods]" for x in [ x for x in dir ( self ) if ( "bound method " + self . classname ( ) in str ( getattr ( self , x ) ) ) and not x . startswith ( "_" ) ] : if ( not showall ) and ( x in entmethods ) : continue attr = getattr ( self , x ) #print attr.__dict__ #print dir(attr) #doc=inspect.getdoc(attr) doc = attr . __doc__ if not doc : doc = "" #else: # docsplit=[z for z in doc.replace("\r","\n").split("\n") if z] # if len(docsplit)>1: # doc = docsplit[0] + "\n" + makeminlength(" ",being.linelen) + "\n".join( makeminlength(" ",being.linelen)+"\t"+z for z in docsplit[1:]) # else: # doc = docsplit[0] y = describe_func ( attr ) if not y : y = "" else : y = ", " . join ( a + "=" + str ( b ) for ( a , b ) in y ) print makeminlength ( "." + x + "(" + y + ")" , being . linelen ) , "\t" , doc if showall : print | Show this object s attributes and methods . | 395 | 8 |
24,010 | def makeBubbleChart ( self , posdict , name , stattup = None ) : xname = [ x for x in name . split ( "." ) if x . startswith ( "X_" ) ] [ 0 ] yname = [ x for x in name . split ( "." ) if x . startswith ( "Y_" ) ] [ 0 ] #elsename=name.replace(xname,'').replace(yname,'').replace('..','.').replace('..','.') o = '<div id="' + name + '"><h2>' + name + '</h2>' if stattup : cc = stattup [ 0 ] p = stattup [ 1 ] o += '<h3>corr.coef=' + str ( cc ) + ' / p-value=' + str ( p ) + '</h3>' o += '<br/><script type="text/javascript">\nvar myChart = new Chart.Bubble("' + name + '", {\nwidth: 400,\nheight: 400,\n bubbleSize: 10,\nxlabel:"' + xname + '",\nylabel:"' + yname + '"});\n' for posnum , xydict in posdict . items ( ) : x_avg , x_std = mean_stdev ( xydict [ 'x' ] ) y_avg , y_std = mean_stdev ( xydict [ 'y' ] ) z = 1 / ( x_std + y_std ) o += 'myChart.addBubble(' + str ( x_avg * 100 ) + ', ' + str ( y_avg * 100 ) + ', ' + str ( z ) + ', "#666", "' + str ( posnum + 1 ) + ' [%' + str ( x_avg * 100 ) [ 0 : 5 ] + ', %' + str ( y_avg * 100 ) [ 0 : 5 ] + ']");\n' o += 'myChart.redraw();\n</script>\n</div>' return o | Returns HTML for a bubble chart of the positin dictionary . | 475 | 12 |
24,011 | def getName ( self ) : name = self . findattr ( 'name' ) if not name : name = "_directinput_" if self . classname ( ) . lower ( ) == "line" : name += "." + str ( self ) . replace ( " " , "_" ) . lower ( ) else : name = name . replace ( '.txt' , '' ) while name . startswith ( "." ) : name = name [ 1 : ] return name | Return a Name string for this object . | 101 | 8 |
24,012 | def scansion_prepare ( self , meter = None , conscious = False ) : import prosodic config = prosodic . config if not meter : if not hasattr ( self , '_Text__bestparses' ) : return x = getattr ( self , '_Text__bestparses' ) if not x . keys ( ) : return meter = x . keys ( ) [ 0 ] ckeys = "\t" . join ( sorted ( [ str ( x ) for x in meter . constraints ] ) ) self . om ( "\t" . join ( [ makeminlength ( str ( "text" ) , config [ 'linelen' ] ) , makeminlength ( str ( "parse" ) , config [ 'linelen' ] ) , "meter" , "num_parses" , "num_viols" , "score_viols" , ckeys ] ) , conscious = conscious ) | Print out header column for line - scansions for a given meter . | 199 | 14 |
24,013 | def report ( self , meter = None , include_bounded = False , reverse = True ) : ReportStr = '' if not meter : from Meter import Meter meter = Meter . genDefault ( ) if ( hasattr ( self , 'allParses' ) ) : self . om ( unicode ( self ) ) allparses = self . allParses ( meter = meter , include_bounded = include_bounded ) numallparses = len ( allparses ) #allparses = reversed(allparses) if reverse else allparses for pi , parseList in enumerate ( allparses ) : line = self . iparse2line ( pi ) . txt #parseList.sort(key = lambda P: P.score()) hdr = "\n\n" + '=' * 30 + '\n[line #' + str ( pi + 1 ) + ' of ' + str ( numallparses ) + ']: ' + line + '\n\n\t' ftr = '=' * 30 + '\n' ReportStr += self . om ( hdr + meter . printParses ( parseList , reverse = reverse ) . replace ( '\n' , '\n\t' ) [ : - 1 ] + ftr , conscious = False ) else : for child in self . children : if type ( child ) == type ( [ ] ) : continue ReportStr += child . report ( ) return ReportStr | Print all parses and their violations in a structured format . | 323 | 12 |
24,014 | def tree ( self , offset = 0 , prefix_inherited = "" , nofeatsplease = [ 'Phoneme' ] ) : tree = "" numchild = 0 for child in self . children : if type ( child ) == type ( [ ] ) : child = child [ 0 ] numchild += 1 classname = child . classname ( ) if classname == "Word" : tree += "\n\n" elif classname == "Line" : tree += "\n\n\n" elif classname == "Stanza" : tree += "\n\n\n\n" if offset != 0 : tree += "\n" for i in range ( 0 , offset ) : tree += " " #if not len(child.feats): # tree+=" " tree += "|" tree += "\n" newline = "" for i in range ( 0 , offset ) : newline += " " newline += "|" cname = "" for letter in classname : if letter == letter . upper ( ) : cname += letter prefix = prefix_inherited + cname + str ( numchild ) + "." newline += "-----| (" + prefix [ : - 1 ] + ") <" + classname + ">" if child . isBroken ( ) : newline += "<<broken>>" else : string = self . u2s ( child ) if ( not "<" in string ) : newline = makeminlength ( newline , 99 ) newline += "[" + string + "]" elif string [ 0 ] != "<" : newline += "\t" + string if len ( child . feats ) : if ( not child . classname ( ) in nofeatsplease ) : for k , v in sorted ( child . feats . items ( ) ) : if v == None : continue newline += "\n" for i in range ( 0 , offset + 1 ) : newline += " " newline += "| " newline += self . showFeat ( k , v ) tree += newline tree += child . tree ( offset + 1 , prefix ) return tree | Print a tree - structure of this object s phonological representation . | 455 | 13 |
24,015 | def search ( self , searchTerm ) : if type ( searchTerm ) == type ( '' ) : searchTerm = SearchTerm ( searchTerm ) if searchTerm not in self . featpaths : matches = None if searchTerm . type != None and searchTerm . type != self . classname ( ) : matches = self . _searchInChildren ( searchTerm ) elif searchTerm . isAtomic ( ) : matches = self . _searchSingleTerm ( searchTerm ) else : matches = self . _searchMultipleTerms ( searchTerm ) if matches == True : matches = [ self ] if matches == False : matches = [ ] self . featpaths [ searchTerm ] = matches return self . featpaths [ searchTerm ] | Returns objects matching the query . | 154 | 6 |
24,016 | def stats_positions ( self , meter = None , all_parses = False ) : """Positions All feats of slots All constraint violations """ parses = self . allParses ( meter = meter ) if all_parses else [ [ parse ] for parse in self . bestParses ( meter = meter ) ] dx = { } for parselist in parses : for parse in parselist : if not parse : continue slot_i = 0 for pos in parse . positions : for slot in pos . slots : slot_i += 1 feat_dicts = [ slot . feats , pos . constraintScores , pos . feats ] for feat_dict in feat_dicts : for k , v in feat_dict . items ( ) : dk = ( slot_i , str ( k ) ) if not dk in dx : dx [ dk ] = [ ] dx [ dk ] += [ v ] def _writegen ( ) : for ( ( slot_i , k ) , l ) in sorted ( dx . items ( ) ) : l2 = [ ] for x in l : if type ( x ) == bool : x = 1 if x else 0 elif type ( x ) == type ( None ) : x = 0 elif type ( x ) in [ str , unicode ] : continue else : x = float ( x ) if x > 1 : x = 1 l2 += [ x ] #print k, l2 #try: if not l2 : continue avg = sum ( l2 ) / float ( len ( l2 ) ) count = sum ( l2 ) chances = len ( l2 ) #except TypeError: # continue odx = { 'slot_num' : slot_i , 'statistic' : k , 'average' : avg , 'count' : count , 'chances' : chances , 'text' : self . name } odx [ 'header' ] = [ 'slot_num' , 'statistic' , 'count' , 'chances' , 'average' ] #print odx yield odx name = self . name . replace ( '.txt' , '' ) ofn = os . path . join ( self . dir_results , 'stats' , 'texts' , name , name + '.positions.csv' ) #print ofn if not os . path . exists ( os . path . split ( ofn ) [ 0 ] ) : os . makedirs ( os . path . split ( ofn ) [ 0 ] ) for dx in writegengen ( ofn , _writegen ) : yield dx print '>> saved:' , ofn | Produce statistics from the parser | 566 | 6 |
24,017 | def iparse ( self , meter = None , num_processes = 1 , arbiter = 'Line' , line_lim = None ) : from Meter import Meter , genDefault , parse_ent , parse_ent_mp import multiprocessing as mp meter = self . get_meter ( meter ) # set internal attributes self . __parses [ meter . id ] = [ ] self . __bestparses [ meter . id ] = [ ] self . __boundParses [ meter . id ] = [ ] self . __parsed_ents [ meter . id ] = [ ] lines = self . lines ( ) lines = lines [ : line_lim ] numlines = len ( lines ) init = self ents = self . ents ( arbiter ) smax = self . config . get ( 'line_maxsylls' , 100 ) smin = self . config . get ( 'line_minsylls' , 0 ) #print '>> # of lines to parse:',len(ents) ents = [ e for e in ents if e . num_syll >= smin and e . num_syll <= smax ] #print '>> # of lines to parse after applying min/max line settings:',len(ents) self . scansion_prepare ( meter = meter , conscious = True ) numents = len ( ents ) #pool=mp.Pool(1) toprint = self . config [ 'print_to_screen' ] objects = [ ( ent , meter , init , False ) for ent in ents ] if num_processes > 1 : print '!! MULTIPROCESSING PARSING IS NOT WORKING YET !!' pool = mp . Pool ( num_processes ) jobs = [ pool . apply_async ( parse_ent_mp , ( x , ) ) for x in objects ] for j in jobs : print j . get ( ) yield j . get ( ) else : now = time . time ( ) clock_snum = 0 #for ei,ent in enumerate(pool.imap(parse_ent_mp,objects)): for ei , objectx in enumerate ( objects ) : clock_snum += ent . num_syll if ei and not ei % 100 : nownow = time . time ( ) if self . config [ 'print_to_screen' ] : print '>> parsing line #' , ei , 'of' , numents , 'lines' , '[' , round ( float ( clock_snum / ( nownow - now ) ) , 2 ) , 'syllables/second' , ']' now = nownow clock_snum = 0 yield parse_ent_mp ( objectx ) if self . config [ 'print_to_screen' ] : print '>> parsing complete in:' , time . time ( ) - now , 'seconds' | Parse this text metrically yielding it line by line . | 628 | 13 |
24,018 | def scansion ( self , meter = None , conscious = False ) : meter = self . get_meter ( meter ) self . scansion_prepare ( meter = meter , conscious = conscious ) for line in self . lines ( ) : try : line . scansion ( meter = meter , conscious = conscious ) except AttributeError : print "!!! Line skipped [Unknown word]:" print line print line . words ( ) print | Print out the parses and their violations in scansion format . | 89 | 13 |
24,019 | def allParses ( self , meter = None , include_bounded = False , one_per_meter = True ) : meter = self . get_meter ( meter ) try : parses = self . __parses [ meter . id ] if one_per_meter : toreturn = [ ] for _parses in parses : sofar = set ( ) _parses2 = [ ] for _p in _parses : _pm = _p . str_meter ( ) if not _pm in sofar : sofar |= { _pm } if _p . isBounded and _p . boundedBy . str_meter ( ) == _pm : pass else : _parses2 += [ _p ] toreturn += [ _parses2 ] parses = toreturn if include_bounded : boundedParses = self . boundParses ( meter ) return [ bp + boundp for bp , boundp in zip ( toreturn , boundedParses ) ] else : return parses except ( KeyError , IndexError ) as e : return [ ] | Return a list of lists of parses . | 240 | 9 |
24,020 | def validlines ( self ) : return [ ln for ln in self . lines ( ) if ( not ln . isBroken ( ) and not ln . ignoreMe ) ] | Return all lines within which Prosodic understood all words . | 40 | 11 |
24,021 | def choices ( self ) : choice_list = getattr ( settings , 'MARKUP_CHOICES' , DEFAULT_MARKUP_CHOICES ) return [ ( f , self . _get_filter_title ( f ) ) for f in choice_list ] | Returns the filter list as a tuple . Useful for model choices . | 58 | 13 |
24,022 | def unregister ( self , filter_name ) : if filter_name in self . filter_list : self . filter_list . pop ( filter_name ) | Unregister a filter from the filter list | 34 | 8 |
24,023 | def convert ( cls , tree ) : if isinstance ( tree , Tree ) : children = [ cls . convert ( child ) for child in tree ] if isinstance ( tree , MetricalTree ) : return cls ( tree . _cat , children , tree . _dep , tree . _lstress ) elif isinstance ( tree , DependencyTree ) : return cls ( tree . _cat , children , tree . _dep ) else : return cls ( tree . _label , children ) else : return tree | Convert a tree between different subtypes of Tree . cls determines which class will be used to encode the new tree . | 111 | 25 |
24,024 | def raw ( self , raw ) : if raw is None : raise ValueError ( "Invalid value for `raw`, must not be `None`" ) # noqa: E501 if raw is not None and not re . search ( r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$' , raw ) : # noqa: E501 raise ValueError ( r"Invalid value for `raw`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`" ) # noqa: E501 self . _raw = raw | Sets the raw of this RuntimeRawExtension . | 218 | 11 |
24,025 | def unmarshal_event ( self , data : str , response_type ) : js = json . loads ( data ) # Make a copy of the original object and save it under the # `raw_object` key because we will replace the data under `object` with # a Python native type shortly. js [ 'raw_object' ] = js [ 'object' ] # Something went wrong. A typical example would be that the user # supplied a resource version that was too old. In that case K8s would # not send a conventional ADDED/DELETED/... event but an error. Turn # this error into a Python exception to save the user the hassle. if js [ 'type' ] . lower ( ) == 'error' : return js # If possible, compile the JSON response into a Python native response # type, eg `V1Namespace` or `V1Pod`,`ExtensionsV1beta1Deployment`, ... if response_type is not None : js [ 'object' ] = self . _api_client . deserialize ( response = SimpleNamespace ( data = json . dumps ( js [ 'raw_object' ] ) ) , response_type = response_type ) # decode and save resource_version to continue watching if hasattr ( js [ 'object' ] , 'metadata' ) : self . resource_version = js [ 'object' ] . metadata . resource_version # For custom objects that we don't have model defined, json # deserialization results in dictionary elif ( isinstance ( js [ 'object' ] , dict ) and 'metadata' in js [ 'object' ] and 'resourceVersion' in js [ 'object' ] [ 'metadata' ] ) : self . resource_version = js [ 'object' ] [ 'metadata' ] [ 'resourceVersion' ] return js | Return the K8s response data in JSON format . | 391 | 11 |
24,026 | def stream ( self , func , * args , * * kwargs ) : self . close ( ) self . _stop = False self . return_type = self . get_return_type ( func ) kwargs [ 'watch' ] = True kwargs [ '_preload_content' ] = False self . func = partial ( func , * args , * * kwargs ) return self | Watch an API resource and stream the result back via a generator . | 87 | 13 |
24,027 | def getheader ( self , name , default = None ) : return self . aiohttp_response . headers . get ( name , default ) | Returns a given response header . | 30 | 6 |
24,028 | def authentication_required ( req , resp , resource , uri_kwargs ) : if 'user' not in req . context : args = [ "Unauthorized" , "This resource requires authentication" ] # compat: falcon >= 1.0.0 requires the list of challenges if FALCON_VERSION >= ( 1 , 0 , 0 ) : args . append ( req . context . get ( 'challenges' , [ ] ) ) raise HTTPUnauthorized ( * args ) | Ensure that user is authenticated otherwise return 401 Unauthorized . | 106 | 12 |
24,029 | def describe ( self , * * kwargs ) : description = { 'label' : self . label , 'details' : inspect . cleandoc ( self . details ) , 'type' : "list of {}" . format ( self . type ) if self . many else self . type , 'spec' : self . spec , 'read_only' : self . read_only , 'write_only' : self . write_only , 'allow_null' : self . allow_null , } description . update ( kwargs ) return description | Describe this field instance for purpose of self - documentation . | 118 | 12 |
24,030 | def from_representation ( self , data ) : if data in self . _TRUE_VALUES : return True elif data in self . _FALSE_VALUES : return False else : raise ValueError ( "{type} type value must be one of {values}" . format ( type = self . type , values = self . _TRUE_VALUES . union ( self . _FALSE_VALUES ) ) ) | Convert representation value to bool if it has expected form . | 91 | 12 |
24,031 | def _get_fields ( mcs , bases , namespace ) : fields = [ ( name , namespace . pop ( name ) ) for name , attribute in list ( namespace . items ( ) ) if isinstance ( attribute , BaseField ) ] for base in reversed ( bases ) : if hasattr ( base , mcs . _fields_storage_key ) : fields = list ( getattr ( base , mcs . _fields_storage_key ) . items ( ) ) + fields return OrderedDict ( fields ) | Create fields dictionary to be used in resource class namespace . | 109 | 11 |
24,032 | def to_representation ( self , obj ) : representation = { } for name , field in self . fields . items ( ) : if field . write_only : continue # note fields do not know their names in source representation # but may know what attribute they target from source object attribute = self . get_attribute ( obj , field . source or name ) if attribute is None : # Skip none attributes so fields do not have to deal with them representation [ name ] = [ ] if field . many else None elif field . many : representation [ name ] = [ field . to_representation ( item ) for item in attribute ] else : representation [ name ] = field . to_representation ( attribute ) return representation | Convert given internal object instance into representation dict . | 149 | 10 |
24,033 | def from_representation ( self , representation ) : object_dict = { } failed = { } for name , field in self . fields . items ( ) : if name not in representation : continue try : if ( # note: we cannot check for any sequence or iterable # because of strings and nested dicts. not isinstance ( representation [ name ] , ( list , tuple ) ) and field . many ) : raise ValueError ( "field should be sequence" ) source = _source ( name , field ) value = representation [ name ] if field . many : if not field . allow_null : object_dict [ source ] = [ field . from_representation ( single_value ) for single_value in value ] else : object_dict [ source ] = [ field . from_representation ( single_value ) if single_value is not None else None for single_value in value ] else : if not field . allow_null : object_dict [ source ] = field . from_representation ( value ) else : object_dict [ source ] = field . from_representation ( value ) if value else None except ValueError as err : failed [ name ] = str ( err ) if failed : # if failed to parse we eagerly perform validation so full # information about what is wrong will be returned try : self . validate ( object_dict ) # note: this exception can be reached with partial==True # since do not support partial updates yet this has 'no cover' raise DeserializationError ( ) # pragma: no cover except DeserializationError as err : err . failed = failed raise return object_dict | Convert given representation dict into internal object . | 342 | 9 |
24,034 | def get_attribute ( self , obj , attr ) : # '*' is a special wildcard character that means whole object # is passed if attr == '*' : return obj # if this is any mapping then instead of attributes use keys if isinstance ( obj , Mapping ) : return obj . get ( attr , None ) return getattr ( obj , attr , None ) | Get attribute of given object instance . | 83 | 7 |
24,035 | def set_attribute ( self , obj , attr , value ) : # if this is any mutable mapping then instead of attributes use keys if isinstance ( obj , MutableMapping ) : obj [ attr ] = value else : setattr ( obj , attr , value ) | Set value of attribute in given object instance . | 60 | 9 |
24,036 | def describe ( self ) : return OrderedDict ( [ ( name , field . describe ( ) ) for name , field in self . fields . items ( ) ] ) | Describe all serialized fields . | 36 | 7 |
24,037 | def _join_host_port ( host , port ) : template = "%s:%s" host_requires_bracketing = ':' in host or '%' in host if host_requires_bracketing : template = "[%s]:%s" return template % ( host , port ) | Adapted golang s net . JoinHostPort | 65 | 10 |
24,038 | def handle ( self , handler , req , resp , * * kwargs ) : params = self . require_params ( req ) # future: remove in 1.x if getattr ( self , '_with_context' , False ) : handler = partial ( handler , context = req . context ) meta , content = self . require_meta_and_content ( handler , params , * * kwargs ) self . make_body ( resp , params , meta , content ) return content | Handle given resource manipulation flow in consistent manner . | 104 | 9 |
24,039 | def on_get ( self , req , resp , handler = None , * * kwargs ) : self . handle ( handler or self . retrieve , req , resp , * * kwargs ) | Respond on GET HTTP request assuming resource retrieval flow . | 42 | 11 |
24,040 | def on_get ( self , req , resp , handler = None , * * kwargs ) : self . handle ( handler or self . list , req , resp , * * kwargs ) | Respond on GET HTTP request assuming resource list retrieval flow . | 42 | 12 |
24,041 | def on_delete ( self , req , resp , handler = None , * * kwargs ) : self . handle ( handler or self . delete , req , resp , * * kwargs ) resp . status = falcon . HTTP_ACCEPTED | Respond on DELETE HTTP request assuming resource deletion flow . | 54 | 13 |
24,042 | def on_put ( self , req , resp , handler = None , * * kwargs ) : self . handle ( handler or self . update , req , resp , * * kwargs ) resp . status = falcon . HTTP_ACCEPTED | Respond on PUT HTTP request assuming resource update flow . | 54 | 12 |
24,043 | def add_pagination_meta ( self , params , meta ) : meta [ 'page_size' ] = params [ 'page_size' ] meta [ 'page' ] = params [ 'page' ] meta [ 'prev' ] = "page={0}&page_size={1}" . format ( params [ 'page' ] - 1 , params [ 'page_size' ] ) if meta [ 'page' ] > 0 else None meta [ 'next' ] = "page={0}&page_size={1}" . format ( params [ 'page' ] + 1 , params [ 'page_size' ] ) if meta . get ( 'has_more' , True ) else None | Extend default meta dictionary value with pagination hints . | 152 | 11 |
24,044 | def _get_params ( mcs , bases , namespace ) : params = [ ( name , namespace . pop ( name ) ) for name , attribute in list ( namespace . items ( ) ) if isinstance ( attribute , BaseParam ) ] for base in reversed ( bases ) : if hasattr ( base , mcs . _params_storage_key ) : params = list ( getattr ( base , mcs . _params_storage_key ) . items ( ) ) + params return OrderedDict ( params ) | Create params dictionary to be used in resource class namespace . | 109 | 11 |
24,045 | def make_body ( self , resp , params , meta , content ) : response = { 'meta' : meta , 'content' : content } resp . content_type = 'application/json' resp . body = json . dumps ( response , indent = params [ 'indent' ] or None if 'indent' in params else None ) | Construct response body in resp object using JSON serialization . | 73 | 11 |
24,046 | def allowed_methods ( self ) : return [ method for method , allowed in ( ( 'GET' , hasattr ( self , 'on_get' ) ) , ( 'POST' , hasattr ( self , 'on_post' ) ) , ( 'PUT' , hasattr ( self , 'on_put' ) ) , ( 'PATCH' , hasattr ( self , 'on_patch' ) ) , ( 'DELETE' , hasattr ( self , 'on_delete' ) ) , ( 'HEAD' , hasattr ( self , 'on_head' ) ) , ( 'OPTIONS' , hasattr ( self , 'on_options' ) ) , ) if allowed ] | Return list of allowed HTTP methods on this resource . | 153 | 10 |
24,047 | def describe ( self , req = None , resp = None , * * kwargs ) : description = { 'params' : OrderedDict ( [ ( name , param . describe ( ) ) for name , param in self . params . items ( ) ] ) , 'details' : inspect . cleandoc ( self . __class__ . __doc__ or "This resource does not have description yet" ) , 'name' : self . __class__ . __name__ , 'methods' : self . allowed_methods ( ) } # note: add path to resource description only if request object was # provided in order to make auto-documentation engines simpler if req : description [ 'path' ] = req . path description . update ( * * kwargs ) return description | Describe API resource using resource introspection . | 166 | 9 |
24,048 | def on_options ( self , req , resp , * * kwargs ) : resp . set_header ( 'Allow' , ', ' . join ( self . allowed_methods ( ) ) ) resp . body = json . dumps ( self . describe ( req , resp ) ) resp . content_type = 'application/json' | Respond with JSON formatted resource description on OPTIONS request . | 71 | 12 |
24,049 | def require_params ( self , req ) : params = { } for name , param in self . params . items ( ) : if name not in req . params and param . required : # we could simply raise with this single param or use get_param # with required=True parameter but for client convenience # we prefer to list all missing params that are required missing = set ( p for p in self . params if self . params [ p ] . required ) - set ( req . params . keys ( ) ) raise errors . HTTPMissingParam ( ", " . join ( missing ) ) elif name in req . params or param . default : # Note: lack of key in req.params means it was not specified # so unless there is default value it will not be included in # output params dict. # This way we have explicit information that param was # not specified. Using None would not be as good because param # class can also return None from `.value()` method as a valid # translated value. try : if param . many : # params with "many" enabled need special care values = req . get_param_as_list ( # note: falcon allows to pass value handler using # `transform` param so we do not need to # iterate through list manually name , param . validated_value ) or [ param . default and param . validated_value ( param . default ) ] params [ name ] = param . container ( values ) else : # note that if many==False and query parameter # occurs multiple times in qs then it is # **unspecified** which one will be used. See: # http://falcon.readthedocs.org/en/latest/api/request_and_response.html#falcon.Request.get_param # noqa params [ name ] = param . validated_value ( req . get_param ( name , default = param . default ) ) except ValidationError as err : # ValidationError allows to easily translate itself to # to falcon's HTTPInvalidParam (Bad Request HTTP response) raise err . as_invalid_param ( name ) except ValueError as err : # Other parsing issues are expected to raise ValueError raise errors . HTTPInvalidParam ( str ( err ) , name ) return params | Require all defined parameters from request query string . | 480 | 10 |
24,050 | def require_meta_and_content ( self , content_handler , params , * * kwargs ) : meta = { 'params' : params } content = content_handler ( params , meta , * * kwargs ) meta [ 'params' ] = params return meta , content | Require meta and content dictionaries using proper hander . | 61 | 12 |
24,051 | def require_representation ( self , req ) : try : type_ , subtype , _ = parse_mime_type ( req . content_type ) content_type = '/' . join ( ( type_ , subtype ) ) except : raise falcon . HTTPUnsupportedMediaType ( description = "Invalid Content-Type header: {}" . format ( req . content_type ) ) if content_type == 'application/json' : body = req . stream . read ( ) return json . loads ( body . decode ( 'utf-8' ) ) else : raise falcon . HTTPUnsupportedMediaType ( description = "only JSON supported, got: {}" . format ( content_type ) ) | Require raw representation dictionary from falcon request object . | 151 | 11 |
24,052 | def require_validated ( self , req , partial = False , bulk = False ) : representations = [ self . require_representation ( req ) ] if not bulk else self . require_representation ( req ) if bulk and not isinstance ( representations , list ) : raise ValidationError ( "Request payload should represent a list of resources." ) . as_bad_request ( ) object_dicts = [ ] try : for representation in representations : object_dict = self . serializer . from_representation ( representation ) self . serializer . validate ( object_dict , partial ) object_dicts . append ( object_dict ) except DeserializationError as err : # when working on Resource we know that we can finally raise # bad request exceptions raise err . as_bad_request ( ) except ValidationError as err : # ValidationError is a suggested way to validate whole resource # so we also are prepared to catch it raise err . as_bad_request ( ) return object_dicts if bulk else object_dicts [ 0 ] | Require fully validated internal object dictionary . | 222 | 8 |
24,053 | def ca_bundle ( self , ca_bundle ) : if ca_bundle is not None and not re . search ( r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$' , ca_bundle ) : # noqa: E501 raise ValueError ( r"Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`" ) # noqa: E501 self . _ca_bundle = ca_bundle | Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig . | 209 | 21 |
24,054 | def certificate ( self , certificate ) : if certificate is not None and not re . search ( r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$' , certificate ) : # noqa: E501 raise ValueError ( r"Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`" ) # noqa: E501 self . _certificate = certificate | Sets the certificate of this V1beta1CertificateSigningRequestStatus . | 190 | 17 |
24,055 | def describe ( self , req = None , resp = None , * * kwargs ) : return super ( ) . describe ( req , resp , type = 'list' , fields = self . serializer . describe ( ) if self . serializer else None , * * kwargs ) | Extend default endpoint description with serializer description . | 61 | 10 |
24,056 | def get_user ( self , identified_with , identifier , req , resp , resource , uri_kwargs ) : return self . user | Return default user object . | 30 | 5 |
24,057 | def _get_storage_key ( self , identified_with , identifier ) : return ':' . join ( ( self . key_prefix , identified_with . name , self . hash_identifier ( identified_with , identifier ) , ) ) | Get key string for given user identifier in consistent manner . | 52 | 11 |
24,058 | def get_user ( self , identified_with , identifier , req , resp , resource , uri_kwargs ) : stored_value = self . kv_store . get ( self . _get_storage_key ( identified_with , identifier ) ) if stored_value is not None : user = self . serialization . loads ( stored_value . decode ( ) ) else : user = None return user | Get user object for given identifier . | 87 | 7 |
24,059 | def register ( self , identified_with , identifier , user ) : self . kv_store . set ( self . _get_storage_key ( identified_with , identifier ) , self . serialization . dumps ( user ) . encode ( ) , ) | Register new key for given client identifier . | 54 | 8 |
24,060 | def process_resource ( self , req , resp , resource , uri_kwargs = None ) : if 'user' in req . context : return identifier = self . identify ( req , resp , resource , uri_kwargs ) user = self . try_storage ( identifier , req , resp , resource , uri_kwargs ) if user is not None : req . context [ 'user' ] = user # if did not succeed then we need to add this to list of available # challenges. elif self . challenge is not None : req . context . setdefault ( 'challenges' , list ( ) ) . append ( self . challenge ) | Process resource after routing to it . | 138 | 7 |
24,061 | def try_storage ( self , identifier , req , resp , resource , uri_kwargs ) : if identifier is None : user = None # note: if user_storage is defined, always use it in order to # authenticate user. elif self . user_storage is not None : user = self . user_storage . get_user ( self , identifier , req , resp , resource , uri_kwargs ) # note: some authentication middleware classes may not require # to be initialized with their own user_storage. In such # case this will always authenticate with "syntetic user" # if there is a valid indentity. elif self . user_storage is None and not self . only_with_storage : user = { 'identified_with' : self , 'identifier' : identifier } else : # pragma: nocover # note: this should not happen if the base class is properly # initialized. Still, user can skip super().__init__() call. user = None return user | Try to find user in configured user storage object . | 217 | 10 |
24,062 | def identify ( self , req , resp , resource , uri_kwargs ) : 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" "Authorization: Basic <base64-user-pass>" ) user_pass = auth [ 1 ] try : decoded = base64 . b64decode ( user_pass ) . decode ( ) except ( TypeError , UnicodeDecodeError , binascii . Error ) : raise HTTPBadRequest ( "Invalid Authorization header" , "Credentials for Basic auth not correctly base64 encoded." ) username , _ , password = decoded . partition ( ":" ) return username , password | Identify user using Authenticate header with Basic auth . | 203 | 11 |
24,063 | def identify ( self , req , resp , resource , uri_kwargs ) : try : return req . get_header ( 'X-Api-Key' , True ) except ( KeyError , HTTPMissingHeader ) : pass | Initialize X - Api - Key authentication middleware . | 52 | 12 |
24,064 | def identify ( self , req , resp , resource , uri_kwargs ) : header = req . get_header ( 'Authorization' , False ) auth = header . split ( ' ' ) if header else None if auth is None or auth [ 0 ] . lower ( ) != 'token' : return None if len ( auth ) != 2 : raise HTTPBadRequest ( "Invalid Authorization header" , "The Authorization header for Token auth should be in form:\n" "Authorization: Token <token_value>" ) return auth [ 1 ] | Identify user using Authenticate header with Token auth . | 115 | 11 |
24,065 | def _get_client_address ( self , req ) : try : forwarded_for = req . get_header ( 'X-Forwarded-For' , True ) return forwarded_for . split ( ',' ) [ 0 ] . strip ( ) except ( KeyError , HTTPMissingHeader ) : return ( req . env . get ( 'REMOTE_ADDR' ) if self . remote_address_fallback else None ) | Get address from X - Forwarded - For header or use remote address . | 94 | 15 |
24,066 | def _get_description ( self ) : return ", " . join ( [ part for part in [ "missing: {}" . format ( self . missing ) if self . missing else "" , ( "forbidden: {}" . format ( self . forbidden ) if self . forbidden else "" ) , "invalid: {}:" . format ( self . invalid ) if self . invalid else "" , ( "failed to parse: {}" . format ( self . failed ) if self . failed else "" ) ] if part ] ) | Return human readable description error description . | 109 | 7 |
24,067 | async def load_kube_config ( config_file = None , context = None , client_configuration = None , persist_config = True ) : if config_file is None : config_file = KUBE_CONFIG_DEFAULT_LOCATION loader = _get_kube_config_loader_for_yaml_file ( config_file , active_context = context , persist_config = persist_config ) if client_configuration is None : config = type . __call__ ( Configuration ) await loader . load_and_set ( config ) Configuration . set_default ( config ) else : await loader . load_and_set ( client_configuration ) return loader | Loads authentication and cluster information from kube - config file and stores them in kubernetes . client . configuration . | 149 | 25 |
24,068 | async def refresh_token ( loader , client_configuration = None , interval = 60 ) : if loader . provider != 'gcp' : return if client_configuration is None : client_configuration = Configuration ( ) while 1 : await asyncio . sleep ( interval ) await loader . load_gcp_token ( ) client_configuration . api_key [ 'authorization' ] = loader . token | Refresh token if necessary updates the token in client configurarion | 88 | 14 |
24,069 | async def new_client_from_config ( config_file = None , context = None , persist_config = True ) : client_config = type . __call__ ( Configuration ) await load_kube_config ( config_file = config_file , context = context , client_configuration = client_config , persist_config = persist_config ) return ApiClient ( configuration = client_config ) | Loads configuration the same as load_kube_config but returns an ApiClient to be used with any API object . This will allow the caller to concurrently talk with multiple clusters . | 88 | 38 |
24,070 | async def _load_authentication ( self ) : if not self . _user : logging . debug ( 'No user section in current context.' ) return if self . provider == 'gcp' : await self . load_gcp_token ( ) return if self . provider == PROVIDER_TYPE_OIDC : await self . _load_oid_token ( ) return if 'exec' in self . _user : logging . debug ( 'Try to use exec provider' ) res_exec_plugin = await self . _load_from_exec_plugin ( ) if res_exec_plugin : return logging . debug ( 'Try to load user token' ) if self . _load_user_token ( ) : return logging . debug ( 'Try to use username and password' ) self . _load_user_pass_token ( ) | Read authentication from kube - config user section if exists . | 180 | 12 |
24,071 | def min_validator ( min_value ) : def validator ( value ) : if value < min_value : raise ValidationError ( "{} is not >= {}" . format ( value , min_value ) ) return validator | Return validator function that ensures lower bound of a number . | 50 | 12 |
24,072 | def max_validator ( max_value ) : def validator ( value ) : if value > max_value : raise ValidationError ( "{} is not <= {}" . format ( value , max_value ) ) return validator | Return validator function that ensures upper bound of a number . | 50 | 12 |
24,073 | def choices_validator ( choices ) : def validator ( value ) : if value not in choices : # note: make it a list for consistent representation raise ValidationError ( "{} is not in {}" . format ( value , list ( choices ) ) ) return validator | Return validator function that will check if value in choices . | 58 | 12 |
24,074 | def match_validator ( expression ) : if isinstance ( expression , str ) : compiled = re . compile ( expression ) elif hasattr ( expression , 'match' ) : # check it early so we could say something is wrong early compiled = expression else : raise TypeError ( 'Provided match is nor a string nor has a match method ' '(like re expressions)' ) def validator ( value ) : if not compiled . match ( value ) : # note: make it a list for consistent representation raise ValidationError ( "{} does not match pattern: {}" . format ( value , compiled . pattern if hasattr ( compiled , 'pattern' ) else compiled ) ) return validator | Return validator function that will check if matches given expression . | 144 | 12 |
24,075 | def validated_value ( self , raw_value ) : value = self . value ( raw_value ) try : for validator in self . validators : validator ( value ) except : raise else : return value | Return parsed parameter value and run validation handlers . | 45 | 9 |
24,076 | def describe ( self , * * kwargs ) : description = { 'label' : self . label , # note: details are expected to be large so it should # be reformatted 'details' : inspect . cleandoc ( self . details ) , 'required' : self . required , 'many' : self . many , 'spec' : self . spec , 'default' : self . default , 'type' : self . type or 'unspecified' } description . update ( kwargs ) return description | Describe this parameter instance for purpose of self - documentation . | 109 | 12 |
24,077 | def value ( self , raw_value ) : try : return base64 . b64decode ( bytes ( raw_value , 'utf-8' ) ) . decode ( 'utf-8' ) except binascii . Error as err : raise ValueError ( str ( err ) ) | Decode param with Base64 . | 62 | 7 |
24,078 | def value ( self , raw_value ) : try : return decimal . Decimal ( raw_value ) except decimal . InvalidOperation : raise ValueError ( "Could not parse '{}' value as decimal" . format ( raw_value ) ) | Decode param as decimal value . | 52 | 7 |
24,079 | def value ( self , raw_value ) : if raw_value in self . _FALSE_VALUES : return False elif raw_value in self . _TRUE_VALUES : return True else : raise ValueError ( "Could not parse '{}' value as boolean" . format ( raw_value ) ) | Decode param as bool value . | 69 | 7 |
24,080 | def request ( self , request ) : if request is None : raise ValueError ( "Invalid value for `request`, must not be `None`" ) # noqa: E501 if request is not None and not re . search ( r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$' , request ) : # noqa: E501 raise ValueError ( r"Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`" ) # noqa: E501 self . _request = request | Sets the request of this V1beta1CertificateSigningRequestSpec . | 218 | 17 |
24,081 | def project ( dataIn , projectionScript ) : # We don't really need to initialize it, but we do it to avoid linter errors dataOut = { } try : projectionScript = str ( projectionScript ) program = makeProgramFromString ( projectionScript ) if PY3 : loc = { 'dataIn' : dataIn , 'dataOut' : dataOut } exec ( program , { } , loc ) dataOut = loc [ 'dataOut' ] else : exec ( program ) except Exception as e : glogger . error ( "Error while executing SPARQL projection" ) glogger . error ( projectionScript ) glogger . error ( "Encountered exception: " ) glogger . error ( e ) dataOut = { 'status' : 'error' , 'message' : e . message } return dataOut | Programs may make use of data in the dataIn variable and should produce data on the dataOut variable . | 178 | 22 |
24,082 | def init_prov_graph ( self ) : try : # Use git2prov to get prov on the repo repo_prov = check_output ( [ 'node_modules/git2prov/bin/git2prov' , 'https://github.com/{}/{}/' . format ( self . user , self . repo ) , 'PROV-O' ] ) . decode ( "utf-8" ) repo_prov = repo_prov [ repo_prov . find ( '@' ) : ] # glogger.debug('Git2PROV output: {}'.format(repo_prov)) glogger . debug ( 'Ingesting Git2PROV output into RDF graph' ) with open ( 'temp.prov.ttl' , 'w' ) as temp_prov : temp_prov . write ( repo_prov ) self . prov_g . parse ( 'temp.prov.ttl' , format = 'turtle' ) except Exception as e : glogger . error ( e ) glogger . error ( "Couldn't parse Git2PROV graph, continuing without repo PROV" ) pass self . prov_g . add ( ( self . agent , RDF . type , self . prov . Agent ) ) self . prov_g . add ( ( self . entity_d , RDF . type , self . prov . Entity ) ) self . prov_g . add ( ( self . activity , RDF . type , self . prov . Activity ) ) # entity_d self . prov_g . add ( ( self . entity_d , self . prov . wasGeneratedBy , self . activity ) ) self . prov_g . add ( ( self . entity_d , self . prov . wasAttributedTo , self . agent ) ) # later: entity_d genereated at time (when we know the end time) # activity self . prov_g . add ( ( self . activity , self . prov . wasAssociatedWith , self . agent ) ) self . prov_g . add ( ( self . activity , self . prov . startedAtTime , Literal ( datetime . now ( ) ) ) ) | Initialize PROV graph with all we know at the start of the recording | 461 | 14 |
24,083 | def add_used_entity ( self , entity_uri ) : entity_o = URIRef ( entity_uri ) self . prov_g . add ( ( entity_o , RDF . type , self . prov . Entity ) ) self . prov_g . add ( ( self . activity , self . prov . used , entity_o ) ) | Add the provided URI as a used entity by the logged activity | 75 | 12 |
24,084 | def end_prov_graph ( self ) : endTime = Literal ( datetime . now ( ) ) self . prov_g . add ( ( self . entity_d , self . prov . generatedAtTime , endTime ) ) self . prov_g . add ( ( self . activity , self . prov . endedAtTime , endTime ) ) | Finalize prov recording with end time | 75 | 7 |
24,085 | def log_prov_graph ( self ) : glogger . debug ( "Spec generation provenance graph:" ) glogger . debug ( self . prov_g . serialize ( format = 'turtle' ) ) | Log provenance graph so far | 47 | 6 |
24,086 | def serialize ( self , format ) : if PY3 : return self . prov_g . serialize ( format = format ) . decode ( 'utf-8' ) else : return self . prov_g . serialize ( format = format ) | Serialize provenance graph in the specified format | 53 | 9 |
24,087 | def get_defaults ( rq , v , metadata ) : glogger . debug ( "Metadata with defaults: {}" . format ( metadata ) ) if 'defaults' not in metadata : return None defaultsDict = _getDictWithKey ( v , metadata [ 'defaults' ] ) if defaultsDict : return defaultsDict [ v ] return None | Returns the default value for a parameter or None | 80 | 9 |
24,088 | def fetchFiles ( self ) : print ( "Fetching files from {}" . format ( self . baseDir ) ) files = glob ( path . join ( self . baseDir , '*' ) ) filesDef = [ ] for f in files : print ( "Found SPARQL file {}" . format ( f ) ) relative = f . replace ( self . baseDir , '' ) filesDef . append ( { 'download_url' : relative , 'name' : relative } ) return filesDef | Returns a list of file items contained on the local repo . | 107 | 12 |
24,089 | def get_repo_info ( loader , sha , prov_g ) : user_repo = loader . getFullName ( ) repo_title = loader . getRepoTitle ( ) contact_name = loader . getContactName ( ) contact_url = loader . getContactUrl ( ) commit_list = loader . getCommitList ( ) licence_url = loader . getLicenceURL ( ) # Add the API URI as a used entity by the activity if prov_g : prov_g . add_used_entity ( loader . getRepoURI ( ) ) prev_commit = None next_commit = None version = sha if sha else commit_list [ 0 ] if commit_list . index ( version ) < len ( commit_list ) - 1 : prev_commit = commit_list [ commit_list . index ( version ) + 1 ] if commit_list . index ( version ) > 0 : next_commit = commit_list [ commit_list . index ( version ) - 1 ] info = { 'version' : version , 'title' : repo_title , 'contact' : { 'name' : contact_name , 'url' : contact_url } , 'license' : { 'name' : 'License' , 'url' : licence_url } } basePath = '/api/' + user_repo + '/' basePath += ( 'commit/' + sha + '/' ) if sha else '' return prev_commit , next_commit , info , basePath | Generate swagger information from the repo being used . | 326 | 11 |
24,090 | def buildPaginationHeader ( resultCount , resultsPerPage , pageArg , url ) : lastPage = resultCount / resultsPerPage if pageArg : page = int ( pageArg ) next_url = re . sub ( "page=[0-9]+" , "page={}" . format ( page + 1 ) , url ) prev_url = re . sub ( "page=[0-9]+" , "page={}" . format ( page - 1 ) , url ) first_url = re . sub ( "page=[0-9]+" , "page=1" , url ) last_url = re . sub ( "page=[0-9]+" , "page={}" . format ( lastPage ) , url ) else : page = 1 next_url = url + "?page=2" prev_url = "" first_url = url + "?page=1" last_url = url + "?page={}" . format ( lastPage ) if page == 1 : headerLink = "<{}>; rel=next, <{}>; rel=last" . format ( next_url , last_url ) elif page == lastPage : headerLink = "<{}>; rel=prev, <{}>; rel=first" . format ( prev_url , first_url ) else : headerLink = "<{}>; rel=next, <{}>; rel=prev, <{}>; rel=first, <{}>; rel=last" . format ( next_url , prev_url , first_url , last_url ) return headerLink | Build link header for result pagination | 347 | 7 |
24,091 | def format_directive ( module , package = None ) : # type: (unicode, unicode) -> unicode directive = '.. automodule:: %s\n' % makename ( package , module ) for option in OPTIONS : directive += ' :%s:\n' % option return directive | Create the automodule directive and add the options . | 67 | 11 |
24,092 | def extract_summary ( obj ) : # type: (List[unicode], Any) -> unicode try : doc = inspect . getdoc ( obj ) . split ( "\n" ) except AttributeError : doc = '' # Skip a blank lines at the top while doc and not doc [ 0 ] . strip ( ) : doc . pop ( 0 ) # If there's a blank line, then we can assume the first sentence / # paragraph has ended, so anything after shouldn't be part of the # summary for i , piece in enumerate ( doc ) : if not piece . strip ( ) : doc = doc [ : i ] break # Try to find the "first sentence", which may span multiple lines sentences = periods_re . split ( " " . join ( doc ) ) # type: ignore if len ( sentences ) == 1 : summary = sentences [ 0 ] . strip ( ) else : summary = '' state_machine = RSTStateMachine ( state_classes , 'Body' ) while sentences : summary += sentences . pop ( 0 ) + '.' node = new_document ( '' ) node . reporter = NullReporter ( '' , 999 , 4 ) node . settings . pep_references = None node . settings . rfc_references = None state_machine . run ( [ summary ] , node ) if not node . traverse ( nodes . system_message ) : # considered as that splitting by period does not break inline # markups break return summary | Extract summary from docstring . | 308 | 7 |
24,093 | def _get_member_ref_str ( name , obj , role = 'obj' , known_refs = None ) : if known_refs is not None : if name in known_refs : return known_refs [ name ] ref = _get_fullname ( name , obj ) return ":%s:`%s <%s>`" % ( role , name , ref ) | generate a ReST - formmated reference link to the given obj of type role using name as the link text | 88 | 24 |
24,094 | def _get_mod_ns ( name , fullname , includeprivate ) : ns = { # template variables 'name' : name , 'fullname' : fullname , 'members' : [ ] , 'functions' : [ ] , 'classes' : [ ] , 'exceptions' : [ ] , 'subpackages' : [ ] , 'submodules' : [ ] , 'doc' : None } p = 0 if includeprivate : p = 1 mod = importlib . import_module ( fullname ) ns [ 'members' ] = _get_members ( mod ) [ p ] ns [ 'functions' ] = _get_members ( mod , typ = 'function' ) [ p ] ns [ 'classes' ] = _get_members ( mod , typ = 'class' ) [ p ] ns [ 'exceptions' ] = _get_members ( mod , typ = 'exception' ) [ p ] ns [ 'data' ] = _get_members ( mod , typ = 'data' ) [ p ] ns [ 'doc' ] = mod . __doc__ return ns | Return the template context of module identified by fullname as a dict | 241 | 13 |
24,095 | def get_all_for ( self , key ) : if not isinstance ( key , _string_type ) : raise TypeError ( "Key needs to be a string." ) return [ self [ ( idx , key ) ] for idx in _range ( self . __kcount [ key ] ) ] | Returns all values of the given key | 66 | 7 |
24,096 | def remove_all_for ( self , key ) : if not isinstance ( key , _string_type ) : raise TypeError ( "Key need to be a string." ) for idx in _range ( self . __kcount [ key ] ) : super ( VDFDict , self ) . __delitem__ ( ( idx , key ) ) self . __omap = list ( filter ( lambda x : x [ 1 ] != key , self . __omap ) ) del self . __kcount [ key ] | Removes all items with the given key | 113 | 8 |
24,097 | def has_duplicates ( self ) : for n in getattr ( self . __kcount , _iter_values ) ( ) : if n != 1 : return True def dict_recurse ( obj ) : for v in getattr ( obj , _iter_values ) ( ) : if isinstance ( v , VDFDict ) and v . has_duplicates ( ) : return True elif isinstance ( v , dict ) : return dict_recurse ( v ) return False return dict_recurse ( self ) | Returns True if the dict contains keys with duplicates . Recurses through any all keys with value that is VDFDict . | 114 | 26 |
24,098 | def dumps ( obj , pretty = False , escaped = True ) : if not isinstance ( obj , dict ) : raise TypeError ( "Expected data to be an instance of``dict``" ) if not isinstance ( pretty , bool ) : raise TypeError ( "Expected pretty to be of type bool" ) if not isinstance ( escaped , bool ) : raise TypeError ( "Expected escaped to be of type bool" ) return '' . join ( _dump_gen ( obj , pretty , escaped ) ) | Serialize obj to a VDF formatted str . | 109 | 10 |
24,099 | def binary_dumps ( obj , alt_format = False ) : return b'' . join ( _binary_dump_gen ( obj , alt_format = alt_format ) ) | Serialize obj to a binary VDF formatted bytes . | 39 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.