idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
222,900
def log_env ( self , level , env ) : self . log ( level , "ENVIRONMENT:" ) for k , v in env . items ( ) : self . log ( level , " {} = {}" . format ( k , pformat ( v ) ) )
dump env into debug logger in readable format
60
8
222,901
def check_configuration_tokens ( self ) : self . info ( 'Check configuration tokens' ) self . migrate_configuration_tokens ( ) get = self . config . getdefault errors = [ ] adderror = errors . append if not get ( 'app' , 'title' , '' ) : adderror ( '[app] "title" is missing' ) if not get ( 'app' , 'source.dir' , '' ) : adderror ( '[app] "source.dir" is missing' ) package_name = get ( 'app' , 'package.name' , '' ) if not package_name : adderror ( '[app] "package.name" is missing' ) elif package_name [ 0 ] in map ( str , range ( 10 ) ) : adderror ( '[app] "package.name" may not start with a number.' ) version = get ( 'app' , 'version' , '' ) version_regex = get ( 'app' , 'version.regex' , '' ) if not version and not version_regex : adderror ( '[app] One of "version" or "version.regex" must be set' ) if version and version_regex : adderror ( '[app] Conflict between "version" and "version.regex"' ', only one can be used.' ) if version_regex and not get ( 'app' , 'version.filename' , '' ) : adderror ( '[app] "version.filename" is missing' ', required by "version.regex"' ) orientation = get ( 'app' , 'orientation' , 'landscape' ) if orientation not in ( 'landscape' , 'portrait' , 'all' , 'sensorLandscape' ) : adderror ( '[app] "orientation" have an invalid value' ) if errors : self . error ( '{0} error(s) found in the buildozer.spec' . format ( len ( errors ) ) ) for error in errors : print ( error ) exit ( 1 )
Ensure the spec file is correct .
444
8
222,902
def check_application_requirements ( self ) : requirements = self . config . getlist ( 'app' , 'requirements' , '' ) target_available_packages = self . target . get_available_packages ( ) if target_available_packages is True : # target handles all packages! return # remove all the requirements that the target can compile onlyname = lambda x : x . split ( '==' ) [ 0 ] # noqa: E731 requirements = [ x for x in requirements if onlyname ( x ) not in target_available_packages ] if requirements and hasattr ( sys , 'real_prefix' ) : e = self . error e ( 'virtualenv is needed to install pure-Python modules, but' ) e ( 'virtualenv does not support nesting, and you are running' ) e ( 'buildozer in one. Please run buildozer outside of a' ) e ( 'virtualenv instead.' ) exit ( 1 ) # did we already installed the libs ? if ( exists ( self . applibs_dir ) and self . state . get ( 'cache.applibs' , '' ) == requirements ) : self . debug ( 'Application requirements already installed, pass' ) return # recreate applibs self . rmdir ( self . applibs_dir ) self . mkdir ( self . applibs_dir ) # ok now check the availability of all requirements for requirement in requirements : self . _install_application_requirement ( requirement ) # everything goes as expected, save this state! self . state [ 'cache.applibs' ] = requirements
Ensure the application requirements are all available and ready to be packaged as well .
342
16
222,903
def check_garden_requirements ( self ) : garden_requirements = self . config . getlist ( 'app' , 'garden_requirements' , '' ) # have we installed the garden packages? if exists ( self . gardenlibs_dir ) and self . state . get ( 'cache.gardenlibs' , '' ) == garden_requirements : self . debug ( 'Garden requirements already installed, pass' ) return # we're going to reinstall all the garden libs. self . rmdir ( self . gardenlibs_dir ) # but if we don't have requirements, or if the user removed everything, # don't do anything. if not garden_requirements : self . state [ 'cache.gardenlibs' ] = garden_requirements return self . _ensure_virtualenv ( ) self . cmd ( 'pip install Kivy-Garden==0.1.1' , env = self . env_venv ) # recreate gardenlibs self . mkdir ( self . gardenlibs_dir ) for requirement in garden_requirements : self . _install_garden_package ( requirement ) # save gardenlibs state self . state [ 'cache.gardenlibs' ] = garden_requirements
Ensure required garden packages are available to be included .
274
11
222,904
def cmd_init ( self , * args ) : if exists ( 'buildozer.spec' ) : print ( 'ERROR: You already have a buildozer.spec file.' ) exit ( 1 ) copyfile ( join ( dirname ( __file__ ) , 'default.spec' ) , 'buildozer.spec' ) print ( 'File buildozer.spec created, ready to customize!' )
Create a initial buildozer . spec in the current directory
88
12
222,905
def cmd_distclean ( self , * args ) : print ( "Warning: Your ndk, sdk and all other cached packages will be" " removed. Continue? (y/n)" ) if sys . stdin . readline ( ) . lower ( ) [ 0 ] == 'y' : self . info ( 'Clean the global build directory' ) if not exists ( self . global_buildozer_dir ) : return rmtree ( self . global_buildozer_dir )
Clean the whole Buildozer environment .
106
8
222,906
def cmd_serve ( self , * args ) : try : from http . server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError : from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import TCPServer os . chdir ( self . bin_dir ) handler = SimpleHTTPRequestHandler httpd = TCPServer ( ( "" , SIMPLE_HTTP_SERVER_PORT ) , handler ) print ( "Serving via HTTP at port {}" . format ( SIMPLE_HTTP_SERVER_PORT ) ) print ( "Press Ctrl+c to quit serving." ) httpd . serve_forever ( )
Serve the bin directory via SimpleHTTPServer
137
10
222,907
def cmd_xcode ( self , * args ) : app_name = self . buildozer . namify ( self . buildozer . config . get ( 'app' , 'package.name' ) ) app_name = app_name . lower ( ) ios_dir = ios_dir = join ( self . buildozer . platform_dir , 'kivy-ios' ) self . buildozer . cmd ( 'open {}.xcodeproj' . format ( app_name ) , cwd = join ( ios_dir , '{}-ios' . format ( app_name ) ) )
Open the xcode project .
139
6
222,908
def cmd_list_identities ( self , * args ) : identities = self . _get_available_identities ( ) print ( 'Available identities:' ) for x in identities : print ( ' - {}' . format ( x ) )
List the available identities to use for signing .
51
9
222,909
def _handle_generator ( self , fn ) : with self as cassette : coroutine = fn ( cassette ) # We don't need to catch StopIteration. The caller (Tornado's # gen.coroutine, for example) will handle that. to_yield = next ( coroutine ) while True : try : to_send = yield to_yield except Exception : to_yield = coroutine . throw ( * sys . exc_info ( ) ) else : try : to_yield = coroutine . send ( to_send ) except StopIteration : break
Wraps a generator so that we re inside the cassette context for the duration of the generator .
125
19
222,910
def append ( self , request , response ) : request = self . _before_record_request ( request ) if not request : return # Deepcopy is here because mutation of `response` will corrupt the # real response. response = copy . deepcopy ( response ) response = self . _before_record_response ( response ) if response is None : return self . data . append ( ( request , response ) ) self . dirty = True
Add a request response pair to this cassette
91
8
222,911
def _responses ( self , request ) : request = self . _before_record_request ( request ) for index , ( stored_request , response ) in enumerate ( self . data ) : if requests_match ( request , stored_request , self . _match_on ) : yield index , response
internal API returns an iterator with all responses matching the request .
65
12
222,912
def play_response ( self , request ) : for index , response in self . _responses ( request ) : if self . play_counts [ index ] == 0 : self . play_counts [ index ] += 1 return response # The cassette doesn't contain the request asked for. raise UnhandledHTTPRequestError ( "The cassette (%r) doesn't contain the request (%r) asked for" % ( self . _path , request ) )
Get the response corresponding to a request but only if it hasn t been played back before and mark it as played
95
22
222,913
def responses_of ( self , request ) : responses = [ response for index , response in self . _responses ( request ) ] if responses : return responses # The cassette doesn't contain the request asked for. raise UnhandledHTTPRequestError ( "The cassette (%r) doesn't contain the request (%r) asked for" % ( self . _path , request ) )
Find the responses corresponding to a request . This function isn t actually used by VCR internally but is provided as an external API .
78
26
222,914
def parse_headers ( header_list ) : header_string = b"" for key , values in header_list . items ( ) : for v in values : header_string += key . encode ( 'utf-8' ) + b":" + v . encode ( 'utf-8' ) + b"\r\n" return compat . get_httpmessage ( header_string )
Convert headers from our serialized dict with lists for keys to a HTTPMessage
82
18
222,915
def _uri ( self , url ) : if url and not url . startswith ( '/' ) : # Then this must be a proxy request. return url uri = "{0}://{1}{2}{3}" . format ( self . _protocol , self . real_connection . host , self . _port_postfix ( ) , url , ) return uri
Returns request absolute URI
81
4
222,916
def _url ( self , uri ) : prefix = "{}://{}{}" . format ( self . _protocol , self . real_connection . host , self . _port_postfix ( ) , ) return uri . replace ( prefix , '' , 1 )
Returns request selector url from absolute URI
58
7
222,917
def request ( self , method , url , body = None , headers = None , * args , * * kwargs ) : self . _vcr_request = Request ( method = method , uri = self . _uri ( url ) , body = body , headers = headers or { } ) log . debug ( 'Got {}' . format ( self . _vcr_request ) ) # Note: The request may not actually be finished at this point, so # I'm not sending the actual request until getresponse(). This # allows me to compare the entire length of the response to see if it # exists in the cassette. self . _sock = VCRFakeSocket ( )
Persist the request metadata in self . _vcr_request
144
13
222,918
def getresponse ( self , _ = False , * * kwargs ) : # Check to see if the cassette has a response for this request. If so, # then return it if self . cassette . can_play_response_for ( self . _vcr_request ) : log . info ( "Playing response for {} from cassette" . format ( self . _vcr_request ) ) response = self . cassette . play_response ( self . _vcr_request ) return VCRHTTPResponse ( response ) else : if self . cassette . write_protected and self . cassette . filter_request ( self . _vcr_request ) : raise CannotOverwriteExistingCassetteException ( "No match for the request (%r) was found. " "Can't overwrite existing cassette (%r) in " "your current record mode (%r)." % ( self . _vcr_request , self . cassette . _path , self . cassette . record_mode ) ) # Otherwise, we should send the request, then get the response # and return it. log . info ( "{} not in cassette, sending to real server" . format ( self . _vcr_request ) ) # This is imported here to avoid circular import. # TODO(@IvanMalison): Refactor to allow normal import. from vcr . patch import force_reset with force_reset ( ) : self . real_connection . request ( method = self . _vcr_request . method , url = self . _url ( self . _vcr_request . uri ) , body = self . _vcr_request . body , headers = self . _vcr_request . headers , ) # get the response response = self . real_connection . getresponse ( ) # put the response into the cassette response = { 'status' : { 'code' : response . status , 'message' : response . reason } , 'headers' : serialize_headers ( response ) , 'body' : { 'string' : response . read ( ) } , } self . cassette . append ( self . _vcr_request , response ) return VCRHTTPResponse ( response )
Retrieve the response
465
4
222,919
def connect ( self , * args , * * kwargs ) : if hasattr ( self , '_vcr_request' ) and self . cassette . can_play_response_for ( self . _vcr_request ) : # We already have a response we are going to play, don't # actually connect return if self . cassette . write_protected : # Cassette is write-protected, don't actually connect return from vcr . patch import force_reset with force_reset ( ) : return self . real_connection . connect ( * args , * * kwargs ) self . _sock = VCRFakeSocket ( )
httplib2 uses this . Connects to the server I m assuming .
137
16
222,920
def _recursively_apply_get_cassette_subclass ( self , replacement_dict_or_obj ) : if isinstance ( replacement_dict_or_obj , dict ) : for key , replacement_obj in replacement_dict_or_obj . items ( ) : replacement_obj = self . _recursively_apply_get_cassette_subclass ( replacement_obj ) replacement_dict_or_obj [ key ] = replacement_obj return replacement_dict_or_obj if hasattr ( replacement_dict_or_obj , 'cassette' ) : replacement_dict_or_obj = self . _get_cassette_subclass ( replacement_dict_or_obj ) return replacement_dict_or_obj
One of the subtleties of this class is that it does not directly replace HTTPSConnection with VCRRequestsHTTPSConnection but a subclass of the aforementioned class that has the cassette class attribute assigned to self . _cassette . This behavior is necessary to properly support nested cassette contexts .
165
59
222,921
def _Widget_fontdict ( ) : flist = Widget_fontobjects [ 2 : - 2 ] . splitlines ( ) fdict = { } for f in flist : k , v = f . split ( " " ) fdict [ k [ 1 : ] ] = v return fdict
Turns the above font definitions into a dictionary . Assumes certain line breaks and spaces .
64
18
222,922
def getTextlength ( text , fontname = "helv" , fontsize = 11 , encoding = 0 ) : fontname = fontname . lower ( ) basename = Base14_fontdict . get ( fontname , None ) glyphs = None if basename == "Symbol" : glyphs = symbol_glyphs if basename == "ZapfDingbats" : glyphs = zapf_glyphs if glyphs is not None : w = sum ( [ glyphs [ ord ( c ) ] [ 1 ] if ord ( c ) < 256 else glyphs [ 183 ] [ 1 ] for c in text ] ) return w * fontsize if fontname in Base14_fontdict . keys ( ) : return TOOLS . measure_string ( text , Base14_fontdict [ fontname ] , fontsize , encoding ) if fontname in [ "china-t" , "china-s" , "china-ts" , "china-ss" , "japan" , "japan-s" , "korea" , "korea-s" ] : return len ( text ) * fontsize raise ValueError ( "Font '%s' is unsupported" % fontname )
Calculate length of a string for a given built - in font .
267
15
222,923
def getPDFstr ( s ) : if not bool ( s ) : return "()" def make_utf16be ( s ) : r = hexlify ( bytearray ( [ 254 , 255 ] ) + bytearray ( s , "UTF-16BE" ) ) t = r if fitz_py2 else r . decode ( ) return "<" + t + ">" # brackets indicate hex # following either returns original string with mixed-in # octal numbers \nnn if outside ASCII range, or: # exits with utf-16be BOM version of the string r = "" for c in s : oc = ord ( c ) if oc > 255 : # shortcut if beyond code range return make_utf16be ( s ) if oc > 31 and oc < 127 : if c in ( "(" , ")" , "\\" ) : r += "\\" r += c continue if oc > 127 : r += "\\" + oct ( oc ) [ - 3 : ] continue if oc < 8 or oc > 13 or oc == 11 or c == 127 : r += "\\267" # indicate unsupported char continue if oc == 8 : r += "\\b" elif oc == 9 : r += "\\t" elif oc == 10 : r += "\\n" elif oc == 12 : r += "\\f" elif oc == 13 : r += "\\r" return "(" + r + ")"
Return a PDF string depending on its coding .
324
9
222,924
def CheckFont ( page , fontname ) : for f in page . getFontList ( ) : if f [ 4 ] == fontname : return f if f [ 3 ] . lower ( ) == fontname . lower ( ) : return f return None
Return an entry in the page s font list if reference name matches .
53
14
222,925
def invert ( self , src = None ) : if src is None : dst = TOOLS . _invert_matrix ( self ) else : dst = TOOLS . _invert_matrix ( src ) if dst [ 0 ] == 1 : return 1 self . a , self . b , self . c , self . d , self . e , self . f = dst [ 1 ] return 0
Calculate the inverted matrix . Return 0 if successful and replace current one . Else return 1 and do nothing .
88
23
222,926
def preTranslate ( self , tx , ty ) : self . e += tx * self . a + ty * self . c self . f += tx * self . b + ty * self . d return self
Calculate pre translation and replace current matrix .
44
10
222,927
def preScale ( self , sx , sy ) : self . a *= sx self . b *= sx self . c *= sy self . d *= sy return self
Calculate pre scaling and replace current matrix .
40
10
222,928
def preShear ( self , h , v ) : a , b = self . a , self . b self . a += v * self . c self . b += v * self . d self . c += h * a self . d += h * b return self
Calculate pre shearing and replace current matrix .
57
11
222,929
def preRotate ( self , theta ) : while theta < 0 : theta += 360 while theta >= 360 : theta -= 360 epsilon = 1e-5 if abs ( 0 - theta ) < epsilon : pass elif abs ( 90.0 - theta ) < epsilon : a = self . a b = self . b self . a = self . c self . b = self . d self . c = - a self . d = - b elif abs ( 180.0 - theta ) < epsilon : self . a = - self . a self . b = - self . b self . c = - self . c self . d = - self . d elif abs ( 270.0 - theta ) < epsilon : a = self . a b = self . b self . a = - self . c self . b = - self . d self . c = a self . d = b else : rad = math . radians ( theta ) s = round ( math . sin ( rad ) , 12 ) c = round ( math . cos ( rad ) , 12 ) a = self . a b = self . b self . a = c * a + s * self . c self . b = c * b + s * self . d self . c = - s * a + c * self . c self . d = - s * b + c * self . d return self
Calculate pre rotation and replace current matrix .
309
10
222,930
def concat ( self , one , two ) : if not len ( one ) == len ( two ) == 6 : raise ValueError ( "bad sequ. length" ) self . a , self . b , self . c , self . d , self . e , self . f = TOOLS . _concat_matrix ( one , two ) return self
Multiply two matrices and replace current one .
77
11
222,931
def transform ( self , m ) : if len ( m ) != 6 : raise ValueError ( "bad sequ. length" ) self . x , self . y = TOOLS . _transform_point ( self , m ) return self
Replace point by its transformation with matrix - like m .
50
12
222,932
def unit ( self ) : s = self . x * self . x + self . y * self . y if s < 1e-5 : return Point ( 0 , 0 ) s = math . sqrt ( s ) return Point ( self . x / s , self . y / s )
Return unit vector of a point .
62
7
222,933
def abs_unit ( self ) : s = self . x * self . x + self . y * self . y if s < 1e-5 : return Point ( 0 , 0 ) s = math . sqrt ( s ) return Point ( abs ( self . x ) / s , abs ( self . y ) / s )
Return unit vector of a point with positive coordinates .
70
10
222,934
def distance_to ( self , * args ) : if not len ( args ) > 0 : raise ValueError ( "at least one parameter must be given" ) x = args [ 0 ] if len ( args ) > 1 : unit = args [ 1 ] else : unit = "px" u = { "px" : ( 1. , 1. ) , "in" : ( 1. , 72. ) , "cm" : ( 2.54 , 72. ) , "mm" : ( 25.4 , 72. ) } f = u [ unit ] [ 0 ] / u [ unit ] [ 1 ] if type ( x ) is Point : return abs ( self - x ) * f # from here on, x is a rectangle # as a safeguard, make a finite copy of it r = Rect ( x . top_left , x . top_left ) r = r | x . bottom_right if self in r : return 0.0 if self . x > r . x1 : if self . y >= r . y1 : return self . distance_to ( r . bottom_right , unit ) elif self . y <= r . y0 : return self . distance_to ( r . top_right , unit ) else : return ( self . x - r . x1 ) * f elif r . x0 <= self . x <= r . x1 : if self . y >= r . y1 : return ( self . y - r . y1 ) * f else : return ( r . y0 - self . y ) * f else : if self . y >= r . y1 : return self . distance_to ( r . bottom_left , unit ) elif self . y <= r . y0 : return self . distance_to ( r . top_left , unit ) else : return ( r . x0 - self . x ) * f
Return the distance to a rectangle or another point .
400
10
222,935
def normalize ( self ) : if self . x1 < self . x0 : self . x0 , self . x1 = self . x1 , self . x0 if self . y1 < self . y0 : self . y0 , self . y1 = self . y1 , self . y0 return self
Replace rectangle with its finite version .
69
8
222,936
def isEmpty ( self ) : return self . x0 == self . x1 or self . y0 == self . y1
Check if rectangle area is empty .
27
7
222,937
def isInfinite ( self ) : return self . x0 > self . x1 or self . y0 > self . y1
Check if rectangle is infinite .
28
6
222,938
def includePoint ( self , p ) : if not len ( p ) == 2 : raise ValueError ( "bad sequ. length" ) self . x0 , self . y0 , self . x1 , self . y1 = TOOLS . _include_point_in_rect ( self , p ) return self
Extend rectangle to include point p .
68
8
222,939
def includeRect ( self , r ) : if not len ( r ) == 4 : raise ValueError ( "bad sequ. length" ) self . x0 , self . y0 , self . x1 , self . y1 = TOOLS . _union_rect ( self , r ) return self
Extend rectangle to include rectangle r .
64
8
222,940
def intersect ( self , r ) : if not len ( r ) == 4 : raise ValueError ( "bad sequ. length" ) self . x0 , self . y0 , self . x1 , self . y1 = TOOLS . _intersect_rect ( self , r ) return self
Restrict self to common area with rectangle r .
64
10
222,941
def transform ( self , m ) : if not len ( m ) == 6 : raise ValueError ( "bad sequ. length" ) self . x0 , self . y0 , self . x1 , self . y1 = TOOLS . _transform_rect ( self , m ) return self
Replace rectangle with its transformation by matrix m .
63
10
222,942
def intersects ( self , x ) : r1 = Rect ( x ) if self . isEmpty or self . isInfinite or r1 . isEmpty : return False r = Rect ( self ) if r . intersect ( r1 ) . isEmpty : return False return True
Check if intersection with rectangle x is not empty .
58
10
222,943
def isRectangular ( self ) : # if any two of the 4 corners are equal return false upper = ( self . ur - self . ul ) . unit if not bool ( upper ) : return False right = ( self . lr - self . ur ) . unit if not bool ( right ) : return False left = ( self . ll - self . ul ) . unit if not bool ( left ) : return False lower = ( self . lr - self . ll ) . unit if not bool ( lower ) : return False eps = 1e-5 # we now have 4 sides of length 1. If 3 of them have 90 deg angles, # then it is a rectangle -- we check via scalar product == 0 return abs ( sum ( map ( lambda x , y : x * y , upper , right ) ) ) <= eps and abs ( sum ( map ( lambda x , y : x * y , upper , left ) ) ) <= eps and abs ( sum ( map ( lambda x , y : x * y , left , lower ) ) ) <= eps
Check if quad is rectangular .
226
6
222,944
def transform ( self , m ) : if len ( m ) != 6 : raise ValueError ( "bad sequ. length" ) self . ul *= m self . ur *= m self . ll *= m self . lr *= m return self
Replace quad by its transformation with matrix m .
54
10
222,945
def _validate ( self ) : checker = ( self . _check0 , self . _check1 , self . _check2 , self . _check3 , self . _check4 , self . _check5 ) if not 0 <= self . field_type <= 5 : raise NotImplementedError ( "unsupported widget type" ) if type ( self . rect ) is not Rect : raise ValueError ( "invalid rect" ) if self . rect . isInfinite or self . rect . isEmpty : raise ValueError ( "rect must be finite and not empty" ) if not self . field_name : raise ValueError ( "field name missing" ) if self . border_color : if not len ( self . border_color ) in range ( 1 , 5 ) or type ( self . border_color ) not in ( list , tuple ) : raise ValueError ( "border_color must be 1 - 4 floats" ) if self . fill_color : if not len ( self . fill_color ) in range ( 1 , 5 ) or type ( self . fill_color ) not in ( list , tuple ) : raise ValueError ( "fill_color must be 1 - 4 floats" ) if not self . text_color : self . text_color = ( 0 , 0 , 0 ) if not len ( self . text_color ) in range ( 1 , 5 ) or type ( self . text_color ) not in ( list , tuple ) : raise ValueError ( "text_color must be 1 - 4 floats" ) if not self . border_width : self . border_width = 0 if not self . text_fontsize : self . text_fontsize = 0 checker [ self . field_type ] ( )
Validate the class entries .
371
6
222,946
def _adjust_font ( self ) : fnames = [ k for k in Widget_fontdict . keys ( ) ] fl = list ( map ( str . lower , fnames ) ) if ( not self . text_font ) or self . text_font . lower ( ) not in fl : self . text_font = "helv" i = fl . index ( self . text_font . lower ( ) ) self . text_font = fnames [ i ] return
Ensure the font name is from our list and correctly spelled .
102
13
222,947
def embeddedFileCount ( self ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_embeddedFileCount ( self )
Return number of embedded files .
49
6
222,948
def embeddedFileDel ( self , name ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_embeddedFileDel ( self , name )
Delete embedded file by name .
53
6
222,949
def embeddedFileInfo ( self , id ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_embeddedFileInfo ( self , id )
Retrieve embedded file information given its entry number or name .
53
12
222,950
def embeddedFileUpd ( self , id , buffer = None , filename = None , ufilename = None , desc = None ) : return _fitz . Document_embeddedFileUpd ( self , id , buffer , filename , ufilename , desc )
Change an embedded file given its entry number or name .
54
11
222,951
def embeddedFileGet ( self , id ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_embeddedFileGet ( self , id )
Retrieve embedded file content by name or by number .
53
11
222,952
def embeddedFileAdd ( self , buffer , name , filename = None , ufilename = None , desc = None ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_embeddedFileAdd ( self , buffer , name , filename , ufilename , desc )
Embed a new file .
77
6
222,953
def convertToPDF ( self , from_page = 0 , to_page = - 1 , rotate = 0 ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_convertToPDF ( self , from_page , to_page , rotate )
Convert document to PDF selecting page range and optional rotation . Output bytes object .
76
16
222,954
def layout ( self , rect = None , width = 0 , height = 0 , fontsize = 11 ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) val = _fitz . Document_layout ( self , rect , width , height , fontsize ) self . _reset_page_refs ( ) self . initData ( ) return val
Re - layout a reflowable document .
90
9
222,955
def makeBookmark ( self , pno = 0 ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_makeBookmark ( self , pno )
Make page bookmark in a reflowable document .
56
10
222,956
def findBookmark ( self , bookmark ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_findBookmark ( self , bookmark )
Find page number after layouting a document .
52
9
222,957
def _deleteObject ( self , xref ) : if self . isClosed : raise ValueError ( "operation illegal for closed doc" ) return _fitz . Document__deleteObject ( self , xref )
Delete an object given its xref .
45
8
222,958
def authenticate ( self , password ) : if self . isClosed : raise ValueError ( "operation illegal for closed doc" ) val = _fitz . Document_authenticate ( self , password ) if val : # the doc is decrypted successfully and we init the outline self . isEncrypted = 0 self . initData ( ) self . thisown = True return val
Decrypt document with a password .
79
7
222,959
def write ( self , garbage = 0 , clean = 0 , deflate = 0 , ascii = 0 , expand = 0 , linear = 0 , pretty = 0 , decrypt = 1 ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) if self . pageCount < 1 : raise ValueError ( "cannot write with zero pages" ) return _fitz . Document_write ( self , garbage , clean , deflate , ascii , expand , linear , pretty , decrypt )
Write document to a bytes object .
119
7
222,960
def select ( self , pyliste ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) val = _fitz . Document_select ( self , pyliste ) self . _reset_page_refs ( ) self . initData ( ) return val
Build sub - pdf with page numbers in list .
72
10
222,961
def _getCharWidths ( self , xref , bfname , ext , ordering , limit , idx = 0 ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document__getCharWidths ( self , xref , bfname , ext , ordering , limit , idx )
Return list of glyphs and glyph widths of a font .
85
13
222,962
def _getPageInfo ( self , pno , what ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) val = _fitz . Document__getPageInfo ( self , pno , what ) x = [ ] for v in val : if v not in x : x . append ( v ) val = x return val
Show fonts or images used on a page .
86
9
222,963
def extractImage ( self , xref = 0 ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document_extractImage ( self , xref )
Extract image which xref is pointing to .
55
10
222,964
def getPageFontList ( self , pno ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) if self . isPDF : return self . _getPageInfo ( pno , 1 ) return [ ]
Retrieve a list of fonts used on a page .
61
11
222,965
def getPageImageList ( self , pno ) : if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) if self . isPDF : return self . _getPageInfo ( pno , 2 ) return [ ]
Retrieve a list of images used on a page .
61
11
222,966
def copyPage ( self , pno , to = - 1 ) : pl = list ( range ( len ( self ) ) ) if pno < 0 or pno > pl [ - 1 ] : raise ValueError ( "'from' page number out of range" ) if to < - 1 or to > pl [ - 1 ] : raise ValueError ( "'to' page number out of range" ) if to == - 1 : pl . append ( pno ) else : pl . insert ( to , pno ) return self . select ( pl )
Copy a page to before some other page of the document . Specify to = - 1 to copy after last page .
115
24
222,967
def movePage ( self , pno , to = - 1 ) : pl = list ( range ( len ( self ) ) ) if pno < 0 or pno > pl [ - 1 ] : raise ValueError ( "'from' page number out of range" ) if to < - 1 or to > pl [ - 1 ] : raise ValueError ( "'to' page number out of range" ) pl . remove ( pno ) if to == - 1 : pl . append ( pno ) else : pl . insert ( to - 1 , pno ) return self . select ( pl )
Move a page to before some other page of the document . Specify to = - 1 to move after last page .
124
24
222,968
def deletePage ( self , pno = - 1 ) : pl = list ( range ( len ( self ) ) ) if pno < - 1 or pno > pl [ - 1 ] : raise ValueError ( "page number out of range" ) if pno >= 0 : pl . remove ( pno ) else : pl . remove ( pl [ - 1 ] ) return self . select ( pl )
Delete a page from the document . First page is 0 last page is - 1 .
85
17
222,969
def deletePageRange ( self , from_page = - 1 , to_page = - 1 ) : pl = list ( range ( len ( self ) ) ) f = from_page t = to_page if f == - 1 : f = pl [ - 1 ] if t == - 1 : t = pl [ - 1 ] if not 0 <= f <= t <= pl [ - 1 ] : raise ValueError ( "page number(s) out of range" ) for i in range ( f , t + 1 ) : pl . remove ( i ) return self . select ( pl )
Delete pages from the document . First page is 0 last page is - 1 .
124
16
222,970
def _forget_page ( self , page ) : pid = id ( page ) if pid in self . _page_refs : self . _page_refs [ pid ] = None
Remove a page from document page dict .
41
8
222,971
def _reset_page_refs ( self ) : if self . isClosed : return for page in self . _page_refs . values ( ) : if page : page . _erase ( ) page = None self . _page_refs . clear ( )
Invalidate all pages in document dictionary .
59
8
222,972
def addLineAnnot ( self , p1 , p2 ) : CheckParent ( self ) val = _fitz . Page_addLineAnnot ( self , p1 , p2 ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add Line annot for points p1 and p2 .
80
11
222,973
def addTextAnnot ( self , point , text ) : CheckParent ( self ) val = _fitz . Page_addTextAnnot ( self , point , text ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a sticky note at position point .
76
8
222,974
def addInkAnnot ( self , list ) : CheckParent ( self ) val = _fitz . Page_addInkAnnot ( self , list ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a handwriting as a list of list of point - likes . Each sublist forms an independent stroke .
74
21
222,975
def addStampAnnot ( self , rect , stamp = 0 ) : CheckParent ( self ) val = _fitz . Page_addStampAnnot ( self , rect , stamp ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a rubber stamp in a rectangle .
80
8
222,976
def addFileAnnot ( self , point , buffer , filename , ufilename = None , desc = None ) : CheckParent ( self ) val = _fitz . Page_addFileAnnot ( self , point , buffer , filename , ufilename , desc ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a FileAttachment annotation at location point .
94
10
222,977
def addStrikeoutAnnot ( self , rect ) : CheckParent ( self ) val = _fitz . Page_addStrikeoutAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Strike out content in a rectangle or quadrilateral .
74
11
222,978
def addUnderlineAnnot ( self , rect ) : CheckParent ( self ) val = _fitz . Page_addUnderlineAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Underline content in a rectangle or quadrilateral .
74
11
222,979
def addSquigglyAnnot ( self , rect ) : CheckParent ( self ) val = _fitz . Page_addSquigglyAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Wavy underline content in a rectangle or quadrilateral .
76
13
222,980
def addHighlightAnnot ( self , rect ) : CheckParent ( self ) val = _fitz . Page_addHighlightAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Highlight content in a rectangle or quadrilateral .
74
11
222,981
def addRectAnnot ( self , rect ) : CheckParent ( self ) val = _fitz . Page_addRectAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a Rectangle annotation .
72
6
222,982
def addCircleAnnot ( self , rect ) : CheckParent ( self ) val = _fitz . Page_addCircleAnnot ( self , rect ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a Circle annotation .
74
5
222,983
def addPolylineAnnot ( self , points ) : CheckParent ( self ) val = _fitz . Page_addPolylineAnnot ( self , points ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a Polyline annotation for a sequence of points .
74
11
222,984
def addPolygonAnnot ( self , points ) : CheckParent ( self ) val = _fitz . Page_addPolygonAnnot ( self , points ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a Polygon annotation for a sequence of points .
74
11
222,985
def addFreetextAnnot ( self , rect , text , fontsize = 12 , fontname = None , color = None , rotate = 0 ) : CheckParent ( self ) val = _fitz . Page_addFreetextAnnot ( self , rect , text , fontsize , fontname , color , rotate ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
Add a FreeText annotation in rectangle rect .
108
9
222,986
def addWidget ( self , widget ) : CheckParent ( self ) doc = self . parent if not doc . isPDF : raise ValueError ( "not a PDF" ) widget . _validate ( ) # Check if PDF already has our fonts. # If none insert all of them in a new object and store the xref. # Else only add any missing fonts. # To determine the situation, /DR object is checked. xref = 0 ff = doc . FormFonts # /DR object: existing fonts if not widget . text_font : # ensure default widget . text_font = "Helv" if not widget . text_font in ff : # if no existent font ... if not doc . isFormPDF or not ff : # a fresh /AcroForm PDF! xref = doc . _getNewXref ( ) # insert all our fonts doc . _updateObject ( xref , Widget_fontobjects ) else : # add any missing fonts for k in Widget_fontdict . keys ( ) : if not k in ff : # add our font if missing doc . _addFormFont ( k , Widget_fontdict [ k ] ) widget . _adjust_font ( ) # ensure correct font spelling widget . _dr_xref = xref # non-zero causes /DR creation # now create the /DA string if len ( widget . text_color ) == 3 : fmt = "{:g} {:g} {:g} rg /{f:s} {s:g} Tf " + widget . _text_da elif len ( widget . text_color ) == 1 : fmt = "{:g} g /{f:s} {s:g} Tf " + widget . _text_da elif len ( widget . text_color ) == 4 : fmt = "{:g} {:g} {:g} {:g} k /{f:s} {s:g} Tf " + widget . _text_da widget . _text_da = fmt . format ( * widget . text_color , f = widget . text_font , s = widget . text_fontsize ) # create the widget at last annot = self . _addWidget ( widget ) if annot : annot . thisown = True annot . parent = weakref . proxy ( self ) # owning page object self . _annot_refs [ id ( annot ) ] = annot return annot
Add a form field .
514
5
222,987
def firstAnnot ( self ) : CheckParent ( self ) val = _fitz . Page_firstAnnot ( self ) if val : val . thisown = True val . parent = weakref . proxy ( self ) # owning page object self . _annot_refs [ id ( val ) ] = val return val
Points to first annotation on page
68
6
222,988
def deleteLink ( self , linkdict ) : CheckParent ( self ) val = _fitz . Page_deleteLink ( self , linkdict ) if linkdict [ "xref" ] == 0 : return linkid = linkdict [ "id" ] try : linkobj = self . _annot_refs [ linkid ] linkobj . _erase ( ) except : pass return val
Delete link if PDF
83
4
222,989
def deleteAnnot ( self , fannot ) : CheckParent ( self ) val = _fitz . Page_deleteAnnot ( self , fannot ) if val : val . thisown = True val . parent = weakref . proxy ( self ) # owning page object val . parent . _annot_refs [ id ( val ) ] = val fannot . _erase ( ) return val
Delete annot if PDF and return next one
84
8
222,990
def _forget_annot ( self , annot ) : aid = id ( annot ) if aid in self . _annot_refs : self . _annot_refs [ aid ] = None
Remove an annot from reference dictionary .
41
7
222,991
def rect ( self ) : CheckParent ( self ) val = _fitz . Annot_rect ( self ) val = Rect ( val ) return val
Rectangle containing the annot
32
5
222,992
def fileUpd ( self , buffer = None , filename = None , ufilename = None , desc = None ) : CheckParent ( self ) return _fitz . Annot_fileUpd ( self , buffer , filename , ufilename , desc )
Update annotation attached file .
53
5
222,993
def dest ( self ) : if hasattr ( self , "parent" ) and self . parent is None : raise ValueError ( "orphaned object: parent is None" ) if self . parent . parent . isClosed or self . parent . parent . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) doc = self . parent . parent if self . isExternal or self . uri . startswith ( "#" ) : uri = None else : uri = doc . resolveLink ( self . uri ) return linkDest ( self , uri )
Create link destination details .
126
5
222,994
def measure_string ( self , text , fontname , fontsize , encoding = 0 ) : return _fitz . Tools_measure_string ( self , text , fontname , fontsize , encoding )
Measure length of a string for a Base14 font .
44
11
222,995
def _le_annot_parms ( self , annot , p1 , p2 ) : w = annot . border [ "width" ] # line width sc = annot . colors [ "stroke" ] # stroke color if not sc : sc = ( 0 , 0 , 0 ) scol = " " . join ( map ( str , sc ) ) + " RG\n" fc = annot . colors [ "fill" ] # fill color if not fc : fc = ( 0 , 0 , 0 ) fcol = " " . join ( map ( str , fc ) ) + " rg\n" nr = annot . rect np1 = p1 # point coord relative to annot rect np2 = p2 # point coord relative to annot rect m = self . _hor_matrix ( np1 , np2 ) # matrix makes the line horizontal im = ~ m # inverted matrix L = np1 * m # converted start (left) point R = np2 * m # converted end (right) point if 0 <= annot . opacity < 1 : opacity = "/Alp0 gs\n" else : opacity = "" return m , im , L , R , w , scol , fcol , opacity
Get common parameters for making line end symbols .
259
9
222,996
def pbis ( a ) : return ( math . cos ( 3 * a - math . pi ) , ( math . sin ( 3 * a - math . pi ) ) )
End point of a reflected sun ray given an angle a .
37
12
222,997
def print_descr ( rect , annot ) : annot . parent . insertText ( rect . br + ( 10 , 0 ) , "'%s' annotation" % annot . type [ 1 ] , color = red )
Print a short description to the right of an annot rect .
46
12
222,998
def recoverpix ( doc , item ) : x = item [ 0 ] # xref of PDF image s = item [ 1 ] # xref of its /SMask try : pix1 = fitz . Pixmap ( doc , x ) # make pixmap from image except : print ( "xref %i " % x + doc . _getGCTXerrmsg ( ) ) return None # skip if error if s == 0 : # has no /SMask return pix1 # no special handling try : pix2 = fitz . Pixmap ( doc , s ) # create pixmap of /SMask entry except : print ( "cannot create mask %i for image xref %i" % ( s , x ) ) return pix1 # return w/ failed transparency # check that we are safe if not ( pix1 . irect == pix2 . irect and pix1 . alpha == pix2 . alpha == 0 and pix2 . n == 1 ) : print ( "unexpected /SMask situation: pix1" , pix1 , "pix2" , pix2 ) return pix1 pix = fitz . Pixmap ( pix1 ) # copy of pix1, alpha channel added pix . setAlpha ( pix2 . samples ) # treat pix2.samples as alpha values pix1 = pix2 = None # free temp pixmaps return pix
Return pixmap for item which is a list of 2 xref numbers . Second xref is that of an smask if > 0 . Return None for any error .
313
35
222,999
def on_update_page_links ( self , evt ) : if not self . update_links : # skip if unsupported links evt . Skip ( ) return pg = self . doc [ getint ( self . TextToPage . Value ) - 1 ] for i in range ( len ( self . page_links ) ) : l = self . page_links [ i ] if l . get ( "update" , False ) : # "update" must be True if l [ "xref" ] == 0 : # no xref => new link pg . insertLink ( l ) elif l [ "kind" ] < 1 or l [ "kind" ] > len ( self . linkTypeStrings ) : pg . deleteLink ( l ) # delete invalid link else : pg . updateLink ( l ) # else link update l [ "update" ] = False # reset update indicator self . page_links [ i ] = l # update list of page links self . btn_Update . Disable ( ) # disable update button self . t_Update . Label = "" # and its message self . btn_Save . Enable ( ) self . t_Save . Label = "There are changes. Press to save them to file." evt . Skip ( ) return
Perform PDF update of changed links .
268
8