idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
34,900
def print_stats ( self , reset = True ) : if not self . ncalls : return stats = self . stats code = self . fn . __code__ print ( '--- Function Profiling ---' ) print ( 'File "{}", line {}, function {}' . format ( code . co_filename , code . co_firstlineno , self . fn . __name__ ) ) stats . sort_stats ( * self . sort_ke...
Manually print profiling result .
34,901
def get_model_home ( ) : d = os . path . join ( get_data_home ( ) , 'nnp_models' ) if not os . path . isdir ( d ) : os . makedirs ( d ) return d
Returns a root folder path for downloading models .
34,902
def get_model_url_base ( ) : url_base = get_model_url_base_from_env ( ) if url_base is not None : logger . info ( 'NNBLA_MODELS_URL_BASE is set as {}.' . format ( url_base ) ) else : url_base = 'https://nnabla.org/pretrained-models/nnp_models/' return url_base
Returns a root folder for models .
34,903
def load_image_imread ( file , shape = None , max_range = 1.0 ) : img255 = imread ( file ) if len ( img255 . shape ) == 2 : height , width = img255 . shape if shape is None : out_height , out_width , out_n_color = height , width , 1 else : out_n_color , out_height , out_width = shape assert ( out_n_color == 1 ) if out_...
Load image from file like object .
34,904
def load_csv ( file , shape = None , normalize = False ) : value_list = [ ] if six . PY2 : for row in csv . reader ( file ) : value_list . append ( list ( map ( float , row ) ) ) elif six . PY34 : for row in csv . reader ( [ l . decode ( 'utf-8' ) for l in file . readlines ( ) ] ) : value_list . append ( list ( map ( f...
Load CSV file .
34,905
def save ( self , vleaf , fpath , cleanup = False , format = None ) : graph = self . create_graphviz_digraph ( vleaf , format = format ) graph . render ( fpath , cleanup = cleanup )
Save the graph to a given file path .
34,906
def view ( self , vleaf , fpath = None , cleanup = True , format = None ) : graph = self . create_graphviz_digraph ( vleaf , format = format ) graph . view ( fpath , cleanup = cleanup )
View the graph .
34,907
def get_modules ( self , memo = None , prefix = "" ) : if memo is None : memo = set ( ) if self not in memo : memo . add ( self ) yield prefix , self for k , v in self . __dict__ . items ( ) : if not isinstance ( v , Module ) : continue name , module = k , v submodule_prefix = "{}/{}" . format ( prefix , name ) if pref...
Get modules .
34,908
def get_prep_value ( self , value ) : if value is None or value == "" : return None if isinstance ( value , six . string_types ) : value = _hex_string_to_unsigned_integer ( value ) if _using_signed_storage ( ) : value = _unsigned_to_signed_integer ( value ) return value
Return the integer value to be stored from the hex string
34,909
def from_db_value ( self , value , expression , connection , context ) : if value is None : return value if _using_signed_storage ( ) : value = _signed_to_unsigned_integer ( value ) return value
Return an unsigned int representation from all db backends
34,910
def to_python ( self , value ) : if isinstance ( value , six . string_types ) : return value if value is None : return value return _unsigned_integer_to_hex_string ( value )
Return a str representation of the hexadecimal
34,911
def apns_send_bulk_message ( registration_ids , alert , application_id = None , certfile = None , ** kwargs ) : results = _apns_send ( registration_ids , alert , batch = True , application_id = application_id , certfile = certfile , ** kwargs ) inactive_tokens = [ token for token , result in results . items ( ) if resu...
Sends an APNS notification to one or more registration_ids . The registration_ids argument needs to be a list .
34,912
def _cm_send_request ( registration_ids , data , cloud_type = "GCM" , application_id = None , use_fcm_notifications = True , ** kwargs ) : payload = { "registration_ids" : registration_ids } if registration_ids else { } data = data . copy ( ) if cloud_type == "FCM" and use_fcm_notifications : notification_payload = { }...
Sends a FCM or GCM notification to one or more registration_ids as json data . The registration_ids needs to be a list .
34,913
def _cm_handle_canonical_id ( canonical_id , current_id , cloud_type ) : devices = GCMDevice . objects . filter ( cloud_message_type = cloud_type ) if devices . filter ( registration_id = canonical_id , active = True ) . exists ( ) : devices . filter ( registration_id = current_id ) . update ( active = False ) else : d...
Handle situation when FCM server response contains canonical ID
34,914
def _validate_applications ( self , apps ) : for application_id , application_config in apps . items ( ) : self . _validate_config ( application_id , application_config ) application_config [ "APPLICATION_ID" ] = application_id
Validate the application collection
34,915
def _validate_apns_certificate ( self , certfile ) : try : with open ( certfile , "r" ) as f : content = f . read ( ) check_apns_certificate ( content ) except Exception as e : raise ImproperlyConfigured ( "The APNS certificate file at %r is not readable: %s" % ( certfile , e ) )
Validate the APNS certificate at startup .
34,916
def _validate_allowed_settings ( self , application_id , application_config , allowed_settings ) : for setting_key in application_config . keys ( ) : if setting_key not in allowed_settings : raise ImproperlyConfigured ( "Platform {}, app {} does not support the setting: {}." . format ( application_config [ "PLATFORM" ]...
Confirm only allowed settings are present .
34,917
def _validate_required_settings ( self , application_id , application_config , required_settings ) : for setting_key in required_settings : if setting_key not in application_config . keys ( ) : raise ImproperlyConfigured ( MISSING_SETTING . format ( application_id = application_id , setting = setting_key ) )
All required keys must be present
34,918
def _get_application_settings ( self , application_id , platform , settings_key ) : if not application_id : conf_cls = "push_notifications.conf.AppConfig" raise ImproperlyConfigured ( "{} requires the application_id be specified at all times." . format ( conf_cls ) ) app_config = self . _settings . get ( "APPLICATIONS"...
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured .
34,919
def _wns_authenticate ( scope = "notify.windows.com" , application_id = None ) : client_id = get_manager ( ) . get_wns_package_security_id ( application_id ) client_secret = get_manager ( ) . get_wns_secret_key ( application_id ) if not client_id : raise ImproperlyConfigured ( 'You need to set PUSH_NOTIFICATIONS_SETTIN...
Requests an Access token for WNS communication .
34,920
def _wns_send ( uri , data , wns_type = "wns/toast" , application_id = None ) : access_token = _wns_authenticate ( application_id = application_id ) content_type = "text/xml" if wns_type == "wns/raw" : content_type = "application/octet-stream" headers = { "Content-Type" : content_type , "Authorization" : "Bearer %s" % ...
Sends a notification data and authentication to WNS .
34,921
def _wns_prepare_toast ( data , ** kwargs ) : root = ET . Element ( "toast" ) visual = ET . SubElement ( root , "visual" ) binding = ET . SubElement ( visual , "binding" ) binding . attrib [ "template" ] = kwargs . pop ( "template" , "ToastText01" ) if "text" in data : for count , item in enumerate ( data [ "text" ] , ...
Creates the xml tree for a toast notification
34,922
def wns_send_bulk_message ( uri_list , message = None , xml_data = None , raw_data = None , application_id = None , ** kwargs ) : res = [ ] if uri_list : for uri in uri_list : r = wns_send_message ( uri = uri , message = message , xml_data = xml_data , raw_data = raw_data , application_id = application_id , ** kwargs )...
WNS doesn t support bulk notification so we loop through each uri .
34,923
def _add_sub_elements_from_dict ( parent , sub_dict ) : for key , value in sub_dict . items ( ) : if isinstance ( value , list ) : for repeated_element in value : sub_element = ET . SubElement ( parent , key ) _add_element_attrs ( sub_element , repeated_element . get ( "attrs" , { } ) ) children = repeated_element . ge...
Add SubElements to the parent element .
34,924
def _add_element_attrs ( elem , attrs ) : for attr , value in attrs . items ( ) : elem . attrib [ attr ] = value return elem
Add attributes to the given element .
34,925
def login ( self , host_spec = "" , username = "" , password = "" ) : warnings . warn ( "shouldn't use this function anymore ! use connect which handles" "handles authentication directly." , DeprecationWarning ) scheme = "http" if not host_spec : u = urlparse ( self . endpoint ) host_spec = u . netloc if u . scheme == ...
Authenticate with infrastructure via the Skydive analyzer
34,926
def _sdkmanager ( self , * args , ** kwargs ) : kwargs [ 'cwd' ] = kwargs . get ( 'cwd' , self . android_sdk_dir ) command = self . sdkmanager_path + ' ' + ' ' . join ( args ) return_child = kwargs . pop ( 'return_child' , False ) if return_child : return self . buildozer . cmd_expect ( command , ** kwargs ) else : kwa...
Call the sdkmanager in our Android SDK with the given arguments .
34,927
def _android_get_installed_platform_tools_version ( self ) : platform_tools_dir = os . path . join ( self . android_sdk_dir , 'platform-tools' ) if not os . path . exists ( platform_tools_dir ) : return None data_file = os . path . join ( platform_tools_dir , 'source.properties' ) if not os . path . exists ( data_file ...
Crudely parse out the installed platform - tools version
34,928
def _android_update_sdk ( self , * sdkmanager_commands ) : auto_accept_license = self . buildozer . config . getbooldefault ( 'app' , 'android.accept_sdk_license' , False ) if auto_accept_license : yes_command = 'yes 2>/dev/null' command = '{} | {} --licenses' . format ( yes_command , self . sdkmanager_path ) self . bu...
Update the tools and package - tools if possible
34,929
def cmd_logcat ( self , * args ) : self . check_requirements ( ) serial = self . serials [ 0 : ] if not serial : return filters = self . buildozer . config . getrawdefault ( "app" , "android.logcat_filters" , "" , section_sep = ":" , split_char = " " ) filters = " " . join ( filters ) self . buildozer . environ [ 'ANDR...
Show the log from the device
34,930
def path_or_git_url ( self , repo , owner = 'kivy' , branch = 'master' , url_format = 'https://github.com/{owner}/{repo}.git' , platform = None , squash_hyphen = True ) : if squash_hyphen : key = repo . replace ( '-' , '_' ) else : key = repo if platform : key = "{}.{}" . format ( platform , key ) config = self . build...
Get source location for a git checkout
34,931
def install_or_update_repo ( self , repo , ** kwargs ) : cmd = self . buildozer . cmd install_dir = join ( self . buildozer . platform_dir , repo ) custom_dir , clone_url , clone_branch = self . path_or_git_url ( repo , ** kwargs ) if not self . buildozer . file_exists ( install_dir ) : if custom_dir : cmd ( 'mkdir -p ...
Install or update a git repository into the platform directory .
34,932
def set_config_token_from_env ( section , token , config ) : env_var_name = '' . join ( [ section . upper ( ) , '_' , token . upper ( ) . replace ( '.' , '_' ) ] ) env_var = os . environ . get ( env_var_name ) if env_var is None : return False config . set ( section , token , env_var ) return True
Given a config section and token checks for an appropriate environment variable . If the variable exists sets the config entry to its value .
34,933
def prepare_for_build ( self ) : assert ( self . target is not None ) if hasattr ( self . target , '_build_prepared' ) : return self . info ( 'Preparing build' ) self . info ( 'Check requirements for {0}' . format ( self . targetname ) ) self . target . check_requirements ( ) self . info ( 'Install platform' ) self . t...
Prepare the build .
34,934
def build ( self ) : assert ( self . target is not None ) assert ( hasattr ( self . target , '_build_prepared' ) ) if hasattr ( self . target , '_build_done' ) : return self . build_id = int ( self . state . get ( 'cache.build_id' , '0' ) ) + 1 self . state [ 'cache.build_id' ] = str ( self . build_id ) self . info ( '...
Do the build .
34,935
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
34,936
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' , '' ) :...
Ensure the spec file is correct .
34,937
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 : return onlyname = lambda x : x . split ( '==' ) [ 0 ] requirements = [ x for x in requirement...
Ensure the application requirements are all available and ready to be packaged as well .
34,938
def check_garden_requirements ( self ) : garden_requirements = self . config . getlist ( 'app' , 'garden_requirements' , '' ) if exists ( self . gardenlibs_dir ) and self . state . get ( 'cache.gardenlibs' , '' ) == garden_requirements : self . debug ( 'Garden requirements already installed, pass' ) return self . rmdir...
Ensure required garden packages are available to be included .
34,939
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
34,940
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 . gl...
Clean the whole Buildozer environment .
34,941
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 (...
Serve the bin directory via SimpleHTTPServer
34,942
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 ...
Open the xcode project .
34,943
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 .
34,944
def _handle_generator ( self , fn ) : with self as cassette : coroutine = fn ( cassette ) 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 .
34,945
def append ( self , request , response ) : request = self . _before_record_request ( request ) if not request : return 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
34,946
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 .
34,947
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 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
34,948
def responses_of ( self , request ) : responses = [ response for index , response in self . _responses ( request ) ] if responses : return responses 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 .
34,949
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
34,950
def _uri ( self , url ) : if url and not url . startswith ( '/' ) : return url uri = "{0}://{1}{2}{3}" . format ( self . _protocol , self . real_connection . host , self . _port_postfix ( ) , url , ) return uri
Returns request absolute URI
34,951
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
34,952
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 ) ) self . _sock = VCRFakeSocket ( )
Persist the request metadata in self . _vcr_request
34,953
def getresponse ( self , _ = False , ** kwargs ) : 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...
Retrieve the response
34,954
def connect ( self , * args , ** kwargs ) : if hasattr ( self , '_vcr_request' ) and self . cassette . can_play_response_for ( self . _vcr_request ) : return if self . cassette . write_protected : return from vcr . patch import force_reset with force_reset ( ) : return self . real_connection . connect ( * args , ** kwa...
httplib2 uses this . Connects to the server I m assuming .
34,955
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 ] = ...
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 .
34,956
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 .
34,957
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 ( [ gly...
Calculate length of a string for a given built - in font .
34,958
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 + ">" r = "" for c in s : oc = ord ( c ) if oc > 255 : return make_utf16be ( s ) if oc > 31 and oc < 127 : if c i...
Return a PDF string depending on its coding .
34,959
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 .
34,960
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 .
34,961
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 .
34,962
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 .
34,963
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 .
34,964
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 ) < epsilo...
Calculate pre rotation and replace current matrix .
34,965
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 .
34,966
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 .
34,967
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 .
34,968
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 .
34,969
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 [ ...
Return the distance to a rectangle or another point .
34,970
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 .
34,971
def isEmpty ( self ) : return self . x0 == self . x1 or self . y0 == self . y1
Check if rectangle area is empty .
34,972
def isInfinite ( self ) : return self . x0 > self . x1 or self . y0 > self . y1
Check if rectangle is infinite .
34,973
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 .
34,974
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 .
34,975
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 .
34,976
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 .
34,977
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 .
34,978
def isRectangular ( self ) : 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 ( lowe...
Check if quad is rectangular .
34,979
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 .
34,980
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...
Validate the class entries .
34,981
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 .
34,982
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 .
34,983
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 .
34,984
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 .
34,985
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 .
34,986
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 .
34,987
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 .
34,988
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 .
34,989
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 .
34,990
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 .
34,991
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 .
34,992
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 .
34,993
def authenticate ( self , password ) : if self . isClosed : raise ValueError ( "operation illegal for closed doc" ) val = _fitz . Document_authenticate ( self , password ) if val : self . isEncrypted = 0 self . initData ( ) self . thisown = True return val
Decrypt document with a password .
34,994
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" ) retur...
Write document to a bytes object .
34,995
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 .
34,996
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 .
34,997
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 .
34,998
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 .
34,999
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 .